A live pixel-art office showing what every agent in the session is doing

A live pixel-art office for Claude Code that shows what every agent in your session is doing. Main, the agent you talk to, sits in the corner office. Each helper it hires arrives by elevator, gets briefed in the meeting room, walks to the station that matches the tool it is using (the library for reading and searching, the server room for commands, the desks for edits, the phone booths for the web) and carries its report back to whoever hired it. Beside the picture, a plain-English feed and an org chart say who is doing what, who is waiting on whom, and who is waiting on you.
Pictures, a full tour and the troubleshooting guide are on the project page.
In Claude Code 2.1.295 or newer:
/plugin install pixel-office --marketplace sb2403/pixel-office
Then start a new session.
Start a session. The office opens by itself the first time a helper is hired, or at any time with /office.
/office shows or hides the office./office settings lists the settings and their values, and /office set <name> <value> changes one. The Settings button under the picture and Claude Code's /config do the same.| Setting | Default | What it does |
|---|---|---|
autoOpen | on-first-subagent | When the office opens by itself: on-first-subagent, session-start or never. |
history | off | last-20 keeps a short record of your newest 20 jobs so the recap can list earlier ones. |
notify | off | after-30s reminds you once, with a toast and a notification, when an agent has waited 30 seconds on you. |
otherSessions | off | on lists your other Claude Code sessions on this computer that also have it on. |
debug | off | on writes a troubleshooting log. |
claude -p or cloud sessions, so the office does not appear there.Pixel Office is readable TypeScript event handlers (a Claude Code mod). It runs no commands, installs no packages and starts no servers.
CLAUDE_CONFIG_DIR, HOME and USERPROFILE, only to find your Claude config folder.history set to last-20: the newest 20 jobs in the mod's own plugin store on this computer. Each entry holds the first 120 characters of the message that began the job, when it started, how long it took, how many helpers and the token counts.otherSessions set to on: one small file per session in pixel-office/sessions under your Claude config folder, rewritten every few seconds. It holds the project folder's name (not its path), the session's status, the kind of work in a few fixed words, the first 60 characters of the message it is working on, and its agents' kinds and positions. No brief, report, tool, file name or command goes in it.debug set to on: debug/log.jsonl inside the plugin's own folder, capped at 3000 lines. It holds event kinds, agent ids, tool names, counts and timings, never commands, file names or your text./office set writes that option under pluginConfigs in your Claude Code settings.json, the same place /config writes it. It never touches permissions or any other setting.notify on, it shows a toast and raises a notification through your own notification setting./office commands are the only text it ever adds.All data stays on your computer. Turning a setting back to off stops the writing.
MIT. See the license.
hooks/register.tsx 723 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, FsEntry, Register, TurnUsage } from 'claude-code'
3
4import type { JobRecord, OfficeEvent, PeerSession, PeerStatus, Usage } from '../types'
5import { debugOn, logText, note, takeDirty } from './debuglog'
6import { MAIN, emptyScene, needsSweep, reduceAt, restore } from './model'
7import { registerPane } from './pane'
8import {
9 BEAT_MS,
10 CALM_MS,
11 PEER_FILE_MAX,
12 POLL_MS,
13 STALE_MS,
14 baseName,
15 contentOf,
16 freeSlots,
17 isTakenFrom,
18 livePeers,
19 lookedOf,
20 parsePeer,
21 peerKey,
22 peerDirOf,
23 peerStatusOf,
24 shownOf,
25 slotName,
26 slotOf,
27 snapshotOf,
28 tombstoneOf,
29 urgentOf,
30} from './peers'
31import type { Self, SlotSeen } from './peers'
32import { HISTORY_MAX, SESSION_MAX, isRecord, jobRecord, recapOf, withRecord } from './recap'
33import { LEAD_MS, nowOf } from './render'
34import { CANNOT, MANY_COPIES, SETTINGS_HELP, USAGE, configKeyOf, parseSet, replyAfterSet, setReply, settingLines } from './settings'
35import type { Setting } from './settings'
36import { PANE, PANE_TITLE, PROBE_BOTTOM, PROBE_TOP } from './state'
37import { WAITING_TOOLS, detailOf, fullText, gist, stationFor, targetOf, todoCounts } from './stations'
38
39export const FLUSH_MS = 350
40// How much of a helper's brief and of its report the office keeps, to be read in full from its details box.
41export const TEXT_MAX = 2000
42// How much of your message names the job in its recap.
43export const TASK_MAX = 120
44const SWEEP_EVERY = 15
45const CLOCK_EVERY = 3
46const QUEUE_MAX = 500
47// With reminders on: how long an agent waits on you before the office says so, once per wait.
48export const REMIND_AFTER_MS = 30_000
49export const REMIND_TITLE = 'Pixel Office'
50// The debug log is written at most this often.
51const DEBUG_WRITE_MS = 1000
52
53// The history, when it is switched on, lives under one key of the mod's store.
54export const HISTORY_KEY = 'jobs'
55const UNTRACKED = new Set(['Agent', 'Task'])
56// These wake Main about work already under way, so they continue the job; a scheduled trigger, the composer,
57// the bridge and the SDK are a person's or a host's own new message.
58const NOT_A_NEW_JOB = new Set(['task-notification', 'peer', 'peer-send-message'])
59
60// Atoms cannot be imported across files, so each file that reads one declares it again; pane.tsx has the same three.
61const sceneAtom = atom({ plugin: 'pixel-office', key: 'scene' } as const, emptyScene())
62const selectedAtom = atom({ plugin: 'pixel-office', key: 'selected' } as const, null as string | null)
63const clockAtom = atom({ plugin: 'pixel-office', key: 'clock' } as const, 0)
64const expandedAtom = atom({ plugin: 'pixel-office', key: 'expanded' } as const, null as 'brief' | 'report' | null)
65const jobOpenAtom = atom({ plugin: 'pixel-office', key: 'jobOpen' } as const, false)
66const historyAtom = atom({ plugin: 'pixel-office', key: 'history' } as const, [] as JobRecord[])
67const sessionAtom = atom({ plugin: 'pixel-office', key: 'session' } as const, [] as JobRecord[])
68const othersAtom = atom({ plugin: 'pixel-office', key: 'others' } as const, [] as PeerSession[])
69const lookingAtom = atom({ plugin: 'pixel-office', key: 'looking' } as const, null as string | null)
70const lookedAtom = atom({ plugin: 'pixel-office', key: 'looked' } as const, null as PeerSession | null)
71
72
73// A turn's token counts, summed over its requests (absent when nothing counted: an interrupt, an API error).
74const usageOf = (u: TurnUsage | undefined): Usage | null =>
75 u === undefined
76 ? null
77 : {
78 tokens: u.input_tokens + u.output_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens,
79 reused: u.cache_read_input_tokens,
80 model: u.model,
81 }
82
83const quietly = async (work: () => Promise<void> | void): Promise<void> => {
84 try {
85 await work()
86 } catch {
87 // The office is best effort: it never disturbs the session it watches.
88 }
89}
90
91// The other sessions on this computer (option `otherSessions`), looked at on a schedule of its own beside the flush,
92// so a slow or stuck disk never holds up this session's own office.
93type Peers = {
94 // The shared folder: undefined until looked up, null when there is none.
95 dir: string | null | undefined
96 // This load of the module: a hot reload or a second process on the same session is another instance.
97 instance: string
98 startedAt: number
99 slot: number | null
100 hasClaimed: boolean
101 // When the slot was last read back holding this instance (or claimed): the tombstone is written only then.
102 verifiedAt: number
103 lastPoll: number
104 lastBeat: number
105 lastContent: string
106 status: PeerStatus | null
107 since: number
108 isBusy: boolean
109 // Counts the looks. A look that overran LOOK_MAX_MS is let go: the next one starts, and the old one, if its disk
110 // call ever comes back, finds the count moved on and changes nothing.
111 looks: number
112 // The file a look is reading now, and the files a look was let go on: those are left alone from then on, as
113 // odd slots are, so one file that never answers cannot stop every later look.
114 reading: string | null
115 stuck: Set<string>
116 isEnded: boolean
117 run: Promise<void> | null
118 // Each slot file last read as a snapshot, by name, with the size and time it had then. A file that did not
119 // parse is never kept, so it is read again next time.
120 cache: Map<string, { mtimeMs: number; size: number; readAt: number; peer: PeerSession }>
121 urgent: string
122 shown: string
123 shownAt: number
124 reminded: Set<string>
125}
126
127// `epoch` counts the /clears: a flush notes it when it takes the queue, so it can tell its batch has gone stale.
128type Office = {
129 queue: OfficeEvent[]
130 isFlushing: boolean
131 flushes: number
132 isOpened: boolean
133 wantsOpen: boolean
134 epoch: number
135 keepsHistory: boolean
136 hasJobToSave: boolean
137 reminds: boolean
138 // When each agent now waiting on you started to, and which of them were reminded about this wait.
139 waitingSince: Map<string, number>
140 reminded: Set<string>
141 // The opt-in debug log: whether it is on, and when it was last written.
142 isDebug: boolean
143 lastDebugWrite: number
144 // Where the latest prompt came from (its origin kind); the turn it starts reads and clears it.
145 lastOrigin: string | null
146 // Null while `otherSessions` is off: then nothing is written or read.
147 peers: Peers | null
148}
149
150// The engine only lets `$` travel into functions declared at the top of this file, so the helpers that
151// take it live here and share the mutable bits through one plain object.
152async function openPane($: EngineInterface, office: Office): Promise<void> {
153 await $.ui.open({ id: PANE, title: PANE_TITLE })
154 office.isOpened = true
155}
156
157async function loadHistory($: EngineInterface): Promise<void> {
158 const saved = await $.store.get(HISTORY_KEY)
159 const list = Array.isArray(saved) ? saved.filter(isRecord).slice(-HISTORY_MAX) : []
160 await update($, historyAtom, () => list)
161}
162
163async function saveJob($: EngineInterface): Promise<void> {
164 const recap = recapOf(restore(await read($, sceneAtom)), await $.clock.now())
165 if (recap === null) return
166 const list = withRecord(await read($, historyAtom), jobRecord(recap))
167 await $.store.set(HISTORY_KEY, list)
168 await update($, historyAtom, () => list)
169}
170
171// The session total is kept in memory whatever the history option says.
172async function recordJob($: EngineInterface): Promise<void> {
173 const recap = recapOf(restore(await read($, sceneAtom)), await $.clock.now())
174 if (recap === null) return
175 await update($, sessionAtom, list => withRecord(list, jobRecord(recap), SESSION_MAX))
176}
177
178// An agent that has waited on you for a while is said once: a toast, which shows over the transcript wherever the
179// session is drawn, and a native notification, which the person's channel raises in a terminal (in the desktop
180// app only their own notification hooks run). A wait that ends and begins again is a new wait.
181async function remind($: EngineInterface, office: Office): Promise<void> {
182 const scene = restore(await read($, sceneAtom))
183 const now = await $.clock.now()
184 const waiting = Object.values(scene.agents).filter(a => a.phase === 'waiting')
185 for (const id of [...office.waitingSince.keys()]) {
186 if (waiting.some(a => a.id === id)) continue
187 office.waitingSince.delete(id)
188 office.reminded.delete(id)
189 }
190 for (const agent of waiting) {
191 const since = office.waitingSince.get(agent.id) ?? now
192 office.waitingSince.set(agent.id, since)
193 if (now - since < REMIND_AFTER_MS || office.reminded.has(agent.id)) continue
194 office.reminded.add(agent.id)
195 const text = `${agent.label} is ${nowOf(scene, agent)}`
196 $.ui.toast(text, { timeoutMs: 10_000 })
197 await $.ui.notify(text, { title: REMIND_TITLE })
198 }
199}
200
201async function flush($: EngineInterface, office: Office): Promise<void> {
202 if (office.isFlushing) return
203 office.isFlushing = true
204 await quietly(async () => {
205 office.flushes += 1
206 const now = await $.clock.now()
207 const batch = office.queue
208 const epoch = office.epoch
209 const began = office.isDebug ? now : 0
210 office.queue = []
211 const isSweepTurn = office.flushes % SWEEP_EVERY === 0
212 // Saved from the batch being applied, so the record never misses the end of the turn it is about.
213 if (batch.some(ev => ev.kind === 'turnEnded')) office.hasJobToSave = true
214 if (batch.length === 0 && !(isSweepTurn && needsSweep(restore(await read($, sceneAtom)), now))) return
215 // The pane draws the picture as of LEAD_MS ahead, right after this write: the walks these events start begin
216 // there, so the picture shows each one from its first step.
217 const shownAt = now + LEAD_MS
218 await update($, sceneAtom, scene => {
219 // A /clear since the queue was taken makes this batch (and sweep) belong to the old conversation. The
220 // updater reruns when a write misses its version, so the check holds however the two interleave.
221 if (office.epoch !== epoch) return scene
222 const applied = batch.reduce((s, ev) => reduceAt(s, ev, shownAt), restore(scene))
223 return isSweepTurn && needsSweep(applied, now) ? reduceAt(applied, { kind: 'tick', at: now }, shownAt) : applied
224 })
225 if (office.isDebug) note('flush', { batch: batch.length, ms: (await $.clock.now()) - began }, now)
226 })
227 // The "On the job" clock of a selected agent is the one thing that changes with no event behind it:
228 // about once a second, while a row is open, write the time to state. The pane reads that atom, and a state
229 // write is what makes the desktop pane redraw (a bare redraw request from this timer does not).
230 // Only a helper still on the job has a clock to keep: not Main, not one that has left, not a pruned id.
231 // The open recap of a job still running keeps time the same way.
232 await quietly(async () => {
233 if (office.flushes % CLOCK_EVERY !== 0) return
234 const scene = restore(await read($, sceneAtom))
235 const selected = await read($, selectedAtom)
236 const agent = selected === null || selected === MAIN ? undefined : scene.agents[selected]
237 const isClockShown = agent !== undefined && agent.phase !== 'gone'
238 const isJobShown = (await read($, jobOpenAtom)) && scene.job !== null && scene.job.endedAt === null
239 if (!isClockShown && !isJobShown) return
240 const now = await $.clock.now()
241 await update($, clockAtom, () => now)
242 })
243 // The history is written after the scene, so the record holds the turn that just ended.
244 const isJobDue = office.hasJobToSave
245 office.hasJobToSave = false
246 await quietly(async () => {
247 if (isJobDue) await recordJob($)
248 })
249 await quietly(async () => {
250 if (office.keepsHistory && isJobDue) await saveJob($)
251 })
252 await quietly(async () => {
253 if (office.reminds && office.flushes % CLOCK_EVERY === 0) await remind($, office)
254 })
255 // The debug log is a file the maintainer can read: rewritten as a whole, when it has changed, at most once a second.
256 await quietly(async () => {
257 if (!office.isDebug || !takeDirty()) return
258 const at = await $.clock.now()
259 if (at - office.lastDebugWrite < DEBUG_WRITE_MS) return
260 office.lastDebugWrite = at
261 await $.fs.write(`${$.plugin.root}/debug/log.jsonl`, logText())
262 })
263 // The session and spawn hooks only ask for the pane; it opens here, off their path, and a failed open tries again next flush.
264 await quietly(async () => {
265 if (office.wantsOpen && !office.isOpened) await openPane($, office)
266 })
267 office.isFlushing = false
268}
269
270// Whether `every` has passed since `at`. A clock set back makes it due at once, so the beat goes on rather than
271// stopping until the clock catches up again.
272// A look that takes longer than this is let go; each wait at the end of a session is shorter still.
273const LOOK_MAX_MS = 5000
274const END_WAIT_MS = 300
275const MTIME_SLACK_MS = 2000
276
277const isDue = (now: number, at: number, every: number): boolean => now < at || now - at >= every
278
279async function peerDir($: EngineInterface): Promise<string | null> {
280 const configDir = await $.env.get('CLAUDE_CONFIG_DIR')
281 const home = await $.env.get('HOME')
282 const userProfile = await $.env.get('USERPROFILE')
283 return peerDirOf({ configDir, home, userProfile })
284}
285
286// Reads the slots that changed since they were last read. A slot that is not a plain small file (a link, a folder,
287// something big) is marked odd: never read, never written to, never free. Null when the folder is there but cannot
288// be listed: every slot would look free, and this copy must not write into one another holds.
289async function readSlots($: EngineInterface, peers: Peers, dir: string, now: number): Promise<Map<number, SlotSeen> | null> {
290 const seen = new Map<number, SlotSeen>()
291 const listed: FsEntry[] | null = await $.fs.list(dir).catch(() => null)
292 if (listed === null && (await $.fs.exists(dir).catch(() => true))) return null
293 const entries = listed ?? []
294 for (const entry of entries) {
295 const slot = slotOf(entry.name)
296 if (slot === null) continue
297 if (entry.kind !== 'file' || entry.isLink || entry.size > PEER_FILE_MAX || peers.stuck.has(entry.name)) {
298 seen.set(slot, { peer: null, mtimeMs: entry.mtimeMs, isOdd: true })
299 continue
300 }
301 // This copy's own slot is always read afresh: it is how a copy learns another took it. So is a file read within
302 // MTIME_SLACK_MS of its last change: a rewrite of the same size in the same tick of a coarse file clock (FAT,
303 // a network share) would keep its time, and the change would go unseen.
304 const cached = peers.cache.get(entry.name)
305 const isSettled = cached !== undefined && cached.readAt - cached.mtimeMs > MTIME_SLACK_MS
306 if (slot !== peers.slot && isSettled && cached.mtimeMs === entry.mtimeMs && cached.size === entry.size) {
307 seen.set(slot, { peer: cached.peer, mtimeMs: entry.mtimeMs, isOdd: false })
308 continue
309 }
310 peers.reading = entry.name
311 const text: unknown = await $.fs.read(`${dir}/${entry.name}`).catch(() => null)
312 peers.reading = null
313 const peer = typeof text === 'string' ? parsePeer(text) : null
314 // A file caught half written keeps its last good copy, which ages out as any other, and stays uncached so the
315 // next look reads it again; a session does not drop out of the list for one bad read.
316 if (peer !== null) peers.cache.set(entry.name, { mtimeMs: entry.mtimeMs, size: entry.size, readAt: now, peer })
317 seen.set(slot, { peer: peer ?? cached?.peer ?? null, mtimeMs: entry.mtimeMs, isOdd: false })
318 }
319 return seen
320}
321
322// One look at the other sessions, at most every POLL_MS: read the slots, keep (or claim) this copy's own, write its
323// snapshot when it changed or a heartbeat is due, and hand the pane the others when what it shows has changed.
324async function lookAround($: EngineInterface, office: Office, peers: Peers, look: number): Promise<void> {
325 const now = await $.clock.now()
326 if (!isDue(now, peers.lastPoll, POLL_MS)) return
327 peers.lastPoll = now
328 if (peers.startedAt === 0) peers.startedAt = now
329 if (peers.dir === undefined) peers.dir = await peerDir($)
330 const dir = peers.dir
331 if (dir === null) return
332 // Read every time: a /clear goes on under a new session id.
333 const sessionId = await $.session.id()
334 const self = { instance: peers.instance, sessionId }
335 const seen = await readSlots($, peers, dir, now)
336 if (seen === null || look !== peers.looks) return
337
338 // Two copies that took one slot at once: the one that sees the other's snapshot there moves.
339 const mine = peers.slot === null ? undefined : seen.get(peers.slot)
340 if (peers.slot !== null && (mine?.isOdd === true || isTakenFrom(mine, peers.instance, now))) {
341 peers.slot = null
342 peers.lastContent = ''
343 }
344 if (peers.slot === null) {
345 const { own, free } = freeSlots(seen, self, now)
346 // Only a first claim takes back this session's slot from an older copy (a hot reload's): a copy that was moved
347 // on must not take it back from the copy that moved it, or two processes on one session would swap for ever.
348 const chosen = !peers.hasClaimed && own !== null ? own : free.length === 0 ? null : free[Math.floor(Math.random() * free.length)] ?? null
349 peers.slot = chosen
350 if (chosen !== null) {
351 peers.hasClaimed = true
352 peers.verifiedAt = now
353 peers.lastContent = ''
354 }
355 } else {
356 peers.verifiedAt = now
357 // Anything but this copy's own snapshot in its slot (a stale one, a broken one) is put right at once.
358 if (mine?.peer?.instance !== peers.instance) peers.lastContent = ''
359 }
360
361 const scene = restore(await read($, sceneAtom))
362 const status = peerStatusOf(scene)
363 if (status !== peers.status) {
364 peers.status = status
365 peers.since = now
366 }
367 if (peers.slot !== null) {
368 const project = baseName(await $.session.root())
369 const snapshot = snapshotOf(scene, { instance: peers.instance, sessionId, startedAt: peers.startedAt, project, since: peers.since }, now)
370 const content = contentOf(snapshot)
371 // Checked last thing before the write: once the session has ended its tombstone must be the slot's last word.
372 if ((content !== peers.lastContent || isDue(now, peers.lastBeat, BEAT_MS)) && !peers.isEnded && look === peers.looks) {
373 await $.fs.write(`${dir}/${slotName(peers.slot)}`, JSON.stringify(snapshot))
374 peers.lastContent = content
375 peers.lastBeat = now
376 }
377 }
378
379 const others = livePeersOf(seen, self, now)
380 const urgent = urgentOf(others)
381 const shown = shownOf(others)
382 if (look !== peers.looks) return
383 if (urgent !== peers.urgent || (shown !== peers.shown && isDue(now, peers.shownAt, CALM_MS))) {
384 peers.urgent = urgent
385 peers.shown = shown
386 peers.shownAt = now
387 await update($, othersAtom, () => others)
388 }
389
390 // The office being looked in on is redrawn as soon as what it shows changes, without the list's calm window: while
391 // it is on show, this session's own walks are not, so its redraws restart nothing anyone is watching. A session
392 // that has gone takes the picture back to this office.
393 const looking = await read($, lookingAtom)
394 const shownNow = await read($, lookedAtom)
395 if (look !== peers.looks) return
396 const found = looking === null ? undefined : others.find(p => peerKey(p) === looking)
397 // A press between the read above and these writes wins: each write checks the pane still looks where it did.
398 if (looking !== null && found === undefined) {
399 await update($, lookingAtom, current => (current === looking ? null : current))
400 if ((await read($, lookingAtom)) === null) await update($, lookedAtom, () => null)
401 } else if (found !== undefined && (shownNow === null || lookedOf(found) !== lookedOf(shownNow))) {
402 if ((await read($, lookingAtom)) === looking) await update($, lookedAtom, () => found)
403 }
404
405 // With reminders on, another session waiting on you for a while is said once, as a toast only: that session
406 // raises its own notification, and one from every other session would repeat it.
407 if (office.reminds) {
408 const waits = new Set(others.filter(p => p.status === 'waiting').map(p => `${p.sessionId}:${p.instance}:${p.since}`))
409 for (const key of [...peers.reminded]) if (!waits.has(key)) peers.reminded.delete(key)
410 for (const peer of others) {
411 const key = `${peer.sessionId}:${peer.instance}:${peer.since}`
412 if (peer.status !== 'waiting' || now - peer.since < REMIND_AFTER_MS || peers.reminded.has(key)) continue
413 peers.reminded.add(key)
414 $.ui.toast(`In ${peer.project === '' ? 'another session' : peer.project}, an agent is waiting on you`, { timeoutMs: 10_000 })
415 }
416 }
417}
418
419const livePeersOf = (seen: ReadonlyMap<number, SlotSeen>, self: Self, now: number): PeerSession[] =>
420 livePeers(
421 [...seen.values()].flatMap(found => (found.peer === null ? [] : [found.peer])),
422 self,
423 now,
424 )
425
426function peerTick($: EngineInterface, office: Office): void {
427 const peers = office.peers
428 if (peers === null || peers.isBusy || peers.isEnded) return
429 peers.isBusy = true
430 peers.looks += 1
431 const look = peers.looks
432 const ran = quietly(() => lookAround($, office, peers, look))
433 peers.run = Promise.race([ran, quietly(() => $.clock.sleep(LOOK_MAX_MS))]).finally(() => {
434 if (peers.looks !== look) return
435 peers.isBusy = false
436 // Let go: whatever the overrun look does when it comes back, it changes nothing.
437 peers.looks += 1
438 if (peers.reading !== null) peers.stuck.add(peers.reading)
439 peers.reading = null
440 })
441}
442
443// The session is over (not a /clear or a resume, which go on under a new id): mark the slot free for the others.
444// One write, after any look already under way, and only into a slot this copy recently saw as its own, as the whole
445// end of a session has a short bound and another copy may have taken a slot this one lost track of.
446async function endPeers($: EngineInterface, office: Office): Promise<void> {
447 const peers = office.peers
448 if (peers === null || peers.isEnded) return
449 peers.isEnded = true
450 // Each wait is short, as the whole end of a session has a bound of its own and a stuck disk must not use it up.
451 if (peers.run !== null) await Promise.race([peers.run, quietly(() => $.clock.sleep(END_WAIT_MS))])
452 if (peers.slot === null || typeof peers.dir !== 'string') return
453 const now = await $.clock.now()
454 if (Math.abs(now - peers.verifiedAt) > STALE_MS) return
455 // Only over this copy's own snapshot: another copy may have taken the slot since the last look.
456 const path = `${peers.dir}/${slotName(peers.slot)}`
457 const text: unknown = await Promise.race([$.fs.read(path).catch(() => null), quietly(() => $.clock.sleep(END_WAIT_MS)).then(() => null)])
458 const held = typeof text === 'string' ? parsePeer(text) : null
459 if (held?.instance !== peers.instance) return
460 const meta = { instance: peers.instance, sessionId: await $.session.id(), startedAt: peers.startedAt, project: '', since: now }
461 await $.fs.write(path, JSON.stringify(tombstoneOf(meta, now)))
462}
463
464// Changes one setting the way the `/config` menu does, and says how it went. pane.tsx and register.tsx each have
465// this: the engine follows `$` only into a function of the same file.
466async function changeSetting($: EngineInterface, setting: Setting, value: string): Promise<string> {
467 let keys: string[] = []
468 try {
469 keys = (await $.config.list()).map(row => row.key)
470 } catch {
471 // An engine without the listing: the key is the plain one.
472 }
473 const key = configKeyOf(keys, setting.field)
474 if (key === null) return setReply(setting, value, MANY_COPIES)
475 let deny: string | undefined
476 try {
477 deny = (await $.config.set({ key, value })).deny
478 } catch {
479 return setReply(setting, value, CANNOT)
480 }
481 let stored: unknown
482 try {
483 stored = (await $.config.list()).find(row => row.key === key)?.value
484 } catch {
485 // Not listed: the change is taken at its word.
486 }
487 return replyAfterSet(setting, value, deny, stored)
488}
489
490export const register: Register = (on, options) => {
491 const autoOpen = String(options.autoOpen ?? 'on-first-subagent')
492 const office: Office = {
493 queue: [],
494 isFlushing: false,
495 flushes: 0,
496 isOpened: false,
497 wantsOpen: false,
498 epoch: 0,
499 keepsHistory: String(options.history ?? 'off') === 'last-20',
500 hasJobToSave: false,
501 reminds: String(options.notify ?? 'off') === 'after-30s',
502 waitingSince: new Map(),
503 reminded: new Set(),
504 isDebug: String(options.debug ?? 'off') === 'on',
505 lastDebugWrite: 0,
506 lastOrigin: null,
507 peers:
508 String(options.otherSessions ?? 'off') === 'on'
509 ? {
510 dir: undefined,
511 instance: crypto.randomUUID(),
512 startedAt: 0,
513 slot: null,
514 hasClaimed: false,
515 verifiedAt: 0,
516 lastPoll: 0,
517 lastBeat: 0,
518 lastContent: '',
519 status: null,
520 since: 0,
521 isBusy: false,
522 looks: 0,
523 reading: null,
524 stuck: new Set(),
525 isEnded: false,
526 run: null,
527 cache: new Map(),
528 urgent: '[]',
529 shown: '[]',
530 shownAt: 0,
531 reminded: new Set(),
532 }
533 : null,
534 }
535 debugOn(office.isDebug)
536
537 const push = (ev: OfficeEvent): void => {
538 if (office.isDebug) {
539 const r = ev as Record<string, unknown>
540 const agent = typeof r.agentId === 'string' ? r.agentId : typeof r.id === 'string' ? r.id : null
541 note('event', { ev: ev.kind, agent, tool: ev.kind === 'toolStarted' ? ev.tool : undefined }, ev.at)
542 }
543 office.queue.push(ev)
544 if (office.queue.length > QUEUE_MAX) office.queue = office.queue.slice(-QUEUE_MAX)
545 }
546
547 on('session.start', async ($, e, next) => {
548 // Each step stands alone: one that fails must not keep the others from running.
549 await quietly(() => {
550 $.clock.every(FLUSH_MS, () => {
551 void flush($, office)
552 peerTick($, office)
553 })
554 })
555 await quietly(async () => {
556 await $.command.register({ name: 'office', description: 'Show or hide the pixel office; /office settings lists its settings' })
557 })
558 await quietly(async () => {
559 if (office.keepsHistory) await loadHistory($)
560 })
561 // The session start hook only asks for the pane, as the spawn hook does; the flush opens it.
562 if (autoOpen === 'session-start') office.wantsOpen = true
563 return next(e)
564 }).catch(($, e, next) => next(e))
565
566 on('session.end', async ($, e, next) => {
567 // A /clear ends the conversation but not the process, and no session.start follows it: the office starts
568 // over, and the flush timer keeps running. Events still queued belong to the old conversation, and so does
569 // a batch a flush has already taken off the queue: bumping the epoch makes that flush leave the new scene alone.
570 if (e.reason !== 'clear' && e.reason !== 'resume') await quietly(() => endPeers($, office))
571 if (e.reason === 'clear') {
572 await quietly(() => {
573 office.epoch += 1
574 office.queue = []
575 })
576 await quietly(async () => {
577 await update($, sceneAtom, () => emptyScene())
578 })
579 await quietly(async () => {
580 await update($, selectedAtom, () => null)
581 })
582 await quietly(async () => {
583 await update($, expandedAtom, () => null)
584 })
585 await quietly(async () => {
586 await update($, sessionAtom, () => [])
587 })
588 }
589 return next(e)
590 }).catch(($, e, next) => next(e))
591
592 on('tool.call', async ($, e, next) => {
593 const tool = String(e.tool)
594 const agentId = e.agentId ?? MAIN
595 const callId = e.tool_use_id
596 const isTracked = !UNTRACKED.has(tool)
597 if (isTracked) {
598 await quietly(async () => {
599 const input = e as Record<string, unknown>
600 const at = await $.clock.now()
601 push({ kind: 'toolStarted', agentId, tool, target: targetOf(tool, input), detail: detailOf(tool, input), callId, at })
602 const counts = stationFor(tool) === 'taskboard' ? todoCounts(input) : null
603 if (counts !== null) push({ kind: 'todos', ...counts, at })
604 })
605 }
606 const ran = await next(e)
607 if (isTracked) {
608 await quietly(async () => {
609 const isError = ran.deny === undefined && ran.isError === true
610 push({ kind: 'toolEnded', agentId, callId, isError, at: await $.clock.now() })
611 })
612 }
613 return ran
614 }).catch(($, e, next) => next(e))
615
616 on('agent.spawn', async ($, e, next) => {
617 const spawned = await next(e)
618 await quietly(async () => {
619 if (spawned.deny !== undefined || spawned.agentId === undefined) return
620 push({
621 kind: 'spawned',
622 id: spawned.agentId,
623 parentId: e.parentAgentId ?? MAIN,
624 type: e.subagentType,
625 description: e.description,
626 brief: fullText(e.prompt, TEXT_MAX),
627 name: e.name ?? null,
628 isTeammate: e.isTeammate === true,
629 isBackground: e.background === true,
630 isResume: e.resume !== undefined,
631 at: await $.clock.now(),
632 })
633 if (autoOpen === 'on-first-subagent' && !office.isOpened) office.wantsOpen = true
634 })
635 return spawned
636 }).catch(($, e, next) => next(e))
637
638 // The engine settles a prompt before the main loop's turn starts; the turn reads where it came from.
639 on('prompt.submit', async ($, e, next) => {
640 office.lastOrigin = e.origin?.kind ?? null
641 return next(e)
642 }).catch(($, e, next) => next(e))
643
644 on('turn.start', async ($, e, next) => {
645 // The engine fires this for a helper's run too; only the main loop's turn is the person's message.
646 if (e.agentId !== undefined) {
647 if (office.isDebug) note('turn-ignored', { agent: e.agentId })
648 return next(e)
649 }
650 const origin = office.lastOrigin
651 office.lastOrigin = null
652 const isNotice = origin !== null ? NOT_A_NEW_JOB.has(origin) : e.text.trimStart().startsWith('<task-notification')
653 // A turn started without typed text, or woken by a notice, carries on the job under way.
654 const continues = e.text === '' || isNotice
655 if (office.isDebug) note('turn-start', { origin: origin ?? 'none', continues })
656 await quietly(async () =>
657 push({
658 kind: 'turnStarted',
659 isContinuation: continues,
660 task: isNotice ? '' : gist(e.text, TASK_MAX),
661 at: await $.clock.now(),
662 }),
663 )
664 return next(e)
665 }).catch(($, e, next) => next(e))
666
667 on('turn.complete', async ($, e, next) => {
668 await quietly(async () => {
669 const at = await $.clock.now()
670 const usage = usageOf(e.usage)
671 if (e.agentId !== undefined) {
672 push({ kind: 'handedBack', agentId: e.agentId, reason: e.reason, report: fullText(e.answer, TEXT_MAX), usage, at })
673 } else push({ kind: 'turnEnded', usage, at })
674 })
675 return next(e)
676 }).catch(($, e, next) => next(e))
677
678 on('classic.PermissionRequest', async ($, e, next) => {
679 await quietly(async () => {
680 // A question or a plan approval already moved and narrated the agent when its tool call began.
681 if (WAITING_TOOLS.has(e.tool_name)) return
682 push({ kind: 'waiting', agentId: e.agent_id ?? null, tool: e.tool_name, at: await $.clock.now() })
683 })
684 return next(e)
685 }).catch(($, e, next) => next(e))
686
687 on('command.run', { command: 'office' }, async ($, e) => {
688 // `/office settings` shows them, `/office set <name> <value>` changes one; `/office` alone shows or hides the pane.
689 const [verb = '', ...rest] = e.args.trim().split(/\s+/)
690 if (verb.toLowerCase() === 'settings') return { text: [...settingLines(options), SETTINGS_HELP].join('\n') }
691 if (verb.toLowerCase() === 'set') {
692 const request = parseSet(rest.join(' '))
693 return { text: 'error' in request ? request.error : await changeSetting($, request.setting, request.value) }
694 }
695 if (verb !== '') return { text: USAGE }
696 const panes = await $.ui.panes()
697 if (panes.some(pane => pane.id === PANE)) {
698 await $.ui.close({ id: PANE })
699 return { text: 'Office closed.' }
700 }
701 await openPane($, office)
702 return { text: 'Office opened.' }
703 })
704
705 // What this plugin's probes (a surface module inside the pane) post: only four plain fields are kept.
706 on('ui.message', async ($, e, next) => {
707 if (e.element !== PROBE_TOP && e.element !== PROBE_BOTTOM) return next(e)
708 if (office.isDebug) {
709 const d = typeof e.data === 'object' && e.data !== null ? (e.data as Record<string, unknown>) : {}
710 note('probe', {
711 element: e.element,
712 ...(typeof d.kind === 'string' ? { msg: d.kind.slice(0, 32) } : {}), // not `kind`: that is the line's own
713 ...(typeof d.where === 'string' ? { where: d.where.slice(0, 32) } : {}),
714 ...(typeof d.columns === 'number' ? { columns: d.columns } : {}),
715 ...(typeof d.rows === 'number' ? { rows: d.rows } : {}),
716 })
717 }
718 return {}
719 }).catch(($, e, next) => next(e))
720
721 registerPane(on, { isDebug: office.isDebug, options })
722}
723hooks/debuglog.ts 35 lines1// An opt-in log of what the office does, kept in memory as JSON lines and written to a file by the flush.
2// Off by default: every function below is a boolean check and nothing more until `debugOn(true)`.
3export const LOG_MAX = 3000
4
5let isOn = false
6let lines: string[] = []
7let isDirty = false
8
9export function debugOn(enabled: boolean): void {
10 isOn = enabled
11}
12
13// Values are plain numbers, booleans and short strings: agent ids, event kinds, tool names, never text of the work.
14export function note(kind: string, data: Record<string, unknown> = {}, at?: number): void {
15 if (!isOn) return
16 lines.push(JSON.stringify({ t: at ?? Date.now(), kind, ...data }))
17 if (lines.length > LOG_MAX) lines = lines.slice(lines.length - LOG_MAX)
18 isDirty = true
19}
20
21export function logText(): string {
22 return lines.length === 0 ? '' : `${lines.join('\n')}\n`
23}
24
25export function takeDirty(): boolean {
26 const was = isDirty
27 isDirty = false
28 return was
29}
30
31export function clearLog(): void {
32 lines = []
33 isDirty = false
34}
35hooks/model.ts 634 lines1import type { Agent, Carry, OfficeEvent, Outcome, Point, Scene, StationId, Usage, Walk } from '../types'
2import { allBackLine, narrate } from './narrate'
3import { COORDINATOR, asName, roleFor } from './roles'
4import { lookFor } from './sprites'
5import {
6 EXCERPT,
7 WAITING_TOOLS,
8 WIDTH,
9 clamp,
10 doorOf,
11 fullText,
12 pathLength,
13 pointAlong,
14 route,
15 slotPoint,
16 stationFor,
17 toCorridor,
18} from './stations'
19
20export const MAIN = 'main'
21export const TICKER_MAX = 8
22export const GONE_KEEP = 50
23export const FULL_KEEP = 10
24export const LINGER_MS = 8_000
25export const IDLE_MS = 600_000
26export const BRIEFING_MAX_MS = 60_000
27export const WALK_SPEED = 70
28
29type Ev<K extends OfficeEvent['kind']> = Extract<OfficeEvent, { kind: K }>
30type Stop = { point: Point; door: Point }
31
32export function emptyScene(): Scene {
33 const main: Agent = {
34 id: MAIN,
35 parentId: null,
36 type: 'main',
37 role: COORDINATOR.title,
38 name: null,
39 label: 'Main',
40 description: '',
41 brief: '',
42 report: '',
43 outcome: null,
44 usage: null,
45 isTeammate: false,
46 isBackground: false,
47 phase: 'idle',
48 station: 'office',
49 slot: 0,
50 desk: -1,
51 pos: slotPoint('office', 0),
52 walk: null,
53 activity: null,
54 lastErrorAt: null,
55 lastEventAt: 0,
56 arrivedAt: 0,
57 doneAt: null,
58 goneAt: null,
59 carry: null,
60 look: lookFor('main', MAIN),
61 }
62 return { agents: { [MAIN]: main }, order: [MAIN], ticker: [], todos: null, briefing: null, job: null }
63}
64
65// Fields added to an agent since the first release, with what an agent saved without them stands for. Session
66// state outlives a hot reload of the mod, so a scene saved by an older version can meet this code.
67const AGENT_DEFAULTS = (agent: Agent): Partial<Agent> => ({
68 role: roleFor(agent.type).title,
69 name: null,
70 brief: '',
71 report: '',
72 outcome: null,
73 // Nothing says its boss waits on it, so it never makes its boss look busy.
74 isBackground: true,
75 carry: null,
76 usage: null,
77 doneAt: null,
78})
79const AGENT_KEYS = Object.keys(AGENT_DEFAULTS({ type: MAIN } as Agent)) as (keyof Agent)[]
80
81// The scene as this version reads it. The same object comes back when nothing is missing, so a scene that is
82// already whole is never rewritten (a write would redraw the pane).
83export function restore(scene: Scene): Scene {
84 const isWhole = (agent: Agent): boolean => AGENT_KEYS.every(key => key in agent)
85 const hasJob = 'job' in scene
86 if (hasJob && Object.values(scene.agents).every(isWhole)) return scene
87 const agents: Record<string, Agent> = {}
88 for (const [id, agent] of Object.entries(scene.agents)) {
89 agents[id] = isWhole(agent) ? agent : ({ ...AGENT_DEFAULTS(agent), ...agent } as Agent)
90 }
91 return { ...scene, agents, job: hasJob ? scene.job : null }
92}
93
94export function isWalkingAt(agent: Agent, at: number): boolean {
95 return agent.walk !== null && at < agent.walk.startedAt + agent.walk.durationMs
96}
97
98export function positionAt(agent: Agent, at: number): Point {
99 if (agent.walk === null || !isWalkingAt(agent, at)) return agent.pos
100 return pointAlong(agent.walk.points, (at - agent.walk.startedAt) / agent.walk.durationMs)
101}
102
103export function homeOf(agent: Agent): StationId {
104 return agent.desk < 0 ? 'office' : 'desk'
105}
106
107const put = (scene: Scene, agent: Agent): Scene => ({ ...scene, agents: { ...scene.agents, [agent.id]: agent } })
108
109const addAgent = (scene: Scene, agent: Agent): Scene => ({ ...put(scene, agent), order: [...scene.order, agent.id] })
110
111// A routine line replaces the same agent's last routine line, so a few busy helpers cannot push the story
112// (who hired whom, who reported back, who needs you) out of the feed within seconds.
113function withLine(scene: Scene, at: number, text: string | null, routineOf: string | null = null): Scene {
114 if (text === null) return scene
115 const kept = routineOf === null ? scene.ticker : scene.ticker.filter(line => line.routineOf !== routineOf)
116 return { ...scene, ticker: [...kept, { at, text, routineOf }].slice(-TICKER_MAX) }
117}
118
119// Tool calls that are part of the story rather than routine work: a message to another agent, and a wait on you.
120const isMilestone = (tool: string): boolean => tool === 'SendMessage' || WAITING_TOOLS.has(tool)
121
122function freeSlot(scene: Scene, station: StationId, selfId: string): number {
123 const taken = new Set(
124 Object.values(scene.agents)
125 .filter(a => a.id !== selfId && a.phase !== 'gone' && a.station === station)
126 .map(a => a.slot),
127 )
128 let slot = 0
129 while (taken.has(slot)) slot += 1
130 return slot
131}
132
133const walkMs = (length: number): number => clamp(Math.round((length / WALK_SPEED) * 1000), 700, 7000)
134
135const isNear = (a: Point, b: Point): boolean => Math.hypot(a.x - b.x, a.y - b.y) < 0.5
136
137// Every walk drops whatever the agent was carrying, unless `item` says it carries something this time: it is
138// handed over when the walk reaches the first stop in `via`, the agent it is walking to.
139function moveTo(
140 scene: Scene,
141 agent: Agent,
142 target: StationId,
143 at: number,
144 via: readonly Stop[] = [],
145 item: Carry['item'] | null = null,
146): Agent {
147 const station: StationId = target === 'desk' && agent.desk < 0 ? 'office' : target
148 if (via.length === 0 && station === agent.station) return agent
149 const slot =
150 station === agent.station
151 ? agent.slot
152 : station === 'desk'
153 ? agent.desk
154 : station === 'office'
155 ? 0
156 : freeSlot(scene, station, agent.id)
157 const dest = slotPoint(station, slot)
158 const current = agent.walk !== null && isWalkingAt(agent, at) ? agent.walk : null
159 // Sent back to where it stood before its walk began, it never left.
160 if (current !== null && via.length === 0 && at <= current.startedAt && isNear(current.points[0] as Point, dest)) {
161 return { ...agent, station, slot, pos: dest, walk: null, carry: null }
162 }
163 // A walk that changes course first gets back to the corridor along the path it is on.
164 const rejoin = current === null ? [] : toCorridor(current.points, (at - current.startedAt) / current.durationMs)
165 const lead = rejoin.length > 0 ? rejoin : [positionAt(agent, at)]
166 const start = lead[lead.length - 1] as Point
167 const stops: Stop[] = [
168 { point: start, door: current !== null ? start : doorOf(agent.station, agent.slot) },
169 ...via,
170 { point: dest, door: doorOf(station, slot) },
171 ]
172 let points: Point[] = lead
173 let handover = 0
174 for (let i = 1; i < stops.length; i++) {
175 const a = stops[i - 1] as Stop
176 const b = stops[i] as Stop
177 points = points.concat(route(a.point, a.door, b.point, b.door).slice(1))
178 if (i === 1) handover = pathLength(points)
179 }
180 const length = pathLength(points)
181 const walk: Walk | null = length < 0.5 ? null : { points, startedAt: at, durationMs: walkMs(length) }
182 const carry: Carry | null =
183 item === null || walk === null || via.length === 0
184 ? null
185 : { item, until: at + Math.round((walk.durationMs * handover) / length) }
186 return { ...agent, station, slot, pos: dest, walk, carry }
187}
188
189function beside(agent: Agent): Stop {
190 return {
191 point: { x: clamp(agent.pos.x + 9, 4, WIDTH - 4), y: agent.pos.y },
192 door: doorOf(agent.station, agent.slot),
193 }
194}
195
196// The first of a kind is plain "Researcher", the next "Researcher 2". Numbering goes on from the highest number
197// in the office, so a label is never handed out twice, even after old helpers are pruned from the model.
198function uniqueLabel(scene: Scene, base: string): string {
199 let highest = 0
200 for (const a of Object.values(scene.agents)) {
201 if (a.label === base) highest = Math.max(highest, 1)
202 else if (a.label.startsWith(`${base} `)) {
203 const n = Number(a.label.slice(base.length + 1))
204 if (Number.isInteger(n) && n > 1) highest = Math.max(highest, n)
205 }
206 }
207 return highest === 0 ? base : `${base} ${highest + 1}`
208}
209
210// What a helper is on the job for, in a few words: "Find the login code" reads as "login code". Short enough to
211// fit on a name tag.
212const TOPIC_MAX = 12
213const FILLER = /^(find|check|look|search|read|review|audit|investigate|explore|analy[sz]e|summari[sz]e|report|list|get|the|a|an|for|on|in|at|of|into|out|how|why|what|where|which|whether|if|and|to)$/i
214export function topicOf(description: string): string {
215 const words = description.split(/\s+/).filter(w => w !== '')
216 const keep = words.filter(w => !FILLER.test(w.replace(/[^A-Za-z]/g, '')))
217 const pool = (keep.length > 0 ? keep : words).map(w => w.toLowerCase())
218 // Whole words only: two if they fit, else the first, cut with an ellipsis if even that is too long.
219 const two = pool.slice(0, 2).join(' ')
220 if (Array.from(two).length <= TOPIC_MAX) return two
221 const first = pool[0] ?? ''
222 const chars = Array.from(first)
223 return chars.length <= TOPIC_MAX ? first : `${chars.slice(0, TOPIC_MAX - 1).join('')}…`
224}
225
226// An agent the engine named keeps its name. The first of a kind is its plain job title; a later one is told apart
227// by its job, "Hooks module" rather than "Researcher 2", when we know it. The job alone is the name: a tag has
228// room for about twelve characters before it runs into its neighbour's, and the details say what kind of agent it is.
229const labelFor = (scene: Scene, type: string, name: string | null, description = ''): string => {
230 if (name !== null && name !== '') return uniqueLabel(scene, asName(name))
231 const topic = topicOf(description)
232 const title = roleFor(type).title
233 const first = uniqueLabel(scene, title)
234 if (first === title || topic === '') return first
235 return uniqueLabel(scene, `${topic[0]?.toUpperCase() ?? ''}${topic.slice(1)}`)
236}
237
238function nextDesk(scene: Scene): number {
239 const used = new Set(
240 Object.values(scene.agents)
241 .filter(a => a.phase !== 'gone' && a.desk >= 0)
242 .map(a => a.desk),
243 )
244 let desk = 0
245 while (used.has(desk)) desk += 1
246 return desk
247}
248
249// A contractor (an agent the office never saw hired) is taken to work in the background: nothing says its boss
250// is waiting on it, so it never makes its boss look busy.
251function arrive(scene: Scene, id: string, type: string, label: string, at: number): Agent {
252 return {
253 id,
254 parentId: MAIN,
255 type,
256 role: roleFor(type).title,
257 name: null,
258 label,
259 description: '',
260 brief: '',
261 report: '',
262 outcome: null,
263 usage: null,
264 isTeammate: false,
265 isBackground: true,
266 phase: 'arriving',
267 station: 'elevator',
268 slot: 0,
269 desk: nextDesk(scene),
270 pos: slotPoint('elevator', 0),
271 walk: null,
272 activity: null,
273 lastErrorAt: null,
274 lastEventAt: at,
275 arrivedAt: at,
276 doneAt: null,
277 goneAt: null,
278 carry: null,
279 look: lookFor(type, id),
280 }
281}
282
283const isOut = (agent: Agent): boolean =>
284 agent.phase === 'arriving' || agent.phase === 'briefing' || agent.phase === 'working' || agent.phase === 'waiting'
285
286// The helpers `bossId` is waiting on: hired in the foreground (the boss's call to hire them only returns with
287// their report) and still out on the job, in the order they were hired. A teammate is a standing colleague
288// rather than an errand, so its boss never waits on it.
289export function waitingOn(scene: Scene, bossId: string): Agent[] {
290 const out: Agent[] = []
291 for (const id of scene.order) {
292 const a = scene.agents[id]
293 if (a !== undefined && a.parentId === bossId && !a.isBackground && !a.isTeammate && isOut(a)) out.push(a)
294 }
295 return out
296}
297
298// A boss with nothing in hand, waiting for the reports of the helpers it hired, is coordinating rather than
299// thinking. A boss that is using a tool, waiting on you, resting or gone is doing that instead.
300export function isCoordinating(scene: Scene, agent: Agent): boolean {
301 if (agent.activity !== null || agent.phase === 'gone' || agent.phase === 'idle' || agent.phase === 'waiting') return false
302 return waitingOn(scene, agent.id).length > 0
303}
304
305function endBriefing(scene: Scene, agent: Agent, at: number, t: number): Scene {
306 const stillBriefing = Object.values(scene.agents).some(a => a.phase === 'briefing')
307 let out: Scene = stillBriefing ? scene : { ...scene, briefing: null }
308 const parent = agent.parentId === null ? undefined : out.agents[agent.parentId]
309 if (parent !== undefined && parent.station === 'meeting' && parent.activity === null && parent.phase !== 'gone') {
310 out = put(out, { ...moveTo(out, parent, homeOf(parent), t), lastEventAt: at })
311 }
312 return out
313}
314
315// The agent walks to the meeting room to be briefed, its boss joins it there unless busy, and the whiteboard
316// shows the job.
317function brief(scene: Scene, agent: Agent, ev: Ev<'spawned'>, t: number): Scene {
318 let s = put(scene, { ...moveTo(scene, agent, 'meeting', t), phase: 'briefing' })
319 const parent = s.agents[ev.parentId]
320 if (parent !== undefined && parent.activity === null && parent.phase !== 'gone') {
321 s = put(s, { ...moveTo(s, parent, 'meeting', t), phase: 'working', lastEventAt: ev.at })
322 }
323 return { ...s, briefing: ev.description }
324}
325
326// A helper back for more work after it handed in its report. One still on its way out turns round where it is;
327// one that has ridden away steps out of the elevator again.
328function comeBack(scene: Scene, agent: Agent, t: number): Partial<Agent> {
329 const hasLeft = agent.goneAt === null || t >= agent.goneAt
330 return { ...(hasLeft ? { station: 'elevator' as const, slot: 0, pos: slotPoint('elevator', 0), walk: null } : {}), desk: nextDesk(scene) }
331}
332
333// A called-back agent comes back if it had left, starts a new stint and is briefed again. The message it is
334// called back with is its new brief; with none, the old brief still stands.
335function callBack(scene: Scene, agent: Agent, ev: Ev<'spawned'>, t: number): Scene {
336 const isBack = agent.phase === 'gone'
337 const returning: Agent = {
338 ...agent,
339 ...(isBack ? comeBack(scene, agent, t) : {}),
340 parentId: ev.parentId,
341 description: ev.description,
342 brief: ev.brief === '' ? agent.brief : ev.brief,
343 isBackground: ev.isBackground,
344 outcome: null,
345 doneAt: null,
346 goneAt: null,
347 carry: null,
348 activity: null,
349 arrivedAt: ev.at,
350 lastEventAt: ev.at,
351 }
352 return brief(scene, returning, ev, t)
353}
354
355function spawned(scene: Scene, ev: Ev<'spawned'>, t: number): Scene {
356 const existing = scene.agents[ev.id]
357 let s = scene
358 const hire = {
359 parentId: ev.parentId,
360 description: ev.description,
361 brief: ev.brief,
362 name: ev.name,
363 isTeammate: ev.isTeammate,
364 isBackground: ev.isBackground,
365 }
366 if (existing === undefined) {
367 const fresh = { ...arrive(s, ev.id, ev.type, labelFor(s, ev.type, ev.name, ev.description), ev.at), ...hire }
368 s = brief(addAgent(s, fresh), fresh, ev, t)
369 } else if (ev.isResume) {
370 s = callBack(s, existing, ev, t)
371 } else {
372 const label = existing.type === 'contractor' ? labelFor(s, ev.type, ev.name, ev.description) : existing.label
373 s = put(s, {
374 ...existing,
375 ...hire,
376 type: ev.type,
377 role: roleFor(ev.type).title,
378 label,
379 look: lookFor(ev.type, ev.id),
380 lastEventAt: ev.at,
381 })
382 }
383 return withLine(s, ev.at, narrate(s, ev))
384}
385
386// Messages are addressed by the name the engine knows an agent by, by its id, or (for "main") by its label.
387function findByName(scene: Scene, name: string, selfId: string): Agent | undefined {
388 const wanted = name.toLowerCase()
389 return Object.values(scene.agents).find(
390 a =>
391 a.id !== selfId &&
392 a.phase !== 'gone' &&
393 (a.name?.toLowerCase() === wanted || a.label.toLowerCase() === wanted || a.id === name),
394 )
395}
396
397const EDITING: ReadonlySet<string> = new Set(['Edit', 'Write', 'NotebookEdit'])
398
399function toolStarted(scene: Scene, ev: Ev<'toolStarted'>, t: number): Scene {
400 let s = scene
401 let agent = s.agents[ev.agentId]
402 if (agent === undefined) {
403 agent = arrive(s, ev.agentId, 'contractor', uniqueLabel(s, 'Contractor'), ev.at)
404 s = addAgent(s, agent)
405 } else if (agent.phase === 'gone') {
406 agent = {
407 ...agent,
408 ...comeBack(s, agent, t),
409 phase: 'arriving',
410 goneAt: null,
411 doneAt: null,
412 outcome: null,
413 carry: null,
414 arrivedAt: ev.at,
415 }
416 }
417 const wasBriefing = agent.phase === 'briefing'
418 let moved: Agent
419 if (ev.tool === 'SendMessage') {
420 const recipient = findByName(s, ev.target, agent.id)
421 moved =
422 recipient !== undefined
423 ? moveTo(s, agent, agent.station, t, [beside(recipient)], 'message')
424 : moveTo(s, agent, 'meeting', t)
425 } else {
426 moved = moveTo(s, agent, stationFor(ev.tool), t)
427 }
428 s = put(s, {
429 ...moved,
430 phase: WAITING_TOOLS.has(ev.tool) ? 'waiting' : 'working',
431 activity: { tool: ev.tool, target: ev.target, detail: ev.detail, callId: ev.callId, since: ev.at },
432 lastEventAt: ev.at,
433 })
434 if (wasBriefing) s = endBriefing(s, agent, ev.at, t)
435 // The coordinator is meant to hire helpers for edits; the recap says how many it made itself.
436 if (agent.id === MAIN && EDITING.has(ev.tool) && s.job !== null) s = { ...s, job: { ...s.job, mainEdits: (s.job.mainEdits ?? 0) + 1 } }
437 return withLine(s, ev.at, narrate(s, ev), isMilestone(ev.tool) ? null : agent.id)
438}
439
440function toolEnded(scene: Scene, ev: Ev<'toolEnded'>, t: number): Scene {
441 const agent = scene.agents[ev.agentId]
442 if (agent === undefined || agent.phase === 'gone') return scene
443 const isCurrent = agent.activity?.callId === ev.callId
444 let next: Agent = {
445 ...agent,
446 activity: isCurrent ? null : agent.activity,
447 lastErrorAt: ev.isError ? ev.at : agent.lastErrorAt,
448 lastEventAt: ev.at,
449 }
450 if (isCurrent && agent.phase === 'waiting') next = { ...moveTo(scene, next, homeOf(next), t), phase: 'working' }
451 return withLine(put(scene, next), ev.at, narrate(scene, ev))
452}
453
454function latestUser(scene: Scene, tool: string): string {
455 let best: Agent | undefined
456 for (const a of Object.values(scene.agents)) {
457 if (a.phase === 'gone' || a.activity?.tool !== tool) continue
458 if (best === undefined || a.activity.since > (best.activity?.since ?? -1)) best = a
459 }
460 return best?.id ?? MAIN
461}
462
463function waiting(scene: Scene, ev: Ev<'waiting'>, t: number): Scene {
464 const id = ev.agentId !== null && scene.agents[ev.agentId] !== undefined ? ev.agentId : latestUser(scene, ev.tool)
465 const agent = scene.agents[id]
466 if (agent === undefined || agent.phase === 'gone') return scene
467 const s = put(scene, { ...moveTo(scene, agent, 'reception', t), phase: 'waiting', lastEventAt: ev.at })
468 return withLine(s, ev.at, narrate(s, { ...ev, agentId: id }))
469}
470
471// A message from you starts a new job; a turn that carries on without one reopens the job it belongs to.
472function turnStarted(scene: Scene, ev: Ev<'turnStarted'>, t: number): Scene {
473 const main = scene.agents[MAIN]
474 if (main === undefined) return scene
475 const job =
476 ev.isContinuation && scene.job !== null
477 ? { ...scene.job, endedAt: null }
478 : { startedAt: ev.at, endedAt: null, task: ev.task, mainUsage: null, mainEdits: 0 }
479 const s = put({ ...scene, job }, { ...moveTo(scene, main, 'office', t), phase: 'working', lastEventAt: ev.at })
480 return withLine(s, ev.at, narrate(s, ev))
481}
482
483// Main's turn is over: it rests where it stands until the next message. No walk; the sweep takes it
484// home after a short while and to the break room after a long one.
485// A teammate or a called-back helper works more than one turn, and Main works one per message: their costs add up.
486export function addUsage(sum: Usage | null, more: Usage | null): Usage | null {
487 if (more === null) return sum
488 if (sum === null) return more
489 return { tokens: sum.tokens + more.tokens, reused: sum.reused + more.reused, model: more.model }
490}
491
492function turnEnded(scene: Scene, ev: Ev<'turnEnded'>): Scene {
493 const main = scene.agents[MAIN]
494 if (main === undefined) return scene
495 const job = scene.job === null ? null : { ...scene.job, endedAt: ev.at, mainUsage: addUsage(scene.job.mainUsage, ev.usage) }
496 const s = put({ ...scene, job }, { ...main, phase: 'idle', activity: null, usage: addUsage(main.usage, ev.usage), lastEventAt: ev.at })
497 return withLine(s, ev.at, narrate(s, ev))
498}
499
500function prune(scene: Scene): Scene {
501 const gone = scene.order.filter(id => scene.agents[id]?.phase === 'gone')
502 if (gone.length <= GONE_KEEP) return scene
503 const drop = new Set(gone.slice(0, gone.length - GONE_KEEP))
504 const agents = { ...scene.agents }
505 for (const id of drop) delete agents[id]
506 return { ...scene, agents, order: scene.order.filter(id => !drop.has(id)) }
507}
508
509// Only the most recently finished helpers keep their whole brief and report; older ones keep as much as the
510// one-line excerpt shows. That bounds the scene, which is written to state on every change.
511function trimTexts(scene: Scene): Scene {
512 const isLong = (a: Agent): boolean => a.brief.length > EXCERPT || a.report.length > EXCERPT
513 const old = Object.values(scene.agents)
514 .filter(a => a.phase === 'gone')
515 .sort((a, b) => (b.goneAt ?? 0) - (a.goneAt ?? 0))
516 .slice(FULL_KEEP)
517 .filter(isLong)
518 if (old.length === 0) return scene
519 const agents = { ...scene.agents }
520 for (const a of old) agents[a.id] = { ...a, brief: fullText(a.brief, EXCERPT), report: fullText(a.report, EXCERPT) }
521 return { ...scene, agents }
522}
523
524const OUTCOMES: Readonly<Record<Ev<'handedBack'>['reason'], Outcome>> = {
525 answer: 'reported',
526 aborted: 'stopped',
527 refusal: 'failed',
528 error: 'failed',
529}
530
531// The helper carries its report to its boss, then leaves by the elevator (a teammate goes for a break instead).
532// When it was the last report its boss was waiting for, the feed says so: that is when the boss takes over again.
533function handedBack(scene: Scene, ev: Ev<'handedBack'>, t: number): Scene {
534 const agent = scene.agents[ev.agentId]
535 if (agent === undefined || agent.id === MAIN || agent.phase === 'gone') return scene
536 const parent = agent.parentId === null ? undefined : scene.agents[agent.parentId]
537 const isParentHere = parent !== undefined && parent.phase !== 'gone'
538 const via = isParentHere ? [beside(parent)] : []
539 const outcome = OUTCOMES[ev.reason]
540 const item = outcome === 'stopped' ? null : 'report'
541 let next: Agent
542 if (agent.isTeammate) {
543 next = { ...moveTo(scene, agent, 'breakroom', t, via, item), phase: 'idle' }
544 } else {
545 const moved = moveTo(scene, agent, 'elevator', t, via, item)
546 next = { ...moved, phase: 'gone', goneAt: t + (moved.walk?.durationMs ?? 0) }
547 }
548 const awaitedBy = isParentHere && waitingOn(scene, parent.id).some(a => a.id === agent.id) ? parent : undefined
549 let s = put(scene, {
550 ...next,
551 activity: null,
552 report: ev.report,
553 outcome,
554 usage: addUsage(agent.usage, ev.usage),
555 doneAt: ev.at,
556 lastEventAt: ev.at,
557 })
558 if (agent.phase === 'briefing') s = endBriefing(s, agent, ev.at, t)
559 s = trimTexts(prune(s))
560 s = withLine(s, ev.at, narrate(s, ev))
561 if (awaitedBy !== undefined && waitingOn(s, awaitedBy.id).length === 0) s = withLine(s, ev.at, allBackLine(awaitedBy.label))
562 return s
563}
564
565// A boss waiting on its helpers is at work however long they take, so the sweep may walk it home but never
566// sends it to the break room.
567function sweepTarget(agent: Agent, now: number, isWaitingOnTeam: boolean): StationId | null {
568 // An agent waiting on you stays at reception until you answer, however long that takes.
569 if (agent.activity !== null || agent.phase === 'gone' || agent.phase === 'waiting') return null
570 const quiet = now - agent.lastEventAt
571 // A briefing normally ends with the agent's first tool; one that never comes must not hold the room forever.
572 if (agent.phase === 'briefing') return quiet >= BRIEFING_MAX_MS ? homeOf(agent) : null
573 if (agent.phase === 'idle') {
574 // Resting in the break room is the end of the road, and an office where nothing has happened yet
575 // (Main's clock still reads zero) has nobody to send for coffee.
576 if (agent.station === 'breakroom' || agent.lastEventAt === 0) return null
577 if (quiet >= IDLE_MS) return 'breakroom'
578 return quiet >= LINGER_MS && agent.station !== homeOf(agent) ? homeOf(agent) : null
579 }
580 if (quiet >= IDLE_MS && !isWaitingOnTeam) return 'breakroom'
581 if (quiet >= LINGER_MS && agent.station !== homeOf(agent)) return homeOf(agent)
582 return null
583}
584
585export function needsSweep(scene: Scene, now: number): boolean {
586 return Object.values(scene.agents).some(a => sweepTarget(a, now, isCoordinating(scene, a)) !== null)
587}
588
589function tick(scene: Scene, at: number, t: number): Scene {
590 let s = scene
591 for (const id of scene.order) {
592 const agent = s.agents[id]
593 if (agent === undefined) continue
594 const target = sweepTarget(agent, at, isCoordinating(s, agent))
595 if (target === null) continue
596 s = put(s, { ...moveTo(s, agent, target, t), phase: target === 'breakroom' || agent.phase === 'idle' ? 'idle' : 'working' })
597 if (agent.phase === 'briefing') s = endBriefing(s, agent, at, t)
598 }
599 return s
600}
601
602export function reduce(scene: Scene, ev: OfficeEvent): Scene {
603 return reduceAt(scene, ev, ev.at)
604}
605
606// The event as the picture plays it: `shownAt` is the first moment the picture can show it, and the walks it
607// starts begin then rather than at the event's own time. Begun at the event's time, a walk would already be part
608// way along when it first appeared (the wait for the next flush, and the time the picture takes to appear), so the
609// walker would leap ahead at the start of every walk. What the office reports (the feed, the recap, the clocks)
610// keeps the event's own time.
611export function reduceAt(scene: Scene, ev: OfficeEvent, shownAt: number): Scene {
612 const t = Math.max(ev.at, shownAt)
613 switch (ev.kind) {
614 case 'spawned':
615 return spawned(scene, ev, t)
616 case 'toolStarted':
617 return toolStarted(scene, ev, t)
618 case 'toolEnded':
619 return toolEnded(scene, ev, t)
620 case 'waiting':
621 return waiting(scene, ev, t)
622 case 'turnStarted':
623 return turnStarted(scene, ev, t)
624 case 'turnEnded':
625 return turnEnded(scene, ev)
626 case 'handedBack':
627 return handedBack(scene, ev, t)
628 case 'todos':
629 return { ...scene, todos: { done: ev.done, open: ev.open } }
630 case 'tick':
631 return tick(scene, ev.at, t)
632 }
633}
634hooks/pane.tsx 364 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, On, PluginOptions } from 'claude-code'
3
4import type { JobRecord, PeerSession } from '../types'
5import { note } from './debuglog'
6import { emptyScene, restore } from './model'
7import { PEERS_SHOWN, officeOf, peerKey, peerRows, peersHeading } from './peers'
8import { LEAD_MS, STATUS_WORDS, agentDetails, altText, clockLabel, fitSize, isCut, objectiveLine, officeSource, orgRows, renderOffice, svgSize } from './render'
9import { historyLine, recapAlt, recapOf, recapRows, recapSummary, recapSvg, sessionLines, sessionTotals } from './recap'
10import { CANNOT, MANY_COPIES, SETTINGS, configKeyOf, currentValues, meaningOf, replyAfterSet, setReply } from './settings'
11import type { Setting } from './settings'
12import { PANE, PROBE_BOTTOM, PROBE_TOP } from './state'
13import { STATIONS, STATION_ORDER } from './stations'
14
15const ORG_MAX = 14
16const sceneAtom = atom({ plugin: 'pixel-office', key: 'scene' } as const, emptyScene())
17const legendAtom = atom({ plugin: 'pixel-office', key: 'legendOpen' } as const, false)
18const selectedAtom = atom({ plugin: 'pixel-office', key: 'selected' } as const, null as string | null)
19const clockAtom = atom({ plugin: 'pixel-office', key: 'clock' } as const, 0)
20const expandedAtom = atom({ plugin: 'pixel-office', key: 'expanded' } as const, null as 'brief' | 'report' | null)
21const jobOpenAtom = atom({ plugin: 'pixel-office', key: 'jobOpen' } as const, false)
22const historyAtom = atom({ plugin: 'pixel-office', key: 'history' } as const, [] as JobRecord[])
23const sessionAtom = atom({ plugin: 'pixel-office', key: 'session' } as const, [] as JobRecord[])
24const othersAtom = atom({ plugin: 'pixel-office', key: 'others' } as const, [] as PeerSession[])
25const lookingAtom = atom({ plugin: 'pixel-office', key: 'looking' } as const, null as string | null)
26const lookedAtom = atom({ plugin: 'pixel-office', key: 'looked' } as const, null as PeerSession | null)
27const settingsOpenAtom = atom({ plugin: 'pixel-office', key: 'settingsOpen' } as const, false)
28const settingsNoteAtom = atom({ plugin: 'pixel-office', key: 'settingsNote' } as const, '')
29const LINK = '#378add'
30// The details lines a whole text belongs under.
31const PARTS = [
32 { part: 'brief', line: 'Brief: ' },
33 { part: 'report', line: 'Report: ' },
34] as const
35// Coordinating wears the meeting room's teal: a boss waiting on its helpers, not on you.
36const STATUS_COLOR = { working: 'green', coordinating: STATIONS.meeting.color, waiting: 'yellow', idle: 'gray', done: 'gray' } as const
37
38// Changes one setting the way the `/config` menu does, and says how it went. pane.tsx and register.tsx each have
39// this: the engine follows `$` only into a function of the same file.
40async function changeSetting($: EngineInterface, setting: Setting, value: string): Promise<string> {
41 let keys: string[] = []
42 try {
43 keys = (await $.config.list()).map(row => row.key)
44 } catch {
45 // An engine without the listing: the key is the plain one.
46 }
47 const key = configKeyOf(keys, setting.field)
48 if (key === null) return setReply(setting, value, MANY_COPIES)
49 let deny: string | undefined
50 try {
51 deny = (await $.config.set({ key, value })).deny
52 } catch {
53 return setReply(setting, value, CANNOT)
54 }
55 let stored: unknown
56 try {
57 stored = (await $.config.list()).find(row => row.key === key)?.value
58 } catch {
59 // Not listed: the change is taken at its word.
60 }
61 return replyAfterSet(setting, value, deny, stored)
62}
63
64export function registerPane(on: On, { isDebug, options = {} }: { isDebug?: boolean; options?: PluginOptions } = {}): void {
65 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
66 const scene = restore(await read($, sceneAtom))
67 const isLegendOpen = await read($, legendAtom)
68 const expanded = await read($, expandedAtom)
69 const isJobOpen = await read($, jobOpenAtom)
70 const isSettingsOpen = await read($, settingsOpenAtom)
71 const settingsNote = await read($, settingsNoteAtom)
72 let configRows: Array<{ key: string; value: unknown }> = []
73 if (isSettingsOpen) {
74 try {
75 configRows = await $.config.list()
76 } catch {
77 // An engine without the listing: the options the office loaded with.
78 }
79 }
80 const values = currentValues(configRows, options)
81 const history = await read($, historyAtom)
82 const session = await read($, sessionAtom)
83 const selected = await read($, selectedAtom)
84 // Reading the clock atom subscribes the pane to it: each write from the flush timer redraws the pane.
85 const now = Math.max(await $.clock.now(), await read($, clockAtom))
86 const rows = orgRows(scene, now)
87 const shown = rows.slice(0, ORG_MAX)
88 const hidden = rows.length - shown.length
89 const details = selected === null ? [] : agentDetails(scene, selected, now)
90 const recap = recapOf(scene, now)
91 // The other sessions on this computer. A row cannot take you to that session, but pressing it shows that
92 // session's office in the picture, until it is pressed again or Back is.
93 const others = await read($, othersAtom)
94 const peers = peerRows(others.slice(0, PEERS_SHOWN), now)
95 const peersHidden = others.length - peers.length
96 const looking = await read($, lookingAtom)
97 const lookedAt = await read($, lookedAtom)
98 const looked = looking !== null && lookedAt !== null && peerKey(lookedAt) === looking ? lookedAt : null
99 const lookIn = async (key: string): Promise<void> => {
100 const next = looking === key ? null : key
101 await update($, lookingAtom, () => next)
102 await update($, lookedAtom, () => (next === null ? null : (others.find(p => peerKey(p) === next) ?? null)))
103 }
104
105 if (e.surface === 'terminal') {
106 const { Box, Text } = $.ui.resolve(e)
107 return (
108 <Box flexDirection="column">
109 <Text dimColor>Open this session in the Claude desktop app to see the pixel office. /office settings lists its settings.</Text>
110 {shown.map(row => {
111 const objective = objectiveLine(scene, row.id, row.depth, e.props.bodyColumns)
112 return (
113 <Box key={`row-${row.id}`} flexDirection="column">
114 <Text wrap="truncate-end">
115 {' '.repeat(row.depth)}
116 {row.label}: {STATUS_WORDS[row.status]}, {row.now}
117 </Text>
118 {objective !== '' && <Text dimColor>{objective}</Text>}
119 </Box>
120 )
121 })}
122 {scene.ticker.map(line => (
123 <Text dimColor>
124 {clockLabel(line.at)} {line.text}
125 </Text>
126 ))}
127 {recap !== null && recapSummary(recap).map(line => <Text>{line}</Text>)}
128 {recap !== null && sessionLines(sessionTotals(session, recap)).map(line => <Text>{line}</Text>)}
129 {others.length > 0 && <Text bold>{peersHeading(others)}</Text>}
130 {peers.map(row => (
131 <Box key={`peer-${row.key}`} flexDirection="column">
132 <Text wrap="truncate-end"> {row.line}</Text>
133 {row.job !== '' && <Text dimColor wrap="truncate-end"> {row.job}</Text>}
134 </Box>
135 ))}
136 {peersHidden > 0 && <Text dimColor> +{peersHidden} more</Text>}
137 </Box>
138 )
139 }
140
141 const { Box, Text, Button, Svg, Markdown, Client } = $.ui.resolve(e)
142 const chosen = selected === null ? undefined : scene.agents[selected]
143 const orgWidth = Math.max(24, Math.min(40, Math.floor(e.props.bodyColumns / 2)))
144 if (isDebug === true) {
145 note(
146 'render',
147 {
148 scroll: e.props.scroll?.offset ?? 0,
149 columns: e.props.bodyColumns,
150 selected: selected !== null,
151 jobOpen: isJobOpen,
152 legendOpen: isLegendOpen,
153 agents: Object.keys(scene.agents).length,
154 },
155 now,
156 )
157 }
158 // Drawn afresh at every render, as of now: the desktop starts the picture over whenever it draws the pane, even
159 // when its text is unchanged, so a picture kept from an earlier render would replay that moment.
160 // Another session's office is drawn by the same code from what its snapshot says: one picture, either way.
161 const lookedScene = looked === null ? null : officeOf(looked, now + LEAD_MS)
162 const officePicture = lookedScene === null ? officeSource(scene, now) : renderOffice(lookedScene, now + LEAD_MS)
163 const lookedName = looked === null ? '' : peerRows([looked], now)[0]?.line ?? ''
164 const size = fitSize(svgSize(officePicture), e.props.bodyColumns)
165 const recapPicture = isJobOpen && recap !== null ? recapSvg(recap) : undefined
166 return (
167 <Box flexDirection="column" gap={1}>
168 {isDebug === true && <Client key={PROBE_TOP} module="./probe.tsx" props={{ where: 'top' }} />}
169 {looked !== null && (
170 <Box key="looking" flexDirection="row" gap={2}>
171 <Text bold color={STATUS_COLOR[looked.status]} wrap="truncate-end">
172 Looking in on {lookedName}
173 </Text>
174 <Button key="back" label="Back to your office" onPress={() => lookIn(peerKey(looked))} />
175 </Box>
176 )}
177 <Svg
178 source={officePicture}
179 alt={lookedScene === null ? altText(scene) : `Another session's office. ${altText(lookedScene)}`}
180 {...size}
181 />
182 <Box flexDirection="row" gap={2}>
183 <Box key="ticker" flexDirection="column" flexGrow={1}>
184 <Text bold>What's happening</Text>
185 {scene.ticker.length === 0 && <Text dimColor>Quiet so far. Agents appear as they start working.</Text>}
186 {scene.ticker.map(line => (
187 <Text wrap="truncate-end">
188 {clockLabel(line.at)} {line.text}
189 </Text>
190 ))}
191 </Box>
192 <Box key="org" flexDirection="column" width={orgWidth}>
193 <Text bold>Who's doing what</Text>
194 {shown.map(row => {
195 const objective = objectiveLine(scene, row.id, row.depth, orgWidth)
196 return (
197 <Box key={`row-${row.id}`} flexDirection="column">
198 <Button
199 key={`agent-${row.id}`}
200 plain
201 onPress={async () => {
202 await update($, selectedAtom, current => (current === row.id ? null : row.id))
203 await update($, expandedAtom, () => null)
204 }}
205 >
206 <Text color={STATUS_COLOR[row.status]} dimColor={row.status === 'done'} wrap="truncate-end">
207 {' '.repeat(row.depth)}
208 {row.label} · {STATUS_WORDS[row.status]} · {row.now}
209 </Text>
210 </Button>
211 {objective !== '' && (
212 <Text color={row.status === 'done' ? 'gray' : undefined} dimColor>
213 {objective}
214 </Text>
215 )}
216 </Box>
217 )
218 })}
219 {hidden > 0 && <Text dimColor>+{hidden} more</Text>}
220 {details.length > 0 && (
221 <Box key="details" flexDirection="column" marginTop={1}>
222 {details.map(line => {
223 // A brief or a report the line cuts short can be read whole, under its line.
224 const found = PARTS.find(p => line.startsWith(p.line))
225 const whole = found === undefined || chosen === undefined ? '' : chosen[found.part]
226 if (found === undefined || !isCut(whole)) return <Text dimColor>{line}</Text>
227 const isOpen = expanded === found.part
228 return (
229 <Box key={`part-${found.part}`} flexDirection="column">
230 <Text dimColor>{line}</Text>
231 <Button
232 key={`read-${found.part}`}
233 plain
234 onPress={() => update($, expandedAtom, current => (current === found.part ? null : found.part))}
235 >
236 <Text color={LINK}>{isOpen ? `Hide the full ${found.part}` : `Read the full ${found.part}`}</Text>
237 </Button>
238 {isOpen && <Markdown key={`full-${found.part}`} text={whole} />}
239 </Box>
240 )
241 })}
242 </Box>
243 )}
244 </Box>
245 </Box>
246 {others.length > 0 && (
247 <Box key="peers" flexDirection="column">
248 <Text bold>{peersHeading(others)}</Text>
249 <Text dimColor>Press one to look in on its office.</Text>
250 {peers.map(row => (
251 <Box key={`peer-${row.key}`} flexDirection="column">
252 <Button key={`look-${row.key}`} plain onPress={() => lookIn(row.key)}>
253 <Text color={STATUS_COLOR[row.status]} dimColor={row.status === 'idle'} bold={row.key === looking} wrap="truncate-end">
254 {row.key === looking ? '▸ ' : ''}
255 {row.line}
256 </Text>
257 </Button>
258 {row.job !== '' && (
259 <Text dimColor wrap="truncate-end">
260 {row.job}
261 </Text>
262 )}
263 </Box>
264 ))}
265 {peersHidden > 0 && <Text dimColor>+{peersHidden} more</Text>}
266 </Box>
267 )}
268 <Box key="buttons" flexDirection="row" gap={2}>
269 <Button
270 key="legend"
271 label={isLegendOpen ? 'Hide legend' : 'Show legend'}
272 onPress={() => update($, legendAtom, isOpen => !isOpen)}
273 />
274 <Button
275 key="settings"
276 label={isSettingsOpen ? 'Hide settings' : 'Settings'}
277 onPress={async () => {
278 await update($, settingsOpenAtom, isOpen => !isOpen)
279 await update($, settingsNoteAtom, () => '')
280 }}
281 />
282 {recap !== null && (
283 <Button
284 key="job"
285 label={isJobOpen ? 'Hide this job' : 'Show this job'}
286 onPress={() => update($, jobOpenAtom, isOpen => !isOpen)}
287 />
288 )}
289 </Box>
290 {recapPicture !== undefined && recap !== null && (
291 <Box key="job-view" flexDirection="column">
292 {recapSummary(recap).map((line, i) => (
293 <Text bold={i === 0}>{line}</Text>
294 ))}
295 {sessionLines(sessionTotals(session, recap)).map(line => (
296 <Text>{line}</Text>
297 ))}
298 <Svg source={recapPicture} alt={recapAlt(recap)} {...svgSize(recapPicture)} />
299 {recapRows(recap).map(line => (
300 <Text dimColor>{line}</Text>
301 ))}
302 {history.length > 0 && (
303 <Box key="history" flexDirection="column" marginTop={1}>
304 <Text bold>Earlier jobs</Text>
305 {[...history].reverse().map(record => (
306 <Text dimColor wrap="truncate-end">
307 {historyLine(record)}
308 </Text>
309 ))}
310 </Box>
311 )}
312 </Box>
313 )}
314 {isSettingsOpen && (
315 <Box key="settings-list" flexDirection="column">
316 <Text bold>Settings</Text>
317 <Text dimColor>Press a value to switch to it. /config shows the same settings.</Text>
318 {SETTINGS.map(setting => {
319 const current = values[setting.field] ?? setting.fallback
320 return (
321 <Box key={`setting-${setting.field}`} flexDirection="column" marginTop={1}>
322 <Text>
323 {setting.title}: <Text bold>{current}</Text>
324 <Text dimColor>, {meaningOf(setting, current)}</Text>
325 </Text>
326 <Box flexDirection="row" gap={2}>
327 {setting.choices.map(choice => (
328 <Button
329 key={`set-${setting.field}-${choice.value}`}
330 plain
331 onPress={async () => {
332 // Said first: a change that takes loads the office again, and this press may not see the end of it.
333 await update($, settingsNoteAtom, () => setReply(setting, choice.value, undefined))
334 const said = await changeSetting($, setting, choice.value)
335 await update($, settingsNoteAtom, () => said)
336 }}
337 >
338 <Text color={choice.value === current ? undefined : LINK} bold={choice.value === current}>
339 {choice.value === current ? `● ${choice.value}` : `○ ${choice.value}`}
340 </Text>
341 </Button>
342 ))}
343 </Box>
344 </Box>
345 )
346 })}
347 {settingsNote !== '' && <Text color="yellow">{settingsNote}</Text>}
348 </Box>
349 )}
350 {isLegendOpen && (
351 <Box key="legend-list" flexDirection="column">
352 {STATION_ORDER.map(id => (
353 <Text color={STATIONS[id].color}>
354 ■ {STATIONS[id].name}: {STATIONS[id].tools}
355 </Text>
356 ))}
357 </Box>
358 )}
359 {isDebug === true && <Client key={PROBE_BOTTOM} module="./probe.tsx" props={{ where: 'bottom' }} />}
360 </Box>
361 )
362 })
363}
364hooks/peers.ts 429 lines1import type { Agent, Look, Phase, PeerAgent, PeerSession, PeerStatus, Scene, StationId } from '../types'
2import { MAIN, waitingOn } from './model'
3import { statusOf } from './render'
4import { isBuiltIn, roleFor } from './roles'
5import { HEIGHT, STATION_ORDER, WIDTH, gist, stationFor } from './stations'
6
7// The other sessions on this computer. Each running copy of the office, with `otherSessions` on, claims one slot
8// file in a shared folder, rewrites it with a small snapshot of its own office, and reads the other slots. A slot,
9// not a file per session: the engine has no delete, so a file per session would pile up for ever.
10export const PEER_SCHEMA = 1
11export const SLOT_COUNT = 32
12// A slot whose heartbeat is further than this from now, either way, is free, and its session is not shown.
13export const STALE_MS = 20_000
14// How often a session looks at the others, and how often it writes its heartbeat when nothing changed.
15export const POLL_MS = 2000
16export const BEAT_MS = 6000
17// A change in what the list shows redraws the pane at once only when a session comes, goes or starts waiting on
18// you; any other change waits this long, as each redraw restarts the walks in the picture.
19export const CALM_MS = 10_000
20// A file bigger than this is not a snapshot, and is not read.
21export const PEER_FILE_MAX = 8192
22// How much of the project's name and of the job's message a snapshot keeps.
23export const PEER_TEXT_MAX = 60
24export const PEERS_SHOWN = 6
25// How many of a session's agents its snapshot carries: Main first, then the latest to do anything. As many as a busy
26// session has at once, and few enough to keep the file (about 250 bytes an agent) well under PEER_FILE_MAX.
27export const PEER_AGENTS_MAX = 20
28const LABEL_MAX = 24
29
30export const slotName = (slot: number): string => `slot-${String(slot).padStart(2, '0')}.json`
31const SLOT_FILE = /^slot-(\d\d)\.json$/
32
33// The slot a file name stands for, or null for any other file.
34export function slotOf(name: string): number | null {
35 const found = SLOT_FILE.exec(name)
36 if (found === null) return null
37 const slot = Number(found[1])
38 return slot < SLOT_COUNT ? slot : null
39}
40
41// The folder all of this person's sessions share: under the same Claude config folder the mod's store lives in.
42export function peerDirOf(env: { configDir?: string; home?: string; userProfile?: string }): string | null {
43 const clean = (path: string | undefined): string | null => {
44 const trimmed = path?.trim() ?? ''
45 return trimmed === '' ? null : trimmed.replace(/[\\/]+$/, '')
46 }
47 const home = clean(env.home) ?? clean(env.userProfile)
48 const config = clean(env.configDir) ?? (home === null ? null : `${home}/.claude`)
49 return config === null ? null : `${config}/pixel-office/sessions`
50}
51
52// The last part of a path, Windows or not: what a session's project is called in the list.
53export function baseName(path: string): string {
54 const parts = path.split(/[\\/]+/).filter(part => part !== '')
55 return parts[parts.length - 1] ?? ''
56}
57
58// What Main is doing, in words that name a kind of work and never its object: no file, command, host or search.
59const DOING: Readonly<Record<StationId, string>> = {
60 office: 'thinking',
61 desk: 'editing files',
62 library: 'reading and searching',
63 phone: 'on the web',
64 mailroom: 'using a connected service',
65 server: 'running a command',
66 meeting: 'messaging',
67 taskboard: 'updating its to-do list',
68 reception: 'waiting on you',
69 elevator: 'working',
70 breakroom: 'resting',
71}
72
73export function doingOf(scene: Scene): string {
74 if (Object.values(scene.agents).some(a => a.phase === 'waiting')) return 'waiting on you'
75 const main = scene.agents[MAIN]
76 if (main === undefined) return ''
77 const awaited = waitingOn(scene, MAIN).length
78 if (main.activity === null) {
79 if (awaited > 0) return awaited === 1 ? 'waiting on 1 helper' : `waiting on ${awaited} helpers`
80 return ''
81 }
82 return DOING[stationFor(main.activity.tool)]
83}
84
85// Main's status in the panel's words, or `waiting` when anyone in the session waits on you.
86export function peerStatusOf(scene: Scene): PeerStatus {
87 if (Object.values(scene.agents).some(a => a.phase === 'waiting')) return 'waiting'
88 const main = scene.agents[MAIN]
89 const status = main === undefined ? 'idle' : statusOf(scene, main)
90 return status === 'working' || status === 'coordinating' ? status : 'idle'
91}
92
93export type PeerMeta = { instance: string; sessionId: string; startedAt: number; project: string; since: number }
94
95// What this session tells the others. Nothing else of the session leaves it: no briefs, reports, commands, file
96// names or helper names.
97export function snapshotOf(scene: Scene, meta: PeerMeta, now: number): PeerSession {
98 return {
99 v: PEER_SCHEMA,
100 instance: meta.instance,
101 sessionId: meta.sessionId,
102 beatAt: now,
103 startedAt: meta.startedAt,
104 endedAt: null,
105 project: gist(meta.project, PEER_TEXT_MAX),
106 status: peerStatusOf(scene),
107 since: meta.since,
108 doing: doingOf(scene),
109 task: scene.job === null || scene.job.endedAt !== null ? '' : gist(scene.job.task, PEER_TEXT_MAX),
110 needsYou: Object.values(scene.agents).filter(a => a.phase === 'waiting').length,
111 agents: agentsOf(scene),
112 }
113}
114
115const tenth = (v: number): number => Math.round(v * 10) / 10
116
117// Who is in this office, for another session to look in on: kinds of agent, role words, where each stands and
118// whether it is busy. A helper of a kind set up by its owner goes as `helper`, and a helper the office named after
119// itself ("code-reviewer", a teammate's name) goes by its role words, so no name leaves the session.
120export function agentsOf(scene: Scene): PeerAgent[] {
121 const here = Object.values(scene.agents)
122 .filter((a): a is Agent & { phase: PeerAgent['phase'] } => a.phase !== 'gone')
123 .sort((a, b) => (a.id === MAIN ? -1 : b.id === MAIN ? 1 : b.lastEventAt - a.lastEventAt || (a.id < b.id ? -1 : 1)))
124 .slice(0, PEER_AGENTS_MAX)
125 // Numbered by when each arrived, and sent in that order, so the file changes only when someone does.
126 const arrival = (id: string): number => (id === MAIN ? -1 : scene.order.indexOf(id))
127 here.sort((a, b) => arrival(a.id) - arrival(b.id))
128 const ids = new Map(here.map((a, i) => [a.id, a.id === MAIN ? MAIN : `a${arrival(a.id) < 0 ? 900 + i : arrival(a.id)}`]))
129 return here.map(a => {
130 const type = a.id === MAIN ? 'main' : isBuiltIn(a.type) ? a.type : 'helper'
131 const title = roleFor(type).title
132 const isRoleName = a.label === title || new RegExp(`^${title} \\d{1,3}$`).test(a.label)
133 return {
134 id: ids.get(a.id) ?? MAIN,
135 boss: a.parentId === null ? null : (ids.get(a.parentId) ?? MAIN),
136 type,
137 label: a.id === MAIN ? 'Main' : isRoleName ? a.label : title,
138 phase: a.phase,
139 station: a.station,
140 slot: a.slot,
141 x: tenth(a.pos.x),
142 y: tenth(a.pos.y),
143 look: a.look,
144 isBusy: a.activity !== null,
145 isTeammate: a.isTeammate,
146 isBackground: a.isBackground,
147 }
148 })
149}
150
151// A session that has ended says so in its slot, with nothing else in it, so the others drop it at once.
152export function tombstoneOf(meta: PeerMeta, now: number): PeerSession {
153 return {
154 v: PEER_SCHEMA,
155 instance: meta.instance,
156 sessionId: meta.sessionId,
157 beatAt: now,
158 startedAt: meta.startedAt,
159 endedAt: now,
160 project: '',
161 status: 'idle',
162 since: now,
163 doing: '',
164 task: '',
165 needsYou: 0,
166 agents: [],
167 }
168}
169
170// Whatever another copy, an older version or anything else left in the folder is read as data and checked field by
171// field, and its text is cleaned again: a file that is not a snapshot of this schema is no session.
172const STATUSES: readonly PeerStatus[] = ['working', 'coordinating', 'waiting', 'idle']
173const DOINGS = new Set(['', 'waiting on 1 helper', ...Object.values(DOING)])
174const isText = (value: unknown): value is string => typeof value === 'string'
175const isTime = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value) && value >= 0
176// Beyond what `gist` drops: the C1 controls and the marks that reorder text on screen.
177const UNSEEN = /[\u0080-\u009F\u061C\u200B-\u200F\u202A-\u202E\u2066-\u2069]/g
178// A whole terminal escape sequence goes, not only its escape character, which would leave "[31m" on show.
179const ESCAPES = /\u001B(\[[0-?]*[ -\/]*[@-~]|\][^\u0007\u001B]*(\u0007|\u001B\\)?|[@-_])/g
180const cleaned = (text: string, max: number): string => gist(text.slice(0, max * 4).replace(ESCAPES, '').replace(UNSEEN, ''), max)
181
182const PHASES: readonly PeerAgent['phase'][] = ['arriving', 'briefing', 'working', 'waiting', 'idle']
183const AGENT_ID = /^(main|a\d{1,3})$/
184const COLOR = /^#[0-9a-fA-F]{6}$/
185const isFlag = (value: unknown): value is boolean => typeof value === 'boolean'
186const isAt = (value: unknown, max: number): value is number => typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= max
187
188function parseLook(raw: unknown): Look | null {
189 if (typeof raw !== 'object' || raw === null) return null
190 const { shirt, hair, skin } = raw as Record<string, unknown>
191 return isText(shirt) && COLOR.test(shirt) && isText(hair) && COLOR.test(hair) && isText(skin) && COLOR.test(skin) ? { shirt, hair, skin } : null
192}
193
194function parseAgent(raw: unknown): PeerAgent | null {
195 if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return null
196 const r = raw as Record<string, unknown>
197 const { id, boss, type, label, phase, station, slot, x, y, isBusy, isTeammate, isBackground } = r
198 if (!isText(id) || !AGENT_ID.test(id) || (boss !== null && (!isText(boss) || !AGENT_ID.test(boss)))) return null
199 if (!isText(type) || !(type === 'helper' || isBuiltIn(type)) || !isText(label)) return null
200 const knownPhase = PHASES.find(p => p === phase)
201 const knownStation = STATION_ORDER.find(st => st === station)
202 const look = parseLook(r.look)
203 if (knownPhase === undefined || knownStation === undefined || look === null) return null
204 if (!isAt(slot, 63) || !Number.isInteger(slot) || !isAt(x, WIDTH) || !isAt(y, HEIGHT)) return null
205 if (!isFlag(isBusy) || !isFlag(isTeammate) || !isFlag(isBackground)) return null
206 const name = cleaned(label, LABEL_MAX)
207 return {
208 id,
209 boss,
210 type,
211 label: name === '' ? roleFor(type).title : name,
212 phase: knownPhase,
213 station: knownStation,
214 slot,
215 x,
216 y,
217 look,
218 isBusy,
219 isTeammate,
220 isBackground,
221 }
222}
223
224// A copy from before the field sends no agents, and one that sends anything off is shown with none: an office with
225// nobody in it says less than a wrong one would.
226function parseAgents(raw: unknown): PeerAgent[] {
227 if (!Array.isArray(raw)) return []
228 const out: PeerAgent[] = []
229 const ids = new Set<string>()
230 for (const item of raw.slice(0, PEER_AGENTS_MAX)) {
231 const agent = parseAgent(item)
232 if (agent === null || ids.has(agent.id)) return []
233 ids.add(agent.id)
234 out.push(agent)
235 }
236 return out
237}
238
239export function parsePeer(text: string): PeerSession | null {
240 let raw: unknown
241 try {
242 raw = JSON.parse(text)
243 } catch {
244 return null
245 }
246 if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return null
247 const r = raw as Record<string, unknown>
248 if (r.v !== PEER_SCHEMA) return null
249 const { instance, sessionId, beatAt, startedAt, endedAt, project, status, since, doing, task, needsYou } = r
250 if (!isText(instance) || instance === '' || instance.length > 64 || !isText(sessionId) || sessionId.length > 128) return null
251 if (!isTime(beatAt) || !isTime(startedAt) || !isTime(since) || (endedAt !== null && !isTime(endedAt))) return null
252 if (!isText(project) || !isText(task) || !isText(doing) || !isTime(needsYou)) return null
253 const known = STATUSES.find(s => s === status)
254 if (known === undefined) return null
255 const isWaitingOnHelpers = /^waiting on \d{1,3} helpers$/.test(doing)
256 return {
257 v: PEER_SCHEMA,
258 instance,
259 sessionId,
260 beatAt,
261 startedAt,
262 endedAt,
263 project: cleaned(project, PEER_TEXT_MAX),
264 status: known,
265 since,
266 // Only the words this office itself writes: anything else in that field is dropped, not shown.
267 doing: DOINGS.has(doing) || isWaitingOnHelpers ? doing : '',
268 task: cleaned(task, PEER_TEXT_MAX),
269 needsYou: Math.min(999, Math.floor(needsYou)),
270 agents: parseAgents(r.agents),
271 }
272}
273
274// What names one session's row in the list, and the office being looked in on.
275export const peerKey = (peer: PeerSession): string => `${peer.sessionId}:${peer.instance}`
276
277// Another session's office, as the picture draws it: its agents where they are headed, busy or not, with nothing
278// in their bubbles but their station's sign. Times are set so nobody looks newly arrived or long gone.
279export function officeOf(peer: PeerSession, now: number): Scene {
280 const agents: Record<string, Agent> = {}
281 peer.agents.forEach((p, i) => {
282 const role = roleFor(p.type)
283 agents[p.id] = {
284 id: p.id,
285 parentId: p.id === MAIN ? null : p.boss !== null && p.boss !== p.id ? p.boss : MAIN,
286 type: p.type,
287 role: role.title,
288 name: null,
289 label: p.label,
290 description: '',
291 brief: '',
292 report: '',
293 outcome: null,
294 usage: null,
295 isTeammate: p.isTeammate,
296 isBackground: p.isBackground,
297 phase: p.phase as Phase,
298 station: p.station,
299 slot: p.slot,
300 desk: -1,
301 pos: { x: p.x, y: p.y },
302 walk: null,
303 activity: p.isBusy ? { tool: '', target: '', detail: '', callId: '', since: now } : null,
304 lastErrorAt: null,
305 lastEventAt: now - i,
306 arrivedAt: now - 60_000,
307 doneAt: null,
308 goneAt: null,
309 carry: null,
310 look: p.look,
311 }
312 })
313 const order = peer.agents.filter(p => p.id !== MAIN).map(p => p.id)
314 return { agents, order, ticker: [], todos: null, briefing: null, job: null }
315}
316
317// What a looked-in office shows: a change in any of it redraws the picture.
318export const lookedOf = (peer: PeerSession): string => JSON.stringify([peerKey(peer), peer.project, peer.status, peer.agents])
319
320// A heartbeat counts while it is near now: not older than the stale window, and not further ahead than it either,
321// so a clock set back neither keeps a dead session on show nor keeps its slot taken.
322export const isLive = (peer: PeerSession, now: number): boolean => peer.endedAt === null && Math.abs(now - peer.beatAt) <= STALE_MS
323
324export type Self = { instance: string; sessionId: string }
325
326const ORDER: Readonly<Record<PeerStatus, number>> = { waiting: 0, working: 1, coordinating: 2, idle: 3 }
327
328// Of two live slots with one session id (a hot reload's old copy beside the new one), the later load.
329const isLater = (a: PeerSession, b: PeerSession): boolean => a.startedAt !== b.startedAt ? a.startedAt > b.startedAt : a.instance > b.instance
330
331// The sessions to show: live, not this copy, not this session under another copy (what a hot reload leaves behind
332// for a moment), one row per session id; the ones waiting on you first, then the busy ones, oldest first in each.
333export function livePeers(found: readonly PeerSession[], self: Self, now: number): PeerSession[] {
334 const bySession = new Map<string, PeerSession>()
335 for (const peer of found) {
336 if (!isLive(peer, now) || peer.instance === self.instance || peer.sessionId === self.sessionId) continue
337 const key = peer.sessionId === '' ? `instance:${peer.instance}` : peer.sessionId
338 const held = bySession.get(key)
339 if (held === undefined || isLater(peer, held)) bySession.set(key, peer)
340 }
341 return [...bySession.values()].sort(
342 (a, b) => ORDER[a.status] - ORDER[b.status] || a.startedAt - b.startedAt || (a.instance < b.instance ? -1 : 1),
343 )
344}
345
346// What a slot was found to hold: its snapshot, or null when it could not be read as one, with the file's own time.
347// `isOdd` is a slot that is not a plain small file (a link, a folder, something big): never read, written or free.
348export type SlotSeen = { peer: PeerSession | null; mtimeMs: number; isOdd: boolean }
349
350// The slots another copy can take: missing, ended, stale, or unreadable for longer than the stale window (a file
351// caught half written is someone's, until it stays broken). `own` is a slot holding this session under an older
352// copy, which a hot reload takes back first.
353export function freeSlots(seen: ReadonlyMap<number, SlotSeen>, self: Self, now: number): { own: number | null; free: number[] } {
354 const free: number[] = []
355 let own: number | null = null
356 for (let slot = 0; slot < SLOT_COUNT; slot += 1) {
357 const found = seen.get(slot)
358 if (found === undefined) {
359 free.push(slot)
360 continue
361 }
362 const { peer } = found
363 if (found.isOdd) continue
364 if (peer === null) {
365 if (Math.abs(now - found.mtimeMs) > STALE_MS) free.push(slot)
366 continue
367 }
368 if (peer.instance === self.instance || !isLive(peer, now)) free.push(slot)
369 else if (own === null && self.sessionId !== '' && peer.sessionId === self.sessionId) own = slot
370 }
371 return { own, free }
372}
373
374// Whether the slot this copy holds now holds someone else, alive: two copies took the same free slot at once, and
375// the one that sees it moves.
376export const isTakenFrom = (found: SlotSeen | undefined, instance: string, now: number): boolean =>
377 found !== undefined && found.peer !== null && found.peer.instance !== instance && isLive(found.peer, now)
378
379const STATUS_WORDS: Readonly<Record<PeerStatus, string>> = {
380 working: 'working',
381 coordinating: 'coordinating',
382 waiting: 'needs you',
383 idle: 'idle',
384}
385
386// "4m", "2h 5m": how long a session has been waiting on you, or idle. Nothing under a minute.
387export function sinceWords(ms: number): string {
388 const minutes = Math.floor(ms / 60_000)
389 if (minutes < 1) return ''
390 if (minutes < 60) return `${minutes}m`
391 const hours = Math.floor(minutes / 60)
392 return minutes % 60 === 0 ? `${hours}h` : `${hours}h ${minutes % 60}m`
393}
394
395export type PeerRow = { key: string; status: PeerStatus; line: string; job: string }
396
397// The list: "pixel-office · needs you 3m · waiting on you", and under it the job. Two projects with one name are
398// told apart by a number, never by their paths.
399export function peerRows(peers: readonly PeerSession[], now: number): PeerRow[] {
400 const seen = new Map<string, number>()
401 return peers.map(peer => {
402 const name = peer.project === '' ? 'A session' : peer.project
403 const count = (seen.get(name) ?? 0) + 1
404 seen.set(name, count)
405 const project = count === 1 ? name : `${name} (${count})`
406 const waited = peer.status === 'waiting' || peer.status === 'idle' ? sinceWords(now - peer.since) : ''
407 const status = waited === '' ? STATUS_WORDS[peer.status] : `${STATUS_WORDS[peer.status]} ${waited}`
408 const line = [project, status, peer.doing === 'waiting on you' ? '' : peer.doing].filter(part => part !== '').join(' · ')
409 return { key: peerKey(peer), status: peer.status, line, job: peer.task === '' ? '' : `→ ${peer.task}` }
410 })
411}
412
413// "Your other sessions (3, 1 needs you)".
414export function peersHeading(peers: readonly PeerSession[]): string {
415 const waiting = peers.filter(p => p.status === 'waiting').length
416 return waiting === 0 ? `Your other sessions (${peers.length})` : `Your other sessions (${peers.length}, ${waiting} need${waiting === 1 ? 's' : ''} you)`
417}
418
419// What would make the pane redraw at once (a session came or went, or started waiting on you), and everything the
420// list shows: a change only in the second waits for the calm window.
421// Sorted, so a change that only reorders the list (one session going from working to idle) is not urgent.
422export const urgentOf = (peers: readonly PeerSession[]): string =>
423 JSON.stringify(peers.map(p => `${p.sessionId}:${p.instance}:${p.status === 'waiting' ? 'w' : '-'}`).sort())
424export const shownOf = (peers: readonly PeerSession[]): string =>
425 JSON.stringify(peers.map(p => [p.sessionId, p.instance, p.project, p.status, p.since, p.doing, p.task]))
426
427// What the snapshot says that the others can see: a beat that changes none of it need not be written early.
428export const contentOf = (peer: PeerSession): string => JSON.stringify({ ...peer, beatAt: 0 })
429hooks/recap.ts 415 lines1import type { Agent, JobRecord, Outcome, Scene } from '../types'
2import { MAIN } from './model'
3import { escapeXml } from './render'
4import { tokenCount } from './roles'
5import { clip } from './stations'
6
7// How each agent worked with Main in this job: Main itself, a helper Main waited for, or one working alongside
8// (in the background, or a teammate). The recap colors its bars by this, not by role: the role is the row's name
9// already, and these three are the colors that stay apart for every reader, with any two of them side by side.
10export type LaneKind = 'main' | 'waited' | 'alongside'
11
12export type Lane = {
13 id: string
14 label: string
15 depth: number
16 kind: LaneKind
17 start: number
18 end: number
19 isOpen: boolean
20 outcome: Outcome | null
21 tokens: number | null
22}
23
24export type Recap = {
25 task: string
26 startedAt: number
27 endedAt: number
28 isOpen: boolean
29 lanes: Lane[]
30 helpers: number
31 // Every helper's time added up, and the time during which at least one helper was at work.
32 helperMs: number
33 togetherMs: number
34 peak: number
35 tokens: number | null
36 // Main's own tokens, and the sum of the helpers' counted tokens; null when none were counted.
37 mainTokens: number | null
38 helperTokens: number | null
39 // File edits Main made itself rather than through a helper.
40 mainEdits: number
41}
42
43// A helper belongs to the job it was hired (or called back) in. A called-back helper's tokens are all its work,
44// earlier stints included: the engine reports them per turn, and the office adds them up.
45export function recapOf(scene: Scene, now: number): Recap | null {
46 const job = scene.job
47 if (job === null) return null
48 const isInJob = (a: Agent): boolean => a.id !== MAIN && a.arrivedAt >= job.startedAt
49 const children = new Map<string, string[]>()
50 for (const id of scene.order) {
51 const a = scene.agents[id]
52 if (a === undefined || !isInJob(a)) continue
53 const parent = a.parentId !== null && scene.agents[a.parentId] !== undefined && (a.parentId === MAIN || isInJob(scene.agents[a.parentId] as Agent)) ? a.parentId : MAIN
54 children.set(parent, [...(children.get(parent) ?? []), id])
55 }
56 const lanes: Lane[] = []
57 const visit = (id: string, depth: number): void => {
58 const a = scene.agents[id]
59 if (a === undefined) return
60 if (id === MAIN) {
61 lanes.push({
62 id,
63 label: a.label,
64 depth,
65 kind: 'main',
66 start: job.startedAt,
67 end: job.endedAt ?? now,
68 isOpen: job.endedAt === null,
69 outcome: null,
70 tokens: job.mainUsage?.tokens ?? null,
71 })
72 } else {
73 const isOpen = a.doneAt === null && a.phase !== 'gone' && a.phase !== 'idle'
74 lanes.push({
75 id,
76 label: a.label,
77 depth,
78 kind: a.isBackground || a.isTeammate ? 'alongside' : 'waited',
79 start: a.arrivedAt,
80 end: a.doneAt ?? (isOpen ? now : Math.max(a.arrivedAt, a.lastEventAt)),
81 isOpen,
82 outcome: a.outcome,
83 tokens: a.usage?.tokens ?? null,
84 })
85 }
86 for (const child of children.get(id) ?? []) visit(child, depth + 1)
87 }
88 visit(MAIN, 0)
89 const helpers = lanes.filter(l => l.kind !== 'main')
90 const counted = lanes.filter(l => l.tokens !== null)
91 const countedHelpers = helpers.filter(l => l.tokens !== null)
92 return {
93 task: job.task,
94 startedAt: job.startedAt,
95 endedAt: Math.max(...lanes.map(l => l.end)),
96 isOpen: lanes.some(l => l.isOpen),
97 lanes,
98 helpers: helpers.length,
99 helperMs: helpers.reduce((sum, l) => sum + (l.end - l.start), 0),
100 togetherMs: unionMs(helpers),
101 peak: peakOf(helpers),
102 tokens: counted.length === 0 ? null : counted.reduce((sum, l) => sum + (l.tokens ?? 0), 0),
103 mainTokens: lanes.find(l => l.kind === 'main')?.tokens ?? null,
104 helperTokens: countedHelpers.length === 0 ? null : countedHelpers.reduce((sum, l) => sum + (l.tokens ?? 0), 0),
105 mainEdits: job.mainEdits ?? 0,
106 }
107}
108
109// How long at least one of them was at work: their spans merged where they overlap, then added up.
110function unionMs(lanes: readonly Lane[]): number {
111 const spans = lanes.map(l => [l.start, l.end] as const).sort((a, b) => a[0] - b[0])
112 let total = 0
113 let open: [number, number] | null = null
114 for (const [s, e] of spans) {
115 if (open === null || s > open[1]) {
116 if (open !== null) total += open[1] - open[0]
117 open = [s, e]
118 } else open[1] = Math.max(open[1], e)
119 }
120 return open === null ? total : total + open[1] - open[0]
121}
122
123// The most helpers at work at the same moment. An end and a start at the same moment do not overlap.
124function peakOf(lanes: readonly Lane[]): number {
125 const marks = lanes.flatMap(l => [
126 { at: l.start, step: 1 },
127 { at: l.end, step: -1 },
128 ])
129 marks.sort((a, b) => a.at - b.at || a.step - b.step)
130 let now = 0
131 let peak = 0
132 for (const m of marks) {
133 now += m.step
134 peak = Math.max(peak, now)
135 }
136 return peak
137}
138
139// 45s, 4m 10s, 1h 2m.
140export function span(ms: number): string {
141 const secs = Math.max(0, Math.round(ms / 1000))
142 if (secs < 60) return `${secs}s`
143 const mins = Math.floor(secs / 60)
144 if (mins < 60) return `${mins}m ${secs % 60}s`
145 return `${Math.floor(mins / 60)}h ${mins % 60}m`
146}
147
148const ENDINGS: Record<Outcome, string> = { reported: 'handed in its report', stopped: 'was stopped', failed: 'ran into a problem' }
149
150function endingOf(lane: Lane): string {
151 if (lane.isOpen) return 'still working'
152 if (lane.kind === 'main') return 'finished'
153 return lane.outcome === null ? 'went quiet' : ENDINGS[lane.outcome]
154}
155
156// Doing the helpers' work one after another would take all their time added up; together it took less. Said
157// only when it is a real saving, with two or more helpers.
158export function speedUp(recap: Recap): number | null {
159 if (recap.helpers < 2 || recap.togetherMs <= 0) return null
160 const ratio = recap.helperMs / recap.togetherMs
161 return ratio >= 1.2 ? ratio : null
162}
163
164// The recap in words: what the job was, how long it took, how many helpers and how much at once, what it cost,
165// and what working in parallel bought. These lines stand on their own without the picture.
166export function recapSummary(recap: Recap): string[] {
167 const took = `${recap.isOpen ? 'Running for' : 'Took'} ${span(recap.endedAt - recap.startedAt)}`
168 const crew =
169 recap.helpers === 0
170 ? 'no helpers'
171 : `${recap.helpers} helper${recap.helpers === 1 ? '' : 's'}, up to ${recap.peak} at once`
172 const split = [
173 ...(recap.mainTokens === null ? [] : [`Main ${tokenCount(recap.mainTokens)}`]),
174 ...(recap.helperTokens === null ? [] : [`helpers ${tokenCount(recap.helperTokens)}`]),
175 ]
176 const cost =
177 recap.tokens === null ? '' : ` · ${tokenCount(recap.tokens)} tokens${split.length === 0 ? '' : ` (${split.join(', ')})`}`
178 const lines = [recap.task === '' ? 'This job' : `This job: ${recap.task}`, `${took} · ${crew}${cost}`]
179 if (recap.mainEdits > 0) {
180 lines.push(`Main made ${recap.mainEdits} file edit${recap.mainEdits === 1 ? '' : 's'} itself${recap.helpers === 0 ? '' : ', not through a helper'}`)
181 }
182 const ratio = speedUp(recap)
183 if (ratio !== null) {
184 lines.push(
185 `Helpers did ${span(recap.helperMs)} of work in ${span(recap.togetherMs)}: about ${ratio.toFixed(1)}× faster than one after another`,
186 )
187 }
188 return lines
189}
190
191// One line per agent, indented by who hired whom: the table the picture is drawn from.
192export function recapRows(recap: Recap): string[] {
193 return recap.lanes.map(l => {
194 const indent = ' '.repeat(l.depth)
195 // The engine reports an agent's tokens when its turn ends, so a lane still at work has none yet.
196 if (l.isOpen && l.tokens === null) return `${indent}${l.label}: ${span(l.end - l.start)}, running, tokens counted when it finishes`
197 const tokens = l.tokens === null ? '' : `, ${tokenCount(l.tokens)} tokens`
198 return `${indent}${l.label}: ${span(l.end - l.start)}${tokens}, ${endingOf(l)}`
199 })
200}
201
202const pad = (v: number): string => String(v).padStart(2, '0')
203const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
204
205// "15 Oct 14:05 fix the login bug: took 4m 10s, 3 helpers, 182k tokens", in local time.
206export function historyLine(record: JobRecord): string {
207 const d = new Date(record.startedAt)
208 const when = `${d.getDate()} ${MONTHS[d.getMonth()] ?? ''} ${pad(d.getHours())}:${pad(d.getMinutes())}`
209 const crew = record.helpers === 0 ? 'no helpers' : `${record.helpers} helper${record.helpers === 1 ? '' : 's'}`
210 const tokens = record.tokens === null ? '' : `, ${tokenCount(record.tokens)} tokens`
211 return `${when} ${record.task === '' ? 'a job' : record.task}: took ${span(record.tookMs)}, ${crew}${tokens}`
212}
213
214// The history keeps the newest 20 jobs.
215export const HISTORY_MAX = 20
216
217// What the store holds is read back from disk: anything that is not a well-formed record is left out.
218export function isRecord(value: unknown): value is JobRecord {
219 const r = value as Partial<JobRecord> | null
220 return (
221 typeof r === 'object' &&
222 r !== null &&
223 typeof r.startedAt === 'number' &&
224 typeof r.task === 'string' &&
225 typeof r.tookMs === 'number' &&
226 typeof r.helpers === 'number' &&
227 typeof r.peak === 'number' &&
228 (r.tokens === null || typeof r.tokens === 'number') &&
229 (r.mainTokens === undefined || r.mainTokens === null || typeof r.mainTokens === 'number') &&
230 (r.helperTokens === undefined || r.helperTokens === null || typeof r.helperTokens === 'number') &&
231 (r.mainEdits === undefined || typeof r.mainEdits === 'number')
232 )
233}
234
235// A job is saved each time Main's turn ends, so a turn that carries on later updates the same record.
236export function withRecord(list: readonly JobRecord[], record: JobRecord, max: number = HISTORY_MAX): JobRecord[] {
237 return [...list.filter(r => r.startedAt !== record.startedAt), record]
238 .sort((a, b) => a.startedAt - b.startedAt)
239 .slice(-max)
240}
241
242// The session keeps up to this many jobs in memory.
243export const SESSION_MAX = 500
244
245export type SessionTotals = {
246 jobs: number
247 helpers: number
248 workMs: number
249 tokens: number | null
250 mainTokens: number | null
251 helperTokens: number | null
252 mainEdits: number
253}
254
255// Every job since the conversation began, the one still running included (it replaces its own saved record).
256export function sessionTotals(records: readonly JobRecord[], open: Recap | null): SessionTotals {
257 const all = open === null ? [...records] : withRecord(records, jobRecord(open), Number.MAX_SAFE_INTEGER)
258 const sum = (pick: (r: JobRecord) => number | null | undefined): number | null => {
259 const values = all.map(pick).filter((v): v is number => typeof v === 'number')
260 return values.length === 0 ? null : values.reduce((a, b) => a + b, 0)
261 }
262 return {
263 jobs: all.length,
264 helpers: all.reduce((a, r) => a + r.helpers, 0),
265 workMs: all.reduce((a, r) => a + r.tookMs, 0),
266 tokens: sum(r => r.tokens),
267 mainTokens: sum(r => r.mainTokens),
268 helperTokens: sum(r => r.helperTokens),
269 mainEdits: all.reduce((a, r) => a + (r.mainEdits ?? 0), 0),
270 }
271}
272
273// One line: This session: 4 jobs · 9 helpers · 12m 40s · 482k tokens (Main 211k, helpers 271k).
274export function sessionLines(totals: SessionTotals): string[] {
275 const crew = totals.helpers === 0 ? 'no helpers' : `${totals.helpers} helper${totals.helpers === 1 ? '' : 's'}`
276 const split = [
277 ...(totals.mainTokens === null ? [] : [`Main ${tokenCount(totals.mainTokens)}`]),
278 ...(totals.helperTokens === null ? [] : [`helpers ${tokenCount(totals.helperTokens)}`]),
279 ]
280 const cost =
281 totals.tokens === null ? '' : ` · ${tokenCount(totals.tokens)} tokens${split.length === 0 ? '' : ` (${split.join(', ')})`}`
282 return [`This session: ${totals.jobs} job${totals.jobs === 1 ? '' : 's'} · ${crew} · ${span(totals.workMs)}${cost}`]
283}
284
285export function jobRecord(recap: Recap): JobRecord {
286 return {
287 startedAt: recap.startedAt,
288 task: recap.task,
289 tookMs: recap.endedAt - recap.startedAt,
290 helpers: recap.helpers,
291 peak: recap.peak,
292 tokens: recap.tokens,
293 mainTokens: recap.mainTokens,
294 helperTokens: recap.helperTokens,
295 mainEdits: recap.mainEdits,
296 }
297}
298
299// ---------------------------------------------------------------------------------------------------
300// The swimlane: one row per agent, a bar from when it started to when it finished, on one time axis.
301// Colors were checked with the data-viz palette validator, all pairs, light and dark surfaces. Light values
302// are presentation attributes, so the picture stays readable where a stylesheet is not applied; the dark
303// steps come in through prefers-color-scheme. Text uses the ink colors, never a bar's.
304// ---------------------------------------------------------------------------------------------------
305
306const LIGHT = {
307 surface: '#fcfcfb',
308 ink: '#0b0b0b',
309 muted: '#52514e',
310 grid: '#e4e2dc',
311 main: '#eb6834',
312 waited: '#2a78d6',
313 alongside: '#1baf7a',
314 token: '#9a968c',
315} as const
316const DARK = {
317 surface: '#1a1a19',
318 ink: '#f0efec',
319 muted: '#c3c2b7',
320 grid: '#383835',
321 main: '#d95926',
322 waited: '#3987e5',
323 alongside: '#199e70',
324 token: '#7d7a72',
325} as const
326// Status colors stand for how a helper's job ended, never for a kind of helper, and always with a shape.
327const STATUS = { reported: { glyph: '✓', fill: '#0ca30c' }, stopped: { glyph: '■', fill: '#fab219' }, failed: { glyph: '✕', fill: '#d03b3b' } } as const
328
329export const KIND_WORDS: Record<LaneKind, string> = {
330 main: 'Main',
331 waited: 'A helper Main waited for',
332 alongside: 'A helper working alongside',
333}
334
335const W = 758
336const PAD = 12
337const LABEL_W = 136
338const END_W = 74
339const X0 = PAD + LABEL_W
340const TOK_W = 118
341const X1 = W - PAD - END_W - TOK_W
342const TOP = 34
343const ROW_H = 22
344const BAR_H = 10
345const STEPS = [5, 10, 15, 30, 60, 120, 300, 600, 900, 1800, 3600, 7200].map(s => s * 1000)
346
347const r1 = (v: number): number => Math.round(v * 10) / 10
348
349function tickLabel(ms: number): string {
350 if (ms === 0) return '0'
351 return ms < 60_000 ? `${ms / 1000}s` : ms < 3_600_000 ? `${ms / 60_000}m` : `${ms / 3_600_000}h`
352}
353
354export function recapSvg(recap: Recap): string {
355 const total = Math.max(1000, recap.endedAt - recap.startedAt)
356 const x = (t: number): number => X0 + ((t - recap.startedAt) / total) * (X1 - X0)
357 const step = STEPS.find(s => total / s <= 6) ?? (STEPS[STEPS.length - 1] as number)
358 const axisY = TOP + recap.lanes.length * ROW_H + 4
359 const height = axisY + 24
360 const css =
361 `<style>@media (prefers-color-scheme: dark){` +
362 `.s{fill:${DARK.surface}}.i{fill:${DARK.ink}}.m{fill:${DARK.muted}}.g{stroke:${DARK.grid}}` +
363 `.k-main{fill:${DARK.main}}.k-waited{fill:${DARK.waited}}.k-alongside{fill:${DARK.alongside}}.t{fill:${DARK.token}}}</style>`
364 let out = `<rect class="s" x="0" y="0" width="${W}" height="${height}" rx="8" fill="${LIGHT.surface}"/>`
365 // Legend: the kinds this job has, in a fixed order, so a color always means the same kind.
366 let lx = PAD
367 for (const kind of (['main', 'waited', 'alongside'] as const).filter(k => recap.lanes.some(l => l.kind === k))) {
368 out += `<rect class="k-${kind}" x="${lx}" y="9" width="10" height="10" rx="2" fill="${LIGHT[kind]}"/>`
369 out += `<text class="m" x="${lx + 15}" y="18" font-size="11" fill="${LIGHT.muted}">${escapeXml(KIND_WORDS[kind])}</text>`
370 lx += r1(15 + KIND_WORDS[kind].length * 5.6 + 16)
371 }
372 const tokX = X1 + END_W + 8
373 out += `<text class="m" x="${tokX}" y="18" font-size="11" text-anchor="start" fill="${LIGHT.muted}">Tokens</text>`
374 const tokenTotal = recap.lanes.reduce((sum, l) => sum + (l.tokens ?? 0), 0)
375 // Time axis: a few clean ticks, faint solid lines behind the bars.
376 for (let t = 0; t <= total; t += step) {
377 const tx = r1(x(recap.startedAt + t))
378 out += `<line class="g" x1="${tx}" y1="${TOP - 4}" x2="${tx}" y2="${axisY}" stroke="${LIGHT.grid}" stroke-width="1"/>`
379 out += `<text class="m" x="${tx}" y="${axisY + 15}" font-size="10" text-anchor="middle" fill="${LIGHT.muted}">${tickLabel(t)}</text>`
380 }
381 recap.lanes.forEach((lane, i) => {
382 const mid = TOP + i * ROW_H + ROW_H / 2
383 const name = clip(lane.label, 20 - lane.depth * 2)
384 out += `<text class="i" x="${PAD + lane.depth * 10}" y="${r1(mid + 4)}" font-size="12" fill="${LIGHT.ink}">${escapeXml(name)}</text>`
385 const bx = r1(x(lane.start))
386 const bw = r1(Math.max(4, x(lane.end) - x(lane.start)))
387 out += `<rect class="k-${lane.kind}" x="${bx}" y="${r1(mid - BAR_H / 2)}" width="${bw}" height="${BAR_H}" rx="4" fill="${LIGHT[lane.kind]}"/>`
388 // At the bar's end: how it ended (a shape and a color) and how long it took, in ink.
389 const status = lane.kind === 'main' || lane.isOpen || lane.outcome === null ? null : STATUS[lane.outcome]
390 const ex = r1(bx + bw + 6)
391 const glyph = status === null ? '' : `<tspan fill="${status.fill}">${status.glyph}</tspan> `
392 const words = lane.isOpen ? `${span(lane.end - lane.start)}…` : span(lane.end - lane.start)
393 out += `<text class="i" x="${ex}" y="${r1(mid + 4)}" font-size="11" fill="${LIGHT.ink}">${glyph}${escapeXml(words)}</text>`
394 // The token column: this agent's share of the job's counted tokens, or why there is none yet.
395 if (lane.tokens !== null) {
396 const share = tokenTotal > 0 ? lane.tokens / tokenTotal : 0
397 const tw = lane.tokens > 0 ? r1(Math.max(2, share * 44)) : 0
398 out += `<rect class="t" x="${tokX}" y="${r1(mid - 2)}" width="${tw}" height="4" rx="2" fill="${LIGHT.token}"/>`
399 out += `<text class="i" x="${tokX + 48}" y="${r1(mid + 4)}" font-size="11" fill="${LIGHT.ink}">${tokenCount(lane.tokens)} · ${Math.round(share * 100)}%</text>`
400 } else {
401 out += `<text class="m" x="${tokX}" y="${r1(mid + 4)}" font-size="11" fill="${LIGHT.muted}">${lane.isOpen ? 'running' : '—'}</text>`
402 }
403 })
404 const title = `Timeline of this job: ${recap.lanes.length} agents`
405 return (
406 `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${W} ${height}" width="${W}" height="${height}" ` +
407 `font-family="system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif"><title>${escapeXml(title)}</title>${css}${out}</svg>`
408 )
409}
410
411// What the picture shows, for anyone who cannot see it.
412export function recapAlt(recap: Recap): string {
413 return `Timeline of this job. ${recapRows(recap).map(line => line.trim()).join('. ')}.`
414}
415hooks/render.ts 528 lines1import type { Agent, Scene, StationId } from '../types'
2import { etaDetail, etaOf, etaWords } from './eta'
3import { MAIN, isCoordinating, isWalkingAt, positionAt, waitingOn } from './model'
4import { doing } from './narrate'
5import { OFFICE_DEFS, officeBase, officeDecor, rect } from './office'
6import { petSvg } from './pet'
7import { modelName, roleFor, tokenCount } from './roles'
8import { iconSvg, itemSvg, personSvg } from './sprites'
9import type { Variant } from './sprites'
10import { EXCERPT, HEIGHT, STATIONS, WAITING_TOOLS, WIDTH, clamp, clip, gist, splitAt, stripControls } from './stations'
11
12export const SVG_BUDGET = 120_000
13export const PUFF_MS = 2500
14
15const PUFF = '#e8453c'
16const BOB: Partial<Record<StationId, number>> = {
17 office: 0.8,
18 desk: 0.4,
19 library: 0.7,
20 server: 0.35,
21 mailroom: 0.6,
22 phone: 1,
23 taskboard: 0.6,
24 meeting: 0.9,
25}
26
27const XML: Readonly<Record<string, string>> = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }
28
29export const escapeXml = (text: string): string => stripControls(text).replace(/[&<>"']/g, ch => XML[ch] ?? ch)
30
31const n = (v: number): number => Math.round(v * 100) / 100
32
33export function isNight(now: number): boolean {
34 const hour = new Date(now).getHours()
35 return hour < 7 || hour >= 19
36}
37
38// `now` says in plain words what the agent is doing at this moment, or how its job ended.
39export type OrgRow = {
40 id: string
41 depth: number
42 label: string
43 status: 'working' | 'coordinating' | 'waiting' | 'idle' | 'done'
44 now: string
45}
46
47// What each status reads as in the panel. `waiting` is always waiting on you; waiting on helpers is coordinating.
48export const STATUS_WORDS: Readonly<Record<OrgRow['status'], string>> = {
49 working: 'working',
50 coordinating: 'coordinating',
51 waiting: 'needs you',
52 idle: 'idle',
53 done: 'done',
54}
55
56export function statusOf(scene: Scene, agent: Agent): OrgRow['status'] {
57 if (isCoordinating(scene, agent)) return 'coordinating'
58 switch (agent.phase) {
59 case 'waiting':
60 return 'waiting'
61 case 'idle':
62 return 'idle'
63 case 'gone':
64 return 'done'
65 default:
66 return 'working'
67 }
68}
69
70export function orgRows(scene: Scene, now: number | null = null): OrgRow[] {
71 const children = new Map<string, string[]>()
72 for (const id of scene.order) {
73 const agent = scene.agents[id]
74 if (agent === undefined || agent.parentId === null) continue
75 const parent = scene.agents[agent.parentId] !== undefined ? agent.parentId : MAIN
76 children.set(parent, [...(children.get(parent) ?? []), id])
77 }
78 // Live agents come first among siblings so a trimmed chart keeps them; arrival order holds inside each group.
79 const isGone = (id: string): boolean => scene.agents[id]?.phase === 'gone'
80 for (const siblings of children.values()) siblings.sort((a, b) => Number(isGone(a)) - Number(isGone(b)))
81 const rows: OrgRow[] = []
82 const seen = new Set<string>()
83 const visit = (id: string, depth: number): void => {
84 if (seen.has(id)) return
85 seen.add(id)
86 const agent = scene.agents[id]
87 if (agent === undefined) return
88 const eta = now === null ? null : etaOf(scene, agent, now)
89 const activity = nowOf(scene, agent)
90 rows.push({ id, depth, label: agent.label, status: statusOf(scene, agent), now: eta === null ? activity : `${activity}, ${etaWords(eta)}` })
91 for (const child of children.get(id) ?? []) visit(child, depth + 1)
92 }
93 visit(MAIN, 0)
94 for (const id of scene.order) visit(id, 1)
95 return rows
96}
97
98// "Researcher", "Researcher and Planner", "Researcher, Planner and Assistant", "4 helpers".
99function names(agents: readonly Agent[]): string {
100 const labels = agents.map(a => a.label)
101 if (labels.length > 3) return `${labels.length} helpers`
102 if (labels.length <= 1) return labels[0] ?? ''
103 return `${labels.slice(0, -1).join(', ')} and ${labels[labels.length - 1] ?? ''}`
104}
105
106const ENDINGS = { reported: 'handed in its report', stopped: 'was stopped', failed: 'ran into a problem' } as const
107
108// What an agent is up to right now, in the words the feed uses: "reading auth.ts", "waiting on Researcher".
109export function nowOf(scene: Scene, agent: Agent): string {
110 if (agent.phase === 'gone') return agent.outcome === null ? 'left' : ENDINGS[agent.outcome]
111 if (isCoordinating(scene, agent)) return `waiting on ${names(waitingOn(scene, agent.id))}`
112 // A tool held at a permission prompt has not run yet: what the agent does now is wait for you.
113 // An activity with no tool is another session's agent looked in on: its office says where it works, not with what.
114 const isUnknown = agent.activity?.tool === ''
115 if (agent.phase === 'waiting' && isUnknown) return 'waiting on you'
116 if (agent.phase === 'waiting' && (agent.activity === null || !WAITING_TOOLS.has(agent.activity.tool))) {
117 return 'waiting for your permission'
118 }
119 if (agent.activity !== null) return isUnknown ? `busy at ${STATIONS[agent.station].name}` : doing(agent.activity)
120 switch (agent.phase) {
121 case 'arriving':
122 return 'arriving'
123 case 'briefing':
124 return 'being briefed'
125 case 'idle':
126 if (agent.station === 'breakroom') return 'on a break'
127 return agent.id === MAIN ? 'ready for your next message' : 'free for the next job'
128 default:
129 return 'thinking'
130 }
131}
132
133// The second line under a helper in the org chart: what it was hired to do, fitted to a column `width` wide.
134export function objectiveLine(scene: Scene, id: string, depth: number, width: number): string {
135 const agent = scene.agents[id]
136 if (agent === undefined || agent.id === MAIN) return ''
137 const objective = clip(agent.description, Math.max(1, width - depth * 2 - 2))
138 return objective === '' ? '' : `${' '.repeat(depth)}↳ ${objective}`
139}
140
141const pad = (v: number): string => String(v).padStart(2, '0')
142
143export function clockLabel(at: number): string {
144 const d = new Date(at)
145 return `${pad(d.getHours())}:${pad(d.getMinutes())}`
146}
147
148export function altText(scene: Scene): string {
149 const here = Object.values(scene.agents).filter(a => a.phase !== 'gone')
150 const noun = here.length === 1 ? 'agent' : 'agents'
151 return `Pixel office with ${here.length} ${noun}: ${here.map(a => `${a.label} at ${STATIONS[a.station].name}`).join(', ')}`
152}
153
154// The details box shows a brief or a report as one line; the whole text is a press away.
155export const excerptOf = (text: string): string => gist(text, EXCERPT)
156// Whether the one line leaves something out, so the whole text is worth offering.
157export const isCut = (text: string): boolean => excerptOf(text).endsWith('…')
158
159// Lines that only belong in the panel: the brief and the report are long, and the job clock ticks every second.
160const PANEL_ONLY = ['Brief:', 'Report:', 'On the job:', 'Expected:', 'Used']
161
162// The details box: who this is, what its kind of agent does, the job it was given, what it is doing, who it
163// works for and how that boss works with it, and what it handed back.
164export function agentDetails(scene: Scene, id: string, now: number): string[] {
165 const agent = scene.agents[id]
166 if (agent === undefined) return []
167 const role = roleFor(agent.type)
168 const boss = agent.parentId === null ? undefined : scene.agents[agent.parentId]?.label
169 const used =
170 agent.usage === null
171 ? []
172 : [`${agent.id === MAIN ? 'Used so far' : 'Used'}: ${tokenCount(agent.usage.tokens)} tokens (${tokenCount(agent.usage.reused)} reused) on ${modelName(agent.usage.model)}`]
173 if (agent.id === MAIN) return [`Main · ${role.title}`, role.blurb, `Now: ${nowOf(scene, agent)}`, ...used]
174 // "Researcher 2 · Explore agent" ties the office's name to the one Claude Code shows; a named agent also gets its role.
175 const isRoleName = agent.label === role.title || agent.label.startsWith(`${role.title} `)
176 const title =
177 agent.type === 'contractor'
178 ? agent.label
179 : isRoleName
180 ? `${agent.label} · ${agent.type} agent`
181 : `${agent.label} · ${role.title} (${agent.type} agent)`
182 const lines = [title, role.blurb]
183 if (agent.description !== '') lines.push(`Job: ${agent.description}`)
184 if (agent.brief !== '') lines.push(`Brief: ${excerptOf(agent.brief)}`)
185 lines.push(`Now: ${nowOf(scene, agent)}`)
186 if (boss !== undefined) {
187 const how = agent.isTeammate ? 'leads the team' : agent.isBackground ? 'keeps working meanwhile' : 'waits for its report'
188 lines.push(`Reports to: ${boss}, who ${how}`)
189 }
190 if (agent.report !== '') lines.push(`Report: ${excerptOf(agent.report)}`)
191 lines.push(...used)
192 if (agent.id !== MAIN) {
193 // A helper that has left stops the clock where it left.
194 const until = agent.phase === 'gone' && agent.goneAt !== null ? Math.min(now, agent.goneAt) : now
195 const secs = Math.max(0, Math.round((until - agent.arrivedAt) / 1000))
196 lines.push(`On the job: ${Math.floor(secs / 60)}m ${secs % 60}s`)
197 const eta = etaOf(scene, agent, now)
198 if (eta !== null) lines.push(etaDetail(eta))
199 }
200 return lines
201}
202
203// A boss waiting on its helpers shows who it is waiting on, with the meeting-room icon.
204type BubbleBox = { text: string; station: StationId; isWaiting: boolean; width: number; left: number; top: number }
205
206// What a speech bubble says and where it would sit over its agent, or null when the agent has nothing to say.
207function bubbleBox(agent: Agent, scene: Scene): BubbleBox | null {
208 const isWaiting = agent.phase === 'waiting'
209 const team = isCoordinating(scene, agent) ? waitingOn(scene, agent.id) : []
210 if (agent.activity === null && !isWaiting && team.length === 0) return null
211 const station: StationId = isWaiting ? 'reception' : team.length > 0 ? 'meeting' : agent.station
212 const text =
213 team.length === 1 ? clip(`waiting on ${team[0]?.label ?? ''}`) : team.length > 1 ? `waiting on ${team.length}` : (agent.activity?.target ?? '')
214 const width = 9 + Math.ceil(text.length * 2.4)
215 const left = clamp(-Math.round(width / 2), 2 - agent.pos.x, WIDTH - 2 - agent.pos.x - width)
216 const top = Math.max(-27, 1 - agent.pos.y)
217 return { text, station, isWaiting, width, left, top }
218}
219
220// Bubbles of agents standing close together would cover each other, so each takes the lowest lane (one bubble
221// higher than the last) that is free, and a thin stem joins a raised bubble to its agent. Near the top of the floor
222// there is no room to go higher: a bubble with no free lane is left out (-1) rather than hidden under another, and
223// the panel still says what that agent is doing.
224const BUBBLE_HEIGHT = 10
225const BUBBLE_STEP = 11
226const BUBBLE_LANES = 3
227
228function bubbleLanes(agents: readonly Agent[], scene: Scene, now: number): Map<string, number> {
229 const placed: Array<{ x0: number; x1: number; y0: number; y1: number }> = []
230 const lanes = new Map<string, number>()
231 for (const agent of agents) {
232 const box = bubbleBox(agent, scene)
233 if (box === null) continue
234 const at = positionAt(agent, now)
235 const x0 = at.x + box.left
236 const x1 = x0 + box.width
237 let found = -1
238 let highest = Infinity
239 for (let lane = 0; lane <= BUBBLE_LANES; lane++) {
240 const y0 = at.y + Math.max(1 - agent.pos.y, box.top - lane * BUBBLE_STEP)
241 // A lane that is no higher than the last, because the floor's top edge stops it, is no new lane.
242 if (y0 >= highest) break
243 highest = y0
244 const rect = { x0, x1, y0, y1: y0 + BUBBLE_HEIGHT }
245 if (!placed.some(r => r.x0 < rect.x1 && rect.x0 < r.x1 && r.y0 < rect.y1 && rect.y0 < r.y1)) {
246 placed.push(rect)
247 found = lane
248 break
249 }
250 }
251 lanes.set(agent.id, found)
252 }
253 return lanes
254}
255
256function bubble(agent: Agent, scene: Scene, lane = 0): string {
257 const box = bubbleBox(agent, scene)
258 if (box === null || lane < 0) return ''
259 const { text, station, isWaiting, width, left } = box
260 const top = Math.max(1 - agent.pos.y, box.top - lane * BUBBLE_STEP)
261 const blink = isWaiting ? '<animate attributeName="opacity" values="1;0.35;1" dur="0.8s" repeatCount="indefinite"/>' : ''
262 const words = text === '' ? '' : `<text x="8.5" y="6" font-size="4" fill="#2c2c2a">${escapeXml(text)}</text>`
263 const stem = box.top - top > 0 ? rect(-left - 0.5, BUBBLE_HEIGHT, 1, box.top - top, '#2c2c2a') : ''
264 return (
265 `<g transform="translate(${n(left)},${n(top)})">${blink}` +
266 rect(0, 0, width, 8, '#ffffff', ' stroke="#2c2c2a" stroke-width="0.5"') +
267 rect(-left - 1, 8, 2, 2, '#ffffff') +
268 stem +
269 iconSvg(station, 2, 1.5, STATIONS[station].color) +
270 `${words}</g>`
271 )
272}
273
274function errorPuff(ms: number): string {
275 return (
276 `<g transform="translate(5,-16)">${rect(-2, -2, 4, 4, PUFF)}${rect(-1, -4, 2, 2, '#f09595')}${rect(2, -1, 2, 2, '#f09595')}` +
277 `<animate attributeName="opacity" values="1;0" dur="${Math.round(ms)}ms" fill="freeze"/></g>`
278 )
279}
280
281function leaveAt(agent: Agent, now: number): string {
282 if (agent.phase !== 'gone' || agent.goneAt === null) return ''
283 return `<set attributeName="visibility" to="hidden" begin="${Math.max(0, Math.round(agent.goneAt - now))}ms"/>`
284}
285
286// The folder or envelope an agent carries to another agent, hidden at the moment it is handed over.
287function carried(agent: Agent, now: number): string {
288 if (agent.carry === null || now >= agent.carry.until) return ''
289 return `<g>${itemSvg(agent.carry.item, -1, -5)}<set attributeName="visibility" to="hidden" begin="${Math.round(agent.carry.until - now)}ms"/></g>`
290}
291
292// Name tags sit over heads, or under the feet when a neighbour's tag already takes the space over a head:
293// a boss briefing a new helper sits right beside it, and both names must stay readable.
294const TAG_ABOVE = -14
295const TAG_BELOW = 5.5
296const TAG_CHAR = 2.1
297
298type TagSpot = { x0: number; x1: number; y: number; isBelow: boolean }
299
300export function tagsBelow(agents: readonly Agent[], now: number): Set<string> {
301 const placed: TagSpot[] = []
302 const below = new Set<string>()
303 for (const agent of agents) {
304 const pos = positionAt(agent, now)
305 const half = (Array.from(agent.label).length * TAG_CHAR) / 2 + 0.5
306 const spot = { x0: pos.x - half, x1: pos.x + half, y: pos.y }
307 const overlap = (isBelow: boolean): number =>
308 placed.reduce(
309 (sum, t) =>
310 t.isBelow === isBelow && Math.abs(t.y - spot.y) < 6
311 ? sum + Math.max(0, Math.min(t.x1, spot.x1) - Math.max(t.x0, spot.x0))
312 : sum,
313 0,
314 )
315 const above = overlap(false)
316 const isBelow = above > 0 && overlap(true) < above
317 placed.push({ ...spot, isBelow })
318 if (isBelow) below.add(agent.id)
319 }
320 return below
321}
322
323// A thin bar under a helper's feet that fills over the time its predecessors took. It is animated inside the
324// picture, so it needs no redraw as it fills; one past what is usual stays full and pulses amber instead.
325const BAR_WIDTH = 9
326export function etaBar(scene: Scene, agent: Agent, now: number): string {
327 const eta = etaOf(scene, agent, now)
328 if (eta === null) return ''
329 const x = -BAR_WIDTH / 2
330 const track = rect(x, 1.8, BAR_WIDTH, 1, '#000000', ' fill-opacity="0.45"')
331 if (eta.leftMs <= 1000) {
332 return `${track}<rect x="${x}" y="1.8" width="${BAR_WIDTH}" height="1" fill="#fac775"><animate attributeName="opacity" values="1;0.4;1" dur="1.2s" repeatCount="indefinite"/></rect>`
333 }
334 const start = n(BAR_WIDTH * clamp((now - agent.arrivedAt) / eta.typicalMs, 0, 1))
335 return `${track}<rect x="${x}" y="1.8" width="${start}" height="1" fill="#97c459"><animate attributeName="width" from="${start}" to="${BAR_WIDTH}" dur="${Math.round(eta.leftMs)}ms" fill="freeze"/></rect>`
336}
337
338function drawAgent(agent: Agent, scene: Scene, now: number, isTagBelow = false, lane = 0): string {
339 const variant: Variant = agent.id === MAIN ? 'main' : agent.isTeammate ? 'teammate' : 'plain'
340 // The panel's own lines (the brief, the report, the ticking job clock) stay out of the picture's title.
341 const facts = agentDetails(scene, agent.id, now).filter(line => !PANEL_ONLY.some(start => line.startsWith(start)))
342 const head = `<title>${escapeXml(facts.join('\n'))}</title>${leaveAt(agent, now)}`
343 const tag =
344 `<text x="0" y="${isTagBelow ? TAG_BELOW : TAG_ABOVE}" font-size="3.5" text-anchor="middle" fill="#ffffff" stroke="#2c2c2a" ` +
345 `stroke-width="0.8" paint-order="stroke">${escapeXml(agent.label)}</text>`
346 const puff = agent.lastErrorAt !== null && now - agent.lastErrorAt < PUFF_MS ? errorPuff(PUFF_MS - (now - agent.lastErrorAt)) : ''
347 const id = `agent-${escapeXml(agent.id)}`
348 if (agent.walk !== null && isWalkingAt(agent, now)) {
349 const rest = splitAt(agent.walk.points, (now - agent.walk.startedAt) / agent.walk.durationMs)
350 // A walk drawn before its first step plays from that step at its own pace.
351 const ms = Math.max(1, Math.round(Math.min(agent.walk.durationMs, agent.walk.startedAt + agent.walk.durationMs - now)))
352 const path = `M${rest.map(p => `${n(p.x)},${n(p.y)}`).join(' L')}`
353 return `<g id="${id}">${head}<animateMotion dur="${ms}ms" fill="freeze" path="${path}"/>${personSvg(agent.look, variant, ms)}${carried(agent, now)}${etaBar(scene, agent, now)}${tag}${bubble(agent, scene, lane)}${puff}</g>`
354 }
355 const period = agent.activity !== null ? BOB[agent.station] : undefined
356 const body = personSvg(agent.look, variant, 0)
357 const working =
358 period === undefined
359 ? body
360 : `<g>${body}<animateTransform attributeName="transform" type="translate" values="0,0;0,-0.6;0,0" dur="${period}s" repeatCount="indefinite"/></g>`
361 return `<g id="${id}" transform="translate(${n(agent.pos.x)},${n(agent.pos.y)})">${head}${working}${etaBar(scene, agent, now)}${tag}${bubble(agent, scene, lane)}${puff}</g>`
362}
363
364// The furniture an agent at work is using, outlined in its station's colour: where on the floor each station's
365// things stand. A desk and a phone booth belong to one agent, so each has its own; the rest are shared.
366type Box = { x: number; y: number; w: number; h: number }
367const IN_USE: Partial<Record<StationId, (slot: number) => Box>> = {
368 desk: slot => ({ x: 77 + 22 * (slot % 4), y: 20 + 30 * Math.floor(slot / 4), w: 18, h: 19 }),
369 library: () => ({ x: 177, y: 11, w: 63, h: 24 }),
370 mailroom: () => ({ x: 177, y: 51, w: 30, h: 19 }),
371 phone: slot => ({ x: 213 + 14 * Math.min(slot, 1), y: 51, w: 14, h: 30 }),
372 server: () => ({ x: 185, y: 101, w: 46, h: 28 }),
373 meeting: () => ({ x: 91, y: 115, w: 44, h: 14 }),
374 taskboard: () => ({ x: 71, y: 0, w: 34, h: 10 }),
375 reception: () => ({ x: 35, y: 122, w: 28, h: 11 }),
376}
377
378function inUse(here: readonly Agent[]): string {
379 const seen = new Set<string>()
380 let out = ''
381 for (const agent of here) {
382 const place = IN_USE[agent.station]
383 if (place === undefined || agent.activity === null) continue
384 const box = place(agent.slot)
385 const key = `${agent.station}:${box.x}:${box.y}`
386 if (seen.has(key)) continue
387 seen.add(key)
388 const color = STATIONS[agent.station].color
389 out +=
390 `<rect x="${box.x}" y="${box.y}" width="${box.w}" height="${box.h}" fill="${color}" fill-opacity="0.14" stroke="${color}" stroke-width="0.8">` +
391 '<animate attributeName="stroke-opacity" values="0.95;0.35;0.95" dur="1.6s" repeatCount="indefinite"/></rect>'
392 }
393 return out
394}
395
396function overlays(scene: Scene, now: number): string {
397 const all = Object.values(scene.agents)
398 const here = all.filter(a => a.phase !== 'gone')
399 const busy = (station: StationId): Agent[] =>
400 here.filter(a => a.station === station && a.activity !== null && !isWalkingAt(a, now))
401 let out = inUse(here)
402 if (scene.briefing !== null) {
403 out += `<text x="116" y="99" font-size="3.5" text-anchor="middle" fill="#2c2c2a">${escapeXml(clip(scene.briefing, 18))}</text>`
404 }
405 if (scene.todos !== null) {
406 const notes = [
407 ...Array<string>(Math.min(scene.todos.done, 6)).fill('#97c459'),
408 ...Array<string>(Math.min(scene.todos.open, 6)).fill('#fac775'),
409 ]
410 notes.forEach((fill, i) => {
411 out += rect(74 + (i % 6) * 5, 2.5 + Math.floor(i / 6) * 3, 4, 2.5, fill)
412 })
413 }
414 if (busy('server').length > 0) {
415 for (const x of [188, 204, 220]) {
416 out +=
417 `<rect x="${x}" y="124" width="6" height="1" fill="#ef9f27">` +
418 '<animate attributeName="opacity" values="1;0.2;1" dur="0.25s" repeatCount="indefinite"/></rect>'
419 }
420 }
421 for (const agent of busy('phone')) out += rect(agent.slot === 0 ? 219 : 233, 53, 2, 1, '#fac775')
422 if (busy('mailroom').length > 0) out += rect(196, 57, 5, 4, '#d3a36b') + rect(198, 57, 1, 4, '#854f0b')
423 if (here.some(a => a.activity?.tool === 'Write')) {
424 out +=
425 '<rect x="166" y="34" width="5" height="1" fill="#ffffff">' +
426 '<animate attributeName="height" values="1;5;1" dur="1s" repeatCount="indefinite"/></rect>'
427 }
428 const isElevatorBusy = all.some(
429 a =>
430 (a.id !== MAIN && now - a.arrivedAt < 2000) ||
431 (a.phase === 'gone' && a.goneAt !== null && now < a.goneAt + 1500),
432 )
433 if (isElevatorBusy) out += rect(9, 112, 14, 24, '#2c2c2a')
434 if (here.some(a => a.phase === 'waiting')) {
435 out +=
436 '<rect x="45" y="117" width="6" height="1" fill="#fac775">' +
437 '<animate attributeName="opacity" values="1;0;1" dur="0.5s" repeatCount="indefinite"/></rect>'
438 }
439 return out
440}
441
442function badge(extra: number): string {
443 return `<g>${rect(196, 1, 42, 7, '#2c2c2a')}<text x="217" y="6.3" font-size="4.5" text-anchor="middle" fill="#ffffff">+${extra} more</text></g>`
444}
445
446// The moment the scene last changed: an event, the start of a walk, an error.
447export function sceneTimeOf(scene: Scene): number {
448 let latest = scene.ticker[scene.ticker.length - 1]?.at ?? 0
449 for (const a of Object.values(scene.agents)) {
450 latest = Math.max(latest, a.lastEventAt, a.arrivedAt, a.lastErrorAt ?? 0, a.walk?.startedAt ?? 0)
451 }
452 return latest
453}
454
455// The desktop draws about 7.9 px per cell column, and a little under is used so the picture never overflows the pane.
456export const CELL_PX = 7.5
457
458// The size the picture takes in a pane of this many columns, keeping its shape.
459export function fitSize(size: { width: number; height: number } | undefined, columns: number): { width: number; height: number } | undefined {
460 if (size === undefined || !Number.isFinite(columns) || columns <= 0) return undefined
461 const width = Math.min(2400, Math.max(320, Math.round(columns * CELL_PX)))
462 return { width, height: Math.round((width * size.height) / size.width) }
463}
464
465// A picture whose box is not sized collapses while the host swaps it, which scrolls the pane back to the top, so
466// each picture is given the size its markup declares: the root element's width and height, never a nested one's.
467export function svgSize(source: string): { width: number; height: number } | undefined {
468 const tag = /<svg\b[^>]*>/.exec(source)?.[0]
469 if (tag === undefined) return undefined
470 const read = (name: string): number => {
471 const value = new RegExp(`\\s${name}="(\\d+(?:\\.\\d+)?|\\.\\d+)"`).exec(tag)?.[1]
472 return value === undefined ? NaN : Number(value)
473 }
474 const width = read('width')
475 const height = read('height')
476 return width > 0 && height > 0 && Number.isFinite(width) && Number.isFinite(height) ? { width, height } : undefined
477}
478
479// Pictures are drawn as of this far ahead of the clock, about when they appear. Each picture is shown late by the
480// desktop's delay less this, and so was the one before it, so the value moves no one: what moves a walker at a redraw
481// is how much that delay changes from one picture to the next.
482export const LEAD_MS = 250
483
484// The picture the pane shows, drawn as of the moment it will appear. The desktop starts a picture's animations over
485// whenever the pane is drawn, even when the picture is the very same text: in a recording, a walker went back to the
486// first step of its walk at every draw while nothing about it had changed. A picture kept from an earlier draw would
487// replay what happened then, so each draw is fresh, and a restart carries on from where everyone is.
488export function officeSource(scene: Scene, now: number): string {
489 return renderOffice(scene, now + LEAD_MS)
490}
491
492const ROOT =
493 `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${WIDTH} ${HEIGHT}" width="${WIDTH * 4}" height="${HEIGHT * 4}" ` +
494 'shape-rendering="crispEdges" font-family="monospace">'
495
496function rankedAgents(scene: Scene, now: number): Agent[] {
497 return Object.values(scene.agents)
498 .filter(a => !(a.phase === 'gone' && a.goneAt !== null && now >= a.goneAt))
499 .sort((a, b) => (a.id === MAIN ? -1 : b.id === MAIN ? 1 : b.lastEventAt - a.lastEventAt))
500}
501
502export function renderOffice(scene: Scene, now: number, budget = SVG_BUDGET): string {
503 const ranked = rankedAgents(scene, now)
504 const head = `${ROOT}${OFFICE_DEFS}${officeBase(isNight(now))}`
505 const props = overlays(scene, now)
506 const build = (withDecor: boolean, count: number): string => {
507 const drawn = ranked
508 .slice(0, count)
509 .map(a => ({ a, y: positionAt(a, now).y }))
510 .sort((p, q) => p.y - q.y)
511 .map(p => p.a)
512 const below = tagsBelow(drawn, now)
513 const lanes = bubbleLanes(drawn, scene, now)
514 const people = drawn.map(a => drawAgent(a, scene, now, below.has(a.id), lanes.get(a.id) ?? 0)).join('')
515 const extra = ranked.length - count
516 return `${head}${withDecor ? officeDecor() + petSvg(now) : ''}${props}${people}${extra > 0 ? badge(extra) : ''}</svg>`
517 }
518 let svg = build(true, ranked.length)
519 if (svg.length <= budget) return svg
520 let count = ranked.length
521 svg = build(false, count)
522 while (svg.length > budget && count > 1) {
523 count -= 1
524 svg = build(false, count)
525 }
526 return svg
527}
528hooks/settings.ts 144 lines1// The office's own settings: the options plugin.json declares, read and changed from inside the office (its
2// Settings button, `/office settings`, `/office set`) rather than at install time. There is no file of the office's
3// own: a change goes through `$.config.set`, the same writer as the `/config` menu, so it lands in settings.json
4// under `pluginConfigs` and the engine loads the office again with the new value.
5
6export type Setting = {
7 field: string
8 title: string
9 fallback: string
10 // Each value plugin.json allows, in its order, with what it does in a few words.
11 choices: ReadonlyArray<{ value: string; meaning: string }>
12}
13
14// Kept in step with plugin.json's `userConfig` by hand: the test kit can check the defaults, not the rest.
15export const SETTINGS: readonly Setting[] = [
16 {
17 field: 'autoOpen',
18 title: 'Open the office',
19 fallback: 'on-first-subagent',
20 choices: [
21 { value: 'on-first-subagent', meaning: 'when the first helper is hired' },
22 { value: 'session-start', meaning: 'as each session starts' },
23 { value: 'never', meaning: 'only with /office' },
24 ],
25 },
26 {
27 field: 'history',
28 title: 'Keep a history of jobs',
29 fallback: 'off',
30 choices: [
31 { value: 'off', meaning: 'nothing kept after the session' },
32 { value: 'last-20', meaning: 'the newest 20 jobs, on this computer' },
33 ],
34 },
35 {
36 field: 'notify',
37 title: 'Remind me when an agent waits on me',
38 fallback: 'off',
39 choices: [
40 { value: 'off', meaning: 'no reminders' },
41 { value: 'after-30s', meaning: 'once, after 30 seconds' },
42 ],
43 },
44 {
45 field: 'otherSessions',
46 title: 'Show my other sessions',
47 fallback: 'off',
48 choices: [
49 { value: 'off', meaning: 'nothing written or read' },
50 { value: 'on', meaning: 'list them, sharing this one\'s status and message start through a small file' },
51 ],
52 },
53 {
54 field: 'debug',
55 title: 'Debug log',
56 fallback: 'off',
57 choices: [
58 { value: 'off', meaning: 'nothing recorded' },
59 { value: 'on', meaning: 'write a log of timings to a file, for troubleshooting' },
60 ],
61 },
62]
63
64// The `/config` row of a field when no listing names it: `<plugin>.<field>`.
65export const PLUGIN = 'pixel-office'
66
67export function valueOf(options: Readonly<Record<string, unknown>>, setting: Setting): string {
68 const value = options[setting.field]
69 return typeof value === 'string' && setting.choices.some(c => c.value === value) ? value : setting.fallback
70}
71
72export function meaningOf(setting: Setting, value: string): string {
73 return setting.choices.find(c => c.value === value)?.meaning ?? ''
74}
75
76// One line per setting, for the terminal and the command's reply: "Keep a history of jobs: off (nothing kept after the session)".
77export function settingLines(options: Readonly<Record<string, unknown>>): string[] {
78 return SETTINGS.map(setting => {
79 const value = valueOf(options, setting)
80 return `${setting.title} (${setting.field}): ${value}, ${meaningOf(setting, value)}`
81 })
82}
83
84export const USAGE = '/office shows or hides the office, /office settings lists its settings, and /office set <name> <value> changes one.'
85
86export const SETTINGS_HELP = 'Change one with /office set <name> <value> (for example /office set history last-20), from Settings in the office, or in /config.'
87
88export type SetRequest = { setting: Setting; value: string } | { error: string }
89
90// Reads `/office set`'s arguments: a field's name, then one of its values. Case is forgiven on both, as the field
91// names are camelCase and easy to mistype.
92export function parseSet(args: string): SetRequest {
93 const words = args.trim().split(/\s+/).filter(w => w !== '')
94 if (words.length !== 2) return { error: `Say which setting and its value, as in /office set history last-20. The settings are ${fieldList()}.` }
95 const [name, raw] = words as [string, string]
96 const setting = SETTINGS.find(s => s.field.toLowerCase() === name.toLowerCase())
97 if (setting === undefined) return { error: `There is no setting called ${name}. The settings are ${fieldList()}.` }
98 const choice = setting.choices.find(c => c.value.toLowerCase() === raw.toLowerCase())
99 if (choice === undefined) return { error: `${setting.field} can be ${setting.choices.map(c => c.value).join(' or ')}.` }
100 return { setting, value: choice.value }
101}
102
103function fieldList(): string {
104 return SETTINGS.map(s => s.field).join(', ')
105}
106
107// The `/config` key of a field: `<plugin>.<field>`, unless another plugin of the same name is loaded too (an
108// installed copy beside a development one), when each copy's rows carry its marketplace. Which of those is this
109// copy cannot be told from here, so then there is no key, and the change is left to `/config`.
110export function configKeyOf(keys: readonly string[], field: string): string | null {
111 const plain = `${PLUGIN}.${field}`
112 if (keys.includes(plain)) return plain
113 const copies = keys.filter(key => key.startsWith(`${PLUGIN}@`) && key.endsWith(`.${field}`))
114 if (copies.length > 1) return null
115 return copies[0] ?? plain
116}
117
118export const MANY_COPIES = 'more than one copy of the office is loaded, so change it in /config'
119export const CANNOT = 'this Claude Code cannot change it from here, so change it in /config'
120
121// What the office says once a change is asked for: the engine's refusal in its own words, or that it took.
122export function setReply(setting: Setting, value: string, deny: string | undefined): string {
123 if (deny !== undefined) return `${setting.title} was not changed: ${deny}`
124 return `${setting.title} is now ${value} (${meaningOf(setting, value)}).`
125}
126
127// The same once the row has been read back: a value saved but not in force (a `--settings` file that sets it, or
128// an engine that did not load the office again) is said as such. `stored` is undefined when it could not be read.
129export function replyAfterSet(setting: Setting, value: string, deny: string | undefined, stored: unknown): string {
130 if (deny !== undefined || stored === undefined || stored === value) return setReply(setting, value, deny)
131 return `${setting.title} was saved as ${value}, but this session still uses ${String(stored)}. It applies after /reload-plugins or in a new session.`
132}
133
134// What each setting holds now: the `/config` rows when the engine lists them, else the options the office loaded with.
135export function currentValues(rows: ReadonlyArray<{ key: string; value: unknown }>, options: Readonly<Record<string, unknown>>): Record<string, string> {
136 const out: Record<string, string> = {}
137 for (const setting of SETTINGS) {
138 const key = configKeyOf(rows.map(row => row.key), setting.field)
139 const row = key === null ? undefined : rows.find(r => r.key === key)
140 out[setting.field] = valueOf(row === undefined ? options : { [setting.field]: row.value }, setting)
141 }
142 return out
143}
144hooks/state.ts 8 lines1// Shared names only. The engine reads each file's own `atom(...)` declarations to list the state a module
2// touches, so a file that reads or writes an atom declares it in that file instead of importing it from here.
3export const PANE = 'pixel-office'
4export const PANE_TITLE = 'Office'
5// The keys of the two probes (debug mode) the pane draws, which the ui.message hook recognises.
6export const PROBE_TOP = 'probe-top'
7export const PROBE_BOTTOM = 'probe-bottom'
8hooks/stations.ts 404 lines1import type { Point, StationId } from '../types'
2import { commandIntent, explainCommand } from './commands'
3
4export { explainCommand }
5
6export const WIDTH = 240
7export const HEIGHT = 150
8export const CORRIDOR_Y = 88
9export const DESK_COUNT = 8
10
11export type StationDef = {
12 name: string
13 tools: string
14 color: string
15 slots: readonly Point[]
16 door: Point | null
17 slotDoors?: readonly Point[]
18}
19
20export const clamp = (value: number, lo: number, hi: number): number => Math.min(Math.max(value, lo), hi)
21
22// What XML 1.0 refuses: everything below space except tab, line feed and carriage return, delete, the two
23// non-characters U+FFFE and U+FFFF, and any UTF-16 surrogate that is not half of a proper pair. The first
24// alternative is a proper pair, which is kept (`$1`); a surrogate it did not take is a lone one and goes.
25const UNSAFE = /([\uD800-\uDBFF][\uDC00-\uDFFF])|[\x00-\x08\x0B\x0C\x0E-\x1F\x7F\uD800-\uDFFF\uFFFE\uFFFF]/g
26
27export const stripControls = (text: string): string => text.replace(UNSAFE, '$1')
28
29// Fits `text` to `max` characters, counting and cutting by code point so an emoji is never split in half.
30export function clip(text: string, max = 24): string {
31 const chars = Array.from(stripControls(text.replace(/\s+/g, ' ')).trim())
32 return chars.length > max ? `${chars.slice(0, max - 1).join('')}…` : chars.join('')
33}
34
35const DESK_SEATS: Point[] = Array.from({ length: DESK_COUNT }, (_, i) => ({
36 x: 86 + 22 * (i % 4),
37 y: 42 + 30 * Math.floor(i / 4),
38}))
39
40const MEETING_SEATS: Point[] = [
41 { x: 98, y: 140 },
42 { x: 110, y: 140 },
43 { x: 122, y: 140 },
44 { x: 98, y: 114 },
45 { x: 110, y: 114 },
46 { x: 122, y: 114 },
47 { x: 134, y: 140 },
48 { x: 134, y: 114 },
49]
50
51export const STATIONS: Record<StationId, StationDef> = {
52 office: {
53 name: 'Corner office',
54 tools: "Main's home base, thinking",
55 color: '#d97757',
56 slots: [{ x: 27, y: 50 }],
57 door: { x: 55, y: 62 },
58 },
59 desk: {
60 name: 'Desks',
61 tools: 'Edit, Write, NotebookEdit',
62 color: '#378add',
63 slots: DESK_SEATS,
64 door: null,
65 slotDoors: DESK_SEATS.map(p => ({ x: p.x + 11, y: p.y })),
66 },
67 library: {
68 name: 'Records library',
69 tools: 'Read, Grep, Glob, LSP, Skill, ToolSearch',
70 color: '#7f77dd',
71 slots: [
72 { x: 184, y: 44 },
73 { x: 194, y: 44 },
74 { x: 204, y: 44 },
75 { x: 216, y: 44 },
76 { x: 228, y: 44 },
77 ],
78 door: { x: 172, y: 44 },
79 },
80 phone: {
81 name: 'Phone booths',
82 tools: 'WebFetch, WebSearch',
83 color: '#e24b4a',
84 slots: [
85 { x: 220, y: 78 },
86 { x: 234, y: 78 },
87 ],
88 door: null,
89 },
90 mailroom: {
91 name: 'Mailroom',
92 tools: 'Outside services (mcp__ tools)',
93 color: '#ba7517',
94 slots: [
95 { x: 186, y: 80 },
96 { x: 198, y: 80 },
97 ],
98 door: null,
99 },
100 server: {
101 name: 'Server room',
102 tools: 'Bash, PowerShell, background shells',
103 color: '#639922',
104 slots: [
105 { x: 191, y: 142 },
106 { x: 207, y: 142 },
107 { x: 223, y: 142 },
108 ],
109 door: { x: 184, y: 94 },
110 },
111 meeting: {
112 name: 'Meeting room',
113 tools: 'Briefings, SendMessage',
114 color: '#1d9e75',
115 slots: MEETING_SEATS,
116 door: null,
117 slotDoors: MEETING_SEATS.map(p => ({ x: 68, y: p.y })),
118 },
119 taskboard: {
120 name: 'Task board',
121 tools: 'TodoWrite, Task tools, plan updates',
122 color: '#ef9f27',
123 slots: [
124 { x: 82, y: 20 },
125 { x: 92, y: 20 },
126 ],
127 door: { x: 97, y: 20 },
128 },
129 reception: {
130 name: 'Reception',
131 tools: 'Waiting on you: questions, permissions, plan approval',
132 color: '#d4537e',
133 slots: [
134 { x: 44, y: 144 },
135 { x: 56, y: 144 },
136 ],
137 door: { x: 66, y: 144 },
138 },
139 elevator: {
140 name: 'Elevator',
141 tools: 'Agents arrive and leave',
142 color: '#888780',
143 slots: [{ x: 16, y: 138 }],
144 door: { x: 32, y: 138 },
145 },
146 breakroom: {
147 name: 'Break room',
148 tools: 'Idle agents',
149 color: '#5dcaa5',
150 slots: [
151 { x: 26, y: 82 },
152 { x: 40, y: 84 },
153 { x: 10, y: 102 },
154 { x: 18, y: 102 },
155 { x: 26, y: 102 },
156 ],
157 door: null,
158 },
159}
160
161export const STATION_ORDER: readonly StationId[] = [
162 'office',
163 'desk',
164 'library',
165 'phone',
166 'mailroom',
167 'server',
168 'meeting',
169 'taskboard',
170 'reception',
171 'elevator',
172 'breakroom',
173]
174
175const TOOL_STATIONS: Readonly<Record<string, StationId>> = {
176 Edit: 'desk',
177 MultiEdit: 'desk',
178 Write: 'desk',
179 NotebookEdit: 'desk',
180 Read: 'library',
181 Grep: 'library',
182 Glob: 'library',
183 LSP: 'library',
184 Skill: 'library',
185 ToolSearch: 'library',
186 Bash: 'server',
187 PowerShell: 'server',
188 BashOutput: 'server',
189 KillShell: 'server',
190 Monitor: 'server',
191 TaskStop: 'server',
192 WebFetch: 'phone',
193 WebSearch: 'phone',
194 SendMessage: 'meeting',
195 TodoWrite: 'taskboard',
196 TaskCreate: 'taskboard',
197 TaskUpdate: 'taskboard',
198 TaskList: 'taskboard',
199 TaskGet: 'taskboard',
200 AskUserQuestion: 'reception',
201 ExitPlanMode: 'reception',
202}
203
204export const WAITING_TOOLS: ReadonlySet<string> = new Set(['AskUserQuestion', 'ExitPlanMode'])
205
206export function stationFor(tool: string): StationId {
207 const known = TOOL_STATIONS[tool]
208 if (known !== undefined) return known
209 if (/^mcp__.+__(update_plan|wrap_up)$/.test(tool)) return 'taskboard'
210 if (tool.startsWith('mcp__')) return 'mailroom'
211 return 'desk'
212}
213
214function baseName(path: string): string {
215 const parts = path.split(/[\\/]/)
216 return parts[parts.length - 1] || path
217}
218
219// What the bubble over an agent says about a command. Claude's own description of it is the most particular, so it
220// is used when it fits a bubble; else what the command is for, read from its first real step; else (a program the
221// office does not know) that step as typed, past the `cd` and variables in front of it.
222const BUBBLE_MAX = 28
223function commandTarget(description: string, command: string): string {
224 const said = description.trim()
225 if (said !== '' && Array.from(said).length <= BUBBLE_MAX) return clip(said, BUBBLE_MAX)
226 const intent = commandIntent(command)
227 if (intent.phrase !== '') return clip(intent.phrase, BUBBLE_MAX)
228 return clip(said !== '' ? said : intent.step, BUBBLE_MAX)
229}
230
231// The active item of a to-do list, said as the list says it: "Fixing the login bug".
232function activeTodo(input: Record<string, unknown>): string {
233 const todos = input.todos
234 if (!Array.isArray(todos)) return ''
235 const items = todos.filter((t): t is Record<string, unknown> => typeof t === 'object' && t !== null)
236 const active = items.find(t => t.status === 'in_progress') ?? items.find(t => t.status === 'pending')
237 const words = active === undefined ? '' : (active.activeForm ?? active.content)
238 return typeof words === 'string' ? words : ''
239}
240
241// What a call to an outside service (an MCP tool) is about: the first of the arguments that names a thing.
242const SUBJECT_KEYS = ['title', 'subject', 'name', 'query', 'q', 'path', 'file', 'repo', 'url', 'id', 'text']
243
244export function targetOf(tool: string, input: Record<string, unknown>): string {
245 const str = (key: string): string => {
246 const value = input[key]
247 return typeof value === 'string' ? value : ''
248 }
249 if (str('file_path')) return clip(baseName(str('file_path')))
250 if (str('notebook_path')) return clip(baseName(str('notebook_path')))
251 if (tool === 'TodoWrite' && activeTodo(input) !== '') return clip(activeTodo(input), BUBBLE_MAX)
252 if (str('command')) return commandTarget(str('description'), str('command'))
253 if (str('pattern')) {
254 // A search says where it looks when it was pointed somewhere: `login in src`.
255 const where = str('path') || str('glob')
256 return clip(where === '' ? str('pattern') : `${str('pattern')} in ${baseName(where)}`)
257 }
258 if (str('query')) return clip(str('query'))
259 if (str('url')) {
260 try {
261 return clip(new URL(str('url')).host)
262 } catch {
263 return clip(str('url'))
264 }
265 }
266 if (str('skill')) return clip(str('skill'))
267 if (str('to')) return clip(str('to'))
268 if (str('description')) return clip(str('description'))
269 if (str('subject')) return clip(str('subject'))
270 if (tool.startsWith('mcp__')) {
271 const key = SUBJECT_KEYS.find(k => str(k) !== '')
272 return clip(key === undefined ? (tool.split('__')[1] ?? tool) : str(key))
273 }
274 return ''
275}
276
277// A short, readable excerpt of free text (a brief, a report, a message): Markdown heading marks, bold and code
278// ticks dropped, everything on one line, cut to `max` characters.
279export function gist(text: string, max: number): string {
280 return clip(text.replace(/^\s*#{1,6}\s+/gm, '').replace(/\*\*|__|`/g, ''), max)
281}
282
283// How long the one-line excerpt of a brief or a report is.
284export const EXCERPT = 200
285
286// Free text kept to be read in full (a brief, a report): line breaks stay, as Markdown needs them, and so do
287// tabs; every other control character goes, Windows line ends become plain ones, runs of blank lines shrink
288// to one, and it is cut to `max` characters by code point.
289export function fullText(text: string, max: number): string {
290 const lines = stripControls(text.replace(/\r\n?/g, '\n')).replace(/\n{3,}/g, '\n\n').trim()
291 const chars = Array.from(lines)
292 return chars.length > max ? `${chars.slice(0, max - 1).join('')}…` : lines
293}
294
295// The plain-English gist of a call, from what Claude wrote into its input: the description it gives every
296// command (falling back to what the command is commonly for), or the summary of a message. Empty otherwise.
297export function detailOf(tool: string, input: Record<string, unknown>): string {
298 const str = (key: string): string => {
299 const value = input[key]
300 return typeof value === 'string' ? value : ''
301 }
302 if (tool === 'Bash' || tool === 'PowerShell') return gist(str('description'), 60) || explainCommand(str('command'))
303 if (tool === 'SendMessage') return gist(str('summary') || (str('message').split('\n')[0] ?? ''), 48)
304 return ''
305}
306
307export function todoCounts(input: Record<string, unknown>): { done: number; open: number } | null {
308 const list = Array.isArray(input.todos) ? input.todos : Array.isArray(input.items) ? input.items : null
309 if (list === null) return null
310 let done = 0
311 let open = 0
312 for (const item of list) {
313 if ((item as { status?: unknown } | null)?.status === 'completed') done += 1
314 else open += 1
315 }
316 return { done, open }
317}
318
319export function slotPoint(station: StationId, slot: number): Point {
320 const { slots } = STATIONS[station]
321 const exact = slots[slot]
322 if (exact !== undefined) return exact
323 const last = slots[slots.length - 1] as Point
324 const k = slot - slots.length + 1
325 return { x: clamp(last.x - 7 * k, 4, WIDTH - 4), y: clamp(last.y + 3 * k, 16, HEIGHT - 2) }
326}
327
328export function doorOf(station: StationId, slot: number): Point {
329 const def = STATIONS[station]
330 return def.slotDoors?.[slot] ?? def.door ?? slotPoint(station, slot)
331}
332
333function dedupe(points: readonly Point[]): Point[] {
334 const out: Point[] = []
335 for (const p of points) {
336 const last = out[out.length - 1]
337 if (last === undefined || Math.abs(last.x - p.x) > 0.01 || Math.abs(last.y - p.y) > 0.01) out.push(p)
338 }
339 return out
340}
341
342export function route(from: Point, fromDoor: Point, to: Point, toDoor: Point): Point[] {
343 return dedupe([
344 from,
345 { x: fromDoor.x, y: from.y },
346 fromDoor,
347 { x: fromDoor.x, y: CORRIDOR_Y },
348 { x: toDoor.x, y: CORRIDOR_Y },
349 toDoor,
350 { x: toDoor.x, y: to.y },
351 to,
352 ])
353}
354
355const dist = (a: Point, b: Point): number => Math.hypot(b.x - a.x, b.y - a.y)
356
357export function pathLength(points: readonly Point[]): number {
358 let total = 0
359 for (let i = 1; i < points.length; i++) total += dist(points[i - 1] as Point, points[i] as Point)
360 return total
361}
362
363export function splitAt(points: readonly Point[], fraction: number): Point[] {
364 if (points.length === 0) return []
365 let remaining = pathLength(points) * clamp(fraction, 0, 1)
366 for (let i = 1; i < points.length; i++) {
367 const a = points[i - 1] as Point
368 const b = points[i] as Point
369 const seg = dist(a, b)
370 if (remaining <= seg) {
371 const t = seg === 0 ? 0 : remaining / seg
372 return [{ x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t }, ...points.slice(i)]
373 }
374 remaining -= seg
375 }
376 return [points[points.length - 1] as Point]
377}
378
379export function pointAlong(points: readonly Point[], fraction: number): Point {
380 return splitAt(points, fraction)[0] ?? { x: 0, y: 0 }
381}
382
383const isOnCorridor = (p: Point): boolean => Math.abs(p.y - CORRIDOR_Y) < 0.01
384
385// The way back to the corridor from `fraction` along a walk, staying on the walk's own path: ahead to its next
386// point on the corridor or back to its last one, whichever is shorter. A walk that changes course takes it before
387// setting off for somewhere else, rather than cutting from where it stands through a wall. It starts where the
388// walker is and ends on the corridor (or where the walker is, when the path never reaches it).
389export function toCorridor(points: readonly Point[], fraction: number): Point[] {
390 const ahead = splitAt(points, fraction)
391 const here = ahead[0]
392 if (here === undefined) return []
393 if (isOnCorridor(here)) return [here]
394 const behind = splitAt([...points].reverse(), 1 - clamp(fraction, 0, 1))
395 const reach = (path: readonly Point[]): Point[] | null => {
396 const i = path.findIndex(isOnCorridor)
397 return i < 0 ? null : [here, ...path.slice(1, i + 1)]
398 }
399 const forward = reach(ahead)
400 const back = reach(behind)
401 if (forward === null || back === null) return forward ?? back ?? [here]
402 return pathLength(back) < pathLength(forward) ? back : forward
403}
404hooks/narrate.ts 143 lines1import type { Activity, OfficeEvent, Scene } from '../types'
2import { gist, stationFor } from './stations'
3
4export const REPORT_IN_FEED = 60
5
6function nameOf(scene: Scene, id: string | null): string {
7 if (id === null) return 'An agent'
8 return scene.agents[id]?.label ?? 'An agent'
9}
10
11// "Run the tests" continues a sentence as "run the tests"; "NPM", "CI" and other capitals stay as they are.
12const lowerFirst = (text: string): string => (/^[A-Z][a-z]/.test(text) ? `${text[0]?.toLowerCase() ?? ''}${text.slice(1)}` : text)
13
14// `mcp__github__create_issue` is GitHub's "create issue".
15function service(tool: string): { name: string; action: string } {
16 const [, name = tool, action = ''] = tool.split('__')
17 return { name, action: action.replace(/_+/g, ' ').trim() }
18}
19
20// What an agent is doing, said the way you would say it of a colleague, with no subject: "reading auth.ts",
21// "running a command to test the code". The feed puts a name in front of it; the panel shows it as is.
22export function doing(activity: Pick<Activity, 'tool' | 'target' | 'detail'>): string {
23 const { tool, target, detail } = activity
24 const t = target === '' ? '' : ` ${target}`
25 switch (tool) {
26 case 'Read':
27 return `reading${t}`
28 case 'Edit':
29 case 'MultiEdit':
30 return `editing${t}`
31 case 'Write':
32 return `writing${t}`
33 case 'NotebookEdit':
34 return `editing the notebook${t}`
35 case 'Grep':
36 return `searching the files for${t}`
37 case 'Glob':
38 return `looking for files named${t}`
39 case 'LSP':
40 return t === '' ? 'asking the code index' : `asking the code index about${t}`
41 case 'ToolSearch':
42 return 'looking up which tools it can use'
43 case 'Skill':
44 return t === '' ? 'reading a manual' : `reading the${t} manual`
45 case 'Bash':
46 case 'PowerShell':
47 return detail === '' ? `running a command:${t}` : `running a command to ${lowerFirst(detail)}`
48 case 'BashOutput':
49 return 'checking on a background command'
50 case 'Monitor':
51 return 'keeping an eye on a background job'
52 case 'KillShell':
53 case 'TaskStop':
54 return 'stopping a background job'
55 case 'WebSearch':
56 return `searching the web for${t}`
57 case 'WebFetch':
58 return `reading a web page on${t}`
59 case 'SendMessage':
60 return `messaging${t}${detail === '' ? '' : `: ${detail}`}`
61 case 'AskUserQuestion':
62 return 'waiting for you to answer a question'
63 case 'ExitPlanMode':
64 return 'waiting for you to approve a plan'
65 }
66 const station = stationFor(tool)
67 if (station === 'taskboard') return t === '' ? 'updating the task board' : `updating the task board: ${target}`
68 if (station === 'mailroom') {
69 const { name, action } = service(tool)
70 return action === '' ? `using ${name}${t}` : `using ${name} to ${action}`
71 }
72 return `using ${tool}${t}`
73}
74
75// What a permission prompt is asking for, in words: "run a command" rather than "use Bash".
76function permissionFor(tool: string): string {
77 switch (tool) {
78 case 'Bash':
79 case 'PowerShell':
80 return 'run a command'
81 case 'Edit':
82 case 'MultiEdit':
83 case 'Write':
84 case 'NotebookEdit':
85 return 'change a file'
86 case 'WebFetch':
87 case 'WebSearch':
88 return 'go on the web'
89 }
90 return tool.startsWith('mcp__') ? `use ${service(tool).name}` : `use ${tool}`
91}
92
93const quoted = (report: string): string => {
94 const excerpt = gist(report, REPORT_IN_FEED)
95 return excerpt === '' ? '' : `: ${excerpt}`
96}
97
98// The line for the moment a boss stops waiting: every helper it hired to work while it waited has reported.
99export const allBackLine = (boss: string): string => `${boss} has every report back and is reviewing the results`
100
101export function narrate(scene: Scene, ev: OfficeEvent): string | null {
102 switch (ev.kind) {
103 case 'spawned': {
104 const who = nameOf(scene, ev.id)
105 const boss = nameOf(scene, ev.parentId)
106 if (ev.isTeammate) {
107 return ev.isResume ? `${boss} brought ${who} back to the team: ${ev.description}` : `${boss} added ${who} to the team: ${ev.description}`
108 }
109 const verb = ev.isResume ? `called ${who} back` : `hired ${who}`
110 if (ev.isBackground) return `${boss} ${verb} to work alongside it: ${ev.description}`
111 return `${boss} ${verb} and is waiting for its report: ${ev.description}`
112 }
113 case 'toolStarted':
114 return `${nameOf(scene, ev.agentId)} is ${doing(ev)}`
115 case 'toolEnded':
116 return ev.isError ? `${nameOf(scene, ev.agentId)} hit an error` : null
117 case 'waiting':
118 return `${nameOf(scene, ev.agentId)} needs your permission to ${permissionFor(ev.tool)}`
119 case 'turnStarted':
120 return ev.isContinuation ? 'Main picked up where it left off' : 'You gave Main a new task'
121 case 'turnEnded':
122 return 'Main finished and is waiting for your next message'
123 case 'handedBack': {
124 const agent = scene.agents[ev.agentId]
125 if (agent === undefined) return null
126 const boss = nameOf(scene, agent.parentId)
127 const isStopped = ev.reason === 'aborted'
128 const isFailed = ev.reason === 'error' || ev.reason === 'refusal'
129 if (agent.isTeammate) {
130 return isStopped
131 ? `${agent.label} was stopped and took a break`
132 : `${agent.label} reported to ${boss} and took a break${quoted(ev.report)}`
133 }
134 if (isStopped) return `${agent.label} was stopped and left`
135 if (isFailed) return `${agent.label} ran into a problem, told ${boss} and left${quoted(ev.report)}`
136 return `${agent.label} handed its report to ${boss} and left${quoted(ev.report)}`
137 }
138 case 'todos':
139 case 'tick':
140 return null
141 }
142}
143hooks/roles.ts 61 lines1// What the office calls each kind of agent, and one line that explains the job to someone who has never seen an
2// agent before. The engine's type names (`Explore`, `general-purpose`) are written for Claude; these are for people.
3
4export type Role = { title: string; blurb: string }
5
6export const COORDINATOR: Role = {
7 title: 'Coordinator',
8 blurb: 'Talks with you, splits the work into jobs, hires helpers and puts their reports together',
9}
10
11const ROLES: Readonly<Record<string, Role>> = {
12 Explore: { title: 'Researcher', blurb: 'Reads and searches, then reports what it found. Changes nothing' },
13 Plan: { title: 'Planner', blurb: 'Works out a step-by-step plan for a job. Changes nothing' },
14 'general-purpose': { title: 'Assistant', blurb: 'Can read, edit and run commands to finish one job' },
15 claude: { title: 'Assistant', blurb: 'Can read, edit and run commands to finish one job' },
16 fork: { title: 'Clone', blurb: 'A copy of its boss that knows everything its boss knew, sent off to do a side job' },
17 'claude-code-guide': { title: 'Guide', blurb: 'Looks up how Claude Code itself works' },
18 'web-fetch': { title: 'Web reader', blurb: 'Reads web pages and reports what they say' },
19 contractor: { title: 'Contractor', blurb: 'A helper the office did not see being hired, so its job is unknown' },
20}
21
22// `code-reviewer`, `my-plugin:code-reviewer` and `codeReviewer` all read as "Code reviewer".
23export function humanize(type: string): string {
24 const words = (type.split(':').pop() ?? type)
25 .replace(/([a-z])([A-Z])/g, '$1 $2')
26 .replace(/[-_]+/g, ' ')
27 .trim()
28 .toLowerCase()
29 return words === '' ? 'Helper' : `${words[0]?.toUpperCase() ?? ''}${words.slice(1)}`
30}
31
32export function roleFor(type: string): Role {
33 if (type === 'main') return COORDINATOR
34 return ROLES[type] ?? { title: humanize(type), blurb: 'A specialist helper set up for one kind of job' }
35}
36
37// The model an agent ran on, the way people say it: `claude-haiku-5-5` is Haiku 5.5, `claude-sonnet-4-5-20250929`
38// Sonnet 4.5, `claude-3-5-haiku-20241022` just Haiku (the number before the name is not read as its version).
39// An id with no family name in it is shown as it is.
40export function modelName(id: string): string {
41 const m = /(opus|sonnet|haiku|fable)(?:-(\d{1,2})(?:-(\d{1,2}))?(?!\d))?/i.exec(id)
42 if (m === null) return id
43 const family = `${m[1]?.[0]?.toUpperCase() ?? ''}${m[1]?.slice(1).toLowerCase() ?? ''}`
44 const version = m[2] === undefined ? '' : ` ${m[2]}${m[3] === undefined ? '' : `.${m[3]}`}`
45 return `${family}${version}`
46}
47
48// 850, 3.4k, 38k, 1.3M.
49export function tokenCount(n: number): string {
50 if (n < 1000) return String(n)
51 if (n < 10_000) return `${(n / 1000).toFixed(1).replace(/\.0$/, '')}k`
52 if (n < 1_000_000) return `${Math.round(n / 1000)}k`
53 return `${(n / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`
54}
55
56// A name the engine gave an agent reads as a name: `scout` is shown as Scout. Messages still go to `scout`.
57export const asName = (name: string): string => `${name[0]?.toUpperCase() ?? ''}${name.slice(1)}`
58
59// A kind of agent Claude Code itself ships, whose name says nothing about anyone's own setup.
60export const isBuiltIn = (type: string): boolean => type === 'main' || Object.prototype.hasOwnProperty.call(ROLES, type)
61