Generic hooks the plugin builds on: the conversations.drawer, composer.send and app.modal slot places (openModal / modal.setResult / modal.close, ?modal= links), runs.start taking the composer's whole payload (auto routing, account, projects, cwd, meta.scheduled) and hub/runs/resolve, a turn's knobs on conversations.send, push buttons answered as the notify.action event, hub/changed (SSE plugin-data), hub/title (conversations.title), the runs.schedule provider behind /api/scheduled, the week's budget and the stopped-run card, providers in /api/plugins/ui, carryover.scheduled. backend/scheduled/ and frontend/src/business/scheduled/ are gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
202 lines
8.8 KiB
Python
202 lines
8.8 KiB
Python
"""A long conversation title's short stand-in for the header.
|
||
|
||
A subagent's parsed title is the first 90 characters of the prompt its parent
|
||
wrote ("You are auditor slice **B** of a Claude Code `prompt-audit`. First
|
||
read the brief at `/tmp…"), and a top-level conversation's can run as long —
|
||
its first prompt when Claude never named it, a ``⑂`` fork, a work
|
||
conversation's ``INS-2229 · <issue> · #13722`` resource title. None of that
|
||
reads in a phone header. So the detail route hands the task — the title, a
|
||
subagent's card description, the first prompt — to the plugin that provides
|
||
``conversation.title`` (the ``conversation-labels`` plugin: any model, no
|
||
transcript, its spend booked in the side-call ledger by the ``complete.run``
|
||
bridge — ``plugins/labels_bridge.py``) and keeps the 3–6 word answer in
|
||
SQLite (``short_titles``) next to the long title it stands for: when the auto
|
||
title changes, the next view asks again. No such plugin, no short titles —
|
||
nothing is asked or stored.
|
||
|
||
A title the owner typed is never shortened (:func:`source_title`).
|
||
|
||
The detail never waits on it: the first view answers with the long title,
|
||
the ask runs on a small pool, and a ``short-title`` event patches the open
|
||
page. A failed ask is stored too (``title`` NULL) and retried only after
|
||
``RETRY_S``, so a sidecar outage doesn't turn every view into a new ask.
|
||
A parent's page names its direct subagents the same way
|
||
(:func:`for_subagents`) — their cards are where they are seen. Lists only
|
||
read the cache (:func:`cached`) — a row never costs an ask.
|
||
"""
|
||
|
||
import concurrent.futures
|
||
import logging
|
||
import re
|
||
import threading
|
||
import time
|
||
|
||
from core.state import AppState
|
||
|
||
log = logging.getLogger(__name__)
|
||
|
||
# The phone header fits ~35 characters; an ai-title rarely runs past 45.
|
||
# Longer is a prompt, not a title.
|
||
MIN_LEN = 48
|
||
RETRY_S = 6 * 3600
|
||
# Who may have stamped `meta.title` without it being the owner's own words.
|
||
# No source at all can't be told apart from a rename made before the field
|
||
# existed (`conv-meta title` and a scheduled run's title send none either),
|
||
# so it counts as typed.
|
||
_AUTO_SOURCES = ("agent", "resources")
|
||
# A title that leads with an issue key or a PR number is told apart from its
|
||
# siblings by it, and Haiku's words drop it.
|
||
_LEADING_ID_RE = re.compile(r"\s*([A-Z][A-Z0-9]+-\d+|#\d+)(?![\w-])")
|
||
# The blocks the composer appends (lib/shortcuts.tsx: attachments, location
|
||
# tags, skill mentions, guidelines) aren't what the conversation is about.
|
||
_GUIDELINES_RE = re.compile(
|
||
r"\n\s*(Attached files \(|Work in the following|Use the following in this "
|
||
r"task:|Guidelines:).*", re.S)
|
||
|
||
|
||
def clean(text: str) -> str:
|
||
"""A prompt without the composer's appended blocks."""
|
||
return _GUIDELINES_RE.sub("", text or "").strip()
|
||
|
||
_POOL = concurrent.futures.ThreadPoolExecutor(max_workers=2,
|
||
thread_name_prefix="short-title")
|
||
_inflight: set[str] = set()
|
||
_lock = threading.Lock()
|
||
|
||
|
||
def source_title(data: dict, sidechain: bool) -> str | None:
|
||
"""The long title a short one would stand in for, or None: short
|
||
enough already, or the owner's rename. A subagent's meta is its
|
||
parent's (shared sessionId), so only a top-level conversation's
|
||
rename counts."""
|
||
title = data.get("title") or ""
|
||
if len(title) <= MIN_LEN:
|
||
return None
|
||
meta = {} if sidechain else (data.get("meta") or {})
|
||
if meta.get("title") and meta.get("titleSource") not in _AUTO_SOURCES:
|
||
return None
|
||
return title
|
||
|
||
|
||
def task_text(data: dict) -> str:
|
||
"""What the conversation is about: a subagent's card description, the
|
||
title when it isn't just the prompt's start, then the first prompt."""
|
||
first = next((it.get("text") for it in data.get("thread") or []
|
||
if it.get("role") == "user" and it.get("kind") == "text"
|
||
and it.get("text")), None)
|
||
desc = ((data.get("parentConversation") or {}).get("description") or "").strip()
|
||
title = (data.get("title") or "").strip()
|
||
body = clean(first or title)
|
||
# Whitespace folded on both sides: a summary's first prompt comes folded.
|
||
head = "" if " ".join(body.split()).startswith(" ".join(title.split())[:40]) else title
|
||
return "\n\n".join(p for p in (desc, head, body) if p)
|
||
|
||
|
||
def _same_source(stored: str | None, title: str) -> bool:
|
||
# NULL: asked before the source was kept — subagents only, whose title
|
||
# is their prompt and never changes.
|
||
return stored is None or stored == title
|
||
|
||
|
||
def _keep_id(long_title: str, short: str) -> str:
|
||
m = _LEADING_ID_RE.match(long_title)
|
||
if not m or m.group(1).lower() in short.lower():
|
||
return short
|
||
return f"{m.group(1)} · {short}"
|
||
|
||
|
||
def for_detail(deps: AppState, conv_id: str, data: dict, sidechain: bool) -> str | None:
|
||
"""The cached short title of a parsed thread, or None — and, when it was
|
||
never asked for this title (or the last ask failed long enough ago),
|
||
start asking in the background."""
|
||
long_title = source_title(data, sidechain)
|
||
if not long_title:
|
||
return None
|
||
hit = deps.store.get_short_title(conv_id)
|
||
if hit and _same_source(hit[2], long_title) and (
|
||
hit[0] or time.time() - hit[1] < RETRY_S):
|
||
return hit[0]
|
||
text = task_text(data)
|
||
if not text:
|
||
return None
|
||
from plugins import labels_bridge
|
||
if not labels_bridge.available(deps):
|
||
return None
|
||
with _lock:
|
||
if conv_id in _inflight:
|
||
return None
|
||
_inflight.add(conv_id)
|
||
_POOL.submit(_ask, deps, conv_id, text, long_title, _account(deps, data))
|
||
return None
|
||
|
||
|
||
def _account(deps: AppState, data: dict) -> str | None:
|
||
"""The Claude login a conversation's short title is asked on (its own
|
||
seat: a work conversation's title never leaves it)."""
|
||
try:
|
||
from conversations import look_pending
|
||
m = data.get("meta") or {}
|
||
return look_pending.claude_account(deps, None, m) if m else None
|
||
except Exception: # noqa: BLE001 — a hint only
|
||
return None
|
||
|
||
|
||
def first_prompt(msgs: list[dict]) -> str | None:
|
||
"""A conversation's first prompt off its search corpus (``searchMsgs``,
|
||
``Store.search_msgs``: clipped to ``SEARCH_CLIP``, whitespace folded —
|
||
plenty to name it by)."""
|
||
return next((m.get("text") for m in msgs or []
|
||
if m.get("role") == "user" and m.get("text")), None)
|
||
|
||
|
||
def for_subagents(deps: AppState, refs: list[dict], paths: dict[str, str]) -> None:
|
||
"""Set ``shortTitle`` on a parent page's subagent refs: the cached ones,
|
||
and for each child never named for its title, an ask started in the
|
||
background (its ``short-title`` event patches the open parent page). The
|
||
parent's page is where a subagent is seen — waiting for each child's own
|
||
page to be opened left nearly all of them on their prompt's first 90
|
||
characters, often the same for every sibling. ``paths`` maps a ref's id
|
||
to the child's transcript; the unnamed children's first prompts are read
|
||
from the store's search corpus in one go (the summaries don't carry it)."""
|
||
shorts = cached(deps, {r["id"]: r.get("title") for r in refs})
|
||
for r in refs:
|
||
r["shortTitle"] = shorts.get(r["id"])
|
||
todo = [r for r in refs if not r["shortTitle"] and r.get("title")]
|
||
corpus = deps.store.search_msgs(paths.get(r["id"]) for r in todo) if todo else {}
|
||
for r in todo:
|
||
r["shortTitle"] = for_detail(deps, r["id"], {
|
||
"title": r["title"],
|
||
"thread": [{"role": "user", "kind": "text",
|
||
"text": first_prompt(corpus.get(paths.get(r["id"])))
|
||
or r["title"]}],
|
||
"parentConversation": {"description": r.get("description")},
|
||
}, True)
|
||
|
||
|
||
def cached(deps: AppState, titles: dict[str, str | None]) -> dict[str, str]:
|
||
"""``{conv_id: short}`` for the conversations (``{conv_id: title}``)
|
||
already named for the title they have now. Never asks: what a list of
|
||
cards shows."""
|
||
want = {cid: t for cid, t in titles.items() if t and len(t) > MIN_LEN}
|
||
rows = deps.store.get_short_titles(list(want)) if want else {}
|
||
return {cid: short for cid, (short, src) in rows.items()
|
||
if short and _same_source(src, want[cid])}
|
||
|
||
|
||
def _ask(deps: AppState, conv_id: str, text: str, long_title: str,
|
||
account: str | None = None) -> None:
|
||
try:
|
||
from plugins import labels_bridge
|
||
ans = labels_bridge.title(deps, text, "short-title", conv_id, account)
|
||
short = _keep_id(long_title, ans["title"]) if ans else None
|
||
if short and len(short) >= len(long_title):
|
||
short = None
|
||
deps.store.set_short_title(conv_id, short, long_title)
|
||
if short:
|
||
deps.hub.publish({"type": "short-title", "id": conv_id, "title": short})
|
||
except Exception:
|
||
log.exception("short title for %s", conv_id)
|
||
finally:
|
||
with _lock:
|
||
_inflight.discard(conv_id)
|