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>
421 lines
20 KiB
Python
421 lines
20 KiB
Python
"""A long title's short header stand-in: asked once per title of the
|
|
``conversation.title`` provider (the conversation-labels plugin, any model
|
|
through ``complete.run`` — faked here), cached in SQLite, asked
|
|
again only when the auto title changes, never for the owner's rename, and its
|
|
spend booked in the side-call ledger that feeds the plan meter. A parent's
|
|
page names its subagents (asking for the ones never named) while the graph
|
|
list only reads the cache. A subagent is never lent its parent's renamed
|
|
title — not on its own page, nor as a nested agent's parent.
|
|
|
|
Imports ``main`` against throwaway paths (no startup event → no threads)."""
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import tempfile
|
|
import unittest
|
|
|
|
TMP = pathlib.Path(tempfile.mkdtemp())
|
|
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t",
|
|
"WORKSPACE": TMP, "REPO_DIR": TMP, "ARCHIVE_DIR": TMP / "arch",
|
|
"META_PATH": TMP / "meta.json", "WORKERS_PATH": TMP / "w.json",
|
|
"PROFILES_PATH": TMP / "profiles.json",
|
|
"WORKERS_TRANSCRIPTS_DIR": TMP / "mirror",
|
|
"CRON_PATH": TMP / "cron.json", "NOTIFY_PATH": TMP / "n.json",
|
|
"FORMS_PATH": TMP / "f.json", "UI_STATE_PATH": TMP / "ui.json",
|
|
"NOTIF_READ_PATH": TMP / "nr.json",
|
|
"MAIL_TRIGGER_SENDERS_PATH": TMP / "mt.json",
|
|
"USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
|
|
"NEW_PROJECTS_PATH": TMP / "np.json", "PROJECTS_DIR": TMP / "projects",
|
|
"SCHEDULED_PATH": TMP / "scheduled.json",
|
|
"INTERNAL_API_TOKEN": "tok", "SIDECAR_TOKEN": "",
|
|
"PI_TRANSCRIPTS_DIR": ""}.items():
|
|
os.environ[k] = str(v)
|
|
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
import main # noqa: E402
|
|
from conversations import ids, pricing, short_title # noqa: E402
|
|
from core.routes import _guest_filter # noqa: E402
|
|
from plugins import hubcomplete, labels_bridge # noqa: E402
|
|
from usage import calibrate # noqa: E402
|
|
from users.caller import Caller # noqa: E402
|
|
|
|
DEPS = main.app.state.ai
|
|
SID = "11111111-2222-4333-8444-666666666666"
|
|
ROOT = f"-home-x/{SID}.jsonl"
|
|
SUB = f"-home-x/{SID}/subagents/agent-a1.jsonl"
|
|
SID2 = "22222222-2222-4333-8444-777777777777"
|
|
TOP = f"-home-x/{SID2}.jsonl"
|
|
TOP_PROMPT = ("Migrate every homelab service's compose file to the new Traefik v3 "
|
|
"middleware syntax, then check that every dashboard still loads.")
|
|
PROMPT = ("You are auditor slice **B** of a Claude Code `prompt-audit`. First read "
|
|
"the brief at `/tmp/scratchpad/audit/brief.md` and follow it exactly. "
|
|
"Your slice: every nested service CLAUDE.md.")
|
|
USAGE = {"input_tokens": 400, "output_tokens": 20, "cache_read_input_tokens": 0,
|
|
"cache_creation_input_tokens": 0}
|
|
MODEL = "claude-haiku-5-5-20261001"
|
|
|
|
|
|
def write(rel: str, prompt: str, sidechain: bool, sid: str = SID) -> None:
|
|
p = TMP / "arch" / rel
|
|
p.parent.mkdir(parents=True, exist_ok=True)
|
|
extra = {"isSidechain": True, "agentId": "a1"} if sidechain else {}
|
|
p.write_text("\n".join(json.dumps(o) for o in [
|
|
{"type": "user", "uuid": "u1", "sessionId": sid, "timestamp": "2026-10-13T20:00:00Z",
|
|
"message": {"role": "user", "content": prompt}, **extra},
|
|
{"type": "assistant", "uuid": "a1", "sessionId": sid, "timestamp": "2026-10-13T20:00:01Z",
|
|
"message": {"role": "assistant", "model": "claude-opus-5-5",
|
|
"content": [{"type": "text", "text": "on it"}]}, **extra},
|
|
]) + "\n")
|
|
|
|
|
|
class FakeSidecar:
|
|
"""The ``conversation.title`` provider as ``labels_bridge.run`` sees it:
|
|
the plugin's answer, its spend booked the way the ``complete.run`` bridge
|
|
books a ``/complete`` reply."""
|
|
|
|
def __init__(self, reply: dict | None):
|
|
self.reply, self.calls = reply, []
|
|
|
|
def __call__(self, deps, key, payload=None, **kw):
|
|
self.calls.append((key, {**payload, "prompt": payload["text"]}))
|
|
if self.reply is None:
|
|
return None
|
|
hubcomplete.book(deps, {**self.reply, "harness": "claude"},
|
|
payload["kind"], payload.get("ref"))
|
|
return {"title": self.reply["title"], "summary": self.reply.get("summary")}
|
|
|
|
|
|
class Inline:
|
|
def submit(self, fn, *args):
|
|
fn(*args)
|
|
|
|
|
|
class Deferred:
|
|
def __init__(self):
|
|
self.jobs = []
|
|
|
|
def submit(self, fn, *args):
|
|
self.jobs.append((fn, args))
|
|
|
|
|
|
def side_calls(kind: str) -> list[tuple]:
|
|
return DEPS.usage_store._db.execute(
|
|
"SELECT ref, account, model, cost, units FROM side_calls WHERE kind=?",
|
|
(kind,)).fetchall()
|
|
|
|
|
|
class Base(unittest.TestCase):
|
|
reply = {"title": "Audit service CLAUDE.md files", "summary": "Reads them.",
|
|
"costUsd": 0.0003, "model": MODEL, "usage": USAGE, "account": "personal"}
|
|
|
|
def setUp(self):
|
|
for db, table in ((DEPS.usage_store._db, "side_calls"),
|
|
(DEPS.store._db, "short_titles")):
|
|
db.execute(f"DELETE FROM {table}")
|
|
db.commit()
|
|
self.sidecar = FakeSidecar(self.reply)
|
|
self._orig = (labels_bridge.run, labels_bridge.available, short_title._POOL,
|
|
short_title.RETRY_S)
|
|
labels_bridge.run = self.sidecar
|
|
labels_bridge.available = lambda deps, key=labels_bridge.TITLE: True
|
|
short_title._POOL = Inline()
|
|
|
|
def tearDown(self):
|
|
(labels_bridge.run, labels_bridge.available, short_title._POOL,
|
|
short_title.RETRY_S) = self._orig
|
|
|
|
|
|
class DetailRoute(Base):
|
|
def setUp(self):
|
|
super().setUp()
|
|
write(ROOT, "Audit the homelab prompts", False)
|
|
write(SUB, PROMPT, True)
|
|
(TMP / "arch" / SUB).with_name("agent-a1.meta.json").write_text(json.dumps(
|
|
{"agentType": "general-purpose", "description": "Audit nested service CLAUDE.md",
|
|
"toolUseId": "toolu_1"}))
|
|
DEPS.meta_store.update(SID, {"title": "Parent renamed"})
|
|
self.c = TestClient(main.app, headers={"x-internal-auth": "tok"})
|
|
self.events = DEPS.hub.subscribe()
|
|
|
|
def tearDown(self):
|
|
DEPS.hub.unsubscribe(self.events)
|
|
super().tearDown()
|
|
|
|
def get(self, rel: str) -> dict:
|
|
r = self.c.get("/api/conversation", params={"id": rel})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
return r.json()
|
|
|
|
def test_asked_once_then_served_from_the_cache(self):
|
|
first = self.get(SUB)
|
|
# Its own task, not the parent's rename (they share a sessionId).
|
|
self.assertEqual(first["title"], PROMPT[:90])
|
|
self.assertIsNone(first["shortTitle"]) # never waits on Haiku
|
|
ev = None
|
|
while not ev or ev.get("type") != "short-title":
|
|
ev = json.loads(self.events.get(timeout=2)[1])
|
|
self.assertEqual(ev, {"type": "short-title", "id": ids.uid_for_rel(SUB),
|
|
"title": "Audit service CLAUDE.md files"})
|
|
for _ in range(2):
|
|
self.assertEqual(self.get(SUB)["shortTitle"], "Audit service CLAUDE.md files")
|
|
self.assertEqual(len(self.sidecar.calls), 1)
|
|
path, payload = self.sidecar.calls[0]
|
|
self.assertEqual(path, "conversation.title")
|
|
self.assertTrue(payload["prompt"].startswith("Audit nested service CLAUDE.md\n\n"))
|
|
self.assertIn("every nested service CLAUDE.md", payload["prompt"])
|
|
|
|
def test_spend_is_booked(self):
|
|
self.get(SUB)
|
|
u = pricing.norm_usage(USAGE)
|
|
[(ref, account, model, cost, units)] = side_calls("short-title")
|
|
self.assertEqual((ref, account, model), (ids.uid_for_rel(SUB), "personal", MODEL))
|
|
self.assertAlmostEqual(cost, pricing.usage_cost(u, MODEL))
|
|
self.assertAlmostEqual(units, pricing.plan_units(u, MODEL))
|
|
|
|
def test_root_conversation_is_left_alone(self):
|
|
d = self.get(ROOT)
|
|
self.assertEqual(d["title"], "Parent renamed")
|
|
self.assertIsNone(d["shortTitle"])
|
|
self.assertIsNone(DEPS.store.get_short_title(ROOT))
|
|
self.assertFalse([p for _, p in self.sidecar.calls
|
|
if "Parent renamed" in p["prompt"]])
|
|
|
|
def test_the_parent_page_names_its_subagents(self):
|
|
# The parent's page is where a subagent is seen: its card must not wait
|
|
# for the child's own page to be opened to get a name.
|
|
with (TMP / "arch" / ROOT).open("a") as fh: # the Task card that spawned it
|
|
fh.write(json.dumps({
|
|
"type": "assistant", "uuid": "a2", "sessionId": SID,
|
|
"timestamp": "2026-10-13T20:00:02Z",
|
|
"message": {"role": "assistant", "model": "claude-opus-5-5", "content": [
|
|
{"type": "tool_use", "id": "toolu_1", "name": "Agent",
|
|
"input": {"description": "Audit nested service CLAUDE.md",
|
|
"prompt": PROMPT}}]}}) + "\n")
|
|
DEPS.indexer.scan_transcripts()
|
|
pool = short_title._POOL = Deferred()
|
|
[ref] = self.get(ROOT)["subagents"]
|
|
self.assertIsNone(ref["shortTitle"]) # never waits on Haiku
|
|
self.assertEqual(len(pool.jobs), 1)
|
|
fn, args = pool.jobs.pop()
|
|
fn(*args)
|
|
ev = None
|
|
while not ev or ev.get("type") != "short-title":
|
|
ev = json.loads(self.events.get(timeout=2)[1])
|
|
self.assertEqual(ev, {"type": "short-title", "id": ids.uid_for_rel(SUB),
|
|
"title": "Audit service CLAUDE.md files"})
|
|
_, payload = self.sidecar.calls[0]
|
|
self.assertTrue(payload["prompt"].startswith("Audit nested service CLAUDE.md\n\n"))
|
|
self.assertIn("every nested service CLAUDE.md", payload["prompt"])
|
|
d = self.get(ROOT)
|
|
[ref] = d["subagents"]
|
|
self.assertEqual(ref["shortTitle"], "Audit service CLAUDE.md files")
|
|
self.assertEqual(ref["title"], PROMPT[:90])
|
|
[card] = [it for it in d["thread"] if it.get("subagent")]
|
|
self.assertEqual(card["subagent"]["shortTitle"], "Audit service CLAUDE.md files")
|
|
# …and its own page is served from the same cache.
|
|
self.assertEqual(self.get(SUB)["shortTitle"], "Audit service CLAUDE.md files")
|
|
self.assertEqual(pool.jobs, [])
|
|
self.assertEqual(len(self.sidecar.calls), 1)
|
|
|
|
def test_the_graph_list_never_asks(self):
|
|
DEPS.indexer.scan_transcripts()
|
|
r = self.c.get("/api/subagents")
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertIn(ids.uid_for_rel(SUB), [s["id"] for s in r.json()["subagents"]])
|
|
self.assertEqual(self.sidecar.calls, [])
|
|
|
|
|
|
class NestedParentChain(Base):
|
|
"""A nested agent's parents are named after their own task, not the root's
|
|
rename: the whole tree shares one sessionId, so the root's meta title (or
|
|
resource title) is every sidechain's sidecar title too."""
|
|
SID3 = "33333333-2222-4333-8444-888888888888"
|
|
ROOT3 = f"-home-x/{SID3}.jsonl"
|
|
MID = f"-home-x/{SID3}/subagents/agent-b1.jsonl"
|
|
LEAF = f"-home-x/{SID3}/subagents/agent-b2.jsonl"
|
|
MID_PROMPT = ("You are the **storage** track of the Emperor browser port. Read "
|
|
"the brief, then port the warehouse and cart systems end to end.")
|
|
|
|
def setUp(self):
|
|
super().setUp()
|
|
write(self.ROOT3, "Port Emperor to the browser", False, self.SID3)
|
|
write(self.MID, self.MID_PROMPT, True, self.SID3)
|
|
write(self.LEAF, "Find where carts pick their warehouse", True, self.SID3)
|
|
sub_dir = TMP / "arch" / self.MID
|
|
sub_dir.with_name("agent-b1.meta.json").write_text(json.dumps(
|
|
{"agentType": "general-purpose", "description": "Storage and carts",
|
|
"toolUseId": "toolu_b1", "spawnDepth": 1}))
|
|
sub_dir.with_name("agent-b2.meta.json").write_text(json.dumps(
|
|
{"agentType": "Explore", "description": "Cart lookup", "toolUseId": "toolu_b2",
|
|
"parentAgentId": "b1", "spawnDepth": 2}))
|
|
DEPS.meta_store.update(self.SID3, {"title": "Emperor web port v0",
|
|
"titleSource": "agent"})
|
|
DEPS.indexer.scan_transcripts()
|
|
self.c = TestClient(main.app, headers={"x-internal-auth": "tok"})
|
|
|
|
def test_a_nested_agents_parent_keeps_its_own_title(self):
|
|
r = self.c.get("/api/conversation", params={"id": self.LEAF})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
d = r.json()
|
|
root, mid = d["parentChain"]
|
|
self.assertEqual(root["title"], "Emperor web port v0") # the root's rename
|
|
self.assertEqual(mid["title"], self.MID_PROMPT[:90])
|
|
self.assertEqual(d["parentConversation"]["title"], self.MID_PROMPT[:90])
|
|
|
|
|
|
class ForDetail(Base):
|
|
def data(self, title=PROMPT[:90]):
|
|
return {"title": title, "thread": [{"role": "user", "kind": "text", "text": PROMPT}]}
|
|
|
|
def test_short_enough_titles_are_kept(self):
|
|
self.assertIsNone(short_title.for_detail(DEPS, "c-short", self.data("Fix the header"),
|
|
True))
|
|
self.assertEqual(self.sidecar.calls, [])
|
|
|
|
def test_a_failed_ask_is_retried_only_later(self):
|
|
self.sidecar.reply = None
|
|
short_title.for_detail(DEPS, "c-fail", self.data(), True)
|
|
short_title.for_detail(DEPS, "c-fail", self.data(), True)
|
|
self.assertEqual(len(self.sidecar.calls), 1)
|
|
self.assertEqual(side_calls("short-title"), []) # nothing answered, nothing spent
|
|
short_title.RETRY_S = 0
|
|
self.sidecar.reply = self.reply
|
|
short_title.for_detail(DEPS, "c-fail", self.data(), True)
|
|
self.assertEqual(len(self.sidecar.calls), 2)
|
|
self.assertEqual(short_title.for_detail(DEPS, "c-fail", self.data(), True),
|
|
"Audit service CLAUDE.md files")
|
|
|
|
def test_one_ask_in_flight_per_conversation(self):
|
|
pool = short_title._POOL = Deferred()
|
|
short_title.for_detail(DEPS, "c-busy", self.data(), True)
|
|
short_title.for_detail(DEPS, "c-busy", self.data(), True)
|
|
self.assertEqual(len(pool.jobs), 1)
|
|
fn, args = pool.jobs[0]
|
|
fn(*args)
|
|
self.assertEqual(short_title.for_detail(DEPS, "c-busy", self.data(), True),
|
|
"Audit service CLAUDE.md files")
|
|
|
|
def test_an_answer_no_shorter_is_dropped(self):
|
|
self.sidecar.reply = {**self.reply, "title": "x" * 95}
|
|
self.assertIsNone(short_title.for_detail(DEPS, "c-long", self.data(), True))
|
|
self.assertEqual(DEPS.store.get_short_title("c-long")[0], None)
|
|
|
|
def test_a_row_from_before_the_source_was_kept_still_counts(self):
|
|
DEPS.store._db.execute("INSERT INTO short_titles (conv_id, title, asked_at) "
|
|
"VALUES ('c-old', 'Old answer', 0)")
|
|
DEPS.store._db.commit()
|
|
self.assertEqual(short_title.for_detail(DEPS, "c-old", self.data(), True), "Old answer")
|
|
self.assertEqual(self.sidecar.calls, [])
|
|
|
|
def test_a_leading_issue_key_or_pr_is_kept(self):
|
|
keep = short_title._keep_id
|
|
self.assertEqual(keep("INS-2229 · Pricing must wait for the server · #13722",
|
|
"Order pricing after update"),
|
|
"INS-2229 · Order pricing after update")
|
|
self.assertEqual(keep("#13841 · feat(tools): check Docker before dev.app.sh starts",
|
|
"Check dev prerequisites"), "#13841 · Check dev prerequisites")
|
|
self.assertEqual(keep("INS-2192 ContractRenewalCreated reactor migration",
|
|
"INS-2192 reactor migration"), "INS-2192 reactor migration")
|
|
self.assertEqual(keep("Address the review on PR #13722 and the INS-2229 nits",
|
|
"Address review nits"), "Address review nits")
|
|
|
|
|
|
class TopLevel(Base):
|
|
"""A top-level conversation's long auto title is shortened too — never
|
|
the owner's rename — and a new auto title is asked about again."""
|
|
reply = {**Base.reply, "title": "Move compose files to Traefik v3"}
|
|
|
|
def setUp(self):
|
|
super().setUp()
|
|
write(TOP, TOP_PROMPT, False, SID2)
|
|
DEPS.meta_store.update(SID2, {"title": ""})
|
|
self.c = TestClient(main.app, headers={"x-internal-auth": "tok"})
|
|
|
|
def get(self) -> dict:
|
|
r = self.c.get("/api/conversation", params={"id": TOP})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
return r.json()
|
|
|
|
def name(self, title: str, source: str | None) -> None:
|
|
DEPS.meta_store.update(SID2, {"title": title, "titleSource": source})
|
|
|
|
def test_a_long_auto_title_is_asked_once(self):
|
|
events = DEPS.hub.subscribe()
|
|
try:
|
|
first = self.get()
|
|
self.assertEqual(first["title"], TOP_PROMPT[:90])
|
|
self.assertIsNone(first["shortTitle"])
|
|
ev = None
|
|
while not ev or ev.get("type") != "short-title":
|
|
ev = json.loads(events.get(timeout=2)[1])
|
|
finally:
|
|
DEPS.hub.unsubscribe(events)
|
|
self.assertEqual(ev, {"type": "short-title", "id": ids.uid_for_rel(TOP),
|
|
"title": "Move compose files to Traefik v3"})
|
|
self.assertEqual(self.get()["shortTitle"], "Move compose files to Traefik v3")
|
|
self.assertEqual(len(self.sidecar.calls), 1)
|
|
self.assertEqual(self.sidecar.calls[0][1]["prompt"], TOP_PROMPT)
|
|
[(ref, *_)] = side_calls("short-title")
|
|
self.assertEqual(ref, ids.uid_for_rel(TOP))
|
|
|
|
def test_the_owners_rename_is_never_shortened(self):
|
|
long = "My own words for this migration, as long as I like them to be"
|
|
for source in ("user", None): # None: a rename from before sources
|
|
with self.subTest(source=source):
|
|
self.name(long, source)
|
|
d = self.get()
|
|
self.assertEqual(d["title"], long)
|
|
self.assertIsNone(d["shortTitle"])
|
|
self.assertEqual(self.sidecar.calls, [])
|
|
|
|
def test_a_new_auto_title_is_asked_again(self):
|
|
self.get()
|
|
stamped = "INS-2229 · Pricing update must wait for the server update · #13722"
|
|
self.name(stamped, "resources")
|
|
self.get()
|
|
self.assertEqual(self.get()["shortTitle"], "INS-2229 · Move compose files to Traefik v3")
|
|
self.assertEqual(len(self.sidecar.calls), 2)
|
|
self.assertTrue(self.sidecar.calls[1][1]["prompt"].startswith(stamped + "\n\n"))
|
|
self.name("", None) # back to the auto title: one row per conversation
|
|
self.assertIsNone(self.get()["shortTitle"])
|
|
self.assertEqual(self.get()["shortTitle"], "Move compose files to Traefik v3")
|
|
self.assertEqual(len(self.sidecar.calls), 3)
|
|
|
|
def test_the_event_reaches_only_who_can_see_it(self):
|
|
DEPS.meta_store.update(SID2, {"owner": "g-dom"})
|
|
dom = Caller(id="g-dom", role="guest", name="Dom")
|
|
flt = _guest_filter(DEPS, dom)
|
|
ev = {"type": "short-title", "id": ids.uid_for_rel(TOP), "title": "x"}
|
|
self.assertEqual(flt(ev), ev)
|
|
self.assertIsNone(flt({**ev, "id": ROOT}))
|
|
|
|
|
|
class Ledger(Base):
|
|
def test_scheduled_titles_are_booked_too(self):
|
|
# a Send later prompt's title (the scheduled-conversations plugin's hub/title)
|
|
self.assertIsNotNone(labels_bridge.title(DEPS, "Audit every compose file", "scheduled-title"))
|
|
[(ref, account, _m, cost, _u)] = side_calls("scheduled-title")
|
|
self.assertEqual((ref, account), (None, "personal"))
|
|
self.assertGreater(cost, 0)
|
|
|
|
def test_an_older_sidecar_books_its_own_dollar_figure(self):
|
|
self.sidecar.reply = {"title": "Nightly audit", "summary": "", "costUsd": 0.001}
|
|
labels_bridge.title(DEPS, "Audit every compose file", "scheduled-title")
|
|
[(_r, account, model, cost, units)] = side_calls("scheduled-title")
|
|
self.assertEqual((account, model, cost, units), ("personal", None, 0.001, 0.0))
|
|
|
|
def test_side_calls_count_on_the_plan_meter(self):
|
|
h = 480_000
|
|
before = calibrate.meters(DEPS, "personal").get(h, [0.0, 0.0])
|
|
DEPS.usage_store.add_side_call("short-title", "c", "personal", MODEL, 0.25, 0.5,
|
|
None, t=h * 3600 + 60)
|
|
self.assertEqual(calibrate.meters(DEPS, "personal")[h],
|
|
[before[0] + 0.25, before[1] + 0.5])
|
|
self.assertNotIn(h, calibrate.meters(DEPS, "work"))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|