diff --git a/CLAUDE.md b/CLAUDE.md index 2df65e5e..45f295b4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -491,7 +491,8 @@ VisibilityPopover.tsx`, switches + store in `lib/visibility.ts`) — a scrollabl grouped list of switches for everything the page renders: per-item metadata (price, tokens, duration, timestamp, model, tool id, result size, diff stat), content (thinking blocks, tool cards, run-command cards, tool output, rich -widgets, error states) and gizmos (task panel, fast-forward, animations). State +widgets, error states) and gizmos (fast-forward, animations; the task panel is +the `tasks` plugin's switch now). State persists server-side via `ui-state` under the key `ai-agent-visibility`, so a reading setup follows the user across devices. @@ -4291,6 +4292,56 @@ generic — docs/plugins.md → "Trackers": `worktrees`), then the hub — a hub without the plugin simply shows no pill until it is installed. +### Tasks are a plugin: tool trackers, checklists (since 2026-12-02) + +A conversation's **task list** — the `✓ 2/5` pill on its card and in its +header, the floating Tasks panel over the thread, the `todo` tool card and the +parse behind them — left the core the same day for the seeded **`tasks`** +plugin (`~/projects/ai-agent-plugins/plugins/tasks`, pure data: no handler, no +capability; `managed` with `defaultForGuests`; Gabriel's picks in forms +`tasks-pill-popover_rdyw4k` and `move-tasks-into-a-plugin_tq2l2e`). The core's +fold (`todo_op`, `_task_times`, `ParserState.tasks`), the summary's and the +card's `tasks` field, the `Task` schema, `TaskPanel.tsx`, the registered `todo` +card and the `taskPanel` visibility key are gone. What the core has instead is +generic — docs/plugins.md → "Trackers" (*Tool trackers*) and "Checklists": + +- **Tool trackers** (`backend/plugins/trackers.py`): a `trackers[]` entry with + `tool` + `ops` + `statuses` reads a **tool's calls** by their neutral name + (`todo` = Claude Code's TaskCreate / TaskUpdate / TodoWrite, agy's + `update_steps`), three ops told apart by the input — **create** (key = its + 1-based ordinal), **update** by id, whole-list **snapshot** (a same-named + row keeps its times). Items carry `status` (pending / in_progress / + completed / cancelled) and `openedAt` (added) / `startedAt` / `closedAt`, + in the list's own order. `ParserState` feeds every tool call to + `Fold.feed_tool`; nothing names tasks in the engine. +- **No `PARSER_VERSION` bump** (it stays 48 — the v49 of the popover commit + never shipped): the re-derive pass finds the transcripts to re-read by what + their bytes hold when they call the tool (`toolnames.byte_hints`, quoted + names: `"todo"`, `"TaskCreate"`, `"TodoWrite"`, `:update_steps"`…), and an older row's `tasks` is + read as the provider's items until then (`plugins/carryover_trackers.py`). +- **`provides: {"tasks.list": ""}`**: the role the core's readers + ask through `trackers.provided("tasks.list", summary, meta)` — the completion + scaffold's *Task list*. No provider ⇒ no list anywhere, nothing breaks. +- **The plugin declares, the app draws** (no frame): a `ui.card[]` list bit + with `style: "checklist"` (the pill and its hover / tap card: rows in plan + order, each task's *added · started · done · took*, 8 rows then it scrolls — + drawn first among the plugin pills, where the badge stood, on the home and + drawer cards, the Conversations page and the details tag row), `ui.panels[]` + (the floating panel, `PluginTrackerPanels`), and a `ui.toolCards[]` entry + naming the `tracker` (the calls' rows: "New task …", "Task #2 → completed", + "3 task updates" folded — `plugins/trackerCards.tsx`, registered into the + tool-card registry while the plugin is active; `useToolCardsEpoch` redraws + mounted rows). `technical/PillPopover.tsx` is the shared hover card (the + worktrees list, the checklist, the preset pill — the preset one stays core). +- **Three eye switches** (the plugin's `vis`): *Tasks pill*, *Task panel* (a + hidden core *Task panel* carries over — `lib/visibility.ts` `RENAMED_KEYS`), + and *Task calls*, off by default: off, the thread leaves the task-list calls + out as it always did; on, they are rows. Without the plugin: no pill, no + panel, and those calls are plain generic tool rows. +- **Deploy order**: the hub first or both together — an older hub can't + validate a tool tracker and skips the seed with a warning (no pill until the + new hub is up); a new hub without the plugin shows no tasks. + ### Model tags Models are a first-class tag on both sides of the app (`frontend/src/lib/models.tsx`): @@ -4868,7 +4919,7 @@ Google ever objects — `agy_cli.run_env` is where it would go. `agent-.jsonl` linked to its spawning call. Tools are shaped as Claude's (`sidecar/agy_tools.py` — both spellings agy uses: `read_file`/`view_file`, `edit_file`/`replace_file_content`…) under neutral - names, agy's own in `native`. **Tasks** (since 2026-12-01, parser v48): `update_steps` is a `todo` snapshot (the Tasks panel, the x/n badge — an older mirror's `agy:update_steps` is read as one), a background `run_command` / `schedule` result carries `data.taskId` (`/task-N`) so its card is a background task, `manage_task` is `shell_output` / `shell_kill`, and agy's `sender=/task-N` messages are `task_done` notes — docs/transcript-format.md → "agy's tasks". agy deletes + names, agy's own in `native`. **Tasks** (since 2026-12-01, parser v48): `update_steps` is a `todo` snapshot (the `tasks` plugin's panel and x/n pill read it — an older mirror's `agy:update_steps` is read as one), a background `run_command` / `schedule` result carries `data.taskId` (`/task-N`) so its card is a background task, `manage_task` is `shell_output` / `shell_kill`, and agy's `sender=/task-N` messages are `task_done` notes — docs/transcript-format.md → "agy's tasks". agy deletes all but its newest 500 conversations; the mirror's copy is what stays. - **CLAUDE.md and skills.** agy reads AGENTS.md / GEMINI.md and `.agents/skills`, never CLAUDE.md or `.claude/skills`: the sidecar keeps a diff --git a/backend/conversations/catalog.py b/backend/conversations/catalog.py index bf387995..70f774c8 100644 --- a/backend/conversations/catalog.py +++ b/backend/conversations/catalog.py @@ -222,7 +222,7 @@ def _conv_card(deps: AppState, path: str, s: dict) -> dict: _CARD_KEYS = ("sessionId", "project", "gitBranch", "model", "models", "efforts", "title", "userTurns", "assistantTurns", "messages", "startedAt", "endedAt", "tokens", "cost", "byTool", "subagentCount", - "subagentTokens", "subagentCost", "tasks", + "subagentTokens", "subagentCost", "planUnits", "subagentPlanUnits", "priceBook", "fastCalls", "local") _EXTRA_FULL_KEYS = ("usage", "byToolSub", "byModel") diff --git a/backend/conversations/parse/__init__.py b/backend/conversations/parse/__init__.py index a596ccd6..e58611a3 100644 --- a/backend/conversations/parse/__init__.py +++ b/backend/conversations/parse/__init__.py @@ -71,7 +71,7 @@ from .tools import ( # noqa: F401 _BASH_PREFIX, _COMMIT_CMD_RE, _DEPLOY_URL_PATTERNS, _EDIT_TOOLS, _HOMELAB_ROOT, _LIFECYCLE_PATTERNS, _LOG_ONE_RE, _MAX_GIT_ROOTS, _MAX_WORKTREE_ADDS, _MAX_WRITTEN_DIRS, _MEMORY_RE, _PROJECT_RE, - _SERVICE_RE, _SKILL_STAGES, _TASK_STATES, _TASK_SUBJECT_MAX, + _SERVICE_RE, _SKILL_STAGES, _TASK_SUBJECT_MAX, _bash_program, _bucket, _deploy_call, _deployed_url, _file_ext, _lifecycle_stages, _projects_in, _services_in, _subkey, _task_subject, diff --git a/backend/conversations/parse/readers/toolnames.py b/backend/conversations/parse/readers/toolnames.py index 94f350e6..0a0838da 100644 --- a/backend/conversations/parse/readers/toolnames.py +++ b/backend/conversations/parse/readers/toolnames.py @@ -115,6 +115,33 @@ def upgrade_call(tool, native, inp): return tool, native, inp +def byte_hints(tool: str) -> tuple[str, ...]: + """ASCII literals of which a transcript's bytes hold at least one when it + calls ``tool`` (a neutral name) — the cheap pre-filter of the tracker + re-derive pass (``Indexer.rederive_trackers``) for a tracker that reads a + tool's calls. + + Each is a tool name **with its JSON quote(s)**, so text that merely talks + about the tool (escaped inside a message's string) doesn't count: a v1 + file names the tool as it is (``"tool": "todo"``), a Claude-Code-format + one by the harness's own name (``"name": "TaskCreate"``), and an older + agy mirror wrote its plan steps as ``"agy:update_steps"``. A tool only + one harness has (``claude:CronCreate``) is ``"CronCreate"`` in its own + records and ``"claude:CronCreate"`` in a v1 file; an MCP tool keeps one + name everywhere.""" + if is_mcp(tool): + return (f'"{tool}"',) + head, sep, rest = tool.partition(":") + if sep: + return (f'"{rest}"', f':{rest}"') + natives = sorted(n for table in (CLAUDE, LEGACY) for n, neutral in table.items() + if neutral == tool) + hints = [f'"{tool}"', *(f'"{n}"' for n in natives)] + if tool == "todo": + hints.append(':update_steps"') + return tuple(hints) + + def display_name(name: str | None) -> str: """A namespaced name without its harness id (``claude:CronCreate`` → ``CronCreate``), for text meant for people.""" diff --git a/backend/conversations/parse/state.py b/backend/conversations/parse/state.py index 7a4db01b..a3e2839b 100644 --- a/backend/conversations/parse/state.py +++ b/backend/conversations/parse/state.py @@ -52,9 +52,7 @@ from .tools import ( _deploy_call, _bucket, _subkey, - _TASK_STATES, _task_subject, - todo_op, _projects_in, _services_in, ) @@ -188,10 +186,6 @@ class ParserState: # it can't be one the call made (see the hook attachment below). self.bash_started: dict[str, str] = {} self.skills: dict[str, dict] = {} - # Task list (TaskCreate/TaskUpdate or the older TodoWrite snapshots), - # keyed by sequential string id; insertion order ≈ creation order. - self.tasks: dict[str, dict] = {} - self.task_seq = 0 # running counter → next task id self.lifecycle: dict[str, str] = {} # stage -> latest evidence ts self.memories_read: set[str] = set() self.last_assistant_text = "" # final assistant text (DONE marker) @@ -898,46 +892,9 @@ class ParserState: sk = (raw_inp or {}).get("skill") if sk: self._count_skill(sk, ts) - # The task list (`todo`, told apart by its input: `todo_op`). - # A create appends a task (id = its 1-based ordinal, the same - # id its tool_result reports and an update cites); an update - # mutates one by id. A snapshot (Claude Code's older - # TodoWrite) re-sends the *entire* list each call, so it resets - # our task map to it — the last snapshot wins. - op = todo_op(inp) if name == "todo" else None - if op == "create": - self.task_seq += 1 - tid = str(self.task_seq) - self.tasks[tid] = { - "id": tid, - "subject": _task_subject( - inp.get("subject") or inp.get("content")), - "status": "pending", - } - elif op == "update": - tid = str(inp.get("taskId") or inp.get("task_id") or "") - cur = self.tasks.get(tid) - if cur is not None: - st = inp.get("status") - if st in _TASK_STATES: - cur["status"] = st - if inp.get("subject"): - cur["subject"] = _task_subject(inp["subject"]) - elif op == "snapshot": - self.tasks.clear() - self.task_seq = 0 - for td in inp["todos"]: - if not isinstance(td, dict): - continue - self.task_seq += 1 - tid = str(self.task_seq) - st = td.get("status") - self.tasks[tid] = { - "id": tid, - "subject": _task_subject( - td.get("content") or td.get("activeForm")), - "status": st if st in _TASK_STATES else "pending", - } + # The plugins' tool trackers (plugins/trackers.py): the + # `tasks` plugin's reads the task list off the `todo` calls. + self.trackers.feed_tool(name, inp, ts) if name == "agent" and bid: self.agent_calls[bid] = { "toolUseId": bid, @@ -1284,7 +1241,6 @@ class ParserState: # none ⇒ the conversation committed nothing, whatever a time # window over its repos would find. "commitCalls": len(self.commit_calls), - "tasks": list(self.tasks.values()), "runningAgents": list(self.agent_calls.values()), "deploying": bool(self.deploying_since), "lifecycleAuto": self.lifecycle, diff --git a/backend/conversations/parse/tools.py b/backend/conversations/parse/tools.py index b4b26d00..243968f4 100644 --- a/backend/conversations/parse/tools.py +++ b/backend/conversations/parse/tools.py @@ -1,6 +1,7 @@ """Tool calls: the activity buckets and their sub-labels, the project / service / commit evidence mined from them, the lifecycle stamps and -deploys, agent launches and task lists.""" +deploys and agent launches. (A task list is a plugin's tool tracker — +plugins/trackers.py.)""" import re @@ -256,28 +257,11 @@ def _subkey(bucket: str, tool: str | None, inp: dict) -> str | None: return tool or "tool" -def todo_op(inp: dict) -> str: - """What a ``todo`` call does, told by its input (the neutral name covers - Claude Code's five task tools): ``snapshot`` — the whole list again - (TodoWrite's ``todos``); ``update`` — one task by id (TaskUpdate; - TaskGet's lone id changes nothing); ``create`` — a new task (TaskCreate's - ``subject``); ``list`` — nothing to fold (TaskList).""" - if isinstance(inp.get("todos"), list): - return "snapshot" - if inp.get("taskId") or inp.get("task_id"): - return "update" - if inp.get("subject") or inp.get("content"): - return "create" - return "list" - - -# Valid task states we normalise to; anything else falls back to "pending". -_TASK_STATES = {"pending", "in_progress", "completed", "cancelled"} _TASK_SUBJECT_MAX = 200 def _task_subject(s) -> str: - """A short, single-line label for a task (bounded for the compact panel).""" + """A short, single-line label (an agent call's description).""" s = " ".join(str(s or "").split()).strip() or "task" return s[:_TASK_SUBJECT_MAX] diff --git a/backend/conversations/scaffold.py b/backend/conversations/scaffold.py index c11dd012..149c744e 100644 --- a/backend/conversations/scaffold.py +++ b/backend/conversations/scaffold.py @@ -178,9 +178,12 @@ def _prompts(thread: list[dict]) -> list[str]: return out -def _work(thread: list[dict], summary: dict) -> list[str]: +def _work(thread: list[dict], summary: dict, meta: dict | None = None) -> list[str]: calls = [it for it in thread if it.get("kind") == "tool_use"] - if not calls and not (summary.get("tasks") or []): + # The task list is the `tasks.list` provider's (a plugin's tool tracker — + # plugins/trackers.py); none active: no list. + tasks = plugin_trackers.provided("tasks.list", summary, meta) + if not calls and not tasks: return [] bash: dict[str, int] = {} bash_examples: dict[str, list[str]] = {} @@ -244,7 +247,6 @@ def _work(thread: list[dict], summary: dict) -> list[str]: out.append("") out += [f"- {a}" for a in agents[:MAX_ROWS]] out.append("") - tasks = summary.get("tasks") or [] if tasks: out.append("### Task list") out.append("") @@ -357,7 +359,7 @@ def build(cid: str, sid: str, summary: dict, meta: dict, store) -> str: ] out += _metadata(cid, sid, summary, meta) out += _prompts(thread) - out += _work(thread, summary) + out += _work(thread, summary, meta) out += _changes(store, summary, meta, sid) out += [SUMMARY_HEADING, "", _SUMMARY_TODO, "", ANALYSIS_HEADING, "", _ANALYSIS_TODO, ""] diff --git a/backend/core/i18n_keys/ui.json b/backend/core/i18n_keys/ui.json index 43c3e043..44cf6a65 100644 --- a/backend/core/i18n_keys/ui.json +++ b/backend/core/i18n_keys/ui.json @@ -33,6 +33,7 @@ "A conversation that's gone", "A few answers first — the line carries them.", "A harness (Claude Code, pi, opencode…) runs the conversations: install one to start.", + "A later turn picked one exact model ({model}): the ladder no longer steps", "A profile picks its ★ account per provider — Settings → Machines.", "A provider brings the models a harness runs on: install one to start.", "A reply to this conversation didn't go out — open it to retry", @@ -241,9 +242,6 @@ "Compaction summary", "Compactions", "Completed", - "Completed {detail}", - "Completed {n} task", - "Completed {n} tasks", "Composer", "Computers", "Config", @@ -327,8 +325,6 @@ "Create a new plugin", "Created {n} file", "Created {n} files", - "Created {n} task", - "Created {n} tasks", "Creating form…", "Credentials", "Currency", @@ -415,6 +411,7 @@ "Every card on {subject} takes it.", "Every model a conversation can run on. The model decides the harness — Claude on Claude Code, Gemini on Antigravity, the EVOX2's models on pi, GPT on OpenCode — and its defaults are what a custom run starts with; the composer still changes them per run. ★ favorites head every model picker, guests' included.", "Every new {profile} prompt runs here.", + "Every rung was full: it fell back to this one", "Everything here is installed.", "Exact search (click for fuzzy)", "Exchange rate used to convert dollar costs to euros.", @@ -839,6 +836,7 @@ "Open it beside the conversation on screen", "Open its card", "Open its page", + "Open preset", "Open sign-in page", "Open site", "Open supported links", @@ -1148,7 +1146,6 @@ "Show less", "Show more", "Show or hide the sidebar", - "Show tasks", "Show the form in the thread", "Show the summary: your messages and Claude's closing ones", "Show the usage tiles", @@ -1196,9 +1193,6 @@ "Start of interval", "Started by", "Started conversations", - "Started {detail}", - "Started {n} task", - "Started {n} tasks", "Started — it will show up in your conversations shortly.", "Starts a new project from a template — click to send a normal prompt", "Starts a new project — the session asks its name and address in a form; click to pick an existing project instead", @@ -1246,8 +1240,6 @@ "Tap to open My computers · swipe to dismiss", "Tap to open the machine · swipe to dismiss", "Tap to open · swipe to dismiss", - "Task panel", - "Tasks", "Teal", "Terminal", "Terminal sessions", @@ -1399,11 +1391,6 @@ "Update a plugin from the catalog", "Update now", "Updated", - "Updated todos {n} list", - "Updated todos {n} lists", - "Updated {detail}", - "Updated {n} task", - "Updated {n} tasks", "Updating…", "Updating… {time}", "Upload SVG", @@ -1710,7 +1697,6 @@ "files changed by these calls (distinct) and their lines, summed", "file|Created {detail}", "finished", - "floating task checklist", "for a terminal — pi runs stay on the {hub}", "fork", "fork from here", @@ -1959,6 +1945,7 @@ "run `claude auth login` on the machine, or switch it to Through the {hub}", "run `gh auth login` on the machine", "run on your own computer", + "rung {i} of {n}", "running", "running-total curve + $1/$5/$10 guides over the cost-growth bars", "save as draft", @@ -1973,6 +1960,8 @@ "select", "sending…", "sent", + "sent here", + "sent here {when}", "sent {time}", "serve not answering", "serve running", @@ -1993,6 +1982,7 @@ "skill", "skill:", "skills: {status}", + "skipped", "spawn", "spawned by a cron job", "spawned by this cron job — open it in Settings", @@ -2004,6 +1994,8 @@ "starts in", "starts in the folder it was installed from", "stepped down", + "stepped down {when}", + "stepped down {when} · {why}", "still loading — try again in a second", "stop the loop", "stopped", @@ -2020,7 +2012,6 @@ "tap a stack to open it · swipe to dismiss", "target {pct}%", "task output|Read {detail}", - "task|Created {detail}", "team", "team {name}", "the --effort level(s) this conversation's turns ran at", @@ -2098,7 +2089,6 @@ "tool|Globbed", "tool|Handed back", "tool|Left worktree", - "tool|New task", "tool|Notified", "tool|Patched", "tool|Plan mode", @@ -2109,10 +2099,8 @@ "tool|Searched", "tool|Searched web", "tool|Stopped", - "tool|Task", "tool|Task output", "tool|Tool search", - "tool|Updated todos", "tool|Waited for code", "tool|Wake-up", "total time these calls took", @@ -2132,6 +2120,7 @@ "unit|hours", "unit|months", "unit|weeks", + "unknown model", "unpaired", "unread", "up to {size}", @@ -2201,7 +2190,6 @@ "{cost} / day", "{cpu} CPU and a {peak} peak, its calls together", "{done} of {total} strings ({pct}%)", - "{done} of {total} tasks done", "{done}/{total} done", "{done}/{total} steps", "{d}d {h}h", diff --git a/backend/fixtures/tracker_plugins/kit.py b/backend/fixtures/tracker_plugins/kit.py index 275d3599..f84a1a6b 100644 --- a/backend/fixtures/tracker_plugins/kit.py +++ b/backend/fixtures/tracker_plugins/kit.py @@ -1,6 +1,7 @@ -"""The reference tracker plugin (``worktrees.json`` — the shape the -``worktrees`` hub plugin ships) and a fake plugin store to run the parser and -the cards on it, as ``fixtures/resource_plugins/kit.py`` does for resources.""" +"""The reference tracker plugins (``worktrees.json`` — the shape the +``worktrees`` hub plugin ships: shell commands; ``tasks.json`` — the ``tasks`` +plugin's: a tool's calls) and a fake plugin store to run the parser and the +cards on them, as ``fixtures/resource_plugins/kit.py`` does for resources.""" from __future__ import annotations @@ -14,6 +15,7 @@ from plugins import trackers as plugin_trackers HERE = pathlib.Path(__file__).resolve().parent KEY = "worktrees:worktrees" +TASKS = "tasks:tasks" def manifest(name: str = "worktrees") -> dict: @@ -45,6 +47,16 @@ def registry(manifests=None): return plugin_trackers.registry(deps_with(FakePluginStore(manifests))) +def tasks_store() -> FakePluginStore: + """A store with the tasks plugin alone.""" + return FakePluginStore([manifest("tasks")]) + + +def task_list(summary: dict) -> list[dict]: + """The tasks tracker's items in a parse (``[]`` when it read none).""" + return ((summary.get("trackersAuto") or {}).get(TASKS) or {}).get("items") or [] + + @contextlib.contextmanager def bound(store=None): """The parser and the deps-less accessors read ``store``'s trackers.""" diff --git a/backend/fixtures/tracker_plugins/tasks.json b/backend/fixtures/tracker_plugins/tasks.json new file mode 100644 index 00000000..5bb01ff6 --- /dev/null +++ b/backend/fixtures/tracker_plugins/tasks.json @@ -0,0 +1,48 @@ +{ + "schema": 1, + "id": "tasks", + "name": "Tasks", + "version": "1.0.0", + "description": "The task list a conversation keeps — a progress pill on its card, a checklist over its thread.", + "trackers": [ + { + "id": "tasks", + "label": "Tasks", + "tool": "todo", + "ops": [ + {"do": "snapshot", "items": "todos", "name": ["content", "activeForm"], "status": "status"}, + {"do": "update", "id": ["taskId", "task_id"], "name": "subject", "status": "status"}, + {"do": "create", "name": ["subject", "content"]} + ], + "statuses": {"deleted": "cancelled"} + } + ], + "provides": {"tasks.list": "tasks"}, + "ui": { + "card": [ + { + "id": "tasks", "place": "tags", "icon": "list-checks", "tone": "primary", + "list": { + "tracker": "tasks", "style": "checklist", + "title": "Tasks", "progress": "{done} of {total} tasks done", + "added": "added {when}", "started": "started {when}", "done": "done {when}", + "cancelled": "cancelled {when}", "took": "took {time}" + }, + "vis": {"key": "pill", "label": "Tasks pill", "hint": "A conversation's task progress — the pill on its card and in its header"} + } + ], + "panels": [ + { + "id": "tasks", "tracker": "tasks", "title": "Tasks", "show": "Show tasks", + "vis": {"key": "panel", "label": "Task panel", "hint": "The floating task checklist over a conversation's thread"} + } + ], + "toolCards": [ + { + "id": "todo", "tracker": "tasks", "icon": "list-checks", + "create": "New task", "update": "Task", "snapshot": "Updated todos", "many": "{count} task updates", + "vis": {"key": "calls", "label": "Task calls", "hint": "The calls that keep the task list, as rows in the thread", "defaultOff": true} + } + ] + } +} diff --git a/backend/indexer.py b/backend/indexer.py index 65976a9a..761d0627 100644 --- a/backend/indexer.py +++ b/backend/indexer.py @@ -135,6 +135,10 @@ from telemetry import metrics as tm # (plugins/trackers.py). Its own pass (`rederive_trackers`) re-reads the # transcripts a rule change concerns; an older row's `worktreesAuto` is # still read (plugins/carryover_trackers.py) until then. +# (no bump, 2026-12-02): the task list (`tasks`) left the summary too — the +# `tasks` plugin's tool tracker reads the `todo` calls into +# `trackersAuto` (status + times per task). An older row's `tasks` is +# read until the re-derive pass has re-read it. # # Each row keeps the version that wrote it (`transcripts.parser_version`). A # bump no longer wipes the store: every row keeps serving its summary until @@ -627,7 +631,9 @@ class Indexer: rules, so an install or an upgrade that changes one must re-derive — but only for that tracker, and only where it can matter: the transcripts whose bytes hold its ``hint`` (a rule matches no command - without it) and whose summary wasn't already read with these rules. + without it; a tool tracker's are its tool's names — + ``toolnames.byte_hints``) and whose summary wasn't already read with + these rules. The rule set every row is known to be good for is the store's ``trackers_sigs`` meta row: equal to the active one (every plain boot), this is one dict compare. Most recently active first, within @@ -658,7 +664,8 @@ class Indexer: continue self._rederive_seen.add(path) ents = (self.store.get_summary(path) or {}).get("trackersAuto") or {} - need = [t.hint for t in changed if (ents.get(t.key) or {}).get("sig") != t.sig] + need = [h for t in changed if (ents.get(t.key) or {}).get("sig") != t.sig + for h in t.hints] if not need or not _file_holds(path, need): continue t0 = time.monotonic() diff --git a/backend/plugins/carryover_trackers.py b/backend/plugins/carryover_trackers.py index ced3411d..adc2c847 100644 --- a/backend/plugins/carryover_trackers.py +++ b/backend/plugins/carryover_trackers.py @@ -9,6 +9,13 @@ the tracker that provides ``git.worktrees`` reads them as its own items, so every past conversation keeps its pill from the first request — before the indexer's re-derive pass has re-read its transcript, and for the stamps for good. A summary re-parsed since carries no ``worktreesAuto`` any more. + +The same day the **task list** left too (the ``tasks`` plugin): the parser +kept ``tasks`` on a summary — ``[{id, subject, status, createdAt?, +startedAt?, endedAt?}]`` — which the tool tracker that provides +``tasks.list`` reads as its items until the re-derive pass has re-read the +transcript with its own rules (``trackers.items_for``: only while the +summary has no entry of the tracker's current rules). """ from __future__ import annotations @@ -27,11 +34,29 @@ def _worktree_items(records) -> list[dict]: return out +_STATUSES = ("pending", "in_progress", "completed", "cancelled") + + +def _task_items(tasks) -> list[dict]: + out = [] + for e in tasks or (): + if not isinstance(e, dict) or not e.get("id"): + continue + st = e.get("status") + out.append({"key": str(e["id"]), "name": e.get("subject") or str(e["id"]), "group": None, + "status": st if st in _STATUSES else "pending", + "openedAt": e.get("createdAt"), "startedAt": e.get("startedAt"), + "closedAt": e.get("endedAt")}) + return out + + def items(role: str, summary: dict, meta: dict) -> list[dict]: """The pre-tracker records of ``role`` on a conversation, as tracker items.""" if role == "git.worktrees": return (_worktree_items(summary.get("worktreesAuto")) + _worktree_items(meta.get("worktrees"))) + if role == "tasks.list": + return _task_items(summary.get("tasks")) return [] diff --git a/backend/plugins/hubtrackers.py b/backend/plugins/hubtrackers.py index 597f72c1..e2b8fbd2 100644 --- a/backend/plugins/hubtrackers.py +++ b/backend/plugins/hubtrackers.py @@ -75,6 +75,9 @@ def _stamp(request: Request, pid: str, tid: str, body: dict): deps, who, key, err = _gate(request, pid, tid) if err: return err + if trackers.registry(deps).by_key[key].tool: + return _error(400, "a tool tracker's list is its transcript's: nothing stamps it", + "bad_request") ev = trackers.clean_event(body) if ev is None: return _error(400, "the body is {sessionId, do: open|close, key, name?, group?, at?}", diff --git a/backend/plugins/manifest.py b/backend/plugins/manifest.py index 4af4bff5..7baa2051 100644 --- a/backend/plugins/manifest.py +++ b/backend/plugins/manifest.py @@ -145,8 +145,8 @@ CARD_FIELDS = frozenset({ CARD_FORMATS = frozenset({"text", "int", "dec1", "pct", "pct2", "apct", "usd", "wh", "duration"}) CARD_ICONS = frozenset({ "alert-triangle", "battery", "bot", "circle-gauge", "clock", "coins", "cpu", "flame", - "gauge", "git-branch", "laptop", "leaf", "server", "shield", "sparkles", "star", "tag", - "wrench", "zap", + "gauge", "git-branch", "laptop", "leaf", "list-checks", "server", "shield", "sparkles", + "star", "tag", "wrench", "zap", }) # ``ui.card[].list``: a tags bit drawn from one of the plugin's trackers — the # pill reads the single item's name or ``many``, and opens a card of rows @@ -162,6 +162,37 @@ CARD_LIST_TEXTS: dict[str, tuple[int, str | None, str]] = { "closedAt": (60, "{when}", "closed {when}"), "lifespan": (60, "{time}", "lasted {time}"), } +# A list bit with ``style: "checklist"`` (a tool tracker's items: each has a +# status): the pill is a progress count — done / total, a cancelled item out +# of both — and its card the checklist, each row's times under it. Its +# wording; the frontend's ``CARD_CHECKLIST_TEXTS`` keeps the same keys. +CARD_LIST_STYLES = ("timeline", "checklist") +CARD_CHECKLIST_TEXTS: dict[str, tuple[int, str | None, str]] = { + "title": (40, None, "Checklist"), + "progress": (80, "{done}", "{done} of {total} done"), + "added": (60, "{when}", "added {when}"), + "started": (60, "{when}", "started {when}"), + "done": (60, "{when}", "done {when}"), + "cancelled": (60, "{when}", "cancelled {when}"), + "took": (60, "{time}", "took {time}"), +} +# ``ui.panels[]``: a tool tracker's checklist floating over the conversation's +# thread (top right, collapsible), drawn by the app. Its wording. +PANEL_TEXTS: dict[str, tuple[int, str | None, str]] = { + "title": (40, None, "Checklist"), + "show": (60, None, "Show the checklist"), +} +_PANELS_MAX = 2 +# ``ui.toolCards[]`` with ``tracker`` (no ``match`` / ``html``): the calls a +# tool tracker reads, drawn by the app as rows — a verb per op, and how a run +# of them folds into a group's line (``many`` holds ``{count}``). +TRACKER_CARD_TEXTS: dict[str, tuple[int, str | None, str]] = { + "create": (40, None, "Added"), + "update": (40, None, "Updated"), + "snapshot": (40, None, "Updated the list"), + "many": (60, "{count}", "{count} list updates"), +} +_TRACKER_CARDS_MAX = 4 _CARD_MAX = 6 _CARD_SLOT_RE = re.compile(r"\{([a-zA-Z0-9.]+)(?:\|([a-z0-9]+))?\}") _CARD_WHEN_RE = re.compile(r'^([a-zA-Z0-9.]+)(?:\s*(==|!=|>=|<=|>|<)\s*(-?\d+(?:\.\d+)?|"[^"]*"))?$') @@ -1356,10 +1387,28 @@ def _card_template(tpl: Any, where: str, max_len: int, errors: list[str]) -> str return tpl +def _texts(raw: dict, table: dict[str, tuple[int, str | None, str]], where: str, + out: dict[str, Any], errors: list[str]) -> bool: + """Fill ``out`` with every text of ``table`` (its default when ``raw`` + leaves it out) — what the app draws as it is. False on a bad one.""" + for k, (mx, slot, default) in table.items(): + v = raw.get(k, default) + if not isinstance(v, str) or not v.strip() or len(v) > mx: + errors.append(f"{where}.{k} must be 1–{mx} characters") + return False + if slot and slot not in v: + errors.append(f"{where}.{k} must hold {slot}") + return False + out[k] = v + return True + + def _card_list(raw: Any, where: str, errors: list[str]) -> dict[str, Any] | None: """A card bit's ``list``: ``{tracker, many?, noGroup?, open?, closed?, - opened?, openedUnknown?, closedAt?, lifespan?}`` — every text filled (its - default when unset), so the app draws it as it is.""" + opened?, openedUnknown?, closedAt?, lifespan?}`` — or, with ``style: + "checklist"``, ``{tracker, style, title?, progress?, added?, started?, + done?, cancelled?, took?}``. Every text filled (its default when unset), + so the app draws it as it is.""" if not isinstance(raw, dict): errors.append(f"{where}.list must be an object") return None @@ -1367,20 +1416,84 @@ def _card_list(raw: Any, where: str, errors: list[str]) -> dict[str, Any] | None if not _KEY_RE.match(tid): errors.append(f"{where}.list.tracker must name one of the plugin's trackers") return None - unknown = set(raw) - {"tracker", *CARD_LIST_TEXTS} + style = raw.get("style", "timeline") + if style not in CARD_LIST_STYLES: + errors.append(f"{where}.list.style must be one of {', '.join(CARD_LIST_STYLES)}") + return None + table = CARD_CHECKLIST_TEXTS if style == "checklist" else CARD_LIST_TEXTS + unknown = set(raw) - {"tracker", "style", *table} if unknown: errors.append(f"{where}.list: unknown key(s) {', '.join(sorted(unknown))}") return None out: dict[str, Any] = {"tracker": tid} - for k, (mx, slot, default) in CARD_LIST_TEXTS.items(): - v = raw.get(k, default) - if not isinstance(v, str) or not v.strip() or len(v) > mx: - errors.append(f"{where}.list.{k} must be 1–{mx} characters") + if style == "checklist": # only when set: an older bit keeps its shape + out["style"] = style + return out if _texts(raw, table, f"{where}.list", out, errors) else None + + +def _panels(raw: Any, errors: list[str]) -> list[dict[str, Any]]: + """``ui.panels[]``: ``{id, tracker, title?, show?, vis?}`` — a tool + tracker's checklist floating over the conversation's thread, drawn by the + app (docs/plugins.md → "Checklists").""" + if raw is None: + return [] + if not isinstance(raw, list): + errors.append("ui.panels must be a list") + return [] + out: list[dict[str, Any]] = [] + ids: set[str] = set() + for i, pn in enumerate(raw[:_PANELS_MAX]): + where = f"ui.panels[{i}]" + if not isinstance(pn, dict): + errors.append(f"{where} must be an object") + continue + pid_ = str(pn.get("id") or "").strip() + tid = str(pn.get("tracker") or "").strip() + if not _KEY_RE.match(pid_) or pid_ in ids or not _KEY_RE.match(tid): + errors.append(f"{where} needs an id (unique) and the tracker it lists") + continue + unknown = set(pn) - {"id", "tracker", "vis", *PANEL_TEXTS} + if unknown: + errors.append(f"{where}: unknown key(s) {', '.join(sorted(unknown))}") + continue + ids.add(pid_) + po: dict[str, Any] = {"id": pid_, "tracker": tid} + if not _texts(pn, PANEL_TEXTS, where, po, errors): + continue + vis = _ui_vis(pn.get("vis"), where, errors) + if vis: + po["vis"] = vis + out.append(po) + if len(raw) > _PANELS_MAX: + errors.append(f"ui.panels: at most {_PANELS_MAX}") + return out + + +def _tracker_card(tc: dict, where: str, errors: list[str]) -> dict[str, Any] | None: + """A ``ui.toolCards[]`` entry that names a ``tracker`` instead of a + document: ``{id, tracker, icon?, create?, update?, snapshot?, many?, + vis?}`` — the calls that tracker reads, drawn by the app.""" + tid = str(tc.get("tracker") or "").strip() + if not _KEY_RE.match(tid): + errors.append(f"{where}.tracker must name one of the plugin's trackers") + return None + unknown = set(tc) - {"id", "tracker", "icon", "vis", *TRACKER_CARD_TEXTS} + if unknown: + errors.append(f"{where}: a tool card drawn from a tracker takes no " + f"{', '.join(sorted(unknown))}") + return None + out: dict[str, Any] = {"id": str(tc["id"]).strip(), "tracker": tid} + icon = tc.get("icon") + if icon is not None: + if icon not in CARD_ICONS: + errors.append(f"{where}.icon must be one of {', '.join(sorted(CARD_ICONS))}") return None - if slot and slot not in v: - errors.append(f"{where}.list.{k} must hold {slot}") - return None - out[k] = v + out["icon"] = icon + if not _texts(tc, TRACKER_CARD_TEXTS, where, out, errors): + return None + vis = _ui_vis(tc.get("vis"), where, errors) + if vis: + out["vis"] = vis return out @@ -1967,6 +2080,19 @@ def validate_manifest(plugin_dir: pathlib.Path) -> dict[str, Any]: if not _KEY_RE.match(tcid): errors.append(f"ui.toolCards[{i}].id invalid") continue + if tc.get("tracker") is not None: + # Drawn by the app from one of the plugin's tool trackers + # (no document): kept apart from the frames' cards. + trc = _tracker_card(tc, f"ui.toolCards[{i}]", errors) + if trc: + cards_ = ui_out.setdefault("trackerCards", []) + if len(cards_) >= _TRACKER_CARDS_MAX \ + or any(c["tracker"] == trc["tracker"] for c in cards_): + errors.append(f"ui.toolCards[{i}]: one card per tracker, " + f"at most {_TRACKER_CARDS_MAX}") + else: + cards_.append(trc) + continue match = tc.get("match") or {} if not isinstance(match, dict) or not match.get("tool"): errors.append(f"ui.toolCards[{i}].match.tool required") @@ -2178,6 +2304,9 @@ def validate_manifest(plugin_dir: pathlib.Path) -> dict[str, Any]: card = _card(ui_raw.get("card"), errors) if card: # only when set: ``ui`` is in the approval fingerprint ui_out["card"] = card + panels = _panels(ui_raw.get("panels"), errors) + if panels: # only when set, like the rest + ui_out["panels"] = panels out["ui"] = ui_out # ── requires / exports / emits (plugin-to-plugin dependencies) ─────────── @@ -2453,9 +2582,21 @@ def validate_manifest(plugin_dir: pathlib.Path) -> dict[str, Any]: trk = plugin_trackers.parse(raw.get("trackers"), errors) if trk: out["trackers"] = trk + by_tracker = {t["id"]: t for t in trk} for b in (out.get("ui") or {}).get("card") or []: - if b.get("list") and b["list"]["tracker"] not in {t["id"] for t in trk}: + if not b.get("list"): + continue + tk = by_tracker.get(b["list"]["tracker"]) + if tk is None: errors.append(f"ui.card `{b['id']}`: list.tracker must name a declared tracker") + elif b["list"].get("style") == "checklist" and not tk.get("tool"): + errors.append(f"ui.card `{b['id']}`: a checklist lists a tool tracker (its items " + "have a status)") + # What the app draws from a tool tracker: its panel, its calls' rows. + for kind, key in (("ui.panels", "panels"), ("ui.toolCards", "trackerCards")): + for d in (out.get("ui") or {}).get(key) or []: + if not (by_tracker.get(d["tracker"]) or {}).get("tool"): + errors.append(f"{kind} `{d['id']}`: tracker must name a declared tool tracker") # ── provides (data the host merges into its own answers) ───────────────── prov_raw = raw.get("provides") or {} @@ -2466,8 +2607,11 @@ def validate_manifest(plugin_dir: pathlib.Path) -> dict[str, Any]: for name, act in prov_raw.items(): if name in plugin_trackers.ROLES: # A role one of its trackers plays (no action runs for it). - if not isinstance(act, str) or act not in {t["id"] for t in trk}: + if not isinstance(act, str) or act not in by_tracker: errors.append(f"provides.{name}: must name a declared tracker") + elif (name in plugin_trackers.TOOL_ROLES) != bool(by_tracker[act].get("tool")): + errors.append(f"provides.{name}: must name a " + f"{'tool' if name in plugin_trackers.TOOL_ROLES else 'command'} tracker") else: prov_out[name] = act elif name not in _PROVIDES: @@ -2806,6 +2950,11 @@ def capability_summary(manifest: dict[str, Any]) -> list[dict[str, Any]]: items.append({"kind": "ui", "label": f"Draws ```{fe['lang']} blocks in agents' messages (sandboxed)"}) for b in ui.get("card") or []: items.append({"kind": "ui", "label": f"Adds `{b['id']}` to the conversation cards ({b['place']})"}) + for pn in ui.get("panels") or []: + items.append({"kind": "ui", "label": f"Floats the `{pn['title']}` checklist over a conversation's thread"}) + for tc in ui.get("trackerCards") or []: + items.append({"kind": "ui", "label": f"Draws the calls of its `{tc['tracker']}` list in the thread" + + (" (or leaves them out)" if tc.get("vis") else "")}) for fp in ui.get("filePreviews") or []: exts = ", ".join("." + t for t in fp["fileTypes"][:6]) + ("…" if len(fp["fileTypes"]) > 6 else "") items.append({"kind": "ui", "label": f"Previews {exts} files agents' messages name (sandboxed)"}) diff --git a/backend/plugins/routes.py b/backend/plugins/routes.py index a0a0fe50..53174c9e 100644 --- a/backend/plugins/routes.py +++ b/backend/plugins/routes.py @@ -131,6 +131,8 @@ def _ui_descriptors(deps: State, caller: CallerDep, installed: list[dict[str, An fences: list[dict[str, Any]] = [] file_previews: list[dict[str, Any]] = [] card: list[dict[str, Any]] = [] + panels: list[dict[str, Any]] = [] + tracker_cards: list[dict[str, Any]] = [] prefs: dict[str, list[dict[str, Any]]] = {} for p in active_recs: mf = p.get("manifest") or {} @@ -184,6 +186,17 @@ def _ui_descriptors(deps: State, caller: CallerDep, installed: list[dict[str, An if t["id"] == b["list"]["tracker"]), None) b["list"] = {**b["list"], "group": (tk or {}).get("group")} card.append(b) + # What the app draws from a tool tracker (declarative too): its + # checklist panel over the thread, and its calls' rows — each with + # what tells the tracker's calls apart (its tool, its ops). + by_tracker = {t["id"]: t for t in mf.get("trackers") or ()} + for pn in ui.get("panels") or []: + panels.append({**pn, "pluginId": pid, "pluginName": p["name"]}) + for tc in ui.get("trackerCards") or []: + tk = by_tracker.get(tc["tracker"]) or {} + if tk.get("tool"): + tracker_cards.append({**tc, "tool": tk["tool"], "ops": tk.get("ops") or [], + "pluginId": pid, "pluginName": p["name"]}) if ui.get("prefs"): prefs[pid] = plugin_agents.enrich_ui_prefs( deps, pid, mf, @@ -209,6 +222,7 @@ def _ui_descriptors(deps: State, caller: CallerDep, installed: list[dict[str, An providers[k] = {"pluginId": p["id"], "action": act} return {"pages": pages, "toolCards": tool_cards, "slots": slots, "overlays": overlays, "menuItems": menu_items, "fences": fences, "filePreviews": file_previews, "card": card, + "panels": panels, "trackerCards": tracker_cards, "prefs": prefs, "resources": resources, "provides": provides, "providers": providers} diff --git a/backend/plugins/trackers.py b/backend/plugins/trackers.py index 3df88b48..6411726c 100644 --- a/backend/plugins/trackers.py +++ b/backend/plugins/trackers.py @@ -36,6 +36,29 @@ invalidates exactly its own entries, and the indexer's re-derive pass hold a changed tracker's ``hint`` — once per rule change (the store's ``trackers_sigs`` meta row), never on a plain boot. +**Tool trackers.** A tracker may read a **tool's calls** instead of shell +commands — ``tool`` (a neutral tool name, ``conversations/parse/readers/ +toolnames.py``) and ``ops``, told apart by the call's input like the parser's +old ``todo_op``:: + + {"id": "tasks", "label": "Tasks", "tool": "todo", + "ops": [{"do": "snapshot", "items": "todos", # the whole list again + "name": ["content", "activeForm"], "status": "status"}, + {"do": "update", "id": ["taskId", "task_id"], # one item, by its id + "name": "subject", "status": "status"}, + {"do": "create", "name": ["subject", "content"]}], # a new item + "statuses": {"deleted": "cancelled"}} # the tool's words → ours + +The first op whose input is there fires (``snapshot``: ``items`` is a list; +``update``: ``id`` is set; ``create``: ``name`` is set). A created item's key +is its 1-based ordinal — the id a sequential task tool's update cites; a +snapshot replaces the list, and an item whose name is unchanged keeps its +times. Such items carry a ``status`` (``pending`` / ``in_progress`` / +``completed`` / ``cancelled``) and three times: ``openedAt`` (added), +``startedAt`` (first in progress), ``closedAt`` (completed or cancelled; gone +again if it reopens). They keep the list's own order, and nothing stamps +them from outside. The ``tasks`` plugin's task list is the first one. + Events can also be **stamped from outside** (``stamp`` — the ``trackers.stamp`` bridge below, and the ``worktree`` key of ``POST /api/conversation-meta`` for the tracker that provides ``git.worktrees``): @@ -45,6 +68,9 @@ they live in ``meta.trackers[]`` and merge with the parse's. tracker whose items are a conversation's git worktrees; :func:`provided` hands them to the diff engines, the storage owners, the scaffold and the CLI as ``{name, dir, project, createdAt, removedAt}`` — ``[]`` with no provider. +``provides: {"tasks.list": ""}`` names the (tool) tracker whose +items are a conversation's task list: ``{id, subject, status, createdAt, +startedAt, endedAt}`` for the completion scaffold. """ from __future__ import annotations @@ -57,7 +83,9 @@ import threading from typing import Any # ``provides`` keys that name one of the plugin's trackers (not an action). -ROLES = frozenset({"git.worktrees"}) +ROLES = frozenset({"git.worktrees", "tasks.list"}) +# A role only a tool tracker can play (its items carry a status). +TOOL_ROLES = frozenset({"tasks.list"}) CAP = "trackers.stamp" MAX_TRACKERS = 4 # per plugin @@ -68,12 +96,25 @@ MAX_ITEMS = 60 # per conversation and tracker MAX_FIELD = 120 # a key / name / group DEFAULT_VALID = r"^[A-Za-z0-9][\w./-]*$" GROUP_KINDS = ("project",) +# Tool trackers (``tool`` + ``ops``). +STATUSES = ("pending", "in_progress", "completed", "cancelled") +OP_KINDS = ("snapshot", "update", "create") +MAX_OPS = 6 +MAX_PATHS = 4 # alternatives of one input field +MAX_STATUSES = 24 +MAX_TOOL_ITEMS = 200 # per conversation and tool tracker +MAX_NAME = 200 # a tool tracker's item name (one line) _VAR_RE = re.compile(r"^[a-z][a-zA-Z0-9]{0,23}$") # Plain ASCII a JSON string never escapes: the indexer looks for it in a # transcript's raw bytes. _HINT_RE = re.compile(r"^[A-Za-z0-9._/:=@-][A-Za-z0-9 ._/:=@-]{2,38}[A-Za-z0-9._/:=@-]$") _FLAG_RE = re.compile(r"^-{1,2}[A-Za-z0-9][\w-]{0,31}$") +# A neutral tool name (`todo`), a harness's own (`claude:CronCreate`) or an MCP one. +_TOOL_RE = re.compile(r"^[A-Za-z][\w.-]{0,79}(?::[\w.-]{1,80})?$") +# An input field, dotted for a nested one (`task.id`). +_PATH_RE = re.compile(r"^[A-Za-z_][\w-]{0,39}(?:\.[A-Za-z_][\w-]{0,39}){0,3}$") +_TOOL_KEYS = frozenset({"id", "label", "tool", "ops", "statuses"}) _TPL_VAR_RE = re.compile(r"\{([^{}]+)\}") _FILTERS = ("upper", "lower", "nodot", "title", "basename") # Command position: the start of a line, after a shell separator, or after a @@ -105,6 +146,79 @@ def _template(tpl: Any, where: str, names: set[str], errors: list[str], return tpl +def _paths(raw: Any, where: str, errors: list[str], required: bool = False) -> list[str] | None: + """An input field of a tool tracker's op: one path or up to + ``MAX_PATHS`` alternatives (the first that is set wins) — as a list.""" + if raw is None: + if required: + errors.append(f"{where} is required") + return None + paths = [raw] if isinstance(raw, str) else raw + if not isinstance(paths, list) or not 1 <= len(paths) <= MAX_PATHS \ + or any(not isinstance(p, str) or not _PATH_RE.match(p) for p in paths): + errors.append(f"{where} must be an input field (or up to {MAX_PATHS} alternatives), " + "dotted for a nested one") + return None + return list(paths) + + +def _parse_tool(t: dict, lb: str, o: dict[str, Any], errors: list[str]) -> bool: + """The ``tool`` / ``ops`` / ``statuses`` of a tool tracker into ``o``.""" + extra = set(t) - _TOOL_KEYS + if extra: + errors.append(f"{lb}: a tool tracker takes id, label, tool, ops and statuses " + f"(not {', '.join(sorted(extra))})") + return False + tool = t.get("tool") + if not isinstance(tool, str) or not _TOOL_RE.match(tool): + errors.append(f"{lb}.tool must be a tool's neutral name (todo, claude:CronCreate, mcp__…)") + return False + ops = t.get("ops") + if not isinstance(ops, list) or not 1 <= len(ops) <= MAX_OPS: + errors.append(f"{lb}.ops must be a list of 1–{MAX_OPS} ops") + return False + out_ops: list[dict[str, Any]] = [] + for j, op in enumerate(ops): + ol = f"{lb}.ops[{j}]" + if not isinstance(op, dict) or op.get("do") not in OP_KINDS: + errors.append(f"{ol}.do must be one of {', '.join(OP_KINDS)}") + return False + do = op["do"] + allowed = {"snapshot": {"do", "items", "name", "status"}, + "update": {"do", "id", "name", "status"}, + "create": {"do", "name", "status"}}[do] + if set(op) - allowed: + errors.append(f"{ol}: a {do} op takes {', '.join(sorted(allowed - {'do'}))}") + return False + oo: dict[str, Any] = {"do": do} + need = {"snapshot": ("items", "name"), "update": ("id",), "create": ("name",)}[do] + bad = False + for k in ("items", "id", "name", "status"): + if k not in allowed: + continue + v = _paths(op.get(k), f"{ol}.{k}", errors, required=k in need) + if v is None: + bad = bad or k in need or op.get(k) is not None + else: + oo[k] = v + if bad: + return False + out_ops.append(oo) + o["tool"] = tool + o["ops"] = out_ops + st = t.get("statuses") + if st is not None: + if not isinstance(st, dict) or len(st) > MAX_STATUSES or any( + not isinstance(k, str) or not 1 <= len(k.strip()) <= 40 or v not in STATUSES + for k, v in st.items()): + errors.append(f"{lb}.statuses must map the tool's own words (at most {MAX_STATUSES}) " + f"to {', '.join(STATUSES)}") + return False + if st: + o["statuses"] = {k.strip().lower(): v for k, v in st.items()} + return True + + def parse(raw: Any, errors: list[str]) -> list[dict[str, Any]]: """Validate ``trackers[]``; the normalized list (only set keys).""" if raw is None: @@ -129,6 +243,15 @@ def parse(raw: Any, errors: list[str]) -> list[dict[str, Any]]: if not 1 <= len(label) <= 40: errors.append(f"{lb}.label must be 1–40 characters") continue + if t.get("tool") is not None: + # A tool tracker: a tool's calls, not shell commands. + if t.get("command") is not None: + errors.append(f"{lb}: one of command (shell commands) or tool (a tool's calls)") + continue + to: dict[str, Any] = {"id": tid, "label": label} + if _parse_tool(t, lb, to, errors): + out.append(to) + continue hint = t.get("hint") if not isinstance(hint, str) or not _HINT_RE.match(hint): errors.append(f"{lb}.hint must be a literal of 4–40 characters (letters, digits, " @@ -244,12 +367,14 @@ def fingerprint_sig(manifest: dict) -> list | None: """What of ``trackers[]`` enters the approval fingerprint: which commands it reads (None when the plugin declares none).""" ts = manifest.get("trackers") or [] - return [(t["id"], t["command"]) for t in ts] or None + return [(t["id"], t["command"] if "command" in t else f"tool:{t['tool']}") for t in ts] or None def consent_items(manifest: dict) -> list[dict]: return [{"kind": "tracker", - "label": f"Tracks `{t['label']}` your conversations open and close, read off their shell commands"} + "label": (f"Keeps the `{t['label']}` list of your conversations, read off their " + f"`{t['tool']}` tool calls") if t.get("tool") else + f"Tracks `{t['label']}` your conversations open and close, read off their shell commands"} for t in manifest.get("trackers") or []] @@ -267,7 +392,24 @@ class Tracker: self.id = item["id"] self.key = f"{pid}:{item['id']}" self.label = item.get("label") or item["id"] + self.sig = hashlib.sha256( + json.dumps(item, sort_keys=True).encode()).hexdigest()[:12] + self.group = item.get("group") + # A tool tracker reads a tool's calls (``fold_call``), not commands. + self.tool: str | None = item.get("tool") + if self.tool: + from conversations.parse.readers.toolnames import byte_hints + self.hint = None + # What a transcript's bytes hold when it calls the tool. + self.hints: tuple[str, ...] = byte_hints(self.tool) + # A path is a list of alternatives (a bare string: one). + self.ops = [{k: ([v] if isinstance(v, str) and k != "do" else v) + for k, v in op.items()} for op in item["ops"]] + self.statuses = {s: s for s in STATUSES} | dict(item.get("statuses") or {}) + self.rules = [] + return self.hint = item["hint"] + self.hints = (self.hint,) self.rx = re.compile(_ANCHOR + f"(?:{item['command']})" + _TAIL) fl = item.get("flags") or {} self.noop = frozenset(fl.get("noop") or ()) @@ -276,9 +418,6 @@ class Tracker: self.defaults = dict(item.get("defaults") or {}) self.valid = re.compile(item.get("valid") or DEFAULT_VALID) self.rules = list(item.get("events") or ()) - self.group = item.get("group") - self.sig = hashlib.sha256( - json.dumps(item, sort_keys=True).encode()).hexdigest()[:12] def _ok(self, v: str | None) -> bool: return bool(v) and len(v) <= MAX_FIELD and bool(self.valid.match(v)) @@ -287,7 +426,7 @@ class Tracker: """The open / close events in a shell command: ``[{"do", "key", "name"?, "group"?}]``.""" out: list[dict] = [] - if not isinstance(text, str) or self.hint not in text: + if self.tool or not isinstance(text, str) or self.hint not in text: return out for m in self.rx.finditer(text): toks = m.group(1).split() @@ -337,6 +476,121 @@ class Tracker: return out + # ── a tool tracker's fold ─────────────────────────────────────────────── + def op_of(self, inp: dict) -> dict | None: + """The op a call's input makes — the first whose input is there: + a snapshot's ``items`` is a list, an update's ``id`` is set, a + create's ``name`` is set. None: the call changes nothing (a read).""" + for op in self.ops: + do = op["do"] + if do == "snapshot": + if isinstance(_field(inp, op["items"], any_type=True), list): + return op + elif _field(inp, op["id" if do == "update" else "name"]) is not None: + return op + return None + + def _status(self, src: dict, op: dict) -> str | None: + raw = _field(src, op.get("status") or ()) + return self.statuses.get(str(raw).strip().lower()) if raw is not None else None + + def fold_call(self, items: dict[str, dict], inp, ts: str | None) -> None: + """Fold one call of the tool at ``ts`` into ``items`` (key → item, in + list order), in place.""" + if not isinstance(inp, dict): + return + op = self.op_of(inp) + if op is None: + return + do = op["do"] + if do == "create": + if len(items) >= MAX_TOOL_ITEMS: + return + # Its key is its 1-based ordinal: the id an update cites. + key = str(len(items) + 1) + items[key] = _stamp_times( + _tool_item(key, _field(inp, op["name"]), self._status(inp, op) or "pending"), + None, ts) + elif do == "update": + ref = _field(inp, op["id"]) + if isinstance(ref, float) and ref.is_integer(): + ref = int(ref) + cur = items.get(str(ref).strip()) + if cur is None: + return + st = self._status(inp, op) + if st: + was = dict(cur) + cur["status"] = st + _stamp_times(cur, was, ts) + name = _field(inp, op.get("name") or ()) + if name is not None: + cur["name"] = _one_line(name) or cur["name"] + else: + # The whole list again: an item is the one it was when its name + # is (its times carry over). + prev: dict[str, dict] = {} + for old in items.values(): + prev.setdefault(old["name"], old) + items.clear() + for row in _field(inp, op["items"], any_type=True): + if not isinstance(row, dict) or len(items) >= MAX_TOOL_ITEMS: + continue + key = str(len(items) + 1) + it = _tool_item(key, _field(row, op["name"]), self._status(row, op) or "pending") + items[key] = _stamp_times(it, prev.pop(it["name"], None), ts) + + +def _field(src, paths, any_type: bool = False): + """The first of ``paths`` (dotted input fields) that is set in ``src`` — + None when none is (an empty string counts as unset).""" + for path in paths: + cur = src + for part in path.split("."): + cur = cur.get(part) if isinstance(cur, dict) else None + if cur is None: + break + if cur is None or cur == "": + continue + if any_type or isinstance(cur, (str, int, float)) and not isinstance(cur, bool): + return cur + return None + + +def _one_line(v) -> str: + return " ".join(str(v if v is not None else "").split())[:MAX_NAME] + + +def _tool_item(key: str, name, status: str) -> dict: + return {"key": key, "name": _one_line(name) or key, "group": None, "status": status, + "openedAt": None, "startedAt": None, "closedAt": None} + + +def _stamp_times(it: dict, before: dict | None, ts: str | None) -> dict: + """Stamp ``it`` (its status just set) with its times: ``openedAt`` (when + it was first listed), ``startedAt`` (the first time it was in progress) + and ``closedAt`` (completed or cancelled; gone again if it reopens). + ``before`` is the same item as it was until this call (a copy taken + before an update, the earlier snapshot's row): its times carry over. A + call with no timestamp stamps nothing. Returns ``it``.""" + before = before or {} + for k in ("openedAt", "startedAt", "closedAt"): + if before.get(k) and not it.get(k): + it[k] = before[k] + if ts: + st = it.get("status") + if not it.get("openedAt"): + it["openedAt"] = ts + if st == "in_progress" and not it.get("startedAt"): + it["startedAt"] = ts + if st in ("completed", "cancelled"): + if before.get("status") != st or not it.get("closedAt"): + it["closedAt"] = ts + else: + it["closedAt"] = None + return it + + class Registry: """The owner's active trackers. Immutable; ``version`` moves when what it is built from does (the cards' memo keys on it).""" @@ -378,7 +632,8 @@ def build(entries: list[tuple[str, list[dict], dict]], *, version: int = 1) -> R trackers.append(t) mine[t.id] = t for role, tid in (provides or {}).items(): - if role in ROLES and tid in mine and role not in roles: + if role in ROLES and tid in mine and role not in roles \ + and (role in TOOL_ROLES) == bool(mine[tid].tool): roles[role] = mine[tid].key sig = hashlib.sha256(json.dumps( [sorted((t.key, t.sig) for t in trackers), sorted(roles.items())]).encode()).hexdigest()[:12] \ @@ -462,21 +717,31 @@ def apply(items: dict[str, dict], ev: dict, ts: str | None) -> None: class Fold: - """A transcript's tracker items as its shell commands go by — one per - ``ParserState``, on the rules of the moment it was made.""" + """A transcript's tracker items as its shell commands and tool calls go + by — one per ``ParserState``, on the rules of the moment it was made.""" def __init__(self, reg: Registry | None = None): self.reg = reg if reg is not None else current() self.sig = self.reg.sig self._items: dict[str, dict[str, dict]] = {t.key: {} for t in self.reg.trackers} + self._commands = [t for t in self.reg.trackers if not t.tool] + self._tools: dict[str, list[Tracker]] = {} + for t in self.reg.trackers: + if t.tool: + self._tools.setdefault(t.tool, []).append(t) def feed(self, command, ts: str | None) -> None: - if not self.reg.trackers or not isinstance(command, str): + if not self._commands or not isinstance(command, str): return - for t in self.reg.trackers: + for t in self._commands: for ev in t.events(command): apply(self._items[t.key], ev, ts) + def feed_tool(self, tool, inp, ts: str | None) -> None: + """One tool call (its neutral name and input) — the tool trackers'.""" + for t in self._tools.get(tool) or (): + t.fold_call(self._items[t.key], inp, ts) + def summary(self) -> dict[str, dict]: """``{key: {"sig", "items"}}`` — an entry for every active tracker, an empty one included: it says "read with these rules, found nothing".""" @@ -535,9 +800,18 @@ def items_for(t: Tracker, summary: dict | None, meta: dict | None, summary, meta = summary or {}, meta or {} ent = (summary.get("trackersAuto") or {}).get(t.key) or {} auto = ent.get("items") if ent.get("sig") == t.sig else None + reg = reg if reg is not None else current() + if t.tool: + # A tool tracker's list is its transcript's, in the list's own order: + # nothing merges into it. Until a summary is re-read with its rules, + # what the core kept before it (a provider role's carry-over). + if auto is None: + from plugins import carryover_trackers + auto = [i for role, key in reg.roles.items() if key == t.key + for i in carryover_trackers.items(role, summary, meta)] + return [dict(i) for i in auto if isinstance(i, dict) and i.get("key")] stamped = (meta.get("trackers") or {}).get(t.key) legacy: list = [] - reg = reg if reg is not None else current() for role, key in reg.roles.items(): if key == t.key: from plugins import carryover_trackers @@ -565,12 +839,13 @@ def provided(role: str, summary: dict | None, meta: dict | None, deps=None) -> list[dict]: """A provider role's records on a conversation, in the shape its readers always had — ``git.worktrees``: ``{name, dir, project, createdAt, - removedAt}``. ``[]`` with no active provider.""" + removedAt}``; ``tasks.list``: ``{id, subject, status, createdAt, + startedAt, endedAt}``. ``[]`` with no active provider.""" reg = registry(deps) if deps is not None else current() t = reg.provider(role) if t is None: return [] - return _records(items_for(t, summary, meta, reg)) + return _records(items_for(t, summary, meta, reg), role) # ── stamping from outside ─────────────────────────────────────────────────── @@ -591,8 +866,10 @@ def clean_event(ev: Any) -> dict | None: def stamp(deps, sid: str, key: str, ev: dict) -> dict | None: """Fold a cleaned event into ``meta.trackers[key]`` of ``sid`` and tell - the app; the conversation's metadata, or None for an unknown tracker.""" - if key not in registry(deps).by_key: + the app; the conversation's metadata, or None for an unknown tracker (a + tool tracker too: its list is its transcript's).""" + t = registry(deps).by_key.get(key) + if t is None or t.tool: return None if ev.get("do") == "close" and not ev.get("at"): import time @@ -610,7 +887,12 @@ def fold_stamped(items: list[dict], ev: dict) -> list[dict]: return list(by.values()) -def _records(items: list[dict]) -> list[dict]: +def _records(items: list[dict], role: str = "git.worktrees") -> list[dict]: + if role == "tasks.list": + return [{"id": it["key"], "subject": it["name"], "status": it.get("status") or "pending", + "createdAt": it.get("openedAt"), "startedAt": it.get("startedAt"), + "endedAt": it.get("closedAt")} + for it in items] return [{"name": it["name"], "dir": it["key"], "project": it.get("group"), "createdAt": it.get("openedAt"), "removedAt": it.get("closedAt")} for it in items] @@ -671,7 +953,7 @@ def sessions(deps, role: str) -> dict[str, list[dict]]: seen.add(sid) items = ((c.get("meta") or {}).get("trackers") or {}).get(t.key) if items: - out[sid] = _records(items) + out[sid] = _records(items, role) from plugins import carryover_trackers for sid, m in deps.meta_store.items(): if sid in seen or not ((m.get("trackers") or {}).get(t.key) @@ -679,5 +961,5 @@ def sessions(deps, role: str) -> dict[str, list[dict]]: continue items = items_for(t, None, m, reg) if items: - out[sid] = _records(items) + out[sid] = _records(items, role) return out diff --git a/backend/schemas/__init__.py b/backend/schemas/__init__.py index 2f2d664e..379d4da7 100644 --- a/backend/schemas/__init__.py +++ b/backend/schemas/__init__.py @@ -138,7 +138,6 @@ from .conversations import ( SubagentsResponse, RunningAgent, ParentConvRef, - Task, ConversationSummary, ThreadItem, TurnAuthor, @@ -332,7 +331,6 @@ __all__ = [ "SubagentsResponse", "RunningAgent", "ParentConvRef", - "Task", "ConversationSummary", "ThreadItem", "FullText", diff --git a/backend/schemas/conversations.py b/backend/schemas/conversations.py index 22963633..80b250ba 100644 --- a/backend/schemas/conversations.py +++ b/backend/schemas/conversations.py @@ -29,7 +29,6 @@ __all__ = [ "StoppedOn", "HeldTurn", "ParentConvRef", - "Task", "ConversationSummary", "TaskEvent", "TaskRef", @@ -79,14 +78,19 @@ class ConvNotification(Schema): class TrackedItem(Schema): """One thing a conversation opened (and maybe closed), read by a plugin's tracker rules (plugins/trackers.py) — a git worktree, for the worktrees - plugin.""" + plugin; one task of its list, for the tasks plugin (a tool tracker's item: + it has a ``status``, and its list keeps the plan's order).""" key: str # what an open and its close share name: str # What it belongs to — a project slug for a tracker whose groups are # projects; None when unknown. group: Optional[str] = None - openedAt: Optional[str] = None - closedAt: Optional[str] = None + openedAt: Optional[str] = None # a tool tracker's item: when it was added + closedAt: Optional[str] = None # …completed or cancelled + # A tool tracker's item only: pending / in_progress / completed / + # cancelled, and when it was first in progress. + status: Optional[str] = None + startedAt: Optional[str] = None class ForkedFrom(Schema): @@ -652,15 +656,6 @@ class SpawnedConvRef(Schema): report: Optional[str] = None -class Task(Schema): - """One task from the conversation's task list (TaskCreate/TaskUpdate, or the - older TodoWrite). ``status`` is one of pending / in_progress / completed / - cancelled.""" - id: str - subject: str - status: str - - class EffortUsage(Schema): """One model's share at one `--effort` level ("none" = unstamped turns).""" turns: int @@ -802,7 +797,6 @@ class ConversationSummary(Schema): # (~4 chars/token) and the remainder is attributed to context. firstContextTokens: Optional[int] = None firstMessageTokens: Optional[int] = None - tasks: Optional[list[Task]] = None # What the conversation *used*, busiest first — the tool-side counterpart of # `meta.projects`/`meta.services`, and what the tag registry derives its # `skill:`/`agent:` tags from. Skills are the `Skill(...)` calls mined from diff --git a/backend/test_agy_tasks.py b/backend/test_agy_tasks.py index 73ceaddd..2f441ca1 100644 --- a/backend/test_agy_tasks.py +++ b/backend/test_agy_tasks.py @@ -9,6 +9,7 @@ Claude Code's are (docs/transcript-format.md → "Tool names", ``data.taskId``): import json import conversations as c +from fixtures.tracker_plugins import kit CONV = "37914220-cbc8-4f69-a195-dc95483599fb" TASK = f"{CONV}/task-4" @@ -48,7 +49,9 @@ def _parse(tmp_path, evs, full=True): p = tmp_path / f"{CONV}.jsonl" end = [_ev("turn_end", "2026-12-01T11:00:00Z", reason="done")] p.write_text("".join(json.dumps(e) + "\n" for e in HEAD + evs + end)) - st = c.ParserState(p, full=full) + # the task list is the tasks plugin's tool tracker (plugins/trackers.py) + with kit.bound(kit.tasks_store()): + st = c.ParserState(p, full=full) for line in p.read_text().splitlines(): st.feed(json.loads(line)) return st @@ -175,8 +178,8 @@ def test_an_older_mirrors_update_steps_fills_the_task_list(tmp_path): *_call(2, "agy:update_steps", {"steps": STEPS}, native="update_steps", at="2026-12-01T10:03:00Z"), ], full=full) - tasks = st.summary()["tasks"] - assert [(t["subject"], t["status"]) for t in tasks] == [ + tasks = kit.task_list(st.summary()) + assert [(t["name"], t["status"]) for t in tasks] == [ ("Create worktrees", "completed"), ("Implement backend", "in_progress"), ("Run tests", "pending"), ("Old idea", "cancelled"), ("Other idea", "cancelled"), ("Odd one", "pending")] @@ -191,6 +194,6 @@ def test_the_new_mirrors_todo_shape_reads_the_same(tmp_path): todos = [{"content": "A", "activeForm": "A", "status": "completed"}, {"content": "B", "activeForm": "B", "status": "in_progress"}] st = _parse(tmp_path, [*_call(1, "todo", {"todos": todos}, native="update_steps")]) - assert [(t["subject"], t["status"]) for t in st.summary()["tasks"]] == [ + assert [(t["name"], t["status"]) for t in kit.task_list(st.summary())] == [ ("A", "completed"), ("B", "in_progress")] assert _card(st, 1)["native"] == "update_steps" diff --git a/backend/test_parse_fixtures.py b/backend/test_parse_fixtures.py index b8585cb3..e05c9c42 100644 --- a/backend/test_parse_fixtures.py +++ b/backend/test_parse_fixtures.py @@ -488,27 +488,6 @@ class ToolNames(unittest.TestCase): self.assertEqual([(it["name"], it.get("native")) for it in items], [("shell", "Bash"), ("mcp__x__y", None)]) - def test_todo_calls_told_apart_by_their_input(self): - from conversations.parse.tools import todo_op - self.assertEqual(todo_op({"todos": []}), "snapshot") - self.assertEqual(todo_op({"taskId": "2", "status": "completed"}), "update") - self.assertEqual(todo_op({"taskId": "2"}), "update") # TaskGet: changes nothing - self.assertEqual(todo_op({"subject": "x", "description": "y"}), "create") - self.assertEqual(todo_op({}), "list") - with tempfile.TemporaryDirectory() as d: - path = pathlib.Path(d) / "s.jsonl" - calls = [("TaskCreate", {"subject": "a", "description": "."}), - ("TaskCreate", {"subject": "b", "description": "."}), - ("TaskList", {}), ("TaskGet", {"taskId": "1"}), - ("TaskUpdate", {"taskId": "1", "status": "completed"})] - recs = [_user("go", s=1)] + [ - _assistant([{"type": "tool_use", "id": f"t{i}", "name": n, "input": inp}], - s=i + 2, mid=f"m{i}") for i, (n, inp) in enumerate(calls)] - path.write_text("\n".join(json.dumps(o) for o in recs) + "\n") - tasks = c.parse_conversation(path)["tasks"] - self.assertEqual([(t["subject"], t["status"]) for t in tasks], - [("a", "completed"), ("b", "pending")]) - class ReaderStateAcrossChunks(unittest.TestCase): """What a reader keeps between records survives ``feed_lines`` cut diff --git a/backend/test_trackers.py b/backend/test_trackers.py index 86ed172e..faf50f4a 100644 --- a/backend/test_trackers.py +++ b/backend/test_trackers.py @@ -227,6 +227,351 @@ class ProviderAndCarryOver(unittest.TestCase): self.assertIsNone(trackers.clean_event({"do": "open", "key": "x" * 500})) +# ── tool trackers (the reference ``tasks`` manifest) ──────────────────────── +TASKS = kit.TASKS +T = "2026-12-02T10:%02d:00Z" + + +def tasks_tracker(): + return kit.registry([kit.manifest("tasks")]).by_key[TASKS] + + +class ToolRules(unittest.TestCase): + """A tracker over a tool's calls: create / update by id / whole-list + snapshot, told apart by the input, with a status and three times.""" + + def fold(self, *calls, tool="todo"): + f = trackers.Fold(kit.registry([kit.manifest("tasks")])) + for i, inp in enumerate(calls): + f.feed_tool(tool, inp, T % i) + return f.summary()[TASKS]["items"] + + def test_the_op_is_told_by_the_input(self): + t = tasks_tracker() + op = lambda inp: (t.op_of(inp) or {}).get("do") # noqa: E731 + self.assertEqual(op({"todos": []}), "snapshot") + self.assertEqual(op({"taskId": "2", "status": "completed"}), "update") + self.assertEqual(op({"task_id": 2}), "update") # a lookup: changes nothing + self.assertEqual(op({"subject": "x", "description": "y"}), "create") + self.assertEqual(op({"content": "x"}), "create") + self.assertIsNone(op({})) # the list read back + self.assertIsNone(op({"todos": "nope"})) + + def test_create_appends_and_update_cites_the_ordinal(self): + items = self.fold({"subject": "a", "description": "."}, {"subject": " b\n two "}, + {}, {"taskId": "1"}, + {"taskId": "1", "status": "completed"}, + {"taskId": 2, "subject": "b2"}, {"taskId": "9", "status": "completed"}) + self.assertEqual([(i["key"], i["name"], i["status"]) for i in items], + [("1", "a", "completed"), ("2", "b2", "pending")]) + self.assertEqual(items[0], {"key": "1", "name": "a", "group": None, "status": "completed", + "openedAt": T % 0, "startedAt": None, "closedAt": T % 4}) + + def test_times_added_first_started_ended(self): + items = self.fold( + {"subject": "a"}, # 0 + {"subject": "b"}, # 1 + {"taskId": "1", "status": "in_progress"}, # 2 + {"taskId": "1", "status": "in_progress"}, # 3: still the first start + {"taskId": "1", "status": "completed"}, # 4 + {"taskId": "1", "status": "completed"}, # 5: still the first end + {"taskId": "2", "status": "completed"}, # 6 + {"taskId": "2", "status": "pending"}) # 7: reopened + self.assertEqual([(i["openedAt"], i["startedAt"], i["closedAt"]) for i in items], + [(T % 0, T % 2, T % 4), (T % 1, None, None)]) + + def test_a_snapshot_replaces_the_list_and_a_same_named_item_keeps_its_times(self): + snap = lambda *rows: {"todos": [{"content": n, "status": st, "activeForm": n} # noqa: E731 + for n, st in rows]} + items = self.fold( + snap(("a", "pending")), # 0 + snap(("a", "in_progress"), ("b", "pending")), # 1 + snap(("c", "pending"), ("a", "completed"), ("b", "cancelled")), # 2 + snap(("c", "pending"), ("a", "completed"), ("b", "cancelled"))) # 3: no change + # the list's own order (the plan's), never by opening time + self.assertEqual([(i["key"], i["name"], i["status"], i["openedAt"], i["startedAt"], i["closedAt"]) + for i in items], [ + ("1", "c", "pending", T % 2, None, None), + ("2", "a", "completed", T % 0, T % 1, T % 2), + ("3", "b", "cancelled", T % 1, None, T % 2)]) + # a row that isn't an object is skipped; an odd status reads pending + odd = self.fold({"todos": ["x", {"content": "", "activeForm": "doing", "status": "weird"}]}) + self.assertEqual([(i["name"], i["status"]) for i in odd], [("doing", "pending")]) + + def test_the_status_map_and_unknown_words(self): + items = self.fold({"subject": "a"}, {"subject": "b"}, + {"taskId": "1", "status": "deleted"}, # the manifest's own word + {"taskId": "2", "status": "Blocked"}) # unknown: nothing moves + self.assertEqual([i["status"] for i in items], ["cancelled", "pending"]) + self.assertEqual(items[0]["closedAt"], T % 2) + + def test_only_its_tool_and_no_timestamp_stamps_nothing(self): + self.assertEqual(self.fold({"subject": "a"}, tool="shell"), []) + f = trackers.Fold(kit.registry([kit.manifest("tasks")])) + f.feed_tool("todo", {"subject": "a"}, None) + f.feed_tool("todo", "not an object", None) + f.feed("new-worktree x", T % 0) # no command tracker: nothing + self.assertEqual(f.summary()[TASKS]["items"], [ + {"key": "1", "name": "a", "group": None, "status": "pending", + "openedAt": None, "startedAt": None, "closedAt": None}]) + + def test_bounded(self): + many = self.fold(*[{"subject": f"t{i}"} for i in range(trackers.MAX_TOOL_ITEMS + 20)]) + self.assertEqual(len(many), trackers.MAX_TOOL_ITEMS) + long = self.fold({"subject": "x" * 1000}) + self.assertEqual(len(long[0]["name"]), trackers.MAX_NAME) + snap = self.fold({"todos": [{"content": f"t{i}"} for i in range(trackers.MAX_TOOL_ITEMS + 20)]}) + self.assertEqual(len(snap), trackers.MAX_TOOL_ITEMS) + + def test_what_a_transcript_holds_when_it_calls_the_tool(self): + from conversations.parse.readers.toolnames import byte_hints + # the tool's names with their JSON quotes: a message that only talks + # about TaskCreate (escaped inside a string) isn't a call + self.assertEqual(set(tasks_tracker().hints), + {'"todo"', '"TodoWrite"', '"TaskCreate"', '"TaskUpdate"', '"TaskGet"', + '"TaskList"', ':update_steps"'}) + self.assertEqual(byte_hints("claude:CronCreate"), ('"CronCreate"', ':CronCreate"')) + self.assertEqual(byte_hints("mcp__linear__get_issue"), ('"mcp__linear__get_issue"',)) + self.assertEqual(byte_hints("shell"), ('"shell"', '"Bash"')) + self.assertEqual(tracker().hints, ("new-worktree",)) + for rec in ({"type": "tool_use", "name": "TaskCreate", "input": {}}, + {"t": "tool_call", "tool": "todo", "native": "update_steps"}, + {"t": "tool_call", "tool": "agy:update_steps", "input": {"steps": []}}): + for dump in (json.dumps(rec), json.dumps(rec, separators=(",", ":"))): + self.assertTrue(any(h in dump for h in tasks_tracker().hints), dump) + prose = json.dumps({"type": "user", "message": {"content": 'use TaskCreate or "TodoWrite" / "todo"'}}) + self.assertFalse(any(h in prose for h in tasks_tracker().hints)) + + +class ToolView(unittest.TestCase): + def deps(self): + return kit.deps_with(kit.tasks_store()) + + def summary(self, *calls): + f = trackers.Fold(trackers.registry(self.deps())) + for i, inp in enumerate(calls): + f.feed_tool("todo", inp, T % i) + return {"trackersAuto": f.summary()} + + def test_the_view_keeps_the_lists_order_and_takes_no_stamp(self): + s = self.summary({"todos": [{"content": "a", "status": "pending"}]}, + {"todos": [{"content": "z", "status": "pending"}, + {"content": "a", "status": "completed"}]}) + meta = {"trackers": {TASKS: [{"key": "9", "name": "stamped", "openedAt": T % 0}]}} + got = trackers.view(self.deps(), s, meta)[TASKS] + self.assertEqual([(i["key"], i["name"]) for i in got], [("1", "z"), ("2", "a")]) + got[0]["name"] = "mutated" # a copy: the summary is read-only + self.assertEqual(trackers.view(self.deps(), s, meta)[TASKS][0]["name"], "z") + + def test_provided_is_the_task_list_the_scaffold_reads(self): + s = self.summary({"subject": "a"}, {"taskId": "1", "status": "in_progress"}, + {"taskId": "1", "status": "completed"}) + self.assertEqual(trackers.provided("tasks.list", s, {}, self.deps()), [ + {"id": "1", "subject": "a", "status": "completed", + "createdAt": T % 0, "startedAt": T % 1, "endedAt": T % 2}]) + # no provider: no list + none = kit.deps_with(kit.FakePluginStore([])) + self.assertEqual(trackers.provided("tasks.list", s, {}, none), []) + self.assertEqual(trackers.provided("tasks.list", s, {}, kit.deps_with(kit.FakePluginStore())), []) + + def test_the_cores_old_task_list_shows_until_the_row_is_re_read(self): + old = {"tasks": [{"id": "1", "subject": "a", "status": "completed", + "createdAt": "C", "startedAt": "S", "endedAt": "E"}, + {"id": "2", "subject": "b", "status": "odd"}]} + got = trackers.view(self.deps(), old, {})[TASKS] + self.assertEqual(got, [ + {"key": "1", "name": "a", "group": None, "status": "completed", + "openedAt": "C", "startedAt": "S", "closedAt": "E"}, + {"key": "2", "name": "b", "group": None, "status": "pending", + "openedAt": None, "startedAt": None, "closedAt": None}]) + # a stale entry (other rules) falls back to it too; a current one wins + stale = {**old, "trackersAuto": {TASKS: {"sig": "0" * 12, "items": []}}} + self.assertEqual(len(trackers.view(self.deps(), stale, {})[TASKS]), 2) + fresh = {**old, **self.summary({"subject": "new"})} + self.assertEqual([i["name"] for i in trackers.view(self.deps(), fresh, {})[TASKS]], ["new"]) + # …and without the role, none of it + mf = kit.manifest("tasks") + mf.pop("provides") + self.assertIsNone(trackers.view(kit.deps_with(kit.FakePluginStore([mf])), old, {})) + + def test_nothing_stamps_a_tool_tracker(self): + import types + deps = self.deps() + deps.meta_store = types.SimpleNamespace(update=mock.Mock()) + deps.hub = types.SimpleNamespace(publish=mock.Mock()) + self.assertIsNone(trackers.stamp(deps, "sid", TASKS, {"do": "open", "key": "1"})) + deps.meta_store.update.assert_not_called() + + def test_a_role_goes_to_a_tracker_of_its_kind(self): + wt, tk = kit.manifest(), kit.manifest("tasks") + reg = kit.registry([wt, tk]) + self.assertEqual(reg.roles, {"git.worktrees": KEY, "tasks.list": TASKS}) + wt["provides"] = {"tasks.list": "worktrees"} # a hand-edited record + tk["provides"] = {"git.worktrees": "tasks"} + self.assertEqual(kit.registry([wt, tk]).roles, {}) + + +class ToolManifest(unittest.TestCase): + def check(self, mutate=None): + mf = kit.manifest("tasks") + if mutate: + mutate(mf) + with tempfile.TemporaryDirectory() as d: + (pathlib.Path(d) / "plugin.json").write_text(json.dumps(mf)) + return validate_manifest(pathlib.Path(d)) + + def bad(self, mutate, needle): + with self.assertRaises(ManifestError) as cm: + self.check(mutate) + self.assertIn(needle, str(cm.exception)) + + def test_the_reference_manifest_validates(self): + mf = self.check() + (t,) = mf["trackers"] + self.assertEqual((t["tool"], t["statuses"]), ("todo", {"deleted": "cancelled"})) + # a path is a list of alternatives once normalized + self.assertEqual(t["ops"], [ + {"do": "snapshot", "items": ["todos"], "name": ["content", "activeForm"], "status": ["status"]}, + {"do": "update", "id": ["taskId", "task_id"], "name": ["subject"], "status": ["status"]}, + {"do": "create", "name": ["subject", "content"]}]) + self.assertEqual(mf["provides"], {"tasks.list": "tasks"}) + ui = mf["ui"] + self.assertEqual(ui["card"][0]["list"], kit.manifest("tasks")["ui"]["card"][0]["list"]) + self.assertEqual(ui["panels"], kit.manifest("tasks")["ui"]["panels"]) + # a card drawn from a tracker is kept apart from the frames' cards + self.assertEqual(ui["toolCards"], []) + self.assertEqual(ui["trackerCards"], kit.manifest("tasks")["ui"]["toolCards"]) + + def test_texts_default(self): + def m(mf): + mf["ui"]["card"][0]["list"] = {"tracker": "tasks", "style": "checklist"} + mf["ui"]["panels"] = [{"id": "p", "tracker": "tasks"}] + mf["ui"]["toolCards"] = [{"id": "c", "tracker": "tasks"}] + ui = self.check(m)["ui"] + self.assertEqual(ui["card"][0]["list"], { + "tracker": "tasks", "style": "checklist", "title": "Checklist", + "progress": "{done} of {total} done", "added": "added {when}", + "started": "started {when}", "done": "done {when}", + "cancelled": "cancelled {when}", "took": "took {time}"}) + self.assertEqual(ui["panels"], [{"id": "p", "tracker": "tasks", "title": "Checklist", + "show": "Show the checklist"}]) + self.assertEqual(ui["trackerCards"], [{"id": "c", "tracker": "tasks", "create": "Added", + "update": "Updated", "snapshot": "Updated the list", + "many": "{count} list updates"}]) + + def test_a_plugin_without_them_keeps_its_shape(self): + # the worktrees manifest gains no key (its approval fingerprint holds) + with tempfile.TemporaryDirectory() as d: + (pathlib.Path(d) / "plugin.json").write_text(json.dumps(kit.manifest())) + ui = validate_manifest(pathlib.Path(d))["ui"] + self.assertNotIn("panels", ui) + self.assertNotIn("trackerCards", ui) + self.assertNotIn("style", ui["card"][0]["list"]) + + def test_refusals(self): + t = lambda f: (lambda mf: f(mf["trackers"][0])) # noqa: E731 + self.bad(t(lambda x: x.update(command="todo")), "one of command") + self.bad(t(lambda x: x.update(hint="TaskCreate")), "a tool tracker takes") + self.bad(t(lambda x: x.update(tool="to do")), "neutral name") + self.bad(t(lambda x: x.update(ops=[])), "ops must be") + self.bad(t(lambda x: x["ops"][0].update(do="merge")), "snapshot, update, create") + self.bad(t(lambda x: x["ops"][0].pop("items")), "items is required") + self.bad(t(lambda x: x["ops"][1].pop("id")), "id is required") + self.bad(t(lambda x: x["ops"][2].update(name="a b")), "input field") + self.bad(t(lambda x: x["ops"][2].update(name=["a", "b", "c", "d", "e"])), "input field") + self.bad(t(lambda x: x["ops"][2].update(id="taskId")), "a create op takes") + self.bad(t(lambda x: x.update(statuses={"done": "finished"})), "statuses") + self.bad(lambda mf: mf.update(provides={"git.worktrees": "tasks"}), "command tracker") + self.bad(lambda mf: mf["ui"]["card"][0]["list"].update(style="grid"), "style") + self.bad(lambda mf: mf["ui"]["card"][0]["list"].update(many="{count}"), "unknown key") + self.bad(lambda mf: mf["ui"]["card"][0]["list"].update(progress="some done"), "{done}") + self.bad(lambda mf: mf["ui"]["panels"][0].update(tracker="nope"), "tool tracker") + self.bad(lambda mf: mf["ui"]["panels"][0].update(html="x.html"), "unknown key") + self.bad(lambda mf: mf["ui"]["toolCards"][0].update(tracker="nope"), "tool tracker") + self.bad(lambda mf: mf["ui"]["toolCards"][0].update(html="x.html"), "takes no html") + self.bad(lambda mf: mf["ui"]["toolCards"][0].update(many="lots"), "{count}") + self.bad(lambda mf: mf["ui"]["toolCards"].append(dict(mf["ui"]["toolCards"][0], id="again")), + "one card per tracker") + + def test_a_checklist_and_a_panel_need_a_tool_tracker(self): + def m(mf): + wt = kit.manifest() + mf["trackers"].append(wt["trackers"][0]) + mf["ui"]["card"][0]["list"]["tracker"] = "worktrees" + self.bad(m, "a checklist lists a tool tracker") + self.bad(lambda mf: (mf["trackers"].append(kit.manifest()["trackers"][0]), + mf["ui"]["panels"][0].update(tracker="worktrees")), "tool tracker") + # …and the worktrees role needs a command tracker, the task list a tool one + wt = kit.manifest() + wt["provides"] = {"tasks.list": "worktrees"} + with tempfile.TemporaryDirectory() as d: + (pathlib.Path(d) / "plugin.json").write_text(json.dumps(wt)) + with self.assertRaises(ManifestError) as cm: + validate_manifest(pathlib.Path(d)) + self.assertIn("tool tracker", str(cm.exception)) + + def test_the_tool_enters_the_fingerprint_and_the_consent(self): + from plugins.manifest import capability_fingerprint + a = capability_fingerprint(self.check()) + b = capability_fingerprint(self.check(lambda mf: mf["trackers"][0].update(tool="claude:Other"))) + self.assertNotEqual(a, b) + (item,) = trackers.consent_items(self.check()) + self.assertIn("`todo` tool calls", item["label"]) + + +class ToolParser(unittest.TestCase): + """The transcript parse folds every tool call through the tool trackers.""" + + def parse(self, calls, store): + import conversations as c + with tempfile.TemporaryDirectory() as d: + p = pathlib.Path(d) / "s.jsonl" + recs = [{"type": "user", "sessionId": "s", "timestamp": T % 0, "cwd": "/home/u/x", + "message": {"role": "user", "content": "go"}}] + for i, (name, inp) in enumerate(calls): + recs.append({"type": "assistant", "sessionId": "s", "timestamp": T % (i + 1), + "message": {"role": "assistant", "model": "claude-opus-5-5", "id": f"m{i}", + "usage": {"input_tokens": 1, "output_tokens": 1}, + "content": [{"type": "tool_use", "id": f"t{i}", "name": name, + "input": inp}]}}) + p.write_text("".join(json.dumps(r) + "\n" for r in recs)) + with kit.bound(store): + return c.parse_conversation(p), c.parse_conversation(p, full=True) + + CALLS = [("TaskCreate", {"subject": "a", "description": "."}), + ("TaskCreate", {"subject": "b", "description": "."}), + ("TaskList", {}), ("TaskGet", {"taskId": "1"}), + ("TaskUpdate", {"taskId": "1", "status": "in_progress"}), + ("TaskUpdate", {"taskId": "1", "status": "completed"})] + + def test_claude_codes_task_tools_fill_the_list(self): + for s in self.parse(self.CALLS, kit.tasks_store()): + self.assertNotIn("tasks", s) # the core keeps no list of its own + self.assertEqual(kit.task_list(s), [ + {"key": "1", "name": "a", "group": None, "status": "completed", + "openedAt": T % 1, "startedAt": T % 5, "closedAt": T % 6}, + {"key": "2", "name": "b", "group": None, "status": "pending", + "openedAt": T % 2, "startedAt": None, "closedAt": None}]) + + def test_the_older_todowrite_snapshots_too(self): + snap = lambda *rows: ("TodoWrite", {"todos": [ # noqa: E731 + {"content": n, "status": st, "activeForm": n} for n, st in rows]}) + s, _ = self.parse([snap(("a", "in_progress")), snap(("a", "completed"), ("b", "pending"))], + kit.tasks_store()) + self.assertEqual([(i["name"], i["status"], i["startedAt"], i["closedAt"]) + for i in kit.task_list(s)], + [("a", "completed", T % 1, T % 2), ("b", "pending", None, None)]) + + def test_without_the_plugin_no_list_anywhere(self): + for store in (kit.FakePluginStore([]), kit.FakePluginStore()): + s, full = self.parse(self.CALLS, store) + self.assertNotIn("tasks", s) + self.assertEqual(kit.task_list(s), []) + # …and the calls are still in the thread, as any tool's + self.assertEqual([it["native"] for it in full["thread"] if it["kind"] == "tool_use"], + [n for n, _ in self.CALLS]) + + class Registry(unittest.TestCase): def test_version_holds_while_the_rules_do(self): store = kit.FakePluginStore() diff --git a/backend/test_trackers_hub.py b/backend/test_trackers_hub.py index 1fc54867..59544153 100644 --- a/backend/test_trackers_hub.py +++ b/backend/test_trackers_hub.py @@ -171,6 +171,56 @@ class Rederive(unittest.TestCase): self.ix.scan_transcripts() self.assertEqual(self.items(self.wt)[1], ["bffr-groups"]) + def test_a_tool_tracker_re_reads_the_transcripts_that_call_its_tool(self): + """The tasks plugin lands on an archive the core parsed: only the + transcripts whose bytes name the tool — Claude Code's own names, a v1 + file's neutral one, an older agy mirror's — are re-read.""" + claude = self.arch / "-x" / "claude.jsonl" + recs = [{"type": "user", "sessionId": "s-c", "uuid": "u0", "timestamp": "2026-11-02T10:00:00Z", + "message": {"role": "user", "content": "go"}}, + {"type": "assistant", "sessionId": "s-c", "uuid": "a0", "timestamp": "2026-11-02T10:01:00Z", + "message": {"role": "assistant", "id": "m0", "model": "claude-opus-5-5", + "usage": {"input_tokens": 10, "output_tokens": 5}, + "content": [{"type": "tool_use", "id": "t0", "name": "TaskCreate", + "input": {"subject": "ship it"}}]}}] + claude.write_text("".join(json.dumps(r) + "\n" for r in recs)) + os.utime(claude, (3000.0, 3000.0)) + + def v1(name, sid, tool, inp): + path = self.arch / "-x" / name + evs = [{"t": "session", "at": "2026-12-01T10:00:00Z", "v": 1, "id": sid, "harness": "agy", + "cwd": "/tmp/x"}, + {"t": "prompt", "at": "2026-12-01T10:00:00Z", "text": "go", "origin": "user"}, + {"t": "call", "at": "2026-12-01T10:00:01Z", "id": "m1", "model": "gemini-4-neon"}, + {"t": "tool_call", "at": "2026-12-01T10:00:01Z", "tool": tool, "id": "toolu_1", + "call": "m1", "native": "update_steps", "input": inp}, + {"t": "turn_end", "at": "2026-12-01T10:05:00Z", "reason": "done"}] + path.write_text("".join(json.dumps(e) + "\n" for e in evs)) + os.utime(path, (2500.0, 2500.0)) + return path + new = v1("v1.jsonl", "11111111-1111-4111-8111-111111111111", "todo", + {"todos": [{"content": "A", "activeForm": "A", "status": "in_progress"}]}) + old = v1("old-agy.jsonl", "22222222-2222-4222-8222-222222222222", "agy:update_steps", + {"steps": [{"title": "B", "status": "done"}]}) + names = lambda path: [(i["name"], i["status"]) for i in kit.task_list( # noqa: E731 + self.store.get_summary(str(path)) or {})] + plugins = kit.FakePluginStore([]) + with kit.bound(plugins): + self.ix.scan_transcripts() + self.assertEqual([names(p) for p in (claude, new, old)], [[], [], []]) + plugins.put(kit.manifest("tasks")) + with self.parsed() as p: + self.assertEqual(self.ix.rederive_trackers(), 3) + self.assertEqual(sorted(c.args[0].name for c in p.call_args_list), + ["claude.jsonl", "old-agy.jsonl", "v1.jsonl"]) + self.assertEqual(names(claude), [("ship it", "pending")]) + self.assertEqual(names(new), [("A", "in_progress")]) + self.assertEqual(names(old), [("B", "completed")]) + self.assertEqual(names(self.wt), []) # a shell-only transcript: not re-read + with self.parsed() as p: + self.assertEqual(self.ix.rederive_trackers(), 0) + self.assertEqual(p.call_count, 0) + def test_file_holds(self): f = self.root / "big.bin" f.write_bytes(b"x" * ((1 << 20) - 5) + b"new-worktree" + b"y" * 100) # across a chunk edge @@ -338,6 +388,98 @@ class Cards(unittest.TestCase): store.remove("worktrees") self.assertIsNone(_conv_meta(DEPS, summary)["trackers"]) + def test_a_card_carries_its_task_list_and_no_tasks_field(self): + """The list card's ``tasks`` field is gone: the task list rides in + ``meta.trackers`` (status and times per item) — a row the core parsed + before the plugin shows its old list until it is re-read.""" + from conversations.cards import _conv_meta + from conversations.catalog import _CARD_KEYS + self.assertNotIn("tasks", _CARD_KEYS) + store = kit.tasks_store() + with mock.patch.object(DEPS, "plugin_store", store): + f = trackers.Fold(trackers.registry(DEPS)) + f.feed_tool("todo", {"subject": "a"}, "2026-12-02T10:00:00Z") + f.feed_tool("todo", {"taskId": "1", "status": "in_progress"}, "2026-12-02T10:01:00Z") + summary = {"sessionId": "s-tasks", "messages": 2, "cwd": "/home/u/x", + "trackersAuto": f.summary()} + self.assertEqual(_conv_meta(DEPS, summary)["trackers"], {kit.TASKS: [ + {"key": "1", "name": "a", "group": None, "status": "in_progress", + "openedAt": "2026-12-02T10:00:00Z", "startedAt": "2026-12-02T10:01:00Z", + "closedAt": None}]}) + old = {"sessionId": "s-old", "messages": 2, "cwd": "/home/u/x", + "tasks": [{"id": "1", "subject": "before", "status": "completed"}]} + (it,) = _conv_meta(DEPS, old)["trackers"][kit.TASKS] + self.assertEqual((it["name"], it["status"]), ("before", "completed")) + store.remove("tasks") + self.assertIsNone(_conv_meta(DEPS, old)["trackers"]) + + +class TasksPlugin(unittest.TestCase): + """The reference tasks plugin on the app: what the frontend is handed to + draw, the scaffold's list, and the bridge that refuses to stamp it.""" + + def setUp(self): + self.tc = TestClient(main.app) + self.td = pathlib.Path(tempfile.mkdtemp(dir=TMP)) + self.store = PluginStore(self.td / "plugins") + p = mock.patch.object(DEPS, "plugin_store", self.store) + p.start() + self.addCleanup(p.stop) + + def install(self, **extra): + src = self.td / "src" + src.mkdir(exist_ok=True) + (src / "plugin.json").write_text(json.dumps({**kit.manifest("tasks"), **extra})) + self.store.install(OWNER_UID, str(src), is_owner=True, approve=True) + + def test_the_ui_payload_carries_what_the_app_draws(self): + ui = self.tc.get("/api/plugins", headers=OWNER_H).json()["ui"] + self.assertEqual((ui["panels"], ui["trackerCards"]), ([], [])) + self.install() + ui = self.tc.get("/api/plugins", headers=OWNER_H).json()["ui"] + (bit,) = [b for b in ui["card"] if b["pluginId"] == "tasks"] + self.assertEqual((bit["list"]["style"], bit["list"]["tracker"], bit["list"]["title"]), + ("checklist", "tasks", "Tasks")) + (panel,) = ui["panels"] + self.assertEqual((panel["pluginId"], panel["tracker"], panel["title"], panel["show"], + panel["vis"]["key"]), ("tasks", "tasks", "Tasks", "Show tasks", "panel")) + (card,) = ui["trackerCards"] + self.assertEqual((card["pluginId"], card["tool"], card["create"], card["many"], + card["vis"]), ("tasks", "todo", "New task", "{count} task updates", + {"key": "calls", "label": "Task calls", + "hint": "The calls that keep the task list, as rows in the thread", + "defaultOff": True})) + # what tells its calls apart goes with it (the same ops the parser folds) + self.assertEqual([op["do"] for op in card["ops"]], ["snapshot", "update", "create"]) + self.assertEqual(card["ops"][1]["id"], ["taskId", "task_id"]) + # a frame's tool cards are untouched + self.assertFalse([c for c in ui["toolCards"] if c["pluginId"] == "tasks"]) + self.assertIn("tasks.list", ui["provides"]) + + def test_the_scaffold_lists_the_tasks_through_the_role(self): + from conversations import scaffold + f = lambda: trackers.Fold(trackers.registry(DEPS)) # noqa: E731 + self.assertEqual(scaffold._work([], {"tasks": [{"id": "1", "subject": "x", "status": "pending"}]}, {}), + []) # no provider: no list + self.install() + fold = f() + fold.feed_tool("todo", {"subject": "a"}, None) + fold.feed_tool("todo", {"subject": "b"}, None) + fold.feed_tool("todo", {"subject": "c"}, None) + fold.feed_tool("todo", {"taskId": "1", "status": "completed"}, None) + fold.feed_tool("todo", {"taskId": "3", "status": "deleted"}, None) + out = scaffold._work([], {"trackersAuto": fold.summary()}, {}) + self.assertEqual(out[-6:], ["### Task list", "", "- [x] a", "- [ ] b", "- [-] c", ""]) + + def test_the_bridge_refuses_to_stamp_a_tool_tracker(self): + self.install(capabilities=["trackers.stamp"]) + tok = access.mint_handler(OWNER_UID, "tasks", ttl=600) + r = self.tc.post("/proxy/tools/plugins/tasks/hub/trackers/tasks/events", + headers={"Authorization": f"Bearer {tok}"}, + json={"sessionId": SID, "do": "open", "key": "1"}) + self.assertEqual(r.status_code, 400, r.text) + self.assertIn("transcript", r.text) + if __name__ == "__main__": unittest.main() diff --git a/docs/plugins.md b/docs/plugins.md index 5c1beb7e..d77e2e64 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -1091,7 +1091,8 @@ plugin (`~/projects/ai-agent-plugins/plugins/worktrees`, form what it stands on is generic, and nothing in it is about git: **`trackers[]`** (`backend/plugins/trackers.py`) — "things a conversation -opened and closed", read off its **shell commands** by rules declared as data. +opened and closed", read off its **shell commands** (or, for a tool tracker, +a **tool's calls** — below) by rules declared as data. No plugin code runs: the host's parser applies them (`trackers.Fold`, fed by `ParserState`) and keeps, per conversation and tracker, `[{key, name, group, openedAt, closedAt}]`. The reference manifest is @@ -1114,6 +1115,67 @@ Every regex is compiled at install and refused with nested quantifiers, like open keeps the earliest `openedAt`, a close the latest `closedAt`; at most 60 items per conversation and tracker, each field ≤ 120 characters. +**Tool trackers** (since 2026-12-02, the `tasks` plugin — form +`move-tasks-into-a-plugin_tq2l2e`). A tracker reads a **tool's calls** instead +of shell commands when it declares `tool` and `ops` (and then no `hint`, +`command`, `flags`, `args`, `events`, `valid` or `group`). The reference +manifest is `backend/fixtures/tracker_plugins/tasks.json`: + +```json +{ "id": "tasks", "label": "Tasks", "tool": "todo", + "ops": [ + { "do": "snapshot", "items": "todos", "name": ["content", "activeForm"], "status": "status" }, + { "do": "update", "id": ["taskId", "task_id"], "name": "subject", "status": "status" }, + { "do": "create", "name": ["subject", "content"] } ], + "statuses": { "deleted": "cancelled" } } +``` + +| Field | What | +|---|---| +| `tool` | the tool's **neutral name** (`todo`, `claude:CronCreate`, `mcp__…` — `conversations/parse/readers/toolnames.py`), so one rule reads every harness: Claude Code's TaskCreate / TaskUpdate / TodoWrite and agy's `update_steps` are all `todo` | +| `ops[]` (1–6) | told apart by the call's **input**, in order — the first whose input is there fires: `snapshot` when `items` is a list, `update` when `id` is set, `create` when `name` is set; a call that matches none (the list read back) changes nothing | +| an op's fields | input **field paths** (`subject`, dotted for a nested one), one or up to 4 alternatives — the first that is set wins. `snapshot`: `items` (the list), `name` and `status?` (of each row); `update`: `id`, `name?`, `status?`; `create`: `name`, `status?` | +| `statuses` | the tool's own words (≤ 24, case-insensitive) → `pending` / `in_progress` / `completed` / `cancelled` (which map to themselves). An unknown word leaves an updated item as it was; a snapshot's row reads `pending` | + +- **Fold** (`Tracker.fold_call`, fed every tool call by `ParserState` through + `Fold.feed_tool(tool, input, ts)`): a **create** appends an item whose `key` + is its **1-based ordinal** — the id a sequential task tool's update cites; an + **update** changes one item by that id (its status, its name); a **snapshot** + replaces the list, and a row whose name is unchanged keeps its times. +- **Items** carry two more fields: `status`, and `startedAt` (the first time + it was in progress) beside `openedAt` (when it was added) and `closedAt` + (completed or cancelled — cleared again if it reopens). `group` is null. + They keep **the list's own order** (never sorted by time), at most 200 per + conversation and tracker, a name ≤ 200 characters on one line. +- **No `hint` to declare**: the re-derive pass looks for what a transcript's + bytes hold when it calls the tool (`toolnames.byte_hints` → `Tracker.hints`), + each **with its JSON quotes** so a message that merely talks about the tool + doesn't count: the neutral name as a v1 file writes it (`"todo"`), every + harness-native name that maps to it (`"TaskCreate"`, `"TaskUpdate"`, + `"TodoWrite"`…) and an older agy mirror's `:update_steps"`. Installing the + plugin re-reads those transcripts in the background, once; nothing else is + touched. +- **Nothing stamps it**: a tool tracker's list is its transcript's — + `trackers.stamp` answers 400 for one, and `merge` never runs. +- `(id, "tool:")` enters the approval fingerprint; the consent line + reads "Keeps the `Tasks` list of your conversations, read off their `todo` + tool calls". +- **Role `tasks.list`** (`provides: {"tasks.list": ""}`): the + conversation's task list for the core's readers — + `trackers.provided("tasks.list", summary, meta)` → `[{id, subject, status, + createdAt, startedAt, endedAt}]`, what the completion scaffold's *Task list* + reads (`conversations/scaffold.py`). No provider: no list anywhere. A role + goes to a tracker of its kind only (`TOOL_ROLES`: `git.worktrees` a command + tracker, `tasks.list` a tool one). +- **Carry-over**: until 2026-12-02 the parser kept `tasks` on every summary + (`[{id, subject, status}]`). A row not re-read yet shows that list as the + `tasks.list` provider's items (`carryover_trackers._task_items`, only while + the summary has no entry of the tracker's current rules), so past + conversations keep their pill from the first request. The summary field, the + card's `tasks`, the `Task` schema and the core fold (`todo_op`) are gone. +- What draws it: a `ui.card[]` **checklist** bit, a `ui.panels[]` entry and a + `ui.toolCards[]` entry that names the tracker — see "Checklists". + - **The registry is the owner's active plugins'** (`trackers.registry(deps)`, cached on `PluginStore.version`, the same object and `version` while its rules hold — the cards' memo and per-card cache key on it). A guest's own @@ -1149,8 +1211,9 @@ items per conversation and tracker, each field ≤ 120 characters. null = the lab). What a clean-up asks before it closes things (`trackers.tracker_sessions`). - **On the card**: `meta.trackers` = `{":": [items]}` (null when - none; `TrackedItem` in `schemas/conversations.py`), drawn by a `ui.card[]` - **list bit** (below). + none; `TrackedItem` in `schemas/conversations.py` — a tool tracker's items + also carry `status` and `startedAt`), drawn by a `ui.card[]` **list bit** + (below). - **Provider roles**: `provides: {"git.worktrees": ""}` — a `provides` key that names one of the plugin's trackers instead of an action (`trackers.ROLES`; the first active plugin keeps a role). It says "this @@ -1173,7 +1236,8 @@ items per conversation and tracker, each field ≤ 120 characters. conversation keeps its pill from the first request; nothing is rewritten. - Tests: `test_trackers.py` (rules, fold, view, manifest), `test_trackers_hub.py` (the re-derive pass, routes, bridge, cards), the - plugin's `tests/test_worktrees_plugin.py`. + plugin's `tests/test_worktrees_plugin.py` — and the tool trackers' (see + "Checklists"). **The worktrees commands** (step 2, 2026-12-02): `ai-agent worktrees` — `ls`, `rm`, `clean` — left `cli/worktrees.py` for the same plugin's `commands` @@ -1598,7 +1662,7 @@ then; forms `home-declutter-phone_kwmprx` and the demo's): - `when`: a field (set and not zero), or a field compared (`== != > >= < <=`) to a number or a `"string"` — `local.wh > 0`, `meta.harness == "pi"`. - `icon`: one of `CARD_ICONS` (lucide: `zap`, `gauge`, `cpu`, `server`, - `laptop`, `leaf`, `clock`, `coins`, `bot`, `sparkles`, `git-branch`…); `tone`: `plain` + `laptop`, `leaf`, `clock`, `coins`, `bot`, `sparkles`, `git-branch`, `list-checks`…); `tone`: `plain` (text only), `muted` (default), `primary`, `amber`, `emerald`, `sky`, `violet`, `rose` (a corner and a border default to `primary`). - **`list`** (a `tags` bit, no `text`): the pill reads one of the plugin's @@ -1615,6 +1679,9 @@ then; forms `home-declutter-phone_kwmprx` and the demo's): and `lifespan` (holds `{time}`); five rows, then the list scrolls. Every text has an English default (`CARD_LIST_TEXTS`, the same keys both sides) and is translated like `text`. +- **`list.style: "checklist"`** (a tool tracker's list — the tasks plugin's + pill; see "Checklists" below): the pill is a progress count instead, + `✓ done/total`, and its card the checklist. - **Where bits are drawn**: the home and drawer cards (every place), the Conversations page (`tags`, `cost`) and the conversation's details tag row (`tags` — over the thread's own detail, which carries the same fields). @@ -1628,6 +1695,97 @@ then; forms `home-declutter-phone_kwmprx` and the demo's): `pluginName`). An older hub ignores the key, so a plugin can ship it before the hub does — its bit just doesn't show there. +## Checklists: a tool tracker's pill, panel and call rows (since 2026-12-02, the `tasks` plugin) + +Everything about a conversation's **task list** left the core for the seeded +`tasks` plugin (`~/projects/ai-agent-plugins/plugins/tasks`, pure data, +`managed` with `defaultForGuests`; forms `tasks-pill-popover_rdyw4k`, +`move-tasks-into-a-plugin_tq2l2e`): the parse is a **tool tracker** (see +"Trackers"), and the three things people see are **declared by the plugin and +drawn by the app** — natively, no frame, the look and the motion the core's +`TaskBadge` / `TaskPanel` / `todo` card had +(`frontend/src/business/plugins/components/Checklist.tsx`, `PluginPanels.tsx`, +`plugins/trackerCards.tsx`). Each reads the conversation's +`meta.trackers[":"]` — the list card's and the thread +detail's alike. All three must name a **tool** tracker (its items have a +status), else the install is refused. + +```json +"ui": { + "card": [{ "id": "tasks", "place": "tags", "icon": "list-checks", "tone": "primary", + "list": { "tracker": "tasks", "style": "checklist", "title": "Tasks", + "progress": "{done} of {total} tasks done", "added": "added {when}", + "started": "started {when}", "done": "done {when}", + "cancelled": "cancelled {when}", "took": "took {time}" }, + "vis": { "key": "pill", "label": "Tasks pill", "hint": "…" } }], + "panels": [{ "id": "tasks", "tracker": "tasks", "title": "Tasks", "show": "Show tasks", + "vis": { "key": "panel", "label": "Task panel", "hint": "…" } }], + "toolCards": [{ "id": "todo", "tracker": "tasks", "icon": "list-checks", + "create": "New task", "update": "Task", "snapshot": "Updated todos", + "many": "{count} task updates", + "vis": { "key": "calls", "label": "Task calls", "hint": "…", "defaultOff": true } }] +} +``` + +- **The pill** — a `ui.card[]` list bit with `style: "checklist"` + (`ChecklistPill`): `✓ done/total`, a cancelled item out of both; emerald + once all are done, amber while one is in progress, else the bit's `tone` + (default `muted`; the tasks plugin's is `primary`). No item left in the + plan: no pill. Hovering (a tap on a phone, which then doesn't open the + conversation) opens the checklist card — `title` and the count, then the + rows in the list's order: a spinner (in progress), an empty or ticked box, a + ✕ and a strike (cancelled), and under each its times, `added … · started … + · done … · took …` (`took`: from its first start, else from when it was + added; an item with no times shows none). **8 rows**, then the list scrolls. + Its wording is `CARD_CHECKLIST_TEXTS` (`title`, `progress` — holds `{done}` + and `{total}`, the pill's label for a screen reader —, `added` / `started` / + `done` / `cancelled` — hold `{when}` —, `took` — holds `{time}`), each with + an English default. Drawn wherever `tags` bits are — the home and drawer + cards, the Conversations page, the conversation's details tag row — and + **leading** them, where the core's tasks badge stood (`CardBits lead`): a + progress pill isn't the first thing folded behind `+N`. +- **The panel** — `ui.panels[]` (≤ 2 per plugin): `{id, tracker, title?, + show?, vis?}` (`ChecklistPanel`). A small card pinned top-right over the + conversation's thread: `title` and x/n, the rows (no times), a minus button + that folds it into a pill (`show` is that pill's tooltip; the folded state + is kept per device and panel — the tasks plugin's under the key the core's + Tasks panel had). Its first item while you watch slides it in from the right + edge, a new row makes room, a done one fills its box and strikes through. + Empty list: no panel. Several plugins' panels stack. +- **The calls' rows** — a `ui.toolCards[]` entry with **`tracker`** and no + `match` / `html`: `{id, tracker, icon?, create?, update?, snapshot?, many?, + vis?}` (one per tracker, ≤ 4; kept apart from the frames' cards as + `ui.trackerCards` in the normalized manifest and in `GET /api/plugins`, + which adds the tracker's `tool` and `ops` so the app tells a call's op the + way the parser does). While the plugin is active the app registers a card + for that tool (`trackerToolCard`): a row per call — `create` + the new + item's name ("New task Ship it"), `update` + `# → ` + ("Task #2 → completed"), `snapshot` ("Updated todos") — whose body is the + call's fields and output, and a run of them folds into a group's line as + `many` ("3 task updates"). A call that changes nothing (a lookup, the list + read back) stays a plain row. **Its `vis` decides whether the calls are + rows at all**: switched off — the tasks plugin's *Task calls* starts off — + the thread **leaves them out**, as the core always did (they are the + tracker's bookkeeping; the pill and the panel show the result). No `vis`: + always rows. +- **Without the plugin** there is no pill and no panel, and the tool's calls + are plain generic rows (`TaskCreate` with its input as JSON): the core keeps + no card for `todo`, only its cost bucket. +- **Switches**: each declaration's `vis` is a switch of the eye popover + (`plugin::`). The core's *Task panel* switch is gone; a person who + had hidden it keeps it hidden (`lib/visibility.ts` `RENAMED_KEYS`: + `taskPanel` → `plugin:tasks:panel`). +- **Translated** with the plugin's dictionary: `plugin_i18n.py` extracts a + checklist bit's wording, a panel's `title` / `show` and a tracker card's + four texts. +- An older hub refuses a manifest with a tool tracker (a seed that can't be + validated is skipped with a warning): ship the hub first, or both together. +- Tests: `test_trackers.py` (`ToolRules`, `ToolView`, `ToolManifest`, + `ToolParser`), `test_trackers_hub.py` (the re-derive pass on a tool tracker, + the card field, the UI payload, the scaffold), the frontend's + `PillPopovers.test.tsx`, `PluginPanels.test.tsx`, `trackerCards.test.tsx`, + the plugin's `tests/test_tasks_plugin.py`. + ## The widget platform: slots, live updates, home tiles (since 2026-11-26) The core widgets of the home page and the conversation page move into plugins diff --git a/docs/transcript-format.md b/docs/transcript-format.md index 492887c8..cc0c0099 100644 --- a/docs/transcript-format.md +++ b/docs/transcript-format.md @@ -141,7 +141,8 @@ TodoWrite (the whole list each call): the mirror writes it as `todo `in_progress`, `pending`, `skipped` / `cancelled` / `canceled` → `cancelled`, anything else `pending`. A file mirrored before 2026-12-01 keeps `tool: "agy:update_steps"` with `{steps}`: the readers turn it into the same `todo` -(`toolnames.upgrade_call`, parser v48). A `run_command` that outlasts its +(`toolnames.upgrade_call`, parser v48). What reads a `todo` call into a task +list is the `tasks` plugin's tool tracker (docs/plugins.md → "Trackers"). A `run_command` that outlasts its wait, and a `schedule` timer (`agy:schedule {delaySeconds, prompt}`), get a `tool_result` whose `data.taskId` is agy's `/task-`; `manage_task` names it in `input.task_id` (`list` stays `agy:manage_task`). diff --git a/frontend/openapi.json b/frontend/openapi.json index 974f4734..c2a3b647 100644 --- a/frontend/openapi.json +++ b/frontend/openapi.json @@ -17871,20 +17871,6 @@ ], "title": "Firstmessagetokens" }, - "tasks": { - "anyOf": [ - { - "items": { - "$ref": "#/components/schemas/Task" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "title": "Tasks" - }, "skillsUsed": { "anyOf": [ { @@ -18836,20 +18822,6 @@ ], "title": "Firstmessagetokens" }, - "tasks": { - "anyOf": [ - { - "items": { - "$ref": "#/components/schemas/Task" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "title": "Tasks" - }, "skillsUsed": { "anyOf": [ { @@ -36095,30 +36067,6 @@ ], "title": "TagPatchBody" }, - "Task": { - "properties": { - "id": { - "type": "string", - "title": "Id" - }, - "subject": { - "type": "string", - "title": "Subject" - }, - "status": { - "type": "string", - "title": "Status" - } - }, - "type": "object", - "required": [ - "id", - "subject", - "status" - ], - "title": "Task", - "description": "One task from the conversation's task list (TaskCreate/TaskUpdate, or the\nolder TodoWrite). ``status`` is one of pending / in_progress / completed /\ncancelled." - }, "TaskEvent": { "properties": { "ts": { @@ -37386,6 +37334,28 @@ } ], "title": "Closedat" + }, + "status": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Status" + }, + "startedAt": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Startedat" } }, "type": "object", @@ -37394,7 +37364,7 @@ "name" ], "title": "TrackedItem", - "description": "One thing a conversation opened (and maybe closed), read by a plugin's\ntracker rules (plugins/trackers.py) \u2014 a git worktree, for the worktrees\nplugin." + "description": "One thing a conversation opened (and maybe closed), read by a plugin's\ntracker rules (plugins/trackers.py) \u2014 a git worktree, for the worktrees\nplugin; one task of its list, for the tasks plugin (a tool tracker's item:\nit has a ``status``, and its list keeps the plan's order)." }, "TrackedSessions": { "properties": { diff --git a/frontend/src/business/conversations/components/ConvMetaBits.tsx b/frontend/src/business/conversations/components/ConvMetaBits.tsx index bbfe6c1a..827fe0dc 100644 --- a/frontend/src/business/conversations/components/ConvMetaBits.tsx +++ b/frontend/src/business/conversations/components/ConvMetaBits.tsx @@ -43,6 +43,8 @@ import type { } from "@/types"; import { Roll } from "@/technical/Roll"; import { PresetChip } from "@/lib/runPresets"; +import { PillPopover } from "@/technical/PillPopover"; +import { PresetRouteCard } from "./PresetRouteCard"; import { usePluginOpener } from "@/business/plugins/opener"; import { useIsOwner } from "@/business/users/api"; import { locale, msg, t, tc } from "@/i18n"; @@ -362,16 +364,31 @@ export function PresetBadge({ n: route.n, model: route.model ?? "", }); + const href = owner && openPreset ? openPreset({ id: meta.preset }) : null; const chip = ( ); - const href = linkify && owner && openPreset ? openPreset({ id: meta.preset }) : null; - return href ? {chip} : chip; + // Hovering (tapping, on a phone) opens the route card; a click in the + // header still opens the preset (the owner's). + return ( + + {linkify && href ? {chip} : chip} + + } + > + + + ); } /** The tools' names on the chip's tooltip. */ diff --git a/frontend/src/business/conversations/components/ConversationListElement.tsx b/frontend/src/business/conversations/components/ConversationListElement.tsx index 99e9d670..796c0f86 100644 --- a/frontend/src/business/conversations/components/ConversationListElement.tsx +++ b/frontend/src/business/conversations/components/ConversationListElement.tsx @@ -23,7 +23,6 @@ import { useVisible } from "@/lib/visibility"; import { useSendFailed } from "@/lib/outbox"; import { TagRows } from "./TagRows"; import { ConvLead, useConvLook, useConvLookOn } from "@/lib/look"; -import { TaskBadge } from "./TaskPanel"; import { ResourceTags } from "./ResourceTags"; import { ResumeChip } from "./StopResume"; import { useCardHides } from "@/lib/profiles"; @@ -221,7 +220,8 @@ export const ConversationListElement = memo(function ConversationListElement({ )} - + {/* The plugins' progress pills (a checklist bit — the tasks plugin's). */} + @@ -235,7 +235,7 @@ export const ConversationListElement = memo(function ConversationListElement({ {/* The plugins' pills (`ui.card[]`): the worktrees plugin's, a local run's energy… */} - + {/* What the price is made of: its paid tools (the agents it started are in the foot). */} diff --git a/frontend/src/business/conversations/components/PillPopovers.test.tsx b/frontend/src/business/conversations/components/PillPopovers.test.tsx new file mode 100644 index 00000000..53a994cb --- /dev/null +++ b/frontend/src/business/conversations/components/PillPopovers.test.tsx @@ -0,0 +1,146 @@ +import { fireEvent, render, screen } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; +import { MemoryRouter } from "react-router-dom"; + +import type { ConvMeta } from "@/types"; +import type { CardBitSpec, TrackedItem } from "@/lib/cardBits"; +import { CardBits } from "@/business/plugins/components/PluginCardBits"; +import { routeRungs } from "./PresetRouteCard"; + +const tap = (el: HTMLElement) => { + fireEvent.pointerDown(el, { pointerType: "touch" }); + fireEvent.click(el); +}; + +/** The pill inside a card-wide link, as on the conversation list. */ +function inCard(node: React.ReactNode, onCard: () => void) { + return render( + + { e.preventDefault(); onCard(); }}> + {node} + + , + ); +} + +/** The tasks plugin's checklist bit, as `/api/plugins` hands it out. */ +const SPEC: CardBitSpec = { + id: "tasks", + place: "tags", + icon: "list-checks", + tone: "primary", + list: { + tracker: "tasks", + style: "checklist", + title: "Tasks", + progress: "{done} of {total} tasks done", + added: "added {when}", + started: "started {when}", + done: "done {when}", + cancelled: "cancelled {when}", + took: "took {time}", + }, + pluginId: "tasks", + pluginName: "Tasks", +}; + +const TASKS: TrackedItem[] = [ + { key: "1", name: "Map the API", status: "completed", openedAt: "2026-11-01T10:00:00Z", startedAt: "2026-11-01T10:01:00Z", closedAt: "2026-11-01T10:13:00Z" }, + { key: "2", name: "Seed it", status: "in_progress", openedAt: "2026-11-01T10:00:00Z", startedAt: "2026-11-01T10:13:00Z" }, + { key: "3", name: "Wire it", status: "pending" }, +]; +const conv = (items: TrackedItem[]) => ({ meta: { trackers: { "tasks:tasks": items } } }); +const pill = (items = TASKS) => ; + +describe("the tasks pill's card (a checklist bit)", () => { + it("a tap opens the checklist, with each task's times, instead of the conversation", () => { + const card = vi.fn(); + inCard(pill(), card); + expect(screen.queryByText("Map the API")).toBeNull(); + tap(screen.getByLabelText("1 of 3 tasks done")); + expect(card).not.toHaveBeenCalled(); + expect(screen.getByText("Tasks")).toBeInTheDocument(); + expect(screen.getByText("Map the API")).toBeInTheDocument(); + expect(screen.getByText("Wire it")).toBeInTheDocument(); + // Done: added · done · took (from its first start); running: started. + expect(screen.getByText(/took 12m/)).toBeInTheDocument(); + expect(screen.getAllByText(/started /)).toHaveLength(1); + // A task from before the times existed: no times line. + const wire = screen.getByText("Wire it").closest("li")!; + expect(wire.textContent).toBe("Wire it"); + }); + + it("a mouse opens it on hover, and a click is still the card's link", () => { + const card = vi.fn(); + inCard(pill(), card); + const el = screen.getByLabelText("1 of 3 tasks done"); + fireEvent.pointerEnter(el.closest("[data-checklist-pill]")!, { pointerType: "mouse" }); + expect(screen.getByText("Seed it")).toBeInTheDocument(); + fireEvent.pointerDown(el, { pointerType: "mouse" }); + fireEvent.click(el); + expect(card).toHaveBeenCalledTimes(1); + }); + + it("emerald once all done, amber while one runs, its own tone otherwise; cancelled ones don't count", () => { + const of = (items: TrackedItem[]) => { + const { container, unmount } = inCard(pill(items), vi.fn()); + const cls = container.querySelector("[aria-label]")?.className ?? null; + const label = container.querySelector("[aria-label]")?.getAttribute("aria-label") ?? null; + unmount(); + return [label, cls] as const; + }; + const [l1, c1] = of(TASKS); + expect(l1).toBe("1 of 3 tasks done"); + expect(c1).toContain("amber"); + const [l2, c2] = of([TASKS[0], { key: "9", name: "Dropped", status: "cancelled" }]); + expect(l2).toBe("1 of 1 tasks done"); + expect(c2).toContain("emerald"); + const [l3, c3] = of([TASKS[2]]); + expect(l3).toBe("0 of 1 tasks done"); + expect(c3).toContain("text-primary"); + // nothing left of the plan: no pill + expect(of([{ key: "9", name: "Dropped", status: "cancelled" }])).toEqual([null, null]); + }); + + it("the tags split in two: the progress pill leads, the rest follows", () => { + const other: CardBitSpec = { id: "e", place: "tags", text: "plain", pluginId: "x", pluginName: "X" }; + const both = { meta: { trackers: { "tasks:tasks": TASKS } } }; + const { container, rerender } = render(); + expect(container.querySelectorAll("[data-card-bit]")).toHaveLength(1); + expect(container.querySelector("[data-checklist-pill]")).not.toBeNull(); + rerender(); + expect(container.querySelector("[data-checklist-pill]")).toBeNull(); + expect(screen.getByText("plain")).toBeInTheDocument(); + }); +}); + +describe("the preset pill's route", () => { + it("lists the rungs it touched in ladder order: skipped, sent here, stepped down", () => { + const meta = { + preset: "best", + presetName: "Best", + route: { + i: 4, n: 6, harness: "agy", model: "gemini-4-hydrogen", at: "2026-11-01T10:00:00Z", + skipped: [ + { i: 1, model: "claude-sonnet-5", harness: "claude", reason: "week 100%" }, + { i: 0, model: "claude-opus-4-8", harness: "claude", reason: "week 100%" }, + ], + }, + routeSteps: [ + { at: "2026-11-01T10:30:00Z", from: { i: 3, model: "gemini-4-neon" }, to: { i: 4, model: "gemini-4-hydrogen" }, why: "5 h 96%" }, + ], + } as ConvMeta; + const rungs = routeRungs(meta); + expect(rungs.map((r) => [r.i, r.model, r.skipped ?? null, !!r.start, r.stepAt ?? null])).toEqual([ + [0, "claude-opus-4-8", "week 100%", false, null], + [1, "claude-sonnet-5", "week 100%", false, null], + [3, "gemini-4-neon", null, true, null], + [4, "gemini-4-hydrogen", null, false, "2026-11-01T10:30:00Z"], + ]); + }); + + it("no step: the rung it was sent to is the current one", () => { + const meta = { preset: "everyday", route: { i: 0, n: 3, model: "sonnet" } } as ConvMeta; + expect(routeRungs(meta).map((r) => [r.i, r.start])).toEqual([[0, true]]); + }); +}); diff --git a/frontend/src/business/conversations/components/PresetRouteCard.tsx b/frontend/src/business/conversations/components/PresetRouteCard.tsx new file mode 100644 index 00000000..34a4e1c3 --- /dev/null +++ b/frontend/src/business/conversations/components/PresetRouteCard.tsx @@ -0,0 +1,174 @@ +import { Link } from "react-router-dom"; +import { ArrowDown, Check, CornerDownRight, SkipForward } from "lucide-react"; +import { cn, fmtDateTime, relTime } from "@/lib/utils"; +import { t } from "@/i18n"; +import { LadderIcon } from "@/lib/runPresets"; +import { modelLabel } from "@/lib/models"; +import { useWorker } from "@/lib/workers"; +import type { ConvMeta } from "@/types"; + +/** One rung of the preset's ladder, as far as this conversation knows it. */ +type Rung = { + i: number; + model?: string | null; + harness?: string | null; + /** Passed over when the run was routed, and why. */ + skipped?: string | null; + /** Where the run was first sent. */ + start?: boolean; + /** A later turn stepped down to it: when, and why. */ + stepAt?: string; + why?: string | null; +}; + +/** + * The rungs this conversation's route touched, in ladder order: the ones it + * skipped (with the reason), the one it was sent to, each one a follow-up + * stepped down to. The rungs below the current one aren't in the meta. + */ +export function routeRungs(meta: ConvMeta): Rung[] { + const route = meta.route!; + const steps = meta.routeSteps ?? []; + const rungs = new Map(); + const at = (i: number) => { + let r = rungs.get(i); + if (!r) rungs.set(i, (r = { i })); + return r; + }; + for (const s of route.skipped ?? []) { + const r = at(s.i); + r.model ??= s.model; + r.harness ??= s.harness; + r.skipped = s.reason || t("skipped"); + } + const first = steps[0]?.from; + const start = at(typeof first?.i === "number" ? first.i : route.i); + start.start = true; + start.skipped = null; + if (first?.model) start.model = first.model; + for (const s of steps) { + if (typeof s.to.i !== "number") continue; + const r = at(s.to.i); + r.model = s.to.model ?? r.model; + r.skipped = null; + r.stepAt = s.at; + r.why = s.why; + } + const cur = at(route.i); + cur.skipped = null; + cur.model = route.model ?? cur.model; + cur.harness = route.harness ?? cur.harness; + return [...rungs.values()].sort((a, b) => a.i - b.i); +} + +function WorkerName({ id }: { id: string }) { + const w = useWorker(id); + return <>{w?.name ?? id}; +} + +/** + * The card the preset pill opens: the preset, the rung the conversation is on + * out of how many, then one row per rung its route touched — skipped (struck, + * with why), sent here, stepped down here (when, why) — and where the current + * one runs (harness, login, machine). The owner gets a link to the preset. + */ +export function PresetRouteCard({ meta, href }: { meta: ConvMeta; href?: string | null }) { + const route = meta.route!; + const name = meta.presetName || meta.preset || ""; + const rungs = routeRungs(meta); + const where = [route.harness, route.account].filter(Boolean).join(" · "); + return ( + + + + {name} + + {t("rung {i} of {n}", { i: route.i + 1, n: route.n })} + + {href && ( + + {t("Open preset")} + + )} + + + {rungs.map((r) => { + const current = r.i === route.i; + return ( + + + {r.i + 1} + + + + + {r.model ? modelLabel(r.model) : t("unknown model")} + + {r.skipped && r.harness && ( + {r.harness} + )} + {current && ( + + {t("now")} + + )} + + + {r.skipped ? ( + <> + + {r.skipped} + + ) : r.stepAt ? ( + + + {r.why + ? t("stepped down {when} · {why}", { when: relTime(r.stepAt), why: r.why }) + : t("stepped down {when}", { when: relTime(r.stepAt) })} + + ) : r.start ? ( + + + {route.at ? t("sent here {when}", { when: relTime(route.at) }) : t("sent here")} + + ) : null} + + + + ); + })} + + {(where || route.worker || route.exact || route.full) && ( + + {(where || route.worker) && ( + + + + {where} + {where && route.worker && " · "} + {route.worker && } + + + )} + {route.full && {t("Every rung was full: it fell back to this one")}} + {route.exact && ( + + {t("A later turn picked one exact model ({model}): the ladder no longer steps", { + model: modelLabel(route.exact), + })} + + )} + + )} + + ); +} diff --git a/frontend/src/business/conversations/components/TaskPanel.tsx b/frontend/src/business/conversations/components/TaskPanel.tsx deleted file mode 100644 index 4dc616cf..00000000 --- a/frontend/src/business/conversations/components/TaskPanel.tsx +++ /dev/null @@ -1,305 +0,0 @@ -import { useEffect, useLayoutEffect, useRef, useState } from "react"; -import { Check, ListChecks, Loader2, Minus, X } from "lucide-react"; -import { cn } from "@/lib/utils"; -import { t } from "@/i18n"; -import type { Task } from "@/types"; -import { Roll } from "@/technical/Roll"; -import { EASE_IN, EASE_OUT, ENTER_MS, ROOM_MS, SLIDE_MS, SPRING, popIn, skipMotion, useMotionOn, useSettled } from "@/technical/motion"; -import { usePrevious } from "@/technical/motionBits"; - -/** Roll a task list up into an x/n progress count. Cancelled tasks drop out of - * both the numerator and the denominator (they're no longer part of the plan). */ -export function taskCounts(tasks?: Task[] | null): { - total: number; - done: number; - inProgress: number; -} { - const list = tasks ?? []; - let total = 0; - let done = 0; - let inProgress = 0; - for (const tk of list) { - if (tk.status === "cancelled") continue; - total++; - if (tk.status === "completed") done++; - else if (tk.status === "in_progress") inProgress++; - } - return { total, done, inProgress }; -} - -/** - * Compact x/n tasks badge (a checklist pill), shown on conversation cards. Emits - * nothing when the conversation has no tasks. Turns emerald once everything is - * done, amber while something is in progress. - */ -export function TaskBadge({ - tasks, - className, -}: { - tasks?: Task[] | null; - className?: string; -}) { - const { total, done, inProgress } = taskCounts(tasks); - if (total === 0) return null; - const complete = done === total; - return ( - - - / - - ); -} - -/** - * A single task row: a status "checkbox" + its (tiny) subject text. Added while - * you watch (`arrive`), it makes room, then shows; done while you watch, its - * box fills with a pop and a strike draws across the subject. - */ -function TaskRow({ task, arrive, live }: { task: Task; arrive: boolean; live: boolean }) { - const { status } = task; - const done = status === "completed"; - const cancelled = status === "cancelled"; - const active = status === "in_progress"; - const motion = useMotionOn(); - const rowRef = useRef(null); - const boxRef = useRef(null); - const wasDone = usePrevious(done); - const justDone = done && !wasDone && live; - - useLayoutEffect(() => { - const li = rowRef.current; - if (!li || !arrive || skipMotion()) return; - const h = li.offsetHeight; - const pad = getComputedStyle(li); - const room = li.animate( - [ - { height: "0px", paddingTop: "0px", paddingBottom: "0px", opacity: 0 }, - { height: `${h}px`, paddingTop: pad.paddingTop, paddingBottom: pad.paddingBottom, opacity: 0 }, - ], - { duration: ROOM_MS, easing: EASE_OUT }, - ); - let show: Animation | null = null; - room.finished.then(() => { - show = li.animate([{ opacity: 0, transform: "translateY(-4px)" }, { opacity: 1, transform: "none" }], { - duration: ENTER_MS, - easing: EASE_OUT, - }); - }, () => {}); - return () => { - room.cancel(); - show?.cancel(); - }; - // Mount only: a task arrives once. - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - - useLayoutEffect(() => { - if (justDone && boxRef.current) popIn(boxRef.current); - }, [justDone]); - - return ( -
  • - {active ? ( - - ) : ( - - {done && } - {cancelled && } - - )} - - {/* The strike is a line drawn under the text (an inline background, - so it follows a subject over two lines), sized to 0 → 100 %. */} - - {task.subject} - - -
  • - ); -} - -/** Collapse ↔ expand: the card shrinks into the corner, then the pill pops out of it (and back). */ -const MORPH_OUT_MS = 200; -const MORPH_IN_MS = 320; - -/** - * Floating task checklist for the conversation detail view — a small card pinned - * top-right of the thread showing each task with a status checkbox in tiny text. - * Collapses to a single pill showing x/n (persisted). Renders nothing when the - * conversation tracked no tasks. - * - * Its first task while you watch slides it in from the right edge; a task - * added later makes room, then shows; one done fills its box and strikes - * through; collapsing shrinks the card toward the corner and the pill pops - * out of it (and back). What was there when the page loaded is just there. - */ -export function TaskPanel({ tasks }: { tasks?: Task[] | null }) { - const { total, done, inProgress } = taskCounts(tasks); - const [collapsed, setCollapsed] = useState( - () => localStorage.getItem("ai-agent:tasks-collapsed") === "1", - ); - useEffect(() => { - localStorage.setItem("ai-agent:tasks-collapsed", collapsed ? "1" : "0"); - }, [collapsed]); - const settled = useSettled(); - const boxRef = useRef(null); - const shown = total > 0 && !!tasks; - const wasShown = usePrevious(shown); - // The task ids already on the panel: a new one makes room as it arrives. - const known = useRef | null>(null); - const morph = useRef(null); - const [toggled, setToggled] = useState(false); - - // In from the right edge with its first task (live only). - useLayoutEffect(() => { - const el = boxRef.current; - if (!shown || wasShown || !el || !settled.current || skipMotion()) return; - const a = el.animate([{ transform: "translateX(calc(100% + 1rem))" }, { transform: "none" }], { - duration: SLIDE_MS, - easing: SPRING, - }); - return () => a.cancel(); - // Only the panel's appearance moves it. - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [shown]); - - // The other half of a collapse / expand: the new shape pops out of the corner. - useLayoutEffect(() => { - if (!toggled) return; - setToggled(false); - const el = boxRef.current; - if (!el || skipMotion()) return; - el.style.transformOrigin = "100% 0"; - el.animate( - [ - { opacity: 0, transform: "scale(.35)" }, - { opacity: 1, transform: "none" }, - ], - { duration: MORPH_IN_MS, easing: SPRING }, - ); - }, [toggled]); - - useEffect(() => { - known.current = new Set((tasks ?? []).map((tk) => tk.id)); - }); - - if (!shown) return null; - const complete = done === total; - const accent = complete - ? "text-emerald-600 dark:text-emerald-400" - : inProgress - ? "text-amber-600 dark:text-amber-400" - : "text-primary"; - - const toggle = (next: boolean) => { - morph.current?.cancel(); - const el = boxRef.current; - if (!el || skipMotion()) { - setCollapsed(next); - return; - } - el.style.transformOrigin = "100% 0"; - const out = el.animate( - [ - { opacity: 1, transform: "none" }, - { opacity: 0, transform: "scale(.35)" }, - ], - { duration: MORPH_OUT_MS, easing: EASE_IN, fill: "forwards" }, - ); - morph.current = out; - out.finished.then(() => { - if (morph.current !== out) return; - morph.current = null; - setCollapsed(next); - setToggled(true); - }, () => {}); - }; - - // A task is "new" once the panel has been on screen: rows of a list that was - // there at load (or before the panel settled) are just there. - const isNew = (id: string) => !!settled.current && known.current != null && !known.current.has(id); - const live = !!settled.current; - - if (collapsed) { - return ( - - ); - } - - return ( -
    { - boxRef.current = el; - }} - className="pointer-events-auto w-56 max-w-[70vw] overflow-hidden rounded-xl border border-border bg-card/95 shadow-lg backdrop-blur" - > -
    - - {t("Tasks")} - - / - - -
    -
      - {tasks.map((tk) => ( - - ))} -
    -
    - ); -} diff --git a/frontend/src/business/conversations/components/ToolUse.tsx b/frontend/src/business/conversations/components/ToolUse.tsx index e56d9f07..249aee8d 100644 --- a/frontend/src/business/conversations/components/ToolUse.tsx +++ b/frontend/src/business/conversations/components/ToolUse.tsx @@ -21,6 +21,7 @@ import { useClipped } from "../fullText"; import { cardIcon, toolCardOf, + useToolCardsEpoch, toolCtx, toolDisplayName, type EditStat, @@ -238,6 +239,7 @@ function plays(item: ThreadItem, vis: Vis): boolean { export const ToolUse = memo(function ToolUse({ item, animate }: { item: ThreadItem; animate?: boolean }) { const factor = useAnimationSpeed(); const vis = useVis(); + useToolCardsEpoch(); // a plugin's declared card may come or go under a mounted row const card = toolCardOf(item); const c = toolCtx(item); const { inp } = c; @@ -422,11 +424,6 @@ const PHRASES: Record string, folded: (n: nu (d) => t("Published {detail}", { detail: d }), (n) => tn(n, "Published {n} artifact", "Published {n} artifacts"), ], - "Updated todos|list": [(d) => d, (n) => tn(n, "Updated todos {n} list", "Updated todos {n} lists")], - "Created|task": [(d) => tc("task", "Created {detail}", { detail: d }), (n) => tn(n, "Created {n} task", "Created {n} tasks")], - "Completed|task": [(d) => t("Completed {detail}", { detail: d }), (n) => tn(n, "Completed {n} task", "Completed {n} tasks")], - "Started|task": [(d) => t("Started {detail}", { detail: d }), (n) => tn(n, "Started {n} task", "Started {n} tasks")], - "Updated|task": [(d) => t("Updated {detail}", { detail: d }), (n) => tn(n, "Updated {n} task", "Updated {n} tasks")], "Stopped|task": [(d) => t("Stopped {detail}", { detail: d }), (n) => tn(n, "Stopped {n} task", "Stopped {n} tasks")], "Read|task output": [ (d) => tc("task output", "Read {detail}", { detail: d }), @@ -456,6 +453,8 @@ const PHRASES: Record string, folded: (n: nu /** `count` consecutive calls of one action, as a phrase. */ function phrase(a: ToolAction, count: number): string { + // A card a plugin declares brings its own wording. + if (a.phrase) return a.phrase(count); const p = PHRASES[`${a.verb}|${a.noun}`]; if (count === 1 && a.detail) return p ? p[0](a.detail) : `${a.verb} ${a.detail}`; if (p) return p[1](count); @@ -524,6 +523,7 @@ function ToolGroupImpl({ const vis = useVis(); const motion = useMotionOn(); const fades = useTransitions(); + useToolCardsEpoch(); // the line's wording follows the registered cards const line = summarize(items); // The lone row's label, shown for the first frame only, then retyped. const [morphed] = useState(() => morphFrom != null && !skipMotion()); diff --git a/frontend/src/business/conversations/pages/Conversation.tsx b/frontend/src/business/conversations/pages/Conversation.tsx index 0b610e5f..38572732 100644 --- a/frontend/src/business/conversations/pages/Conversation.tsx +++ b/frontend/src/business/conversations/pages/Conversation.tsx @@ -124,7 +124,7 @@ import { import { useConversationPluginTabs } from "@/business/plugins/components/ConversationPluginTabs"; import type { TabAddress } from "@/business/plugins/tabs"; import { useReplyRequests } from "@/business/conversations/replyRequests"; -import { bucketForTool, toolCardOf, type InThreadCard } from "@/business/conversations/toolCards/registry"; +import { bucketForTool, toolCardOf, useToolCardsEpoch, type InThreadCard } from "@/business/conversations/toolCards/registry"; import { CallCostProvider } from "@/business/conversations/components/CallCost"; import { DrawerOpenContext, useDrawerOpen } from "@/lib/drawerOpen"; import { useDesktop } from "@/lib/floating"; @@ -148,7 +148,7 @@ import { ResourceTags } from "@/business/conversations/components/ResourceTags"; import { SpawnedChildrenContext, } from "@/business/conversations/components/SpawnedConversations"; -import { TaskBadge, TaskPanel } from "@/business/conversations/components/TaskPanel"; +import { PluginTrackerPanels } from "@/business/plugins/components/PluginPanels"; import { BatchReveal } from "@/business/conversations/components/BatchReveal"; import { PluginBundleContext, @@ -227,9 +227,6 @@ const EMPTY_SLOTS: PluginUiSlot[] = []; */ const continuedFrom = new Set(); -// Task-list tool calls (TaskCreate/TaskUpdate, and the older TodoWrite). Their -// state is surfaced in the floating TaskPanel instead of inline in the thread, -// so we strip these cards out of the rendered conversation. /** * The side a live thread row comes in from (Gabriel's pick, 2026-11-03): * Claude's messages, tools and widgets from the left, yours from the right, a @@ -246,12 +243,14 @@ function rowFrom(b: ThreadItem | ThreadItem[]): RowEnter { /** How the cost chart names a bucket: its key, as it read before the neutral * tool names renamed two of them. */ -/** A task-list call (the Tasks panel's, left out of the thread). */ -function isTaskTool(it: ThreadItem): boolean { +/** A call the thread leaves out: a tool tracker's bookkeeping (the tasks + * plugin's task-list calls — its pill and panel show the list), unless the + * plugin's own switch draws them as rows. */ +function isLeftOut(it: ThreadItem): boolean { return ( (it.kind === "tool_use" || it.kind === "tool_result") && it.name != null && - !!toolCardOf(it).taskList?.(it) + !!toolCardOf(it).leftOut?.(it) ); } @@ -425,6 +424,7 @@ export function ConversationPane({ id, pane }: { id: string; pane: PaneCtl }) { // key, before the thread is grouped (grouping and the summary read the marks). // (A card whose own switch — its `vis` — is off doesn't take part.) const threadPluginCards = useVisiblePluginToolCards(); + const cardsEpoch = useToolCardsEpoch(); const pluginCardMarks = useMemo( () => planPluginThread(convo?.thread ?? [], threadPluginCards), [convo?.thread, threadPluginCards], @@ -446,7 +446,7 @@ export function ConversationPane({ id, pane }: { id: string; pane: PaneCtl }) { groupThread( (hoistForms ? hoistAgentForms(convo?.thread ?? []) : convo?.thread ?? []).filter( (it) => - !isTaskTool(it) && + !isLeftOut(it) && !hiddenByVis(it, vis) && !(it.script && codeCalls.has(it.script)) && // A Monitor on `ask-form wait` folds into its form card (the @@ -464,8 +464,9 @@ export function ConversationPane({ id, pane }: { id: string; pane: PaneCtl }) { // (the commits plugin's stack). (it) => (isPluginThreadCard(it, vis) ? pluginStackKeyOf(it) : null), ), - // pluginCardMarks: the marks isPluginThreadCard reads. - [convo?.thread, vis, hoistForms, notifInThread, codeCalls, pluginCardMarks], + // pluginCardMarks: the marks isPluginThreadCard reads; cardsEpoch: the + // cards a plugin declares (which calls the thread leaves out). + [convo?.thread, vis, hoistForms, notifInThread, codeCalls, pluginCardMarks, cardsEpoch], ); // Still catching up (opened, switched to, back after being away) until its @@ -1422,10 +1423,11 @@ export function ConversationPane({ id, pane }: { id: string; pane: PaneCtl }) { {/* The plugins' tabs: hidden until one is the view — then it fills the pane (ConversationPluginTabs). */} {tabs.frames} - {/* Floating task checklist, pinned top-right over the thread. */} - {convo && vis.taskPanel && !tabOn && ( -
    - + {/* The plugins' floating checklists (`ui.panels[]` — the tasks + plugin's Tasks panel), pinned top-right over the thread. */} + {convo && !tabOn && ( +
    +
    )} @@ -2331,7 +2333,8 @@ function MetaTags({ - + {/* The plugins' progress pills (a checklist bit — the tasks plugin's). */} + {showModel && } {showEffort && } @@ -2342,7 +2345,7 @@ function MetaTags({ {/* The plugins' pills (`ui.card[]`, place `tags`) — the worktrees plugin's, a local run's energy: what the cards show, here too. */} - +
    ); } diff --git a/frontend/src/business/conversations/pages/ConversationPage.tsx b/frontend/src/business/conversations/pages/ConversationPage.tsx index 8f102b15..435bd538 100644 --- a/frontend/src/business/conversations/pages/ConversationPage.tsx +++ b/frontend/src/business/conversations/pages/ConversationPage.tsx @@ -21,6 +21,7 @@ import { type PaneCtl, } from "../split"; import { ConversationPane } from "./Conversation"; +import { useTrackerToolCards } from "@/business/plugins/trackerCards"; /** * The `/conversation/*` route: one conversation, or up to three side by side @@ -35,6 +36,8 @@ import { ConversationPane } from "./Conversation"; * with a tab strip to switch. */ export function Conversation() { + // The tool cards the active plugins declare (the tasks plugin's `todo`). + useTrackerToolCards(); const { ids, focused, go } = useSplitNav(); const navigate = useNavigate(); const location = useLocation(); diff --git a/frontend/src/business/conversations/pages/Conversations.tsx b/frontend/src/business/conversations/pages/Conversations.tsx index cf163e44..a606feaa 100644 --- a/frontend/src/business/conversations/pages/Conversations.tsx +++ b/frontend/src/business/conversations/pages/Conversations.tsx @@ -43,7 +43,6 @@ import { CardTitle } from "@/business/conversations/components/CardTitle"; import { useSendFailed } from "@/lib/outbox"; import { ResourceTags, hasBranchResource } from "@/business/conversations/components/ResourceTags"; import { resourceSearchText } from "@/lib/resources"; -import { TaskBadge } from "@/business/conversations/components/TaskPanel"; import { CompletionStamp } from "@/business/conversations/components/CompletionStamp"; import type { ConversationSummary } from "@/types"; import { Roll, DurationRoll } from "@/technical/Roll"; @@ -395,7 +394,7 @@ function ConversationCard({ - + {/* Subagents in flight — only meaningful while the run is live; a Task call left open by an interrupted run isn't a running agent. */} {running && } @@ -403,7 +402,7 @@ function ConversationCard({ {running && } - + diff --git a/frontend/src/business/conversations/toolCards/core.tsx b/frontend/src/business/conversations/toolCards/core.tsx index e3deab78..9fb93b88 100644 --- a/frontend/src/business/conversations/toolCards/core.tsx +++ b/frontend/src/business/conversations/toolCards/core.tsx @@ -6,7 +6,7 @@ * * A neutral name can cover several of a harness's tools whose cards differ * (Claude Code's Edit / MultiEdit / NotebookEdit are all `edit`): the card - * tells them apart by the call's input shape (`editShape`, `todoShape`, + * tells them apart by the call's input shape (`editShape`, * `shellTaskShape`), as the backend's fold does. A shape whose card is the * generic one returns undefined and falls back to it, so its row still reads * as the harness's own tool name (`item.native`). @@ -24,7 +24,6 @@ import { Sparkles, Search, Globe, - ListChecks, Activity, AlarmClock, ClipboardList, @@ -93,13 +92,13 @@ import { worktreeRowChip, } from "../components/AgentToolWidgets"; import { McpBadge, mcpCount, mcpDetail, parseMcpName } from "../components/McpNames"; -import { FieldsBody, Json, Output, SkillBody, SubagentLink, base, firstLine, str } from "./bodies"; +import { Json, Output, SkillBody, SubagentLink, base, firstLine, str } from "./bodies"; import { + GENERIC_TOOL_CARD, cardIcon, editShape, registerToolCard, shellTaskShape, - todoShape, toolCard, type Dict, type ToolCardSpec, @@ -478,47 +477,10 @@ reg("skill", { bucket: "skill", }); -reg("todo", { - icon: ListChecks, - label: ({ inp }) => { - switch (todoShape(inp)) { - case "list": - return { verb: tc("tool", "Updated todos"), detail: "" }; - case "create": - return { verb: tc("tool", "New task"), detail: str(inp.subject) }; - case "update": - return { verb: tc("tool", "Task"), detail: `#${str(inp.taskId)} → ${str(inp.status)}` }; - default: - return undefined; - } - }, - action: ({ inp }) => { - switch (todoShape(inp)) { - case "list": - return { verb: "Updated todos", noun: "list", detail: "" }; - case "create": - return { verb: "Created", noun: "task", detail: str(inp.subject) }; - case "update": { - const s = str(inp.status); - const verb = s === "completed" ? "Completed" : s === "in_progress" ? "Started" : "Updated"; - return { verb, noun: "task", detail: `#${str(inp.taskId)}` }; - } - default: - return undefined; - } - }, - body: ({ inp, result, error }) => { - const shape = todoShape(inp); - return shape === "create" || shape === "update" ? : undefined; - }, - // The task list is the Tasks panel's: the thread leaves its calls out. - taskList: (item) => { - if (item.kind === "tool_result") return true; - const shape = todoShape((item.input ?? {}) as Dict); - return shape === "list" || shape === "create" || shape === "update"; - }, - bucket: "todo", -}); +// `todo` (a harness's task-list tool) has no card of its own: the tasks plugin +// declares one (`ui.toolCards[]` over its tracker — plugins/trackerCards.tsx), +// and without it a call is a plain row. Its cost bucket stays. +reg("todo", { icon: GENERIC_TOOL_CARD.icon, bucket: "todo" }); reg("ask_user", { icon: MessageCircleQuestion, diff --git a/frontend/src/business/conversations/toolCards/registry.test.tsx b/frontend/src/business/conversations/toolCards/registry.test.tsx index e3bbd7a6..ee51eed2 100644 --- a/frontend/src/business/conversations/toolCards/registry.test.tsx +++ b/frontend/src/business/conversations/toolCards/registry.test.tsx @@ -15,7 +15,6 @@ import { registerToolCard, shellTaskShape, stripHarness, - todoShape, toolCard, toolCtx, toolDisplayName, @@ -104,20 +103,12 @@ describe("one neutral name, several cards (by input shape)", () => { expect(screen.getByText(/"new_source": "x"/)).toBeInTheDocument(); // the generic body, as before }); - it("todo: a list snapshot, a new task, an update, a lookup, the list read back", () => { - expect(todoShape({ todos: [] })).toBe("list"); - expect(todoShape({ subject: "Ship it", description: "d" })).toBe("create"); - expect(todoShape({ taskId: "2", status: "completed" })).toBe("update"); - expect(todoShape({ taskId: "2" })).toBe("get"); - expect(todoShape({})).toBe("read"); - expect(toolRowLabel(call("todo", { todos: [] }))).toBe("Updated todos"); - expect(toolRowLabel(call("todo", { subject: "Ship it" }))).toBe("New task Ship it"); - expect(toolRowLabel(call("todo", { taskId: "2", status: "completed" }))).toBe("Task #2 → completed"); - expect(toolRowLabel(call("todo", { taskId: "2" }, { native: "TaskGet" }))).toBe("TaskGet"); - expect(toolRowLabel(call("todo", {}, { native: "TaskList" }))).toBe("TaskList"); - const card = toolCard("todo"); - expect(card.taskList!(call("todo", { subject: "x" }))).toBe(true); - expect(card.taskList!(call("todo", { taskId: "2" }))).toBe(false); + it("todo has no card of its own (the tasks plugin declares one): a plain row, its bucket kept", () => { + expect(toolRowLabel(call("todo", { subject: "Ship it" }, { native: "TaskCreate" }))).toBe("TaskCreate"); + expect(toolRowLabel(call("todo", { todos: [] }, { native: "TodoWrite" }))).toBe("TodoWrite"); + expect(iconOf(call("todo", {}))).toBe(Wrench); + expect(toolCard("todo").leftOut).toBeUndefined(); + expect(bucketForTool("todo")).toBe("todo"); }); it("shell_output / shell_kill: a background task's, or a shell's own", () => { diff --git a/frontend/src/business/conversations/toolCards/registry.ts b/frontend/src/business/conversations/toolCards/registry.ts index bdd69e82..a76bda46 100644 --- a/frontend/src/business/conversations/toolCards/registry.ts +++ b/frontend/src/business/conversations/toolCards/registry.ts @@ -17,10 +17,16 @@ * name.startsWith("mcp__linear__"), …)`), newest registration first, then the * generic card. Nothing in the thread switches on a tool name. * + * A plugin can also *declare* a card the app draws (`ui.toolCards[]` naming + * one of its tool trackers — `business/plugins/trackerCards.tsx`): it is + * registered here while the plugin is active, so the registry can change + * under a mounted thread — what reads it at render subscribes with + * {@link useToolCardsEpoch}. + * * This module holds no card and imports no widget, so any component can look * cards up without an import cycle; `core.tsx` is loaded by `ToolUse.tsx`. */ -import type { ReactNode } from "react"; +import { useSyncExternalStore, type ReactNode } from "react"; import { Wrench, type LucideIcon } from "lucide-react"; import type { SubagentRef, ThreadItem } from "@/types"; import type { VisKey } from "@/lib/visibility"; @@ -51,6 +57,9 @@ export interface ToolAction { verb: string; noun: string; detail: string; + /** Its own phrase for `count` consecutive calls (a card a plugin declares + * brings its wording) — instead of the `verb|noun` table's. */ + phrase?: (count: number) => string; } /** +N −M lines (and, for a shell call's diff, how many files). */ @@ -119,8 +128,9 @@ export interface ToolCardSpec { ownRow?: (item: ThreadItem) => boolean; /** The visibility switch that hides it from the thread ("Run-command calls"). */ hideWith?: (item: ThreadItem) => VisKey | null; - /** A task-list call: the thread leaves it out, the Tasks panel shows it. */ - taskList?: (item: ThreadItem) => boolean; + /** A call the thread leaves out: bookkeeping whose result shows elsewhere + * (a tool tracker's calls — its pill and panel show the list). */ + leftOut?: (item: ThreadItem) => boolean; /** Its cost bucket, for a turn the summary has no `turnBucket` for. */ bucket?: string; } @@ -136,6 +146,28 @@ const GENERIC = GENERIC_TOOL_CARD; const byName = new Map(); const matchers: { match: Matcher; spec: ToolCardSpec }[] = []; +// The registry's version: it moves with every registration, so a mounted +// thread redraws when a plugin's declared card comes or goes. +let epoch = 0; +const listeners = new Set<() => void>(); +const changed = () => { + epoch++; + listeners.forEach((f) => f()); +}; +const subscribe = (f: () => void) => { + listeners.add(f); + return () => { + listeners.delete(f); + }; +}; +const getEpoch = () => epoch; + +/** Re-render when a card is registered or removed (returns the version, for + * a memo's dependencies). */ +export function useToolCardsEpoch(): number { + return useSyncExternalStore(subscribe, getEpoch, getEpoch); +} + /** * Add (or replace) the card of a tool — by its exact neutral name, or by a * matcher over names. A later registration wins over an earlier one. @@ -145,17 +177,21 @@ export function registerToolCard(name: string | Matcher, spec: ToolCardSpec): () if (typeof name === "string") { const prev = byName.get(name); byName.set(name, spec); + changed(); return () => { if (byName.get(name) !== spec) return; if (prev) byName.set(name, prev); else byName.delete(name); + changed(); }; } const entry = { match: name, spec }; matchers.unshift(entry); + changed(); return () => { const i = matchers.indexOf(entry); if (i >= 0) matchers.splice(i, 1); + changed(); }; } @@ -216,17 +252,6 @@ export function editShape(inp: Dict): "single" | "multi" | "notebook" { return "single"; } -/** `todo`: a whole-list snapshot, one task's update, a task looked up, a - * task created, or the list read back. */ -export function todoShape(inp: Dict): "list" | "update" | "get" | "create" | "read" { - if (Array.isArray(inp.todos)) return "list"; - if (present(inp.taskId) || present(inp.task_id)) { - return Object.keys(inp).some((k) => k !== "taskId" && k !== "task_id") ? "update" : "get"; - } - if (present(inp.subject) || present(inp.content)) return "create"; - return "read"; -} - /** `shell_output` / `shell_kill`: about a background *task* (`task_id`), or * about a shell by its own id. */ export function shellTaskShape(inp: Dict): "task" | "shell" { diff --git a/frontend/src/business/plugins/api.ts b/frontend/src/business/plugins/api.ts index e14d6059..368aafc4 100644 --- a/frontend/src/business/plugins/api.ts +++ b/frontend/src/business/plugins/api.ts @@ -141,6 +141,10 @@ export interface PluginManifest { filePreviews?: Array<{ id: string; label: string; html: string; fileTypes: string[]; height?: number; vis?: PluginVisSpec }>; /** What the plugin adds to the conversation cards (lib/cardBits). */ card?: Array>; + /** Floating checklists of its tool trackers (drawn by the app). */ + panels?: Array>; + /** Its tool trackers' calls as thread rows (drawn by the app). */ + trackerCards?: Array>; } | null; webhooks?: Array<{ id: string; mode: string; description?: string; url?: string }>; actions?: Record; @@ -265,6 +269,50 @@ export interface PluginVisSpec { /** The host SSE event types a frame may ask for. */ export type PluginUiEvent = "askform" | "meta" | "transcript" | "usage"; +/** `ui.panels[]`: one of the plugin's tool trackers as a floating checklist + * (its items are the conversation's `meta.trackers[":"]`). */ +export interface PluginPanelSpec { + id: string; + tracker: string; + /** The panel's heading ("Tasks"). */ + title: string; + /** The collapsed pill's tooltip ("Show tasks"). */ + show: string; + vis?: PluginVisSpec; + pluginId: string; + pluginName: string; +} + +/** One op of a tool tracker (backend `plugins/trackers.py`): what a call's + * input must carry, as lists of alternative (dotted) field paths. */ +export interface TrackerOp { + do: "snapshot" | "update" | "create"; + items?: string[]; + id?: string[]; + name?: string[]; + status?: string[]; +} + +/** A `ui.toolCards[]` entry that names a `tracker`: the app draws that + * tracker's calls as rows — a verb per op, `many` ({count}) for a run of + * them folded in a group's line. With a `vis` switched off the thread leaves + * the calls out (the pill and the panel show their result). */ +export interface PluginTrackerCardSpec { + id: string; + tracker: string; + /** The neutral tool name the tracker reads (`todo`) and its ops. */ + tool: string; + ops: TrackerOp[]; + icon?: string; + create: string; + update: string; + snapshot: string; + many: string; + vis?: PluginVisSpec; + pluginId: string; + pluginName: string; +} + /** ThreadItem fields a tool card's `match.hasField` may require. */ export type PluginHasField = "deploy" | "commits" | "subagent" | "bashDiff" | "taskId"; @@ -530,6 +578,14 @@ export interface PluginsPayload { /** The active plugins' conversation card bits (`ui.card[]`), in plugin * order — `PluginCardBits.tsx`. Absent on an older hub. */ card?: CardBitSpec[]; + /** A tool tracker's checklist floating over the conversation's thread + * (`ui.panels[]`), drawn by the app — `PluginPanels.tsx`. Absent on an + * older hub. */ + panels?: PluginPanelSpec[]; + /** The calls a tool tracker reads, drawn by the app as thread rows + * (`ui.toolCards[]` naming a `tracker`) — `trackerCards.tsx`. Absent on + * an older hub. */ + trackerCards?: PluginTrackerCardSpec[]; /** Per plugin id: the per-person preferences its overlays read. */ prefs?: Record; /** The conversation resource kinds pills are drawn with (the owner's diff --git a/frontend/src/business/plugins/components/Checklist.tsx b/frontend/src/business/plugins/components/Checklist.tsx new file mode 100644 index 00000000..bddd04b2 --- /dev/null +++ b/frontend/src/business/plugins/components/Checklist.tsx @@ -0,0 +1,437 @@ +import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react"; +import { Check, ListChecks, Loader2, Minus, X } from "lucide-react"; +import { cn, fmtDateTime, fmtDuration, relTime } from "@/lib/utils"; +import { t } from "@/i18n"; +import { checklistCounts, type ChecklistTexts, type TrackedItem } from "@/lib/cardBits"; +import { Roll } from "@/technical/Roll"; +import { EASE_IN, EASE_OUT, ENTER_MS, ROOM_MS, SLIDE_MS, SPRING, popIn, skipMotion, useMotionOn, useSettled } from "@/technical/motion"; +import { usePrevious } from "@/technical/motionBits"; +import { PillPopover } from "@/technical/PillPopover"; + +/** + * A tool tracker's checklist, drawn by the app from a plugin's declarations + * (docs/plugins.md → "Checklists"): the progress pill of a `ui.card[]` list + * bit with `style: "checklist"` ({@link ChecklistPill}), and the floating + * panel of a `ui.panels[]` entry ({@link ChecklistPanel}). The tasks plugin's + * task list is the first one — these were the core's TaskBadge / TaskPanel. + * Every word comes from the declaration (`texts`, already translated). + */ + +/** The rows the pill's card shows before its list scrolls. */ +const CARD_ROWS = 8; + +/** The x/n colour: emerald once all done, amber while one runs. */ +function accentOf(complete: boolean, inProgress: number) { + return complete + ? "text-emerald-600 dark:text-emerald-400" + : inProgress + ? "text-amber-600 dark:text-amber-400" + : "text-primary"; +} + +/** + * Compact x/n progress pill, shown on conversation cards and in the + * conversation's header. Emits nothing when the list has no item left in the + * plan. Turns emerald once everything is done, amber while something is in + * progress, else its own colour (`rest`). Hovering it (tapping it, on a phone) + * opens the checklist — the floating panel's rows, in plan order, each with + * its times. + */ +export function ChecklistPill({ + items, + texts, + id, + rest = "bg-primary/10 text-primary", + className, +}: { + items?: readonly TrackedItem[] | null; + texts: ChecklistTexts; + /** `:` — the pill's and its card's data attributes. */ + id: string; + /** The pill's classes while nothing runs and something is left. */ + rest?: string; + className?: string; +}) { + const { total, done, inProgress } = checklistCounts(items); + if (total === 0) return null; + const complete = done === total; + const label = texts.progress.replace("{done}", String(done)).replace("{total}", String(total)); + return ( + + + / + + } + > + + + ); +} + +/** + * The checklist under its " x/n" heading — the floating panel's body + * and the pill's card. `trailing` sits at the heading's right (the panel's + * collapse button); `isNew` says which rows arrive while you watch. + */ +function ChecklistList({ + items, + texts, + total, + done, + inProgress, + card = false, + trailing, + isNew, + live = true, +}: { + items: readonly TrackedItem[]; + texts: ChecklistTexts; + total: number; + done: number; + inProgress: number; + card?: boolean; + trailing?: ReactNode; + isNew?: (id: string) => boolean; + live?: boolean; +}) { + const accent = accentOf(done === total, inProgress); + return ( + <> + <div className="flex items-center gap-1.5 border-b border-border px-2.5 py-1.5"> + <ListChecks className={cn("h-3.5 w-3.5", accent)} /> + <span className="text-[11px] font-semibold">{texts.title}</span> + <span className={cn("font-mono text-[10px] font-semibold tabular-nums", accent)}> + <Roll value={done} />/<Roll value={total} /> + </span> + {trailing} + </div> + <ul + data-popover-list + className={cn( + "space-y-px overflow-y-auto p-1.5", + card ? "overscroll-contain" : "max-h-[50vh]", + )} + > + {items.map((it) => ( + <ChecklistRow key={it.key} item={it} texts={texts} arrive={isNew?.(it.key) ?? false} live={live} times={card} /> + ))} + </ul> + </> + ); +} + +/** + * A single row: a status "checkbox" + its (tiny) name. Added while you watch + * (`arrive`), it makes room, then shows; done while you watch, its box fills + * with a pop and a strike draws across the name. + */ +function ChecklistRow({ + item, + texts, + arrive, + live, + times = false, +}: { + item: TrackedItem; + texts: ChecklistTexts; + arrive: boolean; + live: boolean; + times?: boolean; +}) { + const { status } = item; + const done = status === "completed"; + const cancelled = status === "cancelled"; + const active = status === "in_progress"; + const motion = useMotionOn(); + const rowRef = useRef<HTMLLIElement>(null); + const boxRef = useRef<HTMLSpanElement>(null); + const wasDone = usePrevious(done); + const justDone = done && !wasDone && live; + + useLayoutEffect(() => { + const li = rowRef.current; + if (!li || !arrive || skipMotion()) return; + const h = li.offsetHeight; + const pad = getComputedStyle(li); + const room = li.animate( + [ + { height: "0px", paddingTop: "0px", paddingBottom: "0px", opacity: 0 }, + { height: `${h}px`, paddingTop: pad.paddingTop, paddingBottom: pad.paddingBottom, opacity: 0 }, + ], + { duration: ROOM_MS, easing: EASE_OUT }, + ); + let show: Animation | null = null; + room.finished.then(() => { + show = li.animate([{ opacity: 0, transform: "translateY(-4px)" }, { opacity: 1, transform: "none" }], { + duration: ENTER_MS, + easing: EASE_OUT, + }); + }, () => {}); + return () => { + room.cancel(); + show?.cancel(); + }; + // Mount only: a row arrives once. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + useLayoutEffect(() => { + if (justDone && boxRef.current) popIn(boxRef.current); + }, [justDone]); + + return ( + <li ref={rowRef} data-popover-row className="flex items-start gap-1.5 overflow-hidden rounded px-1 py-[3px] text-[10px] leading-snug"> + {active ? ( + <Loader2 className="mt-[1px] h-3 w-3 shrink-0 animate-spin text-amber-500" /> + ) : ( + <span + ref={boxRef} + className={cn( + "mt-[1px] flex h-3 w-3 shrink-0 items-center justify-center rounded-[3px] border", + done + ? "border-emerald-500 bg-emerald-500 text-white" + : "border-muted-foreground/40 text-muted-foreground", + )} + > + {done && <Check className="h-2.5 w-2.5" strokeWidth={3.5} />} + {cancelled && <X className="h-2.5 w-2.5" strokeWidth={3} />} + </span> + )} + <span + className={cn( + "min-w-0 flex-1", + active && "font-medium text-foreground", + done && "text-muted-foreground", + cancelled && "text-muted-foreground/70 line-through", + !active && !done && !cancelled && "text-foreground/90", + motion && live && "transition-colors duration-300", + )} + > + {/* The strike is a line drawn under the text (an inline background, + so it follows a name over two lines), sized to 0 → 100 %. */} + <span + className={cn( + "bg-no-repeat [background-image:linear-gradient(currentColor,currentColor)] [background-position:0_55%]", + motion && live && "transition-[background-size] delay-150 duration-300 ease-out", + )} + style={{ backgroundSize: done ? "100% 1px" : "0% 1px" }} + > + {item.name} + </span> + {times && <ChecklistTimes item={item} texts={texts} />} + </span> + </li> + ); +} + +/** + * When an item was added, started and done (or cancelled), and how long it + * took — from its first start, else from when it was added. A list read + * before the times existed has none: nothing shows. + */ +function ChecklistTimes({ item, texts }: { item: TrackedItem; texts: ChecklistTexts }) { + const { openedAt: createdAt, startedAt, closedAt: endedAt, status } = item; + const when = (tpl: string, at: string) => tpl.replace("{when}", relTime(at)); + if (!createdAt && !startedAt && !endedAt) return null; + const from = startedAt ?? createdAt; + const took = endedAt && from ? new Date(endedAt).getTime() - new Date(from).getTime() : null; + const parts: { key: string; text: string; at: string }[] = []; + if (createdAt) parts.push({ key: "c", text: when(texts.added, createdAt), at: createdAt }); + if (startedAt && !endedAt) parts.push({ key: "s", text: when(texts.started, startedAt), at: startedAt }); + if (endedAt) + parts.push({ + key: "e", + text: when(status === "cancelled" ? texts.cancelled : texts.done, endedAt), + at: endedAt, + }); + // inline-block: a cancelled row's line-through stays on its subject. + return ( + <span className="mt-px inline-block w-full text-[9.5px] font-normal text-muted-foreground"> + {parts.map((p, i) => ( + <span key={p.key} title={fmtDateTime(p.at)}> + {i > 0 && " · "} + {p.text} + </span> + ))} + {took != null && took >= 0 && status === "completed" && ` · ${texts.took.replace("{time}", fmtDuration(took))}`} + </span> + ); +} + +/** Collapse ↔ expand: the card shrinks into the corner, then the pill pops out of it (and back). */ +const MORPH_OUT_MS = 200; +const MORPH_IN_MS = 320; + +/** Where a panel's collapsed state is kept, per device. The tasks plugin's + * panel keeps the key the core's Tasks panel had. */ +const collapsedKey = (id: string) => + id === "tasks:tasks" ? "ai-agent:tasks-collapsed" : `ai-agent:panel-collapsed:${id}`; + +/** + * Floating checklist for the conversation detail view — a small card pinned + * top-right of the thread showing each item with a status checkbox in tiny + * text. Collapses to a single pill showing x/n (persisted per device and + * panel). Renders nothing when the conversation's list is empty. + * + * Its first item while you watch slides it in from the right edge; an item + * added later makes room, then shows; one done fills its box and strikes + * through; collapsing shrinks the card toward the corner and the pill pops + * out of it (and back). What was there when the page loaded is just there. + */ +export function ChecklistPanel({ + items, + texts, + show, + id, +}: { + items?: readonly TrackedItem[] | null; + texts: ChecklistTexts; + /** The collapsed pill's tooltip ("Show tasks"). */ + show: string; + /** `<pluginId>:<panel id>`. */ + id: string; +}) { + const { total, done, inProgress } = checklistCounts(items); + const [collapsed, setCollapsed] = useState(() => localStorage.getItem(collapsedKey(id)) === "1"); + useEffect(() => { + localStorage.setItem(collapsedKey(id), collapsed ? "1" : "0"); + }, [collapsed, id]); + const settled = useSettled(); + const boxRef = useRef<HTMLElement | null>(null); + const shown = total > 0 && !!items; + const wasShown = usePrevious(shown); + // The keys already on the panel: a new one makes room as it arrives. + const known = useRef<Set<string> | null>(null); + const morph = useRef<Animation | null>(null); + const [toggled, setToggled] = useState(false); + + // In from the right edge with its first item (live only). + useLayoutEffect(() => { + const el = boxRef.current; + if (!shown || wasShown || !el || !settled.current || skipMotion()) return; + const a = el.animate([{ transform: "translateX(calc(100% + 1rem))" }, { transform: "none" }], { + duration: SLIDE_MS, + easing: SPRING, + }); + return () => a.cancel(); + // Only the panel's appearance moves it. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [shown]); + + // The other half of a collapse / expand: the new shape pops out of the corner. + useLayoutEffect(() => { + if (!toggled) return; + setToggled(false); + const el = boxRef.current; + if (!el || skipMotion()) return; + el.style.transformOrigin = "100% 0"; + el.animate( + [ + { opacity: 0, transform: "scale(.35)" }, + { opacity: 1, transform: "none" }, + ], + { duration: MORPH_IN_MS, easing: SPRING }, + ); + }, [toggled]); + + useEffect(() => { + known.current = new Set((items ?? []).map((it) => it.key)); + }); + + if (!shown) return null; + const accent = accentOf(done === total, inProgress); + + const toggle = (next: boolean) => { + morph.current?.cancel(); + const el = boxRef.current; + if (!el || skipMotion()) { + setCollapsed(next); + return; + } + el.style.transformOrigin = "100% 0"; + const out = el.animate( + [ + { opacity: 1, transform: "none" }, + { opacity: 0, transform: "scale(.35)" }, + ], + { duration: MORPH_OUT_MS, easing: EASE_IN, fill: "forwards" }, + ); + morph.current = out; + out.finished.then(() => { + if (morph.current !== out) return; + morph.current = null; + setCollapsed(next); + setToggled(true); + }, () => {}); + }; + + // An item is "new" once the panel has been on screen: rows of a list that was + // there at load (or before the panel settled) are just there. + const isNew = (key: string) => !!settled.current && known.current != null && !known.current.has(key); + const live = !!settled.current; + + if (collapsed) { + return ( + <button + ref={(el) => { + boxRef.current = el; + }} + onClick={() => toggle(false)} + title={show} + data-checklist-panel={id} + className="pointer-events-auto flex items-center gap-1 rounded-full border border-border bg-card/95 px-2 py-1 text-[11px] font-semibold tabular-nums shadow-md backdrop-blur transition-colors hover:bg-accent" + > + <ListChecks className={cn("h-3.5 w-3.5", accent)} /> + <span className={accent}> + <Roll value={done} />/<Roll value={total} /> + </span> + </button> + ); + } + + return ( + <div + ref={(el) => { + boxRef.current = el; + }} + data-checklist-panel={id} + className="pointer-events-auto w-56 max-w-[70vw] overflow-hidden rounded-xl border border-border bg-card/95 shadow-lg backdrop-blur" + > + <ChecklistList + items={items!} + texts={texts} + total={total} + done={done} + inProgress={inProgress} + isNew={isNew} + live={live} + trailing={ + <button + onClick={() => toggle(true)} + title={t("Collapse")} + className="ml-auto flex h-5 w-5 items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground" + > + <Minus className="h-3.5 w-3.5" /> + </button> + } + /> + </div> + ); +} diff --git a/frontend/src/business/plugins/components/PluginCardBits.tsx b/frontend/src/business/plugins/components/PluginCardBits.tsx index b2d2a13b..784a2326 100644 --- a/frontend/src/business/plugins/components/PluginCardBits.tsx +++ b/frontend/src/business/plugins/components/PluginCardBits.tsx @@ -1,5 +1,4 @@ -import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; -import { createPortal } from "react-dom"; +import { useCallback, useMemo } from "react"; import { Link } from "react-router-dom"; import { AlertTriangle, @@ -14,6 +13,7 @@ import { GitBranch, Laptop, Leaf, + ListChecks, Server, Shield, Sparkles, @@ -29,19 +29,23 @@ import { t } from "@/i18n"; import { isOn, useVisibility, type PluginVisKey } from "@/lib/visibility"; import { pluginT } from "@/i18n/plugins"; import { + CARD_CHECKLIST_TEXTS, cardBitsFor, type CardBit, type CardBitSpec, type CardListSpec, + type ChecklistTexts, type CardPlace, type CardSubject, type CardTone, type TrackedItem, } from "@/lib/cardBits"; +import { PillPopover } from "@/technical/PillPopover"; import { usePluginsUi } from "../api"; +import { ChecklistPill } from "./Checklist"; /** The icons a bit may name (`ui.card[].icon`) — the backend's `CARD_ICONS`. */ -const ICONS: Record<string, LucideIcon> = { +export const CARD_ICONS: Record<string, LucideIcon> = { "alert-triangle": AlertTriangle, battery: Battery, bot: Bot, @@ -54,6 +58,7 @@ const ICONS: Record<string, LucideIcon> = { "git-branch": GitBranch, laptop: Laptop, leaf: Leaf, + "list-checks": ListChecks, server: Server, shield: Shield, sparkles: Sparkles, @@ -162,10 +167,6 @@ const LIST_ICON: Record<CardTone, string> = { rose: "text-rose-500", }; -/** Space between a list pill and its card, in px. */ -const CARD_GAP = 4; -/** The card's closest approach to a viewport edge, in px. */ -const CARD_EDGE = 8; /** Rows the card shows before its list scrolls. */ const LIST_ROWS = 5; @@ -255,7 +256,7 @@ function ListRow({ ? fmtDuration(new Date(it.closedAt).getTime() - new Date(it.openedAt).getTime()) : null; return ( - <span data-list-row className="flex flex-col gap-0.5" title={it.key}> + <span data-popover-row className="flex flex-col gap-0.5" title={it.key}> <span className="flex items-center gap-1.5 text-[11px] font-medium"> {Icon && ( <Icon className={cn("h-3 w-3 shrink-0", it.closedAt ? "text-muted-foreground" : LIST_ICON[tone])} /> @@ -301,169 +302,89 @@ function ListRow({ */ function ListBitPill({ bit, className }: { bit: CardBit; className?: string }) { const items = bit.items!; - const list = bit.spec.list!; + const list = bit.spec.list as CardListSpec; const tone = bit.spec.tone ?? "muted"; - const Icon = bit.spec.icon ? ICONS[bit.spec.icon] : undefined; + const Icon = bit.spec.icon ? CARD_ICONS[bit.spec.icon] : undefined; const pid = bit.spec.pluginId; const tr = useCallback((s: string) => pluginT(pid, s), [pid]); - const anchorRef = useRef<HTMLSpanElement>(null); - const cardRef = useRef<HTMLSpanElement>(null); - const listRef = useRef<HTMLSpanElement>(null); - const hideTimer = useRef<ReturnType<typeof setTimeout>>(); - const lastPointer = useRef("mouse"); - // The pill's rect while the card is open; where the card lands is worked out - // from its measured size once it has rendered (hidden) — see below. - const [anchor, setAnchor] = useState<DOMRect | null>(null); - const [place, setPlace] = useState<{ top: number; left: number; maxH: number } | null>(null); - - const show = useCallback(() => { - clearTimeout(hideTimer.current); - const rect = anchorRef.current?.getBoundingClientRect(); - if (rect) setAnchor(rect); - }, []); - const hide = useCallback(() => { - hideTimer.current = setTimeout(() => { - setAnchor(null); - setPlace(null); - }, 100); - }, []); - - // Place the card inside the viewport: right-aligned under the pill, shifted - // sideways when that would cross an edge (a pill in the left panel used to - // push it off the left of the screen), and flipped above the pill when there - // is more room there. Past LIST_ROWS rows its list scrolls instead. - useLayoutEffect(() => { - const card = cardRef.current; - if (!anchor || !card) return; - const el = listRef.current; - if (el) { - // The rows sit inside per-group boxes; the list is their offsetParent. - const last = el.querySelectorAll<HTMLElement>("[data-list-row]")[LIST_ROWS - 1]; - el.style.maxHeight = - items.length > LIST_ROWS && last ? `${last.offsetTop + last.offsetHeight}px` : ""; - } - const w = card.offsetWidth; - const h = card.offsetHeight; - const vw = window.innerWidth; - const vh = window.innerHeight; - const left = Math.max(CARD_EDGE, Math.min(anchor.right - w, vw - w - CARD_EDGE)); - const below = vh - anchor.bottom - CARD_GAP - CARD_EDGE; - const above = anchor.top - CARD_GAP - CARD_EDGE; - setPlace( - h <= below || below >= above - ? { left, top: anchor.bottom + CARD_GAP, maxH: below } - : { left, top: Math.max(CARD_EDGE, anchor.top - CARD_GAP - h), maxH: above }, - ); - }, [anchor, items]); - - // The card is open above a scroll container: close it on scroll/resize so it - // never drifts away from the pill it's anchored to — but not when the scroll - // is the card's own list. A tap anywhere else closes it too (a touch has no - // pointer-leave to do it). - useEffect(() => { - if (!anchor) return; - const onScroll = (e: Event) => { - if (cardRef.current?.contains(e.target as Node)) return; - hide(); - }; - const onDown = (e: PointerEvent) => { - const node = e.target as Node; - if (anchorRef.current?.contains(node) || cardRef.current?.contains(node)) return; - hide(); - }; - window.addEventListener("scroll", onScroll, true); - window.addEventListener("resize", hide); - document.addEventListener("pointerdown", onDown, true); - return () => { - window.removeEventListener("scroll", onScroll, true); - window.removeEventListener("resize", hide); - document.removeEventListener("pointerdown", onDown, true); - }; - }, [anchor, hide]); - - useEffect(() => () => clearTimeout(hideTimer.current), []); - const allClosed = items.every((it) => it.closedAt); const single = items.length === 1 ? items[0] : null; return ( - <span - ref={anchorRef} - data-card-bit={`${pid}:${bit.spec.id}`} - className={cn("relative inline-flex", className)} - // Hover is a mouse's; a touch taps the pill instead (below). - onPointerEnter={(e) => e.pointerType === "mouse" && show()} - onPointerLeave={(e) => e.pointerType === "mouse" && hide()} - onPointerDown={(e) => (lastPointer.current = e.pointerType)} - onClick={(e) => { - // On a phone the pill is a button: it toggles the card instead of - // opening the conversation the card around it links to. - if (lastPointer.current === "mouse") return; - e.preventDefault(); - e.stopPropagation(); - if (anchor) hide(); - else show(); - }} + <PillPopover + className={className} + rows={LIST_ROWS} + anchorProps={{ "data-card-bit": `${pid}:${bit.spec.id}` }} + cardProps={{ "data-card-bit-list": `${pid}:${bit.spec.id}` }} + pill={ + <span + className={cn( + "inline-flex items-center gap-1 rounded-full px-1.5 py-0.5 text-[10px] font-medium", + allClosed ? "bg-muted text-muted-foreground" : LIST_PILL[tone], + )} + > + {Icon && <Icon className="h-2.5 w-2.5" />} + <span className={cn(single?.closedAt && "line-through opacity-80")}>{bit.text}</span> + </span> + } > + {/* One timeline row per item, under its group's heading. */} <span + data-popover-list className={cn( - "inline-flex items-center gap-1 rounded-full px-1.5 py-0.5 text-[10px] font-medium", - allClosed ? "bg-muted text-muted-foreground" : LIST_PILL[tone], + "relative flex flex-col gap-2.5", + items.length > LIST_ROWS && "overflow-y-auto overscroll-contain pr-1", )} > - {Icon && <Icon className="h-2.5 w-2.5" />} - <span className={cn(single?.closedAt && "line-through opacity-80")}>{bit.text}</span> + {byGroup(items).map(({ group, list: rows }) => ( + <span key={group ?? ""} className="flex flex-col gap-1.5"> + <ListGroupHeader group={group} count={rows.length} list={list} tr={tr} /> + {rows.map((it) => ( + <ListRow key={it.key} it={it} list={list} tone={tone} Icon={Icon} tr={tr} /> + ))} + </span> + ))} </span> - {/* The card — one timeline row per item. Portaled to <body> and - positioned from the pill's own bounding rect (fixed, viewport coords) - so it escapes any ancestor's overflow clipping instead of being - cropped by the scroll container it lives in. Rendered hidden first, - so the layout effect can measure it before placing it. */} - {anchor && - typeof document !== "undefined" && - createPortal( - <span - ref={cardRef} - data-card-bit-list={`${pid}:${bit.spec.id}`} - className="fixed z-50 flex w-max max-w-[min(18rem,calc(100vw-1rem))] flex-col overflow-y-auto - rounded-lg border border-border bg-card p-2.5 text-left shadow-xl" - style={ - place - ? { top: place.top, left: place.left, maxHeight: place.maxH } - : { top: 0, left: 0, visibility: "hidden" } - } - onPointerEnter={(e) => e.pointerType === "mouse" && show()} - onPointerLeave={(e) => e.pointerType === "mouse" && hide()} - // React bubbles a portal's events to the pill's ancestors: keep a - // click in the card (a group's link, a stray tap) from also opening - // the conversation card or toggling this card shut. - onClick={(e) => e.stopPropagation()} - > - <span - ref={listRef} - className={cn( - "relative flex flex-col gap-2.5", - items.length > LIST_ROWS && "overflow-y-auto overscroll-contain pr-1", - )} - > - {byGroup(items).map(({ group, list: rows }) => ( - <span key={group ?? ""} className="flex flex-col gap-1.5"> - <ListGroupHeader group={group} count={rows.length} list={list} tr={tr} /> - {rows.map((it) => ( - <ListRow key={it.key} it={it} list={list} tone={tone} Icon={Icon} tr={tr} /> - ))} - </span> - ))} - </span> - </span>, - document.body, - )} - </span> + </PillPopover> + ); +} + +/** A plugin's wording of a checklist, in the reader's language: what it + * declares, else `fallback`, through its own dictionary. */ +export function checklistTexts( + pluginId: string, + src: Partial<ChecklistTexts>, + fallback: ChecklistTexts, +): ChecklistTexts { + const out = {} as ChecklistTexts; + for (const k of CARD_CHECKLIST_TEXTS) out[k] = pluginT(pluginId, src[k] ?? fallback[k]); + return out; +} + +/** + * A checklist bit (`list.style: "checklist"`) — the progress pill of a tool + * tracker's list (the tasks plugin: `✓ 2/5`), which opens the checklist. In + * the bit's tone while nothing runs; amber while an item is in progress, + * emerald once all are done. + */ +function ChecklistBitPill({ bit, className }: { bit: CardBit; className?: string }) { + const spec = bit.spec; + const list = spec.list as ChecklistTexts; + const texts = checklistTexts(spec.pluginId, list, list); + return ( + <ChecklistPill + items={bit.items} + texts={texts} + id={`${spec.pluginId}:${spec.id}`} + rest={LIST_PILL[spec.tone ?? "primary"]} + className={className} + /> ); } function BitPill({ bit, className }: { bit: CardBit; className?: string }) { + if (bit.items && bit.spec.list?.style === "checklist") return <ChecklistBitPill bit={bit} className={className} />; if (bit.items) return <ListBitPill bit={bit} className={className} />; - const Icon = bit.spec.icon ? ICONS[bit.spec.icon] : undefined; + const Icon = bit.spec.icon ? CARD_ICONS[bit.spec.icon] : undefined; const tone = bit.spec.tone ?? "muted"; return ( <span @@ -482,23 +403,32 @@ function BitPill({ bit, className }: { bit: CardBit; className?: string }) { ); } +/** A progress pill (a checklist bit): it leads the tags, where the core's + * tasks badge stood, so it isn't the first thing folded behind +N. */ +const leads = (b: CardBit) => b.spec.list?.style === "checklist"; + /** * The bits a plugin draws at one place of a conversation card (`tags`, `cost`, * `foot`). Renders its pills as siblings — inside `TagRows` each is one more - * pill to fold. + * pill to fold. The tags come in two calls: `lead` draws the progress pills + * (checklists) early in the row, the call without it the rest. */ export function CardBits({ c, place, specs, + lead, className, }: { c: CardSubject; place: Exclude<CardPlace, "border" | "corner">; specs: CardBitSpec[]; + /** `tags` only: true = the progress pills alone, false = every other bit. */ + lead?: boolean; className?: string; }) { - const bits = useCardBits(c, place, specs); + const all = useCardBits(c, place, specs); + const bits = lead === undefined ? all : all.filter((b) => leads(b) === lead); if (!bits.length) return null; return ( <> @@ -516,7 +446,7 @@ export function CardBits({ export function CardCornerBit({ c, specs }: { c: CardSubject; specs: CardBitSpec[] }) { const bit = useCardBits(c, "corner", specs)[0]; if (!bit) return null; - const Icon = bit.spec.icon ? ICONS[bit.spec.icon] : undefined; + const Icon = bit.spec.icon ? CARD_ICONS[bit.spec.icon] : undefined; return ( <span data-card-bit={`${bit.spec.pluginId}:${bit.spec.id}`} diff --git a/frontend/src/business/plugins/components/PluginPanels.test.tsx b/frontend/src/business/plugins/components/PluginPanels.test.tsx new file mode 100644 index 00000000..7172766f --- /dev/null +++ b/frontend/src/business/plugins/components/PluginPanels.test.tsx @@ -0,0 +1,83 @@ +import { fireEvent, render, screen } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import type { TrackedItem } from "@/lib/cardBits"; +import { renameKeys, useVisibility } from "@/lib/visibility"; +import type { PluginPanelSpec } from "../api"; +import { PluginTrackerPanels } from "./PluginPanels"; + +/** The tasks plugin's panel, as `/api/plugins` hands it out. */ +const PANEL: PluginPanelSpec = { + id: "tasks", + tracker: "tasks", + title: "Tasks", + show: "Show tasks", + vis: { key: "panel", label: "Task panel", hint: "" }, + pluginId: "tasks", + pluginName: "Tasks", +}; +let panels: PluginPanelSpec[] | undefined = [PANEL]; +vi.mock("../api", async (orig) => ({ + ...(await orig<typeof import("../api")>()), + usePluginsUi: () => ({ data: panels ? { ui: { panels } } : undefined }), +})); + +const TASKS: TrackedItem[] = [ + { key: "1", name: "Map the API", status: "completed", openedAt: "2026-11-01T10:00:00Z" }, + { key: "2", name: "Seed it", status: "in_progress" }, + { key: "3", name: "Dropped", status: "cancelled" }, +]; +const conv = (items: TrackedItem[] | null) => ({ meta: { trackers: items ? { "tasks:tasks": items } : null } }); + +describe("a plugin's floating checklist (ui.panels[])", () => { + beforeEach(() => { + panels = [PANEL]; + localStorage.clear(); + useVisibility.setState({ hidden: [], shown: [] }); + }); + + it("lists the conversation's items under the plugin's title, x/n without the cancelled", () => { + const { container } = render(<PluginTrackerPanels c={conv(TASKS)} />); + expect(screen.getByText("Tasks")).toBeInTheDocument(); + expect(screen.getByText("Map the API")).toBeInTheDocument(); + expect(screen.getByText("Dropped")).toBeInTheDocument(); + expect(container.querySelector("[data-checklist-panel='tasks:tasks']")!.textContent).toContain("1/2"); + // the panel's rows carry no times (the pill's card does) + expect(screen.queryByText(/added /)).toBeNull(); + }); + + it("nothing without items, without a plugin, or with its switch off", () => { + const { container, rerender } = render(<PluginTrackerPanels c={conv(null)} />); + expect(container.innerHTML).toBe(""); + rerender(<PluginTrackerPanels c={conv([TASKS[2]])} />); // all cancelled + expect(container.innerHTML).toBe(""); + panels = undefined; + rerender(<PluginTrackerPanels c={conv(TASKS)} />); + expect(container.innerHTML).toBe(""); + panels = [PANEL]; + useVisibility.setState({ hidden: ["plugin:tasks:panel"], shown: [] }); + rerender(<PluginTrackerPanels c={conv(TASKS)} />); + expect(container.innerHTML).toBe(""); + }); + + it("collapses to a pill and remembers it where the core's Tasks panel did", () => { + const { unmount } = render(<PluginTrackerPanels c={conv(TASKS)} />); + fireEvent.click(screen.getByTitle("Collapse")); + expect(screen.queryByText("Map the API")).toBeNull(); + expect(screen.getByTitle("Show tasks")).toBeInTheDocument(); + expect(localStorage.getItem("ai-agent:tasks-collapsed")).toBe("1"); + unmount(); + render(<PluginTrackerPanels c={conv(TASKS)} />); + expect(screen.getByTitle("Show tasks")).toBeInTheDocument(); // still collapsed + fireEvent.click(screen.getByTitle("Show tasks")); + expect(screen.getByText("Map the API")).toBeInTheDocument(); + }); +}); + +describe("a core switch that became a plugin's keeps its state", () => { + it("a hidden Task panel hides the tasks plugin's panel", () => { + expect(renameKeys(["taskPanel", "cost"])).toEqual(["plugin:tasks:panel", "cost"]); + expect(renameKeys(["taskPanel", "plugin:tasks:panel"])).toEqual(["plugin:tasks:panel"]); + expect(renameKeys(undefined)).toEqual([]); + }); +}); diff --git a/frontend/src/business/plugins/components/PluginPanels.tsx b/frontend/src/business/plugins/components/PluginPanels.tsx new file mode 100644 index 00000000..a2771a3c --- /dev/null +++ b/frontend/src/business/plugins/components/PluginPanels.tsx @@ -0,0 +1,54 @@ +import { useMemo } from "react"; + +import { pluginT } from "@/i18n/plugins"; +import { CHECKLIST_DEFAULTS, type CardSubject } from "@/lib/cardBits"; +import { useVisibility } from "@/lib/visibility"; +import { usePluginsUi, type PluginPanelSpec } from "../api"; +import { ChecklistPanel } from "./Checklist"; +import { checklistTexts } from "./PluginCardBits"; +import { toolCardVisible } from "./PluginToolCard"; + +const NONE: PluginPanelSpec[] = []; + +/** The active plugins' panels (`ui.panels[]`) whose switch is on. */ +export function useVisiblePanels(): PluginPanelSpec[] { + const panels = usePluginsUi().data?.ui.panels; + const hidden = useVisibility((s) => s.hidden); + const shown = useVisibility((s) => s.shown); + return useMemo( + () => (panels?.length ? panels.filter((p) => toolCardVisible({ hidden, shown }, p)) : NONE), + [panels, hidden, shown], + ); +} + +function Panel({ spec, c }: { spec: PluginPanelSpec; c: CardSubject }) { + const items = c.meta?.trackers?.[`${spec.pluginId}:${spec.tracker}`]; + const texts = checklistTexts(spec.pluginId, { title: spec.title }, CHECKLIST_DEFAULTS); + return ( + <ChecklistPanel + items={items} + texts={texts} + show={pluginT(spec.pluginId, spec.show)} + id={`${spec.pluginId}:${spec.id}`} + /> + ); +} + +/** + * The floating checklists over a conversation's thread — one per `ui.panels[]` + * entry of an active plugin (docs/plugins.md → "Checklists"): a tool + * tracker's list of this conversation (`meta.trackers`), drawn by the app. A + * panel whose list is empty takes no room. Place it in the thread's top-right + * corner box. + */ +export function PluginTrackerPanels({ c }: { c: CardSubject }) { + const panels = useVisiblePanels(); + if (!panels.length) return null; + return ( + <> + {panels.map((p) => ( + <Panel key={`${p.pluginId}:${p.id}`} spec={p} c={c} /> + ))} + </> + ); +} diff --git a/frontend/src/business/plugins/components/PluginToolCard.tsx b/frontend/src/business/plugins/components/PluginToolCard.tsx index f463450c..68d60730 100644 --- a/frontend/src/business/plugins/components/PluginToolCard.tsx +++ b/frontend/src/business/plugins/components/PluginToolCard.tsx @@ -75,7 +75,7 @@ export function matchToolCard(cards: readonly PluginToolCardDesc[], item: Thread /** Whether a card's own switch (`vis`) is on — no `vis`: always. */ export function toolCardVisible( s: { hidden: readonly string[]; shown: readonly string[] }, - tc: PluginToolCardDesc, + tc: { pluginId: string; vis?: { key: string; defaultOff?: boolean } | null }, ): boolean { if (!tc.vis) return true; return isOn( diff --git a/frontend/src/business/plugins/trackerCards.test.tsx b/frontend/src/business/plugins/trackerCards.test.tsx new file mode 100644 index 00000000..5d454392 --- /dev/null +++ b/frontend/src/business/plugins/trackerCards.test.tsx @@ -0,0 +1,137 @@ +import { act, render, renderHook, screen } from "@testing-library/react"; +import { MemoryRouter } from "react-router-dom"; +import { ListChecks, Wrench } from "lucide-react"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import type { ThreadItem } from "@/types"; +import { ToolGroup, ToolUse, toolRowLabel } from "@/business/conversations/components/ToolUse"; +import { + bucketForTool, + cardIcon, + registerToolCard, + toolCard, + toolCtx, + useToolCardsEpoch, +} from "@/business/conversations/toolCards/registry"; +import type { PluginTrackerCardSpec, TrackerOp } from "./api"; +import { trackerField, trackerOp, trackerToolCard } from "./trackerCards"; + +vi.mock("./api", async (orig) => ({ ...(await orig<typeof import("./api")>()), usePluginsUi: () => ({ data: undefined }) })); + +/** The tasks plugin's ops, as the hub normalizes them. */ +const OPS: TrackerOp[] = [ + { do: "snapshot", items: ["todos"], name: ["content", "activeForm"], status: ["status"] }, + { do: "update", id: ["taskId", "task_id"], name: ["subject"], status: ["status"] }, + { do: "create", name: ["subject", "content"] }, +]; + +/** Its tool card, as `/api/plugins` hands it out. */ +const CARD: PluginTrackerCardSpec = { + id: "todo", + tracker: "tasks", + tool: "todo", + ops: OPS, + icon: "list-checks", + create: "New task", + update: "Task", + snapshot: "Updated todos", + many: "{count} task updates", + vis: { key: "calls", label: "Task calls", hint: "", defaultOff: true }, + pluginId: "tasks", + pluginName: "Tasks", +}; + +const call = (input: object, extra: Partial<ThreadItem> = {}): ThreadItem => + ({ role: "assistant", kind: "tool_use", name: "todo", input, ...extra }) as ThreadItem; + +describe("a tool tracker's ops, told by the input like the hub's fold", () => { + it("snapshot, update, create — and a read is none", () => { + const op = (inp: Record<string, unknown>) => trackerOp(inp, OPS)?.do ?? null; + expect(op({ todos: [] })).toBe("snapshot"); + expect(op({ taskId: "2", status: "completed" })).toBe("update"); + expect(op({ task_id: 2 })).toBe("update"); + expect(op({ subject: "Ship it", description: "d" })).toBe("create"); + expect(op({ content: "x" })).toBe("create"); + expect(op({})).toBeNull(); + expect(op({ todos: "nope" })).toBeNull(); + }); + + it("a field is the first alternative that is set, dotted for a nested one", () => { + expect(trackerField({ a: "", b: "x" }, ["a", "b"])).toBe("x"); + expect(trackerField({ task: { id: 3 } }, ["task.id"])).toBe(3); + expect(trackerField({ a: { b: 1 } }, ["a"])).toBeUndefined(); // not a scalar + expect(trackerField({ a: [1] }, ["a"], true)).toEqual([1]); + expect(trackerField({}, undefined)).toBeUndefined(); + }); +}); + +describe("a tool card the app draws from a plugin's declaration", () => { + const undo: (() => void)[] = []; + afterEach(() => undo.splice(0).forEach((f) => f())); + const declare = (shown: boolean) => undo.push(registerToolCard("todo", trackerToolCard(CARD, shown, toolCard("todo")))); + + it("without the plugin: a plain row, never left out", () => { + const it = call({ subject: "Ship it" }, { native: "TaskCreate" }); + expect(toolRowLabel(it)).toBe("TaskCreate"); + expect(cardIcon(toolCard("todo"), toolCtx(it))).toBe(Wrench); + expect(toolCard("todo").leftOut).toBeUndefined(); + }); + + it("its switch on: a row per call, in the plugin's words", () => { + declare(true); + expect(toolRowLabel(call({ todos: [] }))).toBe("Updated todos"); + expect(toolRowLabel(call({ subject: "Ship it" }))).toBe("New task Ship it"); + expect(toolRowLabel(call({ taskId: "2", status: "completed" }))).toBe("Task #2 → completed"); + expect(toolRowLabel(call({ taskId: "2", subject: "Renamed" }))).toBe("Task #2"); + // a lookup and the list read back change nothing: the harness's own name + expect(toolRowLabel(call({ taskId: "2" }, { native: "TaskGet" }))).toBe("TaskGet"); + expect(toolRowLabel(call({}, { native: "TaskList" }))).toBe("TaskList"); + const card = toolCard("todo"); + expect(cardIcon(card, toolCtx(call({})))).toBe(ListChecks); + expect(card.leftOut).toBeUndefined(); + expect(bucketForTool("todo")).toBe("todo"); // the tool's bucket carries over + }); + + it("a run of them folds into the plugin's phrase", () => { + declare(true); + const items = [call({ subject: "a" }), call({ subject: "b" }), call({ taskId: "1", status: "in_progress" })]; + render( + <MemoryRouter> + <ToolGroup items={items} /> + </MemoryRouter>, + ); + expect(screen.getByText("3 task updates")).toBeInTheDocument(); + }); + + it("its switch off: the thread leaves the calls out, but not the lookups", () => { + declare(false); + const card = toolCard("todo"); + expect(card.leftOut!(call({ subject: "x" }))).toBe(true); + expect(card.leftOut!(call({ todos: [] }))).toBe(true); + expect(card.leftOut!(call({ taskId: "2", status: "completed" }))).toBe(true); + expect(card.leftOut!(call({ taskId: "2" }))).toBe(false); + expect(card.leftOut!(call({}))).toBe(false); + expect(card.leftOut!({ role: "user", kind: "tool_result", name: "todo" } as ThreadItem)).toBe(true); + }); + + it("a mounted row redraws when the card comes and goes", () => { + const it = call({ subject: "Ship it" }, { native: "TaskCreate" }); + render( + <MemoryRouter> + <ToolUse item={it} /> + </MemoryRouter>, + ); + expect(screen.getByText("TaskCreate")).toBeInTheDocument(); + const { result } = renderHook(() => useToolCardsEpoch()); + const before = result.current; + let off = () => {}; + act(() => { + off = registerToolCard("todo", trackerToolCard(CARD, true, toolCard("todo"))); + }); + expect(result.current).toBeGreaterThan(before); + expect(screen.getByText("New task")).toBeInTheDocument(); + act(() => off()); + expect(screen.queryByText("New task")).toBeNull(); + expect(screen.getByText("TaskCreate")).toBeInTheDocument(); + }); +}); diff --git a/frontend/src/business/plugins/trackerCards.tsx b/frontend/src/business/plugins/trackerCards.tsx new file mode 100644 index 00000000..f6addf60 --- /dev/null +++ b/frontend/src/business/plugins/trackerCards.tsx @@ -0,0 +1,140 @@ +/** + * Tool cards the app draws from a plugin's declaration — a `ui.toolCards[]` + * entry that names one of the plugin's **tool trackers** instead of a + * document (docs/plugins.md → "Checklists"; backend `plugins/manifest.py` + * `_tracker_card`). The tracker says which tool it reads and how to tell its + * calls apart (`ops`, the same rules the hub's parser folds — + * `plugins/trackers.py`); the card says how each reads in the thread: a verb + * per op (`create`, `update`, `snapshot`) and `many` for a run of them folded + * into a group's line. The tasks plugin's `todo` card is the first one — it + * was the core's. + * + * A declared card is registered in the tool-card registry while its plugin is + * active ({@link useTrackerToolCards}, once, in the app shell). Its `vis` + * switch decides whether the calls are rows at all: off, the thread leaves + * them out — they are the tracker's bookkeeping, and its pill and panel show + * the result. Without the plugin the tool has no card: a plain row. + */ +import { useLayoutEffect } from "react"; +import { ListChecks, type LucideIcon } from "lucide-react"; + +import { pluginT } from "@/i18n/plugins"; +import { useVisibility } from "@/lib/visibility"; +import { FieldsBody } from "@/business/conversations/toolCards/bodies"; +import { + registerToolCard, + toolCard, + type Dict, + type ToolCardSpec, + type ToolLabel, +} from "@/business/conversations/toolCards/registry"; +import { usePluginsUi, type PluginTrackerCardSpec, type TrackerOp } from "./api"; +import { CARD_ICONS } from "./components/PluginCardBits"; +import { toolCardVisible } from "./components/PluginToolCard"; + +const asDict = (v: unknown): Dict => (v && typeof v === "object" && !Array.isArray(v) ? (v as Dict) : {}); + +/** The first of `paths` (dotted input fields) that is set — the backend's + * `trackers._field`: an empty string counts as unset. */ +export function trackerField(src: unknown, paths: readonly string[] | undefined, anyType = false): unknown { + for (const path of paths ?? []) { + let cur: unknown = src; + for (const part of path.split(".")) { + cur = cur && typeof cur === "object" && !Array.isArray(cur) ? (cur as Dict)[part] : undefined; + if (cur == null) break; + } + if (cur == null || cur === "") continue; + if (anyType || typeof cur === "string" || typeof cur === "number") return cur; + } + return undefined; +} + +/** + * The op a call's input makes, as the hub's fold tells it (`Tracker.op_of`): + * the first whose input is there — a snapshot's `items` is a list, an + * update's `id` is set, a create's `name` is set. Null: a read (the list + * asked back). + */ +export function trackerOp(inp: Dict, ops: readonly TrackerOp[]): TrackerOp | null { + for (const op of ops) { + if (op.do === "snapshot") { + if (Array.isArray(trackerField(inp, op.items, true))) return op; + } else if (trackerField(inp, op.do === "update" ? op.id : op.name) !== undefined) { + return op; + } + } + return null; +} + +/** The op of a call that changes the list: an update that carries nothing + * but its id is a lookup — a plain row, like a read. */ +function changing(inp: Dict, ops: readonly TrackerOp[]): TrackerOp | null { + const op = trackerOp(inp, ops); + if (op?.do !== "update") return op; + return trackerField(inp, op.status) !== undefined || trackerField(inp, op.name) !== undefined ? op : null; +} + +/** + * The card of one declaration. `shown`: its `vis` switch — off, the thread + * leaves the tracker's calls out. `base`: the tool's card under it (its cost + * bucket carries over). + */ +export function trackerToolCard(card: PluginTrackerCardSpec, shown: boolean, base?: ToolCardSpec): ToolCardSpec { + const tr = (s: string) => pluginT(card.pluginId, s); + const icon: LucideIcon = (card.icon && CARD_ICONS[card.icon]) || ListChecks; + const label = (inp: Dict): ToolLabel | undefined => { + const op = changing(inp, card.ops); + if (!op) return undefined; + if (op.do === "snapshot") return { verb: tr(card.snapshot), detail: "" }; + if (op.do === "create") return { verb: tr(card.create), detail: String(trackerField(inp, op.name) ?? "") }; + const st = trackerField(inp, op.status); + const id = trackerField(inp, op.id); + return { verb: tr(card.update), detail: st !== undefined ? `#${id} → ${st}` : `#${id}` }; + }; + return { + icon, + label: ({ inp }) => label(inp), + action: ({ inp }) => { + const l = label(inp); + if (!l) return undefined; + return { + // Every call of the card folds with its neighbours, whatever its op. + verb: `tracker:${card.pluginId}:${card.id}`, + noun: "call", + detail: l.detail, + phrase: (n) => + n === 1 ? (l.detail ? `${l.verb} ${l.detail}` : l.verb) : tr(card.many).replace("{count}", String(n)), + }; + }, + body: ({ inp, result, error }) => { + const op = changing(inp, card.ops); + return op && op.do !== "snapshot" ? <FieldsBody inp={inp} result={result} error={error} /> : undefined; + }, + leftOut: shown + ? undefined + : (item) => item.kind === "tool_result" || changing(asDict(item.input), card.ops) != null, + bucket: base?.bucket, + }; +} + +/** + * Keeps the active plugins' declared cards registered (the first plugin to + * declare a tool keeps it), following their `vis` switches. Mount once, in + * the app shell — before any thread renders. + */ +export function useTrackerToolCards(): void { + const cards = usePluginsUi().data?.ui.trackerCards; + const hidden = useVisibility((s) => s.hidden); + const shown = useVisibility((s) => s.shown); + useLayoutEffect(() => { + if (!cards?.length) return; + const seen = new Set<string>(); + const undo: Array<() => void> = []; + for (const c of cards) { + if (seen.has(c.tool)) continue; + seen.add(c.tool); + undo.push(registerToolCard(c.tool, trackerToolCard(c, toolCardVisible({ hidden, shown }, c), toolCard(c.tool)))); + } + return () => undo.reverse().forEach((f) => f()); + }, [cards, hidden, shown]); +} diff --git a/frontend/src/generated/model/conversationDetail.ts b/frontend/src/generated/model/conversationDetail.ts index bfa814c0..96602e0b 100644 --- a/frontend/src/generated/model/conversationDetail.ts +++ b/frontend/src/generated/model/conversationDetail.ts @@ -19,7 +19,6 @@ import type { RunningAgent } from './runningAgent.ts'; import type { SpawnedConvRef } from './spawnedConvRef.ts'; import type { StoppedOn } from './stoppedOn.ts'; import type { SubagentRef } from './subagentRef.ts'; -import type { Task } from './task.ts'; import type { ThreadItem } from './threadItem.ts'; import type { TurnUsage } from './turnUsage.ts'; import type { Usage } from './usage.ts'; @@ -69,7 +68,6 @@ export interface ConversationDetail { compactions?: number | null; firstContextTokens?: number | null; firstMessageTokens?: number | null; - tasks?: Task[] | null; skillsUsed?: string[] | null; agentsUsed?: string[] | null; meta?: ConvMeta | null; diff --git a/frontend/src/generated/model/conversationSummary.ts b/frontend/src/generated/model/conversationSummary.ts index ab0bb216..27cc8e13 100644 --- a/frontend/src/generated/model/conversationSummary.ts +++ b/frontend/src/generated/model/conversationSummary.ts @@ -13,7 +13,6 @@ import type { PlanPct } from './planPct.ts'; import type { QueuedFollowup } from './queuedFollowup.ts'; import type { RunningAgent } from './runningAgent.ts'; import type { StoppedOn } from './stoppedOn.ts'; -import type { Task } from './task.ts'; import type { Usage } from './usage.ts'; export interface ConversationSummary { @@ -61,7 +60,6 @@ export interface ConversationSummary { compactions?: number | null; firstContextTokens?: number | null; firstMessageTokens?: number | null; - tasks?: Task[] | null; skillsUsed?: string[] | null; agentsUsed?: string[] | null; meta?: ConvMeta | null; diff --git a/frontend/src/generated/model/index.ts b/frontend/src/generated/model/index.ts index 351b3e7a..3244a1a3 100644 --- a/frontend/src/generated/model/index.ts +++ b/frontend/src/generated/model/index.ts @@ -601,7 +601,6 @@ export * from './tagMetaSnapshotIcons.ts'; export * from './tagMetaSnapshotTags.ts'; export * from './tagPatchBody.ts'; export * from './tagPatchBodyPatch.ts'; -export * from './task.ts'; export * from './taskEvent.ts'; export * from './taskRef.ts'; export * from './telemetryHub.ts'; diff --git a/frontend/src/generated/model/task.ts b/frontend/src/generated/model/task.ts deleted file mode 100644 index 954c9940..00000000 --- a/frontend/src/generated/model/task.ts +++ /dev/null @@ -1,17 +0,0 @@ -/** - * Generated by orval v8.20.0 🍺 - * Do not edit manually. - * ai-agent - * OpenAPI spec version: 0.1.0 - */ - -/** - * One task from the conversation's task list (TaskCreate/TaskUpdate, or the - * older TodoWrite). ``status`` is one of pending / in_progress / completed / - * cancelled. - */ -export interface Task { - id: string; - subject: string; - status: string; -} diff --git a/frontend/src/generated/model/trackedItem.ts b/frontend/src/generated/model/trackedItem.ts index 90e7ae12..b3a715bc 100644 --- a/frontend/src/generated/model/trackedItem.ts +++ b/frontend/src/generated/model/trackedItem.ts @@ -8,7 +8,8 @@ /** * One thing a conversation opened (and maybe closed), read by a plugin's * tracker rules (plugins/trackers.py) — a git worktree, for the worktrees - * plugin. + * plugin; one task of its list, for the tasks plugin (a tool tracker's item: + * it has a ``status``, and its list keeps the plan's order). */ export interface TrackedItem { key: string; @@ -16,4 +17,6 @@ export interface TrackedItem { group?: string | null; openedAt?: string | null; closedAt?: string | null; + status?: string | null; + startedAt?: string | null; } diff --git a/frontend/src/lib/cardBits.ts b/frontend/src/lib/cardBits.ts index c4e689f6..0f8f261b 100644 --- a/frontend/src/lib/cardBits.ts +++ b/frontend/src/lib/cardBits.ts @@ -18,7 +18,9 @@ * what one of the plugin's trackers recorded on the conversation * (`meta.trackers["<plugin>:<tracker>"]` — backend `plugins/trackers.py`): the * single item's name or a count, and it opens a card of rows grouped by - * `group` (`PluginCardBits.tsx`). + * `group` (`PluginCardBits.tsx`). With `style: "checklist"` (a tool tracker: + * its items have a status) the pill is a progress count — done / total — and + * its card the checklist (`Checklist.tsx`; the tasks plugin's). * * `text` / `title` are templates: `{planPct.week|pct}` reads a field from * {@link CARD_FIELDS} and formats it. A bit whose template names a field the @@ -34,13 +36,19 @@ export const CARD_PLACES: readonly CardPlace[] = ["tags", "cost", "foot", "corne export type CardTone = "plain" | "muted" | "primary" | "amber" | "emerald" | "sky" | "violet" | "rose"; -/** One thing a conversation opened (and maybe closed) — a tracker's item. */ +/** One thing a conversation opened (and maybe closed) — a tracker's item. A + * tool tracker's (a task of its list) also has a `status` and when it was + * first in progress; `openedAt` is then when it was added, `closedAt` when it + * was completed or cancelled. */ export interface TrackedItem { key: string; name: string; group?: string | null; openedAt?: string | null; closedAt?: string | null; + /** pending | in_progress | completed | cancelled (a tool tracker's item). */ + status?: string | null; + startedAt?: string | null; } /** @@ -62,7 +70,54 @@ export const CARD_LIST_TEXTS = [ export type CardListText = (typeof CARD_LIST_TEXTS)[number]; /** `ui.card[].list`: the tracker a `tags` bit lists, and its wording. */ -export type CardListSpec = { tracker: string; group?: "project" | null } & Record<CardListText, string>; +export type CardListSpec = { tracker: string; style?: undefined; group?: "project" | null } & Record< + CardListText, + string +>; + +/** + * A checklist's wording — the backend's `CARD_CHECKLIST_TEXTS`. `progress` + * holds `{done}` and `{total}`, `added` / `started` / `done` / `cancelled` + * hold `{when}`, `took` holds `{time}`. + */ +export const CARD_CHECKLIST_TEXTS = ["title", "progress", "added", "started", "done", "cancelled", "took"] as const; +export type CardChecklistText = (typeof CARD_CHECKLIST_TEXTS)[number]; +export type ChecklistTexts = Record<CardChecklistText, string>; + +/** `ui.card[].list` with `style: "checklist"`: a tool tracker's progress pill. */ +export type CardChecklistSpec = { tracker: string; style: "checklist"; group?: null } & ChecklistTexts; + +/** What a checklist's wording falls back to (a panel declares only its title). */ +export const CHECKLIST_DEFAULTS: ChecklistTexts = { + title: "Checklist", + progress: "{done} of {total} done", + added: "added {when}", + started: "started {when}", + done: "done {when}", + cancelled: "cancelled {when}", + took: "took {time}", +}; + +/** + * Roll a checklist up into an x/n progress count. Cancelled items drop out of + * both the numerator and the denominator (they're no longer part of the plan). + */ +export function checklistCounts(items?: readonly TrackedItem[] | null): { + total: number; + done: number; + inProgress: number; +} { + let total = 0; + let done = 0; + let inProgress = 0; + for (const it of items ?? []) { + if (it.status === "cancelled") continue; + total++; + if (it.status === "completed") done++; + else if (it.status === "in_progress") inProgress++; + } + return { total, done, inProgress }; +} /** A `ui.card[]` entry, as `/api/plugins/ui` hands it out. */ export interface CardBitSpec { @@ -73,7 +128,7 @@ export interface CardBitSpec { when?: string; icon?: string; tone?: CardTone; - list?: CardListSpec; + list?: CardListSpec | CardChecklistSpec; vis?: { key: string; label: string; hint: string; defaultOff?: boolean }; pluginId: string; pluginName: string; @@ -232,6 +287,11 @@ export function cardBitsFor( if (spec.list) { const items = cardListItems(spec, c); if (!items.length) continue; + if (spec.list.style === "checklist") { + // A progress pill: nothing left of the plan (all cancelled), no pill. + if (checklistCounts(items).total > 0) out.push({ spec, text: null, title: null, items }); + continue; + } const text = items.length === 1 ? items[0].name diff --git a/frontend/src/lib/visibility.ts b/frontend/src/lib/visibility.ts index 176c9a18..2e96d3c1 100644 --- a/frontend/src/lib/visibility.ts +++ b/frontend/src/lib/visibility.ts @@ -61,7 +61,6 @@ export type VisKey = | "compactSummary" | "msgNav" // chrome floating over the thread - | "taskPanel" | "fastForward" | "contextGizmo" | "costCurve" @@ -255,7 +254,6 @@ export const VIS_GROUPS: VisGroup[] = [ id: "Gizmos", title: t("Gizmos"), items: [ - { key: "taskPanel", label: t("Task panel"), hint: t("floating task checklist") }, { key: "fastForward", label: t("Fast-forward"), hint: t("hold-to-3× button") }, { key: "contextGizmo", @@ -314,6 +312,20 @@ export function isOn(s: Pick<VisState, "hidden" | "shown">, k: AnyVisKey, defaul return startsOff(k, defaultOff) ? (s.shown ?? []).includes(k) : !(s.hidden ?? []).includes(k); } +/** Core switches that became a plugin's (2026-12-02: the Tasks panel is the + * tasks plugin's `ui.panels[]`). */ +const RENAMED_KEYS: Record<string, PluginVisKey> = { taskPanel: "plugin:tasks:panel" }; + +/** A persisted list with any renamed key under its new name, once. */ +export function renameKeys(list: readonly string[] | undefined): AnyVisKey[] { + const out: AnyVisKey[] = []; + for (const k of list ?? []) { + const nk = (RENAMED_KEYS[k] ?? k) as AnyVisKey; + if (!out.includes(nk)) out.push(nk); + } + return out; +} + const flip = (list: AnyVisKey[], k: AnyVisKey) => list.includes(k) ? list.filter((x) => x !== k) : [...list, k]; @@ -339,6 +351,12 @@ export const useVisibility = create<VisState>()( { name: "ai-agent-visibility", storage: createJSONStorage(() => serverStorage), + // Switches that left the core for a plugin keep what they were set to: + // a hidden core key becomes its plugin's (RENAMED_KEYS). + merge: (persisted, current) => { + const p = (persisted ?? {}) as Partial<Pick<VisState, "hidden" | "shown">>; + return { ...current, ...p, hidden: renameKeys(p.hidden), shown: renameKeys(p.shown) }; + }, }, ), ); diff --git a/frontend/src/mock/plugins.ts b/frontend/src/mock/plugins.ts index 6cb5ce66..52161d42 100644 --- a/frontend/src/mock/plugins.ts +++ b/frontend/src/mock/plugins.ts @@ -82,8 +82,42 @@ const CARD_BITS = [ vis: { key: "worktrees", label: "Worktrees", hint: "The git worktrees a conversation made, on its card and in its header" }, pluginId: "worktrees", pluginName: "Worktrees", }, + // The tasks plugin: a checklist bit over its tool tracker (meta.trackers). + { + id: "tasks", place: "tags", icon: "list-checks", tone: "primary", + list: { + tracker: "tasks", style: "checklist", title: "Tasks", progress: "{done} of {total} tasks done", + added: "added {when}", started: "started {when}", done: "done {when}", + cancelled: "cancelled {when}", took: "took {time}", + }, + vis: { key: "pill", label: "Tasks pill", hint: "A conversation's task progress, on its card and in its header" }, + pluginId: "tasks", pluginName: "Tasks", + }, ] as const; +// …its floating panel over the thread (`ui.panels[]`) and its `todo` tool +// card (`ui.toolCards[]` naming the tracker), both drawn by the app. +const TASKS_PANELS = [ + { + id: "tasks", tracker: "tasks", title: "Tasks", show: "Show tasks", + vis: { key: "panel", label: "Task panel", hint: "The floating task checklist over a conversation's thread" }, + pluginId: "tasks", pluginName: "Tasks", + }, +]; +const TASKS_TRACKER_CARDS = [ + { + id: "todo", tracker: "tasks", tool: "todo", icon: "list-checks", + ops: [ + { do: "snapshot" as const, items: ["todos"], name: ["content", "activeForm"], status: ["status"] }, + { do: "update" as const, id: ["taskId", "task_id"], name: ["subject"], status: ["status"] }, + { do: "create" as const, name: ["subject", "content"] }, + ], + create: "New task", update: "Task", snapshot: "Updated todos", many: "{count} task updates", + vis: { key: "calls", label: "Task calls", hint: "The calls that keep the task list, as rows in the thread", defaultOff: true }, + pluginId: "tasks", pluginName: "Tasks", + }, +]; + const CHARTS_FENCES = [ { id: "chart-fence", lang: "chart", label: "Chart", pluginId: "charts", pluginName: "Charts", height: 330, vis: CHARTS_VIS }, ]; @@ -372,6 +406,8 @@ export async function handlePlugins(p: string, method: string, body?: unknown, g fences: CHARTS_FENCES, filePreviews: pdfViewerOn() ? PDF_FILE_PREVIEWS : [], card: CARD_BITS, + panels: TASKS_PANELS, + trackerCards: TASKS_TRACKER_CARDS, overlays: PETS_OVERLAYS.map((o) => ({ ...o, pluginId: "pets", pluginName: "Pets" })), prefs: { pets: PETS_PREFS }, resources: MOCK_RESOURCE_KINDS, diff --git a/frontend/src/mock/seed.ts b/frontend/src/mock/seed.ts index ec570f7b..11bdddc9 100644 --- a/frontend/src/mock/seed.ts +++ b/frontend/src/mock/seed.ts @@ -18,7 +18,6 @@ import type { ServiceAuth, SkillSummary, SubagentRef, - Task, SpawnedConvRef, ThreadItem, ToolUsage, @@ -52,6 +51,9 @@ const T0 = Date.parse("2026-07-01T09:00:00.000Z"); const min = (n: number) => n * 60_000; /** The mock worktrees plugin's tracker (`mock/plugins.ts` lists its card bit). */ export const WORKTREES_TRACKER = "worktrees:worktrees"; +/** The mock tasks plugin's tracker (`mock/plugins.ts`: its checklist bit, its + * floating panel and its `todo` tool card). */ +export const TASKS_TRACKER = "tasks:tasks"; const at = (offsetMin: number) => new Date(T0 + min(offsetMin)).toISOString(); @@ -871,12 +873,15 @@ function fullThread(model: string): ThreadItem[] { }, }, ), + // Task-list calls: the tasks plugin's tracker reads them; rows in the + // thread only with its "Task calls" switch on. toolPair( "TaskCreate", - { tasks: [{ subject: "seed db", status: "in_progress" }] }, - "Created 1 task", + { subject: "Seed every combination", description: "Cross every field the UI branches on" }, + "Task #2 created successfully: Seed every combination", i++, ), + toolPair("TaskUpdate", { taskId: "2", status: "in_progress" }, "Updated task #2 status", i++), // An error result (the red tool card). toolPair("Bash", { command: "npx tsc --noEmit" }, "error TS2322: Type 'null' is not assignable", i++, { isError: true, @@ -1018,11 +1023,13 @@ function shortThread(model: string, title: string, running: boolean): ThreadItem return items; } -const TASKS: Task[] = [ - { id: "t1", subject: "Map the API surface", status: "completed" }, - { id: "t2", subject: "Seed every combination", status: "in_progress" }, - { id: "t3", subject: "Wire the fetch interceptor", status: "pending" }, - { id: "t4", subject: "Drop the MSW idea", status: "cancelled" }, +// What the tasks plugin's tool tracker read off the `todo` calls: the list in +// plan order, each task with its status and times. +const TASKS: NonNullable<ConvMeta["trackers"]>[string] = [ + { key: "1", name: "Map the API surface", status: "completed", openedAt: at(1), startedAt: at(2), closedAt: at(9) }, + { key: "2", name: "Seed every combination", status: "in_progress", openedAt: at(1), startedAt: at(9) }, + { key: "3", name: "Wire the fetch interceptor", status: "pending", openedAt: at(1) }, + { key: "4", name: "Drop the MSW idea", status: "cancelled", openedAt: at(1), closedAt: at(6) }, ]; const BY_TOOL: Record<string, ToolUsage> = { @@ -1165,6 +1172,8 @@ function conversation( effort, account, }); + // The kitchen-sink conversations keep a task list (the tasks plugin's). + if (opts.full) convMeta.trackers = { ...(convMeta.trackers ?? {}), [TASKS_TRACKER]: TASKS }; // A run whose ended turn the Stop guard holds for a background shell (its // deploy wait): running, with the "Waiting on a background shell" chip. if (state === "running" && lifecycle === "committed" && harness === "claude") { @@ -1234,7 +1243,6 @@ function conversation( cacheTtl: 3600, firstContextTokens: 39_800 + idx * 400, firstMessageTokens: 90 + idx * 15, - tasks: opts.full ? TASKS : null, // The tool axis the `skill:`/`agent:` tags are derived from. Cycled by // index so a mock load shows both the short case and one long enough to // hit the detail header's "+N" overflow. diff --git a/frontend/src/mock/sim.ts b/frontend/src/mock/sim.ts index 1b7f78cb..80adff98 100644 --- a/frontend/src/mock/sim.ts +++ b/frontend/src/mock/sim.ts @@ -209,7 +209,6 @@ export function spawn( subagentCost: 0, contextTokens: 24_000, contextModel: model || db.models.default, - tasks: null, meta: { state: "running", harness: harness || "claude", diff --git a/frontend/src/technical/PillPopover.tsx b/frontend/src/technical/PillPopover.tsx new file mode 100644 index 00000000..73acf492 --- /dev/null +++ b/frontend/src/technical/PillPopover.tsx @@ -0,0 +1,173 @@ +import { useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react"; +import { createPortal } from "react-dom"; +import { cn } from "@/lib/utils"; + +/** Space between a pill and its card, in px. */ +const GAP = 4; +/** The card's closest approach to a viewport edge, in px. */ +const EDGE = 8; + +type DataAttrs = { [k: `data-${string}`]: string | undefined }; + +/** + * A pill that opens a details card — the worktrees plugin's list pill, the + * tasks pill, the preset pill. A mouse opens it on hover (the card stays + * open while the pointer is over it); a touch taps the pill instead, which + * toggles the card and doesn't follow the link the pill sits in (the + * conversation card around it, or the pill's own link) — a mouse click + * still does. + * + * The card is portaled to `<body>` and placed from the pill's bounding rect + * (fixed, viewport coordinates), so no scroll container clips it: under the + * pill, right-aligned, shifted sideways rather than crossing an edge, and + * above the pill when there is more room there. It renders hidden first so it + * can be measured. With `rows`, the element marked `data-popover-list` stops + * growing after that many `data-popover-row` rows and scrolls. A scroll + * outside it, a resize or a tap elsewhere closes it. + */ +export function PillPopover({ + pill, + children, + rows, + className, + cardClassName, + anchorProps, + cardProps, +}: { + pill: ReactNode; + /** The card's content — mounted only while it is open. */ + children: ReactNode; + rows?: number; + className?: string; + cardClassName?: string; + anchorProps?: DataAttrs; + cardProps?: DataAttrs; +}) { + const anchorRef = useRef<HTMLSpanElement>(null); + const cardRef = useRef<HTMLSpanElement>(null); + const hideTimer = useRef<ReturnType<typeof setTimeout>>(); + const lastPointer = useRef("mouse"); + // The pill's rect while the card is open; where the card lands is worked out + // from its measured size once it has rendered (hidden) — see below. + const [anchor, setAnchor] = useState<DOMRect | null>(null); + const [place, setPlace] = useState<{ top: number; left: number; maxH: number } | null>(null); + + const show = useCallback(() => { + clearTimeout(hideTimer.current); + const rect = anchorRef.current?.getBoundingClientRect(); + if (rect) setAnchor(rect); + }, []); + const hide = useCallback(() => { + clearTimeout(hideTimer.current); + hideTimer.current = setTimeout(() => { + setAnchor(null); + setPlace(null); + }, 100); + }, []); + + // Every render while open: the content may have changed under it (a task + // done, a step down) — re-measured, re-placed only when that moves it. + useLayoutEffect(() => { + const card = cardRef.current; + if (!anchor || !card) return; + const list = card.querySelector<HTMLElement>("[data-popover-list]"); + if (list && rows) { + // The rows may sit inside per-group boxes; the list is their offsetParent. + const all = list.querySelectorAll<HTMLElement>("[data-popover-row]"); + const last = all[rows - 1]; + list.style.maxHeight = all.length > rows && last ? `${last.offsetTop + last.offsetHeight}px` : ""; + } + const w = card.offsetWidth; + const h = card.scrollHeight; + const vw = window.innerWidth; + const vh = window.innerHeight; + const left = Math.max(EDGE, Math.min(anchor.right - w, vw - w - EDGE)); + const below = vh - anchor.bottom - GAP - EDGE; + const above = anchor.top - GAP - EDGE; + const next = + h <= below || below >= above + ? { left, top: anchor.bottom + GAP, maxH: below } + : { left, top: Math.max(EDGE, anchor.top - GAP - h), maxH: above }; + setPlace((p) => + p && p.left === next.left && p.top === next.top && p.maxH === next.maxH ? p : next, + ); + }); + + // The card is open above a scroll container: close it on scroll/resize so it + // never drifts away from the pill it's anchored to — but not when the scroll + // is the card's own list. A tap anywhere else closes it too (a touch has no + // pointer-leave to do it). + useEffect(() => { + if (!anchor) return; + const onScroll = (e: Event) => { + if (cardRef.current?.contains(e.target as Node)) return; + hide(); + }; + const onDown = (e: PointerEvent) => { + const node = e.target as Node; + if (anchorRef.current?.contains(node) || cardRef.current?.contains(node)) return; + hide(); + }; + window.addEventListener("scroll", onScroll, true); + window.addEventListener("resize", hide); + document.addEventListener("pointerdown", onDown, true); + return () => { + window.removeEventListener("scroll", onScroll, true); + window.removeEventListener("resize", hide); + document.removeEventListener("pointerdown", onDown, true); + }; + }, [anchor, hide]); + + useEffect(() => () => clearTimeout(hideTimer.current), []); + + return ( + <span + ref={anchorRef} + {...anchorProps} + className={cn("relative inline-flex", className)} + // Hover is a mouse's; a touch taps the pill instead (below). + onPointerEnter={(e) => e.pointerType === "mouse" && show()} + onPointerLeave={(e) => e.pointerType === "mouse" && hide()} + onPointerDown={(e) => (lastPointer.current = e.pointerType)} + // Capture, so a tap is caught before a link inside the pill follows it. + onClickCapture={(e) => { + if (lastPointer.current === "mouse") return; + // React routes the portaled card's events through here too: a tap in + // the card (one of its links) is the card's. + if (cardRef.current?.contains(e.target as Node)) return; + e.preventDefault(); + e.stopPropagation(); + if (anchor) hide(); + else show(); + }} + > + {pill} + {anchor && + typeof document !== "undefined" && + createPortal( + <span + ref={cardRef} + {...cardProps} + className={cn( + "fixed z-50 flex w-max max-w-[min(18rem,calc(100vw-1rem))] flex-col overflow-y-auto rounded-lg border border-border bg-card p-2.5 text-left shadow-xl", + cardClassName, + )} + style={ + place + ? { top: place.top, left: place.left, maxHeight: place.maxH } + : { top: 0, left: 0, visibility: "hidden" } + } + onPointerEnter={(e) => e.pointerType === "mouse" && show()} + onPointerLeave={(e) => e.pointerType === "mouse" && hide()} + // React bubbles a portal's events to the pill's ancestors: keep a + // click in the card (one of its links, a stray tap) from also + // opening the conversation card around the pill. + onClick={(e) => e.stopPropagation()} + > + {children} + </span>, + document.body, + )} + </span> + ); +} diff --git a/frontend/src/technical/VisibilityPopover.tsx b/frontend/src/technical/VisibilityPopover.tsx index 64f56c9d..554d4d06 100644 --- a/frontend/src/technical/VisibilityPopover.tsx +++ b/frontend/src/technical/VisibilityPopover.tsx @@ -154,14 +154,15 @@ export function usePluginVisGroup(): VisGroup | null { const ui = plugins.data?.ui; return useMemo(() => { if (!ui) return null; - const items = pluginVisItems(ui.slots ?? [], ui.toolCards ?? [], ui.fences ?? [], ui.filePreviews ?? [], ui.card ?? []); + const items = pluginVisItems(ui.slots ?? [], ui.toolCards ?? [], ui.fences ?? [], ui.filePreviews ?? [], ui.card ?? [], + ui.panels ?? [], ui.trackerCards ?? []); if (!items.length) return null; registerPluginVis(items as Array<{ key: PluginVisKey; defaultOff?: boolean }>); return { id: "Plugins", title: t("Plugins"), items }; }, [ui]); } -/** The plugin switches of a payload's slots, tool cards, fences, file previews and card bits, first one wins. */ +/** The plugin switches of a payload's slots, tool cards, fences, file previews, card bits, panels and tracker cards, first one wins. */ export function pluginVisItems( ...lists: Array<ReadonlyArray<{ pluginId: string; pluginName: string; vis?: { key: string; label: string; hint: string; defaultOff?: boolean } }>> ): VisItem[] {