A ticket system for Claude Code: your todo as a live ticket board you can hand to Claude, with each step Claude takes and each helper agent linked to the…

![]()
A ticket system for Claude Code. Plan the work, hand it to Claude, and watch it get done.
.claude_todo/ list as a board you can send, ask about and move.Claudeopticon is a mod for Claude Code. It adds a work pane next to your conversation which shows your todo list as a ticket board, what Claude is doing, and what its helpers (Claude Code calls them agents) are doing. You can send a ticket to Claude, ask how it is going, or move it yourself.
At its core is a ticket system that lives in your repo. Each line in .claude_todo/ is a ticket with an ID such as #T002A. From the board you can send a ticket to Claude, ask for a status update, or move it between Open, Queued, In progress and done. A ticket that is done leaves the board for the archive. Claude keeps each ticket's state up to date as it works, and every helper agent is linked to the tickets it works on.
$.model.complete, the output-truncation flag of process.run) that an older version may lack.Run this line in Claude Code:
/plugin install claudeopticon --marketplace Marceux-Croix/Claudeopticon
The pane opens at the start of each session. To open it again, run /claudeopticon. In a session that is already running, run /reload-plugins first.
.claude_todo/ at the root of your repo, and a file in it, for example .claude_todo/TODO.md: - [ ] #T0001 Write the migration for the v2 config format
- [ ] #T0002 Document the plugin API
⋙ on a ticket to send it to Claude. Claude marks it [~], and the ticket moves to In progress.The top card is a live graph of the last 30 minutes, with three lines:
Each vertical axis has a title ("Live agents", "Tokens"). The top row gives the totals, "total session tokens" and how many agents have finished, followed by the key for the three lines. Each line ends in a dot with its current value. The end value is a label with a halo, placed clear of the lines where the plot has a clear place, with a leader line to its dot when it must sit far away. Lines that end at equal values share one dot, split into wedges of their colors. The token axis shows "0" at the bottom and counts up in k, M and B (thousand, million, billion). Each axis's numbers are in its line's color: yellow for live agents, green for all tokens since compact, blue for tokens per minute. The axes grow when a line would leave the graph, and shrink once every value in view is below half. The graph redraws at most every 5 seconds while numbers change, and every 30 seconds otherwise. A reload keeps the last 30 minutes. Todo progress is in the Todo section's header. The mod's version is in small type in the lower right corner, so after a reload you can see which version runs.
The mod counts every model request once, at the step that used it: the main conversation's and each agent's. It never counts a whole run at its end, so a compaction splits the tokens at the right place.
This card lists what Claude does itself, not its agents. Each line is the short description Claude already writes for an action, with its start time. A dim second line shows the detail from the action itself: the command, the file path, the search pattern, the web address, or the kind of agent started. A command that looks like it holds a password, token or key shows "(hidden)". The newest is on top. A pulsing dot means the action still runs. Older and Newer page through the history.
Each agent gets a card, labeled A1, A2, and so on, in start order. A label never changes during a session, also after /reload-plugins, and long labels such as A1000 shrink to fit their circle. Each agent gets a color when it starts and keeps it. There are 16 colors, the most distinct used first. A color is used again once its agent finishes. With 16 agents live, a new agent shares a color. A card shows what the agent was asked to do, its tickets, its progress ("Step 3 of 7" with a bar), its run time, tool calls and tokens, and what it does now. A timeline above the cards shows one bar per agent.
Claude sometimes works on a ticket itself, with no helper agent. Then an Orchestrator card, tagged O, shows above the agent cards, but only while Claude works such a ticket in a turn. Between turns the card is gone. Its title is a headline Claude writes for that work, through report_progress; until Claude sends one, the title is the text of its first ticket ("and 2 more" when it has several). It shows the tickets Claude works on, Running, and Claude's last action. When Claude hands a ticket to a helper agent, the ticket belongs to that agent while it runs: it shows on the agent's card and with the agent's disk on the board, not the orchestrator's. A ticket counts as Claude's own when Claude moves it to in progress or names it in a progress report, or when you send it with ⋙. The ? button makes a ticket Claude's own only when its box is already in progress: a status ask on an open or queued ticket leaves it where it is. A ticket stops counting when it is done, when it leaves In progress, or when Claude moves it to open or queued with move_ticket. The Orchestrator card has no Stop button and does not count in the top card.
A running agent has a Stop button. It is drawn in the agent's card at the right edge, red with a white stop sign, on the same row and at the same height as the status badge. The badge sits left of it. A blank pane button over the drawing takes the press. An agent that has ended has no Stop button. Stop ends the agent at once. It gets no chance to finish its step or write a summary. Use it when an agent has gone wrong.
An agent that finished its work but was never stopped shows Idle, with the time it finished and its last command marked "Last:". It does not count as live, it owns no ticket (its chip leaves the ticket cards, and a ticket it held is no longer moved to In progress, as on the boards of other sessions), and it keeps its Stop button so you can close it. An agent that stays idle for 10 minutes is filed with the finished agents: the headings and the top card count it as finished, and it shows only with Show finished agents.
If an agent vanishes from Claude Code's agent list without a report of how it ended, its card shows Ended after 15 seconds.
Finished agents are hidden. Show finished agents brings them back, grayed out, and Hide finished agents hides them again. You can name an agent by its label in chat ("how is A2 doing?"), up to A999999. The mod tells Claude which agent that is.
The pane draws one board for all your todo files, with the columns In progress, Queued and Open. Queued (- [>]) holds the work slated next: tickets nobody works on yet, but that come before the rest of Open. There is no Done column: a ticket that is done leaves the board and goes to the archive. Above it, one header card has a row for each file: its name, its progress bar, and its own "done of total" count, which includes the file's closed items in the archive. If two files have the same name, the row also shows the folder in dim text. Columns and stacked tickets are 10 px apart, and a column with no tickets keeps its width. The gaps scale with the card when the desktop fits it to the pane, so they can draw slightly under 10 px. A ticket shows its number, its group, its status, and the tags of the agents working on it. The tags blink in the agent's color while it works, and the O tag blinks while Claude works on the ticket itself. When an agent starts on an open or queued ticket, the ticket moves to In progress by itself.
Several sessions on one repo. When more than one Claude Code session works on the same repo, each session's board marks the tickets the other sessions claim. A claim is a ticket another session works on (itself or through its agents) or plans: a ticket its main conversation set to queued (- [>]) itself, or that the mod queued after Claude took it out of progress. A ticket a peer works on stays claimed until it is done, on any box, because the peer's own board shows it in In progress; a planned claim lasts as long as the ticket's box is [~] or [>], and ends when the box goes to done or open. A ticket a peer works on, that this session does not, shows in In progress with a yellow outlined "Peer owned" pill on a row of its own above the buttons, also when its box is open or queued, so both boards place it alike. A ticket a peer only plans stays in Queued, with the same pill. An agent of this session that has finished does not hide a peer's claim. The pill names the owner: "Peer owned: <name of that session> owns this" (in progress) or "Peer owned: <name> plans to work this" (queued), with "An unnamed peer session" in place of the name when that session never sent its name (Claude sends it through report_progress, see below). A name too long for the card is cut with an ellipsis. The pill is drawn at any card width and with any number of buttons. A box set by hand on the board plans nothing, and neither does a helper agent's edit. A card with the pill is a plain image, the same width as the other cards. The tag means check in with the owner first, not hands off. The ⋙ button stays, but on a peer-claimed ticket it sends a different prompt: Claude is told the ticket is claimed by session "<name>", to ask that session with SendMessage (to: "<name>") whether it can take the ticket, and to start only when the owner agrees and releases it, or when you say to take it anyway. When the owner has no name, Claude calls ListAgents and sends each other session one message with the ticket and this repo's root path, asking whether it claims the ticket and can release it; it starts once the tag clears, or when you say to take it anyway. If this session holds the ticket too, its own claim wins on its board and there is no pill (the peer still sees "Peer owned" on its own).
Claude is told about claims in notes with its next tool result or prompt, once each: when the mod records a planned claim (including a move_ticket to queued that you approved; a move you make by hand claims nothing), the note says "<ID> is now claimed by this session as planned work" and how to release it, since a queue move may be triage or work for another session. report_progress takes release, a list of ticket IDs or quoted ticket text from the main conversation; it drops this session's claims on them, planned and own, and nothing claims them again until a new move to queued or a new claim. When this session claims a ticket a peer claims too, a note tells Claude to check in with that session first. A session whose record was not refreshed for 2 minutes still counts, but its pill and text are dimmed to about half opacity and the pill adds " (inactive since HH:MM)", in local 24-hour time. A record not refreshed for 24 hours is ignored. Worktrees of one repo share a board; sessions in other repos do not.
Tickets have buttons on the bottom edge:
| Button | On | What it does |
|---|---|---|
⋙ Send to Claude | Open and queued tickets not yet sent | Sends the item to Claude as a prompt, to build it. |
? Ask Claude for a status update | Every ticket, in every column | Asks Claude for a short report in the chat. It starts no new work. |
≡ Move to queued | Open tickets | Moves the ticket by hand. |
◐ Mark in progress | Open and queued tickets | Moves the ticket by hand. |
✓ Mark done | Open, queued and in-progress tickets | Moves the ticket by hand. The mod then archives it. |
↪ Move back | Queued tickets and tickets in progress | Moves the ticket back one column by hand: in progress to queued, queued to open. |
The move buttons are for work you do yourself, such as a human review. They change the checkbox in your todo file and nothing else. Claude is told at its next action, so it does not work on a ticket you closed. It is not asked to do anything.
The Todo heading says how many todo files the board pulls from ("Pulling todo from 3 files"; archives are not counted). When some files could not be read, it says "Could not read N todo files". Up to three buttons sit next to it. Each shows only when it has work to do, and disappears once it is done. You can use one, two or all three, in any order.
TODO.md in the repo's root .claude_todo/. If that folder has no TODO.md but exactly one other todo file, that file is the central file. Notes move too, under a ## From <folder>/<file> heading per file. Nothing is folded and nothing is deleted. A listed todo folder that resolves outside the repo is skipped with a toast and never read. A ticket whose #T ID the central file already uses gets the next ID that no file uses, references to it follow, and Claude is told the new IDs once. Archive files move into the same-named file in the central archive/. Each old file is emptied only after its content is confirmed in the central file. If a file changed in the meantime, it is left alone, and the pane names it. The emptied files stay on disk and in the header, marked Empty, until you delete them. Each press ends with one toast that joins every refusal and the result, cut at 1500 characters. "Moved 0 files" is left out when a note explains why.archive/ and .claude_todo/ folders if those are empty too. It never deletes a file outright: if it cannot use the Trash, it keeps the file and says why. It never removes the central file, a file with content, or categories.json.## From section (or before the first one). A subtask, or a ticket with subtasks under it, is never removed. A removed ticket's ID is rewritten to the kept one in the central file and in the central archive files, outside code fences and HTML comments, and Claude is told once. If the reference fix fails on an archive file, the button stays and the next press tries again.Each button reads a file again right before it writes it, and skips a file that changed. The buttons are off in a git worktree and when the repo root is ~/.claude.
Other controls:
.claude_todo/archive/TODO.md, in your system's default app for Markdown files. N is the number of closed tickets in the archive. The mod makes the file if it does not exist yet.The mod reads checkbox lines in the Markdown files at the top level of .claude_todo/, and in .claude_todo/archive/.
- [ ] #T0004 Open item
- [>] #T0007 Queued item, slated next
- [~] #T0005 Item in progress
- [x] #T0006 Done item
#T plus 4 characters, digits and capital letters, the first one a digit. They count in base 36: #T0009, then #T000A, up to #T9ZZZ, which gives 466,559 IDs. After that the IDs have 5 characters, from #T10000. Older short IDs such as #T12 stay valid and are never renamed. A new ID always comes after the highest one in use, old or new.- [x]), the mod moves it, about 5 seconds later, to the file of the same name in .claude_todo/archive/ (TODO.md to archive/TODO.md). It makes the archive file if it is missing, and puts the item under the same heading it had. So the live file holds only open and in-progress items, and the archive is the record of finished work. Nothing is deleted. A closed item with subtasks moves only when all of its subtasks are done, and they move with it. A wrapped line directly under a closed item, with no indent, is part of its text and moves with it; prose after a blank line stays. Headings and notes stay in the live file. An ATX heading (# to ######) may have 0 to 3 spaces of indent. Setext headings (a line underlined with === or ---) are not read: a ticket under one files under the heading above it. Lines nest at most 64 containers deep. When the archive step fails (a symlinked archive, an archive that is not writable, a write that is not on disk, an error), the pane shows one toast per file and the ticket stays in the live file..claude_todo/ folder in the repo together, as if they were one todo. It finds the folders with git (tracked, untracked and ignored ones; at most 20; a folder under an ignored directory is not found, but an ignored .claude_todo is) and adds the main checkout's folders from a git worktree. It never reads the global ~/.claude/.claude_todo.#T ID: they stay two tickets.categories.json lives in the folder nearest to the session folder. With no such folder, items are not sorted into categories.At the start of each conversation, the mod gives Claude short instructions, about 5,000 characters (roughly 1,250 tokens). The text is RULES in hooks/rules.ts. The rules option turns it off. Claude is told to:
.claude_todo/ at the root of the repo's main checkout (a git worktree uses the main checkout's), make the folder when the repo has none, and keep each item in the folder it is in;~/.claude/.claude_todo/ (or .claude_todo/ in $CLAUDE_CONFIG_DIR), because the board never reads it; when the repo root is that folder's parent, use the .claude_todo/ of the project it works in;.md file (- [ ], - [>], - [~], - [x]) and update its box the moment the status changes;- [>]) when it decides the ticket comes next or waits for an event, writes a new ticket as queued when it plans to work on it now, next, or after the next checkpoint, gate, closeout or merge, and when it stops a ticket it has not finished but still plans to do;#T and 4 digits and capital letters, or 5 characters when the 4-character IDs run out; an item with no ID gets one from the mod), and put the item's ID in the description of each agent it starts for that item, marking the item [~];- [x]) in the same turn its work is done, before its final reply, never leave finished work open or in progress, and close an agent's item when the agent's work is done;hooks/register.tsx 6536 lines1/**
2 * The hooks module that hooks.json loads. It registers the hooks and the tools, and it holds each
3 * function that calls the engine through `$`, with the session state that those functions write.
4 * It is one responsibility, the engine-bound layer. `claude plugin validate`
5 * follows `$` only into functions in this file, never across an import, and it reads a hook filter
6 * only from a constant in this file. An imported `let` cannot get a new value, so the state that
7 * these functions assign stays here too. The pure logic is in the modules that this file imports.
8 */
9
10import type { EngineInterface, Register, Timer } from 'claude-code'
11import type { AgentRow, AgentRowStatus, TodoFile, TodoItem } from '../types'
12import { agentSvg, orchestratorSvg, timelineSvg } from './agent-cards'
13import { isEnded, notifiedEnd, unlistedEnds } from './agent-ends'
14import { respawnedRow } from './agent-respawn'
15import { colorSlots } from './agent-colors'
16import { agentColor, AGENT_COLORS, agentLabel, ORCH, setColorSlots, setLabelBase } from './agent-identity'
17import { MATCH_ITEMS, matchPrompt, readMatchReply } from './agent-match'
18import { addToArchive, ARCHIVE_AFTER_MS, archiveName, blockFinder, blocksLeft, blocksStandAsItems, closedBlocks, recordAfterRollback, removeBlocks } from './archive-blocks'
19import type { ClosedBlock } from './archive-blocks'
20import { addFailure, isRetryDue } from './backoff'
21import type { Failing } from './backoff'
22import { clock, elapsed, tokens } from './card-format'
23import { ACCENT, DANGER, GREEN, setWidth } from './card-stage'
24import { altText, controlFree, cutUnits, keyText, toastText } from './card-text'
25import type { AgentView, FileView, ItemStatus, ItemView, Usage, View } from './card-types'
26import { applySortReply, bookBackups, bookKeptBy, categoryGroups, categoryOf, emptyBook, filterNames, groupOf, isSubstantialChange, mergeRecategorized, pruneBookItems, readBook, SORT_BATCH, SORT_BATCHES, SORT_EVERY_MS, SORT_MODEL, SORT_TRIES, sortPrompt, usedCategories, withoutHidden } from './categories'
27import type { CategoryBook } from './categories'
28import { keepsMissing, MISSING_CLAIM_MS } from './claim-keeping'
29import { elapsedSince, isDeadlinePast } from './clock-elapsed'
30import type { ClaimFolder } from './claim-keeping'
31import { bestMatches } from './claim-score'
32import type { PendingNotes } from './claude-notes'
33import { claimNotes, DATA_MARK, SESSION_NAME_NOTE, deferredNote, endedNote, hasLabel, labelNote, moveLine, movesNote, NEXT_IDS_SHOWN, nextIdsLine, noteName, NUDGE_REPEAT_MS, NUDGE_TICKETS, numberedLine, numberedNote, peerClaimedLine, plannedLine, quoteName, quoteTicket, removedNote, renameNote, stillOpenNote, stoppedNote, withoutTold } from './claude-notes'
34import { mergeMarks, readKeptMarks, retryStep } from './consolidate-marks'
35import type { CopyMark } from './consolidate-marks'
36import { appendSections, copyLines, destOf, eolOf, isUnsafeHeadingName, itemLines, keepsEveryItem, pressToast, renameLines, renumberLines, sectionCount, sectionText } from './consolidate-text'
37import { removeDuplicateTickets, renameRefs } from './duplicate-tickets'
38import { endsInExample } from './example-end'
39import { heroCard, heroText } from './hero-card'
40import { fileId, filePath, itemKey, keptKey, storedKey } from './item-keys'
41import { pruneTo } from './key-prune'
42import { cutReturnSlots, forgottenCut, isOldSessionList, KEPT_AGENTS, KEPT_CUT, KEPT_DROPPING, liveSessionIds, MAX_BASE, nextDropping, nextSessions, readDropping, readKeptAgents, readKeptBase, readKeptBlocks, readKeptCut, readKeptReserved, readKeptTickets, readKeptWrote, SESSION_PREFIXES, SESSION_RETRY_MS, SESSION_TOUCH_MS, STORED_BRIEF, storedBrief } from './kept-records'
43import { linkOne } from './links'
44import { normalize } from './normalize'
45import { blockIds, blockOf, CLAIM_PRUNE_MS, CLAIM_SCAN, claimDirs, claimFrom, firstBlock, needsBlock, prunableClaims } from './id-blocks'
46import type { HeldBlock } from './id-blocks'
47import { claimAcross, END_BLOCK } from './block-claim'
48import type { ClaimPort } from './block-claim'
49import { gitWhereUp } from './git-file'
50import type { GitFs } from './git-file'
51import { insertIds, lineHolding, lineIds, NUMBER_AFTER_MS, NUMBER_MAX, textIds } from './numbering'
52import { ORCHESTRATOR_KEPT, orchestratorView, pageLabel } from './orchestrator-history'
53import type { OrchestratorEntry } from './orchestrator-history'
54import { envDirs, isAbsPath, isSameFolder, isWinPath, listedName, normPath, psPath, relIn, resolveAgainst, samePath } from './path-forms'
55import { MAC_SIGNS, openCommand, platformFrom, trashReason } from './platform-commands'
56import { CLAIM_CHECK_MS, progressReply, readClaims, readProgress, readTitle } from './progress-report'
57import { DIR, diskSpelling, findTodoDirWith, folderPlace, gitCommonDir, globalParents, isGlobalTodo, isInsideRoots, isMisspelledTodo, isSameTodo, isTodoOf, MAX_FOLDERS, pickFolders, placeOf, replaceGlobals, REV_PARSE, repoRoots, sessionFolder, todoFoldersIn } from './repo-folders'
58import type { TodoFolder } from './repo-folders'
59import { sameRows } from './row-equality'
60import { buildPresence, holdings, newlyQueued, peerHolds, peerIds, peerTip, PEER_DIM_MS, PEER_IGNORE_MS, PEERS_EVERY_MS, plannedKey, PRESENCE_EVERY_MS, presenceKey, prunePlanned, readPlanned, readPresence, samePresence, sanitizeSessionName, ticketId, waitOver } from './peer-sessions'
61import type { PeerClaim, Presence } from './peer-sessions'
62import { withRules } from './rules'
63import { HIDDEN, hideSecretLines, hideSecrets, hideTitle } from './secrets'
64import { addAgents, addCompact, addTokens, emptySeries, readKeptSeries, seedSeries, stepAxes } from './series'
65import { addAloneTry, isItemsFailure, nextBatchSize, nextSortBatch, nextThrows, sortReplyKind, THROWS_TO_HALVE } from './sort-queue'
66import type { BatchThrows } from './sort-queue'
67import type { Axes, Series } from './series'
68import { bar, clip, textChildren } from './terminal-text'
69import { DONE_ACTION, QUEUE_ACTION, REOPEN_ACTION, SEND_ACTION, START_ACTION, STATUS_ACTION, UNSTART_ACTION } from './ticket-actions'
70import type { TicketAction } from './ticket-actions'
71import { drawnPlaces, isDrawnLine, setBox, statusNamed, STATUS_WORDS } from './ticket-boxes'
72import type { DrawnPlace } from './ticket-boxes'
73import { heldBy, highestId, lostIds, RESERVE_MS, ticketValue } from './ticket-ids'
74import type { Reservation } from './ticket-ids'
75import { findTickets, narrowTickets } from './ticket-lookup'
76import { moveQuestion, peerSendPrompt, sendScope, ticketSummary } from './ticket-prompts'
77import { beginRender, clearSpaces, columnSlots, expireSpaces, newLayout, pressKeepsSpaces } from './ticket-spaces'
78import { boardHead, boardWidth, cardWidth, fileCards, isTicketLong, listRowHeights, padCard, longItems, ticketSvg } from './todo-cards'
79import { bare, CHECKBOX, exampleMask, ITEM_ID, leadingId, lineOwnIds, parseTodo, plainText } from './todo-markdown'
80import { readReason, reasonOf, TodoReadError } from './todo-read'
81import type { TodoRead } from './todo-read'
82import { isTurnKept, readKeptUsage, stepUsage, turnKey as turnKeyOf, turnTokens } from './token-usage'
83import type { StepUsage } from './token-usage'
84import { isSkipped, nextStreak } from './unread-files'
85import type { UnreadStreak } from './unread-files'
86import { foldersWithUnread } from './unread-folders'
87import { mergeToldLines, readToldLists } from './told-notes'
88import { callDetail, callSummary, describeCall } from './tool-calls'
89import { boardTargets, buildView, columnPx, columnsThatFit, itemChipId, ledger, MIN_TICKET_PX, rowsOf, searchTodo, TICKET_GAP_PX, ticketColumns, todoLedger } from './view-model'
90import type { OrchestratorState, TicketOrder } from './view-model'
91import { failAfter, inTime, NoAnswer, RUN_LIMIT_MS, STORE_LIMIT_MS, TIMED_OUT } from './time-limit'
92import { tryWriteLock, withWriteLock } from './write-lock'
93import { deferredIds } from './deferred-tickets'
94import { stoppedKeys } from './stop-queue'
95import { blankCard, holdRoom, NO_ROOM } from './agent-room'
96import type { AgentRoom } from './agent-room'
97import { manifestVersion } from './plugin-version'
98
99const PANE = 'claudeopticon'
100const TITLE = 'Claudeopticon'
101/** The hover group of the room switch and its tip. */
102const ROOM_SCOPE = 'claudeopticon-room'
103const ROOM_TIP = 'Limit UI shift reserves interface space so new agent activity does not cause scroll jumps.'
104/** Whether this load of the mod has tried to reopen a pane that carried an older title: once, failed or not. */
105let isRetitled = false
106const TICK_MS = 1000
107const SCAN_EVERY = 3
108/** Ticks between full resyncs: every file reread whatever its mtime, the categories reloaded, the agent list asked again. */
109const RESYNC_EVERY = 60
110const CLOCK_MS = 5000
111const ITEMS_SHOWN = 12
112/** The corner button's offsets from the card's lower right corner, in cells: about even in px. */
113const ACTION_RIGHT = 2
114const ACTION_BOTTOM = 1
115/** Rows from a live agent card's top edge to its Stop button, on the title row at the card's right edge. */
116const STOP_TOP = 1
117/** The Stop button's label: blank, since the card draws the red key it lies over; two no-break spaces and the button's padding are about the key's width. */
118const STOP_HIT = '\u00a0'.repeat(2)
119/** Cells the blank Stop button's right edge sits left of the drawn key's: the button's own padding, measured on the desktop (2026-10-24). */
120const STOP_PAD_CELLS = 1
121/** The cells one corner button and its gap take, to set the tip left of them all. */
122const ACTION_CELLS = 5
123/**
124 * CSS pixels per pane cell on the desktop: an estimate, not a measure (the pane reports cells, not pixels). It must be an
125 * overestimate. A card drawn wider than the pane scales down to the pane's exact width, and the buttons placed over a card
126 * in cells (Stop, tips) then land on the scaled card at any real cell width, since both use this value. An underestimate
127 * draws every card short of the pane, out of line with the buttons outside the cards, and a Stop button over the badge
128 * (, 8.5 fell short after a desktop update, 2026-10-24).
129 */
130const CELL_PX = 10
131
132/** The tool names stay in this file: the validator reads the tool filter of a hook only from a constant here. */
133const PROGRESS_TOOL = 'mcp__claudeopticon__report_progress'
134const MOVE_TOOL = 'mcp__claudeopticon__move_ticket'
135
136/** Appended to each agent's prompt: about 100 tokens, and each report rides along with a tool call. */
137export const PROGRESS_NOTE = `
138
139Progress: if you have the ${PROGRESS_TOOL} tool, call it once you have a plan, with done (steps finished), total (steps planned) and step (a few words on the current step). If your task covers items in the project's .claude_todo/ files, also pass items: each one quoted from its line, or its #T ID. Call it again after each step, in the same message as your next tool call. Raise total if the plan grows; pass items again only if they change.`
140
141/** When each agent's claim was last set or confirmed, by agent ID. */
142const claimCheckedAt = new Map<string, number>()
143
144/**
145 * What the pane draws, held by this session's own process. Each session runs its own copy of the
146 * mod, so this can hold nothing but this session's project and agents. A hot reload starts it
147 * over; the next scan and agent list fill it again within a few seconds.
148 */
149let todoFiles: TodoFile[] = []
150let agentRows: AgentRow[] = []
151let clockMs = 0
152const expandedFiles = new Set<string>()
153/** Files whose long items show whole, past 8 lines, by the pane's file ID. */
154const openText = new Set<string>()
155let isTicketView = true
156let usage: Usage | undefined
157let orchestrator: { isActive: boolean; history: OrchestratorEntry[] } = { isActive: false, history: [] }
158let callCount = 0
159/**
160 * The tickets the orchestrator handles itself, by stored item key (keptKey): the value is whether a
161 * scan has seen the ticket in progress since the claim. A claim ends when the ticket is done, gone,
162 * or back to open after it was seen in progress. A ticket an agent works on may be in here too.
163 */
164const orchTickets = new Map<string, boolean>()
165/**
166 * The tickets this session's main conversation planned: it set the box to `[>]` itself, or the mod queued a ticket it took
167 * out of progress. By `ticketId`, as the presence record carries them. A planned ticket stays while its box is `[~]` or `[>]` (prunePlanned).
168 * A hand move on the board and a helper's edit never add to it. Saved per session as `planned:<session id>`.
169 */
170let plannedTickets: ReadonlySet<string> = new Set()
171/** The headline Claude gave the assignment it works on itself (report_progress `title`); per session, cleared with the last ticket. */
172let orchTitle: string | undefined
173/** Which page of the history the card shows: 0 the newest. */
174let orchestratorPage = 0
175/** Categories the person hid, by name; their items leave the list and the board (search still finds them). */
176const hiddenCategories = new Set<string>()
177/** Tickets already sent to Claude this session, by file and item key. */
178const sentTickets = new Set<string>()
179let isFinishedShown = false
180/** True while the Recategorize request runs: a press is ignored. */
181let isRecategorizing = false
182/** The line beside the Recategorize button, shown until `until` (clock ms); the tick clears it. */
183let recatNote: { text: string; until: number } | undefined
184const NOTE_MS = 4000
185let sortBy: 'file' | 'category' = 'file'
186/** How the board orders each column's tickets: by group, or newest ID first. */
187let ticketOrder: TicketOrder = 'group'
188let query = ''
189/** The tallest the agent area was drawn this session, held so the board below it stays put. */
190let agentRoom: AgentRoom = NO_ROOM
191/** Whether the pane holds that room at all: off by default, the reader turns it on (). */
192let isRoomHeld = false
193/** The mod's version from its plugin.json, read at each load, for the hero card's corner. */
194let pluginVersion: string | undefined
195/** The mod's version from its own plugin.json; undefined when the manifest cannot be read. */
196async function readPluginVersion($: EngineInterface): Promise<string | undefined> {
197 const text: unknown = await fsBounded($, () => $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`)).catch(() => undefined)
198
199 return typeof text === 'string' ? manifestVersion(text) : undefined
200}
201function redraw($: EngineInterface): void {
202 noteLive()
203 $.ui.invalidate('ui.render')
204 saveAgents($)
205}
206
207// ---------------------------------------------------------------- the top card's series
208
209/** What the top card plots; kept in the store per session, so a reload keeps the trace. */
210let series: Series = emptySeries()
211/** The axes the top card plots on: in memory, per session, stepped at each draw. */
212let axes: Axes | undefined
213/** The last time any code here read the clock, ms: a sync stand-in for `$.clock.now()` in the render. */
214let wallMs = 0
215/** When the pane last redrew for a token report, and whether a later report still waits for its redraw (CLOCK_MS throttle). */
216let lastBurnDraw = 0
217let isBurnDirty = false
218/** The top card redraws this often when nothing else does, so its time axis scrolls. */
219const IDLE_DRAW_MS = 30_000
220let lastIdleDraw = 0
221
222function nowSync(): number {
223 return Math.max(wallMs, clockMs)
224}
225
226/** Records the live-agent count when it changed. Waits until the kept series is loaded, so a reload cannot overwrite it. */
227function noteLive(): void {
228 if (!loadedGroups.has('series')) {
229 return
230 }
231 const count = agentRows.filter(row => !isEnded(row.status) && row.idleSince === undefined).length
232 series = addAgents(series, nowSync(), count)
233}
234
235async function seriesKey($: EngineInterface): Promise<string> {
236 return `series:${await $.session.id()}`
237}
238
239// ---------------------------------------------------------------- stable layout when a ticket leaves
240
241const layout = newLayout()
242
243// ---------------------------------------------------------------- agents kept across a reload
244
245let isAgentsLoaded = false
246
247async function agentsKey($: EngineInterface): Promise<string> {
248 return `agents:${await $.session.id()}`
249}
250
251/** The store key of the label base: how many agents came before the first kept row. */
252async function baseKey($: EngineInterface): Promise<string> {
253 return `agents-base:${await $.session.id()}`
254}
255
256/** The number of agents before `agentRows[0]`, so A201 stays A201 after a reload drops older rows. */
257let agentBase = 0
258
259const reservedIds = new Map<string, Reservation>()
260
261/**
262 * The store key of the reservations: one per repo (the main checkout's root), so every session on it
263 * shares one key. Outside git, the primary todo folder's real path stands in for the repo, so two
264 * sessions in one folder still share a key; the session ID only when there is no folder.
265 */
266async function reservedKey($: EngineInterface): Promise<string> {
267 const primary = todoFolders?.find(one => !one.isOther)
268
269 return `reserved:${centralRoot ?? repoRoot ?? primary?.real ?? primary?.path ?? (await $.session.id())}`
270}
271
272/** This session's ID, as reservations name their holder. */
273function sessionOf($: EngineInterface): Promise<string> {
274 return Promise.resolve().then(() => $.session.id()).catch(() => 'session')
275}
276
277/** Drops the reserved IDs that a file holds now (on the board, or in `held`: IDs just read from the disk), and the expired ones. */
278function pruneReserved(time = nowSync(), held: Iterable<string> = []): void {
279 const all = new Set([...projectIds(), ...held])
280 for (const [id, one] of reservedIds) {
281 if (all.has(id) || one.until <= time) {
282 reservedIds.delete(id)
283 }
284 }
285}
286
287/** The reservation writes of this session run one after another, so each read-modify-write sees the last. */
288let reserveChain: Promise<unknown> = Promise.resolve()
289
290/** Store rounds per sync: each writes, and the next reads back what another session may have written meanwhile. The last only reads. */
291const SYNC_ROUNDS = 4
292
293/**
294 * Merges the repo's stored reservations into memory (an entry that is not expired, and not in
295 * `removed` when this session holds it), prunes (`held`: IDs a file holds), then stores the union and
296 * reads it back, until the store holds it (an overlapping write of another session that
297 * dropped an entry is repaired). An ID this session held that the store gives to another session is
298 * lost: the store's holder keeps it, and the ID leaves this session's hands. A failed read leaves the
299 * store alone: it never writes over what it could not read. Resolves the lost IDs, or undefined when
300 * a read of the store (the read-back after a write included) failed.
301 *
302 * The store has only get and set, with no compare-and-set across sessions, so this record alone
303 * cannot keep two sessions off one ID: the ID block claims do (`freeIds`). The record keeps
304 * the offers of this session across a reload, and the IDs of a session of an older build count.
305 */
306function syncReserved($: EngineInterface, removed: readonly string[] = [], held: readonly string[] = []): Promise<string[] | undefined> {
307 const job = async (): Promise<string[] | undefined> => {
308 const me = await sessionOf($)
309 const key = await reservedKey($)
310 const gone = new Set(removed)
311 const lost: string[] = []
312 for (let round = 0; round < SYNC_ROUNDS; round += 1) {
313 const got = await tryGet($, key)
314 // A read that fails, the read-back after a write included, is no answer: the caller cannot tell what the store holds.
315 if (!got.ok) {
316 return undefined
317 }
318 const time = nowSync()
319 // An ID given back is dropped from the store only while this session holds it there: never another session's entry.
320 const stored = readKeptReserved(got.value).filter(([id, one]) => !(gone.has(id) && heldBy(one) === me))
321 for (const id of lostIds(reservedIds, stored, me, time)) {
322 reservedIds.delete(id)
323 lost.push(id)
324 }
325 for (const [id, one] of stored) {
326 if (one.until > time && !reservedIds.has(id)) {
327 reservedIds.set(id, one)
328 }
329 }
330 pruneReserved(time, held)
331 const value = [...reservedIds].map(([id, one]) => [id, one.until, one.offeredTo ?? null, one.by ?? null])
332 // Done when the store already holds exactly this; else written, and read back in the next round.
333 if (JSON.stringify(value) === JSON.stringify(got.value ?? []) || round === SYNC_ROUNDS - 1) {
334 return lost
335 }
336 await storeSet($, key, value)
337 }
338
339 return lost
340 }
341 const run = reserveChain.then(job, job).catch(() => undefined)
342 reserveChain = run
343
344 return run
345}
346
347/** The orchestrator's tickets are kept beside the agent rows, per session, so a reload keeps them. */
348async function orchKey($: EngineInterface): Promise<string> {
349 return `orchestrator:${await $.session.id()}`
350}
351
352async function plannedStoreKey($: EngineInterface): Promise<string> {
353 return plannedKey(await $.session.id())
354}
355
356async function orchTitleKey($: EngineInterface): Promise<string> {
357 return `orchestrator-title:${await $.session.id()}`
358}
359
360/** A store read: the value (undefined when the key is absent), or a failure. A failure is not an absent key. */
361type Got = { ok: true; value: unknown } | { ok: false }
362
363/**
364 * The store keys whose last call went unanswered for STORE_LIMIT_MS; an answer for the
365 * key, a rejection included, takes it out. While any key is in it the store is stalled, and the
366 * hooks do not wait on store work (unlessStoreWaits): a load would read that key again. By key, so
367 * one key that never answers is not hidden by others that do.
368 */
369const stalledKeys = new Set<string>()
370
371/** One store call for `key` under the store time limit: an unanswered call fails with NoAnswer and marks the key stalled. */
372function storeCall<T>($: EngineInterface, key: string, call: () => Promise<T>): Promise<T> {
373 return Promise.resolve()
374 .then(() => failAfter(Promise.resolve(call()), STORE_LIMIT_MS, (ms, fire) => $.clock.after(ms, fire)))
375 .then(
376 value => {
377 stalledKeys.delete(key)
378
379 return value
380 },
381 (error: unknown) => {
382 if (error instanceof NoAnswer) {
383 stalledKeys.add(key)
384 } else {
385 stalledKeys.delete(key)
386 }
387 throw error
388 },
389 )
390}
391
392/** A read that has not answered within STORE_LIMIT_MS is a failed read: a store that never answers never holds a hook. */
393function tryGet($: EngineInterface, key: string): Promise<Got> {
394 return storeCall($, key, () => $.store.get(key))
395 .then(
396 (value): Got => ({ ok: true, value }),
397 (): Got => ({ ok: false }),
398 )
399}
400
401/**
402 * A store write, rejected when it has not answered within STORE_LIMIT_MS, as a write that
403 * failed: each caller tries it again or goes on, as it does for a store that rejects. A write that
404 * only answers late may still land; each key is written whole, so a late write is one older copy that
405 * the next write replaces.
406 */
407function storeSet($: EngineInterface, key: string, value: unknown): Promise<void> {
408 return storeCall($, key, () => $.store.set(key, value)).then(() => undefined)
409}
410
411/**
412 * The one way the rows change. Keeps at most KEPT_AGENTS in memory: the oldest go, and `agentBase`
413 * grows by the number dropped, so a label stays the same (A201 stays A201). `rowsVersion` counts
414 * real changes, which is all the store step compares: it never rebuilds the JSON to find out.
415 */
416function setRows(next: AgentRow[]): void {
417 let rows = next
418 if (rows.length > KEPT_AGENTS) {
419 const dropped = rows.length - KEPT_AGENTS
420 // Never past MAX_BASE: a stored base past it reads back as 0, and every label would change on reload. The save toasts once when it is reached.
421 agentBase = Math.min(MAX_BASE, agentBase + dropped)
422 setLabelBase(agentBase)
423 // The cut rows are remembered, so the agent list never adds them back as new rows.
424 for (const row of rows.slice(0, dropped)) {
425 cutRowIds.add(row.id)
426 }
427 cutRowVersion += 1
428 while (cutRowIds.size > KEPT_CUT) {
429 cutRowIds.delete(cutRowIds.values().next().value!)
430 }
431 rows = rows.slice(dropped)
432 }
433 if (!sameRows(agentRows, rows)) {
434 rowsVersion += 1
435 }
436 agentRows = rows
437}
438
439/** Bumped by each real change of the rows. */
440let rowsVersion = 0
441
442/** The IDs of the rows cut from the kept window: kept per session, so neither a refresh nor a reload adds one back. */
443const cutRowIds = new Set<string>()
444/** Bumped by each change of `cutRowIds`: the stamp its save compares. */
445let cutRowVersion = 0
446
447async function cutKey($: EngineInterface): Promise<string> {
448 return `agents-cut:${await $.session.id()}`
449}
450
451/** When this session last noted itself in the session list, clock ms; undefined before the first note. Set only by a note that was stored. */
452let lastTouch: number | undefined
453/** When the last note failed, clock ms; undefined while no note failed. It is tried again SESSION_RETRY_MS later. */
454let touchFailedAt: number | undefined
455let isTouching = false
456/** The notes that failed in a row, and whether the toast that says so is shown (it clears with the next note that is stored). */
457let touchFailures = 0
458let isTouchToastShown = false
459
460/**
461 * Notes this session in the store's list of the last KEPT_SESSIONS sessions, with the time, and
462 * clears the keys of the sessions that fell off it. The session start calls it, and so does the save
463 * every SESSION_TOUCH_MS, so a session that runs for days stays in the list: a session that
464 * noted itself in the last SESSION_LIVE_MS is never cleared. The times are in the list itself, one
465 * key and one write; the old `sessions-seen` key is only read, for a list in the older form. The
466 * store has no delete, so a key is overwritten with null; every reader treats null as absent. The
467 * list is written first. A failed read of the list (or of the old times a list in the older form
468 * needs) clears nothing. A note that is not stored is tried again after SESSION_RETRY_MS. A session
469 * that finds itself gone from the list (cleared while it was asleep) writes every key again with its
470 * next save.
471 */
472async function pruneSessions($: EngineInterface): Promise<void> {
473 const time = await $.clock.now()
474 try {
475 await noteSession($, time)
476 lastTouch = time
477 touchFailedAt = undefined
478 touchFailures = 0
479 isTouchToastShown = false
480 } catch (error) {
481 touchFailedAt = time
482 touchFailures += 1
483 // Like a failing save (saveKey): one toast after SAVE_FAILS_TOAST failures in a row. Until a note is stored, other sessions may clear this session's keys.
484 if (touchFailures >= SAVE_FAILS_TOAST && !isTouchToastShown) {
485 isTouchToastShown = true
486 try {
487 showToast($, `Claudeopticon cannot note this session in the store: ${touchFailures} notes in a row failed. Another session may clear what this session saved.`)
488 } catch {
489 // A toast that fails must not hide the failed note.
490 }
491 }
492 throw error
493 }
494}
495
496/** One note of this session in the session list; throws when the list is not read or not stored. */
497async function noteSession($: EngineInterface, time: number): Promise<void> {
498 const me = await $.session.id()
499 const [got, seenGot] = await Promise.all([tryGet($, 'sessions-recent'), tryGet($, 'sessions-seen')])
500 if (!got.ok || (!seenGot.ok && isOldSessionList(got.value))) {
501 throw new Error('session list read failed')
502 }
503 wallMs = Math.max(wallMs, time)
504 const { list, dropped, untimed, isListed } = nextSessions(got.value, seenGot.ok ? seenGot.value : undefined, me, time)
505 // A session the list forgets is queued in `sessions-dropping` first: once the list no longer names it, no later note finds it dropped, so its keys would never be cleared. A queue that is not read or not stored throws before the list is written, and the next note starts from the same list.
506 const droppedTimed = dropped.filter(one => !untimed.includes(one))
507 if (droppedTimed.length > 0) {
508 const queued = await tryGet($, 'sessions-dropping')
509 if (!queued.ok) {
510 throw new Error('session list read failed')
511 }
512 const held = readDropping(queued.value)
513 const queue = new Map(held)
514 for (const id of droppedTimed) {
515 if (!queue.has(id)) {
516 queue.set(id, time)
517 }
518 }
519 if (queue.size !== held.size) {
520 await storeSet($, 'sessions-dropping', [...queue].slice(-KEPT_DROPPING))
521 }
522 }
523 await storeSet($, 'sessions-recent', list)
524 if (isOldSessionList(got.value)) {
525 // The list is in the new form now; the old times key is not read again.
526 await storeSet($, 'sessions-seen', null).catch(() => undefined)
527 }
528 if (!isListed) {
529 saved.clear()
530 saved.set('title', undefined)
531 }
532 // A dropped session that noted itself while this call read a stale list is live: it keeps its keys.
533 // A session with a time is cleared only in two steps: found droppable now, it waits in
534 // `sessions-dropping`, and a note SESSION_DROP_CONFIRM_MS later clears its keys only when a read of
535 // the list made then still shows it not live. One read cannot tell a dead session from a live one
536 // whose note this write just overwrote (it read the list before that note and wrote after it); the
537 // live one notes itself again within SESSION_TOUCH_MS, so the second step sees it.
538 const timed = droppedTimed
539 const pendingGot = await tryGet($, 'sessions-dropping')
540 const pendingBefore = pendingGot.ok ? readDropping(pendingGot.value) : new Map<string, number>()
541 const fresh = untimed.length === 0 && timed.length === 0 && pendingBefore.size === 0 ? undefined : await tryGet($, 'sessions-recent')
542 const live = fresh?.ok === true ? new Set([...liveSessionIds(fresh.value, time), ...liveSessionIds(list, time)]) : liveSessionIds(list, time)
543 // With the pending list or the fresh read missing, no timed session is cleared: the step waits for a note that reads both.
544 const step = pendingGot.ok && fresh?.ok === true ? nextDropping(pendingBefore, timed, live, time) : undefined
545 if (step !== undefined && JSON.stringify([...step.pending]) !== JSON.stringify([...pendingBefore])) {
546 await storeSet($, 'sessions-dropping', [...step.pending]).catch(() => undefined)
547 }
548 const clear = [...untimed.filter(one => !live.has(one)), ...(step?.confirmed ?? [])]
549 for (const id of clear) {
550 for (const prefix of SESSION_PREFIXES) {
551 await storeSet($, `${prefix}:${id}`, null).catch(() => undefined)
552 }
553 }
554}
555
556/** The groups of per-session keys, loaded each on its own: the save names of each group. The rows, their label base and their cut IDs belong together, since the base counts rows. */
557type StoreGroup = 'rows' | 'tickets' | 'title' | 'series'
558const GROUP_NAMES: Record<StoreGroup, readonly string[]> = { rows: ['agents', 'base', 'cut'], tickets: ['tickets', 'planned'], title: ['title'], series: ['series'] }
559/** The groups whose stored value was read and merged: only these are ever saved, so a key that did not read is never written over. */
560const loadedGroups = new Set<StoreGroup>()
561
562/**
563 * The load of what this session kept in the store. Every caller awaits the same promise, so nothing
564 * merges twice. Each group loads on its own: a group whose read worked is merged and saved
565 * from then on; one whose read failed stays unsaved, and the next caller reads it again.
566 * `isAgentsLoaded` turns true once every group is loaded.
567 */
568let loading: Promise<void> | undefined
569function loadAgents($: EngineInterface): Promise<void> {
570 if (isAgentsLoaded) {
571 return Promise.resolve()
572 }
573 loading ??= readStores($).finally(() => {
574 loading = undefined
575 })
576
577 return loading
578}
579
580/**
581 * Reads each group not loaded yet and merges the ones that read, under what was seen since the
582 * load: a row seen since the load wins. An agent whose ticket match already ran is not matched
583 * again. Rejects when any group failed, so a caller knows the load is not whole.
584 */
585async function readStores($: EngineInterface): Promise<void> {
586 const want = (['rows', 'tickets', 'title', 'series'] as const).filter(group => !loadedGroups.has(group))
587 const keyOf: Record<StoreGroup, () => Promise<string[]>> = {
588 rows: () => Promise.all([agentsKey($), baseKey($), cutKey($)]),
589 tickets: async () => [await orchKey($), await plannedStoreKey($)],
590 title: async () => [await orchTitleKey($)],
591 series: async () => [await seriesKey($)],
592 }
593 const reads = await Promise.all(want.map(async group => ({ group, got: await Promise.all((await keyOf[group]()).map(key => tryGet($, key))) })))
594 // The clock is read before any merge: the series read bounds kept points by it, and a clock nothing has read yet is 0, which would drop every kept point as future.
595 wallMs = Math.max(wallMs, await $.clock.now())
596 // From here to the end there is no await: each merge is one step, and its group turns loaded with it.
597 let isWhole = true
598 for (const { group, got } of reads) {
599 if (!got.every(one => one.ok)) {
600 isWhole = false
601 continue
602 }
603 const values = got.map(one => (one.ok ? one.value : undefined))
604 mergeGroup(group, values)
605 loadedGroups.add(group)
606 // The first save after a load rewrites the group's keys (the title only when there is one).
607 for (const name of GROUP_NAMES[group]) {
608 saved.delete(name)
609 }
610 if (group === 'title') {
611 saved.set('title', undefined)
612 }
613 }
614 seedTrace()
615 if (loadedGroups.size === Object.keys(GROUP_NAMES).length) {
616 isAgentsLoaded = true
617 }
618 if (!isWhole) {
619 throw new Error('store read failed')
620 }
621}
622
623/** Merges one group's stored values into the session state. */
624function mergeGroup(group: StoreGroup, values: readonly unknown[]): void {
625 if (group === 'rows') {
626 const [agentsRaw, base, cutRaw] = values
627 for (const id of readKeptCut(cutRaw)) {
628 cutRowIds.add(id)
629 }
630 const kept = readKeptAgents(agentsRaw).filter(row => !cutRowIds.has(row.id))
631 const keptBase = readKeptBase(base)
632 // Never lowered: cuts made while the group did not load moved the base on, and a label once shown keeps its number.
633 if (kept.length > 0 && keptBase > agentBase) {
634 agentBase = keptBase
635 setLabelBase(agentBase)
636 }
637 // A row the list added back before the cut IDs were read goes again.
638 const live = agentRows.filter(row => !cutRowIds.has(row.id))
639 const seen = new Set(live.map(row => row.id))
640 setRows([...kept.filter(row => !seen.has(row.id)), ...live])
641 for (const row of kept) {
642 if (row.autoClaims !== undefined) {
643 matchedAgents.add(row.id)
644 }
645 }
646 } else if (group === 'tickets') {
647 for (const [kept, seen] of readKeptTickets(values[0])) {
648 // A key stored with a place number is read as its first-place key: never a place.
649 const key = storedKey(kept)
650 if (!orchTickets.has(key)) {
651 orchTickets.set(key, seen)
652 }
653 }
654 // What this load added to the planned set since the read stays; a stored ticket joins it.
655 plannedTickets = new Set([...readPlanned(values[1]), ...plannedTickets])
656 } else if (group === 'title') {
657 // A title kept by an older version is checked again, as a new one is.
658 orchTitle ??= hideTitle(readTitle(values[0]))
659 } else {
660 // A clock still unknown (0) sets no future bound.
661 const keptSeries = readKeptSeries(values[0], nowSync() > 0 ? nowSync() : Infinity)
662 const after = (points: readonly (readonly [number, number])[], from: readonly (readonly [number, number])[]) => [...from, ...points.filter(point => point[0] > (from[from.length - 1]?.[0] ?? -Infinity))]
663 series = {
664 agents: after(series.agents, keptSeries.agents),
665 tokens: after(series.tokens, keptSeries.tokens),
666 compacts: [...keptSeries.compacts, ...series.compacts.filter(one => one > (keptSeries.compacts[keptSeries.compacts.length - 1] ?? -Infinity))],
667 // The times of seeded points, kept and new, so a reload never counts a seed's rise as usage.
668 ...(keptSeries.seeds === undefined && series.seeds === undefined ? {} : { seeds: [...new Set([...(keptSeries.seeds ?? []), ...(series.seeds ?? [])])] }),
669 }
670 }
671}
672
673/** What was last stored for each key, as the stamp compared next time: set when the write resolved, never before. */
674const saved = new Map<string, unknown>()
675/** The stamp of a write still out, so a redraw does not start the same write twice. */
676const writing = new Map<string, unknown>()
677
678/** The failed writes in a row of each save name, and when it is tried next. */
679const saveFailures = new Map<string, Failing>()
680/** The first wait after a failed write, and the longest: 1 s doubling to 5 min. */
681const SAVE_RETRY_MS = 1000
682const SAVE_RETRY_MAX_MS = 5 * 60_000
683/** After this many failed writes in a row of one key, one toast says nothing is kept. */
684const SAVE_FAILS_TOAST = 5
685/** True once the store toast is shown; shown again only after every key was stored once more. */
686let isSaveToastShown = false
687/** True once the label-base toast is shown. */
688let isBaseToastShown = false
689
690/**
691 * Stores `value` under `name`'s key unless `stamp` is what was stored last (or is being stored now).
692 * The marker is set when the write resolves, and cleared when it fails. A failed write is tried
693 * again with a later redraw, after a wait per key: 1 s, doubled for each failure in a row,
694 * up to 5 min, so a store that rejects every write does not get every key again with every redraw.
695 * After SAVE_FAILS_TOAST failures in a row, one toast says so.
696 */
697function saveKey($: EngineInterface, name: string, prefix: string, stamp: unknown, value: unknown): void {
698 if ((saved.has(name) && Object.is(saved.get(name), stamp)) || (writing.has(name) && Object.is(writing.get(name), stamp))) {
699 return
700 }
701 if (!isRetryDue(saveFailures.get(name), nowSync(), SAVE_RETRY_MAX_MS)) {
702 return
703 }
704 writing.set(name, stamp)
705 void $.session.id()
706 .then(id => storeSet($, `${prefix}:${id}`, value))
707 .then(
708 () => {
709 saved.set(name, stamp)
710 saveFailures.delete(name)
711 if (saveFailures.size === 0) {
712 isSaveToastShown = false
713 }
714 },
715 () => {
716 saved.delete(name)
717 const failing = addFailure(saveFailures.get(name), nowSync(), SAVE_RETRY_MS, SAVE_RETRY_MAX_MS)
718 saveFailures.set(name, failing)
719 if (failing.count >= SAVE_FAILS_TOAST && !isSaveToastShown) {
720 isSaveToastShown = true
721 try {
722 showToast($, `Claudeopticon cannot save to the store: ${failing.count} writes in a row failed. The pane works, but a reload loses what this session saw.`)
723 } catch {
724 // A toast that fails must not turn a failed write into an unhandled rejection.
725 }
726 }
727 },
728 )
729 .finally(() => {
730 if (Object.is(writing.get(name), stamp)) {
731 writing.delete(name)
732 }
733 })
734}
735
736/**
737 * Stores what changed since the last store, for each group whose stored value was loaded:
738 * a group that did not read is never written over. Every SESSION_TOUCH_MS it notes the session in
739 * the session list again.
740 */
741function saveAgents($: EngineInterface): void {
742 const time = nowSync()
743 // A load with no session start (a hot reload) counts the interval from its first save.
744 // A note that failed is not a note: it is tried again SESSION_RETRY_MS after it.
745 lastTouch ??= time > 0 && touchFailedAt === undefined ? time : undefined
746 // Timed with elapsedSince: a clock set back restarts the wait from now, so the notes go on and no other session prunes this one.
747 const touch = lastTouch === undefined ? undefined : elapsedSince(lastTouch, time)
748 const retry = touchFailedAt === undefined ? undefined : elapsedSince(touchFailedAt, time)
749 lastTouch = touch?.from
750 touchFailedAt = retry?.from
751 // After a failed note the retry time is the due time: lastTouch stays old then, so the touch
752 // interval alone would make every redraw a try.
753 const isDue = retry !== undefined ? retry.ms >= SESSION_RETRY_MS : touch !== undefined && touch.ms >= SESSION_TOUCH_MS
754 if (agentBase >= MAX_BASE && !isBaseToastShown) {
755 isBaseToastShown = true
756 showToast($, `Agent labels reached A${MAX_BASE}: from here on, a label may name another agent than it did before.`)
757 }
758 if (!isTouching && isDue) {
759 isTouching = true
760 void pruneSessions($)
761 .catch(() => undefined)
762 .finally(() => {
763 isTouching = false
764 })
765 }
766 // Small values compare by text; the archive by identity (it is replaced, never edited); the rows by version.
767 if (loadedGroups.has('tickets')) {
768 const tickets = JSON.stringify([...orchTickets])
769 saveKey($, 'tickets', 'orchestrator', tickets, [...orchTickets])
770 saveKey($, 'planned', 'planned', JSON.stringify([...plannedTickets]), [...plannedTickets])
771 }
772 if (loadedGroups.has('title')) {
773 saveKey($, 'title', 'orchestrator-title', orchTitle, orchTitle ?? '')
774 }
775 if (loadedGroups.has('series')) {
776 saveKey($, 'series', 'series', JSON.stringify(series), series)
777 }
778 if (!loadedGroups.has('rows')) {
779 return
780 }
781 saveKey($, 'base', 'agents-base', agentBase, agentBase)
782 saveKey($, 'cut', 'agents-cut', cutRowVersion, [...cutRowIds])
783 if (!(saved.has('agents') && saved.get('agents') === rowsVersion) && !(writing.has('agents') && writing.get('agents') === rowsVersion)) {
784 // Every stored brief goes through storedBrief: its secrets hidden and its length capped.
785 saveKey(
786 $,
787 'agents',
788 'agents',
789 rowsVersion,
790 agentRows.map(row => {
791 const brief = storedBrief(row.brief)
792
793 return brief === row.brief ? row : { ...row, brief }
794 }),
795 )
796 }
797}
798
799// ---------------------------------------------------------------- todo
800
801/**
802 * Finds the project's own todo folder: `.claude_todo/` at the root of the repo the session works
803 * in, or of its main checkout from a git worktree (whose `.git` file names it; `.claude_todo/` may
804 * be gitignored, so a worktree may have none). Outside a repo, only the session folder's own. Never
805 * the `.claude_todo/` in the home `.claude` folder, which belongs to no project.
806 */
807export async function findTodoDir($: EngineInterface): Promise<string | undefined> {
808 return findTodoDirWith({
809 exists: path => fsBounded($, () => $.fs.exists(path)),
810 kind: path => fsBounded($, () => $.fs.stat(path)).then(stat => stat.kind).catch(() => undefined),
811 realPath: path => realOf($, path),
812 read: path => $.fs.read(path).then(text => (typeof text === 'string' ? text : '')).catch(() => ''),
813 })
814}
815/** True once the environment gave a usable home; false means every write is off (fail closed). Windows paths need no home: the text rule covers them. */
816let globalsKnown = false
817let globalsToasted = false
818
819/**
820 * Reads one environment variable as the forms of an absolute folder (`envDirs`): through `printenv`
821 * (no shell), and where `printenv` cannot start (Windows has none) through PowerShell with the name
822 * as a fixed literal. Empty when unset, failed, timed out, or not an absolute path.
823 */
824async function envPath($: EngineInterface, name: 'HOME' | 'USERPROFILE' | 'CLAUDE_CONFIG_DIR'): Promise<string[]> {
825 // Bounded: a call that does not return is a failure, told once, and the mod fails closed as for no home.
826 const ask = async (argv: string[]) => {
827 const ran = await runInTime($, argv)
828 if (ran === TIMED_OUT) {
829 noteTimedOut($, argv)
830
831 return { timedOut: true } as const
832 }
833
834 return ran
835 }
836 let done = await ask(['printenv', name])
837 // Not started (a throw) or not found (exit 127, as the trash code reads it): where there is no printenv, ask PowerShell.
838 if (done === undefined || ('exitCode' in done && done.exitCode === 127)) {
839 done = await ask(['powershell.exe', '-NoProfile', '-NonInteractive', '-Command', `[Environment]::GetEnvironmentVariable('${name}')`])
840 }
841
842 return envDirs(done !== undefined && 'exitCode' in done && done.exitCode === 0 ? done.stdout.split('\n')[0] : undefined)
843}
844
845/**
846 * Finds the global todo folders of this machine, once per load: under HOME (USERPROFILE, a Windows
847 * home, when HOME is not set) and CLAUDE_CONFIG_DIR. Without a readable home the mod fails closed.
848 */
849async function loadGlobals($: EngineInterface): Promise<void> {
850 // Built aside, swapped in with no await between (`replaceGlobals`): a write check during the load sees the folders of the last load, never none.
851 const dirs = new Set<string>()
852 const parentSet = new Set<string>()
853 let homes = await envPath($, 'HOME')
854 if (homes.length === 0) {
855 homes = (await envPath($, 'USERPROFILE')).filter(isWinPath)
856 }
857 const configs = await envPath($, 'CLAUDE_CONFIG_DIR')
858 const home = homes[0]
859 const parents = [...homes.map(one => `${one.replace(/\/$/, '')}/.claude`), ...configs.map(one => one.replace(/\/$/, ''))]
860 for (const parent of parents) {
861 parentSet.add(parent)
862 const dir = `${parent}/${DIR}`
863 dirs.add(dir)
864 const real = await realOf($, dir)
865 if (real !== undefined) {
866 dirs.add(real.replace(/\/+$/, ''))
867 }
868 // The parent exists at load even when `.claude_todo` does not yet: a symlinked `~/.claude`,
869 // HOME or CLAUDE_CONFIG_DIR (stow, chezmoi) gives the real path a folder made later will have.
870 const realParent = await realOf($, parent)
871 if (realParent !== undefined) {
872 dirs.add(`${realParent.replace(/[\\/]+$/, '')}/${DIR}`)
873 }
874 }
875 replaceGlobals(dirs, parentSet)
876 globalsKnown = home !== undefined
877}
878
879// ---------------------------------------------------------------- folders
880
881/**
882 * The pathspecs that limit `git ls-files` to todo folders: every path inside a `.claude_todo`
883 * folder at any depth, and the folder itself for the ignored listing, where git gives an ignored
884 * folder as one collapsed entry. `icase` keeps the case-only spellings `todoFoldersIn` reads
885 *. On a real index of 90,002 entries the whole listing is 4,950,053 bytes, past the
886 * engine's 4 MiB stdout cap; with these it is the todo entries only (53 bytes).
887 */
888const TODO_PATHSPECS = [`:(icase,glob)**/${DIR}/**`, `:(icase,glob)**/${DIR}`]
889
890/** A `git ls-files` that failed, threw, did not return in time or was cut at the engine's stdout cap: the folder list is unknown, never empty. */
891class FolderListError extends Error {}
892
893/**
894 * The `.claude_todo/` folders of a checkout, tracked, untracked and ignored, through git. Each call is
895 * bounded (`runInTime`). A call that throws, exits non-zero, times out, or whose output the
896 * engine cut at its stdout cap (it keeps the first 4 MiB and still gives exit 0) throws
897 * `FolderListError`: no list is not an empty list.
898 */
899async function listFolders($: EngineInterface, root: string): Promise<{ path: string; rel: string }[]> {
900 const run = async (argv: string[]) => {
901 const done = await runInTime($, argv, { cwd: root })
902 if (done === TIMED_OUT) {
903 noteTimedOut($, argv)
904 throw new FolderListError(`git ls-files did not return within ${RUN_LIMIT_MS / 1000} s`)
905 }
906 if (done === undefined || done.exitCode !== 0) {
907 const said = typeof done?.stderr === 'string' ? done.stderr.trim().split('\n')[0] ?? '' : ''
908 throw new FolderListError(done === undefined ? 'git ls-files did not start' : `git ls-files exited ${done.exitCode}${said === '' ? '' : `: ${said}`}`)
909 }
910 if ((done as { isStdoutTruncated?: boolean }).isStdoutTruncated === true) {
911 throw new FolderListError('git ls-files output was cut at the size limit')
912 }
913
914 return done.stdout
915 }
916 const tracked = await run(['git', 'ls-files', '-z', '--cached', '--others', '--exclude-standard', '--', ...TODO_PATHSPECS])
917 const ignored = await run(['git', 'ls-files', '-z', '--others', '--ignored', '--exclude-standard', '--directory', '--', ...TODO_PATHSPECS])
918
919 return todoFoldersIn(`${tracked}\0${ignored}`, root)
920}
921
922/** True once a folder-list failure was told; a list that works clears it, so the next failure is told again. */
923let listFailToasted = false
924
925/** Tells once that git could not list the todo folders, and what the board does instead. */
926function noteListFailed($: EngineInterface, error: FolderListError, isKept: boolean): void {
927 if (!listFailToasted) {
928 listFailToasted = true
929 showToast($, `Claudeopticon could not list the todo folders (${error.message}). ${isKept ? 'The board keeps the folders it had' : 'The board shows the nearest todo folder only'} until a later search works: press Consolidate todos or reload the mod to search again.`)
930 }
931}
932
933/**
934 * One fs read under the time limit of an outside call (RUN_LIMIT_MS, at most; calls started in one bucket share a timer). The engine's fs gives no time limit of its
935 * own, and the files may sit on a network mount or a stuck volume; a read that never answers would hold the
936 * scan, and with it every later scan, for the whole session. An unanswered read rejects with NoAnswer, so it is
937 * a failed read: never a missing file, an empty file or an empty folder. Use it only where a rejection already
938 * means "could not be read". The call itself is not stopped; its late result is dropped. Writes are not bounded:
939 * a write that gave no answer may still land, and a retry would not know.
940 */
941function fsBounded<T>($: EngineInterface, call: () => Promise<T>): Promise<T> {
942 return new Promise<T>((resolve, reject) => {
943 const bucket = fsBucketFor($)
944 const giveUp = () => reject(new NoAnswer(`no answer within ${RUN_LIMIT_MS / 1000} s`))
945 bucket.add(giveUp)
946 Promise.resolve()
947 .then(call)
948 .then(
949 value => {
950 bucket.delete(giveUp)
951 resolve(value)
952 },
953 (error: unknown) => {
954 bucket.delete(giveUp)
955 reject(error)
956 },
957 )
958 })
959}
960
961/** How long one bucket of fs calls takes new calls: a call waits between RUN_LIMIT_MS minus this and RUN_LIMIT_MS. */
962const FS_BUCKET_MS = 5000
963/** The calls started since the open bucket began: one timer gives them all up, so a scan of many files holds two timers, not one per call. */
964let fsBucket: Set<() => void> | undefined
965
966/** The bucket that a new fs call joins; the first call after the last bucket closed opens the next, with its two timers. */
967function fsBucketFor($: EngineInterface): Set<() => void> {
968 if (fsBucket !== undefined) {
969 return fsBucket
970 }
971 const bucket = new Set<() => void>()
972 fsBucket = bucket
973 // A timer the engine refuses leaves the calls of this bucket unbounded, as for a store call; they still settle by their own answer.
974 const arm = (ms: number, fire: () => void) => {
975 try {
976 const timer: unknown = $.clock.after(ms, fire)
977 if (typeof (timer as { then?: unknown } | null)?.then === 'function') {
978 void (timer as Promise<unknown>).then(undefined, () => undefined)
979 }
980 } catch {
981 // Nothing to do: the bucket stays open and its calls are not timed.
982 }
983 }
984 arm(FS_BUCKET_MS, () => {
985 if (fsBucket === bucket) {
986 fsBucket = undefined
987 }
988 })
989 arm(RUN_LIMIT_MS, () => {
990 for (const giveUp of [...bucket]) {
991 giveUp()
992 }
993 bucket.clear()
994 if (fsBucket === bucket) {
995 fsBucket = undefined
996 }
997 })
998
999 return bucket
1000}
1001
1002/**
1003 * The real path of a folder in the one spelling the mod uses (`normPath`), or undefined when it cannot
1004 * be resolved. The engine's realpath gives backslashes on Windows: kept raw, the session
1005 * folder became `C:\proj`, its todo `C:\proj/.claude_todo`, which the trust check refuses, and the
1006 * claim folder was cut at a `/` it does not have. A POSIX path is returned as it is.
1007 */
1008function realOf($: EngineInterface, path: string): Promise<string | undefined> {
1009 return fsBounded($, () => $.fs.stat(path, { resolve: true })).then(stat => (typeof stat.realPath === 'string' ? normPath(stat.realPath) : stat.realPath)).catch(() => undefined)
1010}
1011
1012/** The todo folders found but cut from the pane by MAX_FOLDERS; their ticket IDs still count. */
1013let cutFolders: string[] = []
1014let cutToasted = false
1015/** The ticket IDs (lowercase) of every file in the cut folders, so a new ID never repeats one of theirs. */
1016let cutIds: string[] = []
1017
1018/** The ticket IDs of each file of the cut folders, by path, from its last good read. */
1019let cutIdsByFile = new Map<string, string[]>()
1020/** The files of the cut folders that have not read once: their IDs are unknown, so new IDs wait for them (`diskIds`). */
1021let cutUnknown = new Set<string>()
1022
1023/**
1024 * Reads the ticket IDs of the cut folders (top level and archive). A file that does not read, or a
1025 * folder that does not list, keeps the IDs of its last good read: a failed read is never
1026 * an empty file. A file whose first read fails is unknown (`cutUnknown`), with one toast, and stops new
1027 * IDs until it reads or is skipped. A file that is gone holds none.
1028 */
1029async function refreshCutIds($: EngineInterface): Promise<void> {
1030 const next = new Map<string, string[]>()
1031 const unknown = new Set<string>()
1032 for (const folder of cutFolders) {
1033 const names = await mdFiles($, folder, true).catch(() => undefined)
1034 if (names === undefined) {
1035 for (const [path, ids] of cutIdsByFile) {
1036 if (path.startsWith(`${folder}/`)) {
1037 next.set(path, ids)
1038 }
1039 }
1040 for (const path of cutUnknown) {
1041 if (path.startsWith(`${folder}/`)) {
1042 unknown.add(path)
1043 }
1044 }
1045 continue
1046 }
1047 for (const name of names) {
1048 const path = `${folder}/${name}`
1049 const read = await readTodo($, path)
1050 const was = cutIdsByFile.get(path)
1051 if (read.kind === 'ok') {
1052 next.set(path, textIds(read.text))
1053 unreadToasted.delete(path)
1054 } else if (read.kind === 'failed' && was !== undefined) {
1055 next.set(path, was)
1056 } else if (read.kind === 'failed') {
1057 // Its first read failed: its IDs are unknown, never none. Named once, until it reads.
1058 unknown.add(path)
1059 if (!unreadToasted.has(path)) {
1060 unreadToasted.add(path)
1061 showToast($, `${path} did not read (${read.reason}). Its ticket IDs are unknown, so no new ticket ID is given until it reads.`)
1062 }
1063 }
1064 }
1065 }
1066 cutIdsByFile = next
1067 cutUnknown = unknown
1068 cutIds = [...next.values()].flat()
1069}
1070
1071/** The repo root of the session, kept to name a folder found later by its place in the repo. */
1072let repoRoot: string | undefined
1073/** The git common dir, absolute (`git rev-parse --git-common-dir`): where the ID claims live in every git layout. */
1074let gitCommon: string | undefined
1075/** Where the central todo lives: the root of the main checkout (the repo root outside a worktree). */
1076let centralRoot: string | undefined
1077/**
1078 * The session folder as an absolute path: from git in a repo (the top plus `--show-prefix`), else the
1079 * real path of `.`. A relative nearest folder is made absolute against it, so the trust check, which
1080 * takes only absolute paths, can pass it.
1081 */
1082let sessionDir: string | undefined
1083/** Outside a repo (or when git fails): the session folder, whose own `.claude_todo` is the one folder trusted there. Undefined in a repo. */
1084let looseRoot: string | undefined
1085
1086/**
1087 * A relative nearest folder as an absolute path against the session folder, when that path is its own
1088 * real path (no symlink at the folder). Undefined when this cannot be told: the folder then stays
1089 * relative, and so untrusted. An absolute path (a worktree's main checkout folder) is returned as it is.
1090 */
1091function absNearest(near: string, real: string | undefined): string | undefined {
1092 if (isAbsPath(near)) {
1093 return near
1094 }
1095 const path = sessionDir === undefined ? undefined : resolveAgainst(sessionDir, near)
1096
1097 return path !== undefined && real !== undefined && samePath(real, path) ? path : undefined
1098}
1099
1100/** Says once that HOME cannot be read, unless the session works on a Windows path, which the text rule covers with no home. */
1101function noteNoHome($: EngineInterface, where: string | undefined): void {
1102 if (!globalsKnown && !globalsToasted && !(where !== undefined && isWinPath(where))) {
1103 globalsToasted = true
1104 showToast($, 'Claudeopticon cannot read the HOME folder, so it cannot tell the global todo folder from a project one. It changes no todo file and the tidy buttons are off.')
1105 }
1106}
1107
1108/** The folders already named in an "outside the repo" toast: one toast each, per load of the module. */
1109const outsideToasted = new Set<string>()
1110
1111/** Says once per folder that a listed todo folder resolves outside the repo, so the mod does not read it. */
1112function noteOutsideRepo($: EngineInterface, path: string, real: string): void {
1113 if (!outsideToasted.has(path)) {
1114 outsideToasted.add(path)
1115 showToast($, `Claudeopticon skips ${path}: it is a link to ${real}, outside the repo, so its files are not read.`)
1116 }
1117}
1118
1119/** True once a failed read of the repo layout was told; a layout that reads clears it, so the next failure is told again. */
1120let layoutFailToasted = false
1121
1122/** Tells once that the repo layout could not be read, and what the board does instead: it shows the nearest todo folder only. */
1123function noteLayoutFailed($: EngineInterface, reason: string): void {
1124 if (!layoutFailToasted) {
1125 layoutFailToasted = true
1126 showToast($, `Claudeopticon could not read the repo layout (${reason}). The board shows the nearest todo folder only until you press Consolidate todos or reload the mod.`)
1127 }
1128}
1129
1130/** The folders already named in a "spelled in another letter case" toast: one toast each, per load of the module. */
1131const misspelledToasted = new Set<string>()
1132
1133/** Says once per folder that a todo folder is spelled `.claude_todo` in another letter case, so the mod leaves it alone. */
1134function noteMisspelled($: EngineInterface, path: string): void {
1135 if (!misspelledToasted.has(path)) {
1136 misspelledToasted.add(path)
1137 showToast($, `Claudeopticon skips ${path}: the folder name must be ${DIR} in lowercase. Rename it to ${DIR} to have it read and numbered.`)
1138 }
1139}
1140
1141/**
1142 * Finds every `.claude_todo/` folder of the repo (and of the main checkout, from a worktree) with
1143 * git. Outside a repo, or when git fails, only the nearest one by the old rule counts, by its
1144 * absolute path so it can be written. A path git lists but the disk no longer has (a
1145 * tracked file deleted) is dropped.
1146 */
1147async function discoverFolders($: EngineInterface, previous?: TodoFolder[]): Promise<TodoFolder[]> {
1148 await loadGlobals($)
1149 const nearest = await findTodoDir($).catch(() => undefined)
1150 const nearestReal = nearest === undefined ? undefined : await realOf($, nearest)
1151 if (nearestReal !== undefined && isMisspelledTodo(nearestReal)) {
1152 // A disk that ignores case answers `.claude_todo` for `.Claude_todo`: the folder stays untrusted, so say why once.
1153 noteMisspelled($, nearestReal)
1154 }
1155 const alone = async (): Promise<TodoFolder[]> => {
1156 sessionDir = await realOf($, '.')
1157 looseRoot = sessionDir
1158 gitCommon = undefined
1159 // A search that finds no repo this time leaves no root of an earlier one trusted (a rediscover after a failed rev-parse).
1160 repoRoot = undefined
1161 centralRoot = undefined
1162 centralBlocked = false
1163 noteNoHome($, sessionDir)
1164 if (nearest === undefined) {
1165 return []
1166 }
1167
1168 return [{ path: absNearest(nearest, nearestReal) ?? nearest, rel: nearest, isOther: false, ...(nearestReal === undefined ? {} : { real: nearestReal }) }]
1169 }
1170 try {
1171 // Bounded: a rev-parse that hangs is a failure, as one that fails is; one toast names it.
1172 const ran = await runInTime($, REV_PARSE)
1173 if (ran === TIMED_OUT) {
1174 noteTimedOut($, REV_PARSE)
1175 }
1176 const top = ran === TIMED_OUT || ran === undefined ? { exitCode: 1, stdout: '', stderr: '' } : ran
1177 // Exit 128 is git's answer outside a repo: normal. Any other failure to ask is told; a time-out already was.
1178 if (ran === undefined) {
1179 noteLayoutFailed($, 'git did not start')
1180 } else if (ran !== TIMED_OUT && top.exitCode !== 0 && top.exitCode !== 128) {
1181 noteLayoutFailed($, `git rev-parse exited ${top.exitCode}`)
1182 }
1183 let roots = top.exitCode === 0 ? repoRoots(top.stdout) : undefined
1184 if (roots !== undefined && (roots.isLinked === true || roots.main !== undefined)) {
1185 // The main checkout is the first entry of the worktree list, whatever the shape of the git dir; the common dir is the fallback only when the list fails.
1186 const listArgv = ['git', 'worktree', 'list', '--porcelain']
1187 const ranList = await runInTime($, listArgv)
1188 if (ranList === TIMED_OUT) {
1189 noteTimedOut($, listArgv)
1190 }
1191 const list = ranList === TIMED_OUT ? undefined : ranList
1192 roots = repoRoots(top.stdout, list?.exitCode === 0 ? list.stdout : '')
1193 }
1194 if (roots === undefined) {
1195 return await alone()
1196 }
1197 // Git must name the folder the session is in: GIT_DIR and GIT_WORK_TREE in the environment
1198 // (vcsh) or a core.worktree set elsewhere give well-formed output for another folder, whose todo and
1199 // `.git` this session must never write. Such a session takes the outside-a-repo path.
1200 if (!isSameFolder(sessionFolder(top.stdout), await realOf($, '.'))) {hooks/agent-cards.ts 238 lines1/** The agent cards: the live agent card, the timeline and the Orchestrator history. */
2
3import { agentColor, agentLabel, ORCH } from './agent-identity'
4import { clock, elapsed, plural, tokens } from './card-format'
5import { actor, badge, badgeWidth, strip } from './card-parts'
6import { ACCENT, Blinks, FAINT, INNER, LABEL, PAD, RULE, stage, STAGE_DANGER, SUB, TRACK, W } from './card-stage'
7import { esc, fit } from './card-text'
8import type { AgentView, Card, View } from './card-types'
9import { ORCHESTRATOR_PAGE } from './orchestrator-history'
10
11const MAX_LINKS_SHOWN = 3
12
13/** The height of one Orchestrator entry: its summary line, and a dim detail line when it has one. */
14const ENTRY_PX = 22
15const DETAIL_PX = 16
16/**
17 * The Orchestrator card's held height: a full page of entries, each with a detail line. A page with
18 * fewer entries or shorter ones keeps it, so the cards below the card stay put as calls come in.
19 */
20export const ORCHESTRATOR_HELD_PX = 8 + ORCHESTRATOR_PAGE * (ENTRY_PX + DETAIL_PX) + 14
21
22/**
23 * The Orchestrator card: one line per tool call summary, newest first, each with its start time in
24 * small text on the right; a call still running has a live dot, a finished one a quiet one. An
25 * entry with a `detail` (the command, path or pattern of the call) has it on a dim mono line below.
26 * Held (the default), the card keeps the height of a full page; not held, it fits its entries.
27 */
28export function orchestratorSvg(entries: readonly { line: string; at: number; isRunning: boolean; detail?: string }[], isHeld = true): Card {
29 let y = 8
30 const parts = entries.map(entry => {
31 y += ENTRY_PX
32 const dot = entry.isRunning
33 ? `<circle cx="${PAD + 5}" cy="${y - 4}" r="4" fill="${ACCENT}"/><circle cx="${PAD + 5}" cy="${y - 4}" r="4" fill="${ACCENT}" class="pulse"/>`
34 : `<circle cx="${PAD + 5}" cy="${y - 4}" r="3" fill="${FAINT}"/>`
35 const detail = entry.detail === undefined || entry.detail === '' ? '' : `\n<text x="${PAD + 18}" y="${y + 14}" fill="${FAINT}" font-size="11" class="mono">${esc(fit(entry.detail, INNER - 18, 11, 400, true))}</text>`
36 const drawn = `${dot}<text x="${PAD + 18}" y="${y}" fill="${entry.isRunning ? LABEL : SUB}" font-size="13">${esc(fit(entry.line, INNER - 18 - 64, 13))}</text>
37<text x="${W - PAD}" y="${y}" text-anchor="end" fill="${FAINT}" font-size="10.5" class="mono">${clock(entry.at)}</text>${detail}`
38 y += detail === '' ? 0 : DETAIL_PX
39
40 return drawn
41 })
42
43 const alt = entries.length === 0 ? 'Orchestrator: nothing done yet' : `Orchestrator: ${entries.map(entry => `${clock(entry.at)} ${entry.line}`).join('; ')}`
44
45 return stage(isHeld ? Math.max(y + 14, ORCHESTRATOR_HELD_PX) : y + 14, parts.join('\n'), alt)
46}
47
48function agentBadge(agent: AgentView): { label: string; kind: 'live' | 'ok' | 'danger' | 'neutral' } {
49 if (agent.isIdle) {
50 return { label: 'Idle', kind: 'neutral' }
51 }
52 if (agent.status === 'completed') {
53 return { label: 'Done', kind: 'ok' }
54 }
55 if (agent.status === 'failed') {
56 return { label: 'Failed', kind: 'danger' }
57 }
58 if (agent.status === 'killed') {
59 return { label: 'Stopped', kind: 'danger' }
60 }
61 if (agent.status === 'running') {
62 return { label: 'Running', kind: 'live' }
63 }
64
65 return { label: `${agent.status.charAt(0).toUpperCase()}${agent.status.slice(1)}`, kind: 'neutral' }
66}
67
68/** The timeline's top margin, and the room each agent's strip takes. */
69const TIMELINE_TOP = 26
70const TIMELINE_ROW_H = 30
71
72/** The height of the timeline for `n` agent strips: one strip's room when there are none. */
73export function timelineHeight(n: number): number {
74 return TIMELINE_TOP + Math.max(n, 1) * TIMELINE_ROW_H - 8 + 28
75}
76
77/**
78 * The agents' timeline, from the first agent's start to now: one strip per agent. The right end
79 * reads "Now" and a running strip pulses at its head.
80 */
81export function timelineSvg(view: View, all: readonly AgentView[]): Card {
82 // No agent shown: the span is empty (Math.min() of nothing is Infinity and would draw NaN).
83 const t0 = all.length === 0 ? view.now : Math.min(...all.map(a => a.startedAt))
84 const t1 = view.now
85 const agents = [...all]
86 const n = agents.length
87 const parts: string[] = []
88 const blinks = new Blinks()
89 const plotX = PAD + 34
90 const plotW = INNER - 34 - 52
91 const span = Math.max(1000, t1 - t0)
92 const x = (t: number) => plotX + ((Math.min(Math.max(t, t0), t1) - t0) / span) * plotW
93 const top = TIMELINE_TOP
94 const rowH = TIMELINE_ROW_H
95 const axisY = timelineHeight(n) - 28
96 for (const f of [0, 0.5, 1]) {
97 const gx = plotX + f * plotW
98 const t = t0 + f * span
99 const tick = f === 1 ? 'Now' : `${elapsed(view.now - t)} ago`
100 parts.push(`<line x1="${gx}" y1="${top - 16}" x2="${gx}" y2="${axisY}" stroke="${RULE}"/>
101<text x="${gx}" y="${axisY + 16}" text-anchor="${f === 0 ? 'start' : f === 1 ? 'end' : 'middle'}" fill="${FAINT}" font-size="11">${tick}</text>`)
102 }
103 if (n === 0) {
104 parts.push(`<text x="${plotX + plotW / 2}" y="${top + 4}" text-anchor="middle" fill="${SUB}" font-size="12">${view.agents.length > 0 ? 'All agents finished' : 'No agents ran in this window'}</text>`)
105 }
106 agents.forEach((agent, i) => {
107 const y = top + i * rowH
108 const end = agent.endedAt ?? agent.idleSince ?? view.now
109 const x0 = x(agent.startedAt)
110 const w = Math.max(6, x(end) - x0)
111 const failed = agent.status === 'failed' || agent.status === 'killed'
112 parts.push(agent.isEnded ? '<g opacity=".55">' : '<g>')
113 parts.push(actor(PAD + 12, y - 2, agent.index, failed ? 'failed' : agent.isEnded ? 'none' : 'working', false, blinks))
114 const fill = agent.isEnded ? (failed ? STAGE_DANGER : TRACK) : 'url(#progress)'
115 parts.push(`<rect x="${x0}" y="${y - 4}" width="${w}" height="4" rx="2" fill="${fill}"/>`)
116 if (agent.status === 'completed' && end <= t1) {
117 parts.push(`<path d="M ${x0 + w + 5} ${y - 2} l 2.4 2.4 l 4.6 -5" fill="none" stroke="#FFF" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>`)
118 } else if (!agent.isEnded && !agent.isIdle) {
119 parts.push(`<circle cx="${x0 + w}" cy="${y - 2}" r="4" fill="${ACCENT}" class="pulse"/>
120<circle cx="${x0 + w}" cy="${y - 2}" r="3.5" fill="${ACCENT}"/>`)
121 }
122 parts.push(`<text x="${W - PAD}" y="${y + 2}" text-anchor="end" fill="${SUB}" font-size="12">${elapsed(end - agent.startedAt)}</text></g>`)
123 })
124
125 return stage(axisY + 28, parts.join('\n'), `Timeline of ${plural(n, 'agent')}`, blinks.css())
126}
127
128/**
129 * A live agent's Stop button, drawn in the card at its right edge, right of the badge: the badge's height and row, red with a white stop sign.
130 * The sign is stroked `#FFF`, not `#FFFFFF`: the light theme turns a `#FFFFFF` stroke dark.
131 */
132const STOP_W = 30
133const STOP_FILL = '#DC2626'
134/** The gap between a live agent's Stop button and its badge. */
135const STOP_GAP_PX = 8
136/** The room left of a live agent's badge that its Stop button and the gap take. */
137const STOP_PX = STOP_W + STOP_GAP_PX
138/**
139 * How far an agent card's title row sits below its usual place: the pane places the Stop button
140 * in whole text rows, and one row down puts its center 5 px below a badge at the usual place.
141 */
142const HEAD_DROP_PX = 5
143
144/** The height of an agent card of `lines` text lines, with the progress strip's extra room when it has one. */
145export function agentCardHeight(lines: number, hasProgress: boolean): number {
146 return 20 + HEAD_DROP_PX + lines * 20 + (hasProgress ? 8 : 0)
147}
148
149/** The smallest agent card: its title line and its meta line. */
150export const AGENT_CARD_MIN_PX = agentCardHeight(2, false)
151
152
153/** The drawn Stop button whose right edge is at `right`, on the badge's row at baseline `y`: a 22 px red key with a white stop sign. */
154function stopKey(right: number, y: number): string {
155 const x = right - STOP_W
156 const cx = x + STOP_W / 2
157 const cy = y - 4
158
159 return `<rect x="${x}" y="${y - 15}" width="${STOP_W}" height="22" rx="4" fill="${STOP_FILL}"/>
160<circle cx="${cx}" cy="${cy}" r="6" fill="none" stroke="#FFF" stroke-width="1.5"/>
161<line x1="${cx - 3}" y1="${cy}" x2="${cx + 3}" y2="${cy}" stroke="#FFF" stroke-width="1.5" stroke-linecap="round"/>`
162}
163
164/** One agent: actor, name and status badge; the item it works on; meta; current tool call. */
165export function agentSvg(agent: AgentView, view: View): Card {
166 const parts: string[] = []
167 // A live agent's title ends short of its badge, which sits left of the Stop button.
168 const isOrch = agent.index === ORCH
169 // The orchestrator has no Stop button: it is the main conversation, not a task to kill.
170 const stop = agent.isEnded || isOrch ? 0 : STOP_PX
171 const failed = agent.status === 'failed' || agent.status === 'killed'
172 const { label, kind } = agentBadge(agent)
173 const bw = badgeWidth(label)
174 const blinks = new Blinks()
175 const color = agentColor(agent.index)
176 const shownLinks = agent.links.slice(0, MAX_LINKS_SHOWN)
177 const moreLinks = agent.links.length - shownLinks.length
178 const hasLink = shownLinks.length > 0
179 const progress = agent.isEnded ? undefined : agent.progress
180 const lines = 2 + shownLinks.length + (moreLinks > 0 ? 1 : 0) + (!agent.isEnded && agent.doing !== undefined ? 1 : 0) + (progress !== undefined ? 1 : 0)
181 const h = agentCardHeight(lines, progress !== undefined)
182 if (hasLink && !agent.isEnded) {
183 parts.push(`<rect x="1" y="1" width="${W - 2}" height="${h - 2}" rx="11" fill="none" stroke="${color}" stroke-opacity=".55"/>`)
184 }
185 parts.push(actor(PAD + 12, 26 + HEAD_DROP_PX, agent.index, failed ? 'failed' : agent.isEnded ? 'none' : 'working', hasLink && !agent.isEnded, blinks))
186 let ty = 31 + HEAD_DROP_PX
187 const tx = PAD + 36
188 parts.push(`<text x="${tx}" y="${ty}" fill="${agent.isEnded ? SUB : LABEL}" font-size="14" font-weight="500">${esc(fit(agent.description, INNER - 44 - bw - stop, 14, 500))}</text>`)
189 // A live agent's Stop key takes the right edge and its badge sits left of it; an ended agent's badge takes the edge.
190 parts.push(badge(W - PAD - stop, ty, label, kind))
191 if (stop > 0) {
192 parts.push(stopKey(W - PAD, ty))
193 }
194 ty += 20
195 for (const link of shownLinks) {
196 parts.push(`<circle cx="${tx + 4}" cy="${ty - 4}" r="4" fill="${color}" class="${blinks.cls([color])}"/>
197<text x="${tx + 14}" y="${ty}" fill="${SUB}" font-size="12">Working on <tspan fill="${color}" font-weight="500">${esc(fit(link, INNER - 130, 12, 500))}</tspan></text>`)
198 ty += 20
199 }
200 if (moreLinks > 0) {
201 parts.push(`<text x="${tx + 14}" y="${ty}" fill="${SUB}" font-size="12">and ${plural(moreLinks, 'more item')}</text>`)
202 ty += 20
203 }
204 if (progress !== undefined) {
205 const percent = Math.round((progress.done / progress.total) * 100)
206 const label = `Step ${Math.min(progress.done + 1, progress.total)} of ${progress.total}${progress.step ? `: ${progress.step}` : ''}`
207 parts.push(`<text x="${tx}" y="${ty}" fill="${LABEL}" font-size="12" font-weight="500">${esc(fit(label, INNER - 90, 12, 500))}</text>
208<text x="${W - PAD}" y="${ty}" text-anchor="end" fill="${SUB}" font-size="12">${percent}%</text>`)
209 parts.push(strip(tx, ty + 7, W - PAD - tx, progress.done, 0, progress.total))
210 ty += 28
211 }
212 const ran = elapsed((agent.endedAt ?? agent.idleSince ?? view.now) - agent.startedAt)
213 const isIdle = agent.isIdle === true && agent.idleSince !== undefined
214 const when = agent.endedAt !== undefined ? [`ran ${ran}`, `ended ${clock(agent.endedAt)}`] : isIdle ? [`ran ${ran}`] : [ran]
215 // An idle agent's note leads, so a narrow card never cuts it off. The orchestrator has no run
216 // time: the main conversation has been there since the session began.
217 const meta = (isOrch
218 ? ['Orchestrator', agent.type, plural(agent.toolCalls, 'tool call')]
219 : [isIdle ? `Finished ${clock(agent.idleSince!)}, not stopped` : undefined, agent.type, agent.model, ...when, plural(agent.toolCalls, 'tool call'), agent.tokens ? `${tokens(agent.tokens)} tokens` : undefined])
220 .filter((part): part is string => part !== undefined && part !== '')
221 .join('\u2002·\u2002')
222 parts.push(`<text x="${tx}" y="${ty}" fill="${SUB}" font-size="12">${esc(fit(meta, INNER - 40, 12))}</text>`)
223 ty += 20
224 if (!agent.isEnded && agent.doing !== undefined) {
225 // An idle agent's call has long returned: it is the last one, not the current one.
226 const doing = agent.isIdle ? `Last: ${agent.doing}` : agent.doing
227 parts.push(`<text x="${tx}" y="${ty}" fill="${SUB}" font-size="12" class="mono">${esc(fit(doing, INNER - 44, 12, 400, true))}</text>`)
228 }
229
230 // A finished agent stays in the ledger, grayed out (STG-DRAW-6: a quiet item draws at reduced opacity).
231 const body = agent.isEnded ? `<g opacity=".55">${parts.join('\n')}</g>` : parts.join('\n')
232
233 // The orchestrator's title is a headline, so its alt text keeps the name that identifies the card.
234 const alt = isOrch ? `${agentLabel(agent.index)}, Orchestrator: ${label}, ${agent.description}` : `${agentLabel(agent.index)}, ${agent.description}: ${label}`
235
236 return stage(h, body, alt, blinks.css())
237}
238hooks/agent-ends.ts 50 lines1/** When an agent has ended: the ended states, the unlisted timeout and its clock, and a task notification's end. */
2
3import type { AgentRowStatus } from '../types'
4import { elapsedSince } from './clock-elapsed'
5
6const ENDED: readonly AgentRowStatus[] = ['completed', 'failed', 'killed', 'ended']
7
8export function isEnded(state: AgentRowStatus): boolean {
9 return ENDED.includes(state)
10}
11/** How long a live agent may be missing from the engine's agent list before its row ends. */
12export const UNLISTED_MS = 15_000
13
14/**
15 * The live rows the engine's list has left for longer than UNLISTED_MS, counted from the
16 * first refresh that missed each one, not from its start: a long-running agent that drops out of one
17 * list is not ended at once. Returns the IDs to end and the new missing-since map, which holds only
18 * the live rows still missing (a row listed again starts over). A clock set back restarts the grace
19 * from `time`, so a set-back never keeps a gone agent live for its length.
20 */
21export function unlistedEnds(rows: readonly { id: string; status: AgentRowStatus }[], listed: ReadonlySet<string>, missing: ReadonlyMap<string, number>, time: number): { ended: Set<string>; missing: Map<string, number> } {
22 const ended = new Set<string>()
23 const next = new Map<string, number>()
24 for (const row of rows) {
25 if (listed.has(row.id) || isEnded(row.status)) {
26 continue
27 }
28 const { ms, from } = elapsedSince(missing.get(row.id) ?? time, time)
29 if (ms > UNLISTED_MS) {
30 ended.add(row.id)
31 } else {
32 next.set(row.id, from)
33 }
34 }
35
36 return { ended, missing: next }
37}
38
39const NOTIFIED_ENDS: Record<string, AgentRowStatus> = { completed: 'completed', failed: 'failed', killed: 'killed', stopped: 'killed', timeout: 'failed', timed_out: 'failed' }
40
41/** The task ID and end status a task notification reports; none when it reports no end. A background agent's task ID is its agent ID. */
42export function notifiedEnd(text: string): { id: string; status: AgentRowStatus } | undefined {
43 const id = /<task-id>\s*([^<\s]+)\s*<\/task-id>/.exec(text)?.[1]
44 const word = (/<status>\s*([^<\s]+)\s*<\/status>/.exec(text)?.[1] ?? '').toLowerCase()
45 // An own key only: `constructor` or `__proto__` in the text would give the row a function as its status.
46 const status = Object.hasOwn(NOTIFIED_ENDS, word) ? NOTIFIED_ENDS[word] : undefined
47
48 return id === undefined || status === undefined ? undefined : { id, status }
49}
50hooks/agent-respawn.ts 18 lines1/** The row of an agent spawned again under an ID that already has a row (a resumed agent). */
2
3import type { AgentRow } from '../types'
4
5/**
6 * The row of a known agent ID that spawns again: the new spawn's row (its task, brief,
7 * model, start and status), with the counts of the old row kept: its tool calls and its tokens. The
8 * caller keeps the row's place, so its label and the labels after it stay. What belonged to the old
9 * task goes: its end, idle time, progress, claims and the model match of the old brief.
10 */
11export function respawnedRow(known: AgentRow, fresh: AgentRow): AgentRow {
12 return {
13 ...fresh,
14 toolCalls: known.toolCalls,
15 ...(known.tokens === undefined ? {} : { tokens: known.tokens }),
16 }
17}
18hooks/agent-colors.ts 47 lines1/** Agent color slots: which agent color each agent holds, reused once an agent finishes. */
2
3/**
4 * The fields of an agent that decide its slot: when it started, and when it finished, if it has.
5 * `pinned` is the slot the agent was first drawn with: it keeps it, whatever the replay would give.
6 */
7export type SlotAgent = { startedAt: number; endedAt?: number; idleSince?: number; isEnded: boolean; pinned?: number }
8
9/**
10 * Each agent's color slot, by its index in `agents` (start order). An agent takes the lowest slot no
11 * live agent holds when it starts, and keeps it; the slot is free again from the time the agent ends or
12 * goes idle. An ended agent with no end time frees its slot at its start. When all slots are held, the
13 * agent shares the slot with the fewest holders: a color may repeat, and no agent waits for one. The
14 * replay depends only on agents that started earlier, so a new agent never changes the color of one
15 * already drawn. A woken agent has no idle time left on its row, so the replay would hold its slot
16 * from its start and move an agent that took the slot in the gap: an agent with a `pinned` slot keeps
17 * it, and still counts as a holder for the agents after it.
18 */
19export function colorSlots(agents: readonly SlotAgent[], slots: number): number[] {
20 const order = agents.map((agent, i) => i).sort((a, b) => agents[a]!.startedAt - agents[b]!.startedAt || a - b)
21 const result: number[] = new Array(agents.length).fill(0)
22 const holders: { slot: number; until: number }[] = []
23
24 for (const i of order) {
25 const agent = agents[i]!
26 const held = new Array(slots).fill(0)
27 for (const holder of holders) {
28 if (holder.until > agent.startedAt) {
29 held[holder.slot] += 1
30 }
31 }
32 const slot = agent.pinned !== undefined && agent.pinned >= 0 && agent.pinned < slots ? agent.pinned : held.indexOf(Math.min(...held))
33 result[i] = slot
34 holders.push({ slot, until: freedAt(agent) })
35 }
36
37 return result
38}
39
40function freedAt(agent: SlotAgent): number {
41 if (agent.isEnded) {
42 return agent.endedAt ?? agent.startedAt
43 }
44
45 return agent.idleSince ?? Infinity
46}
47hooks/agent-identity.ts 58 lines1/** An agent's identity on the pane: its label (A1, O), the label's font size, and its color. */
2
3/** The owner index of the orchestrator (the main conversation) in `owners`: no agent has it. */
4export const ORCH = -1
5
6/**
7 * The number of agents before the first kept row: rows past the kept window are dropped from the store,
8 * so after a reload the first row is not A1. Labels and colors count from this base, and never shift.
9 */
10let labelBase = 0
11export function setLabelBase(base: number): void {
12 labelBase = Math.max(0, Math.floor(base))
13}
14
15export function agentLabel(index: number): string {
16 return index === ORCH ? 'O' : `A${labelBase + index + 1}`
17}
18
19/**
20 * The font size that fits a label in its 28 px circle, with at most 17 px of text, so a few pixels stay clear on each side. Widths are
21 * Instrument Sans at weight 500, the widest of the fallback fonts: `A` is 0.461 em, a digit 0.664 em.
22 */
23export function labelFontSize(label: string): number {
24 const em = 0.461 + 0.664 * Math.max(1, label.length - 1)
25
26 return Math.min(11, Math.floor((17 / em) * 10) / 10)
27}
28
29/**
30 * Agent colors, a deliberate exception to Stage UI COL-8: each live agent
31 * blinks a color, and so does each todo item it works on. Sixteen colors, most distinct first: each is
32 * the OKLab color farthest from the ones before it, from the orchestrator teal, the progress violet and the
33 * stage gray, with at least 3:1 contrast to white chip text and to the dark card. An agent takes the first
34 * free color when it starts and keeps it; the color is free again once the agent finishes (agent-colors.ts).
35 * The A1, A2 labels stay, so color is never the only cue (COL-9).
36 */
37export const AGENT_COLORS = [
38 '#3987e5', '#a05001', '#f55a79', '#207e27', '#da7e1e', '#79579b', '#d665cf', '#8e8227',
39 '#1870a1', '#d9471b', '#269573', '#2d5ed4', '#cc4394', '#8a87fd', '#ad52c8', '#0f9b23',
40]
41
42/** The orchestrator's color: a teal, apart from the agent colors and from the violet progress. */
43const ORCH_COLOR = '#1fa7b8'
44
45/** Each agent's color slot by its index, set with each view. */
46let slots: readonly number[] = []
47export function setColorSlots(next: readonly number[]): void {
48 slots = next
49}
50
51export function agentColor(index: number): string {
52 if (index === ORCH) {
53 return ORCH_COLOR
54 }
55
56 return AGENT_COLORS[slots[index] ?? index % AGENT_COLORS.length] ?? AGENT_COLORS[0]!
57}
58hooks/agent-match.ts 37 lines1/** The Haiku match of a new agent's task to open items: the prompt and the reply. */
2
3import { cutUnits } from './card-text'
4
5export const MATCH_ITEMS = 80
6const MATCH_MAX = 3
7
8export function matchPrompt(task: string, texts: readonly string[]): string {
9 return [
10 "An agent was started with this task. Which of the project's todo items is it working on?",
11 '',
12 'Task:',
13 cutUnits(task, 2000),
14 '',
15 'Todo items:',
16 ...texts.map((text, i) => `${i + 1}. ${cutUnits(text, 160)}`),
17 '',
18 `Reply with JSON only: {"items": [numbers]}, at most ${MATCH_MAX}, only items the task works on directly; {"items": []} when none fits.`,
19 ].join('\n')
20}
21
22/** The item numbers in a match reply, 0-based, in range, at most three; empty when unreadable. */
23export function readMatchReply(reply: string, count: number): number[] {
24 const found = /\{[\s\S]*\}/.exec(reply)?.[0]
25 if (found === undefined) {
26 return []
27 }
28 try {
29 const parsed = JSON.parse(found) as { items?: unknown }
30 const items = Array.isArray(parsed.items) ? parsed.items : []
31
32 return [...new Set(items.filter((n): n is number => Number.isInteger(n) && n >= 1 && n <= count).map(n => n - 1))].slice(0, MATCH_MAX)
33 } catch {
34 return []
35 }
36}
37hooks/archive-blocks.ts 318 lines1/** The text work of the archive step: closed blocks, their removal, and where they go in the archive file. */
2
3import { itemKey, storedKey } from './item-keys'
4import { continuesParagraph } from './markdown-blocks'
5import { bare, CHECKBOX, exampleMask, FENCE, HEADING_LINE, itemsAt, parseTodo } from './todo-markdown'
6
7/** A closed ticket is moved once it has been closed this long: a mis-click on Mark done can still be undone. */
8export const ARCHIVE_AFTER_MS = 5000
9
10/** A closed ticket in a todo file's text: its lines, where they sit (`from` to `to`, end excluded), and the heading above it. */
11export type ClosedBlock = { heading?: string; lines: string[]; from: number; to: number }
12
13/** True for a line that is, or looks like, a checkbox that is not done: a line that looks like one but fails the match counts open. */
14function isOpenLine(line: string): boolean {
15 const box = CHECKBOX.exec(line)?.[1]
16 if (box !== undefined) {
17 return box.toLowerCase() !== 'x'
18 }
19
20 return /^\s*[-*+] \[[^\]]*\]/.test(line)
21}
22
23/**
24 * The tickets of a todo file that can leave it: a top-level `- [x]` line plus the indented lines
25 * under it, when every checkbox in that block is `[x]`. The block runs past blank lines while the
26 * next non-blank line is indented, and takes a line that is not indented when it goes on the paragraph
27 * right above it (a wrapped ticket text, `continuesParagraph`). The heading is an ATX heading with up
28 * to 3 spaces of indent (setext headings are not read). An open or in-progress subtask keeps the whole block, and so does
29 * a code fence, HTML or block quote line in it. Prose, headings and tables are never part of a
30 * block. Every line `exampleMask` marks (a code fence and its lines, an HTML block, a block quote) is an
31 * example: it never starts or joins a block, and is never a heading. The heading is the
32 * last heading line above the block (any level), outside examples. A trailing carriage return is
33 * ignored, so a CRLF file reads as an LF one; `lines` are without it.
34 */
35export function closedBlocks(markdown: string): ClosedBlock[] {
36 const lines = markdown.split('\n').map(bare)
37 const isExample = exampleMask(lines)
38 const blocks: ClosedBlock[] = []
39 let heading: string | undefined
40 let i = 0
41 while (i < lines.length) {
42 const line = lines[i]!
43 if (isExample[i] === true) {
44 i += 1
45
46 continue
47 }
48 if (HEADING_LINE.test(line)) {
49 heading = line.trim()
50 } else if (/^[-*+] \[[xX]\]\s+/.test(line)) {
51 // The block ends at its last indented line; blank lines after it are not taken.
52 let end = i + 1
53 // A line that is not indented but goes on the paragraph above it (a wrapped ticket text) is part of the block: an open subtask after it holds the block back.
54 const isInside = (at: number) => lines[at]!.trim() === '' || /^[ \t]+\S/.test(lines[at]!) || continuesParagraph(lines[at - 1]!, lines[at]!)
55 for (let at = i + 1; at < lines.length && isInside(at); at += 1) {
56 end = lines[at]!.trim() === '' ? end : at + 1
57 }
58 const block = lines.slice(i, end)
59 // A block that holds an example line (a fence, a comment) or a fence-like line stays whole; the walk goes on line by line.
60 if (isExample.slice(i, end).some(is => is === true) || block.some(one => FENCE.test(one))) {
61 i += 1
62
63 continue
64 }
65 if (!block.some(isOpenLine)) {
66 blocks.push({ ...(heading === undefined ? {} : { heading }), lines: block, from: i, to: end })
67 }
68 i = end
69
70 continue
71 }
72 i += 1
73 }
74
75 return blocks
76}
77
78/** The text without the lines of the given blocks; everything else stays as it was. One pass: the lines a block covers are marked, then dropped. */
79export function removeBlocks(markdown: string, blocks: readonly ClosedBlock[]): string {
80 const lines = markdown.split('\n')
81 const gone = new Uint8Array(lines.length)
82 for (const block of blocks) {
83 gone.fill(1, Math.max(block.from, 0), Math.min(block.to, lines.length))
84 }
85
86 return lines.filter((_, i) => gone[i] === 0).join('\n')
87}
88
89/**
90 * The lines of a text, indexed for the question "does this block stand whole here": the lines without a
91 * trailing space or carriage return, where each line occurs, and for each place the next non-blank line.
92 * Built once per text, so a question costs the size of the block, not of the text.
93 */
94type LineIndex = { flat: string[]; where: Map<string, number[]>; nextFilled: number[] }
95
96function indexLines(lines: readonly string[]): LineIndex {
97 const flat = lines.map(line => bare(line).trimEnd())
98 const where = new Map<string, number[]>()
99 flat.forEach((line, at) => {
100 const seen = where.get(line)
101 if (seen === undefined) {
102 where.set(line, [at])
103 } else {
104 seen.push(at)
105 }
106 })
107 const nextFilled: number[] = new Array<number>(flat.length + 1)
108 nextFilled[flat.length] = flat.length
109 for (let at = flat.length - 1; at >= 0; at -= 1) {
110 nextFilled[at] = flat[at]!.trim() === '' ? nextFilled[at + 1]! : at
111 }
112
113 return { flat, where, nextFilled }
114}
115
116/** The places in `index` where `block` stands in order (trailing spaces ignored), with the block's trimmed lines. */
117function placesOf(index: LineIndex, block: readonly string[]): { want: string[]; places: number[] } {
118 const want = block.map(line => bare(line).trimEnd())
119 const places = want.length === 0 ? [] : (index.where.get(want[0]!) ?? []).filter(at => want.every((line, k) => index.flat[at + k] === line))
120
121 return { want, places }
122}
123
124/** True when `block` stands whole at a place of `index`: in order, and the next non-blank line after it is not indented. */
125function standsWhole(index: LineIndex, block: readonly string[]): boolean {
126 const { want, places } = placesOf(index, block)
127
128 return places.some(at => {
129 const after = index.nextFilled[at + want.length]!
130
131 return after >= index.flat.length || !/^[ \t]/.test(index.flat[after]!)
132 })
133}
134
135/**
136 * A test of "this block stands whole in these lines" (`hasBlock`) for many blocks: the lines are indexed
137 * once, so the checks cost the sum of the block sizes, not the blocks times the lines.
138 */
139export function blockFinder(lines: readonly string[]): (block: readonly string[]) => boolean {
140 const index = indexLines(lines)
141
142 return block => standsWhole(index, block)
143}
144
145/**
146 * True when `block` stands in `lines` as one whole block: its lines in order (trailing spaces
147 * ignored), from a non-indented first line, and the next non-blank line after it is not indented.
148 */
149export function hasBlock(lines: readonly string[], block: readonly string[]): boolean {
150 return blockFinder(lines)(block)
151}
152
153/**
154 * The blank line to put between `before` and a block that starts with `first`, when the block would
155 * sit inside an example right after `before` and a blank line ends that example: an HTML block of type
156 * 6 or 7 (`<details>`, `<div>`, a lone tag) runs to the next blank line. Else none, so an
157 * archive keeps its blocks together as before.
158 */
159function gapBefore(before: readonly string[], first: string): string[] {
160 return exampleMask([...before, first]).at(-1) === true && exampleMask([...before, '', first]).at(-1) !== true ? [''] : []
161}
162
163/** The lines of the last section of `heading` in `lines` (outside examples; up to the next heading), or none when it has no section. */
164function sectionOf(lines: readonly string[], isExample: readonly boolean[], heading: string): string[] {
165 const at = lines.reduce((last, line, k) => (isExample[k] !== true && line.trim() === heading ? k : last), -1)
166 if (at < 0) {
167 return []
168 }
169 const next = lines.findIndex((line, k) => k > at && isExample[k] !== true && HEADING_LINE.test(line))
170
171 return lines.slice(at + 1, next < 0 ? lines.length : next)
172}
173
174/**
175 * The archive file's text with the blocks added. A block goes at the end of the section under its
176 * own heading when the archive has that heading (the last one, outside code fences and HTML
177 * comments), else the
178 * heading is added at the end of the file; a block with no heading goes at the end. A block is
179 * skipped only when it stands whole in the archive under its own heading (anywhere for a block with
180 * none) AND is one of `wrote`, the blocks this mod wrote last for the file: a retry never adds a block
181 * twice, and a new block that equals an old archived one, in another section or after a failed write,
182 * is added. Lines end with the archive's own line ending (CRLF if it has one), else `eol`.
183 */
184export function addToArchive(existing: string, blocks: readonly ClosedBlock[], wrote: readonly (readonly string[])[] = [], eol = '\n'): string {
185 const lines = existing.trim() === '' ? [] : existing.replace(/(\r?\n)+$/, '').split('\n').map(bare)
186 const end = existing.includes('\r\n') ? '\r\n' : existing.trim() === '' ? eol : '\n'
187 const base = [...lines]
188 const wroteSet = new Set(wrote.map(one => one.join('\n')))
189 // Blocks by heading, in the order the headings first occur.
190 const byHeading = new Map<string | undefined, ClosedBlock[]>()
191 for (const block of blocks) {
192 const own = byHeading.get(block.heading)
193 if (own === undefined) {
194 byHeading.set(block.heading, [block])
195 } else {
196 own.push(block)
197 }
198 }
199 // The archive as it was before this call, for the retry check: a block is skipped only when it stands whole under its own heading.
200 const baseMask = wroteSet.size === 0 ? [] : exampleMask(base)
201 const stands = new Map<string | undefined, (block: readonly string[]) => boolean>()
202 const standsUnder = (heading: string | undefined, block: readonly string[]): boolean => {
203 let find = stands.get(heading)
204 if (find === undefined) {
205 find = blockFinder(heading === undefined ? base : sectionOf(base, baseMask, heading))
206 stands.set(heading, find)
207 }
208
209 return find(block)
210 }
211 for (const [heading, own] of byHeading) {
212 const fresh = own.filter(block => !(wroteSet.has(block.lines.join('\n')) && standsUnder(heading, block.lines))).flatMap(block => block.lines)
213 if (fresh.length === 0) {
214 continue
215 }
216 // Outside every example: a heading inside a code fence or an HTML comment is no heading, so a block put
217 // under it would sit inside the comment and be no item. Read again each turn: the lines grow as blocks go in.
218 const isExample = exampleMask(lines)
219 const at = heading === undefined ? -1 : lines.map((line, k) => (isExample[k] !== true && line.trim() === heading ? k : -1)).reduce((last, k) => Math.max(last, k), -1)
220 if (heading === undefined) {
221 lines.push(...gapBefore(lines, fresh[0]!), ...fresh)
222 } else if (at < 0) {
223 lines.push(...(lines.length > 0 ? [''] : []), heading, '', ...fresh)
224 } else {
225 let stop = lines.findIndex((line, k) => k > at && isExample[k] !== true && HEADING_LINE.test(line))
226 stop = stop < 0 ? lines.length : stop
227 while (stop - 1 > at && lines[stop - 1]!.trim() === '') {
228 stop -= 1
229 }
230 const isNext = stop < lines.length
231 lines.splice(stop, 0, ...(stop === at + 1 ? [''] : gapBefore(lines.slice(0, stop), fresh[0]!)), ...fresh, ...(isNext && lines[stop]!.trim() !== '' ? [''] : []))
232 }
233 }
234
235 return `${lines.join(end)}${end}`
236}
237
238/**
239 * True when every block stands in `text` as items: at some place where its lines stand in
240 * order, each of its checkbox lines is an item of the whole text (`itemsAt`), not a line inside a code
241 * fence or an HTML comment. The archive move checks its new text with this before the write, so a moved
242 * ticket never lands where it is no ticket.
243 */
244export function blocksStandAsItems(text: string, blocks: readonly ClosedBlock[]): boolean {
245 const lines = text.split('\n').map(bare)
246 const items = new Set(itemsAt(lines).map(one => one.at))
247 const index = indexLines(lines)
248
249 return blocks.every(block => {
250 const { want, places } = placesOf(index, block.lines)
251
252 return places.some(at => want.every((line, k) => !CHECKBOX.test(line) || items.has(at + k)))
253 })
254}
255
256/**
257 * The record a rollback leaves: the blocks of `wrote`, the record the move read, that still
258 * stand whole in the archive text it put back (`back`) and in the source (`source`). Such a block was
259 * written by an earlier step (another session's) whose own rollback was refused, so it is in both files;
260 * the record keeps the next pass from adding it to the archive again (a duplicate), and that pass only
261 * cuts it from the source. Every other block is in one file, so its record is cleared.
262 */
263export function recordAfterRollback(wrote: readonly (readonly string[])[], back: string, source: string): string[][] {
264 const archived = back.split('\n').map(bare)
265 const live = source.split('\n').map(bare)
266
267 return wrote.filter(block => hasBlock(archived, block) && hasBlock(live, block)).map(block => [...block])
268}
269
270/**
271 * The blocks that left the source between the read the move worked from (`read`) and now:
272 * for each item key of the blocks, as many of its blocks as the source lost lines with that key, the
273 * first ones. Another session that moved the same blocks to the archive cut them; a user who deleted
274 * a done line did too. A block whose line is still there (a box set back, a line typed elsewhere) has
275 * not left. The key ignores the box, so a ticket set back to open is still there.
276 */
277export function blocksLeft(read: string, now: string, blocks: readonly ClosedBlock[]): ClosedBlock[] {
278 const counts = (markdown: string) => {
279 const out = new Map<string, number>()
280 for (const item of parseTodo(markdown)) {
281 const key = storedKey(itemKey(item))
282 out.set(key, (out.get(key) ?? 0) + 1)
283 }
284
285 return out
286 }
287 const [was, is] = [counts(read), counts(now)]
288 const taken = new Map<string, number>()
289
290 return blocks.filter(block => {
291 const first = parseTodo(block.lines[0] ?? '')[0]
292 if (first === undefined) {
293 return false
294 }
295 const key = storedKey(itemKey(first))
296 const lost = (was.get(key) ?? 0) - (is.get(key) ?? 0)
297 const used = taken.get(key) ?? 0
298 if (used >= lost) {
299 return false
300 }
301 taken.set(key, used + 1)
302
303 return true
304 })
305}
306
307/**
308 * The name of the archive file the Show completed link opens, for a folder: a `TODO.md` (any case)
309 * among its todo or archive files; else its only live file; else its only archive file; else `TODO.md`.
310 */
311export function archiveName(files: readonly { name: string; folder: string; isArchived?: boolean }[], folder: string): string {
312 const mine = files.filter(file => file.folder === folder)
313 const live = mine.filter(file => file.isArchived !== true).map(file => file.name)
314 const old = mine.filter(file => file.isArchived === true).map(file => file.name.slice('archive/'.length))
315
316 return [...live, ...old].find(name => name.toLowerCase() === 'todo.md') ?? (live.length === 1 ? live[0] : old.length === 1 ? old[0] : undefined) ?? 'TODO.md'
317}
318hooks/backoff.ts 34 lines1/** Retry backoff: how long to wait after a run of failures in a row. */
2
3/**
4 * The wait before the next try after `failures` failures in a row: `firstMs`, doubled for each
5 * failure after the first, never more than `maxMs`. No failure, no wait.
6 */
7export function backoffMs(failures: number, firstMs: number, maxMs: number): number {
8 if (failures <= 0) {
9 return 0
10 }
11
12 // The exponent is capped, so a long run of failures stays a finite, exact number.
13 return Math.min(maxMs, firstMs * 2 ** Math.min(failures - 1, 30))
14}
15
16/** The failures in a row of one retried thing, and the earliest time of its next try, clock ms. */
17export type Failing = { count: number; retryAt: number }
18
19/** The record after one more failure at `time`: the count goes up by one and the next try waits backoffMs. */
20export function addFailure(before: Failing | undefined, time: number, firstMs: number, maxMs: number): Failing {
21 const count = (before?.count ?? 0) + 1
22
23 return { count, retryAt: time + backoffMs(count, firstMs, maxMs) }
24}
25
26/**
27 * True when a thing with record `failing` may be tried at `time`: it never failed, or its wait is
28 * over. A `retryAt` more than `maxMs` ahead of `time` can only come from a clock set back:
29 * it counts as over, so a set-back never freezes the retries for its length.
30 */
31export function isRetryDue(failing: Failing | undefined, time: number, maxMs: number): boolean {
32 return failing === undefined || time >= failing.retryAt || failing.retryAt - time > maxMs
33}
34hooks/card-format.ts 40 lines1/** The number and time formats on the cards: token counts, durations, plurals and clock times. */
2
3/** "950", "84.3k", "1.23M", "17.38M", "1.50B": a token count, to 2 decimals in millions and billions and 1 in thousands. */
4export function tokens(n: number): string {
5 // A value that is not a finite number shows as 0, as turnTokens counts it: never "NaN" or "InfinityB".
6 if (!Number.isFinite(n)) {
7 return '0'
8 }
9 // The unit is chosen after rounding: 999950 is 1.00M, not 1000.0k.
10 if (n >= 1_000_000_000 || (n >= 1_000_000 && Number((n / 1_000_000).toFixed(2)) >= 1000)) {
11 return `${(n / 1_000_000_000).toFixed(2)}B`
12 }
13 if (n >= 1_000_000 || (n >= 1000 && Number((n / 1000).toFixed(1)) >= 1000)) {
14 return `${(n / 1_000_000).toFixed(2)}M`
15 }
16
17 // Rounded before the unit is chosen: 999.6 rounds to 1000, so it is "1.0k", never "1000".
18 return Math.round(n) >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(Math.round(n))
19}
20
21export function elapsed(ms: number): string {
22 const seconds = Math.max(0, Math.round(ms / 1000))
23 const minutes = Math.floor(seconds / 60)
24
25 return minutes === 0 ? `${seconds}s` : `${minutes}m ${String(seconds % 60).padStart(2, '0')}s`
26}
27
28/** "1 agent", "3 agents" (TXT-4). */
29export function plural(n: number, noun: string): string {
30 return `${n} ${noun}${n === 1 ? '' : 's'}`
31}
32
33/** A wall-clock time in the local time zone, `14:32:05`. */
34export function clock(ms: number): string {
35 const at = new Date(ms)
36 const two = (n: number) => String(n).padStart(2, '0')
37
38 return `${two(at.getHours())}:${two(at.getMinutes())}:${two(at.getSeconds())}`
39}
40hooks/card-stage.ts 141 lines1/** The card stage: the Stage UI palette, the card width, the blink classes and the SVG frame every card sits in. */
2
3/**
4 * The desktop look, to the Stage UI style guide (v1.10), with two deliberate
5 * exceptions: the cards follow the system theme (the stage palette when dark, the guide's
6 * light page tokens when light, LIGHT_CSS; STG-1 keeps the stage black in every theme), and each
7 * live agent has a color that its todo items blink (AGENT_COLORS; COL-8 names no category by
8 * color). Violet is progress and live (COL-1); failed is orange (COL-7). Motion is CSS, so reduced
9 * motion stops it (MOT-2). A ticket card, a file card and the card of an ended agent hold nothing
10 * that changes with the clock alone: a redraw that changes no data sends the same markup, so the
11 * pane does not reload the image. The card of a live agent and the timeline show elapsed time, so
12 * they change with the clock.
13 */
14
15import { esc } from './card-text'
16import type { Card } from './card-types'
17
18// Stage UI tokens: section 3.3 (fixed) and 3.4 (stage palette).
19export const ACCENT = '#8B5CF6'
20const PROGRESS_END = '#C084FC'
21export const INDICATOR = '#7C3AED'
22export const SUGGESTED = '#10303B'
23export const DANGER = '#FB923C'
24export const STAGE_DANGER = '#FF7A33'
25export const GREEN = '#34D399'
26export const STAGE_BG = '#07080F'
27export const CARD = '#171A26'
28export const ACTOR = '#1E2233'
29export const STAGE_GRAY = '#9AA0B4'
30
31export const LABEL = 'rgba(255,255,255,.88)'
32export const SUB = 'rgba(255,255,255,.62)'
33export const FAINT = 'rgba(255,255,255,.38)'
34export const TRACK = 'rgba(255,255,255,.22)'
35export const RULE = 'rgba(255,255,255,.08)'
36
37export const PAD = 16
38/** The widest card the desktop draws, in CSS pixels. */
39const MAX_WIDTH = 4096
40export let W = 384
41export let INNER = W - PAD * 2
42/** The pane's width in CSS pixels: the board's ticket columns grow with it. Equal to `W` since the cards lost their 960 px cap (). */
43export let PANE = W
44
45/**
46 * The cards' width in CSS pixels, set once per draw from the pane's width: from 300 to 4096, the
47 * most the desktop draws. A width that is no finite number leaves the width as it is.
48 */
49export function setWidth(px: number): void {
50 if (!Number.isFinite(px)) {
51 return
52 }
53 W = Math.round(Math.min(MAX_WIDTH, Math.max(300, px)))
54 PANE = W
55 INNER = W - PAD * 2
56}
57
58/**
59 * The light theme: each dark-palette color as drawn, and its Stage UI light page token (section
60 * 3.2). A CSS rule beats a presentation attribute, so one block per card swaps them all when the
61 * system is light; the desktop app on its default "system" theme follows the same setting. Agent
62 * colors and the violet progress stay as they are.
63 */
64const LIGHT: readonly (readonly [string, string, string])[] = [
65 ['fill', STAGE_BG, '#FFFFFF'],
66 ['stroke', STAGE_BG, '#FFFFFF'],
67 ['fill', 'rgba(255,255,255,.88)', '#10131C'],
68 ['fill', 'rgba(255,255,255,.62)', '#5A6072'],
69 ['fill', 'rgba(255,255,255,.38)', 'rgba(16,19,28,.45)'],
70 ['stroke', 'rgba(255,255,255,.38)', 'rgba(16,19,28,.45)'],
71 ['fill', 'rgba(255,255,255,.22)', 'rgba(16,19,28,.12)'],
72 ['stroke', 'rgba(255,255,255,.22)', 'rgba(16,19,28,.12)'],
73 ['stroke', 'rgba(255,255,255,.08)', 'rgba(16,19,28,.08)'],
74 ['fill', 'rgba(255,255,255,.1)', 'rgba(16,19,28,.06)'],
75 ['stroke', 'rgba(255,255,255,.6)', 'rgba(16,19,28,.35)'],
76 ['fill', '#171A26', '#F1F3F8'],
77 ['fill', '#1E2233', '#E1E4EE'],
78 ['fill', '#10303B', '#DDF6FB'],
79 ['fill', '#9AA0B4', '#6B7186'],
80 ['stroke', '#FFFFFF', '#10131C'],
81 ['stroke', '#9AA0B4', '#6B7186'],
82 ['fill', '#FB923C', '#B83C0B'],
83 ['fill', 'rgba(251,146,60,.16)', '#FFEDE3'],
84 ['fill', '#34D399', '#047857'],
85 ['fill', '#22D3EE', '#0E7490'],
86]
87
88export const LIGHT_CSS = `@media (prefers-color-scheme:light){${LIGHT.map(([prop, dark, light]) => `[${prop}="${dark}"]{${prop}:${light}}`).join('')}rect[fill="${STAGE_BG}"]{stroke:rgba(16,19,28,.12);stroke-width:2}}`
89const BLINK_S = 1.2
90
91/**
92 * The blink animations one card uses: a class per set of colors, which blinks each color in turn,
93 * 1.2 s per color. Reduced motion holds the first color solid.
94 */
95export class Blinks {
96 private readonly rules = new Map<string, string>()
97
98 cls(colors: readonly string[]): string {
99 const id = colors.join(',')
100 const known = this.rules.get(id)
101 if (known !== undefined) {
102 return known.split('{')[0]?.slice(1) ?? ''
103 }
104 const name = `k${this.rules.size}`
105 const n = colors.length
106 const frames = colors
107 .map((color, k) => `${((k / n) * 100).toFixed(2)}%{fill:${color};opacity:1}${(((k + 0.5) / n) * 100).toFixed(2)}%{fill:${color};opacity:.25}`)
108 .join('')
109 this.rules.set(id, `.${name}{animation:${name} ${(BLINK_S * n).toFixed(1)}s steps(1,end) infinite}@keyframes ${name}{${frames}}`)
110
111 return name
112 }
113
114 css(): string {
115 const names = [...this.rules.values()].map(rule => `.${rule.split('{')[0]?.slice(1)}`)
116
117 return [...this.rules.values()].join('\n') + (names.length === 0 ? '' : `\n@media (prefers-reduced-motion:reduce){${names.join(',')}{animation:none}}`)
118 }
119}
120
121
122export function stage(height: number, body: string, alt: string, css = ''): Card {
123 const source = `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${height}" viewBox="0 0 ${W} ${height}" role="img" aria-label="${esc(alt)}">
124<defs><linearGradient id="progress" x1="0" x2="1"><stop offset="0.7" stop-color="${ACCENT}"/><stop offset="1" stop-color="${PROGRESS_END}"/></linearGradient></defs>
125<style>
126text{font-family:"Instrument Sans","Helvetica Neue",Arial,sans-serif;font-variant-numeric:tabular-nums;-webkit-font-smoothing:antialiased}
127.mono{font-family:"Fragment Mono",ui-monospace,Menlo,monospace}
128.blink{animation:blink 1.2s steps(1,end) infinite}
129@keyframes blink{50%{opacity:.25}}
130.pulse{animation:pulse 1.2s cubic-bezier(0,0,.2,1) infinite;transform-box:fill-box;transform-origin:center}
131@keyframes pulse{0%{opacity:.6;transform:scale(1)}100%{opacity:0;transform:scale(2.4)}}
132@media (prefers-reduced-motion:reduce){.blink,.pulse{animation:none}.pulse{opacity:0}}
133${LIGHT_CSS}
134${css}
135</style>
136<rect width="${W}" height="${height}" rx="12" fill="${STAGE_BG}"/>
137${body}</svg>`
138
139 return { source, width: W, height, alt }
140}
141hooks/card-text.ts 201 lines1/** Card text: XML-safe characters, alt text, escaping, cutting, fitting a line and wrapping lines. */
2
3/** XML 1.0 forbids these: C0 controls but tab, LF and CR, U+FFFE and U+FFFF, and a surrogate with no partner. */
4const BAD_XML = /[\x00-\x08\x0B\x0C\x0E-\x1F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g
5
6/** The text without the characters an XML document cannot hold. */
7export function cleanText(text: string): string {
8 return text.replace(BAD_XML, '')
9}
10
11/**
12 * Every control character (C0, DEL and C1: \x00-\x1F and \x7F-\x9F, tab and line breaks too) and
13 * every lone surrogate. The engine refuses a whole pane whose Svg alt holds a control character.
14 */
15const BAD_ALT = /[\x00-\x1F\x7F-\x9F]+|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g
16
17/**
18 * The text with no character the engine refuses in a pane's text: each run of control characters
19 * becomes one space (a line break or tab parts words) and a lone surrogate goes. Spaces the text
20 * already had stay, so a terminal line keeps its indent.
21 */
22export function controlFree(text: string): string {
23 return text.replace(BAD_ALT, match => (/^[\uD800-\uDFFF]$/.test(match) ? '' : ' '))
24}
25
26/** Characters that print nothing but reorder or hide text: bidi controls, word joiners, the byte order mark and tag characters. */
27const HIDDEN_FORMAT = /[\u061C\u200B\u200E\u200F\u202A-\u202E\u2060-\u2064\u2066-\u2069\uFEFF]|\uDB40[\uDC00-\uDC7F]/g
28
29/**
30 * Text for a toast: controlFree, and without the format characters that reorder a name or hide
31 * text in it (a right-to-left override, a zero-width space, tag characters), since a toast prints
32 * a file, folder or ticket name as it is.
33 */
34export function toastText(text: string): string {
35 return controlFree(text).replace(HIDDEN_FORMAT, '')
36}
37
38/**
39 * An element key made safe for the engine: a `%` becomes `%25`, and each control
40 * character or lone surrogate becomes `%` and its code in hex (`%1B`, `%D800`). It is an encoding,
41 * not a strip, so two names that differ only by such a character keep two keys. Every key that
42 * holds user text (a file name, a ticket key, a category) goes through it, on both surfaces.
43 */
44export function keyText(text: string): string {
45 const hex = (unit: number) => `%${unit.toString(16).toUpperCase().padStart(2, '0')}`
46
47 return text.replace(/%/g, '%25').replace(BAD_ALT, run => Array.from({ length: run.length }, (_, i) => hex(run.charCodeAt(i))).join(''))
48}
49
50/** A card's alt text as the engine takes it: controlFree, runs of spaces made one, and the ends trimmed. */
51export function altText(text: string): string {
52 return controlFree(text).replace(/ {2,}/g, ' ').trim()
53}
54
55/** At most `n` UTF-16 units of `text`, one fewer when the cut would split a surrogate pair. */
56export function cutUnits(text: string, n: number): string {
57 if (text.length <= n) {
58 return text
59 }
60 const end = Math.max(0, n)
61 const last = text.charCodeAt(end - 1)
62
63 return text.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end)
64}
65
66/** The first `n` code points of `text`: a cut never splits a surrogate pair. */
67export function cutText(text: string, n: number): string {
68 if (text.length <= n) {
69 return text
70 }
71
72 return Array.from(text).slice(0, Math.max(0, n)).join('')
73}
74
75/**
76 * The width of one code point in cells: 2 for East Asian wide characters and emoji (about 1 em),
77 * else 1 (about 0.52 em). A line sized by cells does not overflow on a CJK or emoji text.
78 */
79function cellsOf(point: string): number {
80 const code = point.codePointAt(0) ?? 0
81
82 return code < 0x1100 ? 1 : isWide(code) ? 2 : 1
83}
84
85function isWide(code: number): boolean {
86 return (
87 code <= 0x115f ||
88 (code >= 0x2e80 && code <= 0xa4cf) ||
89 (code >= 0xac00 && code <= 0xd7a3) ||
90 (code >= 0xf900 && code <= 0xfaff) ||
91 (code >= 0xfe30 && code <= 0xfe6f) ||
92 (code >= 0xff00 && code <= 0xff60) ||
93 (code >= 0xffe0 && code <= 0xffe6) ||
94 (code >= 0x1f300 && code <= 0x1faff) ||
95 (code >= 0x20000 && code <= 0x3fffd)
96 )
97}
98
99/** The width of `text` in cells. */
100function cells(text: string): number {
101 let total = 0
102 for (const point of text) {
103 total += cellsOf(point)
104 }
105
106 return total
107}
108
109/** The longest start of `text` that is at most `n` cells wide; a cut never splits a surrogate pair. */
110function cutCells(text: string, n: number): string {
111 let used = 0
112 let end = 0
113 for (const point of text) {
114 used += cellsOf(point)
115 if (used > n) {
116 break
117 }
118 end += point.length
119 }
120
121 return text.slice(0, end)
122}
123
124export function esc(text: string): string {
125 return cleanText(text).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
126}
127
128/** Ends a single-line text with an ellipsis when it does not fit (TYP-3). */
129export function fit(text: string, px: number, size: number, weight = 400, isMono = false): string {
130 const glyph = size * (isMono ? 0.62 : weight >= 500 ? 0.55 : 0.52)
131 const room = Math.max(1, Math.floor(px / glyph))
132
133 return cells(text) > room ? `${cutCells(text, Math.max(1, room - 1)).trimEnd()}…` : text
134}
135export const MAX_LINES = 8
136
137/**
138 * Breaks a text into lines that fit `px` at `size`, at spaces where it can and inside a long word
139 * where it must; past `maxLines` the last line ends with an ellipsis (TYP-3: long free text wraps).
140 */
141export function wrap(text: string, px: number, size: number, weight = 400, maxLines = MAX_LINES): string[] {
142 const room = Math.max(8, Math.floor(px / (size * (weight >= 500 ? 0.55 : 0.52))))
143 const lines: string[] = []
144 let line = ''
145 // Every pass is linear in the text: a long word is cut once, in one scan, and the walk ends as
146 // soon as one line more than `maxLines` exists, since only the first `maxLines` are kept.
147 for (const word of text.split(/\s+/)) {
148 if (word === '') {
149 continue
150 }
151 if (lines.length > maxLines) {
152 break
153 }
154 let rest = word
155 if (cells(word) > room) {
156 let used = 0
157 let start = 0
158 let at = 0
159 const chunks: string[] = []
160 for (const point of word) {
161 const width = cellsOf(point)
162 if (used + width > room) {
163 chunks.push(word.slice(start, at))
164 start = at
165 used = 0
166 if (lines.length + chunks.length > maxLines + 1) {
167 break
168 }
169 }
170 used += width
171 at += point.length
172 }
173 chunks.push(word.slice(start, at))
174 rest = chunks.pop() ?? ''
175 if (line !== '') {
176 lines.push(line)
177 line = ''
178 }
179 lines.push(...chunks)
180 }
181 if (line === '') {
182 line = rest
183 } else if (cells(line) + 1 + cells(rest) <= room) {
184 line = `${line} ${rest}`
185 } else {
186 lines.push(line)
187 line = rest
188 }
189 }
190 if (line !== '' || lines.length === 0) {
191 lines.push(line)
192 }
193 if (lines.length <= maxLines) {
194 return lines
195 }
196 const kept = lines.slice(0, maxLines)
197 kept[maxLines - 1] = `${cutCells(kept[maxLines - 1] ?? '', Math.max(1, room - 1)).trimEnd()}…`
198
199 return kept
200}
201