From 0270262e6f3328b14eb733c6d58da760e09ed6c8 Mon Sep 17 00:00:00 2001 From: julienwuthrich-ant Date: Mon, 23 Nov 2026 10:41:10 -0800 Subject: [PATCH 001/120] Lists and traces: a second press removes no other comment, a failed search says so, a stopped call reads "stopped" Review comments: the rows of comments whose line or file left the diff were keyed by position (DiffView) or by joined text (DiffsLens). After "Remove", the same row, with the focus on its button, became the next comment's. One helper (commentKeys) now gives each comment a key of its own, so the row goes with its comment. Code search (Knowledge): a search that failed showed the empty "Ask the index." state. It now shows the failure with "Try again", and a search still on its way no longer answers after the box was cleared. Traces: a call with no result whose turn ended, whose process is gone, or whose helper is over read "running" for ever and counted as running. It is "stopped" now: no duration, not running, not failed. A helper's call stays running while the helper works on after the turn. Notices: when a long turn's start had left the event log, each notice was a row of its own until the turn ended. Until the log says that a turn started or ended, they are one row now. Check the work: every focus of the window asked the core, which starts git. A focus now asks once in 10 seconds for an agent; a focus inside that time is asked when the time is over. A click on the button always reads. Also: the empty line of the Messages tab, and the doc comment of itemId. Co-Authored-By: Claude Fable 5.2 --- src/home/__tests__/notices.test.ts | 33 +++++++++- src/home/notices.ts | 21 ++++--- src/home/spine.ts | 6 +- src/lib/__tests__/checksFocus.test.ts | 89 +++++++++++++++++++++++++++ src/lib/__tests__/commentKeys.test.ts | 50 +++++++++++++++ src/lib/__tests__/traces.test.ts | 61 ++++++++++++++++-- src/lib/state/agentChecks.svelte.ts | 31 +++++++++- src/lib/util/__tests__/search.test.ts | 15 ++++- src/lib/util/review.ts | 13 ++++ src/lib/util/search.ts | 13 ++++ src/lib/util/traces.ts | 49 ++++++++++++--- src/rooms/changes/DiffView.svelte | 6 +- src/rooms/changes/DiffsLens.svelte | 5 +- src/rooms/knowledge/SearchLens.svelte | 24 +++++++- src/sheet/AgentChecks.svelte | 5 +- src/sheet/AgentMessagesTab.svelte | 2 +- src/sheet/AgentTracesTab.svelte | 4 +- 17 files changed, 388 insertions(+), 39 deletions(-) create mode 100644 src/lib/__tests__/checksFocus.test.ts create mode 100644 src/lib/__tests__/commentKeys.test.ts diff --git a/src/home/__tests__/notices.test.ts b/src/home/__tests__/notices.test.ts index e7194e9f..f3056239 100644 --- a/src/home/__tests__/notices.test.ts +++ b/src/home/__tests__/notices.test.ts @@ -65,12 +65,39 @@ describe('noticeRows', () => { it('a log that begins inside a turn: what was told before that turn ended is one row', () => { expect(words([notice('a'), notice('b'), notice('c'), turnEnd(), notice('d')])).toEqual([['a', 'b', 'c'], ['d']]); - // Nothing says a turn ran: they stay rows of their own. - expect(words([notice('a'), notice('b'), turn(), notice('c')])).toEqual([['a'], ['b'], ['c']]); + // The turn that starts next is another one, with a row of its own. + expect(words([notice('a'), notice('b'), turn(), notice('c')])).toEqual([['a', 'b'], ['c']]); + }); + + it('a long turn whose start left the log is one row while it runs, and still one when it ends', () => { + // The log holds the newest events only: the `turn_started` of this turn is not in it any more. + const hook = Array.from({ length: 30 }, (_, i) => notice(`hook: checked call ${i + 1}`)); + const running = noticeRows(hook, 'l1'); + expect(running).toHaveLength(1); + expect(running[0].map((n) => n.eventId)).toEqual(hook.map((e) => e.id)); + expect(moreOf(running[0])).toBe('and 29 more'); + // The row does not change when the turn's end comes: the same notes, so the same key. + const ended = noticeRows([...hook, turnEnd()], 'l1'); + expect(ended).toHaveLength(1); + expect(ended[0]).toEqual(running[0]); + }); + + it('a turn end between two groups, with no turn start in the log, gives two rows', () => { + const first = [notice('a'), notice('b'), notice('c')]; + const second = [notice('d'), notice('d')]; + expect(words([...first, turnEnd(), ...second])).toEqual([['a', 'b', 'c'], ['d', 'd']]); + // After the end the log says that no turn runs: other words are a row of their own again. + expect(words([...first, turnEnd(), notice('d'), notice('e')])).toEqual([['a', 'b', 'c'], ['d'], ['e']]); + // The process that ended closes the turn too. + expect(words([...first, ev({ type: 'exited', code: 1 }), notice('d'), notice('e')])).toEqual([['a', 'b', 'c'], ['d'], ['e']]); }); it("another agent's turns and notices are not this agent's", () => { - expect(words([notice('mine, outside'), turn('w1'), notice('theirs', 'w1'), notice('mine, still outside'), turnEnd('w1')])).toEqual([['mine, outside'], ['mine, still outside']]); + // No turn of `l1` runs. Were the worker's turn taken for its own, the words told during it would be a row apart. + const events = [turn(), turnEnd(), notice('Goal: ship it'), turn('w1'), notice('theirs', 'w1'), notice('Goal: ship it'), turnEnd('w1'), notice('Goal: ship it')]; + expect(words(events)).toEqual([['Goal: ship it', 'Goal: ship it', 'Goal: ship it']]); + // And the worker's end does not close a turn of `l1` whose start left the log. + expect(words([notice('a'), turnEnd('w1'), notice('b')])).toEqual([['a', 'b']]); }); it('says how many there are: a count for the same words, "more" for different ones', () => { diff --git a/src/home/notices.ts b/src/home/notices.ts index 4d669641..71d87f12 100644 --- a/src/home/notices.ts +++ b/src/home/notices.ts @@ -13,14 +13,16 @@ const noteOf = new WeakMap(); * The agent's notices as the rows that show them, oldest first (in a row: oldest first too). * Everything told between the start and the end of one turn is one row. A notice outside any * turn is a row of its own; the same words told again right after it join its row. - * The log may begin inside a turn: what was told before the first turn end it holds, with no - * turn start before it, was told in that turn. + * The log may begin inside a turn whose start it does not hold any more (a long turn): until + * the log says that a turn started or ended, what is told is one row too, as in a turn. Nothing + * between those notices says that they are of different turns, and the row lists them all. */ export function noticeRows(events: EventRow[], agentId: string): Note[][] { const rows: Note[][] = []; - /** unknown: nothing in the log says yet whether a turn runs. */ - let turn: 'unknown' | 'open' | 'none' = 'unknown'; - /** The row of the turn that runs. */ + /** The log says that no turn runs: a turn or the process ended, and no turn started since. + * At the log's start it does not say so: a turn may run whose start left the log. */ + let outside = false; + /** The row of the turn that runs, or that may run. */ let inTurn: Note[] | null = null; /** The newest row outside a turn, while nothing came after it. */ let alone: Note[] | null = null; @@ -29,22 +31,21 @@ export function noticeRows(events: EventRow[], agentId: string): Note[][] { const k = ev.kind; switch (k.type) { case 'turn_started': - turn = 'open'; + outside = false; inTurn = alone = null; break; case 'turn_completed': - if (turn === 'unknown' && rows.length > 1) rows.splice(0, rows.length, rows.flat()); - turn = 'none'; + outside = true; inTurn = alone = null; break; case 'exited': - turn = 'none'; + outside = true; inTurn = null; break; case 'notice': { let note = noteOf.get(ev); if (!note) noteOf.set(ev, (note = { eventId: ev.id, ts: ev.ts, text: k.text })); - if (turn === 'open') { + if (!outside) { if (!inTurn) rows.push((inTurn = [])); inTurn.push(note); } else if (alone && alone[0].text === note.text) alone.push(note); diff --git a/src/home/spine.ts b/src/home/spine.ts index 87416b84..baffa574 100644 --- a/src/home/spine.ts +++ b/src/home/spine.ts @@ -37,8 +37,10 @@ export type Item = * The message of the agent this row shows: its key, and the words it reads while they are * written. Null for a chat row with no held message behind it: the message is not held * (any more), the row's author is not the thread's agent (another Lead served the request - * then, or the thread has no agent now), or the core posted the row for a turn result - * that no message carried. + * then, the thread has no agent now, or a Lead wrote to a worker: the core posts that in + * the worker's thread with the Lead as author), the row's id belongs to a later message by + * now (a CLI used the id again: a newer row shows that message, or it was said after this + * row), or the core posted the row for a turn result that no message carried. */ itemId: string | null; text: string; diff --git a/src/lib/__tests__/checksFocus.test.ts b/src/lib/__tests__/checksFocus.test.ts new file mode 100644 index 00000000..b7208c45 --- /dev/null +++ b/src/lib/__tests__/checksFocus.test.ts @@ -0,0 +1,89 @@ +// "Check the work" asks the core again when Codly's window gets the focus back (a file you +// changed in your editor is not the checked one any more). Each question starts git in the +// core, so a window that gets the focus again and again does not ask each time. +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { api } from '../api'; +import type { AgentCheck } from '../gen/AgentCheck'; +import { agentChecks, FOCUS_READ_MS } from '../state/agentChecks.svelte'; + +const idle: AgentCheck = { running: false, last: null }; + +describe('the focus of the window and “Check the work”', () => { + /** Each test has an agent of its own: the state keeps when each agent was last asked about. */ + let n = 0; + let agent = ''; + /** The agents the core was asked about, in order. */ + const asked = () => vi.mocked(api.agentCheckState).mock.calls.map(([id]) => id); + /** The clock moves on: the time the state reads, and the questions that wait for it. */ + const later = (ms: number) => vi.advanceTimersByTime(ms); + + beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(1_760_000_000_000); + vi.spyOn(api, 'agentCheckState').mockResolvedValue(idle); + agent = `focus-${++n}`; + }); + afterEach(() => { + vi.runOnlyPendingTimers(); + vi.useRealTimers(); + vi.restoreAllMocks(); + agentChecks.state = {}; + agentChecks.failed = {}; + agentChecks.unread = {}; + }); + + it('asks at once when the agent was not asked about for a while', () => { + agentChecks.focused(agent); + expect(asked()).toEqual([agent]); + later(FOCUS_READ_MS); + agentChecks.focused(agent); + expect(asked()).toEqual([agent, agent]); + }); + + it('asks once for many focuses in a row, and once more when the time is over', () => { + agentChecks.focused(agent); + for (const ms of [50, 850, 3100, 5999]) { + later(ms); + agentChecks.focused(agent); + } + // 9999 ms after the first question: still the only one. + expect(asked()).toEqual([agent]); + // The focuses in between are not dropped: a file changed before the last of them is seen + // when the time is over, with one question for all of them. + later(1); + expect(asked()).toEqual([agent, agent]); + // Nothing waits any more: no further question comes without a focus. + later(FOCUS_READ_MS * 3); + expect(asked()).toEqual([agent, agent]); + }); + + it('counts the time from the last question, whoever asked it', async () => { + // The Git tab opened and read the worktree: the focus right after it waits its turn. + await agentChecks.load(agent); + later(2000); + agentChecks.focused(agent); + expect(asked()).toEqual([agent]); + later(FOCUS_READ_MS - 2001); + expect(asked()).toEqual([agent]); + later(1); + expect(asked()).toEqual([agent, agent]); + }); + + it('is by agent: one agent’s focus does not hold back another’s', () => { + agentChecks.focused(agent); + agentChecks.focused(`${agent}-other`); + expect(asked()).toEqual([agent, `${agent}-other`]); + }); + + it('a click on “Check the work” always reads, also right after a focus', async () => { + const run = vi.spyOn(api, 'checkAgent').mockResolvedValue([]); + agentChecks.focused(agent); + await agentChecks.run(agent); + expect(run).toHaveBeenCalledTimes(1); + // The focus asked, and the run asked again when it ended. + expect(asked()).toEqual([agent, agent]); + await agentChecks.run(agent); + expect(run).toHaveBeenCalledTimes(2); + expect(asked()).toEqual([agent, agent, agent]); + }); +}); diff --git a/src/lib/__tests__/commentKeys.test.ts b/src/lib/__tests__/commentKeys.test.ts new file mode 100644 index 00000000..aa0e2936 --- /dev/null +++ b/src/lib/__tests__/commentKeys.test.ts @@ -0,0 +1,50 @@ +// The rows of your review comments each hold a "Remove" button. A row is its comment's own: +// when the comment is removed the row goes with it, and the button that had the focus is not +// handed to the next comment (a second press would remove a comment you did not mean). +import { describe, expect, it } from 'vitest'; +import { commentKeys, withComment, type ReviewComment } from '../util/review'; + +const on = (path: string, line: number | null, quote: string | null, side: 'old' | 'new' | null = line == null ? null : 'new'): ReviewComment => ({ path, line, side, quote, text: 'Rename this.' }); + +describe('commentKeys', () => { + it('gives each comment a key no other has, also with the same place and the same quoted line', () => { + const list = [ + on('src/a.ts', 3, '+const a = 1;'), + on('src/b.ts', 3, '+const a = 1;'), // the same line and words in another file + on('src/a.ts', 3, '-const a = 1;', 'old'), // the removed line with the same number + on('src/a.ts', 3, '+const a = 2;'), // the same line as it read before the worker changed it + on('src/a.ts', null, null), // the whole file + ]; + const keys = commentKeys(list); + expect(keys).toHaveLength(list.length); + expect(new Set(keys).size).toBe(list.length); + }); + + it('keeps the parts of a key apart, whatever a path or a quoted line holds', () => { + // Joined with no mark between them, these two would read the same. + const keys = commentKeys([on('a new:1', 12, '+x'), on('a', 1, ' new:12+x')]); + expect(keys[0]).not.toBe(keys[1]); + }); + + it('gives two comments that are equal in all of it different keys', () => { + // The review state keeps one comment per place; a list that still holds two must not stop the view. + const twin = on('src/a.ts', 3, '+const a = 1;'); + const keys = commentKeys([twin, { ...twin }, on('src/a.ts', 4, '+const b = 2;')]); + expect(new Set(keys).size).toBe(3); + }); + + it('a comment keeps its key from one render to the next, also when the one before it is removed', () => { + const first = on('src/a.ts', 3, '+const a = 1;'); + const second = on('src/a.ts', 9, '+const b = 2;'); + const third = on('src/c.ts', null, null); + const list = [first, second, third]; + const before = commentKeys(list); + expect(commentKeys([...list])).toEqual(before); + + // "Remove" on the first one: the others keep their keys, so the first row is destroyed + // (with the focus on its button) and the second comment does not move into it. + const after = commentKeys(withComment(list, first, '')); + expect(after).toEqual([before[1], before[2]]); + expect(after).not.toContain(before[0]); + }); +}); diff --git a/src/lib/__tests__/traces.test.ts b/src/lib/__tests__/traces.test.ts index 7712547d..bccd8e51 100644 --- a/src/lib/__tests__/traces.test.ts +++ b/src/lib/__tests__/traces.test.ts @@ -58,9 +58,9 @@ describe('buildTraces', () => { for (const end of [{ type: 'turn_completed', status: 'interrupted', result_text: null, duration_ms: null }, { type: 'exited', code: null }]) { const t = buildTraces([started('a', T0, 'c1'), ev('a', T0 + 400, end), started('a', T0 + 60_000, 'c1', 'Read'), done('a', T0 + 60_300, 'c1')], 'a'); // The later call has its own start: its duration is not measured from the turn before. - expect(t.map((c) => [c.name, c.start, c.durationMs, c.ok])).toEqual([ - ['Bash', T0, null, null], - ['Read', T0 + 60_000, 300, true], + expect(t.map((c) => [c.name, c.start, c.durationMs, c.ok, c.stopped])).toEqual([ + ['Bash', T0, null, null, true], + ['Read', T0 + 60_000, 300, true, false], ]); expect(summarize(t)).toMatchObject({ calls: 2, totalMs: 300 }); } @@ -69,7 +69,60 @@ describe('buildTraces', () => { it('still pairs a result that comes after the turn with the call it belongs to', () => { const t = buildTraces([started('a', T0, 'c1'), ev('a', T0 + 400, { type: 'turn_completed', status: 'completed', result_text: null, duration_ms: null }), done('a', T0 + 900, 'c1')], 'a'); expect(t).toHaveLength(1); - expect(t[0]).toMatchObject({ start: T0, durationMs: 900, ok: true }); + expect(t[0]).toMatchObject({ start: T0, durationMs: 900, ok: true, stopped: false }); + }); + + describe('a call with no completion', () => { + const turnEnd = (ts: number, status = 'completed') => ev('a', ts, { type: 'turn_completed', status, result_text: null, duration_ms: null }); + const helper = (ts: number, call_id: string, status: string) => ev('a', ts, { type: 'sub_agent', call_id, description: 'Run the tests', status }); + /** `call` is a call of the helper that the call `of` started. */ + const ofHelper = (ts: number, of: string, call: string) => + ev('a', ts, { type: 'sub_agent_progress', call_id: of, name: null, step: null, tool_call_id: call, tool_uses: null, tokens: null, report: null }); + + it('is running while its turn runs', () => { + const t = buildTraces([ev('a', T0 - 10, { type: 'turn_started', input: null }), started('a', T0, 'c1')], 'a'); + expect(t[0]).toMatchObject({ ok: null, durationMs: null, stopped: false }); + expect(summarize(t)).toEqual({ calls: 1, failed: 0, running: 1, totalMs: 0 }); + }); + + it('is stopped once its turn or its process ended: not running, not failed, no duration', () => { + for (const end of [turnEnd(T0 + 400), turnEnd(T0 + 400, 'interrupted'), ev('a', T0 + 400, { type: 'exited', code: null })]) { + const t = buildTraces([started('a', T0, 'c1'), end, started('a', T0 + 9000, 'c2')], 'a'); + expect(t.map((c) => [c.callId, c.ok, c.durationMs, c.source, c.stopped])).toEqual([ + ['c1', null, null, null, true], + ['c2', null, null, null, false], // a call of the next turn runs + ]); + expect(summarize(t)).toEqual({ calls: 2, failed: 0, running: 1, totalMs: 0 }); + } + // Another agent's turn end stops nothing here. + const other = buildTraces([started('a', T0, 'c1'), ev('b', T0 + 400, { type: 'turn_completed', status: 'completed', result_text: null, duration_ms: null })], 'a'); + expect(other[0].stopped).toBe(false); + }); + + it("stays running when it is a helper's and the helper works on after the turn", () => { + // A helper in the background: the call that started it returned, the turn ended, the helper works on. + const launched = [helper(T0, 'h1', 'running'), started('a', T0, 'h1', 'Agent'), done('a', T0 + 100, 'h1'), started('a', T0 + 200, 'c1'), ofHelper(T0 + 200, 'h1', 'c1'), started('a', T0 + 300, 'own')]; + const after = buildTraces([...launched, turnEnd(T0 + 400)], 'a'); + // The agent's own call ended with the turn; the helper's did not. + expect(after.map((c) => [c.callId, c.stopped])).toEqual([['h1', false], ['c1', false], ['own', true]]); + expect(summarize(after)).toMatchObject({ running: 1, failed: 0 }); + + // Its result comes later: a finished call. + const finished = buildTraces([...launched, turnEnd(T0 + 400), done('a', T0 + 900, 'c1')], 'a'); + expect(finished[1]).toMatchObject({ callId: 'c1', ok: true, durationMs: 700, stopped: false }); + + // The helper is over with the call still open: no result comes any more. + const over = buildTraces([...launched, turnEnd(T0 + 400), helper(T0 + 900, 'h1', 'completed')], 'a'); + expect(over[1]).toMatchObject({ callId: 'c1', ok: null, stopped: true }); + expect(summarize(over)).toMatchObject({ running: 0, failed: 0 }); + + // A turn that was interrupted, and a process that ended, take the helper with them. + for (const end of [turnEnd(T0 + 400, 'interrupted'), turnEnd(T0 + 400, 'failed'), ev('a', T0 + 400, { type: 'exited', code: 1 })]) { + const t = buildTraces([...launched, end], 'a'); + expect(t.map((c) => c.stopped)).toEqual([false, true, true]); + expect(summarize(t)).toMatchObject({ running: 0, failed: 0 }); + } + }); }); it("says which calls a subagent made, and leaves the agent's own unmarked", () => { diff --git a/src/lib/state/agentChecks.svelte.ts b/src/lib/state/agentChecks.svelte.ts index 4b43677c..8688f32c 100644 --- a/src/lib/state/agentChecks.svelte.ts +++ b/src/lib/state/agentChecks.svelte.ts @@ -7,6 +7,10 @@ import type { AgentCheck } from '../gen/AgentCheck'; const message = (e: unknown) => (e instanceof Error ? e.message : String(e)); +/** When the window gets the focus, the core is asked about an agent once in this time at most: + * each question makes it compare the agent's files, which starts git. */ +export const FOCUS_READ_MS = 10_000; + class AgentChecks { /** What the core last said about each agent. */ state = $state>({}); @@ -16,11 +20,16 @@ class AgentChecks { unread = $state>({}); /** The newest question to the core about each agent: an older answer that comes later is dropped. */ private asked: Record = {}; + /** When the core was last asked about each agent. */ + private askedAt: Record = {}; + /** By agent: the question of a focus that came too soon after the last one, until it is asked. */ + private waiting: Record> = {}; /** Ask the core what it has for the agent now: when its Git tab opens, when its worktree was - * read again, when Codly's window gets the focus back, and while a run is on its way. */ + * read again, after a run, and while a run is on its way. (The window's focus: `focused`.) */ async load(agentId: string) { const mine = (this.asked[agentId] = (this.asked[agentId] ?? 0) + 1); + this.askedAt[agentId] = Date.now(); try { const now = await api.agentCheckState(agentId); if (this.asked[agentId] !== mine) return; @@ -31,6 +40,26 @@ class AgentChecks { } } + /** + * Codly's window got the focus back: a file you changed in your editor meanwhile is not the + * checked one any more, and no event says so, so the core is asked. A window that gets the + * focus again and again asks once in `FOCUS_READ_MS` for an agent. A focus inside that time + * is not dropped: its question is asked when the time is over, so a result that is not about + * the files any more never stays longer than that. + */ + focused(agentId: string) { + if (agentId in this.waiting) return; + const wait = (this.askedAt[agentId] ?? -Infinity) + FOCUS_READ_MS - Date.now(); + if (wait <= 0) { + void this.load(agentId); + return; + } + this.waiting[agentId] = setTimeout(() => { + delete this.waiting[agentId]; + void this.load(agentId); + }, wait); + } + /** Run the repo's required checks in the agent's worktree. One run for an agent at a time. */ async run(agentId: string) { if (this.state[agentId]?.running) return; diff --git a/src/lib/util/__tests__/search.test.ts b/src/lib/util/__tests__/search.test.ts index 5e53d65b..146dada6 100644 --- a/src/lib/util/__tests__/search.test.ts +++ b/src/lib/util/__tests__/search.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { searchFailure } from '../search'; +import { searchEnd, searchFailure } from '../search'; describe('searchFailure', () => { it('says the index is not ready only when the core says so', () => { @@ -13,3 +13,16 @@ describe('searchFailure', () => { expect(searchFailure(new Error('no repository is open'))).toBe('Code search failed: no repository is open'); }); }); + +describe('searchEnd', () => { + it('a search that answered ends with its result and no failure', async () => { + const found = { citations: [], confidence: 'low' }; + expect(await searchEnd(Promise.resolve(found))).toEqual({ res: found, failed: null }); + }); + + it('a search that failed ends with the failure in words, not as a search that was never asked', async () => { + // The view shows its empty state ("Ask the index.") only with no result and no failure. + expect(await searchEnd(Promise.reject(new Error('no repository is open')))).toEqual({ res: null, failed: 'Code search failed: no repository is open' }); + expect(await searchEnd(Promise.reject('the code index is not ready; use grep/rg instead'))).toEqual({ res: null, failed: 'The code index is not ready yet.' }); + }); +}); diff --git a/src/lib/util/review.ts b/src/lib/util/review.ts index b00e1ff4..290beb62 100644 --- a/src/lib/util/review.ts +++ b/src/lib/util/review.ts @@ -8,6 +8,7 @@ import type { Plan } from '../gen/Plan'; import type { Task } from '../gen/Task'; import type { TaskStatus } from '../gen/TaskStatus'; import { parseDiff, type DiffFile, type DiffHunk, type DiffLine } from './diff'; +import { uniqueKeys } from './keys'; /** Where a comment sits: a line of a file's diff (in the new file, or in the old one for a line * the change removes), or the whole file (`line` null). `quote` is that line as the diff shows it. */ @@ -73,6 +74,18 @@ export function offDiff(list: ReviewComment[], paths: string[]): ReviewComment[] return list.filter((c) => !inDiff.has(c.path)); } +/** + * A key for the row of each comment, in the list's order: no two the same, and a comment keeps + * its key when another one is removed, so its row (and a button in it that has the focus) goes + * with it and is never handed to the next comment. A comment has no id and no time of its own: + * its file, its place and the line as you quoted it name it (`sameSpot`, one comment per such + * place). Should two ever share all three, the later one adds its position among them. + */ +export function commentKeys(list: readonly ReviewComment[]): string[] { + // As JSON: the three parts cannot run into each other, whatever a path or a quoted line holds. + return uniqueKeys(list, (c) => JSON.stringify([c.path, placeId(c), c.quote])); +} + /** Reading order: the diff's file order; in a file, its own comment first, then by line (a removed * line before the new line with the same number). A file that left the diff comes last. */ export function inOrder(list: ReviewComment[], paths: string[]): ReviewComment[] { diff --git a/src/lib/util/search.ts b/src/lib/util/search.ts index 9d9589d7..c4cf1023 100644 --- a/src/lib/util/search.ts +++ b/src/lib/util/search.ts @@ -11,3 +11,16 @@ export function searchFailure(e: unknown): string { const why = e instanceof Error ? e.message : String(e); return NOT_READY.test(why) ? 'The code index is not ready yet.' : `Code search failed: ${why}`; } + +/** How a code search ended, as a view keeps it: its result, or why there is none. Never both. */ +export type SearchEnd = { res: R; failed: null } | { res: null; failed: string }; + +/** + * A code search on its way → how it ended. A search that failed is not a search that was never + * asked: the view shows `failed` (`searchFailure`) with Try again, not its empty state. + */ +export const searchEnd = (search: Promise): Promise> => + search.then( + (res): SearchEnd => ({ res, failed: null }), + (e: unknown): SearchEnd => ({ res: null, failed: searchFailure(e) }), + ); diff --git a/src/lib/util/traces.ts b/src/lib/util/traces.ts index ee028d52..291cf33b 100644 --- a/src/lib/util/traces.ts +++ b/src/lib/util/traces.ts @@ -1,8 +1,9 @@ // The Traces tab: an agent's tool calls, built from the events Codly records. A call is a // `tool_started` paired with its `tool_completed` by call id. Duration is what the CLI reported // when it did (Observed); else the gap between the two events (Measured by Codly); a call with no -// completion yet is still running and has no duration. A Claude agent's call that showed you a -// plan is named as that, and a plan you did not accept is no failed call. +// completion yet is still running and has no duration. A call whose turn ended before its result +// came was stopped: it does not run any more, and nothing says it failed. A Claude agent's call +// that showed you a plan is named as that, and a plan you did not accept is no failed call. import type { ActivityKind } from '../gen/ActivityKind'; import type { EventRow } from '../gen/EventRow'; import type { Provider } from '../gen/Provider'; @@ -18,12 +19,18 @@ export interface TraceCall { /** "subagent Ada (explorer)" when one of the agent's subagents made the call; '' for its own. */ subagent: string; start: number; - /** null while running. */ + /** null while running, and for a stopped call. */ durationMs: number | null; /** Where the duration comes from. */ source: 'reported' | 'measured' | null; - /** null while running. */ + /** null while running, and for a stopped call. */ ok: boolean | null; + /** + * No result came and none is expected: the call's turn ended, its process is gone, or the + * helper that made it is over. It does not run, and nothing says it failed. A result that + * still comes late makes it a finished call. + */ + stopped: boolean; exitCode: number | null; testsPassed: number | null; testsFailed: number | null; @@ -44,6 +51,8 @@ export interface TraceSummary { * them. A call id names one call while that call runs, and no longer than its turn: a CLI that * uses the id again after the call ended, or in a later turn (the first call was stopped with its * turn and has no completion), started another call. Both are listed, as on the timeline. + * A helper (subagent) that is still at work when a turn ends normally goes on after it: a call + * of its own stays running until its result comes or the helper is over, as in the conversation. * `provider`: the agent's CLI (none when Codly does not know the agent): only a Claude agent's * call of the plan tool is its plan; for every other CLI a call of that name is shown by its name. */ @@ -55,16 +64,41 @@ export function buildTraces(events: readonly EventRow[], agentId: string, provid const left = new Set(); /** The calls that showed you a plan. */ const plans = new Set(); + /** The helpers at work, by the id of the call that started each. */ + const atWork = new Set(); + /** A helper's own call → the id of the call that started that helper. */ + const helperOf = new Map(); for (const e of events) { if (e.agent_id !== agentId) continue; const k = e.kind; if (k.type === 'turn_completed' || k.type === 'exited') { - for (const c of open.values()) left.add(c); + // The process, or a turn that was interrupted or that failed, takes its helpers with it. + if (k.type === 'exited' || k.status === 'interrupted' || k.status === 'failed') atWork.clear(); + for (const c of open.values()) { + left.add(c); + const helper = helperOf.get(c); + if (helper == null || !atWork.has(helper)) c.stopped = true; + } + } else if (k.type === 'sub_agent') { + if (k.status === 'running') atWork.add(k.call_id); + else { + atWork.delete(k.call_id); + // The helper is over: a call of its own that is still open gets no result any more. + for (const c of open.values()) { + if (helperOf.get(c) !== k.call_id) continue; + left.add(c); + c.stopped = true; + } + } + } else if (k.type === 'sub_agent_progress') { + // A call of the helper's own: its `tool_started` came just before. + const c = k.tool_call_id != null ? open.get(k.tool_call_id) : undefined; + if (c) helperOf.set(c, k.call_id); } else if (k.type === 'tool_started') { const plan = isPlanCall(k.name, provider); const call: TraceCall = { callId: k.call_id, name: plan ? 'Its plan' : k.name, activity: k.activity, label: plan ? 'shown to you' : targetLabel(k.target, k.activity), subagent: subagentTag(k.input), start: e.ts, - durationMs: null, source: null, ok: null, exitCode: null, testsPassed: null, testsFailed: null, planSentBack: false, + durationMs: null, source: null, ok: null, stopped: false, exitCode: null, testsPassed: null, testsFailed: null, planSentBack: false, }; const running = open.get(k.call_id); // Announced again in the turn it runs in (the CLI knows more of its input by now): the same call. @@ -82,6 +116,7 @@ export function buildTraces(events: readonly EventRow[], agentId: string, provid c.durationMs = reported ? k.duration_ms : Math.max(0, e.ts - c.start); c.source = reported ? 'reported' : 'measured'; c.ok = k.ok; + c.stopped = false; c.exitCode = k.exit_code; c.testsPassed = k.tests_passed; c.testsFailed = k.tests_failed; @@ -95,7 +130,7 @@ export function summarize(calls: readonly TraceCall[]): TraceSummary { return { calls: calls.length, failed: calls.filter((c) => c.ok === false && !c.planSentBack).length, - running: calls.filter((c) => c.ok === null).length, + running: calls.filter((c) => c.ok === null && !c.stopped).length, totalMs: calls.reduce((n, c) => n + (c.durationMs ?? 0), 0), }; } diff --git a/src/rooms/changes/DiffView.svelte b/src/rooms/changes/DiffView.svelte index 581e016e..05d4a270 100644 --- a/src/rooms/changes/DiffView.svelte +++ b/src/rooms/changes/DiffView.svelte @@ -8,7 +8,7 @@ - void agentChecks.load(agent.id)} /> + any more, and no event says so. The core is asked again, but not on every focus: each question + starts git there (`agentChecks.focused`). --> + agentChecks.focused(agent.id)} />
diff --git a/src/sheet/AgentMessagesTab.svelte b/src/sheet/AgentMessagesTab.svelte index 7172f8a1..2d5aabcf 100644 --- a/src/sheet/AgentMessagesTab.svelte +++ b/src/sheet/AgentMessagesTab.svelte @@ -53,7 +53,7 @@
{:else} -

No messages with {agent.name} in this list yet. Your chat with {agent.name} is on Home.

+

No chat with {agent.name} yet. Write below; what {agent.name} does right now shows in its conversation on Home.

{/each}
diff --git a/src/sheet/AgentTracesTab.svelte b/src/sheet/AgentTracesTab.svelte index bacbbc6d..634dc698 100644 --- a/src/sheet/AgentTracesTab.svelte +++ b/src/sheet/AgentTracesTab.svelte @@ -33,11 +33,11 @@ {#each shown as { c, key } (key)}
  • - + {c.name} {c.label} {#if c.subagent}{c.subagent}{/if} - +

    {clockSec(c.start)}{c.planSentBack ? ' · you sent it back' : ''}{c.exitCode != null && c.exitCode !== 0 ? ` · exit ${c.exitCode}` : ''}{c.testsPassed != null ? ` · ${c.testsPassed} passed${c.testsFailed ? `, ${c.testsFailed} failed` : ''}` : ''}{c.source === 'measured' ? ' · measured' : ''}

    From fbc401395183871639f56e0655a55fd97d21c33b Mon Sep 17 00:00:00 2001 From: julienwuthrich-ant Date: Mon, 23 Nov 2026 10:42:41 -0800 Subject: [PATCH 002/120] Helpers: stop one from the sheet, and its rows say what really happened MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A helper (a subagent of a Claude agent) shows in the sheet's helper section, in "In the background" and in History, and the three did not agree. - Stop: a running helper of the background list has "Stop" too. Claude Code's stop_task is recorded for it (cli-claude-stream-json-2.1.311-part3, section 1). The button says that the agent is told and takes a turn of its own, and reads "Stopping..." until the list drops the work (10 s at most). - A stopped helper is not "finished": the section's line counts the helpers by how they ended ("2 finished · 1 stopped"), the button over the ended ones reads "3 ended", and each ended row shows its own word. - A background helper of a Claude agent no longer reads "stopped" after an interrupted or failed turn. The adapter says which helpers ended with the turn; the store follows its rows. Other CLIs keep the old rule, and the end of the process still stops every helper. - One word, "helper": the section is "Helpers", History says "Helper completed: ...". The end of a background helper is one History row: the list's row names only the commands that ended, and a list that only drops a helper is no row. - History says "Compaction started" for a Claude row with no token numbers and "Compacted context 180k → 40k" for one with numbers. A row with no numbers from another CLI can be the start or the end, so it says neither. - After the window is loaded again, background work that the first list at hand names shows "running" with no timer: when it started is not known, and the timer was too short before. Co-Authored-By: Claude Fable 5.2 --- src/home/__tests__/helpers.test.ts | 5 +- src/lib/__tests__/helperTurnEnd.test.ts | 76 +++++++++++++++++++++ src/lib/__tests__/session.test.ts | 87 +++++++++++++++++++++--- src/lib/state/session.ts | 62 ++++++++++++++--- src/lib/state/store.svelte.ts | 13 ++-- src/sheet/AgentBackground.svelte | 32 +++++---- src/sheet/AgentSheet.svelte | 32 +++++---- src/sheet/__tests__/helperRows.test.ts | 32 +++++++++ src/sheet/__tests__/historyWords.test.ts | 44 +++++++++++- src/sheet/helperRows.ts | 30 ++++++++ src/sheet/historyWords.ts | 40 +++++++++-- 11 files changed, 391 insertions(+), 62 deletions(-) create mode 100644 src/lib/__tests__/helperTurnEnd.test.ts create mode 100644 src/sheet/__tests__/helperRows.test.ts create mode 100644 src/sheet/helperRows.ts diff --git a/src/home/__tests__/helpers.test.ts b/src/home/__tests__/helpers.test.ts index 3ecb38fc..0c6e1ee6 100644 --- a/src/home/__tests__/helpers.test.ts +++ b/src/home/__tests__/helpers.test.ts @@ -165,7 +165,9 @@ describe('a plan a Claude agent shows you', () => { describe('a helper whose turn was interrupted or failed', () => { const atWork = () => (store.live.l1?.subagents ?? []).filter((s) => s.status === 'running').map((s) => s.callId); - /** As `launchEarly`, but the turn does not end normally. */ + /** As `launchEarly`, but the turn does not end normally. The helper's `Agent` call still + * waited for it, so the Claude adapter says "stopped" for it right after the turn's end (for + * a Claude agent that row decides, not the turn's end: lib/__tests__/helperTurnEnd.test.ts). */ function cut(status: 'interrupted' | 'failed') { apply( ev(10, { type: 'turn_started', input: 'Have a subagent run the tests' }), @@ -174,6 +176,7 @@ describe('a helper whose turn was interrupted or failed', () => { started(13, 'toolu-2', 'Bash', 'execute'), progress(13, 'toolu-1', { tool_call_id: 'toolu-2' }), ev(14, { type: 'turn_completed', status, result_text: null, duration_ms: null }), + helper(14, 'toolu-1', 'stopped'), ); } diff --git a/src/lib/__tests__/helperTurnEnd.test.ts b/src/lib/__tests__/helperTurnEnd.test.ts new file mode 100644 index 00000000..7a78e202 --- /dev/null +++ b/src/lib/__tests__/helperTurnEnd.test.ts @@ -0,0 +1,76 @@ +// Which helpers (subagents) are still at work after a turn that was interrupted or that failed. +// A Claude agent's adapter says it: a `sub_agent` row "stopped" for each helper that ends with +// the turn (the ones whose `Agent` call still waited), and nothing for a helper in the +// background, which works on. For another CLI no such row is known, so the end of the turn +// stops its helpers. The end of the process stops every helper of every CLI. +import { beforeEach, describe, expect, it } from 'vitest'; +import type { EventKind } from '../gen/EventKind'; +import type { EventRow } from '../gen/EventRow'; +import type { Snapshot } from '../gen/Snapshot'; +import { store } from '../state/store.svelte'; +import { mkAgent } from '../../office/demo/script'; + +const claude = { ...mkAgent('c1', 'Bo', 'claude', 'solo', 0, 'working'), run_id: 'r1' }; +const codex = { ...mkAgent('x1', 'Ada', 'codex', 'solo', 1, 'working'), run_id: 'r2' }; +const apply = (...evs: EventRow[]) => (store as unknown as { applyEvents(evs: EventRow[]): void }).applyEvents(evs); +const snapshot = (events: EventRow[]) => + ({ as_of: events.length, clis: [], accounts: [], workspace: null, settings: null, workspace_team: null, request_prefs: {}, agents: [claude, codex], plans: [], tasks: [], approvals: [], chats: [], memories: [], triples: [], artifacts: [], events }) as unknown as Snapshot; +const load = (events: EventRow[] = []) => (store as unknown as { applySnapshot(s: Snapshot): void }).applySnapshot(snapshot(events)); + +let id = 0; +beforeEach(() => { + id = 0; + load(); +}); + +const ev = (agent: string, ts: number, kind: EventKind): EventRow => ({ id: ++id, ts, agent_id: agent, task_id: null, run_id: agent === 'c1' ? 'r1' : 'r2', kind }); +const helper = (agent: string, ts: number, call: string, status: string) => ev(agent, ts, { type: 'sub_agent', call_id: call, description: `Run the tests (${call})`, status }); +const turnEnd = (agent: string, ts: number, status: 'completed' | 'interrupted' | 'failed') => ev(agent, ts, { type: 'turn_completed', status, result_text: null, duration_ms: null }); +/** A turn with two helpers at work: `fg` (its call still waits) and `bg` (in the background). */ +const turn = (agent: string) => [ev(agent, 10, { type: 'turn_started', input: 'Have two subagents run the tests' }), helper(agent, 11, 'fg', 'running'), helper(agent, 12, 'bg', 'running')]; +const helpers = (agent: string) => (store.live[agent]?.subagents ?? []).map((s) => [s.callId, s.status, s.ts]); + +describe('the helpers of a Claude agent after a turn that did not end normally', () => { + it.each(['interrupted', 'failed'] as const)('still run after a turn that was %s, when the adapter said nothing about them', (status) => { + apply(...turn('c1'), turnEnd('c1', 14, status)); + expect(helpers('c1')).toEqual([['fg', 'running', 11], ['bg', 'running', 12]]); + }); + + it('the ones the adapter says "stopped" for are stopped; the one in the background works on', () => { + // The adapter's order: the turn's end, then one row for each helper that ends with it. + apply(...turn('c1'), turnEnd('c1', 14, 'interrupted'), helper('c1', 14, 'fg', 'stopped')); + expect(helpers('c1')).toEqual([['bg', 'running', 12], ['fg', 'stopped', 14]]); + // The helper in the background ends at its own row. + apply(helper('c1', 30, 'bg', 'completed')); + expect(helpers('c1')).toEqual([['fg', 'stopped', 14], ['bg', 'completed', 30]]); + }); + + it('reads the same from a snapshot as from live events', () => { + load([...turn('c1'), turnEnd('c1', 14, 'interrupted'), helper('c1', 14, 'fg', 'stopped')]); + expect(helpers('c1')).toEqual([['bg', 'running', 12], ['fg', 'stopped', 14]]); + }); +}); + +describe('the helpers of an agent of another CLI', () => { + it.each(['interrupted', 'failed'] as const)('are stopped with a turn that was %s', (status) => { + apply(...turn('x1'), turnEnd('x1', 14, status)); + expect(helpers('x1')).toEqual([['fg', 'stopped', 14], ['bg', 'stopped', 14]]); + }); + + it('go on after a turn that ended normally', () => { + apply(...turn('x1'), turnEnd('x1', 14, 'completed')); + expect(helpers('x1')).toEqual([['fg', 'running', 11], ['bg', 'running', 12]]); + }); +}); + +describe('the end of the process', () => { + it.each(['c1', 'x1'])('stops every helper of %s', (agent) => { + apply(...turn(agent), turnEnd(agent, 14, 'completed'), ev(agent, 20, { type: 'exited', code: 0 })); + expect(helpers(agent)).toEqual([['fg', 'stopped', 20], ['bg', 'stopped', 20]]); + }); + + it('stops the Claude helper that worked on after an interrupted turn', () => { + apply(...turn('c1'), turnEnd('c1', 14, 'interrupted'), helper('c1', 14, 'fg', 'stopped'), ev('c1', 20, { type: 'exited', code: 0 })); + expect(helpers('c1')).toEqual([['bg', 'stopped', 20], ['fg', 'stopped', 14]]); + }); +}); diff --git a/src/lib/__tests__/session.test.ts b/src/lib/__tests__/session.test.ts index f2a03c8e..36020175 100644 --- a/src/lib/__tests__/session.test.ts +++ b/src/lib/__tests__/session.test.ts @@ -8,7 +8,7 @@ import type { EventKind } from '../gen/EventKind'; import type { EventRow } from '../gen/EventRow'; import type { McpServerStatus } from '../gen/McpServerStatus'; import type { Snapshot } from '../gen/Snapshot'; -import { MCP_HINT, MCP_LABEL, backgroundKind, backgroundSummary, canReconnect, canStop, mcpSummary, ofLiveRun, reconnectAnswer, reconnectMcp, signInSteps, stopBackgroundTask } from '../state/session'; +import { MCP_HINT, MCP_LABEL, STOP_WAIT_MS, backgroundKind, backgroundSummary, canReconnect, canStop, mcpSummary, ofLiveRun, reconnectAnswer, reconnectMcp, signInSteps, stopBackgroundTask, stopHint, stopOnItsWay } from '../state/session'; import { store } from '../state/store.svelte'; import { toasts } from '../state/toasts.svelte'; import { mkAgent } from '../../office/demo/script'; @@ -107,13 +107,14 @@ describe('a snapshot of a run that went on for long', () => { ['docs', 'connected', null, 10], ['linear', 'needs_sign_in', REFUSED, 11], ]); - expect(ofLiveRun(live().background, bo.run_id).map((w) => [w.id, w.status, w.startedAt])).toEqual([['tid-1', 'running', 12]]); + // (the list was read from the snapshot: when its work started is not known) + expect(ofLiveRun(live().background, bo.run_id).map((w) => [w.id, w.status, w.startedAt])).toEqual([['tid-1', 'running', null]]); // They are state, not rows of the log: the log starts where the snapshot's events start. expect(store.events.map((e) => e.id)).toEqual([899, 900]); // What comes live lands on them. apply({ ...list(20_000, 'r2', [], [['tid-1', 'stopped']]), id: 901 }, { ...server(20_001, 'r2', 'linear', 'connected'), id: 902 }); expect(live().mcp.map((s) => [s.name, s.status])).toEqual([['docs', 'connected'], ['linear', 'connected']]); - expect(live().background.map((w) => [w.id, w.status, w.startedAt, w.endedAt])).toEqual([['tid-1', 'stopped', 12, 20_000]]); + expect(live().background.map((w) => [w.id, w.status, w.startedAt, w.endedAt])).toEqual([['tid-1', 'stopped', null, 20_000]]); }); it('keeps them when the agent\'s earlier history is loaded and its state is built again', async () => { @@ -197,12 +198,30 @@ describe('what an agent left at work in the background', () => { expect(backgroundSummary(live().background)).toBe('2 ended'); }); - it('a helper is listed beside the commands, and only a command that runs has "Stop"', () => { + // Recorded (docs/research/cli-claude-stream-json-2.1.311-part3.md, section 1): `stop_task` stops a + // helper of the list as it stops a command. Before, a helper had no "Stop". + it('a helper is listed beside the commands; a command and a helper that run have "Stop", another kind of task has none', () => { const tasks = [task('tid-1'), task('tid-3', 'helper'), task('tid-4', 'remote')]; apply(ev(10, 'r2', { type: 'background_tasks', tasks, ended: [] })); - expect(live().background.map((w) => [w.id, backgroundKind(w), canStop(w)])).toEqual([['tid-1', null, true], ['tid-3', 'helper', false], ['tid-4', 'task', false]]); - apply(list(20, 'r2', [], [['tid-1', 'completed']])); - expect(live().background.filter(canStop)).toEqual([]); + expect(live().background.map((w) => [w.id, backgroundKind(w), canStop(w)])).toEqual([['tid-1', null, true], ['tid-3', 'helper', true], ['tid-4', 'task', false]]); + // What ended has no "Stop": the command, and the helper. + apply(ev(20, 'r2', { type: 'background_tasks', tasks: [tasks[2]], ended: [{ ...tasks[0], status: 'completed' }, { ...tasks[1], status: 'stopped' }] })); + expect(live().background.map((w) => [w.id, w.status, canStop(w)])).toEqual([['tid-4', 'running', false], ['tid-1', 'completed', false], ['tid-3', 'stopped', false]]); + }); + + it('the "Stop" of a helper says what follows: its agent is told and takes a turn', () => { + apply(ev(10, 'r2', { type: 'background_tasks', tasks: [task('tid-1'), task('tid-3', 'helper')], ended: [] })); + const [command, helper] = live().background; + expect(stopHint(helper, 'Bo')).toBe('Stops this helper. Bo is told and goes on with a turn of its own.'); + expect(stopHint(command, 'Bo')).toBeNull(); + }); + + it('a row reads "Stopping…" from the stop Claude Code took until its list drops the work, for 10 s at most', () => { + expect(stopOnItsWay(undefined, 50_000)).toBe(false); // no stop was asked + expect(stopOnItsWay(50_000, 50_000)).toBe(true); + expect(stopOnItsWay(50_000, 50_000 + STOP_WAIT_MS - 1)).toBe(true); + // The row still runs after the wait: that request did not stop it, and "Stop" is there again. + expect(stopOnItsWay(50_000, 50_000 + STOP_WAIT_MS)).toBe(false); }); it('work that a list drops without a word is over too, and work that was never seen running has no start', () => { @@ -237,14 +256,60 @@ describe('what an agent left at work in the background', () => { expect(rows()).toEqual([['tid-1', 'stopped', null, 30]]); }); - it('"Stop" names the command by Claude Code\'s id, and a refusal says why', async () => { + it('"Stop" names the work by Claude Code\'s id, and a refusal says why', async () => { for (const t of toasts.list) toasts.dismiss(t.id); - const stop = vi.spyOn(api, 'stopAgentTask').mockResolvedValueOnce(undefined).mockRejectedValueOnce('Bo is not running'); - expect(await stopBackgroundTask('a1', 'tid-2')).toBe(true); + const stop = vi.spyOn(api, 'stopAgentTask').mockResolvedValueOnce(undefined).mockRejectedValueOnce('Bo is not running').mockResolvedValueOnce(undefined).mockRejectedValueOnce('Bo is not running'); + expect(await stopBackgroundTask('a1', { id: 'tid-2', kind: 'command' })).toBe(true); expect(stop).toHaveBeenCalledWith('a1', 'tid-2'); expect(toasts.list).toHaveLength(0); - expect(await stopBackgroundTask('a1', 'tid-2')).toBe(false); + expect(await stopBackgroundTask('a1', { id: 'tid-2', kind: 'command' })).toBe(false); expect(toasts.list.map((t) => [t.title, t.body])).toEqual([['Couldn’t stop the command', 'Bo is not running']]); for (const t of toasts.list) toasts.dismiss(t.id); + // A helper goes the same way, by its id of the list. + expect(await stopBackgroundTask('a1', { id: 'tid-3', kind: 'helper' })).toBe(true); + expect(stop).toHaveBeenLastCalledWith('a1', 'tid-3'); + expect(await stopBackgroundTask('a1', { id: 'tid-3', kind: 'helper' })).toBe(false); + expect(toasts.list.map((t) => [t.title, t.body])).toEqual([['Couldn’t stop the helper', 'Bo is not running']]); + for (const t of toasts.list) toasts.dismiss(t.id); + }); +}); + +// The event of a list has no start time: work starts with the list that names it first. After +// the window was loaded again, the first list at hand of a run can be a late one of a long run. +// Before, its work got that list's time, and the row's timer was too short. +describe('when background work started', () => { + const said = (n: number): EventRow => ({ id: n, ts: 1000 + n, agent_id: 'a1', task_id: null, run_id: 'r2', kind: { type: 'message', item_id: `m${n}`, text: 'on it', phase: 'final' } as EventKind }); + const starts = () => live().background.map((w) => [w.id, w.status, w.startedAt]); + + it('is the time of the list that names it first, when the window saw that list come', () => { + apply(list(10, 'r2', ['tid-1']), list(20, 'r2', ['tid-1', 'tid-2'])); + expect(starts()).toEqual([['tid-1', 'running', 10], ['tid-2', 'running', 20]]); + }); + + it('is not known for work that the first list of a snapshot names, in its events or beside them', () => { + fresh({ as_of: 900, events: [{ ...list(500, 'r2', ['tid-1']), id: 890 }, said(899), said(900)] }); + expect(starts()).toEqual([['tid-1', 'running', null]]); + fresh({ as_of: 900, events: [said(899), said(900)], session_events: [{ ...list(500, 'r2', ['tid-1']), id: 40 }] }); + expect(starts()).toEqual([['tid-1', 'running', null]]); + // It ends: how long it ran is not known either. + apply({ ...list(20_000, 'r2', [], [['tid-1', 'completed']]), id: 901 }); + expect(live().background.map((w) => [w.id, w.status, w.startedAt, w.endedAt])).toEqual([['tid-1', 'completed', null, 20_000]]); + }); + + it('is known for work that a later list of the snapshot adds, and for work that comes after the snapshot', () => { + fresh({ as_of: 900, events: [{ ...list(500, 'r2', ['tid-1']), id: 890 }, { ...list(600, 'r2', ['tid-1', 'tid-2']), id: 895 }, said(900)] }); + expect(starts()).toEqual([['tid-1', 'running', null], ['tid-2', 'running', 600]]); + apply({ ...list(20_000, 'r2', ['tid-1', 'tid-2', 'tid-3']), id: 901 }); + expect(starts()).toEqual([['tid-1', 'running', null], ['tid-2', 'running', 600], ['tid-3', 'running', 20_000]]); + }); + + it('a start the window saw stays known when the agent\'s earlier history is loaded and its state is built again', async () => { + fresh({ as_of: 900, events: [said(899), said(900)] }); + apply({ ...list(20_000, 'r2', ['tid-1']), id: 901 }); + expect(starts()).toEqual([['tid-1', 'running', 20_000]]); + vi.spyOn(api, 'threadEvents').mockResolvedValue([said(898), said(897)]); + await store.loadEarlier('agent:a1'); + expect(live().messages).toHaveLength(4); + expect(starts()).toEqual([['tid-1', 'running', 20_000]]); }); }); diff --git a/src/lib/state/session.ts b/src/lib/state/session.ts index 3896771b..96b78333 100644 --- a/src/lib/state/session.ts +++ b/src/lib/state/session.ts @@ -17,9 +17,10 @@ export type McpServer = { name: string; status: McpServerStatus; error: string | * One piece of work of an agent's run in the background: a command it left running ("command": * "Stop" names it by `id`, the CLI's id of it), a helper ("helper"), or another task of the CLI. * `status` is "running", then the CLI's word for how it ended ("completed", "stopped"; "ended" - * when the CLI did not say). `startedAt`: when the first list of the run that names it came, - * as far back as the events at hand go (null: it was never seen running). `endedAt`: when the - * list that no longer names it came. + * when the CLI did not say). `startedAt`: when the list in which it started came (null: that + * list is not known: the work was never seen running, or the first list at hand that names it + * was read from a snapshot and may not be the first one that did). `endedAt`: when the list + * that no longer names it came. */ export type BackgroundWork = { id: string; kind: string; description: string; status: string; runId: string | null; startedAt: number | null; endedAt: number | null }; @@ -46,13 +47,22 @@ export function withMcpServer(list: McpServer[], k: McpEvent, runId: string | nu * its end. The list is the whole list each time, so work that ran and is in neither part of * the event is over too (the event of its end is not at hand: "ended"). The work of an earlier * run is gone with that run's process. Of the ended work the last ones are kept. + * + * The event has no start time: work starts with the list that names it first. `replayed`: the + * list was read from a snapshot or from stored rows (the store says so), not as it came. Such + * a list with nothing of its run before it (the window was loaded again) can be a late list + * of a long run: the work it names started at a time nobody knows, and its row shows no timer. */ -export function withBackgroundTasks(list: BackgroundWork[], k: TasksEvent, runId: string | null, ts: number): BackgroundWork[] { +export function withBackgroundTasks(list: BackgroundWork[], k: TasksEvent, runId: string | null, ts: number, replayed = false): BackgroundWork[] { const same = list.filter((w) => w.runId === runId); const ran = new Map(same.filter((w) => w.status === 'running').map((w) => [w.id, w])); + const startsHere = !replayed || same.length > 0; // One row per id, in each part: the rows are keyed by it. const running = new Map(); - for (const t of k.tasks) running.set(t.id, { id: t.id, kind: t.kind, description: t.description, status: 'running', runId, startedAt: ran.get(t.id)?.startedAt ?? ts, endedAt: null }); + for (const t of k.tasks) { + const was = ran.get(t.id); + running.set(t.id, { id: t.id, kind: t.kind, description: t.description, status: 'running', runId, startedAt: was ? was.startedAt : startsHere ? ts : null, endedAt: null }); + } const said = new Set([...k.tasks, ...k.ended].map((t) => t.id)); const lost = [...ran.values()].filter((w) => !said.has(w.id)).map((w): BackgroundWork => ({ ...w, status: 'ended', endedAt: ts })); const ended = k.ended.map((e): BackgroundWork => ({ id: e.id, kind: e.kind, description: e.description, status: e.status, runId, startedAt: ran.get(e.id)?.startedAt ?? null, endedAt: ts })); @@ -64,6 +74,17 @@ export function withBackgroundTasks(list: BackgroundWork[], k: TasksEvent, runId return [...running.values(), ...[...over.values()].slice(-ENDED_KEPT)]; } +/** + * Background work that was built again from an agent's stored rows (`built`), with the start + * times the window knew before (`held`): a start it saw is not in doubt because the rows were + * read again. + */ +export function withKnownStarts(built: BackgroundWork[], held: BackgroundWork[]): BackgroundWork[] { + const key = (w: BackgroundWork) => `${w.runId ?? ''} ${w.id}`; + const known = new Map(held.map((w) => [key(w), w.startedAt])); + return built.map((w) => (w.startedAt != null ? w : { ...w, startedAt: known.get(key(w)) ?? null })); +} + /** What belongs to the agent's live run (nothing when it has none: its process is gone). */ export function ofLiveRun(list: T[], runId: string | null): T[] { return runId == null ? [] : list.filter((x) => x.runId === runId); @@ -134,8 +155,27 @@ export function backgroundSummary(list: BackgroundWork[]): string { /** What a row calls its piece of work, when it is no command: "helper", "task". */ export const backgroundKind = (w: BackgroundWork): string | null => (w.kind === 'command' ? null : w.kind === 'helper' ? 'helper' : 'task'); -/** "Stop" is Claude Code's `stop_task` request, which is recorded for a command only. */ -export const canStop = (w: BackgroundWork) => w.status === 'running' && w.kind === 'command'; +/** + * "Stop" is Claude Code's `stop_task` request. It is recorded for a command and for a helper + * of the list (docs/research/cli-claude-stream-json-2.1.311-part3.md, section 1), not for + * another kind of task. + */ +export const canStop = (w: BackgroundWork) => w.status === 'running' && (w.kind === 'command' || w.kind === 'helper'); + +/** What "Stop" does to a helper, on its button (`agent`: the name of the helper's agent). A command just ends: no hint. */ +export const stopHint = (w: BackgroundWork, agent: string): string | null => + w.kind === 'helper' ? `Stops this helper. ${agent} is told and goes on with a turn of its own.` : null; + +/** + * How long a row reads "Stopping…" after Claude Code took the stop. Claude Code writes the + * list that no longer names the work before it answers (recorded: both in the same 10 ms), + * so the row moves to the ended ones at once. A row that still runs after this wait was not + * stopped by that request: "Stop" is there again. + */ +export const STOP_WAIT_MS = 10_000; + +/** Whether a stop that Claude Code took at `takenAt` is still on its way (`now`: the clock of the screen; no time: none was taken). */ +export const stopOnItsWay = (takenAt: number | undefined, now: number): boolean => takenAt != null && now - takenAt < STOP_WAIT_MS; const msg = (e: unknown) => (e instanceof Error ? e.message : typeof e === 'string' ? e : 'Unknown error'); @@ -152,13 +192,13 @@ export async function reconnectMcp(agentId: string, server: string): Promise { +/** Stop a background command or helper. Returns whether Claude Code took the request; its next list of background tasks says that the work stopped. */ +export async function stopBackgroundTask(agentId: string, work: Pick): Promise { try { - await api.stopAgentTask(agentId, taskId); + await api.stopAgentTask(agentId, work.id); return true; } catch (e) { - toast({ kind: 'error', title: 'Couldn’t stop the command', body: msg(e) }); + toast({ kind: 'error', title: work.kind === 'helper' ? 'Couldn’t stop the helper' : 'Couldn’t stop the command', body: msg(e) }); return false; } } diff --git a/src/lib/state/store.svelte.ts b/src/lib/state/store.svelte.ts index 92b69bae..5adac0fb 100644 --- a/src/lib/state/store.svelte.ts +++ b/src/lib/state/store.svelte.ts @@ -46,7 +46,7 @@ import { targetLabel, type Provenance } from '../util/labels'; import { transferredOut } from '../util/transfer'; import { accounts } from './accounts.svelte'; import { controls } from './control.svelte'; -import { withBackgroundTasks, withMcpServer, type BackgroundWork, type McpServer } from './session'; +import { withBackgroundTasks, withKnownStarts, withMcpServer, type BackgroundWork, type McpServer } from './session'; export const LOG_CAP = 5000; const SEG_CAP = 1500; @@ -859,8 +859,11 @@ class CodlyStore { const t = l.turns; if (t.length && t[t.length - 1].end == null) l.turns = [...t.slice(0, -1), { ...t[t.length - 1], end: ev.ts }]; // A turn that was interrupted or that failed takes its helpers with it: none of them - // is at work any more. - if ((k.status === 'interrupted' || k.status === 'failed') && l.subagents.some((s) => s.status === 'running')) + // is at work any more. Not so for a Claude agent: a helper in the background works on + // after such a turn, and its adapter says which helpers ended with the turn (a + // `sub_agent` row "stopped" for each, right after this one), so its rows decide. + const cli = (aid ? this.agentMap.get(aid)?.provider : undefined) ?? l.session?.provider; + if (cli !== 'claude' && (k.status === 'interrupted' || k.status === 'failed') && l.subagents.some((s) => s.status === 'running')) l.subagents = l.subagents.map((s) => (s.status === 'running' ? { ...s, status: 'stopped', ts: ev.ts } : s)); // A helper that is still at work when a turn ends normally goes on after it: a call of its // own stays open until its result comes, or until the helper is over (`sub_agent`, `exited`). @@ -1041,7 +1044,7 @@ class CodlyStore { if (l) l.mcp = withMcpServer(l.mcp, k, ev.run_id, ev.ts); break; case 'background_tasks': - if (l) l.background = withBackgroundTasks(l.background, k, ev.run_id, ev.ts); + if (l) l.background = withBackgroundTasks(l.background, k, ev.run_id, ev.ts, replay); break; case 'error': if (l) l.errors = [...l.errors, { message: k.message, fatal: k.fatal, ts: ev.ts }].slice(-20); @@ -1198,6 +1201,8 @@ class CodlyStore { // Nor is a server that stands where an earlier run recorded it. The servers as held are // the newest there are: older rows add nothing to them. if (prev) l.mcp = prev.mcp; + // A start of background work that the window saw is known, though the rows do not say it. + if (prev) l.background = withKnownStarts(l.background, prev.background); this.live[owner] = l; this.bump(this.revBy, [owner]); } diff --git a/src/sheet/AgentBackground.svelte b/src/sheet/AgentBackground.svelte index e1863068..88f62a4d 100644 --- a/src/sheet/AgentBackground.svelte +++ b/src/sheet/AgentBackground.svelte @@ -1,13 +1,16 @@ @@ -47,7 +55,7 @@ {clean(w.description)} {kind ? `${kind} · ` : ''}{w.startedAt == null ? 'running' : timer(ui.now - w.startedAt)} {#if canStop(w)} - + {/if}
  • {/each} diff --git a/src/sheet/AgentSheet.svelte b/src/sheet/AgentSheet.svelte index 385c24fb..102eefa4 100644 --- a/src/sheet/AgentSheet.svelte +++ b/src/sheet/AgentSheet.svelte @@ -1,7 +1,7 @@ @@ -35,7 +35,8 @@ import UsageBars from '../components/UsageBars.svelte'; import AgentBackground from './AgentBackground.svelte'; import AgentControls from './AgentControls.svelte'; - import { backgroundLine, historyFacts, repeatsReply, taskChangedLine, tripleLine, withoutRepeatedTaskRows, type Names } from './historyWords'; + import { helperEndWord, helpersSummary } from './helperRows'; + import { backgroundLine, compactionRowLine, helperRowLine, historyFacts, repeatsReply, taskChangedLine, tripleLine, withoutRepeatedTaskRows, type Names } from './historyWords'; import { isPlanCall, planCallEnd, planStep } from '../lib/util/planRequest'; import AgentMcp from './AgentMcp.svelte'; import AgentTakeover from './AgentTakeover.svelte'; @@ -117,10 +118,11 @@ } const fileState = (f: FileTouch) => (f.created ? 'created' : f.deleted ? 'deleted' : f.modified ? 'changed' : f.read ? 'read' : 'provided'); - // ── subagents ── + // ── helpers (subagents) ── const subs = $derived(live?.subagents ?? []); const subsRunning = $derived(subs.filter((s) => s.status === 'running')); - const subsDone = $derived(subs.filter((s) => s.status !== 'running')); + /** The ones that are over, however they ended: each row says its own word (helperRows.ts). */ + const subsEnded = $derived(subs.filter((s) => s.status !== 'running')); let moreSubs = $state(false); let moreFiles = $state(false); const SHOW = 4; @@ -194,6 +196,8 @@ if (filter === 'decisions' && t !== 'decision') continue; if (filter === 'errors' && t !== 'error' && !(e.kind.type === 'tool_completed' && !e.kind.ok && !facts.planCalls.has(e.kind.call_id))) continue; if (repeatsReply(e, agent.id, facts)) continue; + // (a list of background work that only drops a helper says nothing: the helper's own row says its end) + if (e.kind.type === 'background_tasks' && backgroundLine(e.kind) == null) continue; out.push(e); } // (a task's row says its status: one that repeats the row before it says nothing) @@ -219,11 +223,11 @@ case 'approval_resolved': return { icon: 'flag', text: settledLine(k.status, k.by, store.approvals.find((a) => a.id === k.approval_id) ?? null, yourAnswers.get(k.approval_id) ?? null, agent.provider), tone: k.status === 'approved' ? 'good' : 'bad' }; case 'retrieval': return { icon: 'link', text: `Codly provided ${k.citations.length} citations for “${oneLine(k.query, 50)}”` }; case 'session_started': return { icon: 'bolt', text: `Session started · ${PROVIDER_LABEL[k.provider]} ${k.cli_version ?? ''}` }; - case 'sub_agent': return { icon: 'crew', text: `Subagent ${k.status}: ${oneLine(k.description, 90)}` }; + case 'sub_agent': return { icon: 'crew', text: helperRowLine(k) }; case 'mcp_server': return { icon: 'link', text: `MCP server ${k.name}: ${MCP_LABEL[k.status].toLowerCase()}${k.error ? ` (${oneLine(k.error, 90)})` : ''}` }; case 'error': return { icon: 'alert', text: oneLine(k.message, 120), tone: 'bad' }; case 'notice': return { icon: 'info', text: oneLine(k.text, 160) }; - case 'background_tasks': return { icon: 'terminal', text: backgroundLine(k) }; + case 'background_tasks': return { icon: 'terminal', text: backgroundLine(k) ?? '' }; // (one with nothing to say is not in `log`) case 'decision': return { icon: 'help', text: k.summary }; case 'committed': return { icon: 'commit', text: `Committed ${k.sha.slice(0, 7)} · ${plural(k.files.length, 'file')}` }; case 'verified': return { icon: k.ok ? 'check-circle' : 'x-circle', text: `Verified ${k.command}`, tone: k.ok ? 'good' : 'bad' }; @@ -233,14 +237,14 @@ case 'triple_added': return { icon: 'graph', text: tripleLine(k.triple, names) }; case 'task_changed': return { icon: 'plan', text: taskChangedLine(k.task) }; case 'exited': return { icon: 'stop', text: `Process exited${k.code != null ? ` (${k.code})` : ''}` }; - case 'compacting': return { icon: 'layers', text: `Compacted context${k.pre_tokens ? ` ${tokens(k.pre_tokens)} → ${tokens(k.post_tokens)}` : ''}` }; + case 'compacting': return { icon: 'layers', text: compactionRowLine(k, agent.provider) }; case 'retrying': return { icon: 'refresh', text: `Retrying (${k.attempt}): ${k.reason}`, tone: 'warn' }; case 'chat': return { icon: 'chat', text: oneLine(k.message.text, 100) }; default: return { icon: 'info', text: k.type.replace(/_/g, ' ') }; } } - // Jump targets: a timeline click (eventId) opens History; a subagent companion opens Subagents. + // Jump targets: a timeline click (eventId) opens History; a helper's companion opens Helpers. let root: HTMLDivElement | undefined = $state(); $effect(() => { const id = ui.selection?.kind === 'agent' ? ui.selection.eventId : undefined; @@ -420,7 +424,7 @@ {#if subs.length} -
    +
      {#each moreSubs ? subsRunning : subsRunning.slice(0, SHOW) as s (s.callId)}
    • @@ -436,17 +440,17 @@ {/each}
    {#if subsRunning.length > SHOW}{/if} - {#if subsDone.length} - + {#if subsEnded.length} + {#if moreSubs}
      - {#each subsDone as s (s.callId)} + {#each subsEnded as s (s.callId)}
    • {#if s.name}{clean(s.name)}{/if} {s.description} - {dur(s.ts - s.startedAt)} + {helperEndWord(s.status)} · {dur(s.ts - s.startedAt)}
      {#if helperLine(s)}

      {helperLine(s)}

      {/if} {#if clean(s.report).trim()}

      {clean(s.report).trim()}

      {/if} @@ -609,7 +613,7 @@ .s-dot { width: 9px; height: 9px; border-radius: 50%; background: var(--ink-4); flex-shrink: 0; } .s-dot.on { background: color-mix(in srgb, var(--hue) 75%, white); box-shadow: 0 0 8px var(--hue); } .s-txt { flex: 1; min-width: 0; font-size: var(--t-md); } - .s-meta { font-size: var(--t-xs); color: var(--ink-3); } + .s-meta { font-size: var(--t-xs); color: var(--ink-3); white-space: nowrap; } .subs li { flex-direction: column; align-items: stretch; gap: 2px; } .s-row { display: flex; gap: 10px; align-items: center; min-width: 0; } .s-row > :global(svg) { flex-shrink: 0; color: var(--ink-3); } diff --git a/src/sheet/__tests__/helperRows.test.ts b/src/sheet/__tests__/helperRows.test.ts new file mode 100644 index 00000000..309effba --- /dev/null +++ b/src/sheet/__tests__/helperRows.test.ts @@ -0,0 +1,32 @@ +// The "Helpers" section of the agent sheet. Before, every helper that was not running counted +// as "finished": also one that you stopped, and one that failed. +import { describe, expect, it } from 'vitest'; +import { helperEndWord, helpersSummary } from '../helperRows'; + +const helpers = (...status: string[]) => status.map((s) => ({ status: s })); + +describe('how a helper ended, in the word of its row', () => { + it('"completed" is finished; "stopped" and "killed" are stopped; "failed" is failed', () => { + expect(['completed', 'stopped', 'killed', 'failed'].map(helperEndWord)).toEqual(['finished', 'stopped', 'stopped', 'failed']); + }); + + it('another word of a CLI stays as it is, on one short line', () => { + expect(helperEndWord('interrupted')).toBe('interrupted'); + expect(helperEndWord('timed\nout')).toBe('timed out'); + expect(helperEndWord('')).toBe('ended'); + }); +}); + +describe('the line of the "Helpers" section', () => { + it('counts the helpers by how they stand: a stopped one is not finished', () => { + expect(helpersSummary(helpers('running'))).toBe('1 running'); + expect(helpersSummary(helpers('completed', 'stopped', 'completed'))).toBe('2 finished · 1 stopped'); + expect(helpersSummary(helpers('failed'))).toBe('1 failed'); + expect(helpersSummary(helpers('killed', 'stopped'))).toBe('2 stopped'); + }); + + it('says what runs first, then what finished, stopped and failed, then a CLI\'s other words', () => { + expect(helpersSummary(helpers('started', 'failed', 'stopped', 'completed', 'running', 'running'))).toBe('2 running · 1 finished · 1 stopped · 1 failed · 1 started'); + expect(helpersSummary([])).toBe(''); + }); +}); diff --git a/src/sheet/__tests__/historyWords.test.ts b/src/sheet/__tests__/historyWords.test.ts index 75ff51b3..612486f9 100644 --- a/src/sheet/__tests__/historyWords.test.ts +++ b/src/sheet/__tests__/historyWords.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest'; import type { EventKind } from '../../lib/gen/EventKind'; import type { EventRow } from '../../lib/gen/EventRow'; import type { TaskStatus } from '../../lib/gen/TaskStatus'; -import { backgroundLine, entityWord, historyFacts, repeatsReply, taskChangedLine, tripleLine, withoutRepeatedTaskRows, type Names } from '../historyWords'; +import { backgroundLine, compactionRowLine, entityWord, helperRowLine, historyFacts, repeatsReply, taskChangedLine, tripleLine, withoutRepeatedTaskRows, type Names } from '../historyWords'; let eid = 0; const ev = (agent: string, kind: unknown): EventRow => ({ id: ++eid, ts: eid, agent_id: agent, task_id: null, run_id: null, kind: kind as EventKind }); @@ -96,6 +96,46 @@ describe('a change of what an agent runs in the background', () => { it('says what ended, in Claude Code\'s word, and what still runs', () => { expect(backgroundLine({ tasks: [], ended: [ended('command', 'sleep 8; echo woke', 'completed')] })).toBe('Background command completed: sleep 8; echo woke'); expect(backgroundLine({ tasks: [task('command', 'npm test')], ended: [ended('command', 'npm run dev', 'stopped')] })).toBe('Background command stopped: npm run dev · still runs: npm test'); - expect(backgroundLine({ tasks: [], ended: [ended('helper', 'Run the tests', 'ended'), ended('task', 'x', 'completed')] })).toBe('Helper ended: Run the tests; Background task completed: x'); + expect(backgroundLine({ tasks: [], ended: [ended('command', 'npm test', 'ended'), ended('task', 'x', 'completed')] })).toBe('Background command ended: npm test; Background task completed: x'); + }); + + // Before, the end of a background helper was two rows with two words: "Subagent completed: Run + // the tests" (its own row) and "Helper completed: Run the tests" (the list's row). + it('leaves the end of a helper to the helper\'s own row: a list that ends a command and a helper names the command', () => { + const k = { tasks: [task('command', 'npm run dev')], ended: [ended('command', 'npm test', 'completed'), ended('helper', 'Run the tests', 'stopped')] }; + expect(backgroundLine(k)).toBe('Background command completed: npm test · still runs: npm run dev'); + }); + + it('a list that ends only a helper has nothing left to say: it is no row', () => { + expect(backgroundLine({ tasks: [], ended: [ended('helper', 'Run the tests', 'stopped')] })).toBeNull(); + expect(backgroundLine({ tasks: [task('command', 'npm run dev')], ended: [ended('helper', 'Run the tests', 'completed'), ended('helper', 'Read the docs', 'ended')] })).toBeNull(); + }); +}); + +describe('the row of a helper', () => { + it('calls it a helper, with its CLI\'s word for where it stands', () => { + expect(helperRowLine({ description: 'Run the tests', status: 'completed' })).toBe('Helper completed: Run the tests'); + expect(helperRowLine({ description: 'Run the\ntests', status: 'stopped' })).toBe('Helper stopped: Run the tests'); + expect(helperRowLine({ description: 'Run the tests', status: 'running' })).toBe('Helper running: Run the tests'); + }); +}); + +// Before, every `compacting` row read "Compacted context", also the one that only says that a +// compaction began. +describe('the row of a compaction', () => { + it('says "Compacted context" only for a row with token numbers, as the row under "Compact now" does', () => { + expect(compactionRowLine({ pre_tokens: 180_000, post_tokens: 40_000 }, 'claude')).toBe('Compacted context 180k → 40k'); + expect(compactionRowLine({ pre_tokens: null, post_tokens: 800 }, 'claude')).toBe('Compacted context'); + expect(compactionRowLine({ pre_tokens: 180_000, post_tokens: 40_000 }, 'codex')).toBe('Compacted context 180k → 40k'); + }); + + it('a Claude row with no numbers says that a compaction started', () => { + expect(compactionRowLine({ pre_tokens: null, post_tokens: null }, 'claude')).toBe('Compaction started'); + }); + + it('a row with no numbers from another CLI can be the start or the end: it says neither', () => { + for (const cli of ['codex', 'gemini', 'opencode', null] as const) { + expect(compactionRowLine({ pre_tokens: null, post_tokens: null }, cli)).toBe('Context compaction'); + } }); }); diff --git a/src/sheet/helperRows.ts b/src/sheet/helperRows.ts new file mode 100644 index 00000000..82c0866f --- /dev/null +++ b/src/sheet/helperRows.ts @@ -0,0 +1,30 @@ +// The "Helpers" section of the agent sheet: how a helper that is over ended, in one word, and +// the section's line. Pure, so the sheet and the tests agree. +import type { SubAgent } from '../lib/state/store.svelte'; +import { oneLine } from '../lib/util/sanitize'; + +/** + * How a helper that is no longer at work ended, as its row says it. The CLI's "completed" is + * "finished". "stopped" and "killed" are "stopped": you, Codly or the end of its turn stopped + * it, so it did not finish. "failed" is "failed". Another word of a CLI stays as it is: Codly + * does not guess what it means. + */ +export function helperEndWord(status: string): string { + if (status === 'completed') return 'finished'; + if (status === 'stopped' || status === 'killed') return 'stopped'; + return oneLine(status, 24) || 'ended'; +} + +/** The words of the section's line that come first, in this order; a CLI's other words follow as they come. */ +const ORDER = ['running', 'finished', 'stopped', 'failed']; + +/** The section's line: "1 running", "2 finished · 1 stopped", "1 running · 1 failed". */ +export function helpersSummary(helpers: readonly Pick[]): string { + const counts = new Map(); + for (const h of helpers) { + const word = h.status === 'running' ? 'running' : helperEndWord(h.status); + counts.set(word, (counts.get(word) ?? 0) + 1); + } + const words = [...ORDER.filter((w) => counts.has(w)), ...[...counts.keys()].filter((w) => !ORDER.includes(w))]; + return words.map((w) => `${counts.get(w)} ${w}`).join(' · '); +} diff --git a/src/sheet/historyWords.ts b/src/sheet/historyWords.ts index 9c4e4957..f792b948 100644 --- a/src/sheet/historyWords.ts +++ b/src/sheet/historyWords.ts @@ -1,13 +1,14 @@ // Words for rows of an agent's History that are built from ids or lists: a fact of the knowledge -// graph, a task that changed, a change of what runs in the background. Which rows of a task say -// something new. And what a row needs to know about the agent's other events: which calls -// showed a plan, and which conversation rows only repeat a reply. +// graph, a task that changed, a helper, a change of what runs in the background, a compaction. +// Which rows of a task say something new. And what a row needs to know about the agent's other +// events: which calls showed a plan, and which conversation rows only repeat a reply. // Pure, so the sheet and the tests agree; the sheet passes the names. import type { EventKind } from '../lib/gen/EventKind'; import type { EventRow } from '../lib/gen/EventRow'; import type { Provider } from '../lib/gen/Provider'; import type { Task } from '../lib/gen/Task'; import type { Triple } from '../lib/gen/Triple'; +import { tokens } from '../lib/util/format'; import { TASK_STATUS_LABEL } from '../lib/util/labels'; import { isPlanCall } from '../lib/util/planRequest'; import { oneLine } from '../lib/util/sanitize'; @@ -84,19 +85,44 @@ export function withoutRepeatedTaskRows(rows: T[] return keep.reverse(); } +type SubAgentRow = Extract; type BackgroundTasks = Extract; +type Compacting = Extract; -/** "Background command", "Helper": what a piece of background work is called in a row. */ -const backgroundWord = (kind: string) => (kind === 'command' ? 'Background command' : kind === 'helper' ? 'Helper' : 'Background task'); +/** "Helper completed: Run the tests": a helper (subagent) with its CLI's word for where it stands. One word for it on every screen: "helper". */ +export function helperRowLine(k: Pick): string { + return `Helper ${oneLine(k.status, 24)}: ${oneLine(k.description, 90)}`; +} + +/** "Background command": what a piece of background work that is no helper is called in a row. */ +const backgroundWord = (kind: string) => (kind === 'command' ? 'Background command' : 'Background task'); /** * One change of what an agent runs in the background, as its CLI lists it: what ended, with the * CLI's word for it, then what still runs. "Background command stopped: npm run dev · still * runs: npm test"; with nothing ended, "Runs in the background: npm run dev". + * + * The end of a helper is not said here: its own row says it ("Helper stopped: Run the tests", + * the adapter writes one for every helper that leaves the list), and History says a thing once. + * Null: the list has nothing left to say (all that ended were helpers), so it is no row. */ -export function backgroundLine(k: Pick): string { +export function backgroundLine(k: Pick): string | null { const runs = oneLine(k.tasks.map((t) => t.description).join(', '), 120); if (!k.ended.length) return k.tasks.length ? `Runs in the background: ${runs}` : 'Nothing runs in the background'; - const ended = k.ended.map((e) => `${backgroundWord(e.kind)} ${e.status}: ${oneLine(e.description, 90)}`).join('; '); + const others = k.ended.filter((e) => e.kind !== 'helper'); + if (!others.length) return null; + const ended = others.map((e) => `${backgroundWord(e.kind)} ${e.status}: ${oneLine(e.description, 90)}`).join('; '); return k.tasks.length ? `${ended} · still runs: ${runs}` : ended; } + +/** + * A row of a compaction, by the rule of the row under "Compact now" (`compactionLine`, + * state/control.svelte.ts): only an event with token numbers says that a compaction is done. + * Claude Code sends one without numbers when a compaction begins, so that row says "started". + * From another CLI such an event can be the start or the end (Codex sends both, and nothing + * tells them apart): its row says neither. + */ +export function compactionRowLine(k: Pick, provider: Provider | null): string { + if (k.post_tokens != null) return `Compacted context${k.pre_tokens == null ? '' : ` ${tokens(k.pre_tokens)} → ${tokens(k.post_tokens)}`}`; + return provider === 'claude' ? 'Compaction started' : 'Context compaction'; +} From 8f1abef0ece22ce53eaea776c30df9b5ec778708 Mon Sep 17 00:00:00 2001 From: julienwuthrich-ant Date: Mon, 23 Nov 2026 10:49:58 -0800 Subject: [PATCH 003/120] Composer: the agent's controls are in the / menu, and Codly opens on the request you left What a Claude Code or Codex user does with a slash command or a mode switch was only in the agent sheet. The composer now has it where you type. - The / menu lists compact, context, undo, terminal and mcp for the agent of the conversation (the Lead of a request, the agent of a 1:1 chat). In a 1:1 chat with a Claude agent, ask, plan and the new name edits set how it works with edits. Every name is in every conversation; one that cannot run says why in full (a long reason takes a second line), and the list scrolls in a low window. The names that were there before keep their place, so "/c" and Enter still clears the draft. The list is built in composerActions.ts. - The chip under a 1:1 Claude agent's composer has a second group, "How it works", and says the way the agent is in (agentPicker.ts). - The request you were last on in each office is also kept in localStorage, one key per office: after a restart you land on it, in the room you were in. A request that is gone lands on the first one, as before. - An open sheet that shows a Lead now shows the Lead of the request you switch to, whatever took you there; with no Lead yet it closes. The sheet of a worker, a 1:1 agent, a task or a file stays. - Send back: a comment written or changed while the call to the worker is on its way stays on the diff. A handed review message that you edit before sending takes the comments it still names off the diff; one you took out of the message stays. Co-Authored-By: Claude Fable 5.2 --- src/App.svelte | 10 ++ src/home/AgentControls.svelte | 32 ++-- src/home/Composer.svelte | 125 +++++++++----- src/home/__tests__/agentPicker.test.ts | 80 +++++++++ src/home/__tests__/composerActions.test.ts | 190 +++++++++++++++++++++ src/home/agentPicker.ts | 71 ++++++++ src/home/composerActions.ts | 170 ++++++++++++++++++ src/lib/__tests__/lastRequest.test.ts | 111 ++++++++++++ src/lib/__tests__/reviewSend.test.ts | 127 ++++++++++++++ src/lib/__tests__/selection.test.ts | 38 ++++- src/lib/state/actions.ts | 20 ++- src/lib/state/control.svelte.ts | 7 + src/lib/state/review.svelte.ts | 17 +- src/lib/state/ui.svelte.ts | 74 ++++++-- src/lib/util/review.ts | 20 ++- 15 files changed, 1014 insertions(+), 78 deletions(-) create mode 100644 src/home/__tests__/agentPicker.test.ts create mode 100644 src/home/__tests__/composerActions.test.ts create mode 100644 src/home/agentPicker.ts create mode 100644 src/home/composerActions.ts create mode 100644 src/lib/__tests__/lastRequest.test.ts create mode 100644 src/lib/__tests__/reviewSend.test.ts diff --git a/src/App.svelte b/src/App.svelte index 6ac7ff53..2693a6aa 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -31,6 +31,7 @@ import { installNoticeOpener } from './lib/state/openNotice'; import { installTooltips } from './lib/state/tooltip.svelte'; import { resumeWork } from './lib/state/resumeWork.svelte'; + import { reopenLastRequest } from './lib/state/actions'; // Dev-only handle for debugging and browser tests (stripped from production builds). if (import.meta.env.DEV) (window as unknown as { __codly: unknown }).__codly = { store, ui }; @@ -56,6 +57,15 @@ if (coreUp) untrack(() => void resumeWork.check()); }); + // The office the core has open at the start shows the request you last had open in it. Once: + // from then on you choose the request. + let landed = false; + $effect(() => { + if (!coreUp || landed) return; + landed = true; + untrack(reopenLastRequest); + }); + // Theme: always resolved onto [data-theme] ("system" follows the OS live). const theme = $derived<'dark' | 'light'>(store.settings.theme === 'dark' || store.settings.theme === 'light' ? store.settings.theme : ui.systemDark ? 'dark' : 'light'); $effect(() => { diff --git a/src/home/AgentControls.svelte b/src/home/AgentControls.svelte index bc7a75e6..87fdbf7f 100644 --- a/src/home/AgentControls.svelte +++ b/src/home/AgentControls.svelte @@ -1,17 +1,21 @@
      -
      diff --git a/src/home/Composer.svelte b/src/home/Composer.svelte index 299721c6..9bd8c339 100644 --- a/src/home/Composer.svelte +++ b/src/home/Composer.svelte @@ -4,7 +4,8 @@ `@agent` to talk to one agent 1:1 (the thread switches and shows as a chip); `@` mid-sentence mentions an agent or a file of the repo (its path, which the agent reads), `#` refers to a task. `/` alone on the line lists Codly's own actions (new request, from an issue or a pull request, - stop, mode, model, clear…) and ↵ + stop, mode, model, clear…) and the controls of the agent you talk to (compact, context, its + way of working, undo, your terminal, its MCP servers: composerActions.ts), and ↵ runs one; it is not sent. One that cannot run right now (stop, with nothing running) says why and is not sent either. A CLI's own slash commands are not offered: Codly cannot run them. Esc twice on an empty line stops the running turn; ↑ on an empty line brings back what you sent. A @@ -17,7 +18,11 @@ From 1c71bc8a990041348941e054122951748ae05481 Mon Sep 17 00:00:00 2001 From: julienwuthrich-ant Date: Mon, 23 Nov 2026 10:58:32 -0800 Subject: [PATCH 006/120] Approvals: what you said with an answer stays on record and on the closed card MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A request you denied with a note, a plan you changed before you accepted it and a question you answered all closed as "Denied by you" or "Approved by you". The note was kept nowhere, and the answer only in the window's memory, so it was gone after a restart. - The core writes a new row, `approval_said` (note, answer, plan_changed), just before the answer's own row. Only for an answer that reached the agent, and only when it carried words. The note is recorded where the CLI hands it to the agent (Claude Code); the answers to a question are one line in the order asked, without the answer to a question Codex marks as secret. A thread's "Load earlier" page has the row too. - The app reads the row live, from a snapshot and from an older page. The closed row and the agent's History end with your note, and a plan reads "Plan accepted with your changes" or "Plan sent back". - A plan card has one way to say no: "Send it back with a note…". The plain reject is gone (without a note Claude Code shows the same plan again), ⌘⌫ opens the note field on a plan, the note form has a Cancel button, and a plan cannot go back with an empty note. - The closed row of a question gives a short question the room of its text and the answer the rest. - The network card, Settings and the README say what the 2.1.311 recordings show: after "Approve once" Claude Code does not ask again for the host while the agent keeps running, and asks again when the agent starts again. - The office says "Skipped its question", "Denied: more permissions" and "Plan sent back" for a request you said no to, and the ticker reads "Waiting for you: its question". - The browser demo writes the same row. Co-Authored-By: Claude Fable 5.2 --- README.md | 5 +- crates/codly-core/src/model.rs | 14 ++ .../codly-core/src/orchestrator/workspace.rs | 179 +++++++++++++- crates/codly-core/src/store/mod.rs | 41 ++- .../tests/orchestrator_approvals.rs | 234 ++++++++++++++++++ src/home/cards/ApprovalCard.svelte | 69 +++--- src/lib/__tests__/answers.test.ts | 5 +- src/lib/__tests__/approvalSaid.test.ts | 92 +++++++ src/lib/__tests__/demoSaid.test.ts | 88 +++++++ src/lib/demo/said.ts | 27 ++ src/lib/demo/story.ts | 4 + src/lib/gen/EventKind.ts | 14 +- src/lib/state/actions.ts | 3 +- src/lib/state/answers.ts | 19 +- src/lib/state/keys.ts | 14 +- src/lib/state/store.svelte.ts | 8 +- src/lib/util/__tests__/approvalFooter.test.ts | 68 +++++ src/lib/util/__tests__/outcome.test.ts | 51 +++- src/lib/util/__tests__/sandbox.test.ts | 6 +- src/lib/util/approvalFooter.ts | 45 ++++ src/lib/util/outcome.ts | 51 +++- src/lib/util/sandbox.ts | 11 +- src/office/__tests__/denied.test.ts | 80 ++++++ src/office/model.ts | 3 +- src/office/reducer.ts | 44 +++- src/sheet/AgentSheet.svelte | 2 + 26 files changed, 1104 insertions(+), 73 deletions(-) create mode 100644 src/lib/__tests__/approvalSaid.test.ts create mode 100644 src/lib/__tests__/demoSaid.test.ts create mode 100644 src/lib/demo/said.ts create mode 100644 src/lib/util/__tests__/approvalFooter.test.ts create mode 100644 src/lib/util/approvalFooter.ts create mode 100644 src/office/__tests__/denied.test.ts diff --git a/README.md b/README.md index c41bc494..4c4f3b74 100644 --- a/README.md +++ b/README.md @@ -353,8 +353,9 @@ The full code map is in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md), section 8. repository's git data. It can still read your other files. - It can reach only the hosts that your Claude Code settings allow. Codly adds no host and no folder. When a command wants another host, Codly asks you, in every approval mode except Full access: the - approval card names the host. If you allow it, the host stays allowed for the rest of that agent's - session, for every later command. If you deny it, the command gets a network error. + approval card names the host. Approve once lets this command connect. Claude Code then does not ask + again for this host while this agent keeps running. When the agent starts again (Codly restarts, or + a change that restarts the agent) it asks again. If you deny it, the command gets a network error. - Commands still go through the approval rules, as they do with the switch off: what the rules ask about (a `git push`, an `rm -rf`, a download) still asks you first. The sandbox is a second check under the rules, not a way around them. So one command can ask twice: once for itself, and once diff --git a/crates/codly-core/src/model.rs b/crates/codly-core/src/model.rs index d8d28944..fecfd270 100644 --- a/crates/codly-core/src/model.rs +++ b/crates/codly-core/src/model.rs @@ -1573,6 +1573,19 @@ pub enum EventKind { ApprovalRequested { approval: Approval, }, + /// What you said with your answer to a request, when it carried words: the note of a "no", + /// the answer to a question, or that you changed a plan before you accepted it. It comes + /// just before the `ApprovalResolved` of that answer, and only for an answer that went to + /// the agent. A request answered without words has no such row. + ApprovalSaid { + approval_id: Id, + /// What you told the agent to do instead (at most 2000 characters). + note: Option, + /// Your answers to a question, on one line (at most 500 characters). + answer: Option, + /// The plan was accepted with your text in place of the agent's. + plan_changed: bool, + }, ApprovalResolved { approval_id: Id, status: ApprovalStatus, @@ -1752,6 +1765,7 @@ impl EventKind { EventKind::FilesChanged { .. } => "files_changed", EventKind::PlanUpdated { .. } => "plan_updated", EventKind::ApprovalRequested { .. } => "approval_requested", + EventKind::ApprovalSaid { .. } => "approval_said", EventKind::ApprovalResolved { .. } => "approval_resolved", EventKind::UsageUpdated { .. } => "usage_updated", EventKind::RateLimit { .. } => "rate_limit", diff --git a/crates/codly-core/src/orchestrator/workspace.rs b/crates/codly-core/src/orchestrator/workspace.rs index 9bdc5e9d..05432743 100644 --- a/crates/codly-core/src/orchestrator/workspace.rs +++ b/crates/codly-core/src/orchestrator/workspace.rs @@ -9,10 +9,11 @@ use std::time::{Duration, Instant}; use anyhow::{anyhow, bail}; use serde::{Deserialize, Serialize}; -use serde_json::json; +use serde_json::{Value, json}; use super::{Inner, guard, lock, merge_conflict, names, prompts, row, scheduler, write}; use crate::adapters::AgentCmd; +use crate::adapters::claude::EXIT_PLAN_MODE; use crate::git::{MergeOutcome, name_list}; use crate::index::{Index, WorktreeView}; use crate::memory::{self, MemoryView}; @@ -414,6 +415,7 @@ impl Inner { bail!("the agent did not offer '{}'", store::enum_str(&decision.choice)); } let ws = self.store.agent_workspace(&a.agent_id)?; + let claude = self.store.agent(&a.agent_id)?.is_some_and(|agent| agent.provider == Provider::Claude); let sent = { let live = lock(&self.live); // A run that is being stopped (you killed the agent, or Codly ended it) takes no @@ -422,6 +424,15 @@ impl Inner { .filter(|l| l.run_id == a.run_id && !l.stopping) .is_some_and(|l| l.handle.send(AgentCmd::Approval { approval_id: a.id.clone(), decision: decision.clone() })) }; + // What you said with the answer goes on record just before the answer. Only for an + // answer that went to the agent: a request that expired heard nothing. + if sent && let Some(said) = said_with(&a, &decision, claude) { + // The agent has the answer by now: words that cannot be stored must not keep the + // answer itself off the record. + if let Err(e) = self.emit(ws.as_deref(), row(Some(&a.agent_id), a.task_id.as_deref(), Some(&a.run_id), said)) { + tracing::warn!("what you said with the answer to approval {} is not on record: {e}", a.id); + } + } let status = if !sent { ApprovalStatus::Expired } else { @@ -1179,6 +1190,68 @@ fn expand_home(p: &str) -> PathBuf { } } +/// What goes on record as said with an answer (`EventKind::ApprovalSaid`). None: the answer +/// carried no words. `claude`: the agent that asked runs Claude Code. +/// - The note of a "no" (deny, or stop the turn). Only Claude Code hands it to the agent +/// (`claude.rs`, `answer`). The answers Codex and the ACP agents take have no place for a +/// note, so for those agents it is not recorded as said: the agent never read it. +/// - Your answers to a question, on one line. +/// - That a plan was accepted with your text: only Claude Code's plan request takes one. +fn said_with(asked: &Approval, d: &ApprovalDecision, claude: bool) -> Option { + const NOTE_MAX: usize = 2000; + const ANSWER_MAX: usize = 500; + let allow = matches!(d.choice, ApprovalChoice::AllowOnce | ApprovalChoice::AllowSession | ApprovalChoice::AllowAlways); + let note = d.message.as_deref().map(str::trim).filter(|m| claude && !allow && !m.is_empty()).map(|m| prompts::clip(m, NOTE_MAX)); + let answer = match (&asked.subject, &d.answers) { + (ApprovalSubject::Question { questions }, Some(answers)) if allow => answer_line(questions, answers).map(|a| prompts::clip(&a, ANSWER_MAX)), + _ => None, + }; + let plan_changed = match (&asked.subject, &d.answers) { + (ApprovalSubject::Tool { name, input }, Some(answers)) if claude && allow && name == EXIT_PLAN_MODE => { + answers["plan"].as_str().is_some_and(|plan| input["plan"].as_str() != Some(plan)) + } + _ => false, + }; + (note.is_some() || answer.is_some() || plan_changed).then(|| EventKind::ApprovalSaid { approval_id: asked.id.clone(), note, answer, plan_changed }) +} + +/// The answers to a question request on one line, in the order the questions were asked: +/// "Keep it", "Red; Small, Fast" (a question with several picks lists them). None when +/// nothing was picked or typed. Claude Code files an answer under its question's text. Codex +/// files it under the question's id, as `{ answers: [...] }`, and marks a question whose +/// answer is a secret (`isSecret`): that answer is left out, it must not be stored +/// (`ToolRequestUserInputQuestion` and `ToolRequestUserInputResponse` of codex-cli 0.166.0). +fn answer_line(questions: &Value, answers: &Value) -> Option { + let answers = answers.as_object()?; + let mut keys: Vec<&str> = Vec::new(); + let mut secret: Vec<&str> = Vec::new(); + for q in questions.as_array().or_else(|| questions["questions"].as_array()).into_iter().flatten() { + for key in [q["question"].as_str(), q["id"].as_str()].into_iter().flatten() { + if q["isSecret"] == true { + secret.push(key); + } else if answers.contains_key(key) && !keys.contains(&key) { + keys.push(key); + } + } + } + // Then what no question names: the free answer to a request that lists no questions. + for key in answers.keys().map(String::as_str) { + if !secret.contains(&key) && !keys.contains(&key) { + keys.push(key); + } + } + let picks = |v: &Value| v.as_array().map(|list| list.iter().filter_map(Value::as_str).filter(|s| !s.is_empty()).collect::>().join(", ")); + let said: Vec = keys + .into_iter() + .map(|key| { + let v = &answers[key]; + v.as_str().map(|s| s.trim().to_string()).or_else(|| picks(v)).or_else(|| picks(&v["answers"])).unwrap_or_default() + }) + .filter(|s| !s.is_empty()) + .collect(); + (!said.is_empty()).then(|| said.join("; ")) +} + #[cfg(test)] mod tests { use super::*; @@ -1247,4 +1320,108 @@ mod tests { let wanted = [(100, ago(30)), (200, ago(30)), (500, ago(183_845)), (100, ago(30))]; assert_eq!(orphans(&snapshot, &wanted), [100, 500]); } + + fn asked(subject: ApprovalSubject) -> Approval { + Approval { + id: "ap".into(), + agent_id: "a".into(), + run_id: "r".into(), + task_id: None, + call_id: None, + subject, + reason: None, + choices: vec![], + risks: vec![], + status: ApprovalStatus::Pending, + decided_by: None, + created_at: 0, + } + } + + fn decision(choice: ApprovalChoice, message: Option<&str>, answers: Option) -> ApprovalDecision { + ApprovalDecision { choice, message: message.map(String::from), answers } + } + + /// (note, answer, plan changed) of what goes on record, or None. + fn said(a: &Approval, d: &ApprovalDecision, claude: bool) -> Option<(Option, Option, bool)> { + match said_with(a, d, claude)? { + EventKind::ApprovalSaid { approval_id, note, answer, plan_changed } => { + assert_eq!(approval_id, a.id); + Some((note, answer, plan_changed)) + } + other => panic!("not what you said: {other:?}"), + } + } + + #[test] + fn the_note_of_a_no_is_on_record_only_where_the_agent_reads_it() { + let command = asked(ApprovalSubject::Command { command: "npm install".into(), cwd: None }); + let no = decision(ApprovalChoice::Deny, Some(" use pnpm "), None); + assert_eq!(said(&command, &no, true), Some((Some("use pnpm".into()), None, false))); + assert_eq!(said(&command, &decision(ApprovalChoice::Cancel, Some("stop here"), None), true), Some((Some("stop here".into()), None, false))); + // Codex and the ACP agents get the "no" without the note. + assert_eq!(said(&command, &no, false), None); + // An answer with no words, a note of blanks, and a note beside a "yes" (no CLI reads it). + assert_eq!(said(&command, &decision(ApprovalChoice::Deny, None, None), true), None); + assert_eq!(said(&command, &decision(ApprovalChoice::Deny, Some(" "), None), true), None); + assert_eq!(said(&command, &decision(ApprovalChoice::AllowOnce, Some("use pnpm"), None), true), None); + // A long note is cut, by characters. + let long = decision(ApprovalChoice::Deny, Some(&"é".repeat(3000)), None); + let (note, ..) = said(&command, &long, true).unwrap(); + assert_eq!(note.unwrap().chars().count(), 2000); + } + + #[test] + fn the_answers_to_a_question_are_one_line_in_the_order_asked() { + // Claude Code's AskUserQuestion: an answer is filed under its question's text. + let claude = asked(ApprovalSubject::Question { + questions: json!([{ "question": "Which sizes?", "multiSelect": true }, { "question": "Colour?" }, { "question": "Anything else?" }]), + }); + let answers = json!({ "Colour?": " Red ", "Which sizes?": ["Small", "", "Fast"], "Anything else?": "" }); + let yes = decision(ApprovalChoice::AllowOnce, None, Some(answers.clone())); + assert_eq!(said(&claude, &yes, true), Some((None, Some("Small, Fast; Red".into()), false))); + // A skipped question carries no answer; nothing picked says nothing. + assert_eq!(said(&claude, &decision(ApprovalChoice::Deny, None, Some(answers)), true), None); + assert_eq!(said(&claude, &decision(ApprovalChoice::AllowOnce, None, Some(json!({ "Colour?": "" }))), true), None); + assert_eq!(said(&claude, &decision(ApprovalChoice::AllowOnce, None, None), true), None); + + // Codex's requestUserInput, written from the schema types of codex-cli 0.166.0 + // (`ToolRequestUserInputQuestion`, `ToolRequestUserInputResponse`): the answers are + // filed under the question's id, and a secret one is not stored. + let codex = asked(ApprovalSubject::Question { + questions: json!([ + { "id": "q2", "header": "DB", "question": "Which database?", "isOther": false, "isSecret": false, "options": null }, + { "id": "q1", "header": "Token", "question": "The token?", "isOther": true, "isSecret": true, "options": null }, + ]), + }); + let answers = json!({ "q1": { "answers": ["s3cret"] }, "q2": { "answers": ["sqlite", "in memory"] } }); + assert_eq!(said(&codex, &decision(ApprovalChoice::AllowOnce, None, Some(answers)), false), Some((None, Some("sqlite, in memory".into()), false))); + // The same secret, filed under the question's text. + let by_text = json!({ "The token?": "s3cret" }); + assert_eq!(said(&codex, &decision(ApprovalChoice::AllowOnce, None, Some(by_text)), false), None); + + // A request that lists no questions: the free answer. A long line is cut. + let free = asked(ApprovalSubject::Question { questions: json!({ "message": "Your name?" }) }); + assert_eq!(said(&free, &decision(ApprovalChoice::AllowOnce, None, Some(json!({ "answer": "Ada" }))), false), Some((None, Some("Ada".into()), false))); + let (_, answer, _) = said(&free, &decision(ApprovalChoice::AllowOnce, None, Some(json!({ "answer": "x".repeat(600) }))), false).unwrap(); + assert_eq!(answer.unwrap().chars().count(), 500); + // The answers of a request that is no question are not an answer to show. + let command = asked(ApprovalSubject::Command { command: "ls".into(), cwd: None }); + assert_eq!(said(&command, &decision(ApprovalChoice::AllowOnce, None, Some(json!({ "answer": "Ada" }))), true), None); + } + + #[test] + fn a_plan_accepted_with_your_text_says_so() { + let plan = asked(ApprovalSubject::Tool { name: EXIT_PLAN_MODE.into(), input: json!({ "plan": "1. Add the line" }) }); + let with = |text: &str| decision(ApprovalChoice::AllowOnce, None, Some(json!({ "plan": text }))); + assert_eq!(said(&plan, &with("1. Add two lines"), true), Some((None, None, true))); + // The agent's own text back, a plain accept, and a plan sent back with a note. + assert_eq!(said(&plan, &with("1. Add the line"), true), None); + assert_eq!(said(&plan, &decision(ApprovalChoice::AllowOnce, None, None), true), None); + assert_eq!(said(&plan, &decision(ApprovalChoice::Deny, Some("Say which file."), Some(json!({ "plan": "x" }))), true), Some((Some("Say which file.".into()), None, false))); + // That request is Claude Code's own: no other CLI, and no other tool, takes a changed plan. + assert_eq!(said(&plan, &with("1. Add two lines"), false), None); + let other = asked(ApprovalSubject::Tool { name: "WebFetch".into(), input: json!({ "plan": "1. Add the line" }) }); + assert_eq!(said(&other, &with("1. Add two lines"), true), None); + } } diff --git a/crates/codly-core/src/store/mod.rs b/crates/codly-core/src/store/mod.rs index bba3c9c0..6669cdfa 100644 --- a/crates/codly-core/src/store/mod.rs +++ b/crates/codly-core/src/store/mod.rs @@ -203,7 +203,7 @@ impl Store { /// One page of a conversation's history, newest first (the "Load earlier" control). A thread /// shows more than one agent's events, so its page is the newest `limit` rows before `before` of: /// - every event of `owner`, the agent the thread belongs to (a request's Lead, a 1:1's agent); - /// - approvals (asked and answered) and results (commits, checks, reviews, merges) of the + /// - approvals (asked, what you said, answered) and results (commits, checks, reviews, merges) of the /// thread's tasks, by whoever did them: a request's tasks are its plans' (tasks with no /// plan belong to "lead"), a 1:1's are the ones assigned to its agent; /// - a request's messages. A closed request's messages moved to its archive thread, so the @@ -242,7 +242,7 @@ impl Store { let mut st = conn.prepare_cached(&format!( "SELECT id, ts, agent_id, task_id, run_id, type, payload FROM event WHERE task_id IN ({tasks}) AND id < ?3 - AND type IN ('approval_requested', 'approval_resolved', 'committed', 'verified', 'reviewed', 'merged') + AND type IN ('approval_requested', 'approval_said', 'approval_resolved', 'committed', 'verified', 'reviewed', 'merged') ORDER BY id DESC LIMIT ?4" ))?; let found = st.query_map(params![workspace_id, of, before, limit], event_from_row)?; @@ -1785,6 +1785,43 @@ mod tests { assert_eq!(t.page("agent:worker", Some("worker"), None, 50).len(), 5, "its message, its work, the approval (asked, answered) and the check"); } + /// What you said with an answer is a row of the request's thread, like the answer: a page + /// of the Lead's thread has the note you gave a worker. + #[test] + fn a_thread_page_has_what_you_said_to_its_tasks_requests() { + let t = Threads::new(); + let approval = Approval { + id: new_id(), + agent_id: "worker".into(), + run_id: "r".into(), + task_id: Some("t1".into()), + call_id: None, + subject: ApprovalSubject::Command { command: "npm install".into(), cwd: None }, + reason: None, + choices: vec![ApprovalChoice::AllowOnce, ApprovalChoice::Deny], + risks: vec![], + status: ApprovalStatus::Pending, + decided_by: None, + created_at: now_ms(), + }; + let asked = t.add(Some("worker"), Some("t1"), EventKind::ApprovalRequested { approval: approval.clone() }); + let said = EventKind::ApprovalSaid { approval_id: approval.id.clone(), note: Some("use pnpm".into()), answer: None, plan_changed: false }; + let said = t.add(Some("worker"), Some("t1"), said); + // The row changes nothing: the request still waits for its answer. + assert_eq!(t.store.approval(&approval.id).unwrap().unwrap().status, ApprovalStatus::Pending); + let answer = EventKind::ApprovalResolved { approval_id: approval.id.clone(), status: ApprovalStatus::Denied, by: "user".into() }; + let answered = t.add(Some("worker"), Some("t1"), answer); + + assert_eq!(t.page("lead:x", Some("lead"), None, 50), vec![answered, said, asked]); + let page = t.store.thread_events(&t.ws, "lead:x", Some("lead"), None, 50).unwrap(); + let note = page.iter().find_map(|e| match &e.kind { + EventKind::ApprovalSaid { note, .. } => note.clone(), + _ => None, + }); + assert_eq!(note.as_deref(), Some("use pnpm"), "the row comes back from the log as it was written"); + assert!(t.page("lead:y", Some("other-lead"), None, 50).is_empty(), "not in another request's thread"); + } + #[test] fn a_closed_requests_messages_stay_out_of_the_reused_thread() { let t = Threads::new(); diff --git a/crates/codly-core/tests/orchestrator_approvals.rs b/crates/codly-core/tests/orchestrator_approvals.rs index 33619a3e..9fdf2349 100644 --- a/crates/codly-core/tests/orchestrator_approvals.rs +++ b/crates/codly-core/tests/orchestrator_approvals.rs @@ -913,3 +913,237 @@ fn the_own_folder_floor_adds_nothing_outside_full_access() { assert!(reason(eval_in("git reset --hard", ApprovalMode::Full, true)).starts_with("risk: discards changes")); assert!(allowed(&eval_in("git status", ApprovalMode::Balanced, false))); } + +/// What you said with an answer, end to end with a fake agent in place of the CLI: your words +/// are a row of the log just before the answer, and only when the answer went to the agent. +mod what_you_said { + use std::path::{Path, PathBuf}; + use std::process::Command; + use std::sync::Arc; + use std::time::Duration; + + use codly_core::adapters::{AdapterEvent, AgentCmd, AgentHandle, SpawnSpec}; + use codly_core::model::*; + use codly_core::orchestrator::{Core, CoreConfig, SpawnFuture, Spawner, StartOptions}; + use serde_json::{Value, json}; + use tokio::sync::mpsc; + + fn git(dir: &Path, args: &[&str]) { + let out = Command::new("git").arg("-C").arg(dir).args(args).env("LC_ALL", "C").output().unwrap(); + assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr)); + } + + fn temp_repo(root: &Path) -> PathBuf { + let repo = root.join("repo"); + std::fs::create_dir_all(&repo).unwrap(); + git(&repo, &["init", "-q", "-b", "main"]); + git(&repo, &["config", "user.name", "Test"]); + git(&repo, &["config", "user.email", "test@example.com"]); + std::fs::write(repo.join("README.md"), "# demo\n").unwrap(); + git(&repo, &["add", "-A"]); + git(&repo, &["commit", "-qm", "init"]); + repo + } + + /// What a message "ask: " makes the fake agent ask you. + fn subject(what: &str) -> Option { + match what { + // Not a read or a test run: balanced mode asks you. + "command" => Some(ApprovalSubject::Command { command: "node scripts/gen.js".into(), cwd: None }), + "plan" => Some(ApprovalSubject::Tool { name: "ExitPlanMode".into(), input: json!({ "plan": "1. Add the line" }) }), + "question" => Some(ApprovalSubject::Question { questions: json!([{ "question": "Which sizes?", "multiSelect": true }, { "question": "Colour?" }]) }), + _ => None, + } + } + + /// A fake Claude agent: a message "ask: command", "ask: plan" or "ask: question" makes it + /// ask you that, and its turn ends when the answer arrives. Its process takes a second to + /// end, like a real CLI's: a card is still on screen meanwhile. + struct Fake; + + impl Spawner for Fake { + fn spawn(&self, spec: SpawnSpec, events: mpsc::UnboundedSender) -> SpawnFuture { + Box::pin(async move { + let (tx, mut rx) = mpsc::unbounded_channel::(); + let (agent_id, run_id) = (spec.agent_id.clone(), spec.run_id.clone()); + let send = { + let (agent_id, run_id) = (agent_id.clone(), run_id.clone()); + move |kind| { + let _ = events.send(AdapterEvent { agent_id: agent_id.clone(), run_id: run_id.clone(), kind }); + } + }; + send(EventKind::SessionStarted { + provider: spec.provider, + model: None, + cwd: spec.cwd.to_string_lossy().into_owned(), + cli_version: None, + session_id: Some("sess".into()), + billing: Billing::Subscription, + tools: vec![], + }); + let handle = AgentHandle { agent_id: agent_id.clone(), run_id: run_id.clone(), tx }; + tokio::spawn(async move { + while let Some(cmd) = rx.recv().await { + match cmd { + AgentCmd::Prompt(text) => { + send(EventKind::TurnStarted { input: Some(text.clone()) }); + let asked = text.rsplit_once("ask: ").and_then(|(_, what)| subject(what.lines().next().unwrap_or_default().trim())); + if let Some(subject) = asked { + let approval = Approval { + id: new_id(), + agent_id: agent_id.clone(), + run_id: run_id.clone(), + task_id: None, + call_id: Some("c1".into()), + subject, + reason: None, + choices: vec![ApprovalChoice::AllowOnce, ApprovalChoice::Deny], + risks: vec![], + status: ApprovalStatus::Pending, + decided_by: None, + created_at: now_ms(), + }; + send(EventKind::ApprovalRequested { approval }); + // The answer arrives as the next command; a stop ends the process. + if let Some(AgentCmd::Shutdown) = rx.recv().await { + tokio::time::sleep(Duration::from_secs(1)).await; + send(EventKind::Exited { code: Some(0) }); + break; + } + } + send(EventKind::TurnCompleted { status: TurnStatus::Completed, result_text: None, duration_ms: Some(1) }); + } + AgentCmd::Shutdown => { + send(EventKind::Exited { code: Some(0) }); + break; + } + AgentCmd::Interrupt | AgentCmd::Approval { .. } | AgentCmd::Session { .. } => {} + } + } + }); + Ok(handle) + }) + } + } + + async fn wait_for(what: &str, mut f: impl AsyncFnMut() -> Option) -> T { + let deadline = tokio::time::Instant::now() + Duration::from_secs(10); + loop { + if let Some(v) = f().await { + return v; + } + assert!(tokio::time::Instant::now() < deadline, "timed out waiting for {what}"); + tokio::time::sleep(Duration::from_millis(25)).await; + } + } + + /// A started core with one hired 1:1 Claude agent (balanced mode, the default). + async fn one_agent(dir: &Path) -> (Arc, String) { + let repo = temp_repo(dir); + let cfg = CoreConfig { data_dir: dir.join("data"), app_exe: PathBuf::from("/usr/bin/true") }; + let claude = CliInfo { + provider: Provider::Claude, + path: Some("/usr/bin/true".into()), + version: Some("fake".into()), + logged_in: Some(true), + billing: Billing::Subscription, + plan: None, + problem: None, + transport: "fake".into(), + install: codly_core::env::install_hint(Provider::Claude), + default_model: None, + }; + let opts = StartOptions { spawner: Some(Arc::new(Fake)), env: Some(std::env::vars().collect()), clis: Some(vec![claude]), index: false }; + let core = Core::start_with(cfg, opts).await.unwrap(); + core.open_workspace(repo.to_str().unwrap()).await.unwrap(); + let agent = core.hire_agent(Provider::Claude, None, None).await.unwrap(); + (core, agent.id) + } + + /// Make the agent ask (once its last turn is over), and wait for the request. + async fn ask(core: &Core, agent: &str, what: &str) -> Approval { + wait_for("the agent to be free", async || { + let a = core.snapshot().await.unwrap().agents.into_iter().find(|a| a.id == agent)?; + matches!(a.status, AgentStatus::Idle | AgentStatus::Offline).then_some(()) + }) + .await; + core.send_chat(&format!("agent:{agent}"), &format!("ask: {what}")).await.unwrap(); + wait_for("the request to wait for you", async || core.snapshot().await.unwrap().approvals.into_iter().find(|a| a.status == ApprovalStatus::Pending)).await + } + + /// The rows of the log about a request's answer, oldest first, as the app gets them. + async fn rows(core: &Core, approval: &Approval) -> Vec { + let mut events = core.events(None, None, 2000).await.unwrap(); + events.sort_by_key(|e| e.id); + events + .into_iter() + .filter(|e| matches!(&e.kind, EventKind::ApprovalSaid { approval_id, .. } | EventKind::ApprovalResolved { approval_id, .. } if *approval_id == approval.id)) + .map(|e| serde_json::to_value(&e.kind).unwrap()) + .collect() + } + + fn resolved(approval: &Approval, status: &str) -> Value { + json!({ "type": "approval_resolved", "approval_id": approval.id, "status": status, "by": "user" }) + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_no_with_a_note_is_on_record_just_before_the_answer() { + let dir = tempfile::tempdir().unwrap(); + let (core, agent) = one_agent(dir.path()).await; + + let command = ask(&core, &agent, "command").await; + core.resolve_approval(&command.id, ApprovalDecision { choice: ApprovalChoice::Deny, message: Some(" use pnpm run gen ".into()), answers: None }).await.unwrap(); + let said = json!({ "type": "approval_said", "approval_id": command.id, "note": "use pnpm run gen", "answer": null, "plan_changed": false }); + assert_eq!(rows(&core, &command).await, [said.clone(), resolved(&command, "denied")]); + // The row is in the agent's own thread too, where "Load earlier" reads it. + let thread = core.thread_events(&format!("agent:{agent}"), Some(&agent), None, 2000).await.unwrap(); + assert!(thread.iter().any(|e| serde_json::to_value(&e.kind).unwrap() == said)); + + // An answer with no words is one row, as before. + let again = ask(&core, &agent, "command").await; + core.resolve_approval(&again.id, ApprovalDecision { choice: ApprovalChoice::Deny, message: None, answers: None }).await.unwrap(); + assert_eq!(rows(&core, &again).await, [resolved(&again, "denied")]); + core.shutdown().await; + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn the_answers_to_a_question_and_a_changed_plan_are_on_record() { + let dir = tempfile::tempdir().unwrap(); + let (core, agent) = one_agent(dir.path()).await; + + let question = ask(&core, &agent, "question").await; + let answers = json!({ "Colour?": "Red", "Which sizes?": ["Small", "Fast"] }); + core.resolve_approval(&question.id, ApprovalDecision { choice: ApprovalChoice::AllowOnce, message: None, answers: Some(answers) }).await.unwrap(); + // One line, in the order the questions were asked. + let said = json!({ "type": "approval_said", "approval_id": question.id, "note": null, "answer": "Small, Fast; Red", "plan_changed": false }); + assert_eq!(rows(&core, &question).await, [said, resolved(&question, "approved")]); + + let plan = ask(&core, &agent, "plan").await; + let changed = json!({ "plan": "1. Add two lines" }); + core.resolve_approval(&plan.id, ApprovalDecision { choice: ApprovalChoice::AllowOnce, message: None, answers: Some(changed) }).await.unwrap(); + let said = json!({ "type": "approval_said", "approval_id": plan.id, "note": null, "answer": null, "plan_changed": true }); + assert_eq!(rows(&core, &plan).await, [said, resolved(&plan, "approved")]); + + // A plan accepted as it is says nothing more. + let plain = ask(&core, &agent, "plan").await; + core.resolve_approval(&plain.id, ApprovalDecision { choice: ApprovalChoice::AllowOnce, message: None, answers: None }).await.unwrap(); + assert_eq!(rows(&core, &plain).await, [resolved(&plain, "approved")]); + core.shutdown().await; + } + + /// The agent was killed while its request waited: an answer that still arrives is refused, + /// and the note that came with it is not recorded as said. The agent never read it. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_request_that_expired_has_no_words_on_record() { + let dir = tempfile::tempdir().unwrap(); + let (core, agent) = one_agent(dir.path()).await; + + let command = ask(&core, &agent, "command").await; + core.stop_agent(&agent).await.unwrap(); + let no = ApprovalDecision { choice: ApprovalChoice::Deny, message: Some("use pnpm run gen".into()), answers: None }; + let refused = core.resolve_approval(&command.id, no).await.expect_err("a killed agent takes no answer").to_string(); + assert_eq!(refused, "the agent that asked is no longer running; the request expired"); + assert_eq!(rows(&core, &command).await, [resolved(&command, "expired")]); + core.shutdown().await; + } +} diff --git a/src/home/cards/ApprovalCard.svelte b/src/home/cards/ApprovalCard.svelte index 0c488587..7c34e63b 100644 --- a/src/home/cards/ApprovalCard.svelte +++ b/src/home/cards/ApprovalCard.svelte @@ -5,7 +5,9 @@ Questions (AskUserQuestion / requestUserInput) render as a choice to answer. A plan (Claude's plan mode asks to leave it with `ExitPlanMode`) renders as the plan itself: accept it, accept it with your changes (Claude Code takes your text as the plan), or send it - back with a note. + back with a note. It has no plain "no" (`footerButtons`): ⌘⌫ opens the note field too. + Once answered, the card is one row: how it ended, and what you said with the answer (your + answer to a question, the note of a "no", that you changed the plan), as the core recorded it. The plan card and the card for a host that Claude Code's sandbox blocks are for Claude agents only: these two tool names are Claude Code's own, and for any other CLI a request with such a name shows as every other tool request, by its name and its input. @@ -29,8 +31,9 @@ import { store } from '../../lib/state/store.svelte'; import { ui } from '../../lib/state/ui.svelte'; import { clock, timer } from '../../lib/util/format'; + import { footerButtons, PLAN_NOTE_HINT, type FooterButton } from '../../lib/util/approvalFooter'; import { idVar } from '../../lib/util/labels'; - import { outcomeBy, outcomeWord } from '../../lib/util/outcome'; + import { outcomeBy, settledWord, wordsOf } from '../../lib/util/outcome'; import { shownPlan } from '../../lib/util/planRequest'; import { HOST_ALLOW_LASTS, sandboxHost, sandboxWants } from '../../lib/util/sandbox'; import { oneLine, tildify } from '../../lib/util/sanitize'; @@ -104,16 +107,13 @@ return lines; }); - const CHOICE: Record = { - allow_once: { label: 'Approve once', kbd: '⌘↵', cls: 'primary' }, - allow_session: { label: 'Allow for this session', kbd: '⌥⌘↵', cls: '' }, - allow_always: { label: 'Always allow', cls: '' }, - deny: { label: 'Deny', kbd: '⌘⌫', cls: 'ghost' }, - cancel: { label: 'Stop the turn', cls: 'danger' }, - }; - const ORDER: ApprovalChoice[] = ['allow_once', 'allow_session', 'allow_always', 'deny', 'cancel']; - /** A plan is accepted or rejected, not "approved once". */ - const choiceLabel = (c: ApprovalChoice) => (plan === null ? CHOICE[c].label : c === 'allow_once' ? 'Accept the plan' : c === 'deny' ? 'Reject the plan' : CHOICE[c].label); + /** The buttons under the request: a plan has its own set, with no plain "no". */ + const buttons = $derived(footerButtons(plan !== null, approval.choices)); + function press(b: FooterButton) { + if (b.act === 'edit') openEdit(); + else if (b.act === 'note') openNote(); + else if (b.choice) decide(b.choice); + } async function decide(choice: ApprovalChoice, message: string | null = null, answers: JsonValue | null = null) { if (!pending || busy || !offered.has(choice)) return; @@ -186,6 +186,11 @@ noteOpen = true; tick().then(() => noteEl?.focus()); } + /** The "no" with what you wrote. A plan goes back only with a note: without one Claude Code shows the same plan again. */ + function sendNote() { + const text = note.trim(); + if (plan === null || text) decide('deny', text || null); + } $effect(() => { if (ui.denyNoteFor === approval.id) { ui.denyNoteFor = null; @@ -228,13 +233,17 @@ } const unanswered = $derived(questions.some((q, i) => q.options.length > 0 && !picks[i]?.length)); - // A question is answered or skipped, with what you answered; only a permission is approved or denied. - const outcome = $derived(outcomeWord(approval.status, approval)); + // A question is answered or skipped, a plan is accepted (with your changes, when you changed + // it) or sent back, every other request is approved or denied. Your words show after it. + const said = $derived(wordsOf(approval, approval.decided_by)); + const outcome = $derived(settledWord(approval.status, approval, agent?.provider ?? null, !!said?.planChanged)); const by = $derived(outcomeBy(approval.decided_by)); const answer = $derived(subject.kind === 'question' && approval.status === 'approved' ? (yourAnswers.get(approval.id) ?? null) : null); + /** Your words on the closed row: your answer to a question, or the note that went with a "no". */ + const quote = $derived(answer ?? said?.note ?? null); const what = $derived(subject.kind === 'command' ? subject.command : subject.kind === 'question' ? (questions[0]?.question ?? 'a question') : subject.kind === 'file_change' ? subject.paths.join(', ') : subject.kind === 'tool' ? (plan !== null ? 'its plan' : netHost !== null ? (netHost ? `network access to ${netHost}` : 'network access') : subject.name) : 'permissions'); - /** The closed row of an answered question cuts both to fit: the whole question and answer, for its tooltip. */ - const asked = $derived(answer ? `${oneLine(what, Infinity)} “${oneLine(answer, Infinity)}”` : null); + /** The closed row cuts what was asked and your words to fit: both whole, for its tooltip. */ + const asked = $derived(quote ? `${oneLine(what, Infinity)} “${oneLine(quote, Infinity)}”` : null); {#if !pending} @@ -242,10 +251,10 @@ {outcome} {by} {#if agent}{agent.name}{/if} - {#if answer} - + {#if quote} + {oneLine(what, 120)} - “{oneLine(answer, 80)}” + “{oneLine(quote, 80)}” {:else} {oneLine(what, 120)} {/if} @@ -320,11 +329,13 @@ {#if offered.has('deny')}{/if} {:else if noteOpen} -
      { e.preventDefault(); decide('deny', note.trim() || null); }}> + { e.preventDefault(); sendNote(); }}> e.key === 'Escape' && (e.stopPropagation(), (noteOpen = false))} /> - + +
      + {#if plan !== null}

      {PLAN_NOTE_HINT}

      {/if} {:else if editOpen}
      @@ -333,13 +344,11 @@

      {agent?.name ?? 'The agent'} then works from your text: Claude Code takes it as the plan.

      {:else}
      - {#each ORDER.filter((c) => offered.has(c)) as c (c)} - {/each} - {#if plan !== null && offered.has('allow_once')}{/if} - {#if offered.has('deny')}{/if}
      {#if rulePrefix || ruleExact}
      @@ -405,9 +414,9 @@ .r-l { color: var(--ink-2); white-space: nowrap; } .r-who { color: var(--ink-2); font-weight: var(--w-med); } .resolved code { flex: 1; font-size: 11.5px; color: var(--ink-3); } - /* An answered question keeps 40 % of the row: a long answer gives way first (its shrink factor takes - nearly all of the cut, hence the 1px over), and a short one leaves the question the rest. */ - .resolved code.asked { flex: 1 1 calc(40% + 1px); } - .r-a { flex: 0 9999 auto; color: var(--ink-1); } + /* A row with your words (an answer, a note): what was asked takes the room of its own text, up + to 60 % of the row, and your words take the rest. Both are cut when they do not fit. */ + .resolved code.asked { flex: 0 1 auto; max-width: 60%; } + .r-a { flex: 1 1 0; min-width: 0; color: var(--ink-1); } .resolved time { font-size: var(--t-xs); } diff --git a/src/lib/__tests__/answers.test.ts b/src/lib/__tests__/answers.test.ts index f152707c..b9ec0c15 100644 --- a/src/lib/__tests__/answers.test.ts +++ b/src/lib/__tests__/answers.test.ts @@ -1,5 +1,6 @@ -// The closed card of a question and the agent's history show what you answered. The core keeps -// no copy of an answer, so the app remembers the ones it sent. +// The closed card of a question and the agent's history show what you answered. The app +// remembers the answers it sent, so they show before the core's record of them comes back +// (that record: approvalSaid.test.ts). import { afterEach, describe, expect, it, vi } from 'vitest'; import { api } from '../api'; import { resolveApproval, resolveApprovals } from '../state/actions'; diff --git a/src/lib/__tests__/approvalSaid.test.ts b/src/lib/__tests__/approvalSaid.test.ts new file mode 100644 index 00000000..0a1bb87a --- /dev/null +++ b/src/lib/__tests__/approvalSaid.test.ts @@ -0,0 +1,92 @@ +// What you said with an answer (a note, an answer, a changed plan) is a row of the record +// (`approval_said`): the store reads it live, from a snapshot after a restart, and from an older +// page of a thread, so the closed card and the history show it each time. +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { mkAgent } from '../../office/demo/script'; +import { api } from '../api'; +import type { Approval } from '../gen/Approval'; +import type { EventKind } from '../gen/EventKind'; +import type { EventRow } from '../gen/EventRow'; +import type { Snapshot } from '../gen/Snapshot'; +import type { Task } from '../gen/Task'; +import type { Workspace } from '../gen/Workspace'; +import { yourAnswers, yourWords } from '../state/answers'; +import { store } from '../state/store.svelte'; + +// The store's transport: `subscribe` answers with the snapshot a test put here. +const core = vi.hoisted(() => ({ snapshot: null as unknown })); +vi.mock('../api', async (original) => ({ + ...(await original()), + getTransport: async () => ({ subscribe: async () => core.snapshot }), +})); + +const lead = mkAgent('lead1', 'Lead', 'claude', 'lead', 0, 'working', 'lead'); +let offices = 0; +/** A snapshot of a new office: the store then starts from nothing, as after a restart. */ +const snap = (o: Partial): Snapshot => + ({ + as_of: Math.max(0, ...(o.events ?? []).map((e) => e.id)), clis: [], accounts: [], workspace: { id: `said-w${++offices}`, name: 'w', repo_path: '/code/w' } as Workspace, + settings: null, workspace_team: null, request_prefs: {}, agents: [lead], plans: [], tasks: [], approvals: [], chats: [], memories: [], triples: [], artifacts: [], events: [], ...o, + }) as unknown as Snapshot; +const sync = async (s: Snapshot) => { + core.snapshot = s; + await store.connect(); + expect(store.error).toBeNull(); +}; +const apply = (...evs: EventRow[]) => (store as unknown as { applyEvents(evs: EventRow[]): void }).applyEvents(evs); + +// A worker's requests on task t1 (a task with no plan: the "lead" request's). +const at = (id: number, kind: unknown): EventRow => ({ id, ts: 1000 + id, agent_id: 'worker', task_id: 't1', run_id: 'r', kind: kind as EventKind }); +const approval = (id: string, subject: Approval['subject'], status: Approval['status']) => + ({ id, agent_id: 'worker', run_id: 'r', task_id: 't1', call_id: null, subject, reason: null, choices: ['allow_once', 'deny'], risks: [], status, decided_by: status === 'pending' ? null : 'user', created_at: 1000 }) as Approval; +const command: Approval['subject'] = { kind: 'command', command: 'npm install', cwd: null }; +const question: Approval['subject'] = { kind: 'question', questions: [{ question: 'Colour?' }] }; +const plan: Approval['subject'] = { kind: 'tool', name: 'ExitPlanMode', input: { plan: '1. Add the line' } }; +const asked = (id: number, a: Approval) => at(id, { type: 'approval_requested', approval: a }); +const said = (id: number, a: string, o: { note?: string; answer?: string; plan_changed?: boolean }) => + at(id, { type: 'approval_said', approval_id: a, note: o.note ?? null, answer: o.answer ?? null, plan_changed: o.plan_changed ?? false }); +const answered = (id: number, a: string, status: Approval['status']) => at(id, { type: 'approval_resolved', approval_id: a, status, by: 'user' }); +const t1 = { id: 't1', plan_id: null, status: 'done', assignee: 'worker' } as Task; + +afterEach(() => { + vi.restoreAllMocks(); + yourAnswers.clear(); + yourWords.clear(); +}); + +describe('what you said with an answer', () => { + it('is read again from the record after a restart: the note, the answer and the changed plan', async () => { + await sync(snap({ + tasks: [t1], + events: [ + asked(1, approval('ap-note', command, 'denied')), said(2, 'ap-note', { note: 'use pnpm' }), answered(3, 'ap-note', 'denied'), + asked(4, approval('ap-q', question, 'approved')), said(5, 'ap-q', { answer: 'Red' }), answered(6, 'ap-q', 'approved'), + asked(7, approval('ap-plan', plan, 'approved')), said(8, 'ap-plan', { plan_changed: true }), answered(9, 'ap-plan', 'approved'), + // Answered without words: one row, and nothing to show. + asked(10, approval('ap-plain', command, 'approved')), answered(11, 'ap-plain', 'approved'), + ], + })); + expect([...yourWords]).toEqual([['ap-note', { note: 'use pnpm', planChanged: false }], ['ap-plan', { note: null, planChanged: true }]]); + expect([...yourAnswers]).toEqual([['ap-q', 'Red']]); + // The closed cards are there to show it on. + expect(store.approvals.map((a) => [a.id, a.status])).toEqual([['ap-note', 'denied'], ['ap-q', 'approved'], ['ap-plan', 'approved'], ['ap-plain', 'approved']]); + }); + + it('is read from the live rows, which come just before the answer', async () => { + await sync(snap({ tasks: [t1], approvals: [approval('ap1', command, 'pending')] })); + apply(said(1, 'ap1', { note: 'use pnpm' })); + expect(yourWords.get('ap1')).toEqual({ note: 'use pnpm', planChanged: false }); + apply(answered(2, 'ap1', 'denied')); + expect(store.approvals.map((a) => [a.id, a.status, a.decided_by])).toEqual([['ap1', 'denied', 'user']]); + expect(yourAnswers.size).toBe(0); + }); + + it('is read from an older page of the thread ("Load earlier")', async () => { + await sync(snap({ tasks: [t1], events: [{ ...at(10, { type: 'reasoning', item_id: 'r10', text: 'hm' }), agent_id: 'lead1', task_id: null }] })); + // The core's page, newest first. The approval comes as it ended. + vi.spyOn(api, 'threadEvents').mockResolvedValue([answered(9, 'ap0', 'denied'), said(8, 'ap0', { note: 'not on main' }), asked(7, approval('ap0', command, 'denied'))]); + await store.loadEarlier('lead'); + expect(store.approvals.map((a) => [a.id, a.status])).toEqual([['ap0', 'denied']]); + expect([...yourWords]).toEqual([['ap0', { note: 'not on main', planChanged: false }]]); + }); +}); diff --git a/src/lib/__tests__/demoSaid.test.ts b/src/lib/__tests__/demoSaid.test.ts new file mode 100644 index 00000000..5da3e55e --- /dev/null +++ b/src/lib/__tests__/demoSaid.test.ts @@ -0,0 +1,88 @@ +// The browser demo puts what you said with an answer on record the way the core does: an +// `approval_said` row just before the answer, and only when the answer carried words. +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { saidWith } from '../demo/said'; +import { REPO, Sim } from '../demo/sim'; +import { Story, type StoryOptions } from '../demo/story'; +import type { Approval } from '../gen/Approval'; +import type { EventKind } from '../gen/EventKind'; +import { DEFAULT_SETTINGS } from '../state/store.svelte'; + +function demo(story: StoryOptions) { + const sim = new Sim({ speed: 1, skipMs: 0, autoplay: false }, { ...DEFAULT_SETTINGS }); + const s = new Story(sim, story); + s.openWorkspace(REPO); + return { sim, story: s }; +} + +/** Let the script play until `done`, for `seconds` of its time at most. */ +async function until(done: () => boolean, seconds = 400) { + for (let i = 0; i < seconds * 2 && !done(); i++) await vi.advanceTimersByTimeAsync(500); + expect(done(), 'the script got there in time').toBe(true); +} + +const requests = (sim: Sim, test: (a: Approval) => boolean) => [...sim.approvals.values()].filter(test); +/** The rows about one request's answer, in order: what you said, then how it ended. */ +const rows = (sim: Sim, id: string): EventKind[] => + sim.log.map((e) => e.kind).filter((k) => (k.type === 'approval_said' || k.type === 'approval_resolved') && k.approval_id === id); + +beforeEach(() => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date', 'performance'] }); + // Every pause and every length of a step is the same in each run. + vi.spyOn(Math, 'random').mockReturnValue(0.5); + // The story draws one picture on a canvas; a test has none. + vi.stubGlobal('OffscreenCanvas', class { getContext() { return null; } }); +}); +afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); + +describe('what you said with an answer, in the demo', () => { + it('a plan sent back with a note, then accepted with your changes, says both on record', async () => { + const { sim, story } = demo({ planMode: true, yourRequestFirst: true }); + const plans = () => requests(sim, (a) => a.subject.kind === 'tool' && a.subject.name === 'ExitPlanMode'); + await until(() => plans().length === 1); + + const first = plans()[0]; + story.resolveApproval(first.id, 'deny', ' Say which file changes. '); + expect(rows(sim, first.id)).toEqual([ + { type: 'approval_said', approval_id: first.id, note: 'Say which file changes.', answer: null, plan_changed: false }, + { type: 'approval_resolved', approval_id: first.id, status: 'denied', by: 'user' }, + ]); + + await until(() => plans().length === 2); + const second = plans()[1]; + story.resolveApproval(second.id, 'allow_once', null, { plan: '1. Change README.md only.' }); + expect(rows(sim, second.id)).toEqual([ + { type: 'approval_said', approval_id: second.id, note: null, answer: null, plan_changed: true }, + { type: 'approval_resolved', approval_id: second.id, status: 'approved', by: 'user' }, + ]); + + // An answer with no words is one row, as before. + const edits = () => requests(sim, (a) => a.subject.kind === 'file_change'); + await until(() => edits().length === 1); + story.resolveApproval(edits()[0].id, 'allow_once', null); + expect(rows(sim, edits()[0].id)).toEqual([{ type: 'approval_resolved', approval_id: edits()[0].id, status: 'approved', by: 'user' }]); + }); + + it('says what the core says: an answer to a question on one line, and no note for a CLI that does not pass it on', () => { + const request = (subject: Approval['subject']) => + ({ id: 'ap', agent_id: 'a', run_id: 'r', task_id: null, call_id: null, subject, reason: null, choices: ['allow_once', 'deny'], risks: [], status: 'pending', decided_by: null, created_at: 0 }) as Approval; + const question = request({ kind: 'question', questions: [{ question: 'Which sizes?', multiSelect: true }, { question: 'Colour?' }] }); + const command = request({ kind: 'command', command: 'npm install', cwd: null }); + const plan = request({ kind: 'tool', name: 'ExitPlanMode', input: { plan: '1. Add the line' } }); + + expect(saidWith(question, 'claude', 'allow_once', null, { 'Which sizes?': ['Small', 'Fast'], 'Colour?': 'Red' })).toEqual({ note: null, answer: 'Small, Fast; Red', plan_changed: false }); + expect(saidWith(question, 'claude', 'deny', null, null)).toBeNull(); + expect(saidWith(command, 'claude', 'deny', 'use pnpm', null)).toEqual({ note: 'use pnpm', answer: null, plan_changed: false }); + expect(saidWith(command, 'codex', 'deny', 'use pnpm', null)).toBeNull(); + expect(saidWith(command, 'claude', 'allow_once', null, null)).toBeNull(); + expect(saidWith(command, 'claude', 'deny', ' ', null)).toBeNull(); + // The agent's own text back is no change, and only Claude Code's plan request takes one. + expect(saidWith(plan, 'claude', 'allow_once', null, { plan: '1. Add the line' })).toBeNull(); + expect(saidWith(plan, 'codex', 'allow_once', null, { plan: '1. Add two lines' })).toBeNull(); + expect(saidWith(command, 'claude', 'deny', 'x'.repeat(3000), null)?.note).toHaveLength(2000); + }); +}); diff --git a/src/lib/demo/said.ts b/src/lib/demo/said.ts new file mode 100644 index 00000000..369267e9 --- /dev/null +++ b/src/lib/demo/said.ts @@ -0,0 +1,27 @@ +// What you said with an answer to a request, as the core puts it on record just before the +// answer (`said_with` in crates/codly-core/src/orchestrator/workspace.rs): the note of a "no", +// your answers to a question, and that a plan went ahead with your text. Null when the answer +// carried no words: then the demo, like the core, writes no `approval_said` row. +import type { Approval } from '../gen/Approval'; +import type { EventKind } from '../gen/EventKind'; +import type { Provider } from '../gen/Provider'; +import { answerText } from '../util/outcome'; +import { shownPlan } from '../util/planRequest'; +import { truncate } from '../util/sanitize'; + +type Said = Omit, 'type' | 'approval_id'>; + +/** `provider`: the CLI of the agent that asked. `choice`: what you answered. */ +export function saidWith(ap: Approval, provider: Provider | undefined, choice: string, message: string | null, answers: unknown): Said | null { + const allow = choice !== 'deny' && choice !== 'cancel'; + // Only Claude Code hands the note of a "no" to the agent: for another CLI it was never said. + const text = message?.trim(); + const note = provider === 'claude' && !allow && text ? truncate(text, 2000) : null; + const line = ap.subject.kind === 'question' && allow ? answerText(answers) : null; + const answer = line ? truncate(line, 500) : null; + // Only Claude Code's plan request takes your text as the plan. + const plan = shownPlan(ap.subject, provider); + const yours = answers && typeof answers === 'object' ? (answers as { plan?: unknown }).plan : null; + const plan_changed = allow && plan !== null && typeof yours === 'string' && yours !== plan; + return note || answer || plan_changed ? { note, answer, plan_changed } : null; +} diff --git a/src/lib/demo/story.ts b/src/lib/demo/story.ts index 96da9e40..d2d72280 100644 --- a/src/lib/demo/story.ts +++ b/src/lib/demo/story.ts @@ -32,6 +32,7 @@ import { ChecksDemo } from './checks'; import { DEMO_MCP, MODE_LABEL } from './controls'; import { BILLING } from './office'; import { BILLING_FILES, diffOf, INDEX, INDEX_AFTER, NEXT_BUMP, TASK_FILES, type RepoFile } from './repo'; +import { saidWith } from './said'; import { Actor, Cancelled, HOME, REPO, Sim, WORKTREES, sha, uid, type ToolSpec } from './sim'; import type { AskKind } from './states'; import { waitingOn } from '../util/plan'; @@ -1233,6 +1234,9 @@ export class Story { if (message) this.notes.set(id, message); const status = choice === 'deny' || choice === 'cancel' ? (choice === 'cancel' ? 'cancelled' : 'denied') : 'approved'; sim.approvals.set(id, { ...ap, status, decided_by: 'user' }); + // Like the core: what you said with the answer is a row of its own, just before the answer. + const said = saidWith(ap, sim.agents.get(ap.agent_id)?.provider, choice, message, answers); + if (said) sim.emit({ type: 'approval_said', approval_id: id, ...said }, { agent: ap.agent_id, task: ap.task_id, run: ap.run_id }); sim.emit({ type: 'approval_resolved', approval_id: id, status, by: 'user' }, { agent: ap.agent_id, task: ap.task_id, run: ap.run_id }); if (message) sim.decision('approval', 'human', `You denied ${'command' in ap.subject ? '`' + ap.subject.command + '`' : 'the request'}: “${message}”`, { approval: id }, { agent: ap.agent_id, task: ap.task_id }); } diff --git a/src/lib/gen/EventKind.ts b/src/lib/gen/EventKind.ts index 7f9fa34d..6de4df10 100644 --- a/src/lib/gen/EventKind.ts +++ b/src/lib/gen/EventKind.ts @@ -52,7 +52,19 @@ tests_passed: number | null, tests_failed: number | null, } | { "type": "files_c /** * "provider" | "tool_input" | "git" */ -source: string, } | { "type": "plan_updated", steps: Array, } | { "type": "approval_requested", approval: Approval, } | { "type": "approval_resolved", approval_id: string, status: ApprovalStatus, +source: string, } | { "type": "plan_updated", steps: Array, } | { "type": "approval_requested", approval: Approval, } | { "type": "approval_said", approval_id: string, +/** + * What you told the agent to do instead (at most 2000 characters). + */ +note: string | null, +/** + * Your answers to a question, on one line (at most 500 characters). + */ +answer: string | null, +/** + * The plan was accepted with your text in place of the agent's. + */ +plan_changed: boolean, } | { "type": "approval_resolved", approval_id: string, status: ApprovalStatus, /** * "user" | "policy" | "provider" */ diff --git a/src/lib/state/actions.ts b/src/lib/state/actions.ts index f496f532..2fa2e1e4 100644 --- a/src/lib/state/actions.ts +++ b/src/lib/state/actions.ts @@ -337,7 +337,8 @@ export async function resolveApproval(approvalId: string, choice: ApprovalChoice await api.resolveApproval(approvalId, { choice, message, answers: (answers ?? null) as never }); return true; }); - // The core keeps no copy of an answer: the closed card and the history show it from here. + // The core puts the answer on record (`approval_said`); until that row is here, the closed + // card and the history show it from this. const said = sent ? answerText(answers) : null; if (said) yourAnswers.set(approvalId, said); } diff --git a/src/lib/state/answers.ts b/src/lib/state/answers.ts index 987ef813..9e3ec78b 100644 --- a/src/lib/state/answers.ts +++ b/src/lib/state/answers.ts @@ -1,6 +1,19 @@ -// What you answered to an agent's question, by approval id. The core hands an answer to the -// agent's CLI and records only that the question was answered, so the words are known for the -// questions answered in this window: an older one reads "Answered by you" without them. +// What you said with your answer to an agent's request, by approval id: the answer to a +// question, the note of a "no", and that you changed a plan before you accepted it. The core +// puts it on record with the answer (the `approval_said` row), so it is known after a restart +// too. A request answered before the core recorded this reads "Answered by you" without the words. import { SvelteMap } from 'svelte/reactivity'; +import type { EventKind } from '../gen/EventKind'; +/** Your answer to a question, on one line. */ export const yourAnswers = new SvelteMap(); + +/** What else you said with an answer: the note of a "no", and that a plan went ahead with your text. */ +export type Words = { note: string | null; planChanged: boolean }; +export const yourWords = new SvelteMap(); + +/** A row of the record, live or read again: what you said with the answer to that request. */ +export function recordSaid(k: Extract): void { + if (k.answer) yourAnswers.set(k.approval_id, k.answer); + if (k.note || k.plan_changed) yourWords.set(k.approval_id, { note: k.note, planChanged: k.plan_changed }); +} diff --git a/src/lib/state/keys.ts b/src/lib/state/keys.ts index 8ef2431e..092aec04 100644 --- a/src/lib/state/keys.ts +++ b/src/lib/state/keys.ts @@ -1,10 +1,11 @@ // Global keyboard map. ⌘K palette · ⌘F find in the conversation · ⌘1 full office · ⌘2 full work · ⌘. focus · ⌘, settings · // ⌘N new request · ⌘[ / ⌘] previous / next request · ⇧⌘N new task · ⌘O open repo · ⌘↵ the one // primary action (approve / run plan) · ⌥⌘↵ allow for the session · ⌘⌫ deny · ⇧⌘⌫ deny with a -// note (both also from the empty composer) · G-sequences to rooms · J/K lists · Esc (close, +// note (both also from the empty composer; on a plan both open the note) · G-sequences to rooms · J/K lists · Esc (close, // deselect, then stop the running turn: the first press asks, the second stops) · ?. // ponytail: hand-rolled instead of tinykeys — one listener, sequences included. import type { Approval } from '../gen/Approval'; +import { showsPlan } from '../util/planRequest'; import { openWorkspace, resolveApprovals, runPlan, stopThreadByEsc } from './actions'; import { twinsIn } from './approvalGroups'; import { denyKeyInField, escStep } from './esc'; @@ -57,6 +58,15 @@ function keyTargetIds(ap: Approval): string[] { return [ap, ...twins].map((a) => a.id); } +/** + * What ⌘⌫ does to the request the keyboard acts on: say no at once, or open the note field + * first. ⇧⌘⌫ opens the note for every request. A Claude agent's plan always gets the note: its + * card has no plain "no", since without a note Claude Code shows the same plan again. + */ +export function denyKeyAction(ap: Approval, shift: boolean): 'deny' | 'note' { + return shift || showsPlan(ap.subject, store.agentMap.get(ap.agent_id)?.provider) ? 'note' : 'deny'; +} + /** The plan ⌘↵ runs when no approval is waiting: the one of the request you are on. */ export function keyTargetPlan(): string | null { if ((ui.mode === 'office' && ui.room === 'home') || ui.mode === 'map') return null; @@ -123,7 +133,7 @@ export function installKeys(): () => void { const ap = keyTargetApproval(); if (!ap || !ap.choices.includes('deny')) return; e.preventDefault(); - if (e.shiftKey) ui.denyNoteFor = ap.id; + if (denyKeyAction(ap, e.shiftKey) === 'note') ui.denyNoteFor = ap.id; else resolveApprovals(keyTargetIds(ap), 'deny'); return; } diff --git a/src/lib/state/store.svelte.ts b/src/lib/state/store.svelte.ts index 92b69bae..707beac9 100644 --- a/src/lib/state/store.svelte.ts +++ b/src/lib/state/store.svelte.ts @@ -45,6 +45,7 @@ import type { Provider } from '../gen/Provider'; import { targetLabel, type Provenance } from '../util/labels'; import { transferredOut } from '../util/transfer'; import { accounts } from './accounts.svelte'; +import { recordSaid } from './answers'; import { controls } from './control.svelte'; import { withBackgroundTasks, withMcpServer, type BackgroundWork, type McpServer } from './session'; @@ -61,7 +62,7 @@ const EARLIER_PAGE = 500; /** Event kinds whose derivation is no part of one agent's own state (`AgentLive`). */ const SHARED_KINDS: ReadonlySet = new Set([ 'control_changed', 'text_delta', 'reasoning_delta', 'tool_output', 'rate_limit', 'decision', - 'approval_requested', 'approval_resolved', 'committed', 'verified', 'reviewed', 'merged', + 'approval_requested', 'approval_said', 'approval_resolved', 'committed', 'verified', 'reviewed', 'merged', ]); export const DEFAULT_SETTINGS: Settings = { @@ -1060,6 +1061,10 @@ class CodlyStore { // was asked, then as it was answered. if (replay) this.pastApproval(k.approval); break; + case 'approval_said': + // What you said with an answer: the closed card and the history show it from here. + recordSaid(k); + break; case 'approval_resolved': { const a = replay ? this.approvals.find((x) => x.id === k.approval_id) : undefined; if (a) this.approvals = upsert(this.approvals, { ...a, status: k.status, decided_by: k.by }); @@ -1178,6 +1183,7 @@ class CodlyStore { const mark = markOf(ev); if (k.type === 'chat' && k.message.thread === thread && !known.has(k.message.id)) said.push(k.message); else if (k.type === 'approval_requested') this.pastApproval(k.approval); // the core sends it as it ended + else if (k.type === 'approval_said') recordSaid(k); else if (mark && ev.task_id) this.addMark(ev.task_id, mark); } if (said.length) this.chats = [...this.chats, ...said].sort((a, b) => a.ts - b.ts); diff --git a/src/lib/util/__tests__/approvalFooter.test.ts b/src/lib/util/__tests__/approvalFooter.test.ts new file mode 100644 index 00000000..cb676d66 --- /dev/null +++ b/src/lib/util/__tests__/approvalFooter.test.ts @@ -0,0 +1,68 @@ +// The buttons under a request that waits, per kind of card, and what ⌘⌫ does to it. +import { afterEach, describe, expect, it } from 'vitest'; +import { mkAgent } from '../../../office/demo/script'; +import type { Approval } from '../../gen/Approval'; +import type { ApprovalChoice } from '../../gen/ApprovalChoice'; +import { denyKeyAction } from '../../state/keys'; +import { store } from '../../state/store.svelte'; +import { footerButtons, PLAN_NOTE_HINT } from '../approvalFooter'; + +/** Label, key and what a press does: the answer it sends, or the field it opens. */ +const shown = (plan: boolean, offered: ApprovalChoice[]) => footerButtons(plan, offered).map((b) => [b.label, b.kbd ?? '', b.act === 'choice' ? b.choice : b.act]); + +describe('the buttons under a request', () => { + it('a plan is accepted, changed, sent back with a note or stopped: it has no plain "no"', () => { + // What Claude Code offers for a plan (2.1.311 recordings): allow, deny, and stop the turn. + expect(shown(true, ['allow_once', 'deny', 'cancel'])).toEqual([ + ['Accept the plan', '⌘↵', 'allow_once'], + ['Change the plan…', '', 'edit'], + ['Send it back with a note…', '⌘⌫', 'note'], + ['Stop the turn', '', 'cancel'], + ]); + // No button sends a bare deny, and "Reject the plan" is gone. + expect(footerButtons(true, ['allow_once', 'deny', 'cancel']).some((b) => b.choice === 'deny' || /reject/i.test(b.label))).toBe(false); + // Only what the CLI offered: no stop without "cancel", and nothing to change in a plan that cannot be accepted. + expect(shown(true, ['allow_once', 'deny']).map((b) => b[0])).toEqual(['Accept the plan', 'Change the plan…', 'Send it back with a note…']); + expect(shown(true, ['deny', 'cancel']).map((b) => b[0])).toEqual(['Send it back with a note…', 'Stop the turn']); + expect(PLAN_NOTE_HINT).toBe('Say what to change: without a note the same plan comes back.'); + }); + + it('a command shows every choice its CLI offered, in one order, then the note', () => { + expect(shown(false, ['cancel', 'deny', 'allow_always', 'allow_session', 'allow_once'])).toEqual([ + ['Approve once', '⌘↵', 'allow_once'], + ['Allow for this session', '⌥⌘↵', 'allow_session'], + ['Always allow', '', 'allow_always'], + ['Deny', '⌘⌫', 'deny'], + ['Stop the turn', '', 'cancel'], + ['Deny with a note…', '⇧⌘⌫', 'note'], + ]); + }); + + it('a tool request with only allow and deny has those and the note; without deny there is no note', () => { + expect(shown(false, ['allow_once', 'deny'])).toEqual([['Approve once', '⌘↵', 'allow_once'], ['Deny', '⌘⌫', 'deny'], ['Deny with a note…', '⇧⌘⌫', 'note']]); + expect(shown(false, ['allow_once'])).toEqual([['Approve once', '⌘↵', 'allow_once']]); + expect(shown(false, [])).toEqual([]); + }); +}); + +describe('⌘⌫ on the request the keyboard acts on', () => { + afterEach(() => { + store.agents = []; + }); + const request = (agent: string, subject: Approval['subject']) => + ({ id: 'ap', agent_id: agent, run_id: 'r', task_id: null, call_id: null, subject, reason: null, choices: ['allow_once', 'deny', 'cancel'], risks: [], status: 'pending', decided_by: null, created_at: 0 }) as Approval; + const plan: Approval['subject'] = { kind: 'tool', name: 'ExitPlanMode', input: { plan: '1. Add the line' } }; + const command: Approval['subject'] = { kind: 'command', command: 'npm install', cwd: null }; + + it('opens the note field of a plan card, with or without ⇧', () => { + store.agents = [mkAgent('eli', 'Eli', 'claude', 'solo', 0, 'waiting_approval'), mkAgent('bo', 'Bo', 'codex', 'solo', 1, 'waiting_approval')]; + expect(denyKeyAction(request('eli', plan), false)).toBe('note'); + expect(denyKeyAction(request('eli', plan), true)).toBe('note'); + // Every other request: ⌘⌫ says no at once, ⇧⌘⌫ opens the note. + expect(denyKeyAction(request('eli', command), false)).toBe('deny'); + expect(denyKeyAction(request('eli', command), true)).toBe('note'); + // That request is Claude Code's own: from another CLI, or an agent Codly does not know, it is a tool like any other. + expect(denyKeyAction(request('bo', plan), false)).toBe('deny'); + expect(denyKeyAction(request('gone', plan), false)).toBe('deny'); + }); +}); diff --git a/src/lib/util/__tests__/outcome.test.ts b/src/lib/util/__tests__/outcome.test.ts index eef02d74..f5043fe1 100644 --- a/src/lib/util/__tests__/outcome.test.ts +++ b/src/lib/util/__tests__/outcome.test.ts @@ -1,6 +1,7 @@ -import { describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it } from 'vitest'; import type { Approval } from '../../gen/Approval'; -import { answerText, askedLine, firstQuestion, outcomeBy, outcomeWord, settledLine } from '../outcome'; +import { yourWords } from '../../state/answers'; +import { answerText, askedLine, firstQuestion, outcomeBy, outcomeWord, settledLine, settledWord, wordsOf } from '../outcome'; const command = { subject: { kind: 'command', command: 'pnpm install', cwd: null } } satisfies Pick; const question = { @@ -21,7 +22,7 @@ describe('how a settled request reads', () => { it('puts the answers a question card sends on one line', () => { expect(answerText({ 'Keep the localStorage fallback?': 'Keep it' })).toBe('Keep it'); - expect(answerText({ Colour: 'Red', Sizes: ['Small', 'Fast'] })).toBe('Red · Small, Fast'); + expect(answerText({ Colour: 'Red', Sizes: ['Small', 'Fast'] })).toBe('Red; Small, Fast'); expect(answerText({ answer: ' use the settings API ' })).toBe('use the settings API'); // Nothing picked, nothing typed, or no answers at all (an approval, a skipped question). expect([answerText({ a: '', b: [] }), answerText(null), answerText(undefined), answerText('yes'), answerText(['yes'])]).toEqual([null, null, null, null, null]); @@ -49,7 +50,7 @@ describe('an agent’s history', () => { it('an answered question reads "Answered by you" with the answer, never "Approval approved"', () => { expect(settledLine('approved', 'user', question, 'Keep it')).toBe('Answered by you: Keep it'); - // Answered before this window opened: the core keeps no copy of the answer. + // Answered before the core kept a copy of the answer. expect(settledLine('approved', 'user', question, null)).toBe('Answered by you'); expect(settledLine('denied', 'user', question, null)).toBe('Skipped by you'); expect(settledLine('cancelled', 'provider', question, 'Keep it')).toBe('Stopped by its CLI'); @@ -76,3 +77,45 @@ describe('an agent’s history', () => { expect(settledLine('approved', 'user', plan, null)).toBe('Approved by you'); }); }); + +describe('what you said with an answer', () => { + afterEach(() => yourWords.clear()); + const held = (id: string, a: Pick) => ({ id, ...a }); + + it('the note of a "no" ends the line of the request it went with, cut to fit', () => { + yourWords.set('ap1', { note: 'use pnpm, not npm', planChanged: false }); + expect(settledLine('denied', 'user', held('ap1', command), null)).toBe('Denied by you: use pnpm, not npm'); + expect(settledLine('denied', 'user', held('ap2', command), null)).toBe('Denied by you'); + yourWords.set('ap3', { note: `Say which file changes.\n${'x'.repeat(200)}`, planChanged: false }); + const line = settledLine('denied', 'user', held('ap3', plan), null, 'claude'); + expect(line.startsWith('Plan sent back by you: Say which file changes. xxx')).toBe(true); + expect(line).toHaveLength('Plan sent back by you: '.length + 80); + }); + + it('a plan you changed before you accepted it says so, on the card and in the history', () => { + yourWords.set('ap1', { note: null, planChanged: true }); + expect(settledLine('approved', 'user', held('ap1', plan), null, 'claude')).toBe('Plan accepted with your changes by you'); + expect(settledLine('approved', 'user', held('ap2', plan), null, 'claude')).toBe('Plan accepted by you'); + // The closed card puts the same word before "by you". + expect(settledWord('approved', plan, 'claude', true)).toBe('Plan accepted with your changes'); + expect(settledWord('approved', plan, 'claude', false)).toBe('Plan accepted'); + expect(settledWord('denied', plan, 'claude', false)).toBe('Plan sent back'); + // Every other request, and a plan of another CLI, reads as before. + expect(settledWord('approved', plan, 'codex', true)).toBe('Approved'); + expect(settledWord('denied', command, 'claude', false)).toBe('Denied'); + expect(settledWord('approved', question, null, false)).toBe('Answered'); + expect(settledWord('expired', null, null, false)).toBe('Closed'); + }); + + it('shows only on a row that reads "by you", and only for a request that is still known', () => { + yourWords.set('ap1', { note: 'use pnpm', planChanged: false }); + expect(wordsOf(held('ap1', command), 'user')).toEqual({ note: 'use pnpm', planChanged: false }); + // Its CLI took the request back, or Codly closed it, while your answer was on its way. + expect(wordsOf(held('ap1', command), 'provider')).toBeNull(); + expect(settledLine('cancelled', 'provider', held('ap1', command), null)).toBe('Stopped by its CLI'); + expect(settledLine('expired', 'codly', held('ap1', command), null)).toBe('Closed by Codly'); + expect(wordsOf(command, 'user')).toBeNull(); + expect(wordsOf(null, 'user')).toBeNull(); + expect(wordsOf(held('ap2', command), 'user')).toBeNull(); + }); +}); diff --git a/src/lib/util/__tests__/sandbox.test.ts b/src/lib/util/__tests__/sandbox.test.ts index 5104d4a8..322b329d 100644 --- a/src/lib/util/__tests__/sandbox.test.ts +++ b/src/lib/util/__tests__/sandbox.test.ts @@ -59,7 +59,9 @@ describe('a command in Claude Code’s sandbox wants a host', () => { } }); - it('says how long an allow lasts without a promise that nothing recorded backs', () => { - expect(HOST_ALLOW_LASTS).toBe('Approve once lets this command connect. Claude Code can keep the host allowed until this agent’s session ends, so it may not ask again for it.'); + it('says how long an allow lasts as the recordings show it: while the agent keeps running, not after it starts again', () => { + expect(HOST_ALLOW_LASTS).toBe( + 'Approve once lets this command connect. Claude Code then does not ask again for this host while this agent keeps running. When the agent starts again (Codly restarts, or a change that restarts the agent) it asks again.', + ); }); }); diff --git a/src/lib/util/approvalFooter.ts b/src/lib/util/approvalFooter.ts new file mode 100644 index 00000000..52e08eee --- /dev/null +++ b/src/lib/util/approvalFooter.ts @@ -0,0 +1,45 @@ +// The buttons under a request that waits for you, in the order they show. Only the choices the +// agent's CLI offered become buttons. +// A plan (a Claude agent in plan mode) has its own set: accept it, change it and accept, send +// it back with a note, or stop the turn. It has no plain "no": without a note Claude Code shows +// the same plan again, so the one way to say no opens the note field. +import type { ApprovalChoice } from '../gen/ApprovalChoice'; + +export type FooterButton = { + /** `choice`: answer with `choice`. `edit`: open the plan to change it. `note`: open the note field. */ + act: 'choice' | 'edit' | 'note'; + /** The answer a `choice` button sends. */ + choice?: ApprovalChoice; + label: string; + /** The key that does the same, shown on the card the keyboard acts on. */ + kbd?: string; + /** The button's look: 'primary', 'ghost', 'danger', or '' for a plain one. */ + cls: string; +}; + +const CHOICE: Record = { + allow_once: { label: 'Approve once', kbd: '⌘↵', cls: 'primary' }, + allow_session: { label: 'Allow for this session', kbd: '⌥⌘↵', cls: '' }, + allow_always: { label: 'Always allow', cls: '' }, + deny: { label: 'Deny', kbd: '⌘⌫', cls: 'ghost' }, + cancel: { label: 'Stop the turn', cls: 'danger' }, +}; +const ORDER: ApprovalChoice[] = ['allow_once', 'allow_session', 'allow_always', 'deny', 'cancel']; + +const answer = (choice: ApprovalChoice, label = CHOICE[choice].label): FooterButton => ({ act: 'choice', choice, label, kbd: CHOICE[choice].kbd, cls: CHOICE[choice].cls }); + +/** `plan`: the card shows a Claude agent's plan. `offered`: the choices its CLI offered. */ +export function footerButtons(plan: boolean, offered: readonly ApprovalChoice[]): FooterButton[] { + const has = (c: ApprovalChoice) => offered.includes(c); + if (plan) { + return [ + ...(has('allow_once') ? [answer('allow_once', 'Accept the plan'), { act: 'edit', label: 'Change the plan…', cls: '' } satisfies FooterButton] : []), + ...(has('deny') ? [{ act: 'note', label: 'Send it back with a note…', kbd: '⌘⌫', cls: 'ghost' } satisfies FooterButton] : []), + ...(has('cancel') ? [answer('cancel')] : []), + ]; + } + return [...ORDER.filter(has).map((c) => answer(c)), ...(has('deny') ? [{ act: 'note', label: 'Deny with a note…', kbd: '⇧⌘⌫', cls: 'ghost' } satisfies FooterButton] : [])]; +} + +/** The note that goes back with a plan must say something: without one the same plan comes back. */ +export const PLAN_NOTE_HINT = 'Say what to change: without a note the same plan comes back.'; diff --git a/src/lib/util/outcome.ts b/src/lib/util/outcome.ts index 24d9e362..a8b8d7e4 100644 --- a/src/lib/util/outcome.ts +++ b/src/lib/util/outcome.ts @@ -1,13 +1,17 @@ // How a request reads once it no longer waits: the closed card in the conversation and the // lines of an agent's history. A permission is approved or denied. A question is answered or -// skipped, and says what you answered. +// skipped, and says what you answered. A "no" says the note you sent with it, and a plan says +// when it went ahead with your changes: your words, as the core recorded them (state/answers). import type { Approval } from '../gen/Approval'; import type { ApprovalStatus } from '../gen/ApprovalStatus'; import type { Provider } from '../gen/Provider'; +import { yourWords, type Words } from '../state/answers'; import { showsPlan } from './planRequest'; import { oneLine } from './sanitize'; type Asked = Pick; +/** A request as the store holds it: what you said with its answer is on record under its id. */ +type Held = Asked & Partial>; /** * "Approved", "Denied", "Stopped", "Closed"; for a question "Answered" and "Skipped". Empty while @@ -40,14 +44,15 @@ export function outcomeBy(decidedBy: string | null): string { } } -/** The answers a question card sends, on one line: "Keep it"; "Red · Small, Fast" for several - * questions (a question with several picks lists them). Null when nothing was picked or typed. */ +/** The answers a question card sends, on one line: "Keep it"; "Red; Small, Fast" for several + * questions (a question with several picks lists them). Null when nothing was picked or typed. + * The core writes the same line on record (`answer_line` in orchestrator/workspace.rs). */ export function answerText(answers: unknown): string | null { if (!answers || typeof answers !== 'object' || Array.isArray(answers)) return null; const said = Object.values(answers) .map((v) => (Array.isArray(v) ? v.filter((x) => typeof x === 'string' && x).join(', ') : typeof v === 'string' ? v.trim() : '')) .filter(Boolean); - return said.length ? said.join(' · ') : null; + return said.length ? said.join('; ') : null; } /** The first question of a question card, as the agent wrote it; null when the card has none to show. */ @@ -71,12 +76,34 @@ export function askedLine(asked: Asked, provider: Provider | null = null): strin return `Asked for approval${s.kind === 'command' ? `: ${oneLine(s.command, 60)}` : ''}`; } -/** An agent's history: how that request ended ("Approved by you", "Denied by you", "Closed by - * Codly"). `asked` is the request when it is still known (the line of a question or of a plan - * says so), `answer` what you answered when this window sent it. */ -export function settledLine(status: ApprovalStatus, by: string, asked: Asked | null, answer: string | null, provider: Provider | null = null): string { - const plan = !!asked && showsPlan(asked.subject, provider); - const word = plan && status === 'approved' ? 'Plan accepted' : plan && status === 'denied' ? 'Plan sent back' : outcomeWord(status, asked); - const line = `${word} ${outcomeBy(by)}`.trim(); - return asked?.subject.kind === 'question' && status === 'approved' && answer ? `${line}: ${oneLine(answer, 80)}` : line; +/** + * What you said with your answer to a request, beside the answer to a question: the note of a + * "no", and that you changed a plan before you accepted it. Null when nothing is on record + * for it, or when it was not you who settled it (`by`): only a row that reads "by you" shows + * your words. + */ +export function wordsOf(asked: Held | null, by: string | null): Words | null { + return by === 'user' && asked?.id ? (yourWords.get(asked.id) ?? null) : null; +} + +/** + * `outcomeWord`, and for a Claude agent's plan what you did with it: "Plan accepted", "Plan + * accepted with your changes" (`planChanged`: your text went back as the plan), "Plan sent back". + */ +export function settledWord(status: ApprovalStatus, asked: Asked | null, provider: Provider | null, planChanged: boolean): string { + if (asked && showsPlan(asked.subject, provider)) { + if (status === 'approved') return planChanged ? 'Plan accepted with your changes' : 'Plan accepted'; + if (status === 'denied') return 'Plan sent back'; + } + return outcomeWord(status, asked); +} + +/** An agent's history: how that request ended ("Approved by you", "Denied by you: use pnpm", + * "Closed by Codly"). `asked` is the request when it is still known (the line of a question or + * of a plan says so, and your note is found by its id), `answer` what you answered to a question. */ +export function settledLine(status: ApprovalStatus, by: string, asked: Held | null, answer: string | null, provider: Provider | null = null): string { + const said = wordsOf(asked, by); + const line = `${settledWord(status, asked, provider, !!said?.planChanged)} ${outcomeBy(by)}`.trim(); + if (asked?.subject.kind === 'question' && status === 'approved' && answer) return `${line}: ${oneLine(answer, 80)}`; + return said?.note ? `${line}: ${oneLine(said.note, 80)}` : line; } diff --git a/src/lib/util/sandbox.ts b/src/lib/util/sandbox.ts index 48ec301b..bfd80dde 100644 --- a/src/lib/util/sandbox.ts +++ b/src/lib/util/sandbox.ts @@ -13,10 +13,15 @@ import { clean, truncate } from './sanitize'; const SANDBOX_NETWORK = 'SandboxNetworkAccess'; /** - * How long an allow lasts, as far as it is sure, on the request's card and in Settings → Safety. - * That the host stays allowed for the session is read from the CLI, not recorded: "can", not "does". + * How long an allow lasts, on the request's card and in Settings → Safety. As recorded on + * Claude Code 2.1.311 (docs/research/cli-claude-stream-json-2.1.311-part3.md, section 6), each + * case once (n=1): + * - after a plain allow the same process did not ask again for the host 2 s later + * (`r5-sandbox-network-once`) and 304 s later (`r5-sandbox-network-once-later`); + * - a new process that resumed the session asked again (`r5-sandbox-network-once-restart-a`, `-b`). + * A wait of more than 5 minutes inside one process is not recorded. */ -export const HOST_ALLOW_LASTS = 'Approve once lets this command connect. Claude Code can keep the host allowed until this agent’s session ends, so it may not ask again for it.'; +export const HOST_ALLOW_LASTS = 'Approve once lets this command connect. Claude Code then does not ask again for this host while this agent keeps running. When the agent starts again (Codly restarts, or a change that restarts the agent) it asks again.'; /** * The host that a sandboxed command wants to reach, when `s` is the sandbox's own request diff --git a/src/office/__tests__/denied.test.ts b/src/office/__tests__/denied.test.ts new file mode 100644 index 00000000..bf2407d7 --- /dev/null +++ b/src/office/__tests__/denied.test.ts @@ -0,0 +1,80 @@ +// A request in the office where nothing asks "May I": the ticker while it waits for you, and +// the agent's line after you said no. The verb-first texts of "May I …?" do not read there. +import { describe, expect, it } from 'vitest'; +import type { Approval } from '../../lib/gen/Approval'; +import type { EventKind } from '../../lib/gen/EventKind'; +import type { EventRow } from '../../lib/gen/EventRow'; +import { AGENTS } from '../demo/script'; +import type { OfficeModel } from '../model'; +import { sentence } from '../narrate'; +import { approvalWaits, deniedLine, emptyModel, reduce, syncAgents } from '../reducer'; + +const T0 = 1_800_000_000_000; +let id = 0; +const row = (t: number, agent: string, kind: EventKind): EventRow => ({ id: ++id, ts: T0 + t, agent_id: agent, task_id: null, run_id: null, kind }); +const live = { replay: false }; + +// Ada runs Claude Code, Bo runs Codex. +function office(): OfficeModel { + const m = emptyModel(); + syncAgents(m, AGENTS.map((a) => ({ ...a, status: a.role === 'lead' ? 'idle' : 'working' })), T0); + return m; +} +const request = (agent: string, subject: Approval['subject']): Approval => + ({ id: 'ap', agent_id: agent, run_id: 'r', task_id: null, call_id: null, subject, reason: null, choices: ['allow_once', 'deny'], risks: [], status: 'pending', decided_by: null, created_at: 0 }); + +const question: Approval['subject'] = { kind: 'question', questions: [{ question: 'Which DB?' }] }; +const permissions: Approval['subject'] = { kind: 'permissions', detail: {} }; +const command: Approval['subject'] = { kind: 'command', command: 'rm -rf dist', cwd: null }; +const edit: Approval['subject'] = { kind: 'file_change', paths: ['src/theme.ts'], diff: null }; +const plan: Approval['subject'] = { kind: 'tool', name: 'ExitPlanMode', input: { plan: '1. Add the line' } }; +const host: Approval['subject'] = { kind: 'tool', name: 'SandboxNetworkAccess', input: { host: 'example.com' } }; + +/** The ticker line of the request, then the agent's line after you said no to it. */ +function askedThenDenied(agent: string, subject: Approval['subject']): [string, string] { + const m = office(); + const asked = reduce(m, row(1000, agent, { type: 'approval_requested', approval: request(agent, subject) }), live); + const ticker = asked.flatMap((f) => (f.t === 'ticker' ? [[f.text, f.code].filter(Boolean).join(' ')] : [])); + reduce(m, row(2000, agent, { type: 'approval_resolved', approval_id: 'ap', status: 'denied', by: 'user' }), live); + return [ticker.join(' | '), sentence(m.agents.get(agent)!, T0 + 2100).text]; +} + +describe('a request you said no to, in the office', () => { + it('a skipped question and denied permissions read as that, not as "Denied ask a question"', () => { + expect(askedThenDenied('a-ada', question)).toEqual(['Ada · Waiting for you: its question', 'Skipped its question']); + expect(askedThenDenied('a-ada', permissions)).toEqual(['Ada · Waiting for you: more permissions', 'Denied: more permissions']); + }); + + it('a command is denied by its first words; every other request says what the agent wanted to do', () => { + expect(askedThenDenied('a-ada', command)).toEqual(['Ada · Waiting for you: rm -rf dist', 'Denied rm -rf dist']); + expect(askedThenDenied('a-ada', edit)).toEqual(['Ada · Waiting for you: edit theme.ts', 'Denied: edit theme.ts']); + expect(askedThenDenied('a-ada', host)).toEqual(['Ada · Waiting for you: reach example.com', 'Denied: reach example.com']); + }); + + it('a Claude agent’s plan is sent back, not denied; from another CLI that request is a tool by its name', () => { + expect(askedThenDenied('a-ada', plan)).toEqual(['Ada · Waiting for you: read its plan', 'Plan sent back']); + expect(askedThenDenied('a-bo', plan)).toEqual(['Bo · Waiting for you: use ExitPlanMode', 'Denied: use ExitPlanMode']); + }); + + it('the line of each kind, and what the ticker says while it waits', () => { + const line = (s: Approval['subject']) => deniedLine(request('a-ada', s), 'claude'); + expect(line(question)).toEqual({ text: 'Skipped its question', code: null }); + expect(line(permissions)).toEqual({ text: 'Denied: more permissions', code: null }); + expect(line(command)).toEqual({ text: 'Denied', code: 'rm -rf dist' }); + expect(line(edit)).toEqual({ text: 'Denied:', code: 'edit theme.ts' }); + expect(line(plan)).toEqual({ text: 'Plan sent back', code: null }); + expect(approvalWaits(request('a-ada', question), 'claude')).toBe('its question'); + expect(approvalWaits(request('a-ada', permissions), null)).toBe('more permissions'); + expect(approvalWaits(request('a-ada', command), 'claude')).toBe('rm -rf dist'); + }); + + it('a request the office never saw asked is only known as denied; an approved one leaves no line', () => { + const m = office(); + reduce(m, row(1000, 'a-ada', { type: 'approval_resolved', approval_id: 'unseen', status: 'denied', by: 'user' }), live); + expect(sentence(m.agents.get('a-ada')!, T0 + 1100).text).toBe('Denied'); + const n = office(); + reduce(n, row(1000, 'a-ada', { type: 'approval_requested', approval: request('a-ada', question) }), live); + reduce(n, row(2000, 'a-ada', { type: 'approval_resolved', approval_id: 'ap', status: 'approved', by: 'user' }), live); + expect(n.agents.get('a-ada')!.outcome).toBeNull(); + }); +}); diff --git a/src/office/model.ts b/src/office/model.ts index cc5dab4e..d45da75d 100644 --- a/src/office/model.ts +++ b/src/office/model.ts @@ -124,7 +124,8 @@ export interface OfficeModel { /** Outcomes of recent test runs (oldest first). */ testHistory: boolean[]; artifacts: Map; - approvals: Map; + /** The requests that wait: who asked, and the agent's line if you say no (`deniedLine`). */ + approvals: Map; resolved: Set; lastEventId: number; } diff --git a/src/office/reducer.ts b/src/office/reducer.ts index 94fe0dff..4dfb1177 100644 --- a/src/office/reducer.ts +++ b/src/office/reducer.ts @@ -212,7 +212,8 @@ export function applyStatus(a: AgentState, status: AgentStatus, ts: number) { /** * What a request asks, in a few words: a command by its first words, every other request by - * what the agent wants to do, so that it reads after "May I" and after "Waiting for you:". A + * what the agent wants to do, so that it reads after "May I" (the ticker and the line of a + * request you denied have forms of their own: `approvalWaits`, `deniedLine`). A * Claude agent's plan is `PLAN_ASK`: what you do with it, since a plan is read, not allowed. * `provider`: the CLI of the agent that asks (null: the office does not know it). */ @@ -234,6 +235,36 @@ export function approvalText(ap: Approval, provider: Provider | null): string { } } +/** + * The same request where nothing asks "May I": after "Waiting for you:" in the ticker. A + * question and a permissions request are named there ("its question", "more permissions"): + * "Waiting for you: ask a question" reads as something you are told to do. Every other + * request reads as in `approvalText`. + */ +export function approvalWaits(ap: Approval, provider: Provider | null): string { + const kind = ap.subject.kind; + return kind === 'question' ? 'its question' : kind === 'permissions' ? 'more permissions' : approvalText(ap, provider); +} + +/** + * The agent's line after you said no to its request: "Denied " for a command, + * "Skipped its question", "Denied: more permissions", "Plan sent back" for a Claude agent's + * plan (a plan is read, not allowed), and "Denied: " for the rest. + */ +export function deniedLine(ap: Approval, provider: Provider | null): { text: string; code: string | null } { + const s = ap.subject; + switch (s.kind) { + case 'command': + return { text: 'Denied', code: approvalText(ap, provider) }; + case 'question': + return { text: 'Skipped its question', code: null }; + case 'permissions': + return { text: 'Denied: more permissions', code: null }; + default: + return s.kind === 'tool' && showsPlan(s, provider) ? { text: 'Plan sent back', code: null } : { text: 'Denied:', code: approvalText(ap, provider) }; + } +} + /** Test counts from a verify tail ("12 passed", "1 failed", cargo's summary). Inferred. */ export function parseTestCounts(tail: string): { passed: number | null; failed: number | null } { const s = clean(tail, 4000); @@ -462,10 +493,10 @@ export function reduce(m: OfficeModel, ev: EventRow, ctx: ReduceContext): Fx[] { const who = ap.agent_id || aid; if (!who || m.resolved.has(ap.id)) break; const ag = ensureAgent(m, who, at); - const text = approvalText(ap, ag.providerKnown ? ag.provider : null); - ag.approval = { id: ap.id, text, command: ap.subject.kind === 'command', since: at }; - m.approvals.set(ap.id, { agentId: who, text, since: at }); - tick('Waiting for you:', text, 'warn', who); + const provider = ag.providerKnown ? ag.provider : null; + ag.approval = { id: ap.id, text: approvalText(ap, provider), command: ap.subject.kind === 'command', since: at }; + m.approvals.set(ap.id, { agentId: who, denied: deniedLine(ap, provider), since: at }); + tick('Waiting for you:', approvalWaits(ap, provider), 'warn', who); break; } case 'approval_resolved': { @@ -475,7 +506,8 @@ export function reduce(m: OfficeModel, ev: EventRow, ctx: ReduceContext): Fx[] { const who = ap?.agentId ?? aid; const ag = who ? m.agents.get(who) : null; if (ag?.approval && (ag.approval.id === k.approval_id || ag.approval.id === 'status')) ag.approval = null; - if (ag && k.status === 'denied') ag.outcome = { text: 'Denied', code: ap?.text ?? null, tone: 'muted', at }; + // A request the office never saw asked (it joined later) is only known as denied. + if (ag && k.status === 'denied') ag.outcome = { ...(ap?.denied ?? { text: 'Denied', code: null }), tone: 'muted', at }; break; } case 'rate_limit': diff --git a/src/sheet/AgentSheet.svelte b/src/sheet/AgentSheet.svelte index 385c24fb..dbe1df30 100644 --- a/src/sheet/AgentSheet.svelte +++ b/src/sheet/AgentSheet.svelte @@ -186,6 +186,8 @@ for (let i = store.events.length - 1; i >= 0 && out.length < 250; i--) { const e = store.events[i]; if (e.agent_id !== agent.id && !(task && e.task_id === task.id && e.kind.type === 'decision')) continue; + // (what you said with an answer is no row of its own: the answer's row ends with it) + if (e.kind.type === 'approval_said') continue; const t = e.kind.type; // (a helper's progress is no step of its own: its calls and its end are rows already) if (t === 'usage_updated' || t === 'rate_limit' || t === 'agent_changed' || t === 'control_changed' || t === 'sub_agent_progress') continue; From a301644336ca84a97fb7aa37a12cca38371955d9 Mon Sep 17 00:00:00 2001 From: julienwuthrich-ant Date: Mon, 23 Nov 2026 10:59:06 -0800 Subject: [PATCH 007/120] Toasts: a stack with no free place folds, the Resume bar has room of its own, "Start an agent" stays in view Three toasts in a small window still lay on buttons (on "Deny" at 1024x640), and the place went stale when the page changed under a toast that stayed. Toasts - When the whole stack finds no free place, it folds: one toast shows (the newest, or the newest error) with "+2 more" under it, and that smaller stack looks for a place the same way. A press on "+2 more" shows the whole stack while the pointer or the keyboard focus is on it. - A toast's text shows six lines; "Show all" opens a longer one in place. The place counts the short height. - The stack looks again when what is in the page's main column gets higher or lower (at most once in 250 ms), when a menu or a dialog comes or goes, when the first-run quest shows another level and when the closed requests are read again. Scroll is still no trigger. - A control wider than twice the stack counts by what it shows (its text and pictures), not by its whole row, so the stack stays at the top over a whole-width row. A field counts whole. - The look when the page has come to rest is no longer put off by each new toast: it comes at the end of the first wait. A change of the page's layout still starts the wait over. Resume bar - The bar is there until you answer, so it gets room of its own: while it shows, the stage and the toast stack start below it, and it starts right of the rail. It covered the request tabs and the plan header before. - It is drawn above the first-run quest, so the question can be answered there. Its comment said it was under the sheet in the order of layers, which was not true. - The Ask me panel's width is one token (--ask-w) for the panel and the bar. Crew strip - "Start an agent" stands after the strip, outside what scrolls: at 900x600 with the sheet open it was out of view. Co-Authored-By: Claude Fable 5.2 --- src/components/Dialog.svelte | 8 +- src/components/Menu.svelte | 6 + src/components/ResumeWork.svelte | 35 ++- src/components/Toasts.svelte | 249 +++++++++++++++++++--- src/home/AskMe.svelte | 2 +- src/lib/state/ui.svelte.ts | 4 + src/lib/util/__tests__/toastPlace.test.ts | 240 ++++++++++++++++++++- src/lib/util/toastPlace.ts | 193 ++++++++++++++++- src/onboarding/Onboarding.svelte | 5 + src/shell/CrewStrip.svelte | 26 ++- src/shell/Shell.svelte | 6 +- src/shell/TopBar.svelte | 2 +- src/styles/tokens.css | 1 + 13 files changed, 716 insertions(+), 61 deletions(-) diff --git a/src/components/Dialog.svelte b/src/components/Dialog.svelte index 78708e91..fe8d8cc3 100644 --- a/src/components/Dialog.svelte +++ b/src/components/Dialog.svelte @@ -4,7 +4,7 @@ was (`modal`). `onkeydown` sees a key before the dialog does: stopPropagation() there keeps it. --> + + resizes++} /> -
      +
      {#each newestFirst as t (t.id)}
      toasts.pause(t.id)} onpointerleave={() => toasts.resume(t.id)} @@ -113,7 +274,10 @@

      {t.title}

      - {#if t.body}

      {t.body}

      {/if} + {#if t.body} +

      {t.body}

      + {#if long[t.id] && opened[t.id] === undefined}{/if} + {/if}
      {#if t.action}
      {/each} + {#if folded && toasts.list.length > 1} + + {/if}
      diff --git a/src/home/AskMe.svelte b/src/home/AskMe.svelte index 3797e05f..2e2992f2 100644 --- a/src/home/AskMe.svelte +++ b/src/home/AskMe.svelte @@ -68,7 +68,7 @@ .ask.has { color: var(--ink-1); } .ask b { font-size: var(--t-sm); font-weight: var(--w-semi); } .ask.blocked { color: var(--amber-ink); background: color-mix(in srgb, var(--amber) 16%, var(--glass)); box-shadow: var(--glass-edge), inset 0 0 0 1px color-mix(in srgb, var(--amber) 45%, transparent); } - .panel { position: fixed; z-index: var(--z-pop); top: calc(var(--top-h) + 6px); right: var(--gutter); width: min(440px, calc(100vw - 2 * var(--gutter))); max-height: calc(100vh - var(--top-h) - 24px); display: flex; flex-direction: column; border-radius: var(--r-xl); background: var(--glass-solid); overflow: hidden; animation: rise-in var(--d-3) var(--spring); } + .panel { position: fixed; z-index: var(--z-pop); top: calc(var(--top-h) + 6px); right: var(--gutter); width: min(var(--ask-w), calc(100vw - 2 * var(--gutter))); max-height: calc(100vh - var(--top-h) - 24px); display: flex; flex-direction: column; border-radius: var(--r-xl); background: var(--glass-solid); overflow: hidden; animation: rise-in var(--d-3) var(--spring); } header { display: flex; align-items: baseline; gap: 10px; padding: 14px 18px 8px; } h2 { font-size: var(--t-lg); font-weight: var(--w-semi); } .sub { font-size: var(--t-sm); color: var(--ink-3); } diff --git a/src/lib/state/ui.svelte.ts b/src/lib/state/ui.svelte.ts index 5519ccb9..d0bdc2a2 100644 --- a/src/lib/state/ui.svelte.ts +++ b/src/lib/state/ui.svelte.ts @@ -182,6 +182,10 @@ class Ui { /** Composer draft injected by other surfaces (palette "Ask the Lead…", file mentions). */ composerSeed = $state<{ thread: string; text: string; keep: boolean; replaces: string | null; nonce: number } | null>(null); + /** Bumped when the page changes in a way no other field here tells: a menu or a dialog comes or + * goes, the first-run quest shows another level. The toast stack then looks for its place again. */ + layoutRev = $state(0); + systemDark = $state(mq('(prefers-color-scheme: dark)')?.matches ?? true); reducedMotion = $state(mq('(prefers-reduced-motion: reduce)')?.matches ?? false); width = $state(typeof window !== 'undefined' ? window.innerWidth : 1440); diff --git a/src/lib/util/__tests__/toastPlace.test.ts b/src/lib/util/__tests__/toastPlace.test.ts index daae6160..c15ab000 100644 --- a/src/lib/util/__tests__/toastPlace.test.ts +++ b/src/lib/util/__tests__/toastPlace.test.ts @@ -1,10 +1,10 @@ // The toast stack lies over the page and must cover nothing you can press. The boxes below // are the ones measured in the app (left, top, right, bottom in px): a one-line toast is // 360 x 63, the stack starts 68 px under the window's top. -import { describe, expect, it } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import tokens from '../../../styles/tokens.css?raw'; import toastsView from '../../../components/Toasts.svelte?raw'; -import { counts, grown, ms, onTop, reachDown, toastTop, visiblePart, type Box, type Seen } from '../toastPlace'; +import { countedBox, counts, frontToast, grown, ms, onTop, paced, reachDown, restLook, stackPlace, toastTop, visiblePart, type Box, type Seen, type Shape } from '../toastPlace'; const box = (left: number, top: number, right: number, bottom: number): Box => ({ left, top, right, bottom }); @@ -139,6 +139,242 @@ describe('reachDown', () => { }); }); +describe('stackPlace: the place, and whether the stack folds', () => { + /** As the stack measures: each control with 4 px around it. */ + const controls = (...boxes: Box[]) => boxes.map((c) => grown(c, 4)); + /** A stack of this height in a window of this height: it may go down 40 percent of the window, and stays 12 px inside it. */ + const shape = (height: number, windowHeight: number): Shape => ({ height, reach: reachDown(windowHeight, 0.4, TOP, height, 12) }); + /** Measured: a one-line toast is 45 px high, three of them with 8 px between are 151. */ + const THREE = 151; + /** One toast, 8 px, and the 22 px line "+2 more". */ + const FOLDED = 75; + + it('a stack with a free place does not fold', () => { + const closed = box(1071, 72, 1101, 102); + expect(stackPlace({ left: 1066, right: 1426 }, shape(THREE, 900), shape(FOLDED, 900), controls(closed), TOP, MOVES)).toEqual({ top: 106, folded: false }); + expect(stackPlace({ left: 1066, right: 1426 }, shape(THREE, 900), shape(FOLDED, 900), [], TOP, MOVES)).toEqual({ top: 68, folded: false }); + }); + + it('folds off "Deny": three toasts over an approval card (Home, 1024 x 640)', () => { + // Measured on the page: the request tabs, the plan header, the card's "Copy command" and "Deny". + const page = controls( + box(453, 72, 679, 102), box(679, 77, 699, 97), box(825, 72, 855, 102), box(863, 72, 893, 102), + box(205, 110, 713.4, 162), box(719.4, 125, 741.4, 147), box(737.4, 125, 759.4, 147), box(769.4, 123, 857, 149), box(869, 124, 893, 148), + box(823, 160.9, 847, 184.9), + box(596.3, 302.9, 686.2, 334.9), + ); + const sides = { left: 650, right: 1010 }; + // The whole stack: 68 -> 188.9, under "Copy command". There it ends at 339.9, on "Deny" (298.9 to 338.9), + // and under "Deny" is further than it may go (68 + 256). + expect(toastTop(box(650, 68, 1010, 68 + THREE), page, TOP, MOVES, shape(THREE, 640).reach)).toBe(188.9); + // Folded, it ends at 263.9: 35 px over "Deny". + expect(stackPlace(sides, shape(THREE, 640), shape(FOLDED, 640), page, TOP, MOVES)).toEqual({ top: 188.9, folded: true }); + // Two toasts (98 px) end at 286.9: free, not folded. + expect(stackPlace(sides, shape(98, 640), shape(FOLDED, 640), page, TOP, MOVES)).toEqual({ top: 188.9, folded: false }); + }); + + it('with no free place for the folded stack either, it stays folded where it last looked: a list of task rows (Home, 1440 x 900, the sheet open)', () => { + // The request tabs, the plan header, three task rows (each one button, 632 px wide: not wider + // than twice the stack, so each counts whole) and "Plan room" under them. + const page = controls( + box(452, 72, 678, 102), box(678, 77, 698, 97), box(824, 72, 854, 102), box(862, 72, 892, 102), + box(204, 110, 712.4, 162), box(718.4, 125, 740.4, 147), box(736.4, 125, 758.4, 147), box(768.4, 123, 856, 149), box(868, 124, 892, 148), + box(228, 221.9, 860, 301.9), box(228, 303.9, 860, 365.9), box(228, 367.9, 860, 429.9), + box(755.4, 439.9, 850, 465.9), + ); + // Whole and folded: 68 -> under the header or the first row -> under the second row. The third + // row ends further down than the stack may go (68 + 360). + expect(stackPlace({ left: 648, right: 1008 }, shape(THREE, 900), shape(FOLDED, 900), page, TOP, MOVES)).toEqual({ top: 369.9, folded: true }); + }); + + it('a stack of one toast cannot fold: it stays where it last looked', () => { + const rows = [0, 1, 2, 3, 4, 5, 6, 7].map((i) => box(1000, 70 + i * 40, 1400, 100 + i * 40)); + expect(stackPlace({ left: 1066, right: 1426 }, shape(63, 900), null, rows, TOP, MOVES)).toEqual({ top: 300, folded: false }); + }); + + it('the folded stack looks with its own reach: it may go where the whole stack would leave the window', () => { + // Three long errors, 511 px high, in a 640 px high window: the whole stack can go down 49 px. + const findClose = box(849, 116, 875, 142); + const page = [box(863, 72, 893, 102), findClose]; + expect(shape(511, 640).reach).toBe(49); + // The whole stack stays on the find bar's button; folded (one long error and the line), it goes under it. + expect(stackPlace({ left: 650, right: 1010 }, shape(511, 640), shape(195, 640), page, TOP, MOVES)).toEqual({ top: 142, folded: true }); + }); +}); + +describe('frontToast: the one toast of a folded stack', () => { + const toast = (id: number, kind: string) => ({ id, kind }); + + it('is the newest toast', () => { + expect(frontToast([toast(3, 'info'), toast(2, 'success'), toast(1, 'progress')])?.id).toBe(3); + }); + + it('is the newest error when the stack has one: an error is never the one that is hidden', () => { + expect(frontToast([toast(3, 'info'), toast(2, 'error'), toast(1, 'error')])?.id).toBe(2); + expect(frontToast([toast(3, 'error'), toast(2, 'info')])?.id).toBe(3); + }); + + it('is nothing for no toast', () => { + expect(frontToast([])).toBeUndefined(); + }); +}); + +describe('countedBox: a control much wider than the stack counts by what it shows', () => { + const STACK = 360; + const never = () => { + throw new Error('not asked'); + }; + + it('a whole-width row whose label is at the left: the stack at the right stays at the top', () => { + // Measured in the Plan room (1440 x 900): the header "Not in a plan" is one button, 860 px wide, + // and its text ends at x 715. Here it is right under the top bar. + const row = box(323, 70, 1183, 102); + const label = box(337, 78, 715, 93); + expect(countedBox(row, STACK, false, () => label)).toEqual(label); + const stack = box(1066, 68, 1426, 113); + expect(toastTop(stack, [grown(row, 4)], TOP, MOVES, REACH_900)).toBe(106); + expect(toastTop(stack, [grown(countedBox(row, STACK, false, () => label)!, 4)], TOP, MOVES, REACH_900)).toBe(68); + }); + + it('a row that shows something at the right too still counts there', () => { + // The question row of the Plan room: its text starts at x 337, its time ends at x 1169. + const row = box(323, 70, 1183, 104); + const shown = countedBox(row, STACK, false, () => box(337, 79, 1169, 94))!; + expect(toastTop(box(1066, 68, 1426, 113), [grown(shown, 4)], TOP, MOVES, REACH_900)).toBe(98); + }); + + it('a press area that shows nothing of its own (it lies over a whole task row) does not count', () => { + expect(countedBox(box(323, 378, 1183, 576), STACK, false, () => null)).toBeNull(); + }); + + it('what a control shows counts only inside the part of it that shows', () => { + // A label that is cut at the row's right edge, and one that lies outside the part that shows. + expect(countedBox(box(100, 70, 900, 102), STACK, false, () => box(120, 78, 1040, 93))).toEqual(box(120, 78, 900, 93)); + expect(countedBox(box(100, 70, 900, 102), STACK, false, () => box(120, 20, 400, 60))).toBeNull(); + }); + + it('a control up to twice as wide as the stack counts whole: what it shows is not asked for', () => { + // A task row of Home is 632 px wide; a control of exactly twice the stack's width. + expect(countedBox(box(228, 222, 860, 302), STACK, false, never)).toEqual(box(228, 222, 860, 302)); + expect(countedBox(box(100, 70, 820, 102), STACK, false, never)).toEqual(box(100, 70, 820, 102)); + }); + + it('a field you type in counts whole, however wide: its text can be anywhere in it', () => { + expect(countedBox(box(100, 70, 1100, 104), STACK, true, never)).toEqual(box(100, 70, 1100, 104)); + }); + + it('follows the stack’s width: a narrow window has a narrower stack', () => { + // The stack is 300 px wide: a 632 px row is wider than twice of it. + expect(countedBox(box(10, 222, 642, 302), 300, false, () => box(24, 240, 200, 256))).toEqual(box(24, 240, 200, 256)); + }); +}); + +describe('paced: at most one run in a time', () => { + beforeEach(() => vi.useFakeTimers()); + afterEach(() => vi.useRealTimers()); + + it('runs at once, and once more at the end of the time for all the calls in it', () => { + const run = vi.fn(); + const call = paced(run, 250); + call(); + expect(run).toHaveBeenCalledTimes(1); + call(); + call(); + vi.advanceTimersByTime(249); + expect(run).toHaveBeenCalledTimes(1); + vi.advanceTimersByTime(1); + expect(run).toHaveBeenCalledTimes(2); + }); + + it('text that streams in for a second makes five runs, not one for each change', () => { + const run = vi.fn(); + const call = paced(run, 250); + for (let at = 0; at < 1000; at += 10) { + call(); + vi.advanceTimersByTime(10); + } + // At 0, 250, 500, 750 and 1000 ms. + expect(run).toHaveBeenCalledTimes(5); + }); + + it('with no call in the time it does not run again, and the next call runs at once', () => { + const run = vi.fn(); + const call = paced(run, 250); + call(); + vi.advanceTimersByTime(1000); + expect(run).toHaveBeenCalledTimes(1); + call(); + expect(run).toHaveBeenCalledTimes(2); + }); + + it('stop drops the run that waits', () => { + const run = vi.fn(); + const call = paced(run, 250); + call(); + call(); + call.stop(); + vi.advanceTimersByTime(1000); + expect(run).toHaveBeenCalledTimes(1); + }); +}); + +describe('restLook: the look when the page has come to rest', () => { + beforeEach(() => vi.useFakeTimers()); + afterEach(() => vi.useRealTimers()); + /** `--d-4` and two frames. */ + const WAIT = 414; + + it('a second toast within the wait does not start the wait over: the look comes once, at the end of the first wait', () => { + const look = vi.fn(); + const rest = restLook(() => WAIT, look); + rest.after(false); + vi.advanceTimersByTime(200); + rest.after(false); + vi.advanceTimersByTime(213); + expect(look).not.toHaveBeenCalled(); + vi.advanceTimersByTime(1); + expect(look).toHaveBeenCalledTimes(1); + vi.advanceTimersByTime(1000); + expect(look).toHaveBeenCalledTimes(1); + }); + + it('a progress toast that changes every 100 ms still gets its look, and a change after it starts a new wait', () => { + const look = vi.fn(); + const rest = restLook(() => WAIT, look); + for (let at = 0; at < 1000; at += 100) { + rest.after(false); + vi.advanceTimersByTime(100); + } + // The first wait ends at 414 ms; the change at 500 ms starts the second, which ends at 914 ms. + expect(look).toHaveBeenCalledTimes(2); + }); + + it('a change of the page’s layout starts the wait over: its boxes move from then on', () => { + const look = vi.fn(); + const rest = restLook(() => WAIT, look); + rest.after(false); + vi.advanceTimersByTime(300); + rest.after(true); + vi.advanceTimersByTime(413); + expect(look).not.toHaveBeenCalled(); + vi.advanceTimersByTime(1); + expect(look).toHaveBeenCalledTimes(1); + }); + + it('stop drops the look that waits (the last toast went)', () => { + const look = vi.fn(); + const rest = restLook(() => WAIT, look); + rest.after(false); + rest.stop(); + vi.advanceTimersByTime(1000); + expect(look).not.toHaveBeenCalled(); + // The next toast starts a wait of its own. + rest.after(false); + vi.advanceTimersByTime(WAIT); + expect(look).toHaveBeenCalledTimes(1); + }); +}); + describe('grown', () => { it('keeps a gap around a control: "+" is 3 px left of the stack, and counts with a 4 px gap', () => { const plus = box(1033, 72, 1063, 102); diff --git a/src/lib/util/toastPlace.ts b/src/lib/util/toastPlace.ts index 413dd0b9..d99e6fce 100644 --- a/src/lib/util/toastPlace.ts +++ b/src/lib/util/toastPlace.ts @@ -34,6 +34,35 @@ export function toastTop(stack: Box, controls: Box[], top: number, maxMoves: num } } +/** A height the stack can have, and how far under `top` a stack of that height may go (`reachDown`), in px. */ +export type Shape = { height: number; reach: number }; + +/** + * Where the stack goes, and whether it folds. + * + * The whole stack looks for a place first (`toastTop`). When it finds none that is free within + * its reach, it folds: one toast shows, with a line "+2 more" under it, and that smaller stack + * looks for a place the same way. With no free place for it either it stays folded at the last + * place it tried: it covers less than the whole stack would. `folded` is the shape of the folded + * stack, null for a stack that cannot fold (one toast). + */ +export function stackPlace(sides: { left: number; right: number }, whole: Shape, folded: Shape | null, controls: Box[], top: number, maxMoves: number): { top: number; folded: boolean } { + const look = (shape: Shape) => { + const at = toastTop({ ...sides, top, bottom: top + shape.height }, controls, top, maxMoves, shape.reach); + const box: Box = { ...sides, top: at, bottom: at + shape.height }; + return { at, free: !controls.some((c) => overlap(c, box)) }; + }; + const all = look(whole); + if (all.free || !folded) return { top: all.at, folded: false }; + return { top: look(folded).at, folded: true }; +} + +/** + * The one toast of a folded stack: the newest, or the newest error when the stack has one (an + * error is never the one that is hidden). `newestFirst`: the stack's toasts, the newest first. + */ +export const frontToast = (newestFirst: T[]): T | undefined => newestFirst.find((t) => t.kind === 'error') ?? newestFirst[0]; + /** * How far under `top` the stack may go, in px: `part` of the window's height, and never so far * that its bottom edge comes nearer than `edge` px to the window's bottom (a toast moved down @@ -81,6 +110,22 @@ export type Seen = { */ export const counts = (c: Seen): boolean => !c.inStack && !c.above && !c.disabled && c.visibility === 'visible' && c.pointerEvents !== 'none' && c.onTop; +/** + * The box a control counts with, null when it does not count. + * + * A control that is wider than twice the stack can never be more than half under it. It counts + * by what it shows: `content()` gives the smallest box around its text and its pictures, null + * when it shows nothing of its own (the press area that lies over a whole row). So a toast at + * the right stays at the top over a whole-width row whose label is at the left. Any narrower + * control counts with its whole box (`part`: the part of it that shows), and so does a field you + * type in: its text can be anywhere in it. + */ +export function countedBox(part: Box, stackWidth: number, field: boolean, content: () => Box | null): Box | null { + if (field || part.right - part.left <= 2 * stackWidth) return part; + const shown = content(); + return shown && visiblePart(shown, [part]); +} + /** * Is `el` what a press at a point reaches? `hits` is everything at that point, the topmost * first (document.elementsFromPoint). What is `aside` is left out: the toast stack itself (the @@ -100,6 +145,59 @@ export function ms(time: string): number { return Number(read[1]) * (read[2] === 's' ? 1000 : 1); } +/** + * `run`, at most once in `every` ms. The first call runs at once; calls in the `every` ms after a + * run make one more run when that time is up. `stop` drops a run that waits. + */ +export function paced(run: () => void, every: number): { (): void; stop(): void } { + let timer: ReturnType | undefined; + let again = false; + const go = () => { + again = false; + run(); + timer = setTimeout(() => { + timer = undefined; + if (again) go(); + }, every); + }; + const call = () => { + if (timer === undefined) go(); + else again = true; + }; + call.stop = () => { + clearTimeout(timer); + timer = undefined; + again = false; + }; + return call; +} + +/** + * The look that comes after the look at once: when the page has come to rest, `wait()` ms later. + * + * `after(false)`: the stack changed and the page's layout did not (a toast came, one changed its + * text). A look that already waits is kept: it comes at the end of the first wait, once, also + * when toasts change faster than the wait is long. `after(true)`: the page's layout changed, and + * its boxes move from now on, so the wait starts over. `stop` drops a look that waits. + */ +export function restLook(wait: () => number, look: () => void): { after(moved: boolean): void; stop(): void } { + let timer: ReturnType | undefined; + const stop = () => { + clearTimeout(timer); + timer = undefined; + }; + return { + after(moved) { + if (moved) stop(); + timer ??= setTimeout(() => { + timer = undefined; + look(); + }, wait()); + }, + stop, + }; +} + // From here on: what reads the page. /** What you press or type in: a toast must not lie on one of these. */ @@ -151,13 +249,48 @@ function clips(el: Element): Box[] { return frames; } +/** What you type in: it counts with its whole box (see `countedBox`). */ +const FIELDS = 'input, select, textarea'; +/** What a control shows beside its text. */ +const PICTURES = 'svg, img, canvas, video'; + +/** Puts into `out` the boxes of what `el` shows: each line of its text, and its pictures. */ +function shownIn(el: Element, range: Range, out: DOMRect[]) { + for (const node of el.childNodes) { + if (node instanceof Text) { + if (!node.data.trim()) continue; + range.selectNodeContents(node); + out.push(...range.getClientRects()); + } else if (node instanceof Element) { + if (node.matches(PICTURES)) out.push(node.getBoundingClientRect()); + else shownIn(node, range, out); + } + } +} + +/** The smallest box around what `el` shows (its text and its pictures); null: it shows nothing of its own. */ +function contentBox(el: Element): Box | null { + const found: DOMRect[] = []; + shownIn(el, document.createRange(), found); + const boxes = found.filter((b) => b.width > 0 && b.height > 0); + if (!boxes.length) return null; + return { + left: Math.min(...boxes.map((b) => b.left)), + top: Math.min(...boxes.map((b) => b.top)), + right: Math.max(...boxes.map((b) => b.right)), + bottom: Math.max(...boxes.map((b) => b.bottom)), + }; +} + /** * The boxes of the page's controls that show inside `area` and that a toast must keep off * (see `counts`). A box is the part of the control that shows: not what is scrolled out of its - * list or lies outside the window. + * list or lies outside the window. A control much wider than the stack counts by what it shows + * (see `countedBox`). */ export function controlBoxes(stack: HTMLElement, area: Box): Box[] { const above = layers(stack); + const stackWidth = stack.offsetWidth; const boxes: Box[] = []; for (const el of document.querySelectorAll(CONTROLS)) { const box = boxOf(el); @@ -173,7 +306,63 @@ export function controlBoxes(stack: HTMLElement, area: Box): Box[] { pointerEvents: own.pointerEvents, onTop: reached(el, part, stack, above), }; - if (counts(seen)) boxes.push(part); + if (!counts(seen)) continue; + const counted = countedBox(part, stackWidth, el.matches(FIELDS), () => contentBox(el)); + if (counted && overlap(counted, area)) boxes.push(counted); } return boxes; } + +/** Puts into `out` every box in `el` (or `el` itself) that scrolls up and down, and what is in it. + * It does not look inside such a box: what scrolls in it is its content. */ +function scrollBoxes(el: Element, out: Element[]) { + const flow = getComputedStyle(el).overflowY; + if (flow === 'auto' || flow === 'scroll') out.push(el, ...el.children); + else for (const child of el.children) scrollBoxes(child, out); +} + +/** + * Tells when what is in the page's main column gets higher or lower: text that streams in, a + * card that arrives, rows that load. A control can then be under a toast that was put there + * before. It watches the boxes that scroll in each `main` of the page and what is in them + * (`scrollBoxes`), and calls `changed` when the height of one changes. Not when one is seen for + * the first time, and not when the page scrolls. + * + * `look()` reads the page again (after a change of layout other boxes scroll); `stop()` ends + * the watch. + */ +export function contentWatch(changed: () => void): { look(): void; stop(): void } { + /** What is watched, with the height it had last (none before its first report). */ + const heights = new Map(); + const observer = new ResizeObserver((entries) => { + let any = false; + for (const entry of entries) { + const before = heights.get(entry.target); + const now = entry.contentRect.height; + if (before !== undefined && before !== now) any = true; + heights.set(entry.target, now); + } + if (any) changed(); + }); + return { + look() { + const found: Element[] = []; + for (const main of document.querySelectorAll('main')) scrollBoxes(main, found); + const now = new Set(found); + for (const el of [...heights.keys()]) { + if (now.has(el)) continue; + observer.unobserve(el); + heights.delete(el); + } + for (const el of now) { + if (heights.has(el)) continue; + heights.set(el, undefined); + observer.observe(el); + } + }, + stop() { + observer.disconnect(); + heights.clear(); + }, + }; +} diff --git a/src/onboarding/Onboarding.svelte b/src/onboarding/Onboarding.svelte index 0ed0941a..1b5e9b88 100644 --- a/src/onboarding/Onboarding.svelte +++ b/src/onboarding/Onboarding.svelte @@ -28,6 +28,11 @@ const points = $derived(xp(ui.quest)); const sound = $derived(ui.questSound && !ui.reducedMotion); const level = $derived(LEVELS[idx]); + // Another level is another page: the toast stack looks for its place again. + $effect(() => { + void current; + untrack(() => ui.layoutRev++); + }); // Someone who already has repositories is not new here: don't walk them through it uninvited. onMount(() => { diff --git a/src/shell/CrewStrip.svelte b/src/shell/CrewStrip.svelte index 690c2297..972193e0 100644 --- a/src/shell/CrewStrip.svelte +++ b/src/shell/CrewStrip.svelte @@ -1,6 +1,8 @@ -
      - {#each leads as a (a.id)} - - {/each} - {#if leads.length && crew.length}{/if} - {#each crew as a (a.id)} - - {/each} +
      + {#if leads.length || crew.length} +
      + {#each leads as a (a.id)} + + {/each} + {#if leads.length && crew.length}{/if} + {#each crew as a (a.id)} + + {/each} +
      + {/if} {#if store.workspace && starter} {/if} + {#if flips} + + {/if}
      {#if s.status === 'needs_sign_in'}

      {signInSteps(clean(s.name))}

      {/if} {#if s.error}

      {clean(s.error)}

      {/if} From 13e67089fa511e3ccc3304dad4eeb85cc2724d70 Mon Sep 17 00:00:00 2001 From: julienwuthrich-ant Date: Mon, 23 Nov 2026 11:51:12 -0800 Subject: [PATCH 017/120] Demo: the guide names the real commands and says where the other demo pages are DEMO.md checked against src/lib/mock.ts and src/lib/demo: every parameter it lists is read, and the demo reads none it leaves out. Cy's saved-rule command, Bo's delete, Ada's question before she stops her type check and `?skip=0` are now said as the script does them. Co-Authored-By: Claude Opus 5.5 --- docs/DEMO.md | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/docs/DEMO.md b/docs/DEMO.md index 93bd6071..a7768e2a 100644 --- a/docs/DEMO.md +++ b/docs/DEMO.md @@ -17,7 +17,7 @@ Parameters go in the URL and can be combined. They are read once, when the page | --- | --- | | `?ws=1` | Opens `acme/web` at once. | | `?speed=2` | Plays the script faster (`0.5` is slower). | -| `?skip=90` | Starts 90 seconds into the script. It also opens the repo. | +| `?skip=90` | Starts 90 seconds into the script. Any value, `0` included, also opens the repo. | | `?autoplay=1` | Runs each plan and allows each request by itself. | | `?onboard=1` | A machine with no agent CLI installed, to see the first-run quest. | @@ -70,8 +70,9 @@ request of one office is there again when you come back to it. agent is in, and gets no turn of its own. With another CLI it waits for the turn's end. The wait is about a second: slow the script down (`?speed=0.25`) to see the "Queued" line. - "Always allow in this repo": Ada asks before `npm install -D @testing-library/react`. Save the - rule for `npm install` on that card, and Cy's later `npm install` is allowed without a question. - A command that deletes (`rm -rf dist && npm run build`) offers no rule. + rule for `npm install` on that card, and Cy's later `npm install -D @axe-core/playwright` is + allowed without a question. + A command that deletes (Bo's `rm -rf dist && npm run build`) offers no rule. - A 1:1 Claude agent you hire works in its mode: "plan first" shows a plan, "ask for edits" asks before the edit, "accept edits" edits without a question. - Close office (on the map) refuses while the office has unfinished work or an agent is in a turn. @@ -84,8 +85,15 @@ request of one office is there again when you come back to it. - A command an agent leaves running in the background: in her first task Ada starts a type check (`npx tsc --noEmit --watch`) and stops it before she reports. While it runs, her sheet lists it under "In the background" with Stop, and her History has one row for each change of the list. - Without `?autoplay=1` it stays until you answer her `npm install` request: run the first plan - (`?skip=20`), open Ada's sheet, and press Stop. + Without `?autoplay=1` it stays until you answer her `npm install` request and then her + question about the `localStorage` fallback: run the first plan (`?skip=20`), open Ada's sheet, + and press Stop. + +## Other demo pages + +`office-demo.html` (the office alone) and `character-lab.html` (the characters) read parameters +of their own: see `src/office/demo.ts`, `src/office/demo/Harness.svelte` and +`src/office/demo/lab.ts`. They are tools for the office's look, not part of the app's demo. ## What the demo cannot show From f35a3fb3cdf46118d81c8e5352ab0d06ad2784fc Mon Sep 17 00:00:00 2001 From: julienwuthrich-ant Date: Mon, 23 Nov 2026 11:52:28 -0800 Subject: [PATCH 018/120] macOS: the Keychain and keep-awake helper lines are tested on every build The lines Codly hands to `security -i` (inbound secrets, connection keys) and the `caffeinate` arguments are now small pure functions, so the Linux CI tests what only ran on a Mac before. No behaviour change. Co-Authored-By: Claude Opus 5.5 --- .../src/housekeeping/connections.rs | 20 +++++++++++++++--- crates/codly-core/src/inbound/secrets.rs | 21 +++++++++++++++---- src-tauri/src/awake.rs | 12 ++++++++++- 3 files changed, 45 insertions(+), 8 deletions(-) diff --git a/crates/codly-core/src/housekeeping/connections.rs b/crates/codly-core/src/housekeeping/connections.rs index 4b7b045f..238a701f 100644 --- a/crates/codly-core/src/housekeeping/connections.rs +++ b/crates/codly-core/src/housekeeping/connections.rs @@ -190,10 +190,8 @@ impl SecretStore for KeychainStore { fn set(&self, account: &str, value: &str) -> anyhow::Result<()> { use std::io::Write; - anyhow::ensure!(!account.contains(['"', '\'', '\\', ' ', '\n']), "bad account name"); - let hex: String = value.bytes().map(|b| format!("{b:02x}")).collect(); + let cmd = add_line(account, value)?; let mut child = Command::new("security").arg("-i").stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::piped()).spawn()?; - let cmd = format!("add-generic-password -U -s {KEYCHAIN_SERVICE} -a {account} -X {hex}\n"); child.stdin.take().ok_or_else(|| anyhow::anyhow!("no stdin"))?.write_all(cmd.as_bytes())?; let out = child.wait_with_output()?; anyhow::ensure!(out.status.success() && out.stderr.is_empty(), "the Keychain refused the key: {}", String::from_utf8_lossy(&out.stderr).trim()); @@ -212,6 +210,14 @@ impl SecretStore for KeychainStore { } } +/// The `security -i` line that stores `value`: hex after `-X`, so no character of the key can +/// end the word or the line. +fn add_line(account: &str, value: &str) -> anyhow::Result { + anyhow::ensure!(!account.contains(['"', '\'', '\\', ' ', '\n']), "bad account name"); + let hex: String = value.bytes().map(|b| format!("{b:02x}")).collect(); + Ok(format!("add-generic-password -U -s {KEYCHAIN_SERVICE} -a {account} -X {hex}\n")) +} + /// All slots of an entry have a key. pub fn has_keys(e: &CatalogEntry, store: &dyn SecretStore) -> bool { e.secrets.iter().all(|s| store.get(&account(e.id, s.env)).is_some()) @@ -370,6 +376,14 @@ pub(crate) mod tests { use super::*; + #[test] + fn the_keychain_line_carries_the_key_as_hex_on_one_line() { + assert_eq!(add_line("github:GITHUB_TOKEN", "a b\"\n").unwrap(), "add-generic-password -U -s codly-mcp -a github:GITHUB_TOKEN -X 612062220a\n"); + for bad in ["a b", "a\"b", "a'b", "a\\b", "a\nb"] { + assert!(add_line(bad, "k").is_err(), "{bad:?}"); + } + } + #[derive(Default)] pub struct MemoryStore(RefCell>); diff --git a/crates/codly-core/src/inbound/secrets.rs b/crates/codly-core/src/inbound/secrets.rs index 207c9ddb..91b58f72 100644 --- a/crates/codly-core/src/inbound/secrets.rs +++ b/crates/codly-core/src/inbound/secrets.rs @@ -81,6 +81,14 @@ fn plain(s: &str) -> bool { !s.is_empty() && s.len() <= 512 && s.bytes().all(|b| b.is_ascii_alphanumeric() || b"._:/+=@-".contains(&b)) } +/// The `security -i` line that stores `value` (stdin, not argv: other processes can read argv). +fn add_line(service: &str, key: &str, value: &str) -> Result { + if !plain(key) || !plain(value) { + bail!("the value contains characters the Keychain helper cannot take (use letters, digits and . _ : / + = @ -)"); + } + Ok(format!("add-generic-password -U -s {service} -a {key} -w {value}\n")) +} + impl SecretStore for Keychain { fn get(&self, key: &str) -> Result> { if !plain(key) { @@ -95,11 +103,8 @@ impl SecretStore for Keychain { } fn set(&self, key: &str, value: &str) -> Result<()> { - if !plain(key) || !plain(value) { - bail!("the value contains characters the Keychain helper cannot take (use letters, digits and . _ : / + = @ -)"); - } + let line = add_line(&self.service, key, value)?; let mut child = Command::new("security").arg("-i").stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::null()).spawn()?; - let line = format!("add-generic-password -U -s {} -a {key} -w {value}\n", self.service); child.stdin.take().expect("piped").write_all(line.as_bytes())?; child.wait()?; // `-i` exits 0 even when a command failed, so read it back if self.get(key)?.as_deref() != Some(value) { @@ -223,6 +228,14 @@ mod tests { assert!(ct_eq(b"", b"")); } + #[test] + fn the_keychain_line_takes_plain_words_only() { + assert_eq!(add_line("dev.codly.inbound", "slack_bot", "xoxb-1-abc.DEF_ghi").unwrap(), "add-generic-password -U -s dev.codly.inbound -a slack_bot -w xoxb-1-abc.DEF_ghi\n"); + for (key, value) in [("a b", "v"), ("k", "two words"), ("k", "a\nadd-generic-password"), ("k", "\"q\""), ("", "v"), ("k", "")] { + assert!(add_line("s", key, value).is_err(), "{key:?} {value:?}"); + } + } + #[test] fn secrets_do_not_debug_print() { assert_eq!(format!("{:?}", Secret::new("hunter2")), "Secret(***)"); diff --git a/src-tauri/src/awake.rs b/src-tauri/src/awake.rs index c692927b..1ae40945 100644 --- a/src-tauri/src/awake.rs +++ b/src-tauri/src/awake.rs @@ -82,13 +82,18 @@ impl Drop for Awake { /// `caffeinate -i -w `: no idle sleep until this process is ended, or Codly is gone. fn caffeinate() -> io::Result { Command::new("/usr/bin/caffeinate") - .args(["-i", "-w", &std::process::id().to_string()]) + .args(caffeinate_args(std::process::id())) .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::null()) .spawn() } +/// `-i`: no idle sleep (the display may still sleep). `-w `: until that process ends. +fn caffeinate_args(pid: u32) -> [String; 3] { + ["-i".into(), "-w".into(), pid.to_string()] +} + /// Keep the Mac awake while work is under way, for as long as Codly runs. Only macOS has the /// tool; elsewhere (`codly serve` on a server) there is nothing to do. pub async fn run(core: Arc) { @@ -125,6 +130,11 @@ mod tests { awake.helper.as_ref().map(Child::id) } + #[test] + fn caffeinate_holds_off_idle_sleep_only_while_codly_runs() { + assert_eq!(caffeinate_args(4242), ["-i", "-w", "4242"]); + } + #[test] fn awake_while_work_is_under_way_and_for_a_moment_after() { let start = Instant::now(); From 76b706684c1ab9bf9c9dc1205dd9c09c9f2ec35d Mon Sep 17 00:00:00 2001 From: julienwuthrich-ant Date: Mon, 23 Nov 2026 11:54:29 -0800 Subject: [PATCH 019/120] README: one guide a new user can follow, checked against the code The README grew in small pieces over five rounds. It now goes in order: what Codly is, install, first run, the main flow (ask, plan, run, approve, review, merge, undo), long runs, safety, each CLI and what was really checked with it, the settings with their real defaults, shortcuts, `codly serve`, troubleshooting and the known gaps. Fixed on the way: Settings paths (Accounts and API keys are in Team, Storage in General, webhooks in Automation), the install button ("Install for me"), the Gemini and Cursor commands, the Codex sandbox (a command can ask to leave it; with network on a push needs no request), Full access also asks for a plan an agent shows you, the exact `.env` files copied into a worktree, and `--host` needs `--allow-remote`. Co-Authored-By: Claude Opus 5.5 --- README.md | 775 ++++++++++++++++++++++++++++++++---------------------- 1 file changed, 459 insertions(+), 316 deletions(-) diff --git a/README.md b/README.md index c41bc494..a46d6c76 100644 --- a/README.md +++ b/README.md @@ -7,116 +7,34 @@ ▶ [Watch the 3-minute tour](https://cdn.jsdelivr.net/gh/jwuthri-cloud/Codly@ed48fc5f4c9288d5e500d73756b29836b638e716/docs/media/codly-tour.mp4): ask the Lead, run its plan, approve, merge, and start a long-term agent of your own. -Codly turns the coding CLIs you already pay for (Claude Code, Codex, Gemini CLI and OpenCode) into one -team on your Mac. A Lead agent plans the work, each agent builds in its own git worktree, and nothing -lands on your branch until you merge it. It is a macOS app built with Tauri, Svelte and Rust. +## What Codly is -![Codly's World view: coding agents at work in a 3D office](site/shots/office.jpg) - -## Why - -Running several coding agents in one repo gets messy fast. They step on each other's files, you lose -track of who is doing what, and every approval is a prompt in a separate terminal. Codly puts them -under one supervisor and shows the same events in two synchronized views: - -- **Workspace**: chat with the Lead or talk 1:1 with any agent. Per-agent timeline, shared board, task - dependency graph, diffs, terminals, and an approvals inbox. -- **World**: a three.js office. Agents walk to the library to search, to the server room to run tests, - and raise a hand when they need you. Every motion comes from a real event. - -## Screenshots - -These come from the built-in demo: a fake `acme/web` repo with a scripted team. - -### The Lead proposes a plan - -Describe the goal to the Lead. It reads the repo read-only and either answers or proposes a small plan: -tasks, dependencies, the agent for each task, and any assumptions it made. You run it, change it or -cancel it. +Codly runs the coding CLIs you already have (Claude Code, Codex, Gemini CLI and OpenCode) as one +team on your Mac. A Lead agent plans the work. Each worker builds in its own git worktree. Codly +checks the work, can have another agent review it, and merges it into a branch of its own. Nothing +lands on your branch until you press Merge. It is a macOS app built with Tauri, Svelte and Rust. -![The Lead proposes a plan with three tasks and assumptions to confirm](site/shots/plan.jpg) - -### Follow the plan as it runs - -The plan room lists every task with its checks and the files it may write. A task that depends on -another waits until that one is merged. - -![Plan room showing tasks in progress and tasks waiting on them](site/shots/planroom.jpg) - -### Review finished work +Running several agents in one repo by hand gets messy: they edit the same files, you lose track of +who does what, and every approval is a prompt in another terminal. Codly puts them under one +supervisor and shows the same events in two views: -Each finished task shows the verify command that ran, the size of the diff, and the integration branch it -merged into. Agents can ask the Lead a question mid-task, and the answer comes back into the thread. - -![A finished task with its test result, diff size and merge target](site/shots/done.jpg) +- **Workspace**: chat with the Lead or talk 1:1 with any agent. A timeline per agent, a shared + board, the task graph, diffs, terminals and the approval cards. +- **World**: a three.js office. Agents walk to the library to search, to the server room to run + tests, and raise a hand when they need you. Every work motion comes from a real event. -### Approve what matters - -Commands an agent wants to run arrive in one approvals inbox. Codly checks each request against its rules -first (here: it deletes files, stays inside the agent's worktree, and makes no network calls), then asks -you. Approve once, allow for the session, or deny. For a command you trust, or a tool of an MCP server -that a Claude Code agent asks for, choose "Always allow in this repo": Codly then stops asking every agent in that repo about it (never about -deletes, `git push`, `sudo`, secrets or paths outside the worktree), and Settings lists the rules so you -can remove them. - -![Approval request for a shell command, with Approve once, Allow for this session and Deny](site/shots/approval.jpg) - -## How it works - -1. **Ask the Lead.** It reads the repo read-only and either answers or submits a task plan. Each request - has a mode: Ask (answers only), Plan (you press Run plan), Auto (plans and runs) or Direct (hands the - work straight to a team member or consultant). Tasks go to your standing team or to a consultant the - Lead hires for one task. -2. **Validate and run.** Codly checks the plan for cycles and for two tasks writing the same files at once. - You click **Run plan**. -3. **Work in isolation.** Each task runs in its own git worktree and branch. The worker gets a pointer pack - of the relevant code and the team's memory. -4. **Land the work.** When a worker finishes, Codly commits, re-runs the verify commands, checks the write - scope, optionally asks a reviewer from another vendor, and merges into the plan's integration branch. - Agents never commit on their own. -5. **You merge.** Review the diff and merge it into your branch. Codly pushes your branch only when you - press Push. For a review on GitHub, **Create pull request** pushes the plan's branch and opens a pull - request with a title and a description drafted from the plan, which you can edit first. - -Agents coordinate through Codly's MCP tools, so every exchange is typed, validated and visible. Every -agent gets `codly_get_task`, `codly_board`, `codly_search`, `codly_memory_search`, `codly_memory_write`, -`codly_kg_query`, `codly_kg_add` and `codly_post_note`. The Lead adds `codly_submit_plan`, -`codly_message_member`, `codly_quick_task` and `codly_reassign`. Workers add `codly_submit_report` and -`codly_ask_lead`. Reviewers get `codly_submit_review`. The Lead and workers can also raise -`codly_ask_user` to ask you a decision. - -## Supported agents - -| Agent | How Codly talks to it | -| ----------- | -------------------------------------------------------------------------------------- | -| Claude Code | `claude` in stream-JSON mode, with the stdin control protocol for approvals and interrupts | -| Codex | One `codex app-server` per agent (JSON-RPC over stdio): live command output, real approvals | -| Gemini CLI | ACP (`gemini --acp`) | -| OpenCode | ACP (`opencode acp`) | - -Cursor and Copilot use the same ACP adapter, but they are less tested. - -## First run - -A short onboarding quest line checks which agent CLIs are installed, offers a visible "Run it for me" -install terminal for the missing ones, and walks you through setting up a Lead, a crew and a first -mission. - -Approvals have four modes: balanced, strict, autonomous and Full access (auto-approves everything except -a few hard floors; off unless you choose it). Autonomous is a list of risky commands, not a sandbox: see -[What an agent's commands can do](#subscriptions-and-safety). Settings also holds Triggers (schedules and -network mode) and Inbound (webhook sources for the Lead; Slack is not available yet). - -## Requirements +![Codly's World view: coding agents at work in a 3D office](site/shots/office.jpg) -- macOS 14 or later -- At least one agent CLI, installed and signed in +Status: early. This is the v0.1 vertical slice. Expect rough edges, and read +[Limits and known gaps](#limits-and-known-gaps) before you point it at a repository you care about. ## Install +You need macOS 14 or later and at least one agent CLI, installed and signed in. + ### Download -Coming with the first release: there is no download yet. Until a release is on the +There is no release yet. Until one is on the [Releases page](https://github.com/jwuthri-cloud/Codly/releases), build Codly from source (below). When a release is there: @@ -144,7 +62,7 @@ Codly does not update itself yet: for a newer version, download it again. ### Build from source -You need Rust 1.90+, Node 22+ and pnpm. +You need Rust 1.90 or later, Node (CI uses Node 22) and pnpm. ```bash pnpm install @@ -152,256 +70,481 @@ pnpm tauri dev # run the desktop app from the checkout scripts/install-app.sh # or build Codly.app and put it in /Applications ``` -Other useful commands: +To look at the UI without building the app, `pnpm dev` serves it in a browser on a scripted demo: +no agent CLI runs and nothing is written to disk. [docs/DEMO.md](docs/DEMO.md) lists the URL +parameters that open each screen. -```bash -pnpm dev # the UI alone in a browser, on a scripted demo session -pnpm test # frontend tests (Vitest) -pnpm check # svelte-check and TypeScript -cargo test --workspace # core tests; adapters replay captured CLI transcripts -pnpm tauri build # build the macOS app and .dmg -``` +## First run -To use Codly from a browser instead of its window, run the app with `serve`: +The onboarding is a short quest line. It checks which agent CLIs are installed and signed in, offers +**Install for me** (a visible terminal that runs the vendor's install command) for the missing ones, +and walks you through a Lead, a crew and a first request. Then open a repository (⌘O). -```bash -/Applications/Codly.app/Contents/MacOS/codly serve # prints a link with a token; --port N -``` +## The main flow -It runs without a window or Dock icon until Ctrl+C. Run while the app is already open, -the open app serves too and opens the link in your browser. +These screenshots come from the browser demo: a made-up `acme/web` repo with a scripted team. -`codly serve` listens on this Mac only (127.0.0.1). The page can open terminals and control your -agents, and the traffic is plain HTTP, so to reach it from another machine use an SSH tunnel: -`ssh -L 4280:127.0.0.1:4280 `, then open the link on that machine. `--host
      ` -with an address other machines can reach is refused unless you add `--allow-remote`; the link -then works for anyone on your network until Codly stops. Quit the app first: an app that is -already open does not serve to the network. `codly --help` lists every command and -`codly --version` prints the version. +### 1. Ask -## Develop +Write to the Lead. It reads the repo read-only. Each request has a mode, picked under the composer +or with ⇧⇥: -Before you push, run the checks that CI runs: +- **Ask**: the Lead only answers. +- **Plan** (the default): the Lead proposes a plan and you press **Run plan**. +- **Auto**: the plan runs at once. **Run plans without asking** in Settings makes Auto the default. +- **Direct**: no plan card; the work goes straight to a team member or a consultant. -```bash -scripts/verify.sh # pnpm check, pnpm test, pnpm build, cargo test --workspace -``` +You can also start a request from a GitHub issue or pull request (**From issue…**, **From pull +request…** in the `/` menu): your own `gh` reads it. Each request has its own Lead and thread +(⌘N for a new one), so several requests can run side by side. -It also fails when the tests rewrite `src/lib/gen`: those TypeScript types are generated from the -Rust types by `cargo test`, so commit them with the change that needs them. +### 2. Plan -CI (`.github/workflows/ci.yml`) runs the same script on Linux for every pull request and every -push to `main`, and compiles the workspace on macOS. To run it on Linux yourself, install the -system packages the workflow lists. +The plan lists tasks, their dependencies, the agent for each task, the files each task may write, +the commands that check it, and the assumptions the Lead made. Codly checks the plan: no cycles, +and two tasks that would write the same files run one after the other. You run it, change it or +cancel it. A task whose checks cannot fail (`true`, `test -f …`) is marked on the card. -## Troubleshooting +![The Lead proposes a plan with three tasks and assumptions to confirm](site/shots/plan.jpg) -Settings → General → Troubleshooting collects what a bug report needs: the Codly version, your -system, your agent CLIs and the last log lines. Tokens, keys, email addresses and paths under your -home folder are taken out. Repository and agent names can remain: read it, then paste it in the -issue. The same button is on the “Codly couldn’t start” screen. +### 3. Run -The log file is `~/Library/Application Support/dev.codly.desktop/logs/codly.log` (at most 5 MB; -the file before it is `codly.1.log`). An internal error (a panic) writes its place and backtrace -there. To log more, start Codly with `CODLY_LOG=debug`: the file then also takes Codly's own -debug lines (those of the libraries it uses go to the terminal only). +Each task runs in its own git worktree and branch, started from the plan's integration branch. The +worker gets a pointer pack of the relevant code and the team's memory. A task that depends on +another waits until that one is merged. Tasks go to your standing team (set in Settings → Team) or +to a consultant the Lead hires for one task. -## Project layout - -- `crates/codly-core/`: the engine, with no Tauri dependency. Orchestrator (Lead, team, planner, scheduler, - merge queue, approval broker, triggers), agent adapters, SQLite store, git, code index, memory, inbound - sources and the MCP server. -- `src-tauri/`: the macOS shell (Tauri 2) that hosts the engine, and `codly serve` (the same UI in a - browser). -- `src/`: the Svelte 5 UI: the Workspace, the World (`src/office/`, three.js), the neighbourhood map - (`src/world/`), Settings (`src/overlays/`) and onboarding. -- `public/`: the office's furniture models and sounds. These are third-party assets (CC0 and CC BY); - each folder has its licence or credits file. -- `site/`: the landing page and the live demo build. -- `scripts/`: `install-app.sh` builds Codly.app and installs it in /Applications; `kaykit-clips.py` - converts animation clips for the World. -- `voice/`: experimental and optional. A Python relay that lets you talk to an agent out loud through - OpenAI Realtime, used only by `codly serve`. Its start script needs the author's own OpenAI workload - identity, so nobody else can run it as it is. Without the relay everything else works; a voice call - fails with "the voice relay is not running". -- `research-skills/`: optional skills for research work. They are not part of the app; you install them - by hand with `research-skills/install.sh`. -- `docs/`: architecture, design notes and the research behind them. +![Plan room showing tasks in progress and tasks waiting on them](site/shots/planroom.jpg) -The full code map is in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md), section 8. +### 4. Approve -## Subscriptions and safety - -**Your sign-ins and keys** - -- Codly spawns the unmodified CLIs you installed and signed in to. It does not proxy them. To see who is - signed in, it runs the CLI's own status command (Claude Code, Codex) or reads the CLI's settings file - (Gemini: the sign-in method and the account email, no token). -- Codly does not read your CLIs' sign-in tokens, with one exception that is off until you turn it on: - **Show Claude usage before an agent runs** (Settings → Accounts). With it on, each time Codly checks - your sign-ins it reads the Claude Code sign-in token (from the Keychain, or from the sign-in's - `.credentials.json` file) and sends it to `api.anthropic.com` to ask for your usage, as `/usage` does. - Codly does not store or log the token. Check Anthropic's terms first: they may not allow another app to - use this token. With it off, a sign-in shows its usage once an agent has run on it. -- Keys that you give to Codly are stored in the macOS Keychain, not in Codly's settings or database: your - own API keys (Settings → API keys; each one goes to one CLI only), the Groq key for dictation, webhook - secrets, and the keys of the tool servers you switch on for agents. -- Each agent shows a billing badge (subscription, API key or third party). API-key variables that would - silently switch billing are removed from agent environments, unless you turned on your own API key for - that vendor. -- The same goes for the variables that give Claude Code another sign-in than `claude auth login`: - `CLAUDE_CODE_USE_BEDROCK`, `CLAUDE_CODE_USE_VERTEX` and `CLAUDE_CODE_OAUTH_TOKEN` (a token from - `claude setup-token`). Codly removes them from agent environments unless you turn on **Use my shell's - Claude sign-in** (Settings → Safety). With it on, Claude agents keep them from your login shell, as - Claude Code does in your terminal, and that account pays. Codly does not store the token. Check - Anthropic's terms before you use a subscription token this way. Every other `CLAUDE_CODE_*` variable - is always removed, so that an agent never takes itself for a part of the Claude Code session that - started Codly. +What an agent wants to do and Codly's rules do not settle comes to you as a card in the +conversation. Codly reads each request against its rules first (for example: it deletes files, it +reaches outside the agent's worktree, it uses the network), then asks you: **Approve once**, +**Allow for this session** or **Deny** (⌘↵, ⌥⌘↵, ⌘⌫). Questions an agent asks you come the same +way. See [Safety](#safety) for the approval modes and the saved rules. -**Your repository** +![Approval request for a shell command, with Approve once, Allow for this session and Deny](site/shots/approval.jpg) + +### 5. Review + +When a worker finishes, Codly commits its work (agents never commit by themselves), runs the task's +checks again, checks that it wrote only the files it was allowed to, and, if you turned on +**Cross-vendor review before merge**, asks an agent of another CLI to review it. A failure goes back +to the worker to fix. Work that passes merges into the plan's integration branch. + +In the Changes room you can read each diff, comment on lines, tick files as viewed, and send a task +back with your comments. **Last turn** shows only what an agent's last turn changed. + +![A finished task with its test result, diff size and merge target](site/shots/done.jpg) + +### 6. Merge + +A finished plan's card has **Merge into \**. Before you merge you can try the work: +**Run…** runs a command you type (for example `pnpm dev --port $CODLY_PORT_BASE`) in the plan's +worktree, and **Open in terminal** opens a shell there. If your branch moved since the plan +started, Codly first runs the plan's checks on the merge result; if the merge conflicts, **Have an +agent resolve it** gives the plan one more task. **Push to \** pushes your branch. +**Create pull request…** pushes the plan's own branch instead and opens a pull request with your +`gh`, with a title and description drafted from the plan that you can edit first. + +### 7. Undo + +**Undo merge** takes the last merge back while nothing was committed or pushed after it. Before +each turn of an agent Codly keeps a checkpoint of its worktree: **Restore files to this point** (in +the agent's Git tab) puts the files back, and can itself be undone. + +### Talk to one agent + +Besides requests to the Lead, you can hire a long-term 1:1 agent and chat with it, as in its own +CLI. It works in its own worktree (or, with **Git isolation** off, in your project folder), and its +Git tab has merge, push, pull request and checkpoints. For a Claude Code agent you can switch its +mode and model, compact its conversation, and read its context use without a restart. **Open in my +terminal** hands a Claude Code agent's session to your terminal (`claude --resume`), and **Give it +back** returns it to Codly. + +### How agents talk to Codly + +Agents coordinate through Codly's own MCP tools, so every exchange is typed, checked and visible. +Every agent gets `codly_get_task`, `codly_board`, `codly_search`, `codly_memory_search`, +`codly_memory_write`, `codly_kg_query`, `codly_kg_add` and `codly_post_note`. The Lead adds +`codly_submit_plan`, `codly_message_member`, `codly_quick_task` and `codly_reassign`. Workers add +`codly_submit_report` and `codly_ask_lead`. Reviewers get `codly_submit_review`. The Lead and +workers can also use `codly_ask_user` to ask you a decision. + +## Long runs and restarts + +- **Keep the Mac awake while agents work** (on by default): the Mac does not go to sleep by itself + while an agent works or a plan runs. It may sleep when all work waits for you. Closing the lid + still puts it to sleep. +- **Ask before quitting while agents work** (on by default). Agents are child processes of Codly: + they stop when it quits. +- **Resume work when Codly opens** (Ask by default): work that was under way when Codly closed does + not go on by itself. Codly asks once; until you answer, no task starts. Always and Never are the + other choices. +- Silent agents: a turn with no output for 10 minutes (60 while a tool call is open) is flagged and + you are notified; at twice that, the turn is interrupted once; after as long again, the run is + stopped. Settings → Safety → Silent agents sets the times. +- A worker turn that fails is retried after a wait; at its third failure in a row the task is + blocked with the error. A plan that cannot go on says so in its thread. +- Notifications (Settings → General → Notifications): one switch per kind, and by default only + while Codly is not in front. +- Budgets (Settings → Safety → Autonomy & Budgets): a token budget and a cost budget for all agents + together, both off by default. A used-up budget stops new work; it never kills an agent. + +## Safety + +### Approval modes and saved rules + +Settings → Safety → Approvals has four modes: + +| Mode | What asks you | +| --- | --- | +| Balanced (default) | Codly's rules settle the obvious cases; what has a risk (`rm -rf`, `git push`, a path outside the worktree, a network install) asks you. | +| Ask first | Every command and edit the CLI would ask about. | +| Autonomous | Only what Codly sees a risk in. | +| Full access | Nothing about commands or edits, risky ones included, except a few hard floors (below). | + +In Full access these still ask: an agent's questions, a plan an agent shows you, permission +changes, changes to an agent's own CLI settings, writes to Codly's own data, anything from a read-only agent, and a command that can +lose work in your project folder itself (a history rewrite, `git reset --hard`, `git clean`, a force +push, `rm -rf` outside the build folders). + +The rules read the text of a command. They do not see what a script, a test or a program does once +it runs. So Autonomous is a list of risky commands, not a sandbox: a command with no risk in its +text runs without asking, with the rights of your account. + +For a command you trust, or a tool of an MCP server that a Claude Code agent asks for, choose +**Always allow in this repo** on its card: Codly then stops asking every agent in that repo about +it. A rule never covers deletes, `git push`, `sudo`, secrets, paths outside the worktree or a +command that can lose work in your project folder. +Settings → Safety lists the rules so you can remove them. + +### OS sandboxes + +- Codex agents always start in Codex's own OS sandbox (`workspace-write`), which keeps their + writes in their working folder (its worktree) and a temporary folder. A command that Codex wants + to run outside the sandbox asks first, and the approval rules decide it like any other request: + Full access approves it. The sandbox's network is closed unless you turn on **Let Codex agents + use the network** (Settings → Safety → Sandbox; off by default). With it on, a command that needs + the network (a `git push`, a download) runs inside the sandbox without asking, so the approval + rules do not see it. +- Claude Code agents have no OS sandbox, unless you turn on **Sandbox Claude's shell** (Settings → + Safety → Claude Code; off by default). With it on, Claude Code runs the shell commands of workers + and 1:1 agents in its own OS sandbox: + - A sandboxed command can write only in the agent's folder (its worktree), a temporary folder and + the repository's git data. It can still read your other files. + - It can reach only the hosts that your Claude Code settings allow. Codly adds no host and no + folder. When a command wants another host, Codly asks you, in every approval mode except Full + access: the approval card names the host. If you allow it, the host stays allowed for the rest + of that agent's session, for every later command. If you deny it, the command gets a network + error. + - Commands still go through the approval rules, as they do with the switch off: what the rules + ask about (a `git push`, an `rm -rf`, a download) still asks you first. The sandbox is a second + check under the rules, not a way around them. So one command can ask twice: once for itself, + and once for a host it wants. + - A command that Claude wants to run outside the sandbox asks you first, in every approval mode + except Full access. The approval card says that it runs outside the sandbox. + - When an agent starts, Codly asks Claude Code whether its sandbox is really on. If it is not + (your system cannot run it, or a setting of your organization changes it), the agent does not + start and Codly tells you why. + - The sandbox covers shell commands only. File edits and tool servers (MCP) are not sandboxed: + they go through approvals as before. Codly's own checks (a task's verify commands, the setup + script) are not sandboxed either. +- Gemini, OpenCode, Cursor and Copilot agents have no OS sandbox. For them, and for Claude Code + agents without the switch, the approval rules are the only check. + +### Folder trust + +A repo's own agent configuration (Claude Code project settings with hooks or allow rules, project +MCP servers, and the like for the other CLIs) loads only after you trusted the folder. Codly asks +when it opens such a repo and again when those files change. Until then Claude Code starts without +them, and a CLI that Codly cannot start without them (Gemini CLI, OpenCode, Cursor) is not started +in that repo: it takes no task and reviews none. A worktree whose files are not the ones of your +folder (an agent changed them there) is shown with its own files, to trust by itself. + +The choice is about the repo's files, not yours: a Codex agent starts the MCP servers of your own +Codex config in every folder, trusted or not. To keep them out, turn off **Use my own CLI setup** +(Settings → General → Plans). + +Text that other people write is never taken as yours: a webhook message, or the issue or pull +request a request starts from, reaches the Lead as quoted data, and the plans made from it wait for +**Run plan** in every mode. The plan's card says why it waits. + +### What Codly never does without you - Codly commits and merges by itself only on its own `codly/…` branches: a task's branch, then the plan's integration branch after the task's checks pass. -- Codly's commit of an agent's work leaves out a new folder with more than 2,000 files and a new file - over 25 MB (build output or a dependency folder that the repository does not ignore). The task says - what was left out, its worker is asked once to ignore it, delete it or stage it (`git add`) as work - before the checks run, and the files stay in the worktree. Checkpoints leave the same paths out. - Every commit Codly makes says it in the same way, also the one before a merge, a push or a pull - request of a solo agent's branch. When no worker turn follows (you re-run a task's checks or merge - it anyway), the task goes on without the files, and the Lead tells you when **Lead follow-ups** is on. -- Codly changes your branch only when you press a button: **Merge** (a plan's integration branch, or one - agent's branch, into the branch you have checked out), **Commit** (your own uncommitted changes) and - **Push** (the branch you have checked out, to its remote, through your own SSH agent). +- It changes your branch only when you press a button: **Merge** (a plan's integration branch, or + one agent's branch, into the branch you have checked out), **Commit** (your own uncommitted + changes) and **Push** (the branch you have checked out, to its remote, through your own SSH + agent). - Before a merge writes to your branch, Codly keeps the branch as it was under the ref - `refs/codly/before-merge` in your repository, until the next merge. **Undo merge** takes the last merge - back while nothing was committed or pushed after it. Before you merge, a plan's card says how many - commits the plan is behind your branch. -- **Create pull request** pushes one of Codly's own `codly/…` branches (a plan's, or one agent's), never - a branch of yours and never with force. It asks first and names the remote, the branch and the base. - Your own `gh` opens the pull request with its sign-in: Codly stores no GitHub token. Without `gh` you - can still push the branch and open the compare page in your browser. A Codly branch starts from your - branch: when yours has commits that the remote does not have yet, they go with the push, and the - dialog says how many before you confirm. -- One kind of agent edits your project folder directly: an agent that you hire with **Git isolation** - switched off. The hire screen warns you about it. A command that can lose work in your folder (a - history rewrite, `git reset --hard`, `git clean`, a force push, `rm -rf` outside the build - folders) asks you first in every approval mode, Full access included: from that agent, and from - any agent that points such a command at your folder from its worktree. -- A repo's own agent configuration (Claude Code project settings with hooks or allow rules, project - MCP servers, and the like for the other CLIs) loads only after you trusted the folder. Codly asks - when it opens such a repo and again when those files change. Until then Claude Code starts - without them, and a CLI that Codly cannot start without them (Gemini CLI, OpenCode, Cursor) is not - started in that repo: it takes no task and reviews none. A worktree whose files are not the ones - of your folder (an agent changed them there) is shown with its own files, to trust by itself. - The choice is about the repo's files, not yours: a Codex agent starts the MCP servers of your own - Codex config in every folder, trusted or not. To keep them out, turn off "Use my own CLI setup" in - Settings. -- An agent that wants to run `git push` itself must ask you first, in every approval mode except Full - access, which approves it. That holds with **Sandbox Claude's shell** on too (below). -- By itself, Codly removes a worktree only when it is clean and merged, and deletes a `codly/…` branch - only when its work is merged and its plan has been over for a day. Work that is not committed or not - merged stays until you delete it in **Settings → Storage**, which first names what you would lose. - Raw logs of agent runs are deleted after 30 days; you can change that there too. + `refs/codly/before-merge` in your repository, until the next merge. Before you merge, a plan's + card says how many commits the plan is behind your branch. +- **Create pull request** pushes one of Codly's own `codly/…` branches (a plan's, or one agent's), + never a branch of yours and never with force. It asks first and names the remote, the branch and + the base. Your own `gh` opens the pull request with its sign-in: Codly stores no GitHub token. + Without `gh` you can still push the branch and open the compare page in your browser. A Codly + branch starts from your branch: when yours has commits that the remote does not have yet, they go + with the push, and the dialog says how many before you confirm. +- An agent that wants to run `git push` itself must ask you first, in every approval mode except + Full access, which approves it, and no saved rule covers it. That holds with **Sandbox Claude's + shell** on too. One exception: with **Let Codex agents use the network** on, a Codex agent's push + runs inside its sandbox without a request. +- One kind of agent edits your project folder directly: an agent that you hire with **Git + isolation** switched off. The hire screen warns you about it. A command that can lose work in + your folder asks you first in every approval mode, Full access included: from that agent, and from + any agent that points such a command at your folder from its worktree. Such an agent has no + checkpoints, because Codly never puts files back in your own folder. +- By itself, Codly removes a worktree only when it is clean and merged, and deletes a `codly/…` + branch only when its work is merged and its plan has been over for a day. Work that is not + committed or not merged stays until you delete it in **Settings → General → Storage**, which first + names what you would lose. Raw logs of agent runs are deleted after 30 days. Storage also has the + switch for this cleanup and the number of days for logs. + +### What Codly commits, copies and runs + +- Codly's commit of an agent's work leaves out a new folder with more than 2,000 files and a new + file over 25 MB (build output or a dependency folder that the repository does not ignore). The + task says what was left out, its worker is asked once to ignore it, delete it or stage it + (`git add`) as work before the checks run, and the files stay in the worktree. Checkpoints leave + the same paths out. - A new worktree gets copies of files that git ignores and an agent needs: `node_modules`, `.venv`, - `venv` and the `.env` files at the top of the repo, plus what a `.worktreeinclude` file at the top of - the repo lists (same syntax as `.gitignore`). Codly copies a file only when git ignores it in your - checkout and in the new worktree too, so that it stays out of the commits: commit the `.gitignore` - line first, or the task says that the file was not copied. To copy one file from a folder that git - ignores as a whole, write its path (`secrets/dev.env`), not only its name. Codly remembers what it - copied into each worktree: on a branch that does not ignore a copy, its commit leaves the copy out - and says so. The worker is then asked for the `.gitignore` line only, never to delete or commit the - copy. -- To try work before you merge it, a finished plan and a solo agent's Git tab have **Run…** and **Open - in terminal**. Run… runs a command you type (for example `pnpm dev --port $CODLY_PORT_BASE`) in that - worktree and shows its output. Codly keeps your last command for the repo and never picks one for - you. The command ends when you press Stop, when you merge that work, or when you quit Codly. In a - solo agent's worktree, a file the command writes becomes part of the agent's work unless git - ignores it. + `venv`, `.env`, `.env.local`, `.env.development.local` and `.env.test.local` at the top of the + repo, plus what a `.worktreeinclude` file at the + top of the repo lists (same syntax as `.gitignore`). Codly copies a file only when git ignores it + in your checkout and in the new worktree too, so that it stays out of the commits. Each worktree + gets its own block of ports in `$CODLY_PORT_BASE`. - A repo can have a setup script, `.codly/setup.sh`, that Codly runs once in each new worktree (to - install packages, or to write the worktree's own ports from `$CODLY_PORT_BASE` into a local env - file). It is off until you turn it on in Settings → Safety, which shows you the script. Codly runs - only the text you turned on: if the file changes, it asks you again. It runs a copy of that text - in the worktree's top folder, with the program its first line names (`#!/usr/bin/env bash`) or - `/bin/sh`: use paths from that folder, or `$CODLY_REPO_PATH` for your checkout, not the script's - own place (`$0`). The script is not sandboxed. + install packages, or to write the worktree's ports into a local env file). It is off until you + turn it on in Settings → Safety → New worktrees, which shows you the script. Codly runs only the + text you turned on: if the file changes, it asks you again. Use paths from the worktree's top + folder, or `$CODLY_REPO_PATH` for your checkout. The script is not sandboxed. - You decide what passes. Write the commands that must pass in `.codly/checks`, one on each line (`pnpm check`, `pnpm test`), and turn them on in Settings → Safety → Required checks, which shows them. Codly then runs them for every task, after the checks the Lead wrote, and again on every finished plan; **Check the work**, in the Git tab of an agent you chat with, runs them on that - agent's work. Codly runs only the text you turned on: if the file changes, tasks wait until you read - it again, and go on by themselves once you turn it on again or off. A plan card also marks a task - whose own checks cannot fail (`true`, `test -f …`). -- Before each turn of an agent, Codly keeps the files of the agent's worktree as a checkpoint (a commit - under a private ref, on no branch). **Restore files to this point**, in the agent's Git tab, puts the - files back and can be undone. It changes files only: the agent still remembers its later turns. An agent - with Git isolation off has no checkpoints, because Codly never puts files back in your own folder. - **Restore this file** puts one file of a checkpoint back and leaves the others. **Last turn**, in the - Git tab and on a task's diff in the Changes room, shows only what the last turn changed. A file or - folder that is too big for a commit is not in a checkpoint either: the Git tab names it, and a restore - that would write over it is refused. - -**What an agent's commands can do** - -- The approval rules read the text of a command. They do not see what a script, a test or a program does - once it runs. So **Autonomous** mode is a list of risky commands, not a sandbox: a command with no risk - in its text runs without asking, with the rights of your account. -- Codex agents always run in Codex's own OS sandbox, which keeps their writes in their worktree. -- Claude Code agents have no OS sandbox, unless you turn on **Sandbox Claude's shell** (Settings → - Safety; off by default). With it on, Claude Code runs the shell commands of workers and 1:1 agents in - its own OS sandbox: - - A sandboxed command can write only in the agent's folder (its worktree), a temporary folder and the - repository's git data. It can still read your other files. - - It can reach only the hosts that your Claude Code settings allow. Codly adds no host and no folder. - When a command wants another host, Codly asks you, in every approval mode except Full access: the - approval card names the host. If you allow it, the host stays allowed for the rest of that agent's - session, for every later command. If you deny it, the command gets a network error. - - Commands still go through the approval rules, as they do with the switch off: what the rules ask - about (a `git push`, an `rm -rf`, a download) still asks you first. The sandbox is a second check - under the rules, not a way around them. So one command can ask twice: once for itself, and once - for a host it wants. - - A command that Claude wants to run outside the sandbox asks you first, in every approval mode except - Full access. The approval card says that it runs outside the sandbox. - - When an agent starts, Codly asks Claude Code whether its sandbox is really on. If it is not (your - system cannot run it, or a setting of your organization changes it), the agent does not start - and Codly tells you why. - - The sandbox covers shell commands only. File edits and tool servers (MCP) are not sandboxed: they go - through approvals as before. Codly's own checks (a task's verify commands, the setup script) are - not sandboxed either. -- Gemini, OpenCode, Cursor and Copilot agents have no OS sandbox. For them, and for Claude Code agents - without the switch, the approval rules are the only check. - -**The network** + agent's work. If the file changes, tasks wait until you read it again. +- The Lead's verify commands go through the same risk rules: one with a risk waits for your OK on + its task. A check runs for at most 10 minutes by default (Settings → Safety → Review). + +### Your sign-ins and keys + +- Codly spawns the unmodified CLIs you installed and signed in to. It does not proxy them. To see + who is signed in, it runs the CLI's own status command (Claude Code, Codex) or reads the CLI's + settings file (Gemini: the sign-in method and the account email, no token). +- Codly does not read your CLIs' sign-in tokens, with one exception that is off until you turn it + on: **Show Claude usage before an agent runs** (Settings → Team → Accounts). With it on, each time + Codly checks your sign-ins it reads the Claude Code sign-in token (from the Keychain, or from the + sign-in's `.credentials.json` file) and sends it to `api.anthropic.com` to ask for your usage, as + `/usage` does. Codly does not store or log the token. Check Anthropic's terms first: they may not + allow another app to use this token. With it off, a sign-in shows its usage once an agent has run + on it. +- Keys that you give to Codly are stored in the macOS Keychain, not in Codly's settings or + database: your own API keys (Settings → Team → API keys; each one goes to one CLI only), the Groq + key for dictation, webhook secrets, and the keys of the tool servers you switch on for agents. +- Each agent shows a billing badge (subscription, API key or third party). API-key variables that + would silently switch billing are removed from agent environments, unless you turned on your own + API key for that vendor. +- The same goes for the variables that give Claude Code another sign-in than `claude auth login`: + `CLAUDE_CODE_USE_BEDROCK`, `CLAUDE_CODE_USE_VERTEX` and `CLAUDE_CODE_OAUTH_TOKEN` (a token from + `claude setup-token`). Codly removes them from agent environments unless you turn on **Use my + shell's Claude sign-in** (Settings → Safety → Claude Code). With it on, Claude agents keep them + from your login shell, as Claude Code does in your terminal, and that account pays. Codly does not + store the token. Check Anthropic's terms before you use a subscription token this way. Every + other `CLAUDE_CODE_*` variable is always removed, so that an agent never takes itself for a part + of the Claude Code session that started Codly. (Codly sets one of its own for Claude agents: + `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1`.) + +### The network - There are no Codly servers: no account, nothing to sync. Your CLIs talk to their own providers as before. -- Codly itself goes online only to install a CLI or a skill when you click, to fetch the tool servers - that agents start with (through `npx` or `uvx`), to push when you press Push or Create pull request - (your `gh` then opens the pull request, and reads its state and checks when you press Refresh), to read - an issue or a pull request with your `gh` when you start a request from one (**From issue…**, **From - pull request…**: the Lead gets its text as quoted data, nothing is written to GitHub, and because other - people write that text, the plans of that request wait for Run plan in every mode until one of them is - done; the plan's card says why), and for two - features that - are off until you turn them on: dictation (audio goes to Groq with your key) and Show Claude usage. - The voice relay in `voice/` talks to OpenAI, and only if you run it. -- Inbound webhooks listen on this Mac only (loopback) and are created switched off. A webhook message - shows under its endpoint's name, not as yours, and a plan made from it waits for Run plan unless you - let that endpoint run plans without asking; the plan's card says why it waits. Until your next - message, the Lead is also stopped before it messages a team member or reassigns a task. An agent you - pick to answer webhook messages asks as its approval mode says, whatever trust you gave it, from the - turn that reads such a message until a turn that your own message to it starts. `codly serve` also - listens on this Mac only, unless you pass `--host`. +- Codly itself goes online only to install a CLI or a skill when you click, to fetch the tool + servers that agents start with (through `npx` or `uvx`), to push when you press Push or Create + pull request, to use your `gh` for a pull request (it reads the pull request's state and checks + only when you press Refresh) or to read an issue or a pull request you start a request from, and + for two features that are off until you turn them on: dictation (audio goes to Groq with your + key) and Show Claude usage. The voice relay in `voice/` talks to OpenAI, and only if you run it. +- Inbound webhooks (Settings → Automation) listen on this Mac only (loopback) and are created + switched off. A webhook message shows under its endpoint's name, not as yours, and a plan made + from it waits for Run plan unless you let that endpoint run plans without asking. Until your next + message, the Lead is also stopped before it messages a team member or reassigns a task. An agent + you pick to answer webhook messages asks as its approval mode says, whatever trust you gave it, + from the turn that reads such a message until a turn that your own message to it starts. +- `codly serve` also listens on this Mac only; another `--host` needs `--allow-remote` (below). Provider terms change. Check them before heavy parallel use. +## The CLIs + +| CLI | How Codly runs it | What was checked | +| --- | --- | --- | +| Claude Code | `claude` in stream-JSON mode, with the stdin control protocol for approvals, interrupts, mode and model changes | The adapter's tests replay real recordings of Claude Code 2.1.311 (`docs/research/fixtures/claude-2.1.311/`, described in `docs/research/cli-claude-stream-json-2.1.311*.md`). | +| Codex | One `codex app-server` per sign-in (JSON-RPC over stdio), one thread per agent | Recorded live with Codex 0.161 before this release's work. The newer parts (subagents, Compact now, usage read, thread names) are built from the protocol types that codex-cli 0.166.0 generates and were never run live. | +| Gemini CLI | ACP (`gemini --acp --skip-trust`) | Recorded transcripts only; never run live during this release's work. | +| OpenCode | ACP (`opencode acp`) | Recorded transcripts only; never run live during this release's work. | +| Cursor, Copilot | ACP (`cursor-agent acp`, `copilot --acp`) | Never run: not installed on the test machine. | + +What works with each: + +- Every CLI: plans, tasks, worktrees, the gate, approvals through Codly's broker, Codly's MCP + tools, merge and pull request. +- Claude Code only: the opt-in OS sandbox, **Open in my terminal**, a message that reaches the agent + in the middle of its turn, the MCP server list with Reconnect, Stop for a background command, and + saved rules for MCP tools. +- Codex: its own OS sandbox, Compact now, usage windows read with its own sign-in, subagents shown + as rows. A message sent mid-turn reaches it in the turn too. +- Gemini CLI, OpenCode, Cursor and Copilot: no OS sandbox and no take-over to your terminal. + Gemini CLI, OpenCode and Cursor are not started in a folder whose own CLI files you did not + trust. + +Several sign-ins per CLI are supported (Settings → Team → Accounts); work is spread by quota left +or taken in order. + +## Settings + +Settings has five tabs: General, Team, Safety, Automation and Developer. The switches whose default +matters most: + +| Setting | Where | Default | +| --- | --- | --- | +| Approval mode | Safety → Approvals | Balanced | +| Run plans without asking | General → Plans | Off | +| Lead follow-ups | General → Plans | On | +| Use my own CLI setup | General → Plans | On | +| Keep the Mac awake while agents work | General → Long runs | On | +| Ask before quitting while agents work | General → Long runs | On | +| Resume work when Codly opens | General → Long runs | Ask | +| Office rules affect work | General → Office | Off: the office game never delays, refuses or changes work | +| Keep the office moving behind the chat | General → Office | Off | +| Notifications | General → Notifications | Every kind on, only while Codly is not in front | +| Agents at once | Team | 3 | +| Workers per account | Team → Accounts | 2 | +| Show Claude usage before an agent runs | Team → Accounts | Off | +| Sandbox Claude's shell | Safety → Claude Code | Off | +| Use my shell's Claude sign-in | Safety → Claude Code | Off | +| Let Codex agents use the network | Safety → Sandbox | Off | +| Cross-vendor review before merge | Safety → Review | Off | +| Time limit for checks | Safety → Review | 10 minutes | +| Circuit breaker | Safety → Autonomy & Budgets | On; token and cost budgets off | +| Silent agents | Safety → Silent agents | Flag after 10 min (60 with a tool call open), idle after 2 min | +| Webhooks | Automation | Each new endpoint off | + +## Keyboard shortcuts + +Press `?` in the app for the full sheet. The main ones: + +| Keys | Action | +| --- | --- | +| ⌘K | Search and commands | +| ⌘N, ⌘[ / ⌘] | New request; previous / next request | +| ⌘F | Find in the conversation | +| ⌘↵ | Approve once, or run the plan | +| ⌥⌘↵ | Allow for this session | +| ⌘⌫, ⇧⌘⌫ | Deny; deny with a note | +| Esc | Close, deselect; press twice to stop the running turn | +| ⇧⇥ | Next request mode: Ask, Plan, Auto, Direct | +| ⌘1, ⌘2, ⌘3 | Full office, full work, the neighbourhood map | +| G then H, P, C, K, T, S | Home, Plan, Changes, Knowledge, Terminal, Settings | +| ⌘O, ⌘, | Open repository; Settings | + +## Codly in a browser (`codly serve`) + +To use Codly from a browser instead of its window: + +```bash +/Applications/Codly.app/Contents/MacOS/codly serve # prints a link with a token; --port N +``` + +It listens on 127.0.0.1, port 4280 by default, and runs without a window or Dock icon until Ctrl+C. +Run while the app is already open, the open app serves too and opens the link in your browser. + +The page can open terminals and control your agents, and the traffic is plain HTTP. To reach it +from another machine, use an SSH tunnel: `ssh -L 4280:127.0.0.1:4280 `, then open the +link on that machine. `--host
      ` with an address other machines can reach is refused +unless you add `--allow-remote`; the link then works for anyone on your network until Codly stops. +Quit the app first: an app that is already open does not serve to the network. `codly --help` +lists every command and `codly --version` prints the version. + +## Troubleshooting + +Settings → General → Troubleshooting collects what a bug report needs: the Codly version, your +system, your agent CLIs and the last log lines. Tokens, keys, email addresses and paths under your +home folder are taken out. Repository and agent names can remain: read it, then paste it in the +issue. The same button is on the "Codly couldn't start" screen. + +The log file is `~/Library/Application Support/dev.codly.desktop/logs/codly.log` (at most 5 MB; +the file before it is `codly.1.log`). An internal error (a panic) writes its place and backtrace +there. To log more, start Codly with `CODLY_LOG=debug`: the file then also takes Codly's own +debug lines (those of the libraries it uses go to the terminal only). + +## Limits and known gaps + +- macOS only. The Linux CI builds and tests the code, but macOS-only code is compiled only by the + macOS CI job, and the packaged app has not been driven end to end by a test. +- Live CLI runs: Gemini CLI, OpenCode, Cursor and Copilot were not run during the latest work; Codex + features newer than version 0.161 come from its generated protocol types. See [The CLIs](#the-clis). +- Agents are children of the app. They stop when it quits or the Mac sleeps; a command an agent + left running with `&` keeps running after its agent stops. +- The approval rules read command text, not what a program does. Only Codex, and Claude Code with + its switch on, have an OS sandbox. +- **Open in my terminal** works for Claude Code agents only, between turns, and never for the Lead. +- Slack as an inbound source is not connected yet: its settings show "Not available yet". +- `voice/` is experimental. Its start script needs the author's own OpenAI workload identity, so + nobody else can run it as it is; without it a voice call fails with "the voice relay is not + running". +- The browser demo has no git, `gh` or shell behind it: diffs, commits and command output there are + made up. + +## Develop + +```bash +pnpm dev # the UI alone in a browser, on a scripted demo session +pnpm test # frontend tests (Vitest) +pnpm check # svelte-check and TypeScript +cargo test --workspace # core tests; adapters replay recorded CLI transcripts +pnpm tauri build # build the macOS app and .dmg +``` + +Before you push, run the checks that CI runs: + +```bash +scripts/verify.sh # pnpm check, pnpm test, pnpm build, cargo test --workspace +``` + +It also fails when the tests rewrite `src/lib/gen`: those TypeScript types are generated from the +Rust types by `cargo test`, so commit them with the change that needs them. + +CI (`.github/workflows/ci.yml`) runs the same script on Linux for every pull request and every +push to `main`, and compiles the workspace on macOS. To run it on Linux yourself, install the +system packages the workflow lists. + +### Project layout + +- `crates/codly-core/`: the engine, with no Tauri dependency. Orchestrator (Lead, team, planner, + scheduler, gate and merge queue, approval broker, triggers), agent adapters, SQLite store, git, + code index, memory, inbound sources and the MCP server. +- `src-tauri/`: the macOS shell (Tauri 2) that hosts the engine, and `codly serve`. +- `src/`: the Svelte 5 UI: the Workspace, the World (`src/office/`, three.js), the neighbourhood + map (`src/world/`), Settings (`src/overlays/`) and onboarding. +- `public/`: the office's furniture models and sounds. These are third-party assets (CC0 and CC + BY); each folder has its licence or credits file. +- `site/`: the landing page and the live demo build. +- `scripts/`: `install-app.sh` builds Codly.app and installs it in /Applications; + `kaykit-clips.py` converts animation clips for the World; `verify.sh` runs every check. +- `voice/`: the experimental voice relay (see above). +- `research-skills/`: optional skills for research work. They are not part of the app; you install + them by hand with `research-skills/install.sh`. +- `docs/`: architecture, design notes and the research behind them. + +The full code map is in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md), section 8. + ## Docs - [Architecture](docs/ARCHITECTURE.md): decisions, processes, event model, orchestration and memory. - [Release](docs/RELEASE.md): how a release is built, signed and published, and where the version is set. - [Browser demo](docs/DEMO.md): the scripted demo behind `pnpm dev`, and the URL parameters that open each screen. -- [Research](docs/research/): the reports behind each decision, and the consolidated - [critique](docs/research/CRITIQUE.md). - -## Status - -Early: this is the v0.1 vertical slice. Expect rough edges. +- [Research](docs/research/): the reports behind each decision, the Claude Code recordings, and the + consolidated [critique](docs/research/CRITIQUE.md). From 5f995cb418d42229e23074dda98afe5ca27748c7 Mon Sep 17 00:00:00 2001 From: julienwuthrich-ant Date: Mon, 23 Nov 2026 11:55:37 -0800 Subject: [PATCH 020/120] Research tools: the sanitizer also keeps the host name, a context report's skills and the machine's own hooks out of a fixture sanitize.py now replaces the machine's network name, empties the skill and plugin-agent lists of a get_context_usage answer, and drops the output of SessionStart hooks (the scenarios configure none, so those are the recording machine's). test_sanitize.py covers these rules and the init-line lists; run it with `python3 -m unittest test_sanitize`. Co-Authored-By: Claude Opus 5.5 --- .../drivers/claude-stream-json/README.md | 3 +- .../drivers/claude-stream-json/sanitize.py | 20 +++++-- .../claude-stream-json/test_sanitize.py | 53 +++++++++++++++++++ 3 files changed, 72 insertions(+), 4 deletions(-) create mode 100644 docs/research/drivers/claude-stream-json/test_sanitize.py diff --git a/docs/research/drivers/claude-stream-json/README.md b/docs/research/drivers/claude-stream-json/README.md index 13ca5ca7..b200ccc1 100644 --- a/docs/research/drivers/claude-stream-json/README.md +++ b/docs/research/drivers/claude-stream-json/README.md @@ -100,7 +100,8 @@ cd "$CAPTURE_DIR/fixtures" | file | what it is | |---|---| | `drv.py` | the driver: starts the CLI, logs both directions, answers `can_use_tool`, sends control requests | -| `sanitize.py` | raw -> fixture: paths, ids, account fields, machine lists, big images, foreign MCP servers | +| `sanitize.py` | raw -> fixture: paths, host name, ids, account fields, machine lists and hooks, big images, foreign MCP servers | +| `test_sanitize.py` | tests of the sanitizer rules that keep the machine out of a fixture (`python3 -m unittest test_sanitize`) | | `tl.py`, `tlq.py` | timeline viewers for a raw recording | | `cost.py` | sum of `total_cost_usd` over the recordings | | `notes_lib.py`, `make_notes_part2.py` | build the part 2 document; every quoted line is copied from a fixture | diff --git a/docs/research/drivers/claude-stream-json/sanitize.py b/docs/research/drivers/claude-stream-json/sanitize.py index 6bb81bc1..34d391f1 100644 --- a/docs/research/drivers/claude-stream-json/sanitize.py +++ b/docs/research/drivers/claude-stream-json/sanitize.py @@ -16,15 +16,19 @@ {"_meta": {...}} a note of the driver (stdin closed, exit code, files found on disk) anything else a line of the CLI's stdout, as written (after sanitizing) -Sanitizing: user name and temp paths, every id (session, request, message, tool use, task, run, hook, uuid), +Sanitizing: user name, host name and temp paths, every id (session, request, message, tool use, task, run, hook, uuid), thinking signatures, account fields, and the lists that describe the machine (slash commands, skills, plugins, -agents, model catalog, usage report) are replaced or shortened. Key names and structure are kept. +agents, model catalog, usage report, skills in a context report, the output of the machine's own SessionStart hooks) +are replaced or shortened. Key names and structure are kept. """ -import datetime, getpass, glob, json, os, re, shutil, subprocess, sys +import datetime, getpass, glob, json, os, re, shutil, socket, subprocess, sys OUT = os.path.abspath(os.environ.get("CAPTURE_DIR") or os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) USER = getpass.getuser() HOME = os.path.expanduser("~") +# The machine's network name ("Someones-MacBook-Pro.local") and its short form: the CLI can write them (remote control). +HOSTNAMES = sorted({h for h in (socket.gethostname(), socket.gethostname().split(".")[0]) if len(h) >= 6 and h != "localhost"}, key=len, reverse=True) +HOOK_GONE = "" DOC_NAME = os.environ.get("DOC_NAME", "the document next to the fixtures") # MCP servers the scenarios themselves configure. Every other server name is this machine's and is removed. OWN_MCP = ("exits-at-once", "no-such-command", "needs-login", "ping-project", @@ -148,6 +152,14 @@ def transform(v, ids, sig, key=None): d["terminal_slash_commands"] = d["terminal_slash_commands"][:1] d["mcp_servers"] = [s for s in d.get("mcp_servers", []) if s.get("name") in OWN_MCP] d["tools"] = [t for t in d.get("tools", []) if not t.startswith("mcp__") or t.split("__")[1] in OWN_MCP] + if d.get("type") == "system" and d.get("subtype") == "hook_response" and d.get("hook_event") == "SessionStart": + # The scenarios configure no SessionStart hook: these are the machine's own, and print its skills and rules. + for k in ("output", "stdout", "stderr"): + if d.get(k): + d[k] = HOOK_GONE + if isinstance(d.get("skills"), dict) and "skillFrontmatter" in d["skills"]: # get_context_usage + d["skills"] = dict(d["skills"], skillFrontmatter=[]) + d["agents"] = [a for a in d.get("agents", []) if not isinstance(a, dict) or a.get("source") == "built-in"] if d.get("type") == "system" and d.get("subtype") == "commands_changed": d["commands"] = keep_commands(d.get("commands", [])) if "commands" in d and "models" in d and "account" in d: # initialize response @@ -189,6 +201,8 @@ def scrub(s, ids, name_map): s = re.sub(r"(?:/private)?/tmp/claude-\d+/", "/tmp/claude-tmp/", s) s = re.sub(r"(?:/private)?/var/folders/[\w+]+/[\w+]+/", "/var/folders/xx/yy/", s) s = s.replace(HOME, "/Users/me").replace(re.sub(r"[^A-Za-z0-9]", "-", HOME) + "-", "-Users-me-") + for h in HOSTNAMES: + s = s.replace(h, "my-mac") s = re.sub(u, "me", s, flags=re.I) s = re.sub(r"/tmp/cc-socks/\d+\.sock", "/tmp/cc-socks/12345.sock", s) s = re.sub(r"[\w.+-]+@[\w-]+\.[A-Za-z][\w.-]*", lambda m: m.group(0) if m.group(0) == "demo@example.invalid" else "user-email", s) diff --git a/docs/research/drivers/claude-stream-json/test_sanitize.py b/docs/research/drivers/claude-stream-json/test_sanitize.py new file mode 100644 index 00000000..2cdb5fbe --- /dev/null +++ b/docs/research/drivers/claude-stream-json/test_sanitize.py @@ -0,0 +1,53 @@ +"""Rules of sanitize.py that a fixture would otherwise leak. Run: python3 -m unittest test_sanitize (in this folder).""" +import unittest + +import sanitize + + +def clean(msg): + ids, sig = sanitize.Ids(), sanitize.Ids() + return sanitize.transform(msg, ids, sig) + + +class Sanitize(unittest.TestCase): + def test_host_name_is_replaced(self): + self.addCleanup(setattr, sanitize, "HOSTNAMES", sanitize.HOSTNAMES) + sanitize.HOSTNAMES = ["Someones-MacBook-Pro.local", "Someones-MacBook-Pro"] + line = '{"serverName":"Someones-MacBook-Pro.local","note":"on Someones-MacBook-Pro"}' + out = sanitize.scrub(line, sanitize.Ids(), None) + self.assertNotIn("Someones", out) + self.assertEqual(out, '{"serverName":"my-mac","note":"on my-mac"}') + + def test_machine_session_start_hook_output_is_removed(self): + msg = {"type": "system", "subtype": "hook_response", "hook_event": "SessionStart", + "output": "PRIVATE RULES", "stdout": "PRIVATE RULES", "stderr": "", "exit_code": 0} + out = clean(msg) + self.assertEqual(out["output"], sanitize.HOOK_GONE) + self.assertEqual(out["stdout"], sanitize.HOOK_GONE) + self.assertEqual(out["stderr"], "") + + def test_scenario_hook_output_is_kept(self): + msg = {"type": "system", "subtype": "hook_response", "hook_event": "PreToolUse", "output": "pre-tool-hook-ran\n"} + self.assertEqual(clean(msg)["output"], "pre-tool-hook-ran\n") + + def test_context_report_lists_no_skill_or_plugin_agent(self): + resp = {"categories": [], "skills": {"totalSkills": 2, "skillFrontmatter": [{"name": "private-skill", "path": "/x"}]}, + "agents": [{"agentType": "acme:helper", "source": "plugin"}, {"agentType": "Explore", "source": "built-in"}], + "mcpTools": []} + out = clean(resp) + self.assertEqual(out["skills"], {"totalSkills": 2, "skillFrontmatter": []}) + self.assertEqual(out["agents"], [{"agentType": "Explore", "source": "built-in"}]) + + def test_init_lists_are_emptied(self): + init = {"type": "system", "subtype": "init", "skills": ["private-skill"], "plugins": [{"name": "p", "path": "/x"}], + "agents": ["general-purpose", "acme:helper"], "slash_commands": ["clear", "private-command"], + "mcp_servers": [{"name": "my-server"}, {"name": "ping-user"}], "tools": ["Bash", "mcp__my-server__x", "mcp__ping-user__ping"]} + out = clean(init) + self.assertEqual((out["skills"], out["plugins"], out["agents"]), ([], [], ["general-purpose"])) + self.assertEqual(out["slash_commands"], ["clear"]) + self.assertEqual(out["mcp_servers"], [{"name": "ping-user"}]) + self.assertEqual(out["tools"], ["Bash", "mcp__ping-user__ping"]) + + +if __name__ == "__main__": + unittest.main() From 6cb8087784a53addfe29235dce0478fac3132bac Mon Sep 17 00:00:00 2001 From: julienwuthrich-ant Date: Mon, 23 Nov 2026 11:55:37 -0800 Subject: [PATCH 021/120] Repository: local settings, env files and Python caches stay out of git These were ignored only by one machine's own exclude files, so a fresh clone could commit them. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/.gitignore b/.gitignore index 5a67d6cd..53da5c53 100644 --- a/.gitignore +++ b/.gitignore @@ -31,6 +31,19 @@ src-tauri/gen/schemas # Tool artifacts .playwright-mcp/ +__pycache__/ +*.pyc + +# Local settings and secrets +.env +.env.* +!.env.example + +# Claude Code's per-machine state (the shared launch.json and skills stay tracked) +.claude/settings.local.json +.claude/worktrees/ +.claude/checkpoints/ +.claude/scheduled_tasks.* # Overrides a global "research/" ignore: these docs and the adapter test fixtures belong in the repo !docs/research/ From e6c062dd55732a65eb36feaa5e77e8e73097888c Mon Sep 17 00:00:00 2001 From: julienwuthrich-ant Date: Mon, 23 Nov 2026 12:00:18 -0800 Subject: [PATCH 022/120] Background work: your own "Send back" gives the worker the whole wait again The wait for what a worker leaves running is one budget per round, and a round began only where the gate sends the work back (a failed check, a file outside the scope, a reviewer's request, a merge conflict). Comments you send back from the diff reach the worker the same way and even hand out new fix rounds, but they kept the old round's budget: after a first round that used the 5 minutes, a test run the worker left open after your comments was stopped at once, and the worker never saw its result. The worker's rules say "each time you hand in your work, it waits up to 5 minutes". send_back_task now starts a round before it sends your comments to a worker that still runs the task, as the gate does. The docs name this caller too. Test: a_round_that_your_send_back_starts_waits_again_for_background_work (the second wait is the whole budget, not what the first one left). Without the call it fails with "stops them after 28 s" in place of 30 s. Co-Authored-By: Claude Fable 5.2 --- .../codly-core/src/orchestrator/background.rs | 32 ++++----- .../codly-core/src/orchestrator/workspace.rs | 3 + .../tests/orchestrator_background.rs | 67 ++++++++++++++++++- docs/ARCHITECTURE.md | 3 +- 4 files changed, 88 insertions(+), 17 deletions(-) diff --git a/crates/codly-core/src/orchestrator/background.rs b/crates/codly-core/src/orchestrator/background.rs index 885fad7d..9fa4b626 100644 --- a/crates/codly-core/src/orchestrator/background.rs +++ b/crates/codly-core/src/orchestrator/background.rs @@ -11,15 +11,15 @@ //! it stopped, and checks the work as it is (`background_wait_over`). //! //! `WAIT` is one budget for a round of the worker, not a time per wait. A round is the work -//! the worker hands in once: it begins with the task's brief, or when the gate sends the work -//! back (a failed check, a file outside the scope, a reviewer's request, a merge conflict: -//! `Inner::background_round`). A turn of the worker inside a round ends the wait of a pass, -//! and the pass at the end of that turn waits again: it gets what is left of the budget. With -//! nothing left Codly stops the open work at once. So a dev server that never ends, beside a -//! test run that ends after 4 minutes and wakes the CLI, is stopped 5 minutes after the first -//! wait began, not 9. The next round has the whole budget again: a test run that the worker -//! leaves open after its fix is waited for, as the worker's rules say (`prompts.rs`). A new -//! run of the task (a retry) has a new budget too. +//! the worker hands in once: it begins with the task's brief, when the gate sends the work +//! back (a failed check, a file outside the scope, a reviewer's request, a merge conflict), +//! or when you send it back from the diff (`Inner::background_round`). A turn of the worker +//! inside a round ends the wait of a pass, and the pass at the end of that turn waits again: +//! it gets what is left of the budget. With nothing left Codly stops the open work at once. +//! So a dev server that never ends, beside a test run that ends after 4 minutes and wakes the +//! CLI, is stopped 5 minutes after the first wait began, not 9. The next round has the whole +//! budget again: a test run that the worker leaves open after its fix is waited for, as the +//! worker's rules say (`prompts.rs`). A new run of the task (a retry) has a new budget too. //! //! What is open comes from the adapters. Claude Code says its whole list at every change //! (`EventKind::BackgroundTasks`, the one record of that work: the agent sheet shows the same @@ -100,10 +100,10 @@ impl Background { self.end_hold(now); } - /// The gate sends the work back to the worker: a new round begins, with the whole budget. - /// A wait that still runs is over (the turn that the gate's message starts would end it), - /// and its time is not the new round's. Work that Codly could not stop stays let go: no - /// round waits for it again. + /// The work goes back to the worker (from the gate, or from you): a new round begins, with + /// the whole budget. A wait that still runs is over (the turn that the message starts + /// would end it), and its time is not the new round's. Work that Codly could not stop + /// stays let go: no round waits for it again. pub(super) fn round_starts(&mut self, now: Instant) { self.end_hold(now); self.waited = Duration::ZERO; @@ -249,8 +249,10 @@ impl Inner { Ok(true) } - /// The gate sends the work back to the worker's live run (`gate.rs`, `back_to_worker`): a - /// new round begins there, with the whole wait for what the worker leaves running. + /// The work goes back to the worker's live run: from the gate (`gate.rs`, `back_to_worker`) + /// or from you (`workspace.rs`, `send_back_task`). A new round begins there, with the whole + /// wait for what the worker leaves running. Call it before the message is sent: the turn + /// that the message starts can end, and its pass can begin a wait, at once. pub(super) fn background_round(&self, worker: &str) { if let Some(l) = lock(&self.live).get_mut(worker) { l.background.round_starts(Instant::now()); diff --git a/crates/codly-core/src/orchestrator/workspace.rs b/crates/codly-core/src/orchestrator/workspace.rs index 9bdc5e9d..326a498d 100644 --- a/crates/codly-core/src/orchestrator/workspace.rs +++ b/crates/codly-core/src/orchestrator/workspace.rs @@ -516,6 +516,9 @@ impl Inner { bail!("a review of {} is starting right now; send your comments again in a moment", t.key); } note(&worker)?; + // A new round, as when the gate sends the work back: what the worker leaves + // running after your comments has the whole wait again (background.rs). + self.background_round(&worker); self.send_prompt(&worker, prompt)?; self.forget_rounds(task_id); // The worker has a turn to come, and its end runs the gate whatever the task diff --git a/crates/codly-core/tests/orchestrator_background.rs b/crates/codly-core/tests/orchestrator_background.rs index 99ecb15d..d931b15d 100644 --- a/crates/codly-core/tests/orchestrator_background.rs +++ b/crates/codly-core/tests/orchestrator_background.rs @@ -13,7 +13,8 @@ //! one question comes after it, when the worker's last turn still gave no report, and the //! record of the stop says which of the two comes next, the question or the checks; //! - the wait is one budget for a round: a turn of the worker in the middle does not start it -//! again, and a round that the gate starts (a failed check) has the whole wait again. +//! again, and a round that the gate starts (a failed check) or that you start ("Send back" +//! from the diff) has the whole wait again. use std::path::{Path, PathBuf}; use std::process::Command; @@ -715,6 +716,70 @@ async fn a_round_that_the_gate_starts_waits_again_for_background_work() { core.shutdown().await; } +/// Your own "Send back" from the diff starts a round too. The first round has used 2 seconds +/// or more of its wait on a dev server when your comments arrive. The worker does what you +/// asked and leaves a test run open: that round waits with the whole budget, not with what the +/// first one left. (With the first round's wait all used up, Codly would stop the test run at +/// once and the worker would never see its result.) +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_round_that_your_send_back_starts_waits_again_for_background_work() { + // Long, so that it cannot run out on a slow build box: the test ends the open work itself. + const BUDGET: Duration = Duration::from_secs(30); + const COMMENTS: &str = "1. `hello.txt:1`\n Say hello twice."; + let dir = tempfile::tempdir().unwrap(); + let cli = Cli::default(); + let both = vec![background("tid-1", "command", "npm run dev"), background("tid-2", "command", "npm test")]; + let state = cli.clone(); + let worker: Behavior = Arc::new(move |turn: FakeTurn| { + let (state, both) = (state.clone(), both.clone()); + Box::pin(async move { + // The first turn: the work, beside a dev server. The turn for your comments: the + // change, beside the server and a test run. + let first = state.lock().unwrap().prompts.len() == 1; + let (content, open) = match first { + true => ("hello\n", both[..1].to_vec()), + false => ("hello\nhello\n", both), + }; + state.lock().unwrap().open = open.clone(); + turn.work(content, listed(open)).await; + }) + }); + let core = start(dir.path(), Provider::Claude, worker, &cli, Some(BUDGET)).await; + + let held = wait_held(&core).await; + tokio::time::sleep(Duration::from_secs(2)).await; + let sent = core.send_back_task(&held.id, COMMENTS).await.unwrap(); + assert_eq!(sent.status, TaskStatus::ChangesRequested); + + // The pass at the end of the worker's next turn waits for both, 30 seconds again: with + // one budget for both rounds it would be 28 seconds or less. + let said = wait_for("the wait of the second round", 40, async || { + let said = background_decisions(&events(&core).await); + (said.len() == 2).then_some(said) + }) + .await; + let waits = |what: &str, it: &str| format!("t1: not checked yet, its worker left {what} running; Codly checks the work when that ends, and stops {it} after 30 s"); + let server = "the background command `npm run dev`"; + assert_eq!(said[0].0, waits(server, "it")); + assert_eq!(said[1].0, waits(&format!("{server}, the background command `npm test`"), "them"), "your comments began a round with the whole wait"); + assert_eq!(said[1].1["wait_secs"], json!(30)); + + // Both end, and Claude Code starts a turn by itself: its end runs the gate. + cli.lock().unwrap().open = vec![]; + emit(&cli, listed(vec![])); + emit(&cli, EventKind::TurnStarted { input: None }); + emit(&cli, EventKind::TurnCompleted { status: TurnStatus::Completed, result_text: Some("The tests pass.".into()), duration_ms: Some(5) }); + wait_plan_done(&core).await; + let after = events(&core).await; + assert_eq!(background_decisions(&after).len(), 2, "no other wait, and no stop"); + assert!(cli.lock().unwrap().stops.is_empty(), "nothing was stopped"); + assert_eq!(verified(&after), [true], "checked once, on the work with your comments in it"); + let prompts = cli.lock().unwrap().prompts.clone(); + assert_eq!(prompts.len(), 2, "the task, and your comments"); + assert!(prompts[1].contains(COMMENTS), "{}", prompts[1]); + core.shutdown().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn a_codex_subagent_that_does_not_end_is_interrupted_when_the_wait_runs_out() { let dir = tempfile::tempdir().unwrap(); diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 383842e0..3ac4b027 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -226,7 +226,8 @@ request), writes in the task's record what it stopped and what it could not stop work as it is. The 5 minutes are one budget each time the worker hands in its work: a turn of the worker in the middle (a test run that ended woke the CLI) does not start them again. They are whole again when Codly sends the work back (a failed check, a file outside the scope, a -reviewer's request, a merge conflict), and for a retry of the task. A worker that ended its turn +reviewer's request, a merge conflict), when you send it back from the diff, and for a retry of +the task. A worker that ended its turn with no report is asked for one only after this wait, and the record of a stop says which comes next: that question, or the checks. For Codex, a subagent that is still in a turn counts; that part is built from the protocol's types and is not verified on a live run. Claude Code says its From 62b8d51f72f535c550df3c1a3b890a838e733893 Mon Sep 17 00:00:00 2001 From: julienwuthrich-ant Date: Mon, 23 Nov 2026 12:05:20 -0800 Subject: [PATCH 023/120] Architecture: the doc says what the code does today, with CI and the approval flow MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Section 9 said the repo has no CI; it now names the Linux and macOS jobs and the release workflow, and says what was recorded without a live run (Claude Code 2.1.311, Codex parts from the 0.166.0 protocol types). Section 3 gains the approval flow as the code runs it. Fixed: the broker bullet said Full access approves changes to an agent's own CLI settings (it asks), the Full access floors and the saved-rule limits now name a plan shown to you and a command that loses work in your checkout, slots are per account, the research count, the store migrations (m2…m6) and the adapter files the code map left out. Co-Authored-By: Claude Opus 5.5 --- docs/ARCHITECTURE.md | 78 ++++++++++++++++++++++++++++++++------------ 1 file changed, 58 insertions(+), 20 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index ef549d09..9aef12dc 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -6,9 +6,12 @@ in isolated git worktrees, with two synchronized views of the same truth: a **Wo (chat, timeline, board, dependency graph, diffs, terminal, inspector) and a **World** (an animated three.js office where every motion is a real event). -Research behind every decision: `docs/research/` (7 reports + `CRITIQUE.md`, the -consolidated decision list) and `docs/research/munder/` (a source-level teardown of -Munder Difflin). Fixtures captured from the real CLIs: `docs/research/fixtures/`. +Research behind every decision: `docs/research/` (8 reports, `CRITIQUE.md`, the +consolidated decision list, and three documents of Claude Code 2.1.311 recordings, +`cli-claude-stream-json-2.1.311*.md`) and `docs/research/munder/` (a source-level teardown of +Munder Difflin). Fixtures captured from the real CLIs: `docs/research/fixtures/` (the Claude Code 2.1.311 +recordings in `fixtures/claude-2.1.311/`, with the scripts that made them in +`docs/research/drivers/claude-stream-json/`). ## 1. Decisions in one table @@ -159,6 +162,24 @@ of activity or usage at each tool call: its row and the UI follow it, the log do Observed (CLI event), Inferred (Codly heuristic), Provided (Codly put it in context, with citations), Model-stated (the model's own words). +**The approval flow.** (1) The CLI asks: Claude Code sends a `can_use_tool` control request, +Codex a JSON-RPC request, an ACP agent `request_permission`. The adapter keeps the provider's +request id, makes a Codly approval id, adds the risks it knows (a sandbox override, a network +host) and emits `ApprovalRequested`. (2) `orchestrator/ingest.rs` stores and broadcasts the +event, so the card exists before anything is decided, and hands it to the broker. (3) The +broker denies at once when the agent's tools are blocked (`controls.rs` `control_deny`); else +it builds the policy context (mode, the trust you gave the agent as `outside.rs` limits it, +worktree, checkout, the Connections of the run) and runs `approvals::evaluate`, then the saved +rules (`approval_rules.rs` `with_saved_rules`). (4) An allow sends `allow_once` to the run, +emits `ApprovalResolved` by "policy" and writes an `approval_policy` decision; an ask writes +only a decision that says why. (5) The UI shows the card from the event (`ApprovalCard.svelte`) +and the shell a native notification (`notify.rs`). (6) Your answer goes through the +`resolve_approval` command to `workspace.rs` `resolve_approval`, which checks that the request +is still open and that the choice was offered, sends it to the run (or marks it expired when +the run is gone) and emits `ApprovalResolved` by "user"; the adapter turns it into the +provider's reply. "Always allow in this repo" saves a rule and answers the waiting requests it +covers. + ## 4. Orchestration ``` @@ -170,7 +191,7 @@ you ─► Lead (read-only agent: Read/Grep/Glob + codly tools) ▼ (you click Run plan, or auto-run) integration branch codly//integration + worktree ▼ - scheduler: deps merged ∧ scope lease free ∧ slots (3 total, 2 per provider) → route + scheduler: deps merged ∧ scope lease free ∧ slots (3 total, 2 per account) → route ▼ worker (worktree, branch codly//) ◄─ prompt = task brief + pointer pack │ + memory pack + dependency notes @@ -319,8 +340,8 @@ not what a script or program then does, so this is a deny-list and not a sandbox agents have an OS sandbox; a tool of an MCP server that is neither Codly's own nor one of the Connections this run was given asks, so a Connection that is off lends its name to no server of the user's own setup or of the repo) and **Full access** -(auto-approve everything, risky commands included, except the hard floors: questions, permission -changes, changes to the agent's own CLI settings, writes by read-only agents and Codly's own data +(auto-approve everything, risky commands included, except the hard floors: questions, a plan +the agent shows you (Claude's plan mode), permission changes, changes to the agent's own CLI settings, writes by read-only agents and Codly's own data dir still ask; and so does a command that can lose work in the user's own checkout: a history rewrite, `git reset --hard`, `git clean`, a force push, `rm -rf` outside the build folders, from an agent hired with Git isolation off or pointed there from a worktree by its `cwd`, a @@ -339,8 +360,9 @@ another CLI gives its request offers no rule and matches none. A rule covers a p the project and a git command that changes the repository (the exact command also covers other network use); deletes, `git push`, `sudo`, a pipe into a shell, secrets, paths outside the worktree (an install for the whole machine too: `npm install -g`), a publish, a change to your own -account or settings (`cargo login`, `npm config set …`) and what cannot be checked always ask, and so do strict mode -and read-only agents. Settings → Safety lists the rules; removing one makes Codly ask again. +account or settings (`cargo login`, `npm config set …`), a command that can lose work in the +user's own checkout, and what cannot be checked always ask, and so do strict mode and +read-only agents. Settings → Safety lists the rules; removing one makes Codly ask again. **Triggers and inbound** (Settings → Triggers / Inbound). `triggers.rs` holds the pure policy and `orchestrator/triggers.rs` the loop: schedules that send a prompt to the Lead on a repeating clock @@ -455,9 +477,9 @@ that are new there are named (the index does not search them). `CLAUDE_CODE_USE_BEDROCK`, `CLAUDE_CODE_USE_VERTEX` and `CLAUDE_CODE_OAUTH_TOKEN` of the login shell in a Claude agent's env (and in the sign-in probes, so the status matches). - Approval broker: rules (path outside worktree, symlinks followed; `rm -rf`, `git push`, - `curl | sh`, `sudo`, `npx`/`uvx` downloads, `printenv` and `.env` reads, changes to an agent's - own CLI settings, git inside a nested repository → ask you, except in Full access, which - approves them), then you. No silent timeouts; choices mirror the provider's. The rules read + `curl | sh`, `sudo`, `npx`/`uvx` downloads, `printenv` and `.env` reads, git inside a nested + repository → ask you, except in Full access, which approves them; changes to an agent's own + CLI settings and to Codly's data dir ask in Full access too), then you. No silent timeouts; choices mirror the provider's. The rules read the command line only: what a test, a script or an interpreter does once it runs is not checked (Codex has an OS sandbox; Claude has one only with `claude_sandbox` on). A Codex agent's command reaches the broker only when Codex asks to leave its sandbox. With `codex_network_access` on, a command that needs @@ -631,7 +653,9 @@ crates/codly-core/src/ the engine: no Tauri dependency model.rs contract: domain + event types (ts-rs → src/lib/gen) env.rs login-shell env, CLI and sign-in detection, scrubbed child envs proc.rs process groups, bounded NDJSON reader, shutdown ladder - adapters/ claude.rs (stream-json + control), codex.rs (app-server), acp.rs, classify.rs; + adapters/ mod.rs (the adapter contract), claude.rs (stream-json + control), codex.rs + (app-server), acp.rs, classify.rs (risk hints), attachments.rs (attached + images reach the model as images), startup.rs (a failed start in plain words); codex/account.rs = questions to a Codex sign-in outside a run (models, usage windows, the user's own MCP servers, compaction); testdata/ = the recorded transcripts that the tests replay @@ -669,7 +693,7 @@ crates/codly-core/src/ the engine: no Tauri dependency wallet.rs lots.rs snapshot.rs the game: coins, plots, office export files activity.rs the work under way now, for the shell (keep awake, quit question) resume.rs after a restart: the question before work goes on, round counts, what stood - store/ SQLite: schema.sql, later migrations (m2…m4), typed queries; backup.rs: a copy + store/ SQLite: schema.sql, later migrations (m2…m6), typed queries; backup.rs: a copy of the database once a day and before a migration (`/backups/`), and the way back from a database that cannot be used (it is moved aside, never deleted; a start with no data moves the copies aside too, as `backups.before-
      + diff --git a/src/home/cards/TaskRow.svelte b/src/home/cards/TaskRow.svelte index cdac8eb5..c5766b97 100644 --- a/src/home/cards/TaskRow.svelte +++ b/src/home/cards/TaskRow.svelte @@ -18,6 +18,7 @@ import Markdown from '../../components/Markdown.svelte'; import Portrait from '../../components/Portrait.svelte'; import Say from '../../components/Say.svelte'; + import { retryTarget } from '../../lib/util/retry'; import StateMark from '../../components/StateMark.svelte'; interface Props { @@ -65,7 +66,8 @@ } }); const lit = $derived(ui.hover.taskId === task.id || (!!agent && ui.hover.agentId === agent.id)); - const retry = $derived(detail && ['blocked', 'failed', 'cancelled'].includes(task.status)); + // The plan room offers it for every stopped task; elsewhere, where the line says "Retry to resume". + const retry = $derived((detail && ['blocked', 'failed', 'cancelled'].includes(task.status)) || !!retryTarget(task)); const queue = $derived(detail && !task.plan_id && task.status === 'pending'); diff --git a/src/lib/util/retry.ts b/src/lib/util/retry.ts new file mode 100644 index 00000000..cd3ad006 --- /dev/null +++ b/src/lib/util/retry.ts @@ -0,0 +1,10 @@ +// "Retry to resume": the words the core (and the demo) put on a task that you stopped, or that +// stopped with its agent. Wherever the UI shows them, a Retry button beside them does what the +// task sheet's Retry does: the task goes back to Ready and its agent resumes it. +import type { Task } from '../gen/Task'; + +/** The task a Retry next to these words resumes, or null: none of them is shown for it. */ +export function retryTarget(task: Pick | null | undefined): string | null { + if (!task || (task.status !== 'blocked' && task.status !== 'failed')) return null; + return /retry to resume/i.test(task.status_reason ?? '') ? task.id : null; +} diff --git a/src/shell/CrewPill.svelte b/src/shell/CrewPill.svelte index 3f12bf23..d231e3d4 100644 --- a/src/shell/CrewPill.svelte +++ b/src/shell/CrewPill.svelte @@ -17,6 +17,7 @@ import Orbit from '../components/Orbit.svelte'; import Portrait from '../components/Portrait.svelte'; import Say from '../components/Say.svelte'; + import RetryButton from '../components/RetryButton.svelte'; import { agentTitle } from '../lib/util/team'; interface Props { @@ -101,6 +102,7 @@ {agent.name}{#if agentTitle(agent)}{agentTitle(agent)}{/if} {#if n}{/if} + {/if}
      @@ -112,6 +114,8 @@ .pill.lead.selected .ln { color: var(--ink-1); } .pill.amber { background: color-mix(in srgb, var(--amber) 16%, var(--glass)); box-shadow: var(--glass-edge), inset 0 0 0 1px color-mix(in srgb, var(--amber) 55%, transparent); } .pill.amber .ln { color: var(--amber-ink); } + /* Above the pill's own hit area: it retries, it does not open the agent. */ + .pill > :global(.retry) { position: relative; z-index: 1; } .hit { position: absolute; inset: 0; border-radius: inherit; z-index: 0; } .hit:focus-visible { outline-offset: 1px; border-radius: var(--r-full); } .face { position: relative; z-index: 1; pointer-events: none; } From 1bbaf0f216ca44ef9ba3ca564ef9f7cf7b544ef5 Mon Sep 17 00:00:00 2001 From: julienwuthrich-ant Date: Mon, 23 Nov 2026 12:12:32 -0800 Subject: [PATCH 030/120] Model dialog: the list is open, Enter switches, failures say why /model opens with every model in view, the current one marked and the field empty and focused; arrows move, Enter switches to the highlighted one. A refused or empty answer shows "Could not switch: " in the dialog. The demo answers set_agent_model as the core does. Co-Authored-By: Claude Opus 5.5 --- src/lib/demo/controls.ts | 14 +++++ src/lib/mock.ts | 2 +- src/lib/util/modelPick.ts | 25 +++++++++ src/overlays/ModelDialog.svelte | 99 ++++++++++++++++++++++++++------- 4 files changed, 119 insertions(+), 21 deletions(-) create mode 100644 src/lib/util/modelPick.ts diff --git a/src/lib/demo/controls.ts b/src/lib/demo/controls.ts index bd77f13c..95afc4c5 100644 --- a/src/lib/demo/controls.ts +++ b/src/lib/demo/controls.ts @@ -152,6 +152,20 @@ export class MockControls { return this.sim.patchAgent(id, { permission_mode: mode }); } + /** A 1:1 agent's model, as the core answers it (`set_agent_model`): only a 1:1 agent, the same + * model is no change, an agent on a task or in a turn refuses (a live Claude session switches + * in place, so it may be mid-turn), otherwise the agent comes back with the new model. */ + setModel(id: string, model: string | null): Agent { + const a = this.sim.agents.get(id); + if (!a) throw new Error('Unknown agent'); + if (a.role !== 'solo') throw new Error("only a 1:1 agent's model can be changed"); + if ((a.model ?? null) === model) return a; + if (a.task_id) throw new Error(`${a.name} is on a task: its model can change when the task is done`); + if (a.provider !== 'claude' && this.sim.actor(id).inTurn) throw new Error(`${a.name} is still working: stop its turn first`); + this.note(id, `${a.name} now runs on ${model ?? 'its CLI’s default model'}`); + return this.sim.patchAgent(id, { model }); + } + /** "Compact now", as in the core: a Codex agent between turns and off a task, a Claude agent * between turns (the demo agent's context shrinks to a quarter). */ compact(id: string): null { diff --git a/src/lib/mock.ts b/src/lib/mock.ts index b936aa84..8b2a6a95 100644 --- a/src/lib/mock.ts +++ b/src/lib/mock.ts @@ -629,7 +629,7 @@ export class MockTransport implements Transport { case 'close_office': return demoCloseOffice(sim, String(a.workspaceId), this.rest()); case 'set_agent_model': - return null; + return this.ctl.setModel(String(a.agentId), (a.model as string | null) ?? null); case 'create_task': return story.createTask(String(a.title), String(a.goal ?? '')); case 'move_task': diff --git a/src/lib/util/modelPick.ts b/src/lib/util/modelPick.ts new file mode 100644 index 00000000..2417033e --- /dev/null +++ b/src/lib/util/modelPick.ts @@ -0,0 +1,25 @@ +// The model dialog's list: it opens with every model in view and the current one marked, and +// what you type narrows it (each word in the model's id or name). A name the CLI does not list +// can still be used: it is the last row. With nothing typed, the first row is the CLI's default, +// and a current model the CLI does not list comes next. +import type { ModelOption } from '../gen/ModelOption'; +import { optionLabel } from './models'; + +/** `id`: what is switched to ('' = the CLI's default model). */ +export type PickRow = { id: string; label: string; current: boolean; typed: boolean }; + +export function pickRows(models: ModelOption[], query: string, current: string): PickRow[] { + const q = query.trim(); + const words = q.toLowerCase().split(/\s+/).filter(Boolean); + const hit = (m: ModelOption) => words.every((w) => m.id.toLowerCase().includes(w) || m.name.toLowerCase().includes(w)); + const rows: PickRow[] = []; + if (!q) rows.push({ id: '', label: 'CLI default', current: current === '', typed: false }); + // A model the catalog does not list (a full name, typed earlier) is still the one it runs on. + if (!q && current && !models.some((m) => m.id === current)) rows.push({ id: current, label: current, current: true, typed: false }); + for (const m of models) if (hit(m)) rows.push({ id: m.id, label: optionLabel(m), current: m.id === current, typed: false }); + if (q && !models.some((m) => m.id === q)) rows.push({ id: q, label: `Use “${q}”`, current: q === current, typed: true }); + return rows; +} + +/** The row highlighted when the list changes: the current model's, else the first. */ +export const firstRow = (rows: PickRow[], typed: boolean): number => (typed ? 0 : Math.max(0, rows.findIndex((r) => r.current))); diff --git a/src/overlays/ModelDialog.svelte b/src/overlays/ModelDialog.svelte index 78081d2f..2ae01cea 100644 --- a/src/overlays/ModelDialog.svelte +++ b/src/overlays/ModelDialog.svelte @@ -1,20 +1,25 @@ {#if agent} -
      + { e.preventDefault(); void submit(); }}>

      {PROVIDER_LABEL[provider]}. {switchNote(store.agentMap.get(agent.id) ?? agent)}

      - +
      + + +
        + {#each rows as r, i (r.id + r.typed)} +
      • (hi = i)} onmousedown={(e) => { e.preventDefault(); choose(r); }}> + {#if r.id === model}{/if} + {r.label} + {#if r.current}current{/if} +
      • + {/each} +
      +
      {#if efforts.length}
      - +
      @@ -92,5 +143,13 @@ .desc { color: var(--ink-2); font-size: var(--t-md); } .field { display: flex; flex-direction: column; gap: 8px; } .muted { color: var(--ink-3); font-weight: var(--w-reg); } + .list { max-height: 216px; overflow-y: auto; padding: 4px; border-radius: var(--r-md); box-shadow: inset 0 0 0 1px var(--line); } + .list li { display: flex; align-items: center; gap: 8px; height: 34px; padding: 0 10px 0 6px; border-radius: var(--r-sm); font-size: var(--t-md); cursor: default; } + .list li.active { background: var(--surface-3); } + .mark { width: 14px; display: grid; place-items: center; color: var(--ink-1); flex-shrink: 0; } + .ml { flex: 1; min-width: 0; } + .picked .ml { font-weight: var(--w-semi); } + .cur { font-size: var(--t-sm); color: var(--ink-3); } + .err { font-size: var(--t-sm); color: var(--bad); } footer { display: flex; justify-content: flex-end; gap: 8px; padding: 0 26px 22px; } From c80dd154224b5ada167cb63ee7958bbf78ba636e Mon Sep 17 00:00:00 2001 From: julienwuthrich-ant Date: Mon, 23 Nov 2026 12:12:32 -0800 Subject: [PATCH 031/120] Confirmations: keyboard first; a Kill says so; closing a busy Lead asks Kill / Keep, Stop / Keep, Let go / Keep and Discard / Keep open on Keep; Esc keeps and the keyboard goes back to the button that asked. After a Kill the thread says "You killed " with the time, and the composer says the agent is stopped and a message starts it again. Closing a request whose Lead is mid-turn asks first. Co-Authored-By: Claude Opus 5.5 --- src/home/spine.ts | 9 ++++-- src/lib/state/closing.ts | 3 ++ src/lib/state/queue.ts | 3 ++ src/lib/state/stops.ts | 15 +++++++++ src/lib/util/confirm.ts | 52 ++++++++++++++++++++++++++++++ src/rooms/changes/DiffsLens.svelte | 6 ++-- src/sheet/AgentControls.svelte | 6 ++-- src/sheet/AgentSheet.svelte | 7 ++-- 8 files changed, 93 insertions(+), 8 deletions(-) create mode 100644 src/lib/util/confirm.ts diff --git a/src/home/spine.ts b/src/home/spine.ts index 87416b84..fc7b8703 100644 --- a/src/home/spine.ts +++ b/src/home/spine.ts @@ -20,7 +20,7 @@ import type { JsonValue } from '../lib/gen/serde_json/JsonValue'; import { store, type AgentMsg, type Outgoing, type Seg, type SubAgent, type Thought } from '../lib/state/store.svelte'; import { groupSame } from '../lib/state/approvalGroups'; import { isSlotNote } from '../lib/state/queue'; -import { stoppedByYou } from '../lib/state/stops'; +import { killedAt, killLine, stoppedByYou } from '../lib/state/stops'; import { isRequestThread } from '../lib/state/ui.svelte'; import { noticeRows, type Note } from './notices'; import { canRetry, messageOf, troublesOf, type TroubleKind } from './outcomes'; @@ -272,12 +272,17 @@ export function buildSpine(thread: string): Item[] { // ── what went wrong, where it happened (added last: a problem never splits a work row) ── const yours = chats.filter((c) => c.author === 'user'); - for (const t of troublesOf(store.events, owner.id, (start) => stoppedByYou(owner.id, start))) + // A turn you killed says so in its own line ("You killed …"): its end is not a trouble. + const kills = killedAt(owner.id); + for (const t of troublesOf(store.events, owner.id, (start) => stoppedByYou(owner.id, start) || kills.some((k) => k >= start))) items.push({ kind: 'trouble', key: `e:${t.eventId}`, ts: t.ts, agentId: owner.id, eventId: t.eventId, what: t.what, reason: t.reason, retry: canRetry(t.what) ? messageOf(t.turn, yours) : null, }); + // ── a Kill of yours: what you did, when ── + for (const at of kills) items.push({ kind: 'system', key: `k:${owner.id}:${at}`, ts: at, text: killLine(owner.name), card: null }); + // ── what its CLI told about the run: one row for a turn, where the newest was told (so // after the work it was told in) ── for (const notes of noticeRows(store.events, owner.id)) diff --git a/src/lib/state/closing.ts b/src/lib/state/closing.ts index 62f6ec03..9f50bf4d 100644 --- a/src/lib/state/closing.ts +++ b/src/lib/state/closing.ts @@ -8,6 +8,7 @@ import type { Plan } from '../gen/Plan'; import { closeRequest } from './actions'; import { loadPullRequest, prKey, prUi } from './pullRequest.svelte'; +import { busy } from './queue'; import { requests, type Request } from './requests.svelte'; import { store } from './store.svelte'; import { toast, toasts } from './toasts.svelte'; @@ -59,6 +60,8 @@ export async function closeQuestion(r: Request): Promise { return holdsText ? { ask: 'Discard this draft?', detail: 'What you wrote in it was not sent: it goes with the tab.', yes: 'Discard' } : null; } if (r.phase === 'running') return { ask: 'Cancel its running plan and close?', detail: 'Its unfinished tasks are cancelled. Nothing is deleted: what is done so far stays on its branch.', yes: 'Close' }; + // Its Lead is in a turn (planning, answering): the close stops it mid-way. + if (busy(r.thread)) return { ask: 'The Lead is working: close and stop it?', detail: 'Its turn stops where it is. Nothing is deleted.', yes: 'Close' }; const finished = store.plans.filter((p) => (p.thread || 'lead') === r.thread && p.status === 'done'); const pr = (planId: string) => prKey({ kind: 'plan', id: planId }); // Their pull requests, from Codly's own record (no network), where nothing read them yet. diff --git a/src/lib/state/queue.ts b/src/lib/state/queue.ts index dd35b250..42fd9a20 100644 --- a/src/lib/state/queue.ts +++ b/src/lib/state/queue.ts @@ -94,6 +94,9 @@ export const busyHint = (name: string, provider: Provider | undefined) => export const waitingHint = (name: string, provider: Provider | undefined) => readsMidTurn(provider) ? `${name} waits for your answer above — it reads your message after that` : `${name} waits for your answer above — your message runs after this turn`; +/** The composer's placeholder in the 1:1 of an agent that is stopped (killed, or not started since Codly opened): a message starts it again, on its conversation. */ +export const stoppedHint = (name: string) => `${name} is stopped — a message starts it again`; + /** When a steer note reaches the agent. */ export const steerHint = (provider: Provider | undefined) => readsMidTurn(provider) ? 'Arrives as context during its current turn, or as its next turn' : 'Arrives as context on its next turn'; diff --git a/src/lib/state/stops.ts b/src/lib/state/stops.ts index be18e997..1a13e996 100644 --- a/src/lib/state/stops.ts +++ b/src/lib/state/stops.ts @@ -38,3 +38,18 @@ export function stopping(agentId: string): boolean { const start = openTurn(agentId); return start != null && !!asked.get(agentId)?.some((s) => s.start === start); } + +/** agent → when you killed it (Kill in its sheet), this session: its conversation says so. */ +const kills = new SvelteMap(); + +/** Remember that you killed the agent now (`at`: the wall clock). Call the result if the core refused. */ +export function noteKill(agentId: string, at: number): () => void { + kills.set(agentId, [...(kills.get(agentId) ?? []), at].slice(-KEPT)); + return () => kills.set(agentId, (kills.get(agentId) ?? []).filter((t) => t !== at)); +} + +/** When you killed the agent, oldest first. */ +export const killedAt = (agentId: string): number[] => kills.get(agentId) ?? []; + +/** The conversation's line for a kill of yours. */ +export const killLine = (name: string): string => `You killed ${name}`; diff --git a/src/lib/util/confirm.ts b/src/lib/util/confirm.ts new file mode 100644 index 00000000..deacb3f0 --- /dev/null +++ b/src/lib/util/confirm.ts @@ -0,0 +1,52 @@ +// What an inline question ("Kill / Keep", "Discard it / Keep") owes the keyboard, the same as the +// request tabs' close question: it opens with the keyboard on the safe button, so Enter keeps; +// Esc anywhere in the question is the safe choice too (and closes no sheet, stops no turn); Enter +// on the other button does what it says. When the question goes, the keyboard goes back to the +// control that asked it (`back`), or to where it was before the question opened. + +/** What a key does in an inline question: 'keep' for the safe choice, null for the default. */ +export function confirmKey(e: Pick): 'keep' | null { + if (e.isComposing || e.repeat) return null; + return e.key === 'Escape' ? 'keep' : null; +} + +export type SafeChoice = { + /** The safe choice: what Keep does. */ + keep: () => void; + /** Where the keyboard goes when the question goes (the control that opened it, shown again). */ + back?: () => HTMLElement | null | undefined; +}; + +/** + * Put on the question's safe button (Keep). It takes the keyboard when it appears; an Esc on any + * button of the question (its parent) keeps. + */ +export function safeChoice(node: HTMLElement, opts: SafeChoice) { + let o = opts; + const prev = document.activeElement instanceof HTMLElement ? document.activeElement : null; + const scope = node.parentElement ?? node; + node.focus(); + const onKey = (e: KeyboardEvent) => { + if (confirmKey(e) !== 'keep') return; + e.preventDefault(); + e.stopPropagation(); + o.keep(); + }; + scope.addEventListener('keydown', onKey); + return { + update(next: SafeChoice) { + o = next; + }, + destroy() { + scope.removeEventListener('keydown', onKey); + // After the update that removed the question: the control that asked it is there again. + queueMicrotask(() => { + const at = document.activeElement; + // Something else took the keyboard meanwhile: it keeps it. + if (at && at !== document.body && at.isConnected) return; + const to = o.back?.() ?? (prev?.isConnected ? prev : null); + to?.focus(); + }); + }, + }; +} diff --git a/src/rooms/changes/DiffsLens.svelte b/src/rooms/changes/DiffsLens.svelte index 97d859b9..3fb56b58 100644 --- a/src/rooms/changes/DiffsLens.svelte +++ b/src/rooms/changes/DiffsLens.svelte @@ -35,6 +35,7 @@ import EmptyState from '../../components/EmptyState.svelte'; import Icon from '../../components/Icon.svelte'; import DiffView from './DiffView.svelte'; + import { safeChoice } from '../../lib/util/confirm'; const allPlans = $derived([...store.plans].filter((p) => p.status !== 'cancelled' && store.tasks.some((t) => t.plan_id === p.id && (t.status === 'done' || t.branch))).sort((a, b) => b.created_at - a.created_at)); const allTasks = $derived([...store.tasks].filter((t) => t.branch || t.status === 'done').sort((a, b) => (a.plan_id ?? '~').localeCompare(b.plan_id ?? '~') || a.key.localeCompare(b.key, undefined, { numeric: true }))); @@ -230,6 +231,7 @@ } /** Discard asks once more, and says where else the comments are (`draft`, read at the first press). */ let discarding = $state<{ draft: ReviewDraft } | null>(null); + let discardBtn: HTMLButtonElement | undefined = $state(); $effect(() => { void comments; discarding = null; @@ -376,9 +378,9 @@

      {comments.length} {comments.length === 1 ? 'comment' : 'comments'} not sent. {discarding ? discardWords(comments.length, discarding.draft) : reviewBarWords(comments.length, toWorker ? workerName : null, waiting ? review.inHand(notesKey) : null)}

      {#if discarding} - + {:else} - + {/if} {/if} diff --git a/src/sheet/AgentControls.svelte b/src/sheet/AgentControls.svelte index bf6c2e64..3c31a1ae 100644 --- a/src/sheet/AgentControls.svelte +++ b/src/sheet/AgentControls.svelte @@ -16,6 +16,7 @@ import { stopAgent } from '../lib/state/actions'; import { PERMISSION_MODES, canCompact, compactAgent, compactHint, compactWait, compactionLine, contextLine, controls, readContext, resumeAgent, setBlockTools, setPermissionMode, steerAgent, stopAfterStep } from '../lib/state/control.svelte'; import { steerHint } from '../lib/state/queue'; + import { safeChoice } from '../lib/util/confirm'; import { store } from '../lib/state/store.svelte'; import { tokens } from '../lib/util/format'; import Icon from '../components/Icon.svelte'; @@ -72,6 +73,7 @@ let note = $state(''); let sending = $state(false); let confirmKill = $state(false); + let killBtn: HTMLButtonElement | undefined = $state(); async function send() { const text = note.trim(); @@ -171,10 +173,10 @@
      Kill {agent.name}? The process ends now; its worktree is kept. - +
      {:else} - + {/if}
      {/if} diff --git a/src/sheet/AgentSheet.svelte b/src/sheet/AgentSheet.svelte index 385c24fb..201b5739 100644 --- a/src/sheet/AgentSheet.svelte +++ b/src/sheet/AgentSheet.svelte @@ -30,6 +30,8 @@ import Portrait from '../components/Portrait.svelte'; import Provenance from '../components/Provenance.svelte'; import Say from '../components/Say.svelte'; + import RetryButton from '../components/RetryButton.svelte'; + import { safeChoice } from '../lib/util/confirm'; import Section from '../components/Section.svelte'; import Why, { type WhyLine } from '../components/Why.svelte'; import UsageBars from '../components/UsageBars.svelte'; @@ -324,20 +326,21 @@
      Stop {agent.name}? The process ends; its worktree is kept. - +
      {/if} {#if confirmLetGo}
      Let {agent.name} go? They leave the office as a ghost by the memory archive, with their career and memory; you can bring them back. - +
      {/if}

      {#if n}{/if}

      +

      {#if !n?.parts.some((p) => p.timer)}{n?.tone === 'live' ? `for ${timer(ui.now - since)}` : `since ${clock(since)}`}{#if agent.worktree}{' · '}{/if}{/if}{#if agent.worktree}{task?.branch ?? tildify(agent.worktree)}{/if}

      From 1d8fb5e12fb6b6c5b6df68907dfb89201ccb6301 Mon Sep 17 00:00:00 2001 From: julienwuthrich-ant Date: Mon, 23 Nov 2026 12:12:40 -0800 Subject: [PATCH 032/120] Palette, shortcuts, Ask me: titles first, a sheet that scrolls, room for the panel The palette ranks title matches before description matches ("merge" no longer offers Go to Knowledge first), offers no "Ask the Lead" in a 1:1, and lists "Start an agent with ". The shortcuts sheet scrolls inside a small window. With Ask me open, the conversation column gives way so the panel covers no composer or tab button. Composer: shift+Tab in a 1:1, the stopped hint, and no stale-assignment warning on /model. Kill records its line; the model switch returns its failure reason. Tests for every rule above. Co-Authored-By: Claude Opus 5.5 --- src/home/Composer.svelte | 12 +- src/lib/__tests__/dailyShortcuts.test.ts | 237 +++++++++++++++++++++++ src/lib/state/actions.ts | 31 ++- src/overlays/Palette.svelte | 26 +-- src/overlays/ShortcutsSheet.svelte | 5 +- src/overlays/palette.ts | 25 +++ src/shell/Shell.svelte | 10 +- 7 files changed, 317 insertions(+), 29 deletions(-) create mode 100644 src/lib/__tests__/dailyShortcuts.test.ts diff --git a/src/home/Composer.svelte b/src/home/Composer.svelte index 299721c6..9f427bca 100644 --- a/src/home/Composer.svelte +++ b/src/home/Composer.svelte @@ -20,7 +20,8 @@ import { sendChat, setRequestPrefs, stopThread, stopThreadByEsc } from '../lib/state/actions'; import { intakeUi } from '../lib/state/intake.svelte'; import { toast } from '../lib/state/toasts.svelte'; - import { busy, busyHint, waitingHint } from '../lib/state/queue'; +import { cyclesMode, nextPermissionMode, setPermissionMode } from '../lib/state/control.svelte'; + import { busy, busyHint, stoppedHint, waitingHint } from '../lib/state/queue'; import { store } from '../lib/state/store.svelte'; import { CLOSED_LIST, isRequestThread, ui } from '../lib/state/ui.svelte'; import { fuzzy } from '../lib/util/fuzzy'; @@ -147,6 +148,7 @@ const placeholder = $derived( waitsForYou ? waitingHint(agent?.name ?? 'The agent', agent?.provider) : isBusy ? busyHint(agent?.name ?? 'The agent', agent?.provider) + : oneToOne && agent?.status === 'offline' ? stoppedHint(agent.name) : oneToOne ? `Message ${agent?.name ?? 'the agent'} directly…` : fresh && thread !== 'lead' ? 'Describe the new request — its own Lead plans it in parallel…' : 'Ask the Lead to build, fix or explain — @ for a file, / for actions', @@ -208,7 +210,7 @@ const model = { name: 'model', label: 'Model', icon: 'sparkle' }; const a = agent; if (!oneToOne) list.push({ ...model, hint: 'The Lead’s CLI, model and thinking', run: () => lead?.showModels() }); - else if (a?.role === 'solo') list.push({ ...model, hint: `${a.name}’s model`, run: () => (ui.modelDialog = { provider: a.provider, agentId: a.id }) }); + else if (a?.role === 'solo') list.push({ ...model, hint: `${a.name}’s model`, run: () => { ui.modelDialog = { provider: a.provider, agentId: a.id }; } }); else list.push({ ...model, off: 'Not for this agent' }); const diff = { name: 'diff', label: 'View the changes', icon: 'diff' }; const p = plan; @@ -373,6 +375,12 @@ setRequestPrefs(thread, { mode: MODES[(MODES.findIndex((m) => m.id === now) + 1) % MODES.length].id }); return; } + // In a 1:1 with a Claude agent it cycles the agent's own mode, as its sheet's select does. + if (e.key === 'Tab' && e.shiftKey && oneToOne && agent && cyclesMode(agent)) { + e.preventDefault(); + if (!e.repeat) void setPermissionMode(agent.id, nextPermissionMode(agent.permission_mode, store.requestPrefs[thread]?.approval_mode ?? store.settings.approval_mode)); + return; + } // ⌫ alone: with a modifier it is another key (⌘⌫ denies), and it never leaves the conversation. if (e.key === 'Backspace' && !text && oneToOne && !e.repeat && !e.metaKey && !e.ctrlKey && !e.altKey && !e.shiftKey) { e.preventDefault(); diff --git a/src/lib/__tests__/dailyShortcuts.test.ts b/src/lib/__tests__/dailyShortcuts.test.ts new file mode 100644 index 00000000..ccbc3169 --- /dev/null +++ b/src/lib/__tests__/dailyShortcuts.test.ts @@ -0,0 +1,237 @@ +// The rules behind the daily shortcuts: ⇧⇥ in a 1:1, Retry where "Retry to resume" shows, the +// model list, the palette's ranking, the keys of an inline question, a Kill's line, a close +// while the Lead works, and the one-step start of an agent. +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { Agent } from '../gen/Agent'; +import type { HireManifest } from '../gen/HireManifest'; +import type { ModelOption } from '../gen/ModelOption'; +import type { Task } from '../gen/Task'; +import { MockTransport } from '../mock'; +import { api } from '../api'; +import { switchAgentModel } from '../state/actions'; +import { offersAsk, rankRows } from '../../overlays/palette'; +import { closeQuestion } from '../state/closing'; +import { cyclesMode, nextPermissionMode, PERMISSION_MODES } from '../state/control.svelte'; +import { quickManifest } from '../state/hireWizard'; +import { SHORTCUTS } from '../state/keys'; +import type { Request } from '../state/requests.svelte'; +import { killedAt, killLine, noteKill } from '../state/stops'; +import { store, type AgentLive } from '../state/store.svelte'; +import { confirmKey } from '../util/confirm'; +import { firstRow, pickRows } from '../util/modelPick'; +import { retryTarget } from '../util/retry'; + +describe('⇧⇥ in a 1:1', () => { + it('cycles the modes of the sheet’s select, in its order, round', () => { + const order = PERMISSION_MODES.map((m) => m.id); + expect(order).toEqual(['ask', 'accept_edits', 'plan']); + expect(nextPermissionMode('ask', 'balanced')).toBe('accept_edits'); + expect(nextPermissionMode('accept_edits', 'balanced')).toBe('plan'); + expect(nextPermissionMode('plan', 'autonomous')).toBe('ask'); + // An agent with no mode set is in "ask for edits". + expect(nextPermissionMode(undefined, 'balanced')).toBe('accept_edits'); + expect(nextPermissionMode(null, 'balanced')).toBe('accept_edits'); + }); + + it('skips "accept edits" under "Ask first", where the core refuses it, so "plan first" stays in reach', () => { + expect(nextPermissionMode('ask', 'strict')).toBe('plan'); + expect(nextPermissionMode('plan', 'strict')).toBe('ask'); + // An agent left in "accept edits" before the permissions changed moves on. + expect(nextPermissionMode('accept_edits', 'strict')).toBe('ask'); + }); + + it('only a 1:1 Claude agent off a task has a mode the key switches', () => { + expect(cyclesMode({ provider: 'claude', role: 'solo', task_id: null })).toBe(true); + expect(cyclesMode({ provider: 'claude', role: 'solo', task_id: 't1' })).toBe(false); + for (const provider of ['codex', 'gemini', 'opencode'] as const) expect(cyclesMode({ provider, role: 'solo', task_id: null })).toBe(false); + expect(cyclesMode({ provider: 'claude', role: 'worker', task_id: null })).toBe(false); + expect(cyclesMode({ provider: 'claude', role: 'lead', task_id: null })).toBe(false); + }); + + it('is in the shortcuts sheet', () => { + const rows = SHORTCUTS.flatMap((g) => g.items); + expect(rows.some(([k, label]) => k === '⇧⇥' && /1:1 with Claude/.test(label) && /accept edits/.test(label))).toBe(true); + }); +}); + +describe('Retry next to “Retry to resume”', () => { + const task = (o: Partial): Pick => ({ id: 't1', status: 'blocked', status_reason: null, ...o }); + + it('targets a stopped or failed task whose reason says the words (core and demo wording)', () => { + expect(retryTarget(task({ status_reason: 'stopped by you; Retry to resume with Ada' }))).toBe('t1'); + expect(retryTarget(task({ status_reason: 'stopped by you; Retry to resume' }))).toBe('t1'); + expect(retryTarget(task({ status_reason: 'Interrupted by you. Retry to resume.' }))).toBe('t1'); + expect(retryTarget(task({ status: 'failed', status_reason: 'interrupted by you; the CLI did not stop, so Codly ended its process; Retry to resume with Bo' }))).toBe('t1'); + }); + + it('offers nothing where the words are not shown', () => { + expect(retryTarget(null)).toBeNull(); + expect(retryTarget(undefined)).toBeNull(); + expect(retryTarget(task({ status_reason: 'waiting for you: which database?' }))).toBeNull(); + expect(retryTarget(task({ status_reason: 'review stopped by you; Retry to re-check' }))).toBeNull(); + // Retried already: the words may linger on a task that is on its way again. + expect(retryTarget(task({ status: 'ready', status_reason: 'stopped by you; Retry to resume' }))).toBeNull(); + expect(retryTarget(task({ status: 'running', status_reason: 'Retry to resume' }))).toBeNull(); + }); +}); + +describe('the model list', () => { + const opt = (id: string, name = id, is_default = false): ModelOption => ({ id, name, is_default, efforts: [], default_effort: null }) as unknown as ModelOption; + const models = [opt('default', 'Default', true), opt('opus', 'Opus'), opt('sonnet', 'Sonnet'), opt('haiku', 'Haiku')]; + + it('opens with every model in view and the current one highlighted', () => { + const rows = pickRows(models, '', 'sonnet'); + expect(rows.map((r) => r.id)).toEqual(['', 'default', 'opus', 'sonnet', 'haiku']); + expect(rows.filter((r) => r.current).map((r) => r.id)).toEqual(['sonnet']); + expect(firstRow(rows, false)).toBe(3); + // A current model the catalog does not list is a row of its own, highlighted. + const own = pickRows(models, '', 'claude-sonnet-5-5'); + expect(own.slice(0, 2).map((r) => [r.id, r.current])).toEqual([['', false], ['claude-sonnet-5-5', true]]); + expect(firstRow(own, false)).toBe(1); + // No model set: the CLI's default row is the current one. + expect(firstRow(pickRows(models, '', ''), false)).toBe(0); + }); + + it('narrows on what you type; a name it does not list is the last row, and ↵ starts on the best match', () => { + const rows = pickRows(models, 'op', 'sonnet'); + expect(rows.map((r) => [r.id, r.typed])).toEqual([['opus', false], ['op', true]]); + expect(firstRow(rows, true)).toBe(0); + expect(pickRows(models, 'opus', 'sonnet').map((r) => r.id)).toEqual(['opus']); // listed: no "Use …" row + expect(pickRows(models, 'claude-opus-4-1', '').map((r) => r.label)).toEqual(['Use “claude-opus-4-1”']); + }); +}); + +describe('the palette', () => { + const row = (id: string, title: string, sub?: string) => ({ id, title, sub }); + + it('a title that matches comes before every row that matches only by its description', () => { + const list = [ + row('go:knowledge', 'Go to Knowledge', 'Memory, merged decisions and the code map'), + row('request:pr', 'From pull request…', 'Its reviews, comments on the code and failing checks go to the Lead'), + row('plan:merge', 'Merge into main: dark mode'), + ]; + expect(rankRows(list, 'merge', [], 12).map((r) => r.id)).toEqual(['plan:merge', 'go:knowledge']); + // A weak title match still beats a strong description match. + const fuzzyTitle = [row('a', 'Read the docs', 'merge them'), row('b', 'Make every row great')]; + expect(rankRows(fuzzyTitle, 'merge', [], 12).map((r) => r.id)).toEqual(['b', 'a']); + }); + + it('within titles, by score, a recent row lifted a little; the hits are the title’s letters', () => { + const list = [row('x', 'Theme: Night'), row('y', 'Theme: Day')]; + expect(rankRows(list, 'theme', ['y'], 12).map((r) => r.id)).toEqual(['y', 'x']); + expect(rankRows(list, 'night', [], 12)[0].hits).toEqual([7, 8, 9, 10, 11]); + expect(rankRows([row('k', 'Go to Knowledge', 'merged')], 'merge', [], 12)[0].hits).toEqual([]); + }); + + it('“Ask the Lead…” is offered for a query on a request, never in a 1:1 or another scope', () => { + expect(offersAsk('fix the bug', null, true)).toBe(true); + expect(offersAsk('fix the bug', '>', true)).toBe(true); + expect(offersAsk('fix the bug', null, false)).toBe(false); + expect(offersAsk('fix the bug', '@', true)).toBe(false); + expect(offersAsk(' ', null, true)).toBe(false); + }); +}); + +describe('an inline question’s keys', () => { + const k = (key: string, o: { isComposing?: boolean; repeat?: boolean } = {}) => ({ key, isComposing: false, repeat: false, ...o }); + it('Esc is the safe choice; Enter and the other keys do what the focused button does', () => { + expect(confirmKey(k('Escape'))).toBe('keep'); + expect(confirmKey(k('Enter'))).toBeNull(); + expect(confirmKey(k(' '))).toBeNull(); + expect(confirmKey(k('Tab'))).toBeNull(); + // An Esc that ends a composition, or a held one, answers nothing. + expect(confirmKey(k('Escape', { isComposing: true }))).toBeNull(); + expect(confirmKey(k('Escape', { repeat: true }))).toBeNull(); + }); +}); + +describe('a Kill of yours', () => { + it('is remembered with its time for the conversation, and forgotten when the core refused it', () => { + const undo = noteKill('k1', 1000); + noteKill('k1', 2000); + expect(killedAt('k1')).toEqual([1000, 2000]); + undo(); + expect(killedAt('k1')).toEqual([2000]); + expect(killedAt('someone-else')).toEqual([]); + expect(killLine('Eli')).toBe('You killed Eli'); + }); +}); + +describe('closing a request whose Lead is mid-turn', () => { + const lead = { id: 'L1', name: 'Lead', role: 'lead', thread: 'lead:a', status: 'thinking', provider: 'claude', archived: false } as unknown as Agent; + const request = (o: Partial = {}): Request => ({ thread: 'lead:a', title: 'Fix A', phase: 'planning', ...o }) as Request; + afterEach(() => { + store.agents = []; + store.live = {}; + }); + + it('asks first, with the inline question’s words', async () => { + store.agents = [lead]; + store.live = { L1: { turns: [{ start: 1, end: null, input: 'plan it' }] } as unknown as AgentLive }; + expect(await closeQuestion(request())).toEqual({ ask: 'The Lead is working: close and stop it?', detail: 'Its turn stops where it is. Nothing is deleted.', yes: 'Close' }); + }); + + it('asks nothing new once its turn is over', async () => { + store.agents = [{ ...lead, status: 'idle' } as Agent]; + store.live = { L1: { turns: [{ start: 1, end: 5, input: 'plan it' }] } as unknown as AgentLive }; + expect(await closeQuestion(request({ phase: 'talking' }))).toBeNull(); + }); +}); + +describe('starting an agent in one step', () => { + beforeEach(() => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date', 'performance'] }); + vi.spyOn(Math, 'random').mockReturnValue(0.5); + vi.stubGlobal('OffscreenCanvas', class { getContext() { return null; } }); + vi.stubGlobal('location', { search: '?ws=1' }); + }); + afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + }); + async function call(t: MockTransport, cmd: string, args: Record = {}): Promise { + const answer = t.call(cmd, args); + answer.catch(() => {}); + await vi.advanceTimersByTimeAsync(200); + return answer; + } + + it('takes the applicant’s name and look, the CLI’s default model, no traits and no brief', () => { + const m = quickManifest('codex', { name: 'Iris', color: 5, avatar: 'fox' }); + expect(m).toMatchObject({ provider: 'codex', name: 'Iris', color: 5, avatar: 'fox', model: null, command: null, traits: [], goal: '', description: '' }); + }); + + it('the demo hires it, and its model switch answers as the core does', async () => { + const t = new MockTransport(); + const snap = t.subscribe(() => {}); + await vi.advanceTimersByTimeAsync(50); + const lead = (await snap).agents.find((x) => x.role === 'lead'); + const [a] = await call<{ name: string; color: number; avatar: string }[]>(t, 'hire_applicants', { n: 1 }); + const agent = await call(t, 'hire_from_manifest', { manifest: quickManifest('claude', a) as HireManifest, confirmShell: false }); + expect(agent).toMatchObject({ name: a.name, role: 'solo', provider: 'claude' }); // the demo gives it the CLI's default model by name + const switched = await call(t, 'set_agent_model', { agentId: agent.id, model: 'opus' }); + expect(switched).toMatchObject({ id: agent.id, model: 'opus' }); + // The same model again is no change, and still answers with the agent: never an empty answer. + expect(await call(t, 'set_agent_model', { agentId: agent.id, model: 'opus' })).toMatchObject({ model: 'opus' }); + if (lead) await expect(call(t, 'set_agent_model', { agentId: lead.id, model: 'opus' })).rejects.toThrow("only a 1:1 agent's model can be changed"); + await expect(call(t, 'set_agent_model', { agentId: 'nobody', model: 'opus' })).rejects.toThrow('Unknown agent'); + }); +}); + +describe('a model switch from the dialog', () => { + const ada = { id: 'a1', name: 'Ada', role: 'solo', provider: 'claude', model: null } as unknown as Agent; + afterEach(() => vi.restoreAllMocks()); + + it('says why it did not happen: the core’s refusal, or an answer with no agent in it', async () => { + vi.spyOn(api, 'setAgentModel').mockRejectedValue(new Error('Ada is still working: stop its turn first')); + expect(await switchAgentModel(ada, 'opus')).toBe('Ada is still working: stop its turn first'); + vi.spyOn(api, 'setAgentModel').mockResolvedValue(null as unknown as Agent); + expect(await switchAgentModel(ada, 'opus')).toBe('Codly got no answer for the switch. Try again.'); + }); + + it('answers nothing when it switched', async () => { + vi.spyOn(api, 'setAgentModel').mockResolvedValue({ ...ada, model: 'opus' } as Agent); + expect(await switchAgentModel(ada, 'opus')).toBeNull(); + }); +}); diff --git a/src/lib/state/actions.ts b/src/lib/state/actions.ts index f496f532..9ecdefac 100644 --- a/src/lib/state/actions.ts +++ b/src/lib/state/actions.ts @@ -34,7 +34,7 @@ import { ESC_STOP_WINDOW, escStop } from './esc'; import { busy } from './queue'; import { requests } from './requests.svelte'; import { review, reviewKey } from './review.svelte'; -import { noteStop, stopping } from './stops'; +import { noteKill, noteStop, stopping } from './stops'; import { store } from './store.svelte'; import { toast, toasts } from './toasts.svelte'; import { ui, wallNow } from './ui.svelte'; @@ -486,13 +486,25 @@ export async function createTask(title: string, goal = '') { * resumes the conversation on the new model with its next message. The core's refusal says * what to do (stop its turn first, wait for its task, pick a model the CLI knows). */ export async function setAgentModel(agent: Agent, model: string | null): Promise { - const label = model ?? 'the default model'; + const why = await switchAgentModel(agent, model); + if (why) toast({ kind: 'error', title: `Couldn’t switch ${agent.name} to ${model ?? 'the default model'}`, body: why }); + return !why; +} + +/** `setAgentModel` for the model dialog, which says the reason itself: null when the agent + * switched, else why not. An answer with no agent in it is a failure too, never a silent one. */ +export async function switchAgentModel(agent: Agent, model: string | null): Promise { const ws = store.workspace?.id; - const a = await attempt(`switch ${agent.name} to ${label}`, () => api.setAgentModel(agent.id, model)); - if (!a) return false; + let a: Agent | null; + try { + a = await api.setAgentModel(agent.id, model); + } catch (e) { + return msg(e); + } + if (!a) return 'Codly got no answer for the switch. Try again.'; if (store.isOpen(ws)) store.upsertAgent(a); - toast({ kind: 'success', title: `${a.name} switched`, body: `${PROVIDER_LABEL[a.provider]} · ${label}` }); - return true; + toast({ kind: 'success', title: `${a.name} switched`, body: `${PROVIDER_LABEL[a.provider]} · ${model ?? 'the default model'}` }); + return null; } /** Give an agent another model (a new Legend's bigger context window; you clicked it): a 1:1 @@ -567,13 +579,18 @@ export function stopThreadByEsc(thread: string): boolean { return true; } +/** Kill: the process ends now. The agent's conversation says that you killed it. */ export async function stopAgent(agentId: string) { const undo = noteStop(agentId); + const unkill = noteKill(agentId, wallNow()); const ok = await attempt('stop the agent', async () => { await api.stopAgent(agentId); return true; }); - if (!ok) undo(); + if (!ok) { + undo(); + unkill(); + } } /** Let go an agent you hired: it joins the ghosts by the memory archive (you can bring it back). */ diff --git a/src/overlays/Palette.svelte b/src/overlays/Palette.svelte index d3eb1eac..02eca269 100644 --- a/src/overlays/Palette.svelte +++ b/src/overlays/Palette.svelte @@ -18,9 +18,9 @@ import { store } from '../lib/state/store.svelte'; import { toast } from '../lib/state/toasts.svelte'; import { narrate } from '../lib/state/narration'; - import { ROOMS, ui } from '../lib/state/ui.svelte'; + import { ROOMS, isRequestThread, ui } from '../lib/state/ui.svelte'; import { article } from '../lib/util/format'; - import { fuzzy, highlight } from '../lib/util/fuzzy'; + import { highlight } from '../lib/util/fuzzy'; import { PROVIDER_LABEL, TASK_STATUS_LABEL, taskState } from '../lib/util/labels'; import { modal } from '../lib/util/modal'; import type { Tone } from '../lib/narrate'; @@ -31,7 +31,8 @@ import StateMark from '../components/StateMark.svelte'; import { skillsUi } from '../lib/state/skills.svelte'; import { intakeUi } from '../lib/state/intake.svelte'; - import { bySection, press, wants } from './palette'; + import { quickStart } from '../lib/state/hireWizard'; + import { bySection, offersAsk, press, rankRows, wants } from './palette'; type Scope = '>' | '@' | '#' | '/' | '+' | null; type Row = { @@ -143,7 +144,10 @@ } for (const c of store.clis) if (c.path && !c.problem) - rows.push({ id: `hire:${c.provider}`, section: 'Agents', title: `Start ${article(PROVIDER_LABEL[c.provider as Provider])} ${PROVIDER_LABEL[c.provider as Provider]} agent (1:1)`, icon: 'user-plus', run: () => (ui.modelDialog = { provider: c.provider as Provider, agentId: null }) }); + rows.push( + { id: `quick:${c.provider}`, section: 'Agents', title: `Start an agent with ${PROVIDER_LABEL[c.provider as Provider]}`, sub: 'One step: its default look, name and model, then talk to it 1:1', icon: 'user-plus', run: () => void quickStart(c.provider as Provider) }, + { id: `hire:${c.provider}`, section: 'Agents', title: `Start ${article(PROVIDER_LABEL[c.provider as Provider])} ${PROVIDER_LABEL[c.provider as Provider]} agent (1:1)…`, sub: 'Choose its name, look, model and brief', icon: 'user-plus', run: () => { ui.modelDialog = { provider: c.provider as Provider, agentId: null }; } }, + ); for (const a of store.agents) if (narrate(a.id)?.tone === 'live') rows.push({ id: `int:${a.id}`, section: 'Agents', title: `Interrupt ${a.name}`, icon: 'pause', run: () => interruptAgent(a.id) }); return rows; @@ -217,17 +221,7 @@ // Ranked by score, then grouped: a section's header shows once, the best match stays first. const rank = (list: Row[], limit = 50): Scored[] => { if (!q) return bySection(list.slice(0, limit).map((r) => ({ ...r, hits: [] }))); - return bySection( - list - .map((r) => { - const sub = r.sub ? fuzzy(q, r.sub) : null; - return { r, m: fuzzy(q, r.title) ?? (sub ? { score: sub.score / 3, hits: [] as number[] } : null) }; - }) - .filter((x) => x.m) - .sort((a, b) => b.m!.score - a.m!.score + (recents.indexOf(b.r.id) >= 0 ? 2 : 0) - (recents.indexOf(a.r.id) >= 0 ? 2 : 0)) - .slice(0, limit) - .map((x) => ({ ...x.r, hits: x.m!.hits })), - ); + return bySection(rankRows(list, q, recents, limit)); }; if (scope === '>') return rank(commands); if (scope === '@') return rank(agentRows); @@ -260,7 +254,7 @@ const withAsk = $derived.by((): Scored[] => { const q = query.trim(); - if (!q || (scope && scope !== '>')) return rows; + if (!offersAsk(q, scope, isRequestThread(ui.thread))) return rows; return [ ...rows, { diff --git a/src/overlays/ShortcutsSheet.svelte b/src/overlays/ShortcutsSheet.svelte index f09084bb..fd8d8496 100644 --- a/src/overlays/ShortcutsSheet.svelte +++ b/src/overlays/ShortcutsSheet.svelte @@ -14,7 +14,7 @@ } - +
      {#each SHORTCUTS as g (g.group)}
      @@ -30,7 +30,8 @@
      diff --git a/src/lib/__tests__/notify.test.ts b/src/lib/__tests__/notify.test.ts index 418705a2..cadf0b00 100644 --- a/src/lib/__tests__/notify.test.ts +++ b/src/lib/__tests__/notify.test.ts @@ -46,6 +46,7 @@ describe('the words of a toast that points at a request', () => { expect(asks({ kind: 'tool', name: 'WebFetch', input: {} }, 'claude')).toBe('Wants to use WebFetch'); expect(asks({ kind: 'file_change', paths: ['README.md'], diff: null }, 'codex')).toBe('Wants to change README.md'); expect(asks({ kind: 'permissions', detail: {} }, 'codex')).toBe('Wants to get more permissions'); + expect(asks({ kind: 'permissions' as const, detail: { cwd: '/Users/someone/Code/acme', reason: null, permissions: { network: null, fileSystem: { read: null, write: ['/Users/someone/Code/acme-docs'] } } } }, 'codex')).toBe('Wants to write in ../acme-docs'); expect(asks({ kind: 'command', command: 'pnpm test', cwd: null }, 'claude')).toBe('pnpm test'); expect([asksTitle('Eli', { kind: 'question', questions: [] }, 'claude'), asks({ kind: 'question', questions: [] }, 'claude')]).toEqual(['Eli has a question', 'Answer it in the conversation']); }); diff --git a/src/lib/__tests__/questionKeyRegistry.test.ts b/src/lib/__tests__/questionKeyRegistry.test.ts new file mode 100644 index 00000000..65fc3e19 --- /dev/null +++ b/src/lib/__tests__/questionKeyRegistry.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from 'vitest'; +import { questionKeysOf, registerQuestionKeys, type QuestionKeys } from '../state/keys'; + +const keys = (): QuestionKeys => ({ options: () => 2, pick: () => {}, send: () => {} }); + +describe('the keys of a question card', () => { + it('go to the card shown last, and back to the first when it goes', () => { + const inThread = keys(); + const inSheet = keys(); + const offThread = registerQuestionKeys('ap-1', inThread); + const offSheet = registerQuestionKeys('ap-1', inSheet); + expect(questionKeysOf('ap-1')).toBe(inSheet); + offSheet(); + expect(questionKeysOf('ap-1')).toBe(inThread); + offThread(); + expect(questionKeysOf('ap-1')).toBeNull(); + }); + + it('belong to their own request only', () => { + const off = registerQuestionKeys('ap-2', keys()); + expect(questionKeysOf('ap-3')).toBeNull(); + off(); + }); +}); diff --git a/src/lib/narrate.ts b/src/lib/narrate.ts index c15c4d61..cb78e7d3 100644 --- a/src/lib/narrate.ts +++ b/src/lib/narrate.ts @@ -15,6 +15,8 @@ import type { AgentLive, RateWindow, Seg } from './state/store.svelte'; import type { DiffStat } from './state/diffstats.svelte'; import { timer } from './util/format'; import { isPlanCall, PLAN_ASK, planStep, showsPlan } from './util/planRequest'; +import { firstQuestion } from './util/outcome'; +import { permissionsAsked } from './util/permissionsAsked'; import { sandboxHost } from './util/sandbox'; import { basename, oneLine, truncate } from './util/sanitize'; @@ -147,11 +149,11 @@ function approvalParts(ap: Approval, provider: Provider): Part[] { const raw = s.questions as unknown; const list = Array.isArray(raw) ? raw : raw && typeof raw === 'object' ? ((raw as { questions?: unknown[] }).questions ?? []) : []; const q = list[0] as { question?: string; header?: string } | undefined; - const text = q?.question ?? q?.header ?? 'a question'; + const text = q?.question ?? q?.header ?? firstQuestion(ap) ?? 'a question'; return [txt(`Asking you: ${oneLine(text, 64)}`)]; } - default: - return [txt('Waiting for you: permissions')]; + case 'permissions': + return [txt(`Waiting for you: ${oneLine(permissionsAsked(s.detail).wants, 56)}`)]; } } diff --git a/src/lib/state/actions.ts b/src/lib/state/actions.ts index f496f532..63070ebb 100644 --- a/src/lib/state/actions.ts +++ b/src/lib/state/actions.ts @@ -26,7 +26,7 @@ import { followUpRequest, reviewMessage, type ReviewDraft } from '../util/review import { answerText } from '../util/outcome'; import { draftSlot, loadDraft, saveDraft, withoutSeed, type Att } from '../../home/drafts'; import { accounts } from './accounts.svelte'; -import { yourAnswers } from './answers'; +import { yourAnswers, yourChoice } from './answers'; import { diffstats } from './diffstats.svelte'; import { fileList, loadMergeState, resolveMergeConflict } from './mergeState.svelte'; import { flushClosing } from './closing'; @@ -340,6 +340,7 @@ export async function resolveApproval(approvalId: string, choice: ApprovalChoice // The core keeps no copy of an answer: the closed card and the history show it from here. const said = sent ? answerText(answers) : null; if (said) yourAnswers.set(approvalId, said); + if (sent) yourChoice.set(approvalId, choice); } /** One answer for the requests that share a card: the same command asked by several agents. */ diff --git a/src/lib/state/answers.ts b/src/lib/state/answers.ts index 987ef813..17d33d55 100644 --- a/src/lib/state/answers.ts +++ b/src/lib/state/answers.ts @@ -2,5 +2,11 @@ // agent's CLI and records only that the question was answered, so the words are known for the // questions answered in this window: an older one reads "Answered by you" without them. import { SvelteMap } from 'svelte/reactivity'; +import type { ApprovalChoice } from '../gen/ApprovalChoice'; export const yourAnswers = new SvelteMap(); + +/** How you allowed a request, by approval id, for the requests allowed in this window: the closed + * row says "for this session" (and "for this turn" for a permissions request). The core keeps + * only that it was approved. */ +export const yourChoice = new SvelteMap(); diff --git a/src/lib/state/keys.ts b/src/lib/state/keys.ts index 8ef2431e..76ac978a 100644 --- a/src/lib/state/keys.ts +++ b/src/lib/state/keys.ts @@ -1,12 +1,13 @@ // Global keyboard map. ⌘K palette · ⌘F find in the conversation · ⌘1 full office · ⌘2 full work · ⌘. focus · ⌘, settings · // ⌘N new request · ⌘[ / ⌘] previous / next request · ⇧⌘N new task · ⌘O open repo · ⌘↵ the one // primary action (approve / run plan) · ⌥⌘↵ allow for the session · ⌘⌫ deny · ⇧⌘⌫ deny with a -// note (both also from the empty composer) · G-sequences to rooms · J/K lists · Esc (close, +// note (both also from the empty composer) · 1-9 pick an option of the question that waits · G-sequences to rooms · J/K lists · Esc (close, // deselect, then stop the running turn: the first press asks, the second stops) · ?. // ponytail: hand-rolled instead of tinykeys — one listener, sequences included. import type { Approval } from '../gen/Approval'; import { openWorkspace, resolveApprovals, runPlan, stopThreadByEsc } from './actions'; import { twinsIn } from './approvalGroups'; +import { digitPick, isTextField } from '../util/questionKeys'; import { denyKeyInField, escStep } from './esc'; import { requests } from './requests.svelte'; import { store } from './store.svelte'; @@ -40,11 +41,11 @@ function inThread(a: Approval): boolean { return isRequestThread(ui.thread) ? store.approvalThread(a) === ui.thread : `agent:${a.agent_id}` === ui.thread; } -/** The approval the keyboard acts on: the oldest pending one you can see in full. */ +/** The request the keyboard acts on: the oldest pending one you can see in full. A question + * is one too: ⌘↵ sends its answer and its digits pick (`registerQuestionKeys`). */ export function keyTargetApproval(): Approval | null { const sheetAgent = ui.selectedAgentId; const pending = store.pendingApprovals - .filter((a) => a.subject.kind !== 'question') .filter((a) => inThread(a) || a.agent_id === sheetAgent) .sort((a, b) => a.created_at - b.created_at); return pending[0] ?? null; @@ -79,6 +80,21 @@ export function keyTargetChanges(): DiffTarget { return p && shows ? { kind: 'plan', id: p.id } : null; } +/** What a question card does with the keys: the card knows what you picked and typed. */ +export type QuestionKeys = { options: () => number; pick: (n: number) => void; send: () => void }; +const questionKeys = new Map(); + +/** A question card takes its keys while it shows; the card shown last wins (the sheet over the conversation). `questionKeysOf` reads them. */ +export function registerQuestionKeys(approvalId: string, k: QuestionKeys): () => void { + questionKeys.set(approvalId, [...(questionKeys.get(approvalId) ?? []), k]); + return () => { + const left = (questionKeys.get(approvalId) ?? []).filter((x) => x !== k); + if (left.length) questionKeys.set(approvalId, left); + else questionKeys.delete(approvalId); + }; +} +export const questionKeysOf = (id: string) => questionKeys.get(id)?.at(-1) ?? null; + const workspaceOpen = () => !!store.workspace; export function installKeys(): () => void { @@ -96,6 +112,14 @@ export function installKeys(): () => void { // A held key acts once: its repeats would answer the next approval, then run the plan. if (mod && e.key === 'Enter' && !e.repeat && !overlay && (!typing || !!(e.target as HTMLElement).closest?.('[aria-label="Composer"]'))) { const ap = keyTargetApproval(); + if (ap?.subject.kind === 'question') { + const q = questionKeysOf(ap.id); + if (q && !e.altKey && !e.shiftKey) { + e.preventDefault(); + q.send(); + } + return; + } if (e.altKey) { if (ap && ap.choices.includes('allow_session')) { e.preventDefault(); @@ -212,6 +236,18 @@ export function installKeys(): () => void { return; } + // ── the options of the question that waits: on a radio or a checkbox too (it is no text field) ── + if (!overlay && /^[1-9]$/.test(e.key)) { + const ap = keyTargetApproval(); + const q = ap?.subject.kind === 'question' ? questionKeysOf(ap.id) : null; + const n = q ? digitPick({ key: e.key, mod, alt: e.altKey, shift: e.shiftKey }, isTextField(e.target as Element | null), q.options()) : null; + if (q && n !== null) { + e.preventDefault(); + q.pick(n); + return; + } + } + if (typing || mod || e.altKey || overlay) return; // ── G-sequences ── @@ -289,10 +325,11 @@ export const SHORTCUTS: { group: string; items: [string, string][] }[] = [ ['@', 'Talk to one agent · mention a file'], ['#', 'Mention a task'], ['/', 'Actions: new request, stop, mode, model…'], - ['⌘↵', 'Approve once · run the plan'], + ['⌘↵', 'Approve once · send the answer · run the plan'], ['⌥⌘↵', 'Allow for this session'], ['⌘⌫', 'Deny'], ['⇧⌘⌫', 'Deny with a note'], + ['1 … 9', 'Pick an option of the question that waits'], ['J K', 'Next · previous'], ['[ ]', 'Previous · next file (Changes)'], ], diff --git a/src/lib/util/__tests__/outcome.test.ts b/src/lib/util/__tests__/outcome.test.ts index eef02d74..9d9facf2 100644 --- a/src/lib/util/__tests__/outcome.test.ts +++ b/src/lib/util/__tests__/outcome.test.ts @@ -7,6 +7,7 @@ const question = { subject: { kind: 'question', questions: { questions: [{ question: 'Keep the localStorage fallback?', header: 'Fallback', options: [{ label: 'Keep it' }, { label: 'Drop it' }] }] } }, } satisfies Pick; +const PERMS = { kind: 'permissions' as const, detail: { cwd: '/Users/someone/Code/acme', reason: null, permissions: { network: null, fileSystem: { read: null, write: ['/Users/someone/Code/acme-docs'] } } } }; const plan = { subject: { kind: 'tool', name: 'ExitPlanMode', input: { plan: '1. Add the line' } } } satisfies Pick; describe('how a settled request reads', () => { @@ -47,6 +48,18 @@ describe('an agent’s history', () => { expect(askedLine(plan)).toBe('Asked for approval'); }); + it('a permissions request says what it asked for; one Codly cannot read says so', () => { + expect(askedLine({ subject: PERMS })).toBe('Asked to write in ../acme-docs'); + expect(askedLine({ subject: { kind: 'permissions', detail: {} } })).toBe('Asked for more permissions'); + }); + + it('a question in its request’s envelope (an MCP elicitation) is its message', () => { + const elicit = { subject: { kind: 'question', questions: { serverName: 'linear', mode: 'form', message: 'Which team gets the issue?', requestedSchema: {} } } } satisfies Pick; + expect(firstQuestion(elicit)).toBe('Which team gets the issue?'); + expect(askedLine(elicit)).toBe('Asked you: Which team gets the issue?'); + expect(firstQuestion({ subject: { kind: 'question', questions: { serverName: 'linear', message: ' ' } } })).toBeNull(); + }); + it('an answered question reads "Answered by you" with the answer, never "Approval approved"', () => { expect(settledLine('approved', 'user', question, 'Keep it')).toBe('Answered by you: Keep it'); // Answered before this window opened: the core keeps no copy of the answer. diff --git a/src/lib/util/__tests__/permissionsAsked.test.ts b/src/lib/util/__tests__/permissionsAsked.test.ts new file mode 100644 index 00000000..111db8ef --- /dev/null +++ b/src/lib/util/__tests__/permissionsAsked.test.ts @@ -0,0 +1,111 @@ +import { describe, expect, it } from 'vitest'; +import { lineText, permissionsAsked, placeOf, within } from '../permissionsAsked'; + +const CWD = '/Users/someone/Code/acme'; +// The shape of `PermissionsRequestApprovalParams` (Codex app-server protocol, generated types). +const req = (permissions: unknown, cwd: string | null = CWD) => ({ + threadId: 't', turnId: 'u', itemId: 'i', environmentId: null, startedAtMs: 1, cwd, reason: 'r', permissions, +}); + +describe('placeOf', () => { + it('reads a near path relative to where the agent works', () => { + expect(placeOf('/Users/someone/Code/acme-docs', CWD)).toBe('../acme-docs'); + expect(placeOf('/Users/someone/Code/acme/docs', CWD)).toBe('docs'); + expect(placeOf('/Users/someone/Code/acme', CWD)).toBe('.'); + expect(placeOf('/Users/someone/x/y', CWD)).toBe('../../x/y'); + }); + it('gives a far path whole, with ~ for the home folder', () => { + expect(placeOf('/Users/someone/elsewhere/deep/z', '/Users/someone/Code/acme/.codly/worktrees/kit')).toBe('~/elsewhere/deep/z'); + expect(placeOf('/etc/hosts', CWD)).toBe('/etc/hosts'); + expect(placeOf('/Users/someone/a', null)).toBe('~/a'); + }); + it('keeps a relative path as it is', () => { + expect(placeOf('build/out', CWD)).toBe('build/out'); + }); +}); + +describe('within', () => { + it('is true for the folder and below it, not for a sibling with the same start', () => { + expect(within('/a/b', '/a/b')).toBe(true); + expect(within('/a/b/c', '/a/b/')).toBe(true); + expect(within('/a/bc', '/a/b')).toBe(false); + }); +}); + +describe('permissionsAsked', () => { + it('says the folder it wants to write in, outside where it works', () => { + const a = permissionsAsked(req({ network: null, fileSystem: { read: null, write: ['/Users/someone/Code/acme-docs'] } })); + expect(a.wants).toBe('write in ../acme-docs'); + expect(a.lines).toEqual([{ verb: 'Write in', place: '../acme-docs', outside: true }]); + expect(a.known).toBe(true); + expect(a.cwd).toBe(CWD); + }); + + it('says a read, and a path inside the folder is not outside', () => { + const a = permissionsAsked(req({ network: null, fileSystem: { read: [`${CWD}/vendor`], write: null } })); + expect(a.wants).toBe('read vendor'); + expect(a.lines[0].outside).toBe(false); + }); + + it('says the network', () => { + expect(permissionsAsked(req({ network: { enabled: true }, fileSystem: null })).wants).toBe('use the network'); + // enabled false or null asks for nothing + expect(permissionsAsked(req({ network: { enabled: false }, fileSystem: null })).wants).toBe('get more permissions'); + }); + + it('joins several asks, and counts several places', () => { + const a = permissionsAsked(req({ network: { enabled: true }, fileSystem: { read: ['/opt/a', '/opt/b'], write: ['/Users/someone/Code/acme-docs'] } })); + expect(a.wants).toBe('write in ../acme-docs, read 2 places and use the network'); + expect(a.lines.map(lineText)).toEqual(['Write in ../acme-docs', 'Read /opt/a', 'Read /opt/b', 'Use the network']); + }); + + it('reads the entries form, without listing a path twice when the older lists name it too', () => { + const a = permissionsAsked(req({ + network: null, + fileSystem: { + read: null, write: ['/Users/someone/Code/acme-docs'], + entries: [ + { path: { type: 'path', path: '/Users/someone/Code/acme-docs' }, access: 'write' }, + { path: { type: 'glob_pattern', pattern: '**/*.lock' }, access: 'read' }, + { path: { type: 'special', value: { kind: 'tmpdir' } }, access: 'write' }, + { path: { type: 'special', value: { kind: 'project_roots', subpath: 'docs' } }, access: 'read' }, + { path: { type: 'path', path: `${CWD}/.env` }, access: 'deny' }, + ], + }, + })); + expect(a.lines.map(lineText)).toEqual([ + 'Write in ../acme-docs', + 'Read the files that match **/*.lock', + 'Write in the temporary folder', + 'Read docs in the project folders', + 'Keep out of .env', + ]); + expect(a.wants).toBe('write in 2 places and read 2 places'); + expect(a.known).toBe(true); + }); + + it('marks a shape it cannot read as not known, and keeps what it could read', () => { + const a = permissionsAsked(req({ network: null, fileSystem: { read: null, write: ['/x'], entries: [{ path: { type: 'new_kind' }, access: 'write' }] } })); + expect(a.lines.map(lineText)).toEqual(['Write in /x']); + expect(a.known).toBe(false); + }); + + it('says only "get more permissions" for an unknown or empty shape', () => { + for (const d of [null, 'text', 42, {}, { permissions: 'all' }, { cwd: CWD, permissions: { sandbox: 'off' } }]) { + const a = permissionsAsked(d); + expect(a.wants).toBe('get more permissions'); + expect(a.lines).toEqual([]); + expect(a.known).toBe(false); + } + const empty = permissionsAsked(req({ network: null, fileSystem: null })); + expect(empty.wants).toBe('get more permissions'); + expect(empty.known).toBe(true); + }); + + it('cuts a long path in the headline, not in its line', () => { + const long = `/opt/${'x'.repeat(100)}`; + const a = permissionsAsked(req({ network: null, fileSystem: { read: null, write: [long] } })); + expect(a.wants.length).toBeLessThan(80); + expect(a.lines[0].place).toBe(long); + }); +}); diff --git a/src/lib/util/__tests__/planRequest.test.ts b/src/lib/util/__tests__/planRequest.test.ts index 8fd863e7..34b087ae 100644 --- a/src/lib/util/__tests__/planRequest.test.ts +++ b/src/lib/util/__tests__/planRequest.test.ts @@ -77,6 +77,7 @@ describe('what a request asks for, in words', () => { expect(wantsTo(host, 'codex')).toBe('use SandboxNetworkAccess'); expect(wantsTo({ kind: 'question', questions: [] }, 'claude')).toBe('ask you a question'); expect(wantsTo({ kind: 'permissions', detail: {} }, 'claude')).toBe('get more permissions'); + expect(wantsTo({ kind: 'permissions' as const, detail: { cwd: '/Users/someone/Code/acme', reason: null, permissions: { network: null, fileSystem: { read: null, write: ['/Users/someone/Code/acme-docs'] } } } }, 'codex')).toBe('write in ../acme-docs'); }); it('one short line cuts a long command', () => { diff --git a/src/lib/util/__tests__/questionKeys.test.ts b/src/lib/util/__tests__/questionKeys.test.ts new file mode 100644 index 00000000..556f239d --- /dev/null +++ b/src/lib/util/__tests__/questionKeys.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it } from 'vitest'; +import { digitPick, digitQuestion, isTextField, sendsFromField } from '../questionKeys'; + +const press = (key: string, o: Partial<{ mod: boolean; alt: boolean; shift: boolean }> = {}) => ({ key, mod: false, alt: false, shift: false, ...o }); + +describe('digitPick', () => { + it('picks options 1 to 9 by their place', () => { + expect(digitPick(press('1'), false, 3)).toBe(0); + expect(digitPick(press('3'), false, 3)).toBe(2); + expect(digitPick(press('9'), false, 9)).toBe(8); + }); + it('does nothing for a digit past the last option, 0, or another key', () => { + expect(digitPick(press('4'), false, 3)).toBeNull(); + expect(digitPick(press('0'), false, 3)).toBeNull(); + expect(digitPick(press('a'), false, 3)).toBeNull(); + expect(digitPick(press('Enter'), false, 3)).toBeNull(); + }); + it('leaves a digit with a modifier to the other shortcuts (⌘1 is the office)', () => { + expect(digitPick(press('1', { mod: true }), false, 3)).toBeNull(); + expect(digitPick(press('1', { alt: true }), false, 3)).toBeNull(); + }); + it('leaves a digit typed in a text field to that field', () => { + expect(digitPick(press('1'), true, 3)).toBeNull(); + }); +}); + +describe('sendsFromField', () => { + it('sends on ↵ and ⌘↵, not on ⇧↵ (a new line) or while an IME composes', () => { + expect(sendsFromField(press('Enter'))).toBe(true); + expect(sendsFromField(press('Enter', { mod: true }))).toBe(true); + expect(sendsFromField(press('Enter', { shift: true }))).toBe(false); + expect(sendsFromField({ ...press('Enter'), composing: true })).toBe(false); + expect(sendsFromField(press('a'))).toBe(false); + }); +}); + +describe('digitQuestion', () => { + it('is the first question with options and no answer yet', () => { + expect(digitQuestion([{ options: 2, answered: true }, { options: 0, answered: false }, { options: 3, answered: false }])).toBe(2); + }); + it('is the last question with options once all have an answer', () => { + expect(digitQuestion([{ options: 2, answered: true }, { options: 3, answered: true }, { options: 0, answered: false }])).toBe(1); + }); + it('is -1 when no question has options', () => { + expect(digitQuestion([{ options: 0, answered: false }])).toBe(-1); + expect(digitQuestion([])).toBe(-1); + }); +}); + +describe('isTextField', () => { + // The fields the rule reads, as an element has them (there is no DOM in these tests). + const el = (tagName: string, o: { type?: string; editable?: boolean; inTerminal?: boolean } = {}) => + ({ tagName, type: o.type ?? 'text', isContentEditable: !!o.editable, closest: (s: string) => (s === '.xterm' && o.inTerminal ? {} : null) }) as unknown as Element; + it('is true where keys write text', () => { + expect(isTextField(el('TEXTAREA'))).toBe(true); + expect(isTextField(el('INPUT'))).toBe(true); + expect(isTextField(el('INPUT', { type: 'search' }))).toBe(true); + expect(isTextField(el('SELECT'))).toBe(true); + expect(isTextField(el('DIV', { editable: true }))).toBe(true); + expect(isTextField(el('SPAN', { inTerminal: true }))).toBe(true); + }); + it('is false on an option, a button, the page', () => { + expect(isTextField(el('INPUT', { type: 'radio' }))).toBe(false); + expect(isTextField(el('INPUT', { type: 'checkbox' }))).toBe(false); + expect(isTextField(el('BUTTON'))).toBe(false); + expect(isTextField(el('BODY'))).toBe(false); + expect(isTextField(null)).toBe(false); + }); +}); diff --git a/src/lib/util/outcome.ts b/src/lib/util/outcome.ts index 24d9e362..4cec26f5 100644 --- a/src/lib/util/outcome.ts +++ b/src/lib/util/outcome.ts @@ -4,6 +4,7 @@ import type { Approval } from '../gen/Approval'; import type { ApprovalStatus } from '../gen/ApprovalStatus'; import type { Provider } from '../gen/Provider'; +import { permissionsAsked } from './permissionsAsked'; import { showsPlan } from './planRequest'; import { oneLine } from './sanitize'; @@ -50,11 +51,17 @@ export function answerText(answers: unknown): string | null { return said.length ? said.join(' · ') : null; } -/** The first question of a question card, as the agent wrote it; null when the card has none to show. */ +/** The first question of a question card, as the agent wrote it; null when the card has none to show. + * A question that comes in its request's envelope (an MCP server's elicitation through Codex: + * `{ serverName, mode, message, … }`) is its `message`. */ export function firstQuestion(asked: Asked): string | null { if (asked.subject.kind !== 'question') return null; const raw = asked.subject.questions as unknown; const list = Array.isArray(raw) ? raw : raw && typeof raw === 'object' ? (raw as { questions?: unknown }).questions : null; + if (!Array.isArray(list)) { + const message = raw && typeof raw === 'object' ? (raw as { message?: unknown }).message : null; + return typeof message === 'string' && message.trim() ? message : null; + } const first = Array.isArray(list) ? (list[0] as { question?: unknown; prompt?: unknown } | null) : null; const text = first && typeof first === 'object' ? (first.question ?? first.prompt) : null; return typeof text === 'string' && text ? text : null; @@ -68,6 +75,10 @@ export function askedLine(asked: Asked, provider: Provider | null = null): strin return q ? `Asked you: ${oneLine(q, 80)}` : 'Asked you a question'; } if (showsPlan(s, provider)) return 'Asked you to read its plan'; + if (s.kind === 'permissions') { + const asks = permissionsAsked(s.detail); + return asks.lines.length ? `Asked to ${oneLine(asks.wants, 60)}` : 'Asked for more permissions'; + } return `Asked for approval${s.kind === 'command' ? `: ${oneLine(s.command, 60)}` : ''}`; } diff --git a/src/lib/util/permissionsAsked.ts b/src/lib/util/permissionsAsked.ts new file mode 100644 index 00000000..c7ef358f --- /dev/null +++ b/src/lib/util/permissionsAsked.ts @@ -0,0 +1,134 @@ +// A Codex agent asks for more than its sandbox gives it (`item/permissions/requestApproval`): +// what it asks, in words. The shape is `PermissionsRequestApprovalParams` of the Codex app-server +// protocol: `cwd`, `reason` and `permissions: RequestPermissionProfile` = `{ network: { enabled } +// | null, fileSystem: { read: path[] | null, write: path[] | null, entries?: [{ path, access }] } +// | null }`, where an entry's path is `{ type: "path", path }`, `{ type: "glob_pattern", pattern }` +// or `{ type: "special", value: { kind } }`. The request does not say for how long: the answer +// does (Codly answers "Allow for this turn" with scope "turn", "Allow for this session" with +// scope "session"). +import { oneLine, tildify } from './sanitize'; + +export type PermissionLine = { + /** "Write in", "Read", "Use the network", "Keep out of". */ + verb: string; + /** The folder, file or pattern, as it reads best (relative to where the agent works when near it); null for the network. */ + place: string | null; + /** The place is not inside the folder the agent works in. */ + outside: boolean; +}; + +export type PermissionsAsk = { + /** After " wants to": "write in ../acme-docs", "read 2 folders and use the network". */ + wants: string; + /** One line per thing it asks for, in the request's order; empty when Codly cannot read the shape. */ + lines: PermissionLine[]; + /** The folder the agent works in, as the request says it. */ + cwd: string | null; + /** Codly read the request: false for a shape it does not know (the card then shows the raw detail). */ + known: boolean; +}; + +const UNKNOWN = 'get more permissions'; + +const isObj = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const strings = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string' && x !== '') : []); +const trimEnd = (p: string) => (p.length > 1 ? p.replace(/\/+$/, '') : p); + +/** Whether `path` is `dir` or under it. */ +export function within(path: string, dir: string): boolean { + const p = trimEnd(path); + const d = trimEnd(dir); + return p === d || p.startsWith(d === '/' ? '/' : `${d}/`); +} + +/** + * A path as it reads best: relative to `cwd` when it is inside it ("docs/x") or at most two + * folders up ("../acme-docs"), else whole with "~" for the home folder. A relative path stays as it is. + */ +export function placeOf(path: string, cwd: string | null): string { + if (!path.startsWith('/') || !cwd || !cwd.startsWith('/')) return tildify(path); + const p = trimEnd(path).split('/').filter(Boolean); + const c = trimEnd(cwd).split('/').filter(Boolean); + let same = 0; + while (same < p.length && same < c.length && p[same] === c[same]) same++; + const up = c.length - same; + if (same === 0 || up > 2) return tildify(path); + const rest = p.slice(same); + if (up === 0) return rest.length ? rest.join('/') : '.'; + return [...Array(up).fill('..'), ...rest].join('/'); +} + +const SPECIAL: Record = { + root: 'the whole disk', + minimal: 'the system folders a command needs', + tmpdir: 'the temporary folder', + slash_tmp: '/tmp', +}; + +/** One sandbox entry (`FileSystemSandboxEntry`) as a line; null for a shape Codly does not know. */ +function entryLine(e: unknown, cwd: string | null): PermissionLine | null { + if (!isObj(e) || !isObj(e.path)) return null; + const verb = e.access === 'write' ? 'Write in' : e.access === 'read' ? 'Read' : e.access === 'deny' ? 'Keep out of' : null; + if (!verb) return null; + const p = e.path; + if (p.type === 'path' && typeof p.path === 'string' && p.path) { + return { verb, place: placeOf(p.path, cwd), outside: !!cwd && p.path.startsWith('/') && !within(p.path, cwd) }; + } + if (p.type === 'glob_pattern' && typeof p.pattern === 'string' && p.pattern) { + return { verb: `${verb} the files that match`, place: p.pattern, outside: false }; + } + if (p.type === 'special' && isObj(p.value) && typeof p.value.kind === 'string') { + const kind = p.value.kind; + const sub = typeof p.value.subpath === 'string' && p.value.subpath ? p.value.subpath : null; + if (kind === 'project_roots') return { verb, place: sub ? `${sub} in the project folders` : 'the project folders', outside: false }; + if (kind === 'unknown' && typeof p.value.path === 'string') return { verb, place: tildify(p.value.path), outside: true }; + const named = SPECIAL[kind]; + return named ? { verb, place: named, outside: kind !== 'minimal' } : null; + } + return null; +} + +/** What a permissions request asks for, in words. */ +export function permissionsAsked(detail: unknown): PermissionsAsk { + const d = isObj(detail) ? detail : {}; + const cwd = typeof d.cwd === 'string' && d.cwd ? d.cwd : null; + const perms = d.permissions; + if (!isObj(perms) || !('network' in perms || 'fileSystem' in perms)) return { wants: UNKNOWN, lines: [], cwd, known: false }; + + const lines: PermissionLine[] = []; + let unread = false; + const add = (l: PermissionLine | null) => { + if (!l) unread = true; + else if (!lines.some((x) => x.verb === l.verb && x.place === l.place)) lines.push(l); + }; + const fs = perms.fileSystem; + if (isObj(fs)) { + // `read` and `write` are the older form of `entries`: a request may carry both, for the same paths. + for (const p of strings(fs.write)) add({ verb: 'Write in', place: placeOf(p, cwd), outside: !!cwd && p.startsWith('/') && !within(p, cwd) }); + for (const p of strings(fs.read)) add({ verb: 'Read', place: placeOf(p, cwd), outside: !!cwd && p.startsWith('/') && !within(p, cwd) }); + if (Array.isArray(fs.entries)) for (const e of fs.entries) add(entryLine(e, cwd)); + } else if (fs != null) unread = true; + const net = perms.network; + if (isObj(net) && net.enabled === true) lines.push({ verb: 'Use the network', place: null, outside: false }); + else if (net != null && !isObj(net)) unread = true; + + if (!lines.length) return { wants: UNKNOWN, lines, cwd, known: !unread }; + + // A "Keep out of" line narrows what it asks: the headline names only what it gets. + const parts: string[] = []; + for (const kind of ['Write', 'Read'] as const) { + const these = lines.filter((l) => l.place !== null && l.verb.startsWith(kind)); + if (these.length === 1) parts.push(`${these[0].verb.toLowerCase()} ${oneLine(these[0].place ?? '', 60)}`); + else if (these.length) parts.push(`${kind === 'Write' ? 'write in' : 'read'} ${these.length} places`); + } + if (lines.some((l) => l.place === null)) parts.push('use the network'); + if (!parts.length) return { wants: UNKNOWN, lines, cwd, known: !unread }; + const wants = parts.length === 1 ? parts[0] : `${parts.slice(0, -1).join(', ')} and ${parts[parts.length - 1]}`; + return { wants, lines, cwd, known: !unread }; +} + +/** One line of the card: "Write in ../acme-docs". */ +export const lineText = (l: PermissionLine): string => (l.place === null ? l.verb : `${l.verb} ${l.place}`); + +/** How long an allow of a permissions request lasts, by the choice: the label of its button. */ +export const PERMISSION_SCOPE = { allow_once: 'Allow for this turn', allow_session: 'Allow for this session' } as const; diff --git a/src/lib/util/planRequest.ts b/src/lib/util/planRequest.ts index 4a9331ef..ceb1cad5 100644 --- a/src/lib/util/planRequest.ts +++ b/src/lib/util/planRequest.ts @@ -8,6 +8,7 @@ import type { ApprovalSubject } from '../gen/ApprovalSubject'; import type { Provider } from '../gen/Provider'; +import { permissionsAsked } from './permissionsAsked'; import { sandboxWants } from './sandbox'; import { basename, oneLine } from './sanitize'; @@ -56,7 +57,7 @@ export function wantsTo(s: ApprovalSubject, provider: Cli, max?: number): string case 'question': return 'ask you a question'; case 'permissions': - return 'get more permissions'; + return permissionsAsked(s.detail).wants; } } diff --git a/src/lib/util/questionKeys.ts b/src/lib/util/questionKeys.ts new file mode 100644 index 00000000..00cfaf1f --- /dev/null +++ b/src/lib/util/questionKeys.ts @@ -0,0 +1,38 @@ +// The keys of a question card, as pure rules (the card and the global key map call them): +// 1-9 pick an option while the card is the one waiting and the caret is in no text field, +// ↵ in the answer field sends (⇧↵ is a new line), ⌘↵ sends from anywhere. + +/** Whether keys typed at `el` write text there: a radio or a checkbox does not (digits pick an option on it). */ +export function isTextField(el: Element | null): boolean { + if (!el) return false; + const h = el as HTMLElement; + if (h.isContentEditable || !!h.closest?.('.xterm')) return true; + if (h.tagName === 'TEXTAREA' || h.tagName === 'SELECT') return true; + if (h.tagName !== 'INPUT') return false; + return !/^(radio|checkbox|button|submit|reset|range|color|file|image)$/i.test((h as HTMLInputElement).type); +} + +type Press = { key: string; mod: boolean; alt: boolean; shift: boolean }; + +/** The option a key picks, 0-based; null for any other key, a key with a modifier, or a press in a text field. */ +export function digitPick(p: Press, inTextField: boolean, options: number): number | null { + if (p.mod || p.alt || inTextField || !/^[1-9]$/.test(p.key)) return null; + const n = Number(p.key) - 1; + return n < options ? n : null; +} + +/** Whether a key press in the answer field sends the answer: ↵ (not ⇧↵, not while an IME composes) and ⌘↵. */ +export function sendsFromField(p: Press & { composing?: boolean }): boolean { + return p.key === 'Enter' && !p.shift && !p.alt && !p.composing; +} + +/** + * Which question the digits pick in: the first one with options that has no answer yet, or the + * last one with options when all have one; -1 when none has options. + */ +export function digitQuestion(qs: { options: number; answered: boolean }[]): number { + const open = qs.findIndex((q) => q.options > 0 && !q.answered); + if (open >= 0) return open; + for (let i = qs.length - 1; i >= 0; i--) if (qs[i].options > 0) return i; + return -1; +} diff --git a/src/office/__tests__/behavior.test.ts b/src/office/__tests__/behavior.test.ts index 0b53010e..3288d227 100644 --- a/src/office/__tests__/behavior.test.ts +++ b/src/office/__tests__/behavior.test.ts @@ -196,6 +196,7 @@ describe('events → behaviour', () => { expect(asked(subject('WebFetch', { url: 'https://example.com' }))).toBe('May I use WebFetch?'); expect(asked({ kind: 'question', questions: [] })).toBe('May I ask a question?'); expect(asked({ kind: 'permissions', detail: {} })).toBe('May I get more permissions?'); + expect(asked({ kind: 'permissions' as const, detail: { cwd: '/Users/someone/Code/acme', reason: null, permissions: { network: null, fileSystem: { read: null, write: ['/Users/someone/Code/acme-docs'] } } } })).toBe('May I write in ../acme-docs?'); }); it('blocked slumps under a rain cloud; rate limited sleeps (zZ); long idle falls asleep at 10 min', () => { diff --git a/src/office/reducer.ts b/src/office/reducer.ts index 94fe0dff..2eb2a69a 100644 --- a/src/office/reducer.ts +++ b/src/office/reducer.ts @@ -10,6 +10,7 @@ import type { Approval } from '../lib/gen/Approval'; import type { EventRow } from '../lib/gen/EventRow'; import type { Provider } from '../lib/gen/Provider'; import type { Task } from '../lib/gen/Task'; +import { permissionsAsked } from '../lib/util/permissionsAsked'; import { PLAN_ASK, showsPlan } from '../lib/util/planRequest'; import { sandboxWants } from '../lib/util/sandbox'; import { columnOf, emptyModel, type AgentState, type Fx, type OfficeModel, type TaskCard, type Tone, type ToolCall } from './model'; @@ -229,8 +230,8 @@ export function approvalText(ap: Approval, provider: Provider | null): string { return showsPlan(s, provider) ? PLAN_ASK : (sandboxWants(s, provider, 30) ?? `use ${clean(s.name, 30)}`); case 'question': return 'ask a question'; - default: - return 'get more permissions'; + case 'permissions': + return clean(permissionsAsked(s.detail).wants, 40); } } diff --git a/src/overlays/Palette.svelte b/src/overlays/Palette.svelte index d3eb1eac..dcc053c8 100644 --- a/src/overlays/Palette.svelte +++ b/src/overlays/Palette.svelte @@ -135,7 +135,7 @@ } for (const ap of store.pendingApprovals) { const a = store.agentMap.get(ap.agent_id); - const what = ap.subject.kind === 'command' ? oneLine(ap.subject.command, 50) : ap.subject.kind; + const what = ap.subject.kind === 'command' ? oneLine(ap.subject.command, 50) : oneLine(wants(ap.subject, a?.provider), 50); // The title shows 50 characters: the confirmation shows all of what is asked. const full = `${a?.name ?? 'An agent'} wants to ${wants(ap.subject, a?.provider)}`; if (ap.choices.includes('allow_once')) rows.push({ id: `ap:ok:${ap.id}`, section: 'Needs you', title: `Approve ${a?.name ?? 'agent'}: ${what}`, icon: 'check', run: () => resolveApproval(ap.id, 'allow_once'), confirm: `Approve once? ${full}` }); @@ -249,7 +249,7 @@ .map((p) => ({ id: `go:plan:${p.id}`, section: 'Suggested', title: `${p.status === 'done' ? 'Ready to merge' : 'Ready to run'}: ${p.summary}`, icon: 'plan', hits: [], run: () => ui.openPlan(p.id, p.thread) })), ...store.pendingApprovals .filter((ap) => ap.choices.includes('allow_once')) - .map((ap) => ({ id: `go:ap:${ap.id}`, section: 'Suggested', title: `${store.agentMap.get(ap.agent_id)?.name ?? 'An agent'} needs you: ${ap.subject.kind === 'command' ? oneLine(ap.subject.command, 50) : ap.subject.kind}`, icon: 'check', hits: [], run: () => ui.selectAgent(ap.agent_id) })), + .map((ap) => ({ id: `go:ap:${ap.id}`, section: 'Suggested', title: `${store.agentMap.get(ap.agent_id)?.name ?? 'An agent'} needs you: ${ap.subject.kind === 'command' ? oneLine(ap.subject.command, 50) : oneLine(wants(ap.subject, store.agentMap.get(ap.agent_id)?.provider), 50)}`, icon: 'check', hits: [], run: () => ui.selectAgent(ap.agent_id) })), ]; const suggested = agentRows.slice(0, 6).map((r) => ({ ...r, hits: [] })); const seen = new Set([...rec, ...needs].map((r) => r.id)); diff --git a/src/overlays/__tests__/palette.test.ts b/src/overlays/__tests__/palette.test.ts index 6c2b6882..e312a94a 100644 --- a/src/overlays/__tests__/palette.test.ts +++ b/src/overlays/__tests__/palette.test.ts @@ -47,6 +47,7 @@ describe('palette confirmation', () => { const long = `rm -rf ${'very/long/path/'.repeat(8)}dist`; expect(wants({ kind: 'command', command: long, cwd: '/repo' }, 'claude')).toBe(`run ${long}\nin /repo`); expect(wants({ kind: 'command', command: 'ls', cwd: null }, 'codex')).toBe('run ls'); + expect(wants({ kind: 'permissions' as const, detail: { cwd: '/Users/someone/Code/acme', reason: null, permissions: { network: null, fileSystem: { read: null, write: ['/Users/someone/Code/acme-docs'] } } } }, 'codex')).toBe('write in ../acme-docs'); expect(wants({ kind: 'file_change', paths: ['a.ts', 'b.ts'], diff: null }, 'claude')).toBe('change a.ts, b.ts'); expect(wants({ kind: 'tool', name: 'WebFetch', input: null }, 'claude')).toBe('use the tool WebFetch'); // A command in Claude Code's sandbox wants a host: the whole host, not the name of the request's tool. diff --git a/src/overlays/palette.ts b/src/overlays/palette.ts index 74351676..ad5ca7d9 100644 --- a/src/overlays/palette.ts +++ b/src/overlays/palette.ts @@ -4,6 +4,7 @@ // are one decision, not two: their repeats do nothing on such a row. import type { ApprovalSubject } from '../lib/gen/ApprovalSubject'; import type { Provider } from '../lib/gen/Provider'; +import { permissionsAsked } from '../lib/util/permissionsAsked'; import { showsPlan } from '../lib/util/planRequest'; import { sandboxWants } from '../lib/util/sandbox'; import { clean } from '../lib/util/sanitize'; @@ -50,6 +51,6 @@ export function wants(s: ApprovalSubject, provider: Provider | null | undefined) case 'question': return 'ask you a question'; case 'permissions': - return 'get more permissions'; + return permissionsAsked(s.detail).wants; } } From 017682b75826b2145df94b53e8a8502dcd1d9fa0 Mon Sep 17 00:00:00 2001 From: julienwuthrich-ant Date: Mon, 23 Nov 2026 12:25:27 -0800 Subject: [PATCH 035/120] Merge and restore: a restore while a task waits is told when the task goes on Checkpoints: - A task that waits for you (blocked, or stopped by you) has let its agent go, and its files are still in the agent's worktree. A restore there was written down as one for the agent's 1:1 conversation, so the prompt that took the task up again (Retry, Re-run checks, Send back) dropped the note, and the agent went on in files that had changed with no word. The note is now written for the task that waits in that worktree: the agent's own task whose branch the worktree is on. The prompt that takes the task up again starts with it. A message you write to the agent there before that also starts with it, as it did before a note said what it was written for. Have an agent resolve it / fix it: - The commit of a task on the plan's own branch leaves out what was in the plan's worktree before the task. For a folder, that also left out a change to a file the branch tracks under it (a file your branch brought into that folder with the merge): the checks ran on the edit, and the commit did not have it. Changes to tracked files are now always committed; only the new files under such a folder stay out. - Test only: a start that was cut short after its task was made (the start, where the plan stood and a task that waits are on record, the merge is open) is taken back before the next Merge, and that task is cancelled, so it never runs beside the task of the next resolution. Co-Authored-By: Claude Fable 5.2 --- crates/codly-core/src/git.rs | 32 +++++-- .../src/orchestrator/checkpoints.rs | 96 ++++++++++++++----- .../tests/orchestrator_checkpoints.rs | 72 ++++++++++++++ .../tests/orchestrator_merge_conflict.rs | 94 +++++++++++++++++- 4 files changed, 257 insertions(+), 37 deletions(-) diff --git a/crates/codly-core/src/git.rs b/crates/codly-core/src/git.rs index d2674a87..15d8917b 100644 --- a/crates/codly-core/src/git.rs +++ b/crates/codly-core/src/git.rs @@ -795,9 +795,10 @@ impl Git { } /// `commit_work` that also leaves out the new paths `kept_out`, as `untracked` lists - /// them (a folder ends in `/` and stands for what is under it): they are not the work - /// this commit is for. They stay untracked. The caller knows them and puts them on - /// record, so they are not in `left_out`. + /// them (a folder ends in `/` and stands for the new files under it): they are not the + /// work this commit is for. They stay untracked. A change to a file that the branch + /// tracks is work wherever the file is, also under such a folder. The caller knows the + /// paths and puts them on record, so they are not in `left_out`. pub async fn commit_work_without(&self, wt: &Path, message: &str, kept_out: &[String]) -> Result { let [c1, hooks, c2, fsmonitor] = Self::SAFE; let left_out = self.not_work(wt, &self.git_path(wt, "--git-dir").await?).await?; @@ -1095,7 +1096,9 @@ fn copied_among(record: &[String], files: &[String]) -> Vec { /// that Codly copied in can hold files that the branch tracks (an older branch of the same /// worktree, a file that somebody staged), and leaving the folder out leaves their changes /// out too. So with such a folder, `add -u` first takes every change to a tracked file, -/// wherever it is: only the new files of the folder stay out. +/// wherever it is: only the new files of the folder stay out. The same for `kept_out`: a +/// path that was new when the caller listed it can be tracked by now (a merge brought a file +/// into a folder that was new before it). fn add_all_but(left_out: &[LeftOut], kept_out: &[String]) -> Vec> { let mut all = vec!["add".to_string(), "-A".to_string()]; if left_out.is_empty() && kept_out.is_empty() { @@ -1105,7 +1108,7 @@ fn add_all_but(left_out: &[LeftOut], kept_out: &[String]) -> Vec> { let paths = left_out.iter().map(LeftOut::path).chain(kept_out.iter().map(String::as_str)); all.extend(paths.map(|path| format!(":(exclude,literal){path}"))); let copied_folder = left_out.iter().any(|l| matches!(l, LeftOut::Copied { path } if path.ends_with('/'))); - let tracked = copied_folder.then(|| vec!["add".to_string(), "-u".to_string()]); + let tracked = (copied_folder || !kept_out.is_empty()).then(|| vec!["add".to_string(), "-u".to_string()]); tracked.into_iter().chain([all]).collect() } @@ -2558,8 +2561,10 @@ mod tests { } /// A commit can leave out new paths that are not its work: a file and a folder that were - /// in the worktree before stay untracked, with what is under the folder, and everything - /// else is committed, a new file too. A path among them that is gone is no error. + /// in the worktree before stay untracked, with the new files under the folder, and + /// everything else is committed, a new file too. A file that the branch tracks by now + /// under that folder (a merge brought it in after the list was made) is work when it + /// changes: the commit has it. A path among them that is gone is no error. #[tokio::test] async fn commit_work_without_leaves_the_named_new_paths_out() { let (_d, repo) = repo(); @@ -2570,15 +2575,22 @@ mod tests { } let before = git.untracked(&repo).await.unwrap(); assert_eq!(before, ["cache/", "notes.tmp"]); + // After the list was made, a commit brings a tracked file into the folder that was new. + std::fs::write(repo.join("cache/schema.json"), "{}\n").unwrap(); + sh(&repo, &["add", "cache/schema.json"]); + sh(&repo, &["commit", "-qm", "schema"]); - // The work: a tracked file changed, a new file, and one more file in the old folder. + // The work: two tracked files changed (one of them in the old folder), a new file, + // and one more new file in the old folder. std::fs::write(repo.join("a.txt"), "changed\n").unwrap(); + std::fs::write(repo.join("cache/schema.json"), "{\"v\": 2}\n").unwrap(); std::fs::write(repo.join("new.txt"), "new\n").unwrap(); std::fs::write(repo.join("cache/more.txt"), "later\n").unwrap(); let kept_out: Vec = before.into_iter().chain(["gone.txt".to_string()]).collect(); let snap = git.commit_work_without(&repo, "work", &kept_out).await.unwrap(); - assert_eq!((snap.commit.unwrap().files, snap.left_out), (vec!["a.txt".to_string(), "new.txt".to_string()], vec![])); - assert_eq!(git.untracked(&repo).await.unwrap(), ["cache/", "notes.tmp"]); + assert_eq!((snap.commit.unwrap().files, snap.left_out), (vec!["a.txt".to_string(), "cache/schema.json".to_string(), "new.txt".to_string()], vec![])); + assert_eq!(git.read(&repo, &["show", "HEAD:cache/schema.json"]).await.unwrap().trim(), "{\"v\": 2}"); + assert_eq!(git.untracked(&repo).await.unwrap(), ["cache/built.txt", "cache/more.txt", "notes.tmp"]); assert_eq!(std::fs::read_to_string(repo.join("notes.tmp")).unwrap(), "from before\n"); // Nothing but those paths is new: no commit. Without the list, they are work. diff --git a/crates/codly-core/src/orchestrator/checkpoints.rs b/crates/codly-core/src/orchestrator/checkpoints.rs index 7fecbcd1..58b2a60f 100644 --- a/crates/codly-core/src/orchestrator/checkpoints.rs +++ b/crates/codly-core/src/orchestrator/checkpoints.rs @@ -30,7 +30,9 @@ //! The note also says what it was written for, a task or the agent's 1:1 conversation, and //! only a prompt for the same reads it. A worktree can go on to another task of the agent (a //! team member has one for all its tasks): a note that the first task never read is dropped -//! there, not shown to the next one, which finds other files. +//! there, not shown to the next one, which finds other files. A task that waits for you has +//! let its agent go, and its files are still in the worktree: a restore there is written for +//! that task, so the prompt that takes the task up again starts with the note. //! //! Only a linked worktree of the repository is ever touched (`Git::check_worktree`). An agent //! hired with Git isolation off works in the user's own checkout: it has no checkpoints. @@ -481,8 +483,9 @@ fn old_note_key(agent_id: &str) -> String { #[derive(Serialize, Deserialize)] struct Note { /// What the agent was on in that worktree when the files went back: a task's id, or - /// `ONE_TO_ONE`. Only a prompt for the same reads the note (`Inner::on_in`): a worktree - /// can go on to another task of the agent, which finds other files there. + /// `ONE_TO_ONE` (`Inner::note_for`). Only a prompt for the same reads the note + /// (`Inner::reads`): a worktree can go on to another task of the agent, which finds other + /// files there. #[serde(rename = "for")] meant_for: String, text: String, @@ -630,9 +633,10 @@ impl Inner { // would look like lost work. let note = restore_note(kind, &label, &files, only.is_none()); let shared = self.store.agents(&ws)?.into_iter().filter(|a| a.id != agent.id && a.worktree.as_deref().map(Path::new) == Some(wt.as_path())); - for reader in shared.chain([agent.clone()]) { + let readers: Vec = shared.chain([agent.clone()]).collect(); + for reader in readers { let key = note_key(&reader.id, &wt); - let meant_for = self.on_in(&reader, &wt)?; + let meant_for = self.note_for(&reader, &wt).await?; // An earlier note for the same is not read yet: this one follows it. One for // something else (a task that is over) gives way. let earlier = self.store.kv_get(&key)?.and_then(|saved| serde_json::from_str::(&saved).ok()).filter(|n| n.meant_for == meant_for); @@ -693,18 +697,57 @@ impl Inner { lock(&self.live).get(agent_id).map(|l| l.cwd.clone()) } - /// What `agent` is on in the worktree `wt`, for a note about a restore there: the task of - /// its run in that worktree, else the task it holds whose worktree that is (its run is - /// over, or it reads a message of yours between two turns of the task), else its own - /// conversation with you (`ONE_TO_ONE`). - fn on_in(&self, agent: &Agent, wt: &Path) -> Result { + /// The task `agent` is on in the worktree `wt`: the task of its run in that worktree, else + /// the task it holds whose worktree that is (its run is over, or it reads a message of + /// yours between two turns of the task). None: it is on no task there. + fn task_in(&self, agent: &Agent, wt: &Path) -> Result> { let run_task = lock(&self.live).get(&agent.id).filter(|l| l.cwd.as_path() == wt).and_then(|l| l.task_id.clone()); - if let Some(task) = run_task { - return Ok(task); + if run_task.is_some() { + return Ok(run_task); } let held = agent.task_id.as_deref().map(|id| self.store.task(id)).transpose()?.flatten(); - let there = held.filter(|t| t.worktree.as_deref().map(Path::new) == Some(wt)); - Ok(there.map_or_else(|| ONE_TO_ONE.to_string(), |t| t.id)) + Ok(held.filter(|t| t.worktree.as_deref().map(Path::new) == Some(wt)).map(|t| t.id)) + } + + /// The tasks of `agent` that are not over and whose worktree is `wt`. One that waits for + /// you (it is blocked, or you stopped it) has let the agent go, and its files are still + /// there: Retry, Re-run checks or Send back gives it to the same agent in that worktree. + /// A team member has one worktree for all its tasks, so there can be several. + fn open_in(&self, agent: &Agent, wt: &Path) -> Result> { + let Some(ws) = self.store.agent_workspace(&agent.id)? else { return Ok(vec![]) }; + let here = |t: &Task| t.assignee.as_deref() == Some(agent.id.as_str()) && t.worktree.as_deref().map(Path::new) == Some(wt); + let open = |t: &Task| !matches!(t.status, TaskStatus::Done | TaskStatus::Cancelled); + Ok(self.store.tasks(&ws)?.into_iter().filter(|t| here(t) && open(t)).collect()) + } + + /// What a note about a restore in the worktree `wt` is written for, for `agent`: the task + /// it is on there (`task_in`); else its task that waits there with the files that went + /// back, which is the one whose branch the worktree is on (`open_in`); else its own + /// conversation with you (`ONE_TO_ONE`). + async fn note_for(&self, agent: &Agent, wt: &Path) -> Result { + if let Some(task) = self.task_in(agent, wt)? { + return Ok(task); + } + let open = self.open_in(agent, wt)?; + if open.is_empty() { + return Ok(ONE_TO_ONE.to_string()); + } + let branch = self.git.checked_out_branch(wt).await?; + let waits = open.into_iter().find(|t| branch.is_some() && t.branch == branch); + Ok(waits.map_or_else(|| ONE_TO_ONE.to_string(), |t| t.id)) + } + + /// Is a note written for `meant_for` (`note_for`) one for the prompt that `agent`'s run + /// reads in the worktree `wt` now? A run on a task there reads that task's note and no + /// other. A conversation with you between tasks reads its own note, and the note of a + /// task of the agent that waits there: it is the same agent in the same files, as before + /// notes said what they were for. (No look at the branch here: a prompt goes out with no + /// wait for git. The prompt that takes a task up again is read by a run of that task.) + fn reads(&self, agent: &Agent, wt: &Path, meant_for: &str) -> Result { + Ok(match self.task_in(agent, wt)? { + Some(task) => task == meant_for, + None => meant_for == ONE_TO_ONE || self.open_in(agent, wt)?.iter().any(|t| t.id == meant_for), + }) } /// `text` with the note in front about files the user put back, since the agent's last @@ -724,10 +767,10 @@ impl Inner { } /// The note that waits for the prompt the agent's run reads now: the one of the worktree - /// that run works in, when it was written for what the run is on there (`on_in`). A note + /// that run works in, when it was written for what the run is on there (`reads`). A note /// written for something else is dropped: the task it was for ended with no prompt after - /// the restore, and the worktree went on to this one, with other files. A note under the - /// old key (`old_note_key`) is dropped too. + /// the restore, or the worktree went on to another task, with other files. A note under + /// the old key (`old_note_key`) is dropped too. fn waiting_note(&self, agent_id: &str) -> Result> { let old = old_note_key(agent_id); if self.store.kv_get(&old)?.is_some() { @@ -736,15 +779,18 @@ impl Inner { let Some(wt) = self.prompt_worktree(agent_id) else { return Ok(None) }; let key = note_key(agent_id, &wt); let Some(saved) = self.store.kv_get(&key)? else { return Ok(None) }; - let reader = self.on_in(&self.agent(agent_id)?, &wt)?; - match serde_json::from_str::(&saved) { - Ok(note) if note.meant_for == reader => Ok(Some(note.text)), - // For something else, or from before a note said what it was for. - _ => { - self.store.kv_write(&[(key, None)])?; - Ok(None) - } + // None: from before a note said what it was for. + let note = serde_json::from_str::(&saved).ok(); + let agent = self.agent(agent_id)?; + let for_this = match ¬e { + Some(note) => self.reads(&agent, &wt, ¬e.meant_for)?, + None => false, + }; + if !for_this { + self.store.kv_write(&[(key, None)])?; + return Ok(None); } + Ok(note.map(|note| note.text)) } /// A prompt reached the agent (it started a turn, or the running turn took it in): it diff --git a/crates/codly-core/tests/orchestrator_checkpoints.rs b/crates/codly-core/tests/orchestrator_checkpoints.rs index 8678a74e..6f638328 100644 --- a/crates/codly-core/tests/orchestrator_checkpoints.rs +++ b/crates/codly-core/tests/orchestrator_checkpoints.rs @@ -737,6 +737,78 @@ async fn a_note_under_the_old_key_is_dropped_at_the_agents_next_prompt() { o.core.shutdown().await; } +/// A team member, Ana, on a task you gave her, which you stop in its first turn. The task +/// waits for you (Blocked), Ana is let go of it and has no run, and her worktree still holds +/// the task's files on the task's branch: the state of every member's task that waits for +/// you. Returns Ana's id, her worktree and the task. +async fn a_members_task_that_waits_for_you(o: &Office) -> (Id, PathBuf, Task) { + let ana = TeamMember { name: "Ana".into(), role: "Backend dev".into(), ..Default::default() }; + o.core.update_settings(Settings { team: vec![ana], lead_followups: false, ..Default::default() }).await.unwrap(); + let id = o.core.snapshot().await.unwrap().agents.into_iter().find(|a| a.name == "Ana").expect("Ana is on the team").id; + let task = o.core.create_task("Say hello", "Write hello.txt").await.unwrap(); + o.core.assign_task(&task.id, Some(&id)).await.unwrap(); + wait_for("the checkpoint before the task's first turn", async || (o.core.agent_checkpoints(&id).await.unwrap().checkpoints.len() == 1).then_some(())).await; + let task = o.core.snapshot().await.unwrap().tasks.into_iter().find(|t| t.id == task.id).unwrap(); + let wt = PathBuf::from(task.worktree.clone().unwrap()); + // The turn writes a file (here the test is the agent's hands), and then you stop the task. + std::fs::write(wt.join("hello.txt"), "hello\n").unwrap(); + let task = o.core.move_task(&task.id, TaskStatus::Blocked).await.unwrap(); + run_over(o, &id).await; + let ana = o.core.snapshot().await.unwrap().agents.into_iter().find(|a| a.id == id).unwrap(); + assert_eq!((ana.task_id.as_deref(), ana.worktree.as_deref()), (None, task.worktree.as_deref()), "Ana holds no task, and her worktree is the task's"); + (id, wt, task) +} + +/// The prompts that were read in the folder `dir`, in order. +fn read_in(o: &Office, dir: &Path) -> Vec { + let seen = o.seen.lock().unwrap(); + seen.prompts.iter().zip(&seen.read_in).filter(|(_, at)| at.as_path() == dir).map(|(prompt, _)| prompt.clone()).collect() +} + +const ONE_FILE_BACK: &str = "[Codly] The user put one file in your worktree back to how it was before the turn that started with "; + +/// A member's task waits for you, and its member holds no task meanwhile. You put a file +/// back in the member's Git tab: those are the task's files. The note is written for that +/// task, and when you click Retry, the prompt that takes the task up again starts with it: +/// the member does not go on in files that changed with no word. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_restore_while_a_members_task_waits_for_you_is_told_when_the_task_goes_on() { + let dir = tempfile::tempdir().unwrap(); + let o = office(dir.path()).await; + let (id, wt, task) = a_members_task_that_waits_for_you(&o).await; + let store = Store::open(&dir.path().join("data/codly.sqlite")).unwrap(); + + let done = o.core.restore_checkpoint_file(&id, 1, "hello.txt").await.unwrap(); + assert_eq!(done.files, files(&["hello.txt"])); + assert!(!wt.join("hello.txt").exists()); + let note = store.kv_get(¬e_key(&id, &wt)).unwrap().expect("a note waits in the member's worktree"); + let read: serde_json::Value = serde_json::from_str(¬e).unwrap(); + assert_eq!(read["for"], task.id.as_str(), "the note is for the task that waits there: {note}"); + + // Retry: the task goes back to Ana, in the same worktree. + o.core.move_task(&task.id, TaskStatus::Ready).await.unwrap(); + let told = wait_for("the prompt that takes the task up again", async || read_in(&o, &wt).get(1).cloned()).await; + assert!(told.starts_with(ONE_FILE_BACK), "{told}"); + assert!(told.contains(", and left the other files as they are. 1 file changed: hello.txt."), "{told}"); + o.core.shutdown().await; +} + +/// The same restore, and then you write to the member before the task goes on. That +/// conversation is read in the same worktree, by the same agent: it starts with the note, as +/// it did before a note said what it was written for. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_restore_while_a_members_task_waits_for_you_is_told_in_the_members_chat() { + let dir = tempfile::tempdir().unwrap(); + let o = office(dir.path()).await; + let (id, wt, _task) = a_members_task_that_waits_for_you(&o).await; + o.core.restore_checkpoint_file(&id, 1, "hello.txt").await.unwrap(); + + o.core.send_chat(&format!("agent:{id}"), "what happened?").await.unwrap(); + let told = wait_for("the message to reach the member", async || read_in(&o, &wt).get(1).cloned()).await; + assert!(told.starts_with(ONE_FILE_BACK) && told.contains("[User] what happened?"), "{told}"); + o.core.shutdown().await; +} + /// An agent that reviews a task reads the task's files and changes none, and no turn of a /// review is kept. Its Git tab says so: it does not promise checkpoints that never come. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] diff --git a/crates/codly-core/tests/orchestrator_merge_conflict.rs b/crates/codly-core/tests/orchestrator_merge_conflict.rs index de778168..5f92f783 100644 --- a/crates/codly-core/tests/orchestrator_merge_conflict.rs +++ b/crates/codly-core/tests/orchestrator_merge_conflict.rs @@ -1294,11 +1294,17 @@ async fn the_new_files_of_a_resolution_that_did_not_finish_go() { /// Makes the store refuse one write of a resolution's start (`write`: the trigger's event, in /// SQL), or lets every write through again (None). fn store_refuses(root: &Path, write: Option<&str>) { + store_trigger(root, "refused", write); +} + +/// The same under a name of its own, for a second write that the store refuses at the same +/// time. +fn store_trigger(root: &Path, name: &str, write: Option<&str>) { let db = rusqlite::Connection::open(root.join("data/codly.sqlite")).unwrap(); db.busy_timeout(Duration::from_secs(5)).unwrap(); let sql = match write { - Some(write) => format!("CREATE TRIGGER refused BEFORE {write} BEGIN SELECT RAISE(ABORT, 'the disk is full'); END"), - None => "DROP TRIGGER refused".to_string(), + Some(write) => format!("CREATE TRIGGER {name} BEFORE {write} BEGIN SELECT RAISE(ABORT, 'the disk is full'); END"), + None => format!("DROP TRIGGER {name}"), }; db.execute_batch(&sql).unwrap(); } @@ -1532,6 +1538,90 @@ async fn a_take_back_that_cannot_be_written_down_still_says_the_branch_is_back() core.shutdown().await; } +/// The write that cancels a task. +const A_TASK_CANCELLED: &str = "UPDATE OF status ON task WHEN NEW.status = 'cancelled'"; + +/// Codly was closed in the middle of a start, later than in the test of the start with no +/// task: the task that resolves the conflict was made, and the plan did not run again yet. +/// On record are the start, where the plan stood, and a task that waits; the merge is open in +/// the plan's worktree. The next Merge takes the merge out and cancels that task: left +/// waiting, it would start beside the task of the next resolution, in the same worktree. The +/// next resolution has one task, and the old one never runs. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_start_cut_short_after_its_task_was_made_cancels_that_task() { + let dir = tempfile::tempdir().unwrap(); + let turns: Turns = Default::default(); + let lead = lead_with("greeting.txt", "grep -q plan greeting.txt", &[]); + let (core, repo) = start(dir.path(), lead, plan_worker(), turns.clone()).await; + core.send_chat("lead", "Please change the greeting").await.unwrap(); + let plan = wait_plan(&core, PlanStatus::Done).await; + let source = PrSource::Plan(plan.id.clone()); + let branch = plan.integration_branch.clone().unwrap(); + let integ_wt = PathBuf::from(plan.integration_worktree.clone().unwrap()); + let tip = sh(&repo, &["rev-parse", &branch]); + let mine = commit(&repo, "greeting.txt", "hello from main\n"); + + // That state, made with Codly's own writes as far as they go: a start that fails once its + // task is made, and whose take-back cannot cancel the task. The start, where the plan + // stood and the task stay on record. + store_refuses(dir.path(), Some(A_MERGE_RECORD)); + store_trigger(dir.path(), "kept", Some(A_TASK_CANCELLED)); + let err = core.resolve_merge_conflict(&source).await.unwrap_err().to_string(); + assert!(err.contains(&format!("Codly took the merge of main back: {branch} is as it was. It could not write that down: ")), "{err}"); + store_refuses(dir.path(), None); + store_trigger(dir.path(), "kept", None); + // The rest by hand: the start is one of another run of Codly, and the merge it made is + // still open in the plan's worktree (that run was closed before it could take it back). + let (start_key, start) = kv_rows(dir.path(), "merge_start:").pop().expect("the start is on record"); + let mut start: Value = serde_json::from_str(&start).unwrap(); + start["run"] = json!("an earlier run"); + let db = rusqlite::Connection::open(dir.path().join("data/codly.sqlite")).unwrap(); + db.busy_timeout(Duration::from_secs(5)).unwrap(); + assert_eq!(db.execute("UPDATE kv SET value = ?2 WHERE key = ?1", [start_key, start.to_string()]).unwrap(), 1); + drop(db); + assert!(!git(&integ_wt, &["merge", "main"]).status.success(), "the merge of main conflicts"); + assert!(in_merge(&integ_wt) && std::fs::read_to_string(integ_wt.join("greeting.txt")).unwrap().contains("<<<<<<<")); + let s = core.snapshot().await.unwrap(); + let task = s.tasks.iter().find(|t| t.key == "resolve").expect("the task had reached the store").clone(); + let stood = s.plans.iter().find(|p| p.id == plan.id).unwrap(); + assert_eq!((task.status, stood.status, &stood.base_commit), (TaskStatus::Pending, PlanStatus::Done, &plan.base_commit)); + assert_eq!(start_records(dir.path()).len(), 2, "{:?}", start_records(dir.path())); + + // The next Merge takes the start back first: the merge is out, and the task is cancelled. + let err = core.merge_plan(&plan.id).await.unwrap_err().to_string(); + assert!(err.contains("merging into main conflicts in greeting.txt"), "{err}"); + let s = core.snapshot().await.unwrap(); + let old = s.tasks.iter().find(|t| t.id == task.id).unwrap(); + assert_eq!((old.status, old.status_reason.as_deref()), (TaskStatus::Cancelled, Some("Codly could not start it"))); + assert_eq!(core.merge_state(&source).await.unwrap().resolving, None); + assert_eq!((sh(&repo, &["rev-parse", &branch]), in_merge(&integ_wt), sh(&integ_wt, &["status", "--porcelain"])), (tip.clone(), false, String::new())); + assert_eq!(std::fs::read_to_string(integ_wt.join("greeting.txt")).unwrap(), "hello from the plan\n", "no marker is left"); + let record = decisions(&core).await; + let taken_back = format!("bringing main into {branch} did not finish when Codly closed; {branch} is back where it was before it"); + assert_eq!(record.iter().filter(|d| **d == taken_back).count(), 1, "{record:?}"); + assert_eq!(start_records(dir.path()), Vec::::new()); + assert_eq!((sh(&repo, &["rev-parse", "HEAD"]), sh(&repo, &["rev-parse", &branch])), (mine, tip)); + + // The next resolution has a task of its own, the only one that runs, and the merge goes + // through. + let state = core.resolve_merge_conflict(&source).await.unwrap(); + let second = core.snapshot().await.unwrap().tasks.into_iter().find(|t| t.key == "resolve-2").expect("a second resolving task"); + assert_eq!(state.resolving.as_deref(), Some(second.id.as_str())); + wait_plan(&core, PlanStatus::Done).await; + let briefed: Vec = turns + .lock() + .unwrap() + .iter() + .filter(|(role, _, _)| *role == Role::Worker) + .filter_map(|(_, _, prompt)| prompt.split("[Codly] Task resolve").nth(1).and_then(|rest| rest.split(':').next()).map(|n| format!("resolve{n}"))) + .collect(); + assert_eq!(briefed, ["resolve-2"], "the task of the start that was cut short never ran"); + assert_eq!(core.snapshot().await.unwrap().tasks.iter().find(|t| t.id == task.id).unwrap().status, TaskStatus::Cancelled); + core.merge_plan(&plan.id).await.unwrap(); + assert_eq!(std::fs::read_to_string(repo.join("greeting.txt")).unwrap(), RESOLVED); + core.shutdown().await; +} + /// No agent works on a cancelled plan any more, and the refusal says what is left for you to /// do: resolve a conflict, or, when the plan's checks failed on this very merge, fix the /// checks. When that cannot be read, the refusal is the same plain words, not the error of From ecf8a3bc243fd1c5a63c266a313ffbac40f57873 Mon Sep 17 00:00:00 2001 From: julienwuthrich-ant Date: Mon, 23 Nov 2026 12:25:34 -0800 Subject: [PATCH 036/120] codly serve: the browser opens on Linux too The link was opened with `open`, which only macOS has as a URL opener. It now goes through the opener plugin the app already loads (`open` on macOS, the desktop's opener on Linux), and a failure is logged. Co-Authored-By: Claude Opus 5.5 --- src-tauri/src/web.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src-tauri/src/web.rs b/src-tauri/src/web.rs index 856d124f..b9063ecb 100644 --- a/src-tauri/src/web.rs +++ b/src-tauri/src/web.rs @@ -24,6 +24,7 @@ use hyper_util::rt::TokioIo; use tauri::ipc::{CallbackFn, InvokeBody, InvokeResponse, InvokeResponseBody}; use tauri::webview::InvokeRequest; use tauri::{AppHandle, Manager}; +use tauri_plugin_opener::OpenerExt; use tokio::sync::{mpsc, oneshot}; use crate::commands::AppState; @@ -114,7 +115,10 @@ async fn serve(app: AppHandle, s: Serve, open: bool) -> anyhow::Result<()> { let url = format!("http://{host}:{}/?token={token}", s.port); println!("Codly is running at {url}\nPress Ctrl+C to stop."); if open { - let _ = std::process::Command::new("open").arg(&url).spawn(); + // The system's own opener: `open` on macOS, `xdg-open` (or the desktop's tool) on Linux. + if let Err(e) = app.opener().open_url(&url, None::<&str>) { + tracing::warn!("could not open the browser: {e}"); + } } loop { let (stream, _) = listener.accept().await?; From b1872acfeaaa13ce9246ba789b9337f8425dad35 Mon Sep 17 00:00:00 2001 From: julienwuthrich-ant Date: Mon, 23 Nov 2026 12:31:00 -0800 Subject: [PATCH 037/120] Adapter tests: the read-tool replay expects the fixture's placeholder message id claude-tool.jsonl now writes its API message ids as msg-N (previous commit); the test checks msg-2 where it checked the recorded id. Co-Authored-By: Claude Opus 5.5 --- crates/codly-core/src/adapters/claude.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/codly-core/src/adapters/claude.rs b/crates/codly-core/src/adapters/claude.rs index 01ace160..0cc3960a 100644 --- a/crates/codly-core/src/adapters/claude.rs +++ b/crates/codly-core/src/adapters/claude.rs @@ -3188,12 +3188,12 @@ mod tests { EventKind::TextDelta { item_id, text } => Some((item_id.clone(), text.clone())), _ => None, }); - assert_eq!(delta, Some(("msg_011CgPgZ5DraWXssRR4rfPzQ:0".into(), "DONE".into()))); + assert_eq!(delta, Some(("msg-2:0".into(), "DONE".into()))); let msg = events.iter().find_map(|e| match e { EventKind::Message { item_id, text, phase } => Some((item_id.clone(), text.clone(), *phase)), _ => None, }); - assert_eq!(msg, Some(("msg_011CgPgZ5DraWXssRR4rfPzQ:0".into(), "DONE".into(), MessagePhase::Final))); + assert_eq!(msg, Some(("msg-2:0".into(), "DONE".into(), MessagePhase::Final))); assert!(events.iter().any(|e| matches!(e, EventKind::RateLimit { window, .. } if window == "five_hour"))); // Usage after each of the two API calls, then the result's own numbers: the same totals. From 5f4564937d0a9407d320247648db57caa4710e9c Mon Sep 17 00:00:00 2001 From: julienwuthrich-ant Date: Mon, 23 Nov 2026 12:31:27 -0800 Subject: [PATCH 038/120] Claude sessions: an MCP switch is on record only when it happened, and its hint promises nothing unrecorded "You turned on for 's run" was written before Claude Code answered. When the CLI refused the switch, or did not answer in time, the sheet said "Couldn't turn on" and the agent's timeline still said that you turned it on. The record is now written after the answer: a switch that happened says "you turned", and one that did not says what you asked and what came back ("asked to turn on: "). A test with a CLI that refuses the switch covers it. The button's hint said "Its next run starts every server again", and the comments said that nothing is saved. No recording shows that: the one recording of mcp_toggle is a single process, and none was started after an "off". The hint now reads "Switches this server for . Claude Code may keep the switch after this run.", and the comments say what is not recorded. Co-Authored-By: Claude Fable 5.2 --- crates/codly-core/src/adapters/mod.rs | 8 ++-- .../src/orchestrator/live_session.rs | 37 ++++++++++++------- .../tests/orchestrator_claude_modes.rs | 25 ++++++++++--- docs/ARCHITECTURE.md | 2 +- src/lib/__tests__/mockTransport.test.ts | 2 +- src/lib/__tests__/session.test.ts | 7 ++-- src/lib/demo/controls.ts | 4 +- src/lib/state/session.ts | 11 ++++-- src/sheet/AgentMcp.svelte | 4 +- 9 files changed, 66 insertions(+), 34 deletions(-) diff --git a/crates/codly-core/src/adapters/mod.rs b/crates/codly-core/src/adapters/mod.rs index 65c00c14..be00d00b 100644 --- a/crates/codly-core/src/adapters/mod.rs +++ b/crates/codly-core/src/adapters/mod.rs @@ -157,9 +157,11 @@ pub enum SessionRequest { /// server that still cannot connect the answer is an error with the CLI's reason; for one /// that connects it is a success with no body (part 3 §10, n=1). McpReconnect(String), - /// `mcp_toggle`: turn the MCP server of this name off (false) or on (true) for this - /// process. Recorded (part 3 §10, n=1): a success with no body either way; the server is - /// then `disabled`, or started again and `connected`. Where it stands is in `mcp_status`. + /// `mcp_toggle`: turn the MCP server of this name off (false) or on (true). Recorded + /// (part 3 §10, n=1): a success with no body either way; the server is then `disabled`, + /// or started again and `connected`. Where it stands is in `mcp_status`. Not recorded: + /// whether the CLI saves the switch (no process was started after an "off"), and what it + /// answers for a server that does not start or that it does not know. McpEnabled(String, bool), /// `stop_task`, with the id of a background task (`BackgroundTask::id`): the CLI ends it. /// The answer is empty also when nothing was stopped (recorded, part 2 §6): the CLI's next diff --git a/crates/codly-core/src/orchestrator/live_session.rs b/crates/codly-core/src/orchestrator/live_session.rs index 62def8df..5f37e622 100644 --- a/crates/codly-core/src/orchestrator/live_session.rs +++ b/crates/codly-core/src/orchestrator/live_session.rs @@ -6,10 +6,12 @@ //! - **Reconnect** an MCP server (`mcp_reconnect`). The CLI's answer is yours to read: when //! the server still does not connect, its own reason is the error. The adapter then asks the //! CLI where its servers stand, so the agent's `McpServer` events follow. -//! - **Turn off** and **Turn on** an MCP server (`mcp_toggle`), for this run: the CLI's -//! process holds the switch, nothing is saved, and the agent's next run starts every server -//! again. The server's state follows as after a reconnect. Codly's own server stays on: -//! the agent reports through it. +//! - **Turn off** and **Turn on** an MCP server (`mcp_toggle`). The server's state follows as +//! after a reconnect, and the act is on record once the CLI answered: a switch the CLI +//! refused is on record as what you asked, with its reason. Not recorded: whether the CLI +//! saves the switch (`r5-mcp-reconnect-toggle` is one process; none was started after an +//! "off"), so nothing here says how the agent's next run starts that server. Codly's own +//! server stays on: the agent reports through it. //! - **Stop** a background command or helper (`stop_task`). The CLI answers the same whether //! or not something ended; its next list of background tasks (`BackgroundTasks`) says that //! it was stopped. @@ -32,7 +34,7 @@ use std::time::Duration; use anyhow::{Result, bail}; -use super::{Inner, lock}; +use super::{Inner, lock, prompts}; use crate::adapters::SessionRequest; use crate::model::{EventKind, EventRow, Id, McpServerStatus}; @@ -132,9 +134,19 @@ impl Inner { } let answer = self.ask_session(agent_id, SessionRequest::McpEnabled(server.to_string(), on))?; let switched = if on { "on" } else { "off" }; - self.control_decision(agent_id, format!("you turned {server} {switched} for {}'s run", agent.name)); - Self::session_answer_within(answer, RECONNECT_ANSWER_LIMIT).await?; - Ok(()) + // "You turned" is true only once the CLI answered that it did. A request it refused, + // or did not answer in time (it can still take effect then), is on record as what you + // asked and what came back. + match Self::session_answer_within(answer, RECONNECT_ANSWER_LIMIT).await { + Ok(_) => { + self.control_decision(agent_id, format!("you turned {server} {switched} for {}'s run", agent.name)); + Ok(()) + } + Err(e) => { + self.control_decision(agent_id, format!("asked {} to turn {server} {switched}: {}", agent.name, prompts::clip(&e.to_string(), 200))); + Err(e) + } + } } async fn stop_background_task(&self, agent_id: &str, task_id: &str) -> Result<()> { @@ -162,11 +174,10 @@ impl super::Core { self.inner.reconnect_mcp(agent_id, server).await } - /// Turn one MCP server of a live Claude agent's session off or on, for this run of the - /// agent: nothing is saved, and its next run starts every server again. The agent's - /// `McpServer` events say where the server stands then. Err = Claude Code's own reason - /// (a server that is turned on and does not start), or a refusal: Codly's own server - /// stays on. + /// Turn one MCP server of a live Claude agent's session off or on. The agent's + /// `McpServer` events say where the server stands then. Err = what Claude Code answered + /// (or that it did not answer), or a refusal: Codly's own server stays on. Not recorded: + /// whether the CLI saves the switch for the agent's later runs. pub async fn set_agent_mcp_enabled(&self, agent_id: &str, server: &str, enabled: bool) -> Result<()> { self.inner.set_mcp_enabled(agent_id, server, enabled).await } diff --git a/crates/codly-core/tests/orchestrator_claude_modes.rs b/crates/codly-core/tests/orchestrator_claude_modes.rs index 0bb5a7cd..c45c9aa0 100644 --- a/crates/codly-core/tests/orchestrator_claude_modes.rs +++ b/crates/codly-core/tests/orchestrator_claude_modes.rs @@ -249,10 +249,12 @@ impl Spawner for Fake { s.log.push(format!("reconnect:{server}")); Err("Dynamic Client Registration rejected (HTTP 401): {\"error\":\"unauthorized\"}".to_string()) } - // (recorded: a success with no body, off and on) + // (recorded: a success with no body, off and on. Not recorded: a + // switch the CLI refuses; the error here is the connect error that a + // reconnect of a dead stdio server answers with.) SessionRequest::McpEnabled(server, on) => { s.log.push(format!("mcp-{}:{server}", if on { "on" } else { "off" })); - Ok(serde_json::Value::Null) + if server == "does-not-start" { Err("Connection closed".to_string()) } else { Ok(serde_json::Value::Null) } } // (recorded: `{}`, whether or not a task ended) SessionRequest::StopTask(task_id) => { @@ -921,8 +923,9 @@ async fn a_background_command_is_stopped_through_the_live_session() { core.shutdown().await; } -/// "Turn off" and "Turn on" of an MCP server reach the live session, for this run of the -/// agent, and each is on record as your act. Codly's own server stays on. +/// "Turn off" and "Turn on" of an MCP server reach the live session, and each is on record +/// as your act once Claude Code answered. A switch it refused is on record as what you asked, +/// with its reason. Codly's own server stays on. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn an_mcp_server_is_turned_off_and_on_through_the_live_session() { let dir = tempfile::tempdir().unwrap(); @@ -936,13 +939,23 @@ async fn an_mcp_server_is_turned_off_and_on_through_the_live_session() { assert_eq!(last_seen(&seen), "mcp-on:docs"); assert_eq!(your_acts(&core, &id).await, [format!("you turned docs off for {name}'s run"), format!("you turned docs on for {name}'s run")]); + // Claude Code refuses a switch: its reason is yours, and the record says what you asked + // and what came back. It does not say "you turned": the server was not turned on. + let e = core.set_agent_mcp_enabled(&id, "does-not-start", true).await.unwrap_err().to_string(); + assert_eq!(e, "Claude Code answered: Connection closed"); + assert_eq!(last_seen(&seen), "mcp-on:does-not-start"); + let acts = your_acts(&core, &id).await; + assert_eq!(acts.len(), 3, "{acts:?}"); + assert_eq!(acts[2], format!("asked {name} to turn does-not-start on: Claude Code answered: Connection closed")); + assert!(!acts.iter().any(|a| a.starts_with("you turned does-not-start")), "{acts:?}"); + // Codly's own server, and no server named: nothing reaches the CLI, nothing is on record. let e = core.set_agent_mcp_enabled(&id, "codly", false).await.unwrap_err().to_string(); assert_eq!(e, format!("codly is Codly's own server: {name} reports to Codly through it, so it stays on")); let e = core.set_agent_mcp_enabled(&id, " ", true).await.unwrap_err().to_string(); assert_eq!(e, "which MCP server?"); - assert_eq!(last_seen(&seen), "mcp-on:docs"); - assert_eq!(your_acts(&core, &id).await.len(), 2); + assert_eq!(last_seen(&seen), "mcp-on:does-not-start"); + assert_eq!(your_acts(&core, &id).await.len(), 3); stop(&core, &id).await; let e = core.set_agent_mcp_enabled(&id, "docs", false).await.unwrap_err().to_string(); diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index df34064a..b20b6558 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -667,7 +667,7 @@ crates/codly-core/src/ the engine: no Tauri dependency preview.rs try work before a merge: your command in a plan's or an agent's worktree checkpoints.rs an agent's files before each turn (private refs); restore takeover.rs "Open in my terminal": a session goes to you, and comes back - live_session.rs a live Claude session from the agent sheet: reconnect an MCP server, turn one off or on for this run, stop a background command; its servers and its last list of background tasks for a snapshot + live_session.rs a live Claude session from the agent sheet: reconnect an MCP server, turn one off or on, stop a background command; its servers and its last list of background tasks for a snapshot tools.rs triggers.rs memgraph.rs MCP tool handler, trigger loop, Knowledge room lenses housekeeping.rs glue for housekeeping/ (storage: housekeeping/storage.rs) worktree_setup.rs a new worktree made ready: copied files, ports, setup script diff --git a/src/lib/__tests__/mockTransport.test.ts b/src/lib/__tests__/mockTransport.test.ts index 2ed67d5a..1202a4e1 100644 --- a/src/lib/__tests__/mockTransport.test.ts +++ b/src/lib/__tests__/mockTransport.test.ts @@ -194,7 +194,7 @@ describe('the demo transport', () => { await expect(reconnect('linear')).rejects.toThrow('linear still needs a sign-in'); expect(await servers()).toEqual([['codly', 'connected'], ['linear', 'needs_sign_in'], ['postgres', 'connected']]); - // "Turn off" and "Turn on", for this run: the server's state follows. Codly's own server stays on. + // "Turn off" and "Turn on": the server's state follows. Codly's own server stays on. expect(await call(t, 'set_agent_mcp_enabled', { agentId: lead.id, server: 'postgres', enabled: false })).toBeNull(); expect(await servers()).toEqual([['codly', 'connected'], ['linear', 'needs_sign_in'], ['postgres', 'disabled']]); expect(await call(t, 'set_agent_mcp_enabled', { agentId: lead.id, server: 'postgres', enabled: true })).toBeNull(); diff --git a/src/lib/__tests__/session.test.ts b/src/lib/__tests__/session.test.ts index 9547728e..7f7bee65 100644 --- a/src/lib/__tests__/session.test.ts +++ b/src/lib/__tests__/session.test.ts @@ -100,7 +100,7 @@ describe('the MCP servers of an agent', () => { expect(reconnectAnswer(tracker(), { ...late, seen: tracker().ts })).toBeNull(); }); - it('a connected server can be turned off and a switched-off one on, for this run; Codly\'s own stays on', () => { + it('a connected server can be turned off and a switched-off one on; Codly\'s own stays on', () => { apply( server(10, 'r2', 'codly', 'connected'), server(10, 'r2', 'docs', 'connected'), @@ -121,8 +121,9 @@ describe('the MCP servers of an agent', () => { ]); expect(mcpSwitch(servers[1])).toEqual({ label: 'Turn off', busy: 'Turning off…', enabled: false }); expect(mcpSwitch(servers[2])).toEqual({ label: 'Turn on', busy: 'Turning on…', enabled: true }); - // Nothing is saved: the button says how far the switch goes. - expect(mcpSwitchHint('Bo')).toBe('For this run of Bo. Its next run starts every server again.'); + // No recording says whether Claude Code saves the switch: the hint promises nothing + // about the agent's next run. + expect(mcpSwitchHint('Bo')).toBe('Switches this server for Bo. Claude Code may keep the switch after this run.'); expect(MCP_HINT.disabled).toBe('This server is switched off: the agent works without its tools. Turn on starts it again.'); expect(mcpSummary(servers)).toBe('2 connected · 1 connecting · 1 needs sign-in · 1 did not start · 1 switched off'); }); diff --git a/src/lib/demo/controls.ts b/src/lib/demo/controls.ts index d1e51d79..5ac902d3 100644 --- a/src/lib/demo/controls.ts +++ b/src/lib/demo/controls.ts @@ -199,8 +199,8 @@ export class MockControls { } /** - * "Turn off" and "Turn on" on an MCP server of a Claude agent, for this run of the agent: - * the server's state says "switched off", or "connected" again. Codly's own server stays on. + * "Turn off" and "Turn on" on an MCP server of a Claude agent's live run: the server's + * state says "switched off", or "connected" again. Codly's own server stays on. */ setMcpEnabled(id: string, server: string, enabled: boolean): null { const a = this.agent(id); diff --git a/src/lib/state/session.ts b/src/lib/state/session.ts index b47f5439..b83bc33a 100644 --- a/src/lib/state/session.ts +++ b/src/lib/state/session.ts @@ -114,11 +114,16 @@ export function mcpSwitch(s: McpServer): McpSwitch | null { return null; } -/** What the switch is for, on its button: nothing is saved, the agent's process holds it. */ -export const mcpSwitchHint = (agent: string): string => `For this run of ${agent}. Its next run starts every server again.`; +/** + * What the switch is for, on its button. Not recorded: whether Claude Code saves the switch + * (docs/research has one process that turns a server off and on, and no process started + * after an "off"). So the line promises nothing about the agent's next run, and says that + * the switch can stay. + */ +export const mcpSwitchHint = (agent: string): string => `Switches this server for ${agent}. Claude Code may keep the switch after this run.`; /** - * Turn an MCP server off or on for this run of the agent. Returns whether Claude Code took + * Turn an MCP server of the agent's live run off or on. Returns whether Claude Code took * the request; the server's next `mcp_server` event says where it stands. A refusal (Codly's * own server, a server that does not start again) is said in a toast, with the reason. */ diff --git a/src/sheet/AgentMcp.svelte b/src/sheet/AgentMcp.svelte index 306b22d4..4e314981 100644 --- a/src/sheet/AgentMcp.svelte +++ b/src/sheet/AgentMcp.svelte @@ -5,8 +5,8 @@ Code to try again (orchestrator/live_session.rs), which can take as long as the server takes to start. When the server still does not connect, the answer shows under the server, beside the server's reason, until the server reports again. "Turn off" on a connected server and - "Turn on" on a switched-off one are for this run of the agent: nothing is saved, and the - agent's next run starts every server again. + "Turn on" on a switched-off one go to the agent's live run. Not recorded: whether Claude + Code saves the switch, so the button's hint promises nothing about the agent's next run. --> - @@ -323,12 +390,14 @@ .txt { flex: 1; min-width: 0; } /* A long word with no place to break (a branch, a file name) breaks anywhere: it stays in its toast. */ .title { font-weight: var(--w-med); color: var(--ink-1); overflow-wrap: anywhere; } + .count { margin-left: 6px; color: var(--ink-3); } .body { margin-top: 2px; color: var(--ink-2); font-size: var(--t-sm); line-height: var(--lh-sm); overflow-wrap: anywhere; } /* Six lines; a longer text ends with "Show all" (no scroll inside a toast). */ .body.clamp { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 6; line-clamp: 6; overflow: hidden; } .all { margin-top: 2px; font-size: var(--t-sm); line-height: var(--lh-sm); font-weight: var(--w-med); color: var(--ink-1); text-decoration: underline; text-underline-offset: 2px; } - .btn { margin-top: -2px; } + .act { margin-top: 8px; } .close { margin: -3px -2px 0 -2px; color: var(--ink-3); } - .more { flex-shrink: 0; align-self: center; pointer-events: auto; padding: 0 12px; border-radius: var(--r-full); background: var(--pop); box-shadow: var(--pop-shadow); font-size: var(--t-sm); font-weight: var(--w-med); color: var(--ink-2); } + .foot { flex-shrink: 0; align-self: center; display: flex; gap: 6px; } + .more { pointer-events: auto; padding: 0 12px; border-radius: var(--r-full); background: var(--pop); box-shadow: var(--pop-shadow); font-size: var(--t-sm); font-weight: var(--w-med); color: var(--ink-2); } .more:hover { color: var(--ink-1); } diff --git a/src/lib/__tests__/esc.test.ts b/src/lib/__tests__/esc.test.ts index 8057fd3c..0aa3c883 100644 --- a/src/lib/__tests__/esc.test.ts +++ b/src/lib/__tests__/esc.test.ts @@ -1,12 +1,12 @@ import { afterEach, describe, expect, it } from 'vitest'; import type { Plan } from '../gen/Plan'; import type { Task } from '../gen/Task'; -import { denyKeyInField, ESC_STOP_WINDOW, escStep, escStop, type EscState } from '../state/esc'; +import { denyKeyInField, ESC_STOP_WINDOW, escStep, escStop, openOne, type EscState } from '../state/esc'; import { keyTargetChanges } from '../state/keys'; import { store } from '../state/store.svelte'; import { ui } from '../state/ui.svelte'; -const home: EscState = { repeat: false, artifactOpen: false, selection: false, mode: 'blend', room: 'home', popupOpen: false, inOffice: false, findOpen: false, readingClosed: false }; +const home: EscState = { repeat: false, artifactOpen: false, selection: false, mode: 'blend', room: 'home', popupOpen: false, inOffice: false, findOpen: false, readingClosed: false, toastWaits: false }; describe('Esc outside a text field', () => { it('closes what is open first, one step per press, and only then stops the turn', () => { @@ -56,6 +56,42 @@ describe('Esc outside a text field', () => { }); }); +describe('Esc and a toast that waits for you', () => { + it('dismisses the toast first and does nothing else: the sheet, the artifact and the turn wait for the next press', () => { + expect(escStep({ ...home, toastWaits: true, selection: true })).toBe('dismiss-toast'); + expect(escStep({ ...home, toastWaits: true, artifactOpen: true })).toBe('dismiss-toast'); + expect(escStep({ ...home, toastWaits: true, mode: 'office' })).toBe('dismiss-toast'); + expect(escStep({ ...home, toastWaits: true })).toBe('dismiss-toast'); + // Once it is gone, the next press closes the sheet. + expect(escStep({ ...home, selection: true })).toBe('deselect'); + }); + + it('a dialog, a menu and the office keep their own Esc', () => { + expect(escStep({ ...home, toastWaits: true, popupOpen: true })).toBeNull(); + expect(escStep({ ...home, toastWaits: true, popupOpen: true, selection: true })).toBe('deselect'); + expect(escStep({ ...home, toastWaits: true, inOffice: true })).toBeNull(); + }); + + it('a held key dismisses no more toasts and closes nothing while one waits', () => { + expect(escStep({ ...home, toastWaits: true, repeat: true, selection: true })).toBeNull(); + }); +}); + +describe('a dialog that is closing', () => { + /** An element of the page: `closing` says whether it is inside a dialog whose close has started. */ + const el = (closing: boolean) => ({ closest: (selector: string) => (selector === '[data-closing]' && closing ? {} : null) }); + + it('is not open: an Esc while it fades out goes to what is under it', () => { + expect(openOne([el(true)])).toBe(false); + expect(openOne([])).toBe(false); + }); + + it('another dialog that is open still counts', () => { + expect(openOne([el(true), el(false)])).toBe(true); + expect(openOne([el(false)])).toBe(true); + }); +}); + describe('Esc on a running turn', () => { it('asks on the first press and stops on a second one for the same thread inside the window', () => { expect(escStop(null, 'lead', 1000)).toBe('ask'); diff --git a/src/lib/__tests__/escKeys.test.ts b/src/lib/__tests__/escKeys.test.ts new file mode 100644 index 00000000..fc07f054 --- /dev/null +++ b/src/lib/__tests__/escKeys.test.ts @@ -0,0 +1,80 @@ +// Esc through the app's key map (installKeys): a toast that waits for you goes first, and a dialog +// that is closing no longer holds the key. The page is a stand-in: the dialogs it has, and a key +// pressed outside every text field. +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { installKeys } from '../state/keys'; +import { toasts } from '../state/toasts.svelte'; +import { ui } from '../state/ui.svelte'; + +/** A part of the page; `closing`: it is inside a dialog whose close has started. */ +const part = (closing = false) => ({ closest: (selector: string) => (selector === '[data-closing]' && closing ? {} : null) }); + +let onKey: ((e: KeyboardEvent) => void) | null = null; +let modals: ReturnType[] = []; +let off: () => void = () => {}; + +/** Esc, pressed on the page's body. */ +function esc() { + const target = { tagName: 'BODY', isContentEditable: false, closest: () => null }; + onKey!({ key: 'Escape', repeat: false, metaKey: false, ctrlKey: false, altKey: false, shiftKey: false, defaultPrevented: false, target, preventDefault() {} } as unknown as KeyboardEvent); +} + +beforeEach(() => { + vi.useFakeTimers(); + vi.stubGlobal('window', { addEventListener: (_: string, fn: (e: KeyboardEvent) => void) => (onKey = fn), removeEventListener: () => (onKey = null) }); + // The modal dialogs are the only dialogs of this page. + vi.stubGlobal('document', { querySelectorAll: (selector: string) => (selector.includes('aria-modal') || selector.includes('role="dialog"') ? modals : []) }); + off = installKeys(); + ui.go('home'); + ui.mode = 'blend'; + ui.selection = { kind: 'agent', id: 'a1' }; +}); + +afterEach(() => { + off(); + for (const t of [...toasts.list]) toasts.dismiss(t.id); + ui.selection = null; + modals = []; + vi.unstubAllGlobals(); + vi.useRealTimers(); +}); + +describe('Esc with the agent sheet open', () => { + it('with an error toast: the first press closes the toast, the second the sheet', () => { + toasts.show({ kind: 'error', title: 'Couldn’t copy' }); + esc(); + expect(toasts.list).toEqual([]); + expect(ui.selection).toEqual({ kind: 'agent', id: 'a1' }); + esc(); + expect(ui.selection).toBeNull(); + }); + + it('with a success toast, which goes by itself: Esc closes the sheet and leaves the toast', () => { + toasts.show({ kind: 'success', title: 'Copied' }); + esc(); + expect(ui.selection).toBeNull(); + expect(toasts.list.map((t) => t.title)).toEqual(['Copied']); + }); + + it('with two errors: one press closes the newest only', () => { + toasts.show({ kind: 'error', title: 'Push failed' }); + toasts.show({ kind: 'error', title: 'Couldn’t copy' }); + esc(); + expect(toasts.list.map((t) => t.title)).toEqual(['Push failed']); + expect(ui.selection).not.toBeNull(); + }); +}); + +describe('Esc right after a dialog closed', () => { + it('a dialog that is closing (it fades out) does not take the key: one press closes the sheet', () => { + modals = [part(true)]; + esc(); + expect(ui.selection).toBeNull(); + }); + + it('a dialog that is open keeps its own Esc', () => { + modals = [part(false)]; + esc(); + expect(ui.selection).toEqual({ kind: 'agent', id: 'a1' }); + }); +}); diff --git a/src/lib/__tests__/toasts.test.ts b/src/lib/__tests__/toasts.test.ts index 46ab96d2..f58552b0 100644 --- a/src/lib/__tests__/toasts.test.ts +++ b/src/lib/__tests__/toasts.test.ts @@ -148,3 +148,105 @@ describe('the pointer on a toast', () => { expect(vi.getTimerCount()).toBe(0); }); }); + +describe('the same message', () => { + beforeEach(() => vi.useFakeTimers()); + afterEach(() => { + for (const t of [...toasts.list]) toasts.dismiss(t.id); + toasts.putAway([]); + vi.useRealTimers(); + }); + + it('shows once: three equal toasts are one toast with a count of 3', () => { + const first = toasts.show({ kind: 'error', title: 'Couldn’t copy', body: 'The clipboard is not available.' }); + expect(toasts.show({ kind: 'error', title: 'Couldn’t copy', body: 'The clipboard is not available.' })).toBe(first); + toasts.show({ kind: 'error', title: 'Couldn’t copy', body: 'The clipboard is not available.' }); + expect(toasts.list.map((t) => [t.title, t.count])).toEqual([['Couldn’t copy', 3]]); + }); + + it('another text, title or kind is another toast', () => { + toasts.show({ kind: 'error', title: 'Couldn’t copy', body: 'The clipboard is not available.' }); + toasts.show({ kind: 'error', title: 'Couldn’t copy', body: 'Nothing to copy.' }); + toasts.show({ kind: 'info', title: 'Couldn’t copy', body: 'Nothing to copy.' }); + expect(toasts.list.map((t) => [t.kind, t.body, t.count])).toEqual([ + ['error', 'The clipboard is not available.', 1], + ['error', 'Nothing to copy.', 1], + ['info', 'Nothing to copy.', 1], + ]); + }); + + it('keeps its place in the stack', () => { + toasts.show({ kind: 'error', title: 'Push failed' }); + toasts.show({ kind: 'error', title: 'Couldn’t copy' }); + toasts.show({ kind: 'error', title: 'Push failed' }); + expect(titles()).toEqual(['Push failed', 'Couldn’t copy']); + }); + + it('starts its time again, and takes the newest action', () => { + const run = vi.fn(); + toasts.show({ kind: 'success', title: 'Copied' }); + vi.advanceTimersByTime(3000); + toasts.show({ kind: 'success', title: 'Copied', action: { label: 'Open', run } }); + vi.advanceTimersByTime(3999); + expect(titles()).toEqual(['Copied']); + toasts.list[0].action!.run(); + expect(run).toHaveBeenCalled(); + vi.advanceTimersByTime(1); + expect(titles()).toEqual([]); + }); + + it('under the pointer its time stands still, and it gets its whole time when the pointer leaves', () => { + const id = toasts.show({ kind: 'success', title: 'Copied' }); + vi.advanceTimersByTime(3000); + toasts.pause(id); + toasts.show({ kind: 'success', title: 'Copied' }); + vi.advanceTimersByTime(60_000); + expect(titles()).toEqual(['Copied']); + toasts.resume(id); + vi.advanceTimersByTime(3999); + expect(titles()).toEqual(['Copied']); + vi.advanceTimersByTime(1); + expect(titles()).toEqual([]); + }); + + it('a progress toast is never joined: each one tells of its own work', () => { + toasts.show({ kind: 'progress', title: 'Pushing…' }); + toasts.show({ kind: 'progress', title: 'Pushing…' }); + expect(toasts.list.map((t) => t.count)).toEqual([1, 1]); + }); +}); + +describe('Dismiss all, and the toast that Esc dismisses', () => { + afterEach(() => { + for (const t of [...toasts.list]) toasts.dismiss(t.id); + toasts.putAway([]); + }); + + it('dismisses every toast but a progress toast', () => { + toasts.show({ kind: 'error', title: 'Push failed' }); + toasts.show({ kind: 'progress', title: 'Merging…' }); + toasts.show({ kind: 'info', title: 'Branch kept' }); + expect(toasts.dismissible.map((t) => t.title)).toEqual(['Push failed', 'Branch kept']); + toasts.dismissAll(); + expect(titles()).toEqual(['Merging…']); + expect(toasts.dismissible).toEqual([]); + }); + + it('Esc takes the newest toast that waits for you: an error or one with no time limit, never a progress toast', () => { + expect(toasts.waiting).toBeUndefined(); + toasts.show({ kind: 'success', title: 'Copied' }); + toasts.show({ kind: 'progress', title: 'Merging…' }); + expect(toasts.waiting).toBeUndefined(); + toasts.show({ kind: 'error', title: 'Push failed' }); + expect(toasts.waiting?.title).toBe('Push failed'); + toasts.show({ kind: 'info', title: 'Not sent', duration: 0 }); + expect(toasts.waiting?.title).toBe('Not sent'); + }); + + it('Esc does not take a toast that a folded stack has put away: it is not seen', () => { + const hidden = toasts.show({ kind: 'info', title: 'Not sent', duration: 0 }); + toasts.show({ kind: 'error', title: 'Push failed' }); + toasts.putAway([hidden]); + expect(toasts.waiting?.title).toBe('Push failed'); + }); +}); diff --git a/src/lib/state/esc.ts b/src/lib/state/esc.ts index 254db452..7c4cd07c 100644 --- a/src/lib/state/esc.ts +++ b/src/lib/state/esc.ts @@ -1,6 +1,8 @@ -// What Esc does outside a text field and outside an overlay: one step per press. It closes what -// is open first (the find bar and a closed request you are reading count); with nothing left to -// close, on Home, it stops the running turn: the first press only asks, a second press stops. +// What Esc does outside a text field and outside an overlay: one step per press. A toast that +// waits for you goes first; then it closes what is open (the find bar and a closed request you +// are reading count); with nothing left to close, on Home, it stops the running turn: the first +// press only asks, a second press stops. +import { CLOSING } from '../util/modal'; import type { Mode, Room } from './ui.svelte'; export type EscState = { @@ -18,10 +20,15 @@ export type EscState = { findOpen: boolean; /** Home shows the closed requests, not a conversation. */ readingClosed: boolean; + /** A toast that does not go by itself shows (an error, or one with no time limit). */ + toastWaits: boolean; }; -export type EscStep = 'close-artifact' | 'deselect' | 'leave-office' | 'close-find' | 'leave-closed' | 'stop'; +export type EscStep = 'dismiss-toast' | 'close-artifact' | 'deselect' | 'leave-office' | 'close-find' | 'leave-closed' | 'stop'; export function escStep(s: EscState): EscStep | null { + // The toast and nothing else. A held key dismisses no more of them: its repeats do nothing while + // one waits. A dialog, a menu and the office keep their own Esc. + if (s.toastWaits && !s.popupOpen && !s.inOffice) return s.repeat ? null : 'dismiss-toast'; if (s.artifactOpen) return 'close-artifact'; if (s.selection) return 'deselect'; if (s.mode === 'office' || s.mode === 'map') return 'leave-office'; @@ -32,6 +39,12 @@ export function escStep(s: EscState): EscStep | null { return s.repeat ? null : 'stop'; } +/** + * Is one of `found` (the page's dialogs, menus or modal layers) open? One that is closing is + * not: it fades out for a moment, and an Esc in that moment goes to what is under it. + */ +export const openOne = (found: Iterable<{ closest(selector: string): unknown }>): boolean => [...found].some((el) => !el.closest(CLOSING)); + /** How long "Press Esc again to stop …" stays, and how long a second Esc counts as its answer. */ export const ESC_STOP_WINDOW = 2000; diff --git a/src/lib/state/keys.ts b/src/lib/state/keys.ts index a72aaa70..24074627 100644 --- a/src/lib/state/keys.ts +++ b/src/lib/state/keys.ts @@ -1,17 +1,18 @@ // Global keyboard map. ⌘K palette · ⌘F find in the conversation · ⌘1 full office · ⌘2 full work · ⌘. focus · ⌘, settings · // ⌘N new request · ⌘[ / ⌘] previous / next request · ⇧⌘N new task · ⌘O open repo · ⌘↵ the one // primary action (approve / run plan) · ⌥⌘↵ allow for the session · ⌘⌫ deny · ⇧⌘⌫ deny with a -// note (both also from the empty composer; on a plan both open the note) · 1-9 pick an option of the question that waits · G-sequences to rooms · J/K lists · Esc (close, -// deselect, then stop the running turn: the first press asks, the second stops) · ?. +// note (both also from the empty composer; on a plan both open the note) · 1-9 pick an option of the question that waits · G-sequences to rooms · J/K lists · Esc (a toast that +// waits for you, close, deselect, then stop the running turn: the first press asks, the second stops) · ?. // ponytail: hand-rolled instead of tinykeys — one listener, sequences included. import type { Approval } from '../gen/Approval'; import { showsPlan } from '../util/planRequest'; import { openWorkspace, resolveApprovals, runPlan, stopThreadByEsc } from './actions'; import { twinsIn } from './approvalGroups'; import { digitPick, isTextField } from '../util/questionKeys'; -import { denyKeyInField, escStep } from './esc'; +import { denyKeyInField, escStep, openOne } from './esc'; import { requests } from './requests.svelte'; import { store } from './store.svelte'; +import { toasts } from './toasts.svelte'; import { ROOMS, isClosedThread, isRequestThread, ui, type DiffTarget, type Room } from './ui.svelte'; export type ListNav = { next: () => void; prev: () => void; open?: () => void }; @@ -115,7 +116,8 @@ export function installKeys(): () => void { const mod = e.metaKey || e.ctrlKey; const typing = isTyping(e.target); const k = e.key.toLowerCase(); - const overlay = ui.paletteOpen || ui.settingsOpen || ui.shortcutsOpen || !!document.querySelector('[aria-modal="true"]'); + // A dialog that is closing is not an overlay any more: an Esc while it fades goes to what is under it. + const overlay = ui.paletteOpen || ui.settingsOpen || ui.shortcutsOpen || openOne(document.querySelectorAll('[aria-modal="true"]')); // ── the primary action (approve / run plan) ── // Other text fields (a deny note…) are not the composer: ⌘↵ there must not approve. @@ -224,20 +226,23 @@ export function installKeys(): () => void { (e.target as HTMLElement).blur(); return; } - // One step per press: close, deselect, leave the full office, close the find bar, leave a - // closed request, and only then stop the running turn. + // One step per press: dismiss the toast that waits for you, close, deselect, leave the full + // office, close the find bar, leave a closed request, and only then stop the running turn. + const waiting = toasts.waiting; const step = escStep({ repeat: e.repeat, artifactOpen: !!ui.artifactOpen, selection: !!ui.selection, mode: ui.mode, room: ui.room, - popupOpen: !!document.querySelector('[role="dialog"], [role="menu"]'), + popupOpen: openOne(document.querySelectorAll('[role="dialog"], [role="menu"]')), inOffice: !!(e.target as HTMLElement).closest?.('[role="application"]'), findOpen: ui.findOpen, readingClosed: isClosedThread(ui.thread), + toastWaits: waiting !== undefined, }); - if (step === 'close-artifact') ui.artifactOpen = null; + if (step === 'dismiss-toast') toasts.dismiss(waiting!.id); + else if (step === 'close-artifact') ui.artifactOpen = null; else if (step === 'deselect') ui.selection = null; else if (step === 'leave-office') ui.mode = 'blend'; else if (step === 'close-find') ui.findOpen = false; @@ -315,7 +320,7 @@ export const SHORTCUTS: { group: string; items: [string, string][] }[] = [ ['⇧⌘N', 'New task'], ['⌘O', 'Open repository'], ['⌘,', 'Settings'], - ['Esc', 'Close · deselect · press twice to stop the running turn'], + ['Esc', 'Dismiss a toast that waits · close · deselect · press twice to stop the running turn'], ['?', 'This sheet'], ], }, diff --git a/src/lib/state/toasts.svelte.ts b/src/lib/state/toasts.svelte.ts index f38dfea5..df9aba74 100644 --- a/src/lib/state/toasts.svelte.ts +++ b/src/lib/state/toasts.svelte.ts @@ -1,8 +1,8 @@ // Toasts (design §4): top-right under the top bar, laid over the page at a place where they cover // nothing you can press (see components/Toasts.svelte), max 3, progress updates in place, success 4 s, info 6 s, // errors persist. Hover pauses dismissal, and so does a folded stack for the toasts it has put -// away (`putAway`): a toast does not go before it was shown. Approvals are never toast-only: an -// approval toast is just a pointer into the Inbox. +// away (`putAway`): a toast does not go before it was shown. The same message shows once, with a +// count. Approvals are never toast-only: an approval toast is just a pointer into the Inbox. export type ToastKind = 'progress' | 'success' | 'info' | 'error' | 'attention'; export type ToastAction = { label: string; run: () => void; kbd?: string }; @@ -15,6 +15,8 @@ export type Toast = { /** ms; 0 = sticky */ duration: number; createdAt: number; + /** How often this message was shown: an equal one joins the toast that shows (`show`). */ + count: number; }; const DEFAULT_DURATION: Record = { progress: 0, success: 4000, info: 6000, error: 0, attention: 8000 }; @@ -29,10 +31,22 @@ class Toasts { /** The toasts that are put away now (`putAway`): none of them counts down. */ private away = new Set(); + /** + * Shows a toast, and gives its id. A toast with the kind, the title and the text of one that + * shows is not added: that one counts it, takes its action and its time (which starts again) + * and keeps its place. A progress toast is never joined: each one tells of its own work. + */ show(t: { kind?: ToastKind; title: string; body?: string; action?: ToastAction; duration?: number }): number { const kind = t.kind ?? 'info'; + const duration = t.duration ?? DEFAULT_DURATION[kind]; + const same = kind === 'progress' ? undefined : this.list.find((x) => x.kind === kind && x.title === t.title && x.body === t.body); + if (same) { + this.list = this.list.map((x) => (x.id === same.id ? { ...x, action: t.action, duration, count: x.count + 1 } : x)); + this.restart(same.id, duration); + return same.id; + } const id = ++this.seq; - const toast: Toast = { id, kind, title: t.title, body: t.body, action: t.action, duration: t.duration ?? DEFAULT_DURATION[kind], createdAt: Date.now() }; + const toast: Toast = { id, kind, title: t.title, body: t.body, action: t.action, duration, createdAt: Date.now(), count: 1 }; const next = [...this.list, toast]; // Drop the oldest dismissible toasts beyond the cap. while (next.length > MAX) { @@ -59,6 +73,22 @@ class Toasts { this.list = this.list.filter((t) => t.id !== id); } + /** The toasts you can dismiss: all but the progress toasts, which go when their work ends. */ + get dismissible(): Toast[] { + return this.list.filter((t) => t.kind !== 'progress'); + } + + /** "Dismiss all": every toast you can dismiss goes; a progress toast stays. */ + dismissAll() { + for (const t of this.dismissible) this.dismiss(t.id); + } + + /** The newest toast that shows and waits for you (Esc dismisses it): an error, or one with no + * time limit; never a progress toast, and not one that a folded stack has put away. */ + get waiting(): Toast | undefined { + return this.dismissible.findLast((t) => (t.kind === 'error' || t.duration === 0) && !this.away.has(t.id)); + } + pause(id: number) { const timer = this.timers.get(id); if (!timer) return; @@ -88,6 +118,12 @@ class Toasts { for (const id of before) if (!this.away.has(id)) this.resume(id); } + /** Its time starts again. One that stands still now (the pointer is on it, or it is put away) gets the whole time when it goes on. */ + private restart(id: number, ms: number) { + if (ms && !this.timers.has(id) && this.remaining.has(id)) this.remaining.set(id, ms); + else this.arm(id, ms); + } + private arm(id: number, ms: number) { clearTimeout(this.timers.get(id)); this.timers.delete(id); diff --git a/src/lib/util/__tests__/toastPlace.test.ts b/src/lib/util/__tests__/toastPlace.test.ts index c15ab000..33990638 100644 --- a/src/lib/util/__tests__/toastPlace.test.ts +++ b/src/lib/util/__tests__/toastPlace.test.ts @@ -4,7 +4,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import tokens from '../../../styles/tokens.css?raw'; import toastsView from '../../../components/Toasts.svelte?raw'; -import { countedBox, counts, frontToast, grown, ms, onTop, paced, reachDown, restLook, stackPlace, toastTop, visiblePart, type Box, type Seen, type Shape } from '../toastPlace'; +import approvalCard from '../../../home/cards/ApprovalCard.svelte?raw'; +import { barRoom, countedBox, counts, covers, frontToast, grown, heightChanged, lookFor, ms, onTop, paced, reachDown, restLook, stackPlace, toastTop, visiblePart, WAITING_CARD, watchedHeight, type Box, type Seen, type Shape } from '../toastPlace'; const box = (left: number, top: number, right: number, bottom: number): Box => ({ left, top, right, bottom }); @@ -174,8 +175,8 @@ describe('stackPlace: the place, and whether the stack folds', () => { }); it('with no free place for the folded stack either, it stays folded where it last looked: a list of task rows (Home, 1440 x 900, the sheet open)', () => { - // The request tabs, the plan header, three task rows (each one button, 632 px wide: not wider - // than twice the stack, so each counts whole) and "Plan room" under them. + // The request tabs, the plan header, three task rows (as boxes that reach under the stack: a + // row whose text runs to its right end) and "Plan room" under them. const page = controls( box(452, 72, 678, 102), box(678, 77, 698, 97), box(824, 72, 854, 102), box(862, 72, 892, 102), box(204, 110, 712.4, 162), box(718.4, 125, 740.4, 147), box(736.4, 125, 758.4, 147), box(768.4, 123, 856, 149), box(868, 124, 892, 148), @@ -219,8 +220,9 @@ describe('frontToast: the one toast of a folded stack', () => { }); }); -describe('countedBox: a control much wider than the stack counts by what it shows', () => { - const STACK = 360; +describe('countedBox: a control wider than the stack counts by what it shows', () => { + /** The stack at the right of a 1440 px window, sheet closed. */ + const STACK = { left: 1066, right: 1426 }; const never = () => { throw new Error('not asked'); }; @@ -253,19 +255,41 @@ describe('countedBox: a control much wider than the stack counts by what it show expect(countedBox(box(100, 70, 900, 102), STACK, false, () => box(120, 20, 400, 60))).toBeNull(); }); - it('a control up to twice as wide as the stack counts whole: what it shows is not asked for', () => { - // A task row of Home is 632 px wide; a control of exactly twice the stack's width. - expect(countedBox(box(228, 222, 860, 302), STACK, false, never)).toEqual(box(228, 222, 860, 302)); - expect(countedBox(box(100, 70, 820, 102), STACK, false, never)).toEqual(box(100, 70, 820, 102)); + it('a task row of Home (632 px, its label at the left) beside the stack counts by its label: the stack has its free place', () => { + // The sheet open at 1440: the stack is at x 648 to 1008, the row at x 228 to 860. The stack + // could cover 212 px of the row's 632: less than half. + const sides = { left: 648, right: 1008 }; + const row = box(228, 221.9, 860, 301.9); + const label = box(268, 240, 520, 256); + expect(countedBox(row, sides, false, () => label)).toEqual(label); + const stack = box(648, 222, 1008, 285); + expect(toastTop(stack, [grown(row, 4)], 222, MOVES, REACH_900)).toBe(305.9); + expect(toastTop(stack, [grown(countedBox(row, sides, false, () => label)!, 4)], 222, MOVES, REACH_900)).toBe(222); + }); + + it('a control no wider than the stack counts whole: what it shows is not asked for', () => { + // A 300 px button under the stack. + expect(countedBox(box(900, 222, 1200, 254), STACK, false, never)).toEqual(box(900, 222, 1200, 254)); + expect(countedBox(box(1066, 70, 1426, 102), STACK, false, never)).toEqual(box(1066, 70, 1426, 102)); + }); + + it('a control wider than the stack that it could cover for half its width or more counts whole', () => { + // 600 px wide, 300 of them under the stack; 500 px wide, 360 of them under it. + expect(countedBox(box(766, 70, 1366, 102), STACK, false, never)).toEqual(box(766, 70, 1366, 102)); + expect(countedBox(box(950, 70, 1450, 102), STACK, false, never)).toEqual(box(950, 70, 1450, 102)); + // 600 px wide, 299 of them under it: by what it shows. + expect(countedBox(box(765, 70, 1365, 102), STACK, false, () => null)).toBeNull(); }); it('a field you type in counts whole, however wide: its text can be anywhere in it', () => { expect(countedBox(box(100, 70, 1100, 104), STACK, true, never)).toEqual(box(100, 70, 1100, 104)); }); - it('follows the stack’s width: a narrow window has a narrower stack', () => { - // The stack is 300 px wide: a 632 px row is wider than twice of it. - expect(countedBox(box(10, 222, 642, 302), 300, false, () => box(24, 240, 200, 256))).toEqual(box(24, 240, 200, 256)); + it('follows the stack’s place and width: a narrow window has a narrower stack', () => { + // The stack is 300 px wide at the right of the row: it could cover 200 px of the 632. + expect(countedBox(box(10, 222, 642, 302), { left: 442, right: 742 }, false, () => box(24, 240, 200, 256))).toEqual(box(24, 240, 200, 256)); + // The same stack over the row's middle could cover 300 px of it, not half: by what it shows too. + expect(countedBox(box(10, 222, 642, 302), { left: 100, right: 400 }, false, () => box(24, 240, 200, 256))).toEqual(box(24, 240, 200, 256)); }); }); @@ -376,10 +400,130 @@ describe('restLook: the look when the page has come to rest', () => { }); describe('grown', () => { - it('keeps a gap around a control: "+" is 3 px left of the stack, and counts with a 4 px gap', () => { + it('keeps a gap around a control, and a few pixels at an edge are not covering', () => { const plus = box(1033, 72, 1063, 102); expect(grown(plus, 4)).toEqual(box(1029, 68, 1067, 106)); - expect(toastTop(box(1066, 68, 1426, 131), [grown(plus, 4)], TOP, MOVES, REACH_900)).toBe(106); + // "+" ends 3 px left of the stack: with the gap the stack is 1 px over it, which is not covering. + expect(toastTop(box(1066, 68, 1426, 131), [grown(plus, 4)], TOP, MOVES, REACH_900)).toBe(68); + // A control that reaches 4 px under the stack: 8 px with the gap, it covers. + const tab = box(1033, 72, 1070, 102); + expect(toastTop(box(1066, 68, 1426, 131), [grown(tab, 4)], TOP, MOVES, REACH_900)).toBe(106); + }); +}); + +describe('covers: a few pixels are not covering', () => { + const stack = box(1066, 106, 1426, 169); + + it('needs 8 px of overlap on both axes', () => { + expect(covers(box(1000, 100, 1074, 200), stack)).toBe(true); + expect(covers(box(1000, 100, 1073, 200), stack)).toBe(false); + expect(covers(box(1100, 161, 1200, 200), stack)).toBe(true); + expect(covers(box(1100, 162, 1200, 200), stack)).toBe(false); + }); + + it('measured: a 3 px overlap with Home’s task rows does not send a single toast 300 px down (1440 x 900)', () => { + // The request tabs, and three task rows whose right end is 3 px under the stack (7 px with the gap). + const tabs = [box(1033, 72, 1063, 102), box(1071, 72, 1101, 102)].map((c) => grown(c, 4)); + const rows = [0, 1, 2].map((i) => grown(box(437, 160 + i * 82, 1069, 240 + i * 82), 4)); + const one = { height: 63, reach: reachDown(900, 0.4, TOP, 63, 12) }; + // The rows only touched the stack: before, it went down row by row. + expect(rows.some((r) => r.left < 1426 && 1066 < r.right && r.top < 169 && 106 < r.bottom)).toBe(true); + expect(stackPlace({ left: 1066, right: 1426 }, one, null, [...tabs, ...rows], TOP, MOVES)).toEqual({ top: 106, folded: false }); + }); +}); + +describe('stackPlace with a place to keep: a dismissal moves nothing', () => { + const sides = { left: 1066, right: 1426 }; + const shape = (height: number): Shape => ({ height, reach: reachDown(900, 0.4, TOP, height, 12) }); + /** A control that three toasts reach and one toast does not. */ + const low = grown(box(1100, 190, 1200, 220), 4); + + it('three toasts go under the control; when two go, the one that stays keeps its place', () => { + expect(stackPlace(sides, shape(151), shape(75), [low], TOP, MOVES)).toEqual({ top: 224, folded: false }); + // Looked for anew (a new toast, a change of layout) one toast would be at the top bar. + expect(stackPlace(sides, shape(45), null, [low], TOP, MOVES)).toEqual({ top: 68, folded: false }); + expect(stackPlace(sides, shape(45), null, [low], TOP, MOVES, 224)).toEqual({ top: 224, folded: false }); + }); + + it('it moves when it would cover something where it is, or is further down than it may be', () => { + const below = grown(box(1100, 240, 1200, 260), 4); + expect(stackPlace(sides, shape(45), null, [low, below], TOP, MOVES, 224)).toEqual({ top: 68, folded: false }); + // 68 + 360 is as far as it may go. + expect(stackPlace(sides, shape(45), null, [], TOP, MOVES, 429)).toEqual({ top: 68, folded: false }); + expect(stackPlace(sides, shape(45), null, [], TOP, MOVES, 428)).toEqual({ top: 428, folded: false }); + }); + + it('a folded stack that fits whole where it is shows whole there', () => { + expect(stackPlace(sides, shape(98), shape(75), [low], TOP, MOVES, 224)).toEqual({ top: 224, folded: false }); + }); +}); + +describe('lookFor: may the stack move now?', () => { + it('a new toast, or a change of the window or the page’s layout: it looks from the top bar down, also under your hand', () => { + expect(lookFor('added', false)).toBe('fresh'); + expect(lookFor('added', true)).toBe('fresh'); + expect(lookFor('layout', false)).toBe('fresh'); + expect(lookFor('layout', true)).toBe('fresh'); + }); + + it('a toast that went or joined another, or what arrived in the page: it keeps its place while that is free', () => { + expect(lookFor('changed', false)).toBe('keep'); + expect(lookFor('page', false)).toBe('keep'); + }); + + it('while the pointer is on it or the focus is in it, that waits until you leave it', () => { + expect(lookFor('changed', true)).toBe('wait'); + expect(lookFor('page', true)).toBe('wait'); + }); +}); + +describe('barRoom: the room for the Resume bar follows the bar on screen', () => { + it('is kept while the bar is offered and shows', () => { + expect(barRoom(true, false, 70)).toBe(70); + }); + + it('is not kept with no bar, or while the editor overlay is drawn over the bar', () => { + expect(barRoom(false, false, 70)).toBe(0); + expect(barRoom(true, true, 70)).toBe(0); + }); +}); + +describe('contentWatch: what counts as a change of height', () => { + it('the first report of a box is not a change: it is only its size', () => { + expect(heightChanged(watchedHeight(120), 120)).toBe(false); + expect(heightChanged(watchedHeight(120), 300)).toBe(false); + }); + + it('a box that was 0 px high when it was watched: its first report is its growth, a change', () => { + expect(watchedHeight(0)).toBe(0); + expect(heightChanged(watchedHeight(0), 180)).toBe(true); + expect(heightChanged(watchedHeight(0), 0)).toBe(false); + }); + + it('a later report is a change when the height is another', () => { + expect(heightChanged(300, 300)).toBe(false); + expect(heightChanged(300, 340)).toBe(true); + }); +}); + +describe('a card that waits for your answer counts whole', () => { + it('the selector finds the waiting card of ApprovalCard.svelte: "Waiting since" in its header', () => { + expect(WAITING_CARD).toContain('article.card'); + expect(approvalCard).toMatch(/
      ]*>\s*
      [\s\S]*?([\s\S]*?)\n {6}<\/div>/.exec(toastsView); + expect(column?.[1]).toContain('t.action.label'); + }); }); diff --git a/src/lib/util/modal.ts b/src/lib/util/modal.ts index 4d12ede6..a1b773c2 100644 --- a/src/lib/util/modal.ts +++ b/src/lib/util/modal.ts @@ -5,6 +5,9 @@ // once the build targets Safari 17 (before that the top layer hides toasts, tooltips and menus). import { on } from 'svelte/events'; +/** What a closing dialog carries from the moment its close starts (components/Dialog.svelte). */ +export const CLOSING = '[data-closing]'; + const TABBABLE = 'a[href], button, input, select, textarea, summary, [tabindex]'; export function modal(node: HTMLElement, onclose: () => void) { @@ -12,8 +15,11 @@ export function modal(node: HTMLElement, onclose: () => void) { if (!node.hasAttribute('tabindex')) node.tabIndex = -1; if (!node.contains(prev)) node.focus(); const stops = () => [...node.querySelectorAll(TABBABLE)].filter((el) => el.tabIndex >= 0 && !el.matches(':disabled') && el.getClientRects().length); + // A dialog that is closing (it fades out) takes no key: an Esc then goes to what is under it. + const closing = () => !!node.closest(CLOSING); // `on`, not addEventListener: a field inside that handles its own Esc still goes first. const off = on(node, 'keydown', (e) => { + if (closing()) return; if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); @@ -30,7 +36,7 @@ export function modal(node: HTMLElement, onclose: () => void) { // The focused control can go away (a button swapped for its confirm): focus is then on // and no key reaches the node. The dialog on top still closes on Esc and takes Tab back in. const offDoc = on(document, 'keydown', (e) => { - if ((e.key !== 'Escape' && e.key !== 'Tab') || node.contains(document.activeElement)) return; + if ((e.key !== 'Escape' && e.key !== 'Tab') || node.contains(document.activeElement) || closing()) return; const open = document.querySelectorAll('[aria-modal="true"]'); if (open[open.length - 1] !== node) return; e.preventDefault(); diff --git a/src/lib/util/toastPlace.ts b/src/lib/util/toastPlace.ts index d99e6fce..af072916 100644 --- a/src/lib/util/toastPlace.ts +++ b/src/lib/util/toastPlace.ts @@ -8,6 +8,17 @@ export type Box = { left: number; top: number; right: number; bottom: number }; /** Do the two boxes share an area? Boxes that only touch do not. */ const overlap = (a: Box, b: Box): boolean => a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom; +/** Less than this many px of overlap, on either axis, is not covering (see `covers`). */ +const MIN_COVER = 8; + +/** + * Does the stack's `box` cover the control `c`? Only when they share at least `MIN_COVER` px on + * both axes: a few pixels at an edge leave the control free to press. The controls come with the + * gap kept around them (`grown`, 4 px), so the stack then lies less than 4 px over the control itself. + */ +export const covers = (c: Box, box: Box): boolean => + Math.min(c.right, box.right) - Math.max(c.left, box.left) >= MIN_COVER && Math.min(c.bottom, box.bottom) - Math.max(c.top, box.top) >= MIN_COVER; + /** * The top edge of the toast stack, in px from the window's top. * @@ -26,7 +37,7 @@ export function toastTop(stack: Box, controls: Box[], top: number, maxMoves: num let at = top; for (let moves = 0; ; moves++) { const box: Box = { left: stack.left, right: stack.right, top: at, bottom: at + height }; - const under = controls.filter((c) => overlap(c, box)); + const under = controls.filter((c) => covers(c, box)); if (!under.length || moves === maxMoves) return at; const reachable = under.map((c) => c.bottom).filter((bottom) => bottom <= top + maxDistance); if (!reachable.length) return at; @@ -45,12 +56,20 @@ export type Shape = { height: number; reach: number }; * looks for a place the same way. With no free place for it either it stays folded at the last * place it tried: it covers less than the whole stack would. `folded` is the shape of the folded * stack, null for a stack that cannot fold (one toast). + * + * `stay`: the top the stack has now, when it may keep it (`lookFor` said 'keep': a toast went or + * changed, nothing of the page's layout moved). The whole stack stays there while it is free there + * and within its reach: the toasts that stay do not move. Null: it looks from the top bar down. */ -export function stackPlace(sides: { left: number; right: number }, whole: Shape, folded: Shape | null, controls: Box[], top: number, maxMoves: number): { top: number; folded: boolean } { +export function stackPlace(sides: { left: number; right: number }, whole: Shape, folded: Shape | null, controls: Box[], top: number, maxMoves: number, stay: number | null = null): { top: number; folded: boolean } { + const freeAt = (at: number, shape: Shape) => { + const box: Box = { ...sides, top: at, bottom: at + shape.height }; + return !controls.some((c) => covers(c, box)); + }; + if (stay !== null && stay >= top && stay - top <= whole.reach && freeAt(stay, whole)) return { top: stay, folded: false }; const look = (shape: Shape) => { const at = toastTop({ ...sides, top, bottom: top + shape.height }, controls, top, maxMoves, shape.reach); - const box: Box = { ...sides, top: at, bottom: at + shape.height }; - return { at, free: !controls.some((c) => overlap(c, box)) }; + return { at, free: freeAt(at, shape) }; }; const all = look(whole); if (all.free || !folded) return { top: all.at, folded: false }; @@ -113,19 +132,60 @@ export const counts = (c: Seen): boolean => !c.inStack && !c.above && !c.disable /** * The box a control counts with, null when it does not count. * - * A control that is wider than twice the stack can never be more than half under it. It counts - * by what it shows: `content()` gives the smallest box around its text and its pictures, null - * when it shows nothing of its own (the press area that lies over a whole row). So a toast at - * the right stays at the top over a whole-width row whose label is at the left. Any narrower - * control counts with its whole box (`part`: the part of it that shows), and so does a field you - * type in: its text can be anywhere in it. + * A control that is wider than the stack, and that the stack could cover for less than half of + * its width (`sides`: the stack's left and right edge), counts by what it shows: `content()` + * gives the smallest box around its text and its pictures, null when it shows nothing of its own + * (the press area that lies over a whole row). So a toast at the right stays at the top over a + * whole-width row whose label is at the left (a task row of Home, 632 px wide). Any other control + * counts with its whole box (`part`: the part of it that shows), and so does a field you type in: + * its text can be anywhere in it. */ -export function countedBox(part: Box, stackWidth: number, field: boolean, content: () => Box | null): Box | null { - if (field || part.right - part.left <= 2 * stackWidth) return part; +export function countedBox(part: Box, sides: { left: number; right: number }, field: boolean, content: () => Box | null): Box | null { + const width = part.right - part.left; + const under = Math.min(part.right, sides.right) - Math.max(part.left, sides.left); + if (field || width <= sides.right - sides.left || 2 * under >= width) return part; const shown = content(); return shown && visiblePart(shown, [part]); } +/** + * What a change asks of the stack: 'fresh', look for its place from the top bar down; 'keep', + * keep the place it has while that is free (`stackPlace`'s `stay`); 'wait', no look now, one + * when you stop working on the stack. + * + * 'layout': the page's layout or the window changed: its boxes moved, the place is looked for anew. + * 'added': a new toast came: a new stack, it goes to the place a stack of its size has. + * 'changed': a toast went, joined an equal one or changed its text, or the stack folded or unfolded. + * 'page': what is in the page's main column got higher or lower. + * `working`: the pointer is on the stack or the keyboard's focus is in it: the stack does not + * move under your hand for a change of its own content or of the page's. + */ +export type StackChange = 'layout' | 'added' | 'changed' | 'page'; +export function lookFor(change: StackChange, working: boolean): 'fresh' | 'keep' | 'wait' { + if (change === 'layout' || change === 'added') return 'fresh'; + return working ? 'wait' : 'keep'; +} + +/** + * The room kept over the stack for the Resume bar, in px: `room` while the bar is offered and + * shows. The editor overlay is drawn over the bar: while it is open the stack starts at its usual place. + */ +export const barRoom = (offered: boolean, ideOpen: boolean, room: number): number => (offered && !ideOpen ? room : 0); + +/** + * Is a report of a watched box a change of its height (`contentWatch`)? `before`: the height of + * its last report (`watchedHeight` before the first one); undefined: none to compare with. + */ +export const heightChanged = (before: number | undefined, now: number): boolean => before !== undefined && before !== now; + +/** + * The height a box is known to have when the watch starts, given its height on screen then. A + * box that is 0 px high may get no first report (a ResizeObserver need not report it before it + * grows), so its first report can be its growth: a card that arrives in an empty list is a change. Any other + * box: unknown until its first report, which is only its size then, not a change. + */ +export const watchedHeight = (heightNow: number): number | undefined => (heightNow === 0 ? 0 : undefined); + /** * Is `el` what a press at a point reaches? `hits` is everything at that point, the topmost * first (document.elementsFromPoint). What is `aside` is left out: the toast stack itself (the @@ -202,6 +262,12 @@ export function restLook(wait: () => number, look: () => void): { after(moved: b /** What you press or type in: a toast must not lie on one of these. */ const CONTROLS = 'button, a[href], input, select, textarea, [role="button"], [role="link"], [role="tab"], [role="switch"]'; +/** + * An approval or question card that waits for your answer (home/cards/ApprovalCard.svelte: the + * card with "Waiting since" in its header; an answered one is a row, not a card). A toast keeps + * off the whole card: who asks, what and why are read before a button is pressed. + */ +export const WAITING_CARD = 'article.card:has(> header > .since[data-tip^="Waiting since"])'; const boxOf = (el: Element): Box => { const r = el.getBoundingClientRect(); @@ -284,15 +350,17 @@ function contentBox(el: Element): Box | null { /** * The boxes of the page's controls that show inside `area` and that a toast must keep off - * (see `counts`). A box is the part of the control that shows: not what is scrolled out of its - * list or lies outside the window. A control much wider than the stack counts by what it shows - * (see `countedBox`). + * (see `counts`), and those of the cards that wait for your answer (`WAITING_CARD`). A box is the + * part that shows: not what is scrolled out of its list or lies outside the window. A control + * much wider than the stack counts by what it shows (see `countedBox`); a waiting card counts whole. */ export function controlBoxes(stack: HTMLElement, area: Box): Box[] { const above = layers(stack); - const stackWidth = stack.offsetWidth; + const own = stack.getBoundingClientRect(); + const sides = { left: own.left, right: own.right }; + const cards = new Set(document.querySelectorAll(WAITING_CARD)); const boxes: Box[] = []; - for (const el of document.querySelectorAll(CONTROLS)) { + for (const el of [...document.querySelectorAll(CONTROLS), ...cards]) { const box = boxOf(el); if (!overlap(box, area)) continue; const part = visiblePart(box, [windowBox(), ...clips(el)]); @@ -307,7 +375,7 @@ export function controlBoxes(stack: HTMLElement, area: Box): Box[] { onTop: reached(el, part, stack, above), }; if (!counts(seen)) continue; - const counted = countedBox(part, stackWidth, el.matches(FIELDS), () => contentBox(el)); + const counted = cards.has(el) ? part : countedBox(part, sides, el.matches(FIELDS), () => contentBox(el)); if (counted && overlap(counted, area)) boxes.push(counted); } return boxes; @@ -326,7 +394,7 @@ function scrollBoxes(el: Element, out: Element[]) { * card that arrives, rows that load. A control can then be under a toast that was put there * before. It watches the boxes that scroll in each `main` of the page and what is in them * (`scrollBoxes`), and calls `changed` when the height of one changes. Not when one is seen for - * the first time, and not when the page scrolls. + * the first time (unless it was 0 px high then: `watchedHeight`), and not when the page scrolls. * * `look()` reads the page again (after a change of layout other boxes scroll); `stop()` ends * the watch. @@ -337,9 +405,8 @@ export function contentWatch(changed: () => void): { look(): void; stop(): void const observer = new ResizeObserver((entries) => { let any = false; for (const entry of entries) { - const before = heights.get(entry.target); const now = entry.contentRect.height; - if (before !== undefined && before !== now) any = true; + if (heightChanged(heights.get(entry.target), now)) any = true; heights.set(entry.target, now); } if (any) changed(); @@ -356,7 +423,7 @@ export function contentWatch(changed: () => void): { look(): void; stop(): void } for (const el of now) { if (heights.has(el)) continue; - heights.set(el, undefined); + heights.set(el, watchedHeight(el.getBoundingClientRect().height)); observer.observe(el); } }, From d054d3d2a42885a2e27acb292c06f0771203f5d5 Mon Sep 17 00:00:00 2001 From: julienwuthrich-ant Date: Mon, 23 Nov 2026 13:56:12 -0800 Subject: [PATCH 043/120] Approvals: long lines answer at once, and daily runner lines get the right label A line whose commands start many others was read in full, so a few KB could hold an agent's events for seconds. Several labels were also wrong: a path such as tests/docker behind uv/bundle counted as a program, the options of yarn's foreach and of the program behind pnpm/yarn exec counted as the package manager's own, mvn/gradle with clean asked in Balanced, a command run by find -exec could still be offered as a rule, and uv run env offered a prefix that covers any program. - A line whose commands start more than 24 others (through runners, shells, find -exec and nested lines) is not read further: it asks as "runs dynamic code" and offers no rule. - Behind uv, poetry, bundle and the like, a path counts by its last part only where a program stands; elsewhere only a bare name counts. Shells, rm, curl, wget, npx and sudo are now read by name there too. - pnpm/yarn exec: only the runner's own options are read for -p/-c; behind yarn workspaces foreach, only those after exec. npm unchanged. - mvn/gradle: one clean before one check is a test run. - find: every -exec/-execdir/-ok command is read, behind a wrapper too, and the own-account check follows it. - No prefix rule when a wrapper or shell follows a runner. Co-Authored-By: Claude Fable 5.2 --- .../codly-core/src/orchestrator/approvals.rs | 297 ++++++++++++++---- .../tests/orchestrator_approvals.rs | 68 ++-- 2 files changed, 287 insertions(+), 78 deletions(-) diff --git a/crates/codly-core/src/orchestrator/approvals.rs b/crates/codly-core/src/orchestrator/approvals.rs index 52b1ca2b..70bc2f3d 100644 --- a/crates/codly-core/src/orchestrator/approvals.rs +++ b/crates/codly-core/src/orchestrator/approvals.rs @@ -222,7 +222,7 @@ pub fn rule_offer(a: &Approval, ctx: &PolicyCtx) -> ApprovalRuleOffer { let download = detected.iter().any(|r| r == PACKAGE_INSTALL || r == NPX_DOWNLOAD) && !detected.iter().any(|r| r == "network"); let by_prefix = |r: &String| [PACKAGE_INSTALL, NPX_DOWNLOAD, GIT_WRITE].contains(&r.as_str()) || (r == "network" && download); let by_exact = |r: &String| r == "network" || by_prefix(r); - if !a.risks.iter().chain(&detected).all(by_exact) || own_account(command, 0) || checkout_loss(&a.subject, ctx).is_some() { + if !a.risks.iter().chain(&detected).all(by_exact) || own_account(command) || checkout_loss(&a.subject, ctx).is_some() { return none; } let prefix = if a.risks.iter().chain(&detected).all(by_prefix) { rule_prefix(command) } else { None }; @@ -266,11 +266,19 @@ const OWN_ACCOUNT: &[&str] = &["config", "login", "logout", "publish"]; /// Does the line run one of the `OWN_ACCOUNT` subcommands (`cargo login x`, /// `npm config set …`, `npm c set …`, `git config …`), behind a wrapper or `sh -c` too, and /// behind a program that starts another (`pnpm exec git config …`, `npx -c 'git config …'`, -/// `uv run git config …`)? -fn own_account(cmd: &str, depth: u8) -> bool { +/// `uv run git config …`)? A line that starts more commands than `MAX_STARTED` is not read to +/// the end and gets yes, so nothing is offered for it, as `command_risks` says "runs dynamic +/// code" for it. +fn own_account(cmd: &str) -> bool { + line_own_account(cmd, 0, &mut 0) +} + +/// `own_account` for a line that stands `depth` lines deep, with the count of the commands +/// that the line around it started already. +fn line_own_account(cmd: &str, depth: u8, started: &mut usize) -> bool { parse(cmd).segments.iter().any(|seg| { let texts: Vec = seg.iter().map(|w| w.text.clone()).collect(); - runs_own_account(&texts, depth) + runs_own_account(&texts, depth, started) }) } @@ -281,9 +289,9 @@ fn own_account(cmd: &str, depth: u8) -> bool { /// the same part is found again behind each program in front of it (`uv run uv run uv run x`: /// the last `uv run x` behind the first `uv` and behind the second), so the work stays small /// on a long line, as in `command_risks`. -fn runs_own_account(words: &[String], depth: u8) -> bool { +fn runs_own_account(words: &[String], depth: u8, started: &mut usize) -> bool { // Deeper than this, `command_risks` says "runs dynamic code": nothing is offered. - let line = |inner: &str| depth < 3 && own_account(inner, depth + 1); + let line = |inner: &str, started: &mut usize| depth < 3 && (one_more(started) || line_own_account(inner, depth + 1, started)); // The commands to read, and where each one stands in `words` (the same place is the same // command). let mut commands = vec![words]; @@ -295,7 +303,7 @@ fn runs_own_account(words: &[String], depth: u8) -> bool { let Some((prog, args)) = command[start..].split_first() else { continue }; let prog = basename(prog); if classify::SHELLS.contains(&prog) { - if matches!(classify::shell_run(args), ShellRun::Command(inner) if line(inner)) { + if matches!(classify::shell_run(args), ShellRun::Command(inner) if line(inner, started)) { return true; } continue; @@ -305,15 +313,18 @@ fn runs_own_account(words: &[String], depth: u8) -> bool { if SUBCOMMAND_TOOLS.contains(&prog) && subs.iter().any(|sub| OWN_ACCOUNT.contains(sub) || names_config(prog, sub)) { return true; } - for started in started_by(prog, args) { - match started { + for next in started_by(prog, args) { + match next { Started::Program(next) => { if places.insert(std::ptr::from_ref(next)) { + if one_more(started) { + return true; + } commands.push(next); } } Started::ShellLine(inner) => { - if line(&inner) { + if line(&inner, started) { return true; } } @@ -381,7 +392,9 @@ fn rule_prefix(cmd: &str) -> Option { // A program with subcommands of its own, started by another (`pnpm exec npm …`, // `uv run cargo …`): these words would cover everything it can do, which the prefix // of the plain command (`npm install`) never does. - if starts_a_program(&prefix) && SUBCOMMAND_TOOLS.contains(&next) { + // The same for a wrapper or a shell that starts yet another program (`uv run env …`, + // `poetry run nice …`, `uv run sh …`): only the exact command is offered. + if starts_a_program(&prefix) && (SUBCOMMAND_TOOLS.contains(&next) || classify::is_wrapper(next) || classify::SHELLS.contains(&next)) { return None; } prefix.push(next); @@ -1128,21 +1141,29 @@ fn runner_commands<'a>(prog: &str, args: &'a [String]) -> Vec> { } } -/// The words of an `exec` line among which a `-c` is the package manager's own and makes it -/// run a line in a shell (`call_flag`). `rest` are the words after `exec`. +/// The words of an `exec` line that are the package manager's own: among them a `-c` makes it +/// run a line in a shell (`call_flag`), and a `-p` / `--package` adds a package +/// (`package_flag`). `rest` are the words after `exec`. /// - npm reads the options of the whole line as its own, behind the program too, up to a /// `--`: `npm exec eslint -c x.json` runs `x.json` as a line for a shell. /// - pnpm, yarn and bun give the words behind the program to that program -/// (`pnpm exec eslint -c x.json`): theirs are the words before `exec` and, after it, the -/// runner's own options (`runner_starts`). +/// (`pnpm exec eslint -c x.json`, `pnpm exec tsc -p tsconfig.json`): theirs are the words +/// before `exec` and, after it, the runner's own options (`runner_starts`). +/// - Behind `yarn workspaces foreach`, the options before `exec` are those of `foreach` +/// (`-p` runs in parallel): only the runner's own options after `exec` are read. /// -/// From the documentation of the CLIs (`npm exec`, "npx vs npm exec"; `pnpm exec`), not from -/// a recording. -fn exec_options<'a>(prog: &str, args: &'a [String], rest: &[String]) -> &'a [String] { +/// From the documentation of the CLIs (`npm exec`, "npx vs npm exec"; `pnpm exec`; +/// `yarn workspaces foreach`), not from a recording. +fn exec_options<'a>(prog: &str, args: &'a [String], rest: &'a [String]) -> &'a [String] { if prog == "npm" { return args; } - &args[..args.len() - rest.len() + runner_starts(rest, false).1] + let own = runner_starts(rest, false).1; + let before = &args[..args.len() - rest.len()]; + if prog == "yarn" && before.windows(2).any(|w| w[0] == "workspaces" && w[1] == "foreach") { + return &rest[..own]; + } + &args[..before.len() + own] } /// Programs that start another program in the project's environment (`uv run pytest`, @@ -1153,8 +1174,13 @@ fn exec_options<'a>(prog: &str, args: &'a [String], rest: &[String]) -> &'a [Str const ENV_RUNNERS: &[&str] = &["uv", "poetry", "pipenv", "pdm", "hatch", "rye", "conda", "mise", "bundle"]; /// The programs that are read by their name behind one of `ENV_RUNNERS`: the package -/// managers, the programs that publish, git, and the command lines of GitHub and Docker. -const READ_BY_NAME: &[&str] = &["npm", "pnpm", "yarn", "bun", "cargo", "pip", "pip3", "uv", "poetry", "twine", "gem", "git", "gh", "docker"]; +/// managers and runners, the programs that publish, git, the command lines of GitHub and +/// Docker, the shells (their `-c` line is read as a line inside the line), `rm`, the +/// programs that fetch from the network, and `sudo`. +const READ_BY_NAME: &[&str] = &[ + "npm", "pnpm", "yarn", "bun", "npx", "cargo", "pip", "pip3", "uv", "poetry", "twine", "gem", "git", "gh", "docker", "sh", "bash", "zsh", "dash", + "rm", "curl", "wget", "sudo", +]; /// The commands that may stand behind one of `ENV_RUNNERS`: after its `run` or `exec` (for /// mise also `x`), every word that names one of `READ_BY_NAME` may be the program it starts, @@ -1162,23 +1188,69 @@ const READ_BY_NAME: &[&str] = &["npm", "pnpm", "yarn", "bun", "cargo", "pip", "p /// risks of all of them. A word that only looks like a program (`uv run pytest -k docker`) /// asks once too often. The names of these subcommands are from the documentation of the /// CLIs, not from a recording. +/// +/// A path counts by its last part only where a program may stand (`uv run ./bin/docker ps`): +/// the first word after `run`, a word behind the runner's own options (`runner_starts`), and +/// the word right after a `--`, a wrapper or a `NAME=value` (`uv run env CI=1 ./bin/npm …`). +/// Elsewhere a path is an argument of the program (`uv run pytest tests/docker`), and only a +/// bare name counts. fn env_runner_commands<'a>(prog: &str, args: &'a [String]) -> Vec<&'a [String]> { if !ENV_RUNNERS.contains(&prog) { return vec![]; } let runs = |word: &String| matches!(word.as_str(), "run" | "exec") || (prog == "mise" && word == "x"); let Some(run) = args.iter().position(runs) else { return vec![] }; - (run + 1..args.len()).filter(|&at| READ_BY_NAME.contains(&basename(&args[at]))).map(|at| &args[at..]).collect() + let program_places: HashSet = runner_starts(&args[run + 1..], false) + .0 + .into_iter() + .filter_map(|started| match started { + Started::Program(command) => Some(args.len() - command.len()), + Started::ShellLine(_) => None, + }) + .collect(); + let program_place = |at: usize| { + let before = args[at - 1].as_str(); + program_places.contains(&at) || before == "--" || classify::is_wrapper(before) || classify::is_assignment(before) + }; + let names_a_program = |at: usize| { + let word = args[at].as_str(); + let name = if program_place(at) { basename(word) } else if word.contains('/') { return false } else { word }; + READ_BY_NAME.contains(&name) + }; + (run + 1..args.len()).filter(|&at| names_a_program(at)).map(|at| &args[at..]).collect() +} + +/// The commands `find` runs for the files it finds: what follows each of its `-exec`, +/// `-execdir`, `-ok` and `-okdir`. +fn find_commands(args: &[String]) -> impl Iterator { + let runs = |word: &String| ["-exec", "-execdir", "-ok", "-okdir"].contains(&word.as_str()); + (0..args.len()).filter(move |&at| runs(&args[at]) && at + 1 < args.len()).map(move |at| &args[at + 1..]) } -/// Every command a program starts: what a package runner starts (`runner_commands`), and what -/// may stand behind another runner (`env_runner_commands`). +/// Every command a program starts: what a package runner starts (`runner_commands`), what may +/// stand behind another runner (`env_runner_commands`), and what `find` runs +/// (`find_commands`). fn started_by<'a>(prog: &str, args: &'a [String]) -> Vec> { let mut started = runner_commands(prog, args); started.extend(env_runner_commands(prog, args).into_iter().map(Started::Program)); + if prog == "find" { + started.extend(find_commands(args).map(Started::Program)); + } started } +/// The most commands that the commands of one line may start, counted over the whole line: +/// through package runners and other runners, shells, `find -exec`, and the lines inside the +/// line. A daily line starts a few. A line that starts more is not read further: it asks as +/// "runs dynamic code" and offers no rule, so the time a line takes to read stays small. +const MAX_STARTED: usize = 24; + +/// Counts one more started command: true when the line has started more than `MAX_STARTED`. +fn one_more(started: &mut usize) -> bool { + *started += 1; + *started > MAX_STARTED +} + /// Is this word the `config` subcommand of the program? npm and pnpm also call it `c`. fn names_config(prog: &str, word: &str) -> bool { word == "config" || (word == "c" && matches!(prog, "npm" | "pnpm")) @@ -1300,7 +1372,7 @@ fn program_outside(w: &Word, base: Option<&Path>, root: Option<&Path>) -> bool { } fn command_risks(cmd: &str, cwd: Option<&Path>, worktree: Option<&Path>, depth: u8) -> Vec { - line_risks(cmd, cwd, worktree, depth, &mut InnerLines::new()) + line_risks(cmd, cwd, worktree, depth, &mut LineReading::default()) } /// The risks of the lines that stand inside one command line (`sh -c '…'`, `bun exec '…'`), @@ -1309,19 +1381,28 @@ fn command_risks(cmd: &str, cwd: Option<&Path>, worktree: Option<&Path>, depth: /// and that rest holds the next one again); it is read once. type InnerLines = HashMap<(String, u8), Vec>; +/// What is kept while one command line is read, the lines inside it included: those lines +/// read already (`InnerLines`), and how many commands its commands have started +/// (`MAX_STARTED`). +#[derive(Default)] +struct LineReading { + inner: InnerLines, + started: usize, +} + /// `line_risks` of a line inside the line, read once for each depth it stands at. -fn inner_risks(line: &str, cwd: Option<&Path>, worktree: Option<&Path>, depth: u8, inner: &mut InnerLines) -> Vec { +fn inner_risks(line: &str, cwd: Option<&Path>, worktree: Option<&Path>, depth: u8, reading: &mut LineReading) -> Vec { let key = (line.to_string(), depth); - if let Some(risks) = inner.get(&key) { + if let Some(risks) = reading.inner.get(&key) { return risks.clone(); } - let risks = line_risks(line, cwd, worktree, depth, inner); - inner.insert(key, risks.clone()); + let risks = line_risks(line, cwd, worktree, depth, reading); + reading.inner.insert(key, risks.clone()); risks } -/// `command_risks`, with the lines inside the line that were read already (`InnerLines`). -fn line_risks(cmd: &str, cwd: Option<&Path>, worktree: Option<&Path>, depth: u8, inner: &mut InnerLines) -> Vec { +/// `command_risks`, with what was kept while the line around it was read (`LineReading`). +fn line_risks(cmd: &str, cwd: Option<&Path>, worktree: Option<&Path>, depth: u8, reading: &mut LineReading) -> Vec { let p = parse(cmd); let mut risks = vec![]; let mut add = |r: &str| { @@ -1348,7 +1429,8 @@ fn line_risks(cmd: &str, cwd: Option<&Path>, worktree: Option<&Path>, depth: u8, } // Where the next simple command runs: `cd` moves it. let mut dir = base.map(Path::to_path_buf); - for seg in &p.segments { + // Left at once when the line starts more commands than `MAX_STARTED`. + 'segments: for seg in &p.segments { let texts: Vec = seg.iter().map(|w| w.text.clone()).collect(); let start = classify::command_start(&texts); let at = start.unwrap_or(texts.len()); @@ -1401,22 +1483,17 @@ fn line_risks(cmd: &str, cwd: Option<&Path>, worktree: Option<&Path>, depth: u8, } // Programs that run other programs: check what they run. let mut runs: Vec<(&str, &[String])> = vec![(prog.as_str(), args)]; - if prog == "find" - && let Some(i) = args.iter().position(|a| ["-exec", "-execdir", "-ok", "-okdir"].contains(&a.as_str())) - && let Some(x) = args.get(i + 1) - { - runs.push((basename(x), &args[i + 2..])); - } if (ENV_RUNNERS.contains(&prog.as_str()) || NODE_RUNNERS.contains(&prog.as_str())) && let Some(i) = args.iter().position(|a| classify::is_interpreter(basename(a))) { runs.push((basename(&args[i]), &args[i + 1..])); } - // `pnpm exec npm publish`, `npx npm publish` and `uv run npm publish` run npm: the - // command a runner starts is read like any other command, and so is one that it - // starts in turn. Each is read once: where its arguments stand among the words of - // the line says which command it is (`uv run uv run npm publish`: the same - // `npm publish` behind the first `uv` and behind the second). + // `pnpm exec npm publish`, `npx npm publish`, `uv run npm publish` and + // `find . -exec npm publish \;` run npm: the command a program starts is read like any + // other command, and so is one that it starts in turn. Each is read once: where its + // arguments stand among the words of the line says which command it is + // (`uv run uv run npm publish`: the same `npm publish` behind the first `uv` and + // behind the second). let mut places: HashSet<*const [String]> = runs.iter().map(|(_, args)| std::ptr::from_ref(*args)).collect(); let mut read = 0; while let Some(&(runner, runner_args)) = runs.get(read) { @@ -1426,9 +1503,16 @@ fn line_risks(cmd: &str, cwd: Option<&Path>, worktree: Option<&Path>, depth: u8, Started::Program(words) => words, // A line for a shell is read as `sh -c` is. Started::ShellLine(line) if depth < 3 => { - for r in inner_risks(&line, cwd, worktree, depth + 1, inner) { + if one_more(&mut reading.started) { + add("runs dynamic code"); + break 'segments; + } + for r in inner_risks(&line, cwd, worktree, depth + 1, reading) { add(&r); } + if reading.started > MAX_STARTED { + break 'segments; + } continue; } Started::ShellLine(_) => { @@ -1447,6 +1531,10 @@ fn line_risks(cmd: &str, cwd: Option<&Path>, worktree: Option<&Path>, depth: u8, let Some(name) = words.get(at) else { continue }; let started_args = &words[at + 1..]; if places.insert(std::ptr::from_ref(started_args)) { + if one_more(&mut reading.started) { + add("runs dynamic code"); + break 'segments; + } runs.push((basename(name), started_args)); } } @@ -1498,9 +1586,16 @@ fn line_risks(cmd: &str, cwd: Option<&Path>, worktree: Option<&Path>, depth: u8, "eval" | "source" | "." => add("runs dynamic code"), p if classify::SHELLS.contains(&p) => match classify::shell_run(a) { ShellRun::Command(line) if depth < 3 => { - for r in inner_risks(line, cwd, worktree, depth + 1, inner) { + if one_more(&mut reading.started) { + add("runs dynamic code"); + break 'segments; + } + for r in inner_risks(line, cwd, worktree, depth + 1, reading) { add(&r); } + if reading.started > MAX_STARTED { + break 'segments; + } } ShellRun::Command(_) => add("runs dynamic code"), ShellRun::Stdin => add("pipes into a shell"), @@ -1529,9 +1624,10 @@ fn line_risks(cmd: &str, cwd: Option<&Path>, worktree: Option<&Path>, depth: u8, match sub { "install" | "i" | "add" | "ci" | "update" | "upgrade" | "up" | "remove" | "rm" | "uninstall" | "dlx" | "x" | "create" => add(PACKAGE_INSTALL), - "exec" if package_flag(a) => add(PACKAGE_INSTALL), - // Only a `-c` of the package manager's own, not one of the - // program it starts (`pnpm exec eslint -c x.json`). + // Only a `-p` or a `-c` of the package manager's own, not one of + // the program it starts (`pnpm exec tsc -p tsconfig.json`, + // `pnpm exec eslint -c x.json`). + "exec" if package_flag(exec_options(prog, a, rest)) => add(PACKAGE_INSTALL), "exec" if call_flag(exec_options(prog, a, rest)) => add("runs dynamic code"), // `npm exec` is npx: it downloads what the project does not have // (pnpm and yarn only run what is installed). @@ -1978,12 +2074,16 @@ const MVN_PLAIN_OPTIONS: &[&str] = &["-q", "--quiet", "-B", "--batch-mode", "-o" /// `mvn verify`, with no word beside them but the options above? Both run every task or /// phase on the line, and which of their other options take a value is not listed here /// (`--tests X`, `-pl module`, `-P profile`), so any other word makes the line an unknown -/// command. Only the two programs by their bare names: a wrapper in the repo (`./gradlew`, -/// `./mvnw`) is a script an agent can edit. +/// command. One `clean` may stand first, before one check (`mvn clean test`): it empties the +/// build folder, which the check fills again. Only the two programs by their bare names: a +/// wrapper in the repo (`./gradlew`, `./mvnw`) is a script an agent can edit. fn java_test_run(prog: &str, args: &[String]) -> bool { let (checks, plain) = if prog == "gradle" { (["test", "check"], GRADLE_PLAIN_OPTIONS) } else { (["test", "verify"], MVN_PLAIN_OPTIONS) }; - let mut targets = args.iter().map(String::as_str).filter(|word| !plain.contains(word)).peekable(); - targets.peek().is_some() && targets.all(|target| checks.contains(&target)) + let targets: Vec<&str> = args.iter().map(String::as_str).filter(|word| !plain.contains(word)).collect(); + match targets.as_slice() { + ["clean", check] => checks.contains(check), + _ => !targets.is_empty() && targets.iter().all(|target| checks.contains(target)), + } } fn test_runner(prog: &str, args: &[String]) -> bool { @@ -2006,7 +2106,17 @@ fn test_runner(prog: &str, args: &[String]) -> bool { } // The first of `run {#if view} -

      Checkpoints{view.off ? '' : ` · ${view.checkpoints.length}`}

      +

      Checkpoints{view.off ? '' : ` · ${view.checkpoints.length}`}

      {#if view.off}

      {view.off}

      {:else} diff --git a/src/sheet/AgentControls.svelte b/src/sheet/AgentControls.svelte index 3c31a1ae..f9316f55 100644 --- a/src/sheet/AgentControls.svelte +++ b/src/sheet/AgentControls.svelte @@ -8,9 +8,13 @@ Claude agent: its CLI sums up the conversation between turns (the core says when it may start). The button reads "Compacting…" while the request is on its way, and the row then shows what the live run last said about a compaction, with the time. + "Model" names the model and its thinking effort, also when the agent is not running, and + "Change…" opens the same dialog as the sheet's menu entry "Change model…". -->
      +
      + + Model + {modelLine(model, agent.model)}{modelOff ? ` · ${modelOff}` : ''} + + +
      {#if hasMode}
      - {#if unseen} + {#if below} + + {:else if unseen} {/if} @@ -296,6 +378,7 @@ .one > .btn { flex-shrink: 0; } .one > .btn:last-child { margin-left: auto; } .o-now { font-size: var(--t-sm); color: var(--ink-3); } + .o-todo { color: var(--ink-2); } .scroll { flex: 1; min-height: 0; overflow-y: auto; overflow-anchor: none; padding: 28px 0 28px; scroll-padding-bottom: 20px; mask-image: linear-gradient(180deg, transparent 0, #000 28px, #000 calc(100% - 10px), transparent 100%); } .hero { height: 100%; display: grid; place-items: center; } .ex { height: 32px; padding: 0 14px; border-radius: var(--r-full); background: var(--surface-2); color: var(--ink-2); font-size: var(--t-sm); } diff --git a/src/home/NextRow.svelte b/src/home/NextRow.svelte index 4acf3063..8026ac6e 100644 --- a/src/home/NextRow.svelte +++ b/src/home/NextRow.svelte @@ -1,9 +1,12 @@ {#if more == null} {:else} {#if open} diff --git a/src/home/cards/PlanCard.svelte b/src/home/cards/PlanCard.svelte index df202ea3..41517c67 100644 --- a/src/home/cards/PlanCard.svelte +++ b/src/home/cards/PlanCard.svelte @@ -16,6 +16,7 @@ import { PLAN_SPENT_TIP, spentLine } from '../../lib/util/cost'; import { clock } from '../../lib/util/format'; import { methodProvenance, PLAN_STATUS_LABEL } from '../../lib/util/labels'; + import { isHeld } from '../../lib/util/held'; import { keyList, stuckPlan } from '../../lib/util/plan'; import Icon from '../../components/Icon.svelte'; import Why, { type WhyLine } from '../../components/Why.svelte'; @@ -68,6 +69,8 @@ const n = `${tasks.length} task${tasks.length === 1 ? '' : 's'}`; if (plan.status === 'planning') return `Plan · drafting · ${n}`; if (plan.status === 'awaiting_approval') return `Plan · waiting for your go · ${n}${startable ? ` · ${startable} start right away` : ''}`; + // Since Codly restarted its tasks wait for your "Resume work", and none of them works. + if (live && tasks.some(isHeld) && !tasks.some((t) => ['running', 'verifying', 'reviewing', 'merging'].includes(t.status))) return `Plan · on hold since Codly restarted · ${done} of ${tasks.length} done`; if (live) return `Plan · ${plan.status === 'integrating' ? 'integrating' : 'running'} · ${done} of ${tasks.length} done`; return `Plan · ${PLAN_STATUS_LABEL[plan.status]} · ${done} of ${tasks.length} done`; }); diff --git a/src/home/cards/PlanDoneCard.svelte b/src/home/cards/PlanDoneCard.svelte index d8004e9f..8666dea5 100644 --- a/src/home/cards/PlanDoneCard.svelte +++ b/src/home/cards/PlanDoneCard.svelte @@ -3,14 +3,15 @@ the agents made, and the decision that is yours — merge into your branch, or keep the branch. A merge that would conflict with your branch says so here, with the two ways out: until the conflict is resolved the card does not say "ready to merge", and the one primary button is - the step's own "Have an agent resolve it". While a pull request for the plan is open with - checks still running, the primary button is to look at the pull request; Merge stays. + the step's own "Have an agent resolve it". While a pull request for the plan is open and its + checks are not read yet, still run or failed, the primary button is to look at the pull + request; Merge stays. --> -
    • {/each}
    -

    as reported by Claude Code

    + {#if servers.length}

    as reported by Claude Code

    {/if}
    {/if} diff --git a/src/sheet/AgentSheet.svelte b/src/sheet/AgentSheet.svelte index baae1399..5c132c60 100644 --- a/src/sheet/AgentSheet.svelte +++ b/src/sheet/AgentSheet.svelte @@ -6,14 +6,17 @@ context) · Model-stated (its own words). -->
    {#each TABS as t (t.id)} - + {/each}
    - {#if ui.sheetTab === 'messages'} + {#if open === 'messages'} - {:else if ui.sheetTab === 'traces'} + {:else if open === 'traces'} {:else} diff --git a/src/sheet/TaskSheet.svelte b/src/sheet/TaskSheet.svelte index 1e397bb5..ccbe3c1c 100644 --- a/src/sheet/TaskSheet.svelte +++ b/src/sheet/TaskSheet.svelte @@ -17,7 +17,7 @@ import { clock, plural, shortSha } from '../lib/util/format'; import { stoppedByChecks } from '../lib/util/gate'; import { keyList, waitingOn } from '../lib/util/plan'; - import { GLOSSARY, idVar, methodProvenance, PROVIDER_LABEL, TASK_STATUS_LABEL } from '../lib/util/labels'; + import { GLOSSARY, idVar, methodProvenance, PROVIDER_LABEL } from '../lib/util/labels'; import { tildify } from '../lib/util/sanitize'; import ArtifactThumb from '../components/ArtifactThumb.svelte'; import Icon from '../components/Icon.svelte'; @@ -29,6 +29,7 @@ import Section from '../components/Section.svelte'; import Why, { type WhyLine } from '../components/Why.svelte'; import TaskChecks from './TaskChecks.svelte'; + import { taskStatusLine } from './taskWords'; interface Props { task: Task; @@ -115,7 +116,7 @@

    {plan ? 'Plan task' : 'Board task'} · {task.key}

    {task.title}

    -

    {TASK_STATUS_LABEL[task.status]}{task.status_reason ? ` — ${task.status_reason}` : ''}

    +

    {taskStatusLine(task, deps.filter((d): d is Task => !!d))}

    {#if marks.length || task.status === 'done'}{/if} {#each LEGAL[task.status] ?? [] as l (l.to)}{/each} diff --git a/src/sheet/__tests__/helperRows.test.ts b/src/sheet/__tests__/helperRows.test.ts index 57b1eb34..cf6e0a05 100644 --- a/src/sheet/__tests__/helperRows.test.ts +++ b/src/sheet/__tests__/helperRows.test.ts @@ -2,7 +2,7 @@ // as "finished": also one that you stopped, and one that failed. import { describe, expect, it } from 'vitest'; import type { BackgroundWork } from '../../lib/state/session'; -import { helperEndWord, helperStop, helpersSummary } from '../helperRows'; +import { SAME_DESCRIPTION, helperEndWord, helperStop, helpersSummary } from '../helperRows'; const helpers = (...status: string[]) => status.map((s) => ({ status: s })); @@ -43,24 +43,44 @@ describe('the “Stop” of a helper’s row', () => { const helper = (callId: string, description: string, status = 'running') => ({ callId, description, status }); const listed = (id: string, description: string, status = 'running'): BackgroundWork => ({ id, kind: 'helper', description, status, runId: 'r1', startedAt: 1, endedAt: null }); + /** The row's "Stop" when `h` is the only helper at work. */ + const alone = (h: ReturnType, background: BackgroundWork[], turnRuns = false) => helperStop(h, [h], background, 'Eli', turnRuns); + it('a helper its agent waits for is stopped by its call id, and its turn goes on', () => { - expect(helperStop(helper('toolu_1', 'Look at the docs'), [], 'Eli')).toEqual({ id: 'toolu_1', hint: 'Stops this helper. Eli’s turn goes on.' }); + expect(alone(helper('toolu_1', 'Look at the docs'), [])).toEqual({ id: 'toolu_1', hint: 'Stops this helper. Eli’s turn goes on.' }); }); it('a helper in the background list is stopped by its id there, with the hint it has there', () => { - expect(helperStop(helper('toolu_2', 'Run the tests'), [listed('task-9', 'Run the tests')], 'Eli')).toEqual({ + expect(alone(helper('toolu_2', 'Run the tests'), [listed('task-9', 'Run the tests')])).toEqual({ id: 'task-9', hint: 'Stops this helper. Eli is told and goes on with a turn of its own.', }); + // While a turn of the agent runs, it is told in that turn. + expect(alone(helper('toolu_2', 'Run the tests'), [listed('task-9', 'Run the tests')], true)?.hint).toBe('Stops this helper. Eli is told in the turn that runs.'); // An entry of the list that ended, or a command of the same words, is not this helper. - expect(helperStop(helper('toolu_2', 'Run the tests'), [listed('task-9', 'Run the tests', 'stopped'), { ...listed('cmd', 'Run the tests'), kind: 'command' }], 'Eli')?.id).toBe('toolu_2'); + expect(alone(helper('toolu_2', 'Run the tests'), [listed('task-9', 'Run the tests', 'stopped'), { ...listed('cmd', 'Run the tests'), kind: 'command' }])?.id).toBe('toolu_2'); }); it('a helper that ended has no “Stop”', () => { - for (const status of ['completed', 'stopped', 'failed']) expect(helperStop(helper('toolu_3', 'x', status), [], 'Eli')).toBeNull(); + for (const status of ['completed', 'stopped', 'failed']) expect(alone(helper('toolu_3', 'x', status), [])).toBeNull(); + }); + + it('two listed helpers of the same words: which is which is not known, and the row says where to stop them', () => { + const h = helper('toolu_4', 'Same'); + expect(helperStop(h, [h, helper('toolu_5', 'Same')], [listed('a', 'Same'), listed('b', 'Same')], 'Eli', false)).toEqual({ id: null, hint: SAME_DESCRIPTION }); }); - it('two listed helpers of the same words: which is which is not known, and the row has none', () => { - expect(helperStop(helper('toolu_4', 'Same'), [listed('a', 'Same'), listed('b', 'Same')], 'Eli')).toBeNull(); + // Before, only the listed entries were counted: with one helper of the description in the list + // and one its agent waits for, the waited helper's row got the listed id, and its "Stop" + // stopped the other helper. + it('two helpers of one description, one listed and one waited for: neither row stops the wrong one', () => { + const inList = helper('toolu_6', 'Look at the docs'); + const waited = helper('toolu_7', 'Look at the docs'); + const both = [inList, waited]; + for (const h of both) expect(helperStop(h, both, [listed('task-1', 'Look at the docs')], 'Eli', false)).toEqual({ id: null, hint: SAME_DESCRIPTION }); + // None listed: each is stopped by its own call id, as today. + for (const h of both) expect(helperStop(h, both, [], 'Eli', false)?.id).toBe(h.callId); + // One running helper of the description and one entry: the entry is that helper. + expect(helperStop(inList, [inList, { ...waited, status: 'completed' }], [listed('task-1', 'Look at the docs')], 'Eli', false)?.id).toBe('task-1'); }); }); diff --git a/src/sheet/__tests__/historyWords.test.ts b/src/sheet/__tests__/historyWords.test.ts index 85b150e1..c0d131b4 100644 --- a/src/sheet/__tests__/historyWords.test.ts +++ b/src/sheet/__tests__/historyWords.test.ts @@ -4,7 +4,7 @@ import type { EventRow } from '../../lib/gen/EventRow'; import type { TaskStatus } from '../../lib/gen/TaskStatus'; import type { Approval } from '../../lib/gen/Approval'; import type { JsonValue } from '../../lib/gen/serde_json/JsonValue'; -import { backgroundLine, closedLine, compactionRowLine, decisionLine, entityWord, foldActs, helperRowLine, historyFacts, historySentence, repeatsReply, savedRuleOf, stoppedWithHelper, taskChangedLine, toolStartLine, tripleLine, withoutRepeatedTaskRows, type Names } from '../historyWords'; +import { backgroundLine, closedLine, compactionRowLine, decisionLine, entityWord, foldActs, helperRowLine, historyFacts, historySentence, quietStatus, reconnectAsked, repeatsReply, restartLine, savedRuleOf, stoppedWithHelper, taskChangedLine, toolDoneLine, toolEndLine, toolStartLine, tripleLine, withoutRepeatedTaskRows, type Names } from '../historyWords'; let eid = 0; const ev = (agent: string, kind: unknown): EventRow => ({ id: ++eid, ts: eid, agent_id: agent, task_id: null, run_id: null, kind: kind as EventKind }); @@ -309,3 +309,102 @@ describe('a call of a helper you stopped', () => { expect(stoppedWithHelper('c9', facts)).toBeNull(); }); }); + +// The fifth browser review (defect 20): a tool call was two rows ("Reading package.json · Read", +// then "Finished · 0.5 s"), "Status → idle" rows came between them, and a Restart read as "You +// asked Lead to reconnect…". +describe('History is one row per act', () => { + let n = 0; + const row = (kind: unknown, run = 'r1'): EventRow => ({ id: ++n, ts: n, agent_id: 'eli', task_id: null, run_id: run, kind: kind as EventKind }); + const target = (o: Record) => ({ path: null, paths: [], command: null, query: null, url: null, server: null, tool: null, ...o }); + const started = (call_id: string, name: string, activity: string, t: Record, input: unknown = {}) => + row({ type: 'tool_started', call_id, name, activity, target: target(t), input, confidence: 'observed' }); + const ended = (call_id: string, o: Record = {}) => + row({ type: 'tool_completed', call_id, ok: true, exit_code: null, tests_passed: null, tests_failed: null, duration_ms: 500, ...o }); + const startOf = (e: EventRow) => e.kind as Extract; + const endOf = (e: EventRow) => e.kind as Extract; + + it('a tool call is the row of its start, which says what it did and how it ended', () => { + const read = started('c1', 'Read', 'read', { path: 'web/package.json' }); + const done = ended('c1'); + const folded = foldActs([done, read], new Set()); + expect(folded.rows.map((r) => r.id)).toEqual([read.id]); + expect(folded.at.get(done.id)).toBe(read.id); + expect(toolStartLine(startOf(read), 'claude')).toBe('Reading package.json · Read'); + expect(toolEndLine(startOf(read), endOf(done), 'claude')).toBe('Read package.json · 0.5 s'); + // A call that runs is still its own row. + expect(foldActs([read], new Set()).rows).toEqual([read]); + }); + + it('a call that failed says so, with its exit code and its tests', () => { + const test = startOf(started('c2', 'Bash', 'test', { command: 'npm test' })); + expect(toolEndLine(test, endOf(ended('c2', { ok: false, exit_code: 1, tests_passed: 4, tests_failed: 2, duration_ms: 2100 })), 'claude')).toBe('Ran npm test · failed · exit 1 · 4 passed, 2 failed · 2 s'); + // An MCP tool is named in words; a helper's call says so. + expect(toolDoneLine(startOf(started('c3', 'mcp__linear__create_issue', 'mcp', { server: 'linear', tool: 'create_issue' })), 'claude')).toBe('Used linear: create_issue'); + expect(toolDoneLine(startOf(started('c4', 'Bash', 'execute', { command: 'ls' }, { subagent: { thread: 't', name: 'Ada' } })), 'codex')).toBe('Ran ls · helper Ada'); + // The end of a call whose start is not shown says only how it ended. + expect(toolEndLine(null, endOf(ended('c5', { ok: false })), 'claude')).toBe('Failed · 0.5 s'); + }); + + it('knows how each call ended, and what it was', () => { + const read = started('c6', 'Read', 'read', { path: 'a.ts' }); + const done = ended('c6'); + const facts = historyFacts([read, done], 'eli', 'claude'); + expect(facts.ends.get('c6')).toBe(done.kind); + expect(facts.starts.get('c6')).toBe(read.kind); + }); + + it('a state its turn and its calls already say is no row', () => { + for (const s of ['idle', 'working', 'thinking', 'starting']) expect(quietStatus(s)).toBe(true); + for (const s of ['waiting_approval', 'blocked', 'rate_limited', 'failed', 'offline']) expect(quietStatus(s)).toBe(false); + }); + + it('a reconnect of a connected server is a restart, and says so', () => { + const reconnect = (server: string) => row({ type: 'decision', id: `d${n}`, decision_type: 'control', method: 'human', summary: `asked Lead to reconnect its MCP server ${server}`, detail: null }); + const server = (name: string, status: string) => row({ type: 'mcp_server', name, status, error: null }); + const restart = reconnect('docs'); + const retry = reconnect('linear'); + const facts = historyFacts([server('docs', 'connected'), server('linear', 'failed'), restart, retry], 'eli', 'claude'); + expect([...facts.restarts]).toEqual([restart.id]); + expect(restartLine((restart.kind as Extract).summary)).toBe('You restarted docs for Lead’s run'); + expect(reconnectAsked('asked Eli 2 to reconnect its MCP server my server')).toEqual({ agent: 'Eli 2', server: 'my server' }); + expect(restartLine('you turned docs off for Lead’s run')).toBeNull(); + // A server of another run is not this one. + expect([...historyFacts([server('docs', 'connected'), { ...reconnect('docs'), run_id: 'r2' }], 'eli', 'claude').restarts]).toEqual([]); + }); + + // Package claude-part5-truth words the record of the switch for the folder: History shows it as a sentence. + it('the record of a switch reads as a sentence, in its old and its new words', () => { + const keeps = () => false; + expect(historySentence("you turned docs off for Lead's run", 'human', keeps)).toBe("You turned docs off for Lead's run"); + expect(historySentence('you turned docs off for Claude Code in this folder (Lead’s run and every later one)', 'human', keeps)).toBe('You turned docs off for Claude Code in this folder (Lead’s run and every later one)'); + }); +}); + +// Round 7's review: a jump from Home to a History row found nothing when the fold dropped it. +describe('a jump to a row that History folded', () => { + let n = 0; + const row = (ts: number, kind: unknown, task: string | null = null): EventRow => ({ id: ++n, ts, agent_id: 'eli', task_id: task, run_id: 'r1', kind: kind as EventKind }); + const COMMENTS = 'Review comments (1):\n\n1. a.ts:4\n Use the v2 client'; + + it('lands on the row that stands for it: the three rows of a send-back on its decision', () => { + const chat = row(1000, { type: 'chat', message: { id: 'c1', thread: 'agent:eli', author: 'user', text: COMMENTS, attachment: null, ts: 1000 } }); + const status = row(1010, { type: 'task_changed', task: { id: 'task-1', key: 't1', status: 'changes_requested' } }); + const sent = row(1020, { type: 'decision', id: 'd1', decision_type: 'review', method: 'human', summary: 'you sent t1 back with review comments; its worker reads them now', detail: { comments: COMMENTS } }, 'task-1'); + const folded = foldActs([sent, status, chat], new Set()); + expect(folded.rows).toEqual([sent]); + // The jump to the first of the three lands on the one that is kept. + expect([chat, status].map((r) => folded.at.get(r.id))).toEqual([sent.id, sent.id]); + expect(folded.at.has(sent.id)).toBe(false); + }); + + it('a closed request and its record land on the answer’s row', () => { + const approval = { id: 'ap1', agent_id: 'eli', run_id: 'r1', task_id: null, call_id: null, subject: { kind: 'command', command: 'rm x', cwd: null }, reason: null, choices: [], risks: [], status: 'pending', decided_by: null, created_at: 0 } as unknown as Approval; + const asked = row(10, { type: 'approval_requested', approval }); + const answered = row(30, { type: 'approval_resolved', approval_id: 'ap1', status: 'approved', by: 'user' }); + const record = row(31, { type: 'decision', id: 'd2', decision_type: 'approval', method: 'human', summary: 'You allowed it', detail: { approval: 'ap1' } }); + const folded = foldActs([record, answered, asked], new Set()); + expect(folded.rows).toEqual([answered]); + expect([asked, record].map((r) => folded.at.get(r.id))).toEqual([answered.id, answered.id]); + }); +}); diff --git a/src/sheet/__tests__/sheetFocus.test.ts b/src/sheet/__tests__/sheetFocus.test.ts index ffcfd86f..20230fce 100644 --- a/src/sheet/__tests__/sheetFocus.test.ts +++ b/src/sheet/__tests__/sheetFocus.test.ts @@ -2,7 +2,7 @@ // under Git, at Checkpoints") opened the sheet on the Messages tab: the open tab was the tabs' // own state, and the focus only scrolled to the section of the tabs. import { describe, expect, it } from 'vitest'; -import { focusPlace } from '../sheetFocus'; +import { focusPlace, tabOf, withTab } from '../sheetFocus'; describe('a focus on the agent sheet', () => { it('“/undo” lands on the Git tab’s checkpoints with no extra click', () => { @@ -15,3 +15,24 @@ describe('a focus on the agent sheet', () => { for (const section of ['mcp', 'subagents', 'trust', 'cost']) expect(focusPlace(section)).toEqual({ section, tab: null, inner: null }); }); }); + +// Round 7's review: the open tab was one value for every agent. After "/undo" or one click on +// Git, every agent's sheet you opened mounted the Git tab and ran its git commands at once. +describe('the open tab of an agent’s sheet', () => { + it('is the agent’s own: another agent’s sheet opens on Messages', () => { + const tabs = withTab({}, 'ada', 'git'); + expect(tabOf(tabs, 'ada')).toBe('git'); + expect(tabOf(tabs, 'bo')).toBe('messages'); + }); + + it('a tab you pick for one agent leaves the others as they were', () => { + const tabs = withTab(withTab({}, 'ada', 'git'), 'bo', 'traces'); + expect(tabs).toEqual({ ada: 'git', bo: 'traces' }); + expect(withTab(tabs, 'ada', 'messages')).toEqual({ ada: 'messages', bo: 'traces' }); + }); + + it('a focus that names a tab opens it for the agent of the sheet', () => { + const at = focusPlace('checkpoints'); + expect(tabOf(withTab({}, 'ada', at.tab!), 'ada')).toBe('git'); + }); +}); diff --git a/src/sheet/__tests__/taskWords.test.ts b/src/sheet/__tests__/taskWords.test.ts new file mode 100644 index 00000000..ea1db4de --- /dev/null +++ b/src/sheet/__tests__/taskWords.test.ts @@ -0,0 +1,53 @@ +// The task sheet's head and the agent's Git tab. The fourth browser review (defects 19 and 20): +// "Cancelled — Cancelled by you", a task after a cancelled one read "Waiting on t1, t2", and +// "Merge into main" stood on an agent with nothing to merge. +import { describe, expect, it } from 'vitest'; +import type { AgentGit } from '../../lib/gen/AgentGit'; +import type { Task } from '../../lib/gen/Task'; +import { hasSomethingToMerge, taskStatusLine } from '../taskWords'; + +const dep = (key: string, status: Task['status']) => ({ key, status }); + +describe('the status line of a task', () => { + it('a reason that only repeats the status is said once', () => { + expect(taskStatusLine({ status: 'cancelled', status_reason: 'cancelled by you' }, [])).toBe('Cancelled by you'); + expect(taskStatusLine({ status: 'cancelled', status_reason: 'Cancelled' }, [])).toBe('Cancelled'); + expect(taskStatusLine({ status: 'blocked', status_reason: 'blocked by you.' }, [])).toBe('Blocked by you'); + }); + + it('another reason follows the status', () => { + expect(taskStatusLine({ status: 'blocked', status_reason: 'stopped by you' }, [])).toBe('Blocked — stopped by you'); + expect(taskStatusLine({ status: 'running', status_reason: null }, [])).toBe('Running'); + }); + + it('a task that waits on a cancelled one says it cannot start, as the thread does', () => { + const deps = [dep('t1', 'cancelled'), dep('t2', 'running')]; + expect(taskStatusLine({ status: 'pending', status_reason: 'Waiting on t1, t2' }, deps)).toBe('Backlog — Can’t start · t1 was cancelled'); + expect(taskStatusLine({ status: 'pending', status_reason: 'Waiting on t1, t2' }, [dep('t1', 'done'), dep('t2', 'running')])).toBe('Backlog — Waiting on t2'); + // A task that waits on nothing any more keeps the core's reason. + expect(taskStatusLine({ status: 'ready', status_reason: 'Ready: a free agent picks it up' }, [dep('t1', 'done')])).toBe('Ready: a free agent picks it up'); + }); +}); + +describe('“Merge into main” in an agent’s Git tab', () => { + const view = (o: Partial): Pick => ({ + branch: 'codly/eli', + files: [], + branches: [{ name: 'main', current: false, sha: 'abc1234', ts: 1 }, { name: 'codly/eli', current: true, sha: 'abc1234', ts: 1 }], + ...o, + }); + + it('is not offered when the branch is where main is and nothing changed', () => { + expect(hasSomethingToMerge(view({}), 'main')).toBe(false); + }); + + it('is offered for a commit of its own, or a change in the worktree', () => { + expect(hasSomethingToMerge(view({ branches: [{ name: 'main', current: false, sha: 'abc1234', ts: 1 }, { name: 'codly/eli', current: true, sha: 'def5678', ts: 2 }] }), 'main')).toBe(true); + expect(hasSomethingToMerge(view({ files: [{ path: 'a.ts', code: ' M' }] }), 'main')).toBe(true); + }); + + it('is offered when the branch it merges into is not known, and never without a branch', () => { + expect(hasSomethingToMerge(view({}), 'your branch')).toBe(true); + expect(hasSomethingToMerge(view({ branch: null }), 'main')).toBe(false); + }); +}); diff --git a/src/sheet/helperRows.ts b/src/sheet/helperRows.ts index bc041fab..a188870f 100644 --- a/src/sheet/helperRows.ts +++ b/src/sheet/helperRows.ts @@ -5,24 +5,41 @@ import { stopHint, waitedHelperStopHint, type BackgroundWork } from '../lib/stat import type { SubAgent } from '../lib/state/store.svelte'; import { oneLine } from '../lib/util/sanitize'; -/** What the "Stop" of a helper's row sends (`id`, for `stop_agent_task`) and says on its button. */ -export type HelperStop = { id: string; hint: string }; +/** + * What the "Stop" of a helper's row sends (`id`, for `stop_agent_task`) and says on its button. + * `id` null: the row has no "Stop", and `hint` says why. + */ +export type HelperStop = { id: string | null; hint: string }; + +/** Why a helper's row has no "Stop": the background list cannot tell it from another helper. */ +export const SAME_DESCRIPTION = 'Two helpers have this description: stop them in “In the background”.'; /** - * The "Stop" of a helper's row, for a helper that runs (none for one that is over). A helper in - * the background list (`background`: the agent's live run's) is stopped by its id there, and its - * button says what its "Stop" there says. A helper its agent still waits for is stopped by the - * id of the call that started it: its call returns to the agent and the turn goes on (recorded: - * docs/research/cli-claude-stream-json-2.1.311-part4.md, section 2). The list names a helper by - * its description: when two helpers that run have the same one, which is which is not known, - * and the row has no "Stop" (each has its own in "In the background"). + * The "Stop" of a helper's row, for a helper that runs (none for one that is over). The + * background list (`background`: the agent's live run's) names a helper by its description + * only, so a row is stopped by the id there only when that is sure: exactly one helper that + * runs (`helpers`: the agent's helpers) has the description, and exactly one entry of the list + * has it; its button then says what its "Stop" there says (`turnRuns`: a turn of the agent runs + * now, `stopHint`). A helper the list does not name is one its agent still waits for: it is + * stopped by the id of the call that started it, its call returns to the agent and the turn + * goes on (recorded: docs/research/cli-claude-stream-json-2.1.311-part4.md, section 2). In any + * other case which entry is which helper is not known (two helpers of one description, one of + * them listed and one waited for, or both listed): the row has no "Stop", and says where to stop + * them. */ -export function helperStop(h: Pick, background: readonly BackgroundWork[], agent: string): HelperStop | null { +export function helperStop( + h: Pick, + helpers: readonly Pick[], + background: readonly BackgroundWork[], + agent: string, + turnRuns: boolean, +): HelperStop | null { if (h.status !== 'running') return null; const listed = background.filter((w) => w.kind === 'helper' && w.status === 'running' && w.description === h.description); - if (listed.length > 1) return null; - if (listed.length === 1) return { id: listed[0].id, hint: stopHint(listed[0], agent)! }; - return { id: h.callId, hint: waitedHelperStopHint(agent) }; + if (!listed.length) return { id: h.callId, hint: waitedHelperStopHint(agent) }; + const alike = helpers.filter((x) => x.status === 'running' && x.description === h.description).length; + if (listed.length === 1 && alike === 1) return { id: listed[0].id, hint: stopHint(listed[0], agent, turnRuns)! }; + return { id: null, hint: SAME_DESCRIPTION }; } /** diff --git a/src/sheet/historyWords.ts b/src/sheet/historyWords.ts index dd90883c..88e6c472 100644 --- a/src/sheet/historyWords.ts +++ b/src/sheet/historyWords.ts @@ -1,9 +1,10 @@ // Words for rows of an agent's History that are built from ids or lists: a fact of the knowledge // graph, a task that changed, a helper, a change of what runs in the background, a compaction, // a tool call, a decision as a sentence. Which rows of a task say something new, and which rows -// are one act of yours (a send-back, an answer to a request) said once. And what a row needs to -// know about the agent's other events: which calls showed a plan, which conversation rows only -// repeat a reply, which calls were a helper's, what ran in the background before. +// are one act said once (a send-back, an answer to a request, a tool call from its start to its +// end). And what a row needs to know about the agent's other events: which calls showed a plan, +// which conversation rows only repeat a reply, which calls were a helper's, how each call +// ended, what ran in the background before, which reconnects were restarts. // Pure, so the sheet and the tests agree; the sheet passes the names. import { CODLY_TOOL } from '../lib/narrate'; import type { Approval } from '../lib/gen/Approval'; @@ -14,8 +15,8 @@ import type { Provider } from '../lib/gen/Provider'; import type { Task } from '../lib/gen/Task'; import type { Triple } from '../lib/gen/Triple'; import type { JsonValue } from '../lib/gen/serde_json/JsonValue'; -import { plural, tokens } from '../lib/util/format'; -import { phrase, subagentMark, TASK_STATUS_LABEL, targetLabel } from '../lib/util/labels'; +import { dur, plural, tokens } from '../lib/util/format'; +import { pastVerb, phrase, subagentMark, TASK_STATUS_LABEL, targetLabel } from '../lib/util/labels'; import { askedLine } from '../lib/util/outcome'; import { isPlanCall, planStep, showsPlan } from '../lib/util/planRequest'; import { oneLine } from '../lib/util/sanitize'; @@ -55,18 +56,33 @@ export type HistoryFacts = { helperOf: Map; /** By the id of a `background_tasks` row: the ids of what the list before it in the same run named (null: none is at hand). */ backgroundBefore: Map | null>; + /** How each call ended, by its id: its row says it, in the past, from its start. */ + ends: Map; + /** What each call was, by its id: the row of an end whose start is not shown says it. */ + starts: Map; + /** The ids of the records of a reconnect that asked a connected server to start again: a restart (`restartLine`). */ + restarts: Set; }; /** `provider`: the agent's CLI (none when Codly does not know the agent): only a Claude agent's call of the plan tool shows a plan. */ export function historyFacts(events: readonly EventRow[], agentId: string, provider: Provider | null = null): HistoryFacts { - const facts: HistoryFacts = { planCalls: new Set(), said: new Set(), helpers: new Map(), helperOf: new Map(), backgroundBefore: new Map() }; + const facts: HistoryFacts = { planCalls: new Set(), said: new Set(), helpers: new Map(), helperOf: new Map(), backgroundBefore: new Map(), ends: new Map(), starts: new Map(), restarts: new Set() }; /** The ids of the last list of background work of each run. */ const listed = new Map>(); + /** Where each server of each run stood last (" " → its status). */ + const servers = new Map(); for (const e of events) { if (e.agent_id !== agentId) continue; const k = e.kind; - if (k.type === 'tool_started' && isPlanCall(k.name, provider)) facts.planCalls.add(k.call_id); - else if (k.type === 'message') facts.said.add(k.text); + if (k.type === 'tool_started') { + facts.starts.set(k.call_id, k); + if (isPlanCall(k.name, provider)) facts.planCalls.add(k.call_id); + } else if (k.type === 'tool_completed') facts.ends.set(k.call_id, k); + else if (k.type === 'mcp_server') servers.set(`${e.run_id ?? ''} ${k.name}`, k.status); + else if (k.type === 'decision') { + const asked = reconnectAsked(k.summary); + if (asked && servers.get(`${e.run_id ?? ''} ${asked.server}`) === 'connected') facts.restarts.add(e.id); + } else if (k.type === 'message') facts.said.add(k.text); else if (k.type === 'sub_agent') facts.helpers.set(k.call_id, k.status); else if (k.type === 'sub_agent_progress' && k.tool_call_id != null) facts.helperOf.set(k.tool_call_id, k.call_id); else if (k.type === 'background_tasks') { @@ -125,6 +141,7 @@ export function withoutRepeatedTaskRows(rows: T[] type SubAgentRow = Extract; type ToolStarted = Extract; +type ToolCompleted = Extract; type DecisionRow = Extract; type BackgroundTasks = Extract; type Compacting = Extract; @@ -193,6 +210,56 @@ export function toolStartLine(k: Pick | null, end: Pick, provider: Provider | null): string { + const said = start ? `${toolDoneLine(start, provider)}${end.ok ? '' : ' · failed'}` : end.ok ? 'Finished' : 'Failed'; + const exit = end.exit_code != null ? ` · exit ${end.exit_code}` : ''; + const tests = end.tests_passed != null ? ` · ${end.tests_passed} passed${end.tests_failed ? `, ${end.tests_failed} failed` : ''}` : ''; + return `${said}${exit}${tests}${end.duration_ms != null ? ` · ${dur(end.duration_ms)}` : ''}`; +} + +/** What a call did, in the past: the start's words (`toolStartLine`) with the verb that says it is done, and without the tool's name. */ +export function toolDoneLine(k: Pick, provider: Provider | null): string { + if (isPlanCall(k.name, provider)) return planStep(false); + const by = subagentMark(k.input); + const t = mcpToolOf(k.name, k.target); + if (t?.server === CODLY_SERVER) return `Used Codly’s ${t.tool.replace(/^codly\./, '').replace(/^codly_/, '').replace(/_/g, ' ')} tool${by}`; + if (t) return `Used ${t.server}: ${t.tool}${by}`; + const label = oneLine(targetLabel(k.target, k.activity), 60); + const verb = k.activity === 'test' && label ? 'Ran' : pastVerb(k.activity); + return `${label ? `${verb} ${label}` : verb}${by}`; +} + +/** The changes of an agent's state that its turn's and its calls' rows already say: History shows no row of their own for them. */ +const QUIET_STATUS = new Set(['idle', 'starting', 'thinking', 'working']); + +/** Whether a `status_changed` row says nothing the rows around it do not ("Status → idle"). */ +export const quietStatus = (status: string): boolean => QUIET_STATUS.has(status); + +/** The core's record of a reconnect: "asked Ada to reconnect its MCP server docs" (orchestrator/live_session.rs). */ +const RECONNECT = /^asked (.+?) to reconnect its MCP server (.+)$/; + +/** The agent and the server of the core's record of a reconnect (null: the record is another one). */ +export function reconnectAsked(summary: string): { agent: string; server: string } | null { + const m = RECONNECT.exec(summary.trim()); + return m ? { agent: m[1], server: m[2] } : null; +} + +/** + * The row of a reconnect that was a restart ("Restart" sends Claude Code the request of + * "Reconnect" for a connected server, session.ts `canRestart`): "You restarted docs for Ada’s + * run". Null when the record is no reconnect. + */ +export function restartLine(summary: string): string | null { + const asked = reconnectAsked(summary); + return asked ? `You restarted ${asked.server} for ${asked.agent}’s run` : null; +} + /** A decision's `detail` as an object (empty when it is none). */ const detailOf = (d: JsonValue | undefined): { [key in string]?: JsonValue } => (d && typeof d === 'object' && !Array.isArray(d) ? d : {}); @@ -261,35 +328,56 @@ function partOfSendBack(r: EventRow, d: EventRow, comments: string): boolean { } /** - * The rows of a History (newest first) with each act of yours said once. A send-back is its - * decision row: the task's new status, your comments in the worker's conversation and the turn - * that took them are part of it (same task, within `ACT_MS`); rows of other tasks between them - * stay. A request that is closed is its answer's row: the row that it asked, a record of the - * answer, and the calls of a plan it showed (`planCalls`) go. `asked`: the requests whose row - * went, by id, so that the answer's row can say what was asked (`closedLine`). + * The rows of a History (newest first) with each act said once. A send-back is its decision + * row: the task's new status, your comments in the worker's conversation and the turn that took + * them are part of it (same task, within `ACT_MS`); rows of other tasks between them stay. A + * request that is closed is its answer's row: the row that it asked, a record of the answer, + * and the calls of a plan it showed (`planCalls`) go. A tool call is the row of its start: the + * row of its end goes, and the start's row says how it ended (`toolEndLine`). `asked`: the + * requests whose row went, by id, so that the answer's row can say what was asked + * (`closedLine`). `at`: for each row that went, by its event id, the id of the row that stands + * for it, so that a jump to it lands there. */ -export function foldActs(rows: readonly EventRow[], planCalls: ReadonlySet): { rows: EventRow[]; asked: Map } { - const resolved = new Set(rows.flatMap((e) => (e.kind.type === 'approval_resolved' ? [e.kind.approval_id] : []))); +export function foldActs(rows: readonly EventRow[], planCalls: ReadonlySet): { rows: EventRow[]; asked: Map; at: Map } { + /** The row of each answer, by the request's id. */ + const answers = new Map(rows.flatMap((e) => (e.kind.type === 'approval_resolved' ? [[e.kind.approval_id, e] as const] : []))); const asked = new Map(); - const drop = new Set(); - const planOf = new Set(); + /** Each row that goes, with the row that stands for it. */ + const into = new Map(); + /** The calls of a plan whose request is closed, with the answer's row. */ + const planOf = new Map(); for (const e of rows) { - if (e.kind.type !== 'approval_requested' || !resolved.has(e.kind.approval.id)) continue; + if (e.kind.type !== 'approval_requested') continue; + const answer = answers.get(e.kind.approval.id); + if (!answer) continue; asked.set(e.kind.approval.id, e.kind.approval); - drop.add(e); + into.set(e, answer); const call = e.kind.approval.call_id; - if (call && planCalls.has(call)) planOf.add(call); + if (call && planCalls.has(call)) planOf.set(call, answer); } + const startOf = new Map(rows.flatMap((e) => (e.kind.type === 'tool_started' ? [[e.kind.call_id, e] as const] : []))); for (const e of rows) { const k = e.kind; - if ((k.type === 'tool_started' || k.type === 'tool_completed') && planOf.has(k.call_id)) drop.add(e); + if (k.type === 'tool_started' || k.type === 'tool_completed') { + const plan = planOf.get(k.call_id); + if (plan) into.set(e, plan); + else if (k.type === 'tool_completed' && startOf.has(k.call_id)) into.set(e, startOf.get(k.call_id)!); + } if (k.type !== 'decision') continue; const answer = answerOf(k); - if (answer != null && resolved.has(answer)) drop.add(e); + const answerRow = answer != null ? answers.get(answer) : undefined; + if (answerRow) into.set(e, answerRow); const comments = sentBack(k); - if (comments && e.task_id) for (const r of rows) if (partOfSendBack(r, e, comments)) drop.add(r); + if (comments && e.task_id) for (const r of rows) if (partOfSendBack(r, e, comments)) into.set(r, e); + } + // (a row can stand for another that went too: the jump follows to the one that stays) + const at = new Map(); + for (const [r, by] of into) { + let to = by; + for (let hops = 0; into.has(to) && hops < into.size; hops++) to = into.get(to)!; + at.set(r.id, to.id); } - return { rows: rows.filter((r) => !drop.has(r)), asked }; + return { rows: rows.filter((r) => !into.has(r)), asked, at }; } /** diff --git a/src/sheet/sheetFocus.ts b/src/sheet/sheetFocus.ts index 0047c532..6bc76885 100644 --- a/src/sheet/sheetFocus.ts +++ b/src/sheet/sheetFocus.ts @@ -3,9 +3,21 @@ // its tabs (Messages, Traces, Git: AgentTabs.svelte): that tab opens first, then the sheet // scrolls to the place in it. Pure, so the sheet and the tests agree. -/** The tabs under the agent sheet's sections, as `ui.sheetTab` holds the open one. */ +/** The tabs under the agent sheet's sections, as `ui.sheetTab` holds the open one of each agent. */ export type SheetTab = 'messages' | 'traces' | 'git'; +/** + * The open tab of each agent's sheet, for the session, by agent id. The tab is one agent's: + * Git runs its git commands while it is open, so another agent's sheet does not open on it. + */ +export type SheetTabs = Readonly>; + +/** The tab an agent's sheet opens on: the one you left it on, else Messages. */ +export const tabOf = (tabs: SheetTabs, agentId: string): SheetTab => tabs[agentId] ?? 'messages'; + +/** The tabs with `tab` open for `agentId`; the other agents keep theirs. */ +export const withTab = (tabs: SheetTabs, agentId: string, tab: SheetTab): SheetTabs => ({ ...tabs, [agentId]: tab }); + /** `section`: the sheet's section to open and scroll to; `tab`: the tab to open in it first; `inner`: the place in that tab to scroll to then. */ export type FocusPlace = { section: string; tab: SheetTab | null; inner: string | null }; diff --git a/src/sheet/taskWords.ts b/src/sheet/taskWords.ts new file mode 100644 index 00000000..0e8c9b70 --- /dev/null +++ b/src/sheet/taskWords.ts @@ -0,0 +1,41 @@ +// The words of the task sheet's head, and when its Git tab offers a merge. Pure, so the sheet +// and the tests agree. +import type { AgentGit } from '../lib/gen/AgentGit'; +import type { Task } from '../lib/gen/Task'; +import { waitLine } from '../home/threadWords'; +import { TASK_STATUS_LABEL } from '../lib/util/labels'; + +/** + * The task's status line: its status and the core's reason, said once. A reason that starts + * with the status ("cancelled by you" on a cancelled task, "Ready: a free agent picks it up") is + * the whole line ("Cancelled by you"). A task that waits on others (still in the backlog or ready) + * says what it waits on as the thread does (`waitLine`: "Can’t start · t1 was cancelled"), not + * the reason the core wrote when it began to wait. `deps`: the tasks it depends on. + */ +export function taskStatusLine(task: Pick, deps: readonly Pick[]): string { + const label = TASK_STATUS_LABEL[task.status]; + const waits = task.status === 'pending' || task.status === 'ready' ? waitLine(deps.filter((d) => d.status !== 'done')) : null; + const reason = task.status_reason?.trim() || null; + if (waits && (!reason || /^waiting on /i.test(reason))) return `${label} — ${waits.text}`; + if (!reason) return label; + const said = reason.toLowerCase().replace(/[.\s]+$/, ''); + const named = label.toLowerCase(); + if (said === named || said.startsWith(`${named} `) || said.startsWith(`${named}:`)) return reason[0].toUpperCase() + reason.slice(1).replace(/[.\s]+$/, ''); + return `${label} — ${reason}`; +} + +/** + * Whether an agent's Git tab offers "Merge into ": its worktree has a change, or its + * branch has a commit that is not the tip of the branch it merges into. A branch whose tip is + * the target's own tip has nothing to merge. When the target is not in the list of branches, + * it cannot be told: the merge is offered and the core says what it finds. + */ +export function hasSomethingToMerge(view: Pick, target: string): boolean { + if (!view.branch) return false; + if (view.files.length) return true; + const sha = (name: string) => view.branches.find((b) => b.name === name)?.sha ?? null; + const mine = sha(view.branch); + const theirs = sha(target); + if (!mine || !theirs) return true; + return !(mine.startsWith(theirs) || theirs.startsWith(mine)); +} From d3d6ff38666c956e0c791d04c2e24f9fb6da7762 Mon Sep 17 00:00:00 2001 From: julienwuthrich-ant Date: Mon, 23 Nov 2026 17:41:39 -0800 Subject: [PATCH 069/120] Demo: three cards at once, a worker's own files, and merges that say one true thing The browser demo could not show three waiting cards in one thread, a worker's Git tab never listed a file, and several of its answers differed from the core's. - `?cards=3`: a release checklist of four independent tasks; three workers ask (a command, a file edit, a question) within seconds, and the fourth finishes while the cards wait. Autoplay runs the plan but leaves the cards. - A worker's Git tab lists what it wrote for its task since Codly committed it, with the task's text; a 1:1 agent's diff shows the lines of its edit. - A plan's worker is found again by the plan it was started for. - Merge follows the core: a running plan or one that never ran is refused, a cancelled plan merges its finished work ("merge anyway"). - The fix-checks task prints the failing test as a sentence and has a diff. - A task that waits on a cancelled task says so, in the scheduler's words. - A stop of something not running is refused as the core refuses it. - A run that starts again emits its session line (also after Resume). - Requests autoplay answered say "by autoplay". - After "Open without" the repo's configuration, Claude runs carry the core's notice. - Agents keep their ids across reloads, so the office look is kept. Co-Authored-By: Claude Fable 5.2 --- docs/DEMO.md | 7 +- src/lib/__tests__/demoBackground.test.ts | 10 +- src/lib/__tests__/demoStory.test.ts | 243 +++++++++++- src/lib/__tests__/demoWorkspaceId.test.ts | 11 +- src/lib/__tests__/demoWorktreeFiles.test.ts | 29 ++ src/lib/__tests__/mockTransport.test.ts | 69 ++++ src/lib/demo/agentgit.ts | 73 +++- src/lib/demo/controls.ts | 9 +- src/lib/demo/sim.ts | 40 +- src/lib/demo/states.ts | 5 +- src/lib/demo/story.ts | 403 +++++++++++++++++--- src/lib/demo/workspaceId.ts | 8 +- src/lib/mock.ts | 17 +- 13 files changed, 814 insertions(+), 110 deletions(-) diff --git a/docs/DEMO.md b/docs/DEMO.md index 421600ad..f776fe44 100644 --- a/docs/DEMO.md +++ b/docs/DEMO.md @@ -18,7 +18,7 @@ Parameters go in the URL and can be combined. They are read once, when the page | `?ws=1` | Opens `acme/web` at once. | | `?speed=2` | Plays the script faster (`0.5` is slower). | | `?skip=90` | Starts 90 seconds into the script. Any value, `0` included, also opens the repo. | -| `?autoplay=1` | Runs each plan and allows each request by itself. | +| `?autoplay=1` | Runs each plan and allows each request by itself. A request it allowed says "by autoplay", not "by you". | | `?onboard=1` | A machine with no agent CLI installed, to see the first-run quest. | `?autoplay=1&skip=180` is the short way to both plans finished. @@ -29,9 +29,9 @@ Each of these opens `acme/web` at once, except `?trust=ask` and `?hour=`. | Parameter | What you get | Where to look | | --- | --- | --- | -| `?trust=ask` | The repo has CLI settings of its own, and you were never asked about them. | Open `acme/web`: the trust dialog. | +| `?trust=ask` | The repo has CLI settings of its own, and you were never asked about them. After "Open without…", each Claude Code agent that starts from then on says that its run started without them. | Open `acme/web`: the trust dialog; then the Lead's sheet, under "MCP servers". | | `?merge=conflict` | Your branch changed a file that each finished plan changed too. Merge is refused. "Have an agent resolve it" gives the plan one more task; when it is done, the plan merges. | The plan's finished card: `?merge=conflict&autoplay=1&skip=180` | -| `?merge=checks` | Your branch moved since each plan started, and one check of a finished plan fails on the merge result. Merge is refused and says which check; "Have an agent fix it" gives the plan one more task (`fix-checks`); when it is done, the plan merges. Cancel a plan with finished work, then try to merge it: the refusal says to fix the checks yourself. | The plan's finished card: `?merge=checks&autoplay=1&skip=180` | +| `?merge=checks` | Your branch moved since each plan started, and one check of a finished plan fails on the merge result. Merge is refused and says which check, with the failing test; "Have an agent fix it" gives the plan one more task (`fix-checks`) that changes one line of that test; when it is done, the plan merges. "Merge anyway" merges without the check. Cancel a plan with finished work, then: Merge is refused for its check as well, "Have an agent fix it" says to fix the checks yourself (no agent works on a cancelled plan), and "Merge anyway" merges the work it finished. | The plan's finished card: `?merge=checks&autoplay=1&skip=180` | | `?pr=open` | Each finished plan has an open pull request whose checks are not read yet. Refresh finds them running, then passed. | The plan's finished card: `?pr=open&autoplay=1&skip=180` | | `?turn=failed` | The first turn of the first 1:1 agent you talk to fails: the API is overloaded. The thread shows the trouble row with "Send again", and sending again works. | Hire a 1:1 agent and send it a message. | | `?requests=two` | Both scripted requests (the dark-mode toggle and the sign-in lockout) are there when the page loads, not 1.6 and 24 seconds later. The demo repo keeps its id in this browser, so after a reload Codly opens on the request you left. | Open the lockout request, then reload the page. | @@ -43,6 +43,7 @@ Each of these opens `acme/web` at once, except `?trust=ask` and `?hour=`. | `?mode=plan` | Eli, a 1:1 Claude agent in the mode "plan first", was asked for a small change and shows a plan. Send it back with a note and it comes again; accept it and Eli asks before the edit. | Eli's conversation; the mode switch is in Eli's sheet, under Controls. | | `?resume=ask` | Codly "closed" while the first plan ran: two of its tasks were in work and wait, each with its worker (offline) and its branch, and nothing starts. The bar at the top asks. "Resume work" starts them, with the same workers and the same attempt; "Not now" keeps them waiting, with the button; cancel a waiting task and the bar counts one less. (`billing-api` plays its own script: it is not held.) | The bar at the top of the window, and the two tasks on the board. | | `?background=on` | Eli, a 1:1 Claude agent, ended its turn with two things at work in the background: a dev server and a helper. "Stop" ends the one you press it on. After the helper's stop Eli says so in a short turn of its own, as Claude Code does; after the command's stop no turn follows. Left alone, the helper reports after about three minutes. | Eli's sheet, under "In the background". | +| `?cards=3` | The one request is a release checklist: a plan of four tasks that wait on nothing. Three of its workers ask you within a few seconds of each other (Max a command, Noa a change to `README.md`, Rio a question), and Sam finishes the fourth task while the three cards wait. Max and Noa have written a file before they ask, so their unfinished tasks have a diff. With `?autoplay=1` the plan runs by itself, and the three cards still wait for you. | The request's thread: `?cards=3&autoplay=1` | | `?hour=13` | The demo's clock says 13:00 when the page loads, and goes on from there (from `0`, below `24`; `21.5` is 21:30). The office and the map are lit for the hour of the clock, so this sets their light; every time on screen follows. It opens no repo. | The office and the map: `?hour=13&ws=1` with the app's dark theme (a bright office under a dark app), `?hour=23&ws=1` with its light theme. | ### A kind of request (`?approval=`) diff --git a/src/lib/__tests__/demoBackground.test.ts b/src/lib/__tests__/demoBackground.test.ts index 5ef13988..6380fafb 100644 --- a/src/lib/__tests__/demoBackground.test.ts +++ b/src/lib/__tests__/demoBackground.test.ts @@ -3,7 +3,7 @@ // change, as the app gets it. "Stop" on her sheet ends the command sooner. With `?background=on` // a 1:1 agent leaves a command and a helper at work: "Stop" ends the one it names. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { MockControls } from '../demo/controls'; +import { MockControls, NOT_RUNNING } from '../demo/controls'; import { REPO, Sim } from '../demo/sim'; import { Story } from '../demo/story'; import type { Agent } from '../gen/Agent'; @@ -86,8 +86,8 @@ describe('the demo: a command an agent leaves running in the background', () => // Your act is on record, as in the app: it names what you stopped. const yours = () => sim.log.slice(before).filter((e) => e.kind.type === 'decision').map((e) => (e.kind.type === 'decision' ? e.kind.summary : '')); expect(yours()).toEqual([`asked Ada to stop what it left running in the background: ${COMMAND}`]); - // A second Stop finds it over: it answers, and nothing is said or recorded again. - expect(controls.stopTask(ada(sim)!.id, id)).toBeNull(); + // A second Stop finds it over: refused as the core refuses it, and nothing is said or recorded again. + expect(() => controls.stopTask(ada(sim)!.id, id)).toThrow(NOT_RUNNING); expect(lists(sim)).toHaveLength(2); expect(yours()).toHaveLength(1); expect(() => controls.stopTask(ada(sim)!.id, ' ')).toThrow('which background command?'); @@ -192,8 +192,8 @@ describe('`?background=on`: a 1:1 Claude agent leaves a command and a helper at expect(said(sim).pop()).toBe('The helper was stopped before it reported, so I do not have its answer.'); expect(eli(sim).status).toBe('idle'); - // A second Stop finds it over. The helper does not report later, and no third turn comes. - expect(controls.stopTask(eli(sim).id, helper.id)).toBeNull(); + // A second Stop finds it over, and is refused. The helper does not report later, and no third turn comes. + expect(() => controls.stopTask(eli(sim).id, helper.id)).toThrow(NOT_RUNNING); await vi.advanceTimersByTimeAsync(240_000); expect(of(sim, 'sub_agent').map((s) => s.status)).toEqual(['running', 'stopped']); expect(of(sim, 'background_tasks')).toHaveLength(3); diff --git a/src/lib/__tests__/demoStory.test.ts b/src/lib/__tests__/demoStory.test.ts index 34d74e3a..d32adcce 100644 --- a/src/lib/__tests__/demoStory.test.ts +++ b/src/lib/__tests__/demoStory.test.ts @@ -4,14 +4,25 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { rulePrefix } from '../demo/approvalRules'; import { ChecksDemo } from '../demo/checks'; -import { MockControls } from '../demo/controls'; +import claudeRs from '../../../crates/codly-core/src/adapters/claude.rs?raw'; +import mergeConflictRs from '../../../crates/codly-core/src/orchestrator/merge_conflict.rs?raw'; +import runsRs from '../../../crates/codly-core/src/orchestrator/runs.rs?raw'; +import schedulerRs from '../../../crates/codly-core/src/orchestrator/scheduler.rs?raw'; +import workspaceRs from '../../../crates/codly-core/src/orchestrator/workspace.rs?raw'; +import { MockControls, NOT_RUNNING } from '../demo/controls'; import { demoDraft, hireFromManifest, reviewHire } from '../demo/hire'; import { demoIntake } from '../demo/intake'; import { MergeConflictDemo } from '../demo/mergeConflict'; import { PullRequestDemo } from '../demo/pullrequest'; -import { REPO, Sim } from '../demo/sim'; +import { REPO, Sim, WITHOUT_FOLDER_CONFIG } from '../demo/sim'; import { demoStates, opensRepo } from '../demo/states'; -import { AMEND, REQUEST, REQUEST_B, Story, type StoryOptions } from '../demo/story'; +import { AMEND, AUTOPLAY, MERGE_FAILURES, REQUEST, REQUEST_B, REQUEST_CARDS, Story, type StoryOptions } from '../demo/story'; +import { TASK_FILES } from '../demo/repo'; +import { mockAgentDiff, mockAgentGit } from '../demo/agentgit'; +import { outcomeBy } from '../util/outcome'; +import { parseDiff } from '../util/diff'; +import { startedWithoutFolderConfig } from '../state/session'; +import type { Workspace } from '../gen/Workspace'; import type { Agent } from '../gen/Agent'; import type { Approval } from '../gen/Approval'; import type { EventKind } from '../gen/EventKind'; @@ -504,17 +515,17 @@ describe('the MCP servers of a Lead you stop', () => { describe('the demo states of docs/DEMO.md', () => { it('reads each parameter, and a value it does not know starts nothing', () => { - const all = demoStates(new URLSearchParams('trust=ask&merge=conflict&preview=running&checks=on&helper=slow&mode=plan&intake=pr&approval=question-long&hour=21.5&resume=ask&background=on&turn=failed&pr=open&search=fail&requests=two')); + const all = demoStates(new URLSearchParams('trust=ask&merge=conflict&preview=running&checks=on&helper=slow&mode=plan&intake=pr&approval=question-long&hour=21.5&resume=ask&background=on&turn=failed&pr=open&search=fail&requests=two&cards=3')); expect(all).toEqual({ trustAsk: true, mergeConflict: true, mergeChecks: false, previewRunning: true, checksOn: true, slowHelper: true, planMode: true, intake: 'pull_request', approval: 'question-long', hour: 21.5, - resumeAsk: true, background: true, turnFailed: true, prOpen: true, searchFails: true, twoRequests: true, + resumeAsk: true, background: true, turnFailed: true, prOpen: true, searchFails: true, twoRequests: true, threeCards: true, }); expect(demoStates(new URLSearchParams('merge=checks'))).toMatchObject({ mergeConflict: false, mergeChecks: true }); expect(demoStates(new URLSearchParams('intake=issue')).intake).toBe('issue'); - const none = demoStates(new URLSearchParams('merge=yes&preview=1&checks=off&helper=fast&mode=ask&intake=linear&speed=2&approval=all&hour=24&resume=always&background=off&turn=ok&pr=closed&search=ok&requests=2')); + const none = demoStates(new URLSearchParams('merge=yes&preview=1&checks=off&helper=fast&mode=ask&intake=linear&speed=2&approval=all&hour=24&resume=always&background=off&turn=ok&pr=closed&search=ok&requests=2&cards=2')); expect(none).toEqual({ trustAsk: false, mergeConflict: false, mergeChecks: false, previewRunning: false, checksOn: false, slowHelper: false, planMode: false, intake: null, approval: null, hour: null, - resumeAsk: false, background: false, turnFailed: false, prOpen: false, searchFails: false, twoRequests: false, + resumeAsk: false, background: false, turnFailed: false, prOpen: false, searchFails: false, twoRequests: false, threeCards: false, }); // Midnight is an hour; a parameter with no value, or with words, is none. expect(['hour=0', 'hour=', 'hour=noon', 'hour=-1'].map((q) => demoStates(new URLSearchParams(q)).hour)).toEqual([0, null, null, null]); @@ -527,7 +538,7 @@ describe('the demo states of docs/DEMO.md', () => { expect(opensRepo({ ...none, approval: 'file' })).toBe(true); expect(opensRepo({ ...none, resumeAsk: true })).toBe(true); expect(opensRepo({ ...none, background: true })).toBe(true); - for (const on of ['mergeChecks', 'turnFailed', 'prOpen', 'searchFails', 'twoRequests'] as const) expect(opensRepo({ ...none, [on]: true })).toBe(true); + for (const on of ['mergeChecks', 'turnFailed', 'prOpen', 'searchFails', 'twoRequests', 'threeCards'] as const) expect(opensRepo({ ...none, [on]: true })).toBe(true); }); it('a helper shows its kind, its own calls and its report; `?checks=on` runs your checks for each task', async () => { @@ -897,8 +908,11 @@ describe('“Stop” on a helper whose call waits for it', () => { await until(() => sim.taskByKey('t1')?.status === 'done'); expect(events(sim, 'turn_started', ada)).toHaveLength(1); expect(events(sim, 'turn_completed', ada).map((t) => t.status)).toEqual(['completed']); - // A second Stop finds it over. - expect(new MockControls(sim).stopTask(ada, row.call_id)).toBeNull(); + // A second Stop finds it over: refused in the core's words, and nothing changes. + const said = /pub const NOT_RUNNING: &str = "([^"]+)";/.exec(claudeRs)?.[1]; + expect(NOT_RUNNING).toBe(said); + expect(() => new MockControls(sim).stopTask(ada, row.call_id)).toThrow(NOT_RUNNING); + expect(() => new MockControls(sim).stopTask(ada, 'tid-nobody')).toThrow(NOT_RUNNING); expect(events(sim, 'sub_agent', ada).map((s) => s.status)).toEqual(['running', 'stopped']); }); }); @@ -946,3 +960,212 @@ describe('`?merge=checks`: a check of the finished plan fails on its merge', () expect(() => merge.resolve({ kind: 'plan', id: plan.id })).toThrow('this plan was cancelled, so no agent works on it any more; fix the checks yourself'); }); }); + +describe('a cancelled plan with finished work', () => { + it('is merged as the core merges it: refused for its check, fixed by you, and merged anyway when you choose so', async () => { + const { sim, story } = demo({ autoplay: true }); + await until(() => sim.taskByKey('t1')?.status === 'done' && planOf(sim, 'lead')?.status === 'running'); + const plan = planOf(sim, 'lead')!; + // While it runs it is not merged, in the core's words (orchestrator/workspace.rs `merge_plan`). + expect(workspaceRs).toContain('bail!("the plan is still running; wait until it is done (or cancel it)")'); + expect(() => story.mergePlan(plan.id)).toThrow('the plan is still running; wait until it is done (or cancel it)'); + story.cancelPlan(plan.id); + const merge = new MergeConflictDemo('checks', sim, story); + expect(() => merge.refuse(plan.id)).toThrow('failed, so nothing was merged'); + // "Have an agent fix it" is the button that says to fix the checks yourself (merge_conflict.rs `cancelled_refusal`). + expect(mergeConflictRs).toContain('format!("this plan was cancelled, so no agent works on it any more; {left} yourself")'); + expect(() => merge.resolve({ kind: 'plan', id: plan.id })).toThrow('this plan was cancelled, so no agent works on it any more; fix the checks yourself'); + // "Merge anyway" runs no check and merges what the plan finished, as the refusal says it can. + expect(() => merge.refuse(plan.id, true)).not.toThrow(); + expect(story.mergePlan(plan.id)).toMatch(/^[0-9a-f]{40}$/); + expect(sim.plans.get(plan.id)).toMatchObject({ status: 'cancelled', merged_sha: expect.any(String) }); + }); + + it('a plan that never ran has nothing to merge', async () => { + const { sim, story } = demo(); + await until(() => planOf(sim, 'lead')?.status === 'awaiting_approval'); + expect(() => story.mergePlan(planOf(sim, 'lead')!.id)).toThrow('the plan never ran, so there is nothing to merge'); + }); +}); + +describe('the fix of a check that fails on the merge', () => { + it('knows the line it changes in each check’s test file', () => { + for (const [check, f] of Object.entries(MERGE_FAILURES)) { + const file = TASK_FILES[f.files].find((x) => x.path === f.path); + expect(file?.after, check).toContain(f.from); + } + }); + + it('prints the failing test as a sentence, and its diff is the line it changed', async () => { + const { sim, story } = demo({ autoplay: true }); + await until(() => planOf(sim, 'lead')?.status === 'done'); + const plan = planOf(sim, 'lead')!; + const merge = new MergeConflictDemo('checks', sim, story); + expect(() => merge.refuse(plan.id)).toThrow('`npx playwright test settings-theme` failed'); + const fix = sim.tasks.get(merge.resolve({ kind: 'plan', id: plan.id }).resolving!)!; + await until(() => sim.tasks.get(fix.id)!.status === 'done'); + const fixer = sim.tasks.get(fix.id)!.assignee!; + const failed = events(sim, 'tool_completed', fixer).filter((c) => !c.ok).pop()!; + expect(failed.output).toContain(' ✘ tests/e2e/settings-theme.spec.ts: settings · theme › dark mode persists after reload: expected “dark”, got “light”'); + // Its card counts what it changed: one line in one file, not "+0 −0 in 0 files". + expect(parseDiff(story.taskDiff(fix.id)).map((f) => [f.path, f.added, f.removed])).toEqual([['tests/e2e/settings-theme.spec.ts', 1, 0]]); + expect(story.taskDiff(fix.id)).toContain("+ await page.waitForResponse((res) => res.url().endsWith('/api/settings'));"); + }); +}); + +describe('a task that waits on others', () => { + it('says why in the core’s words, and says it again when a task it waits on is cancelled', async () => { + expect(schedulerRs).toContain('format!("blocked: depends on {}", stuck.join(", "))'); + expect(schedulerRs).toContain('format!("waiting: depends on {}"'); + const { sim, story } = demo({ autoplay: true }); + await until(() => planOf(sim, 'lead')?.status === 'running'); + const plan = planOf(sim, 'lead')!; + const t3 = () => task(sim, plan.id, 't3')!; + expect(t3()).toMatchObject({ status: 'pending', status_reason: 'waiting: depends on t1, t2' }); + story.moveTask(task(sim, plan.id, 't1')!.id, 'cancelled'); + await vi.advanceTimersByTimeAsync(1000); + expect(t3()).toMatchObject({ status: 'pending', status_reason: 'blocked: depends on t1 (cancelled)' }); + const said = sim.log.filter((e) => e.task_id === t3().id && e.kind.type === 'decision' && e.kind.decision_type === 'schedule'); + expect(said.map((e) => e.kind.type === 'decision' && e.kind.summary)).toEqual(['waiting: depends on t1, t2', 'blocked: depends on t1 (cancelled)']); + }); +}); + +describe('a plan’s worker you took a task away from', () => { + it('takes the task again when you retry it, also when a 1:1 agent you hired has its name', async () => { + const { sim, story } = demo({ autoplay: true, story: { yourRequestFirst: true } }); + const fay = story.hire('codex'); + story.userChat('lead', REQUEST_B); + const t1 = () => task(sim, planOf(sim, 'lead')!.id, 't1'); + await until(() => !!planOf(sim, 'lead') && !!t1()?.assignee && sim.actor(t1()!.assignee!).inTurn); + const worker = t1()!.assignee!; + expect(sim.agents.get(worker)!.name).toBe('Fay 2'); + // Stop it, unassign it, Retry. + story.moveTask(t1()!.id, 'blocked'); + await until(() => sim.agents.get(worker)!.status === 'idle' && !sim.actor(worker).inTurn); + story.assignTask(t1()!.id, null); + story.moveTask(t1()!.id, 'ready'); + await until(() => t1()!.status === 'running'); + expect(t1()!.assignee).toBe(worker); + expect([...sim.agents.values()].map((a) => a.name)).not.toContain('Fay 3'); + expect(sim.agents.get(fay.id)).toMatchObject({ role: 'solo', task_id: null }); + }); +}); + +describe('a request that autoplay answered', () => { + it('says autoplay answered it, not you', async () => { + const { sim } = demo({ autoplay: true }); + const install = () => requests(sim, (a) => isCommand(a, 'npm install -D @testing-library/react'))[0]; + await until(() => install()?.status === 'approved'); + expect(install().decided_by).toBe(AUTOPLAY); + expect(events(sim, 'approval_resolved').find((e) => e.approval_id === install().id)).toMatchObject({ status: 'approved', by: AUTOPLAY }); + expect(outcomeBy(install().decided_by)).toBe('by autoplay'); + }); +}); + +describe('`?resume=ask`: a worker that waited for your Resume', () => { + it('starts its run with its session line, in its task’s worktree, before its turn', async () => { + const { sim, story } = demo({ story: { resumeAsk: true } }); + const ada = named(sim, 'Ada')!; + expect(events(sim, 'session_started', ada.id)).toEqual([]); + story.resumeWork(); + await until(() => events(sim, 'turn_started', ada.id).length === 1); + const session = sim.log.find((e) => e.agent_id === ada.id && e.kind.type === 'session_started')!; + expect(session.run_id).toBe(sim.agents.get(ada.id)!.run_id); + expect(session.kind).toMatchObject({ provider: 'claude', cwd: ada.worktree, session_id: ada.session_id }); + expect(sim.log.indexOf(session)).toBeLessThan(sim.log.findIndex((e) => e.agent_id === ada.id && e.kind.type === 'turn_started')); + }); +}); + +describe('a run that leaves out the repo’s own configuration', () => { + it('says so once, in the core’s words, for each Claude run that starts while you have not trusted it', async () => { + const fmt = /"(Started without this folder's \{\} configuration[^"]+)"/.exec(runsRs)?.[1]; + expect(fmt?.replace('{}', 'Claude Code')).toBe(WITHOUT_FOLDER_CONFIG); + const sim = new Sim({ speed: 1, skipMs: 0, autoplay: false }, DEFAULT_SETTINGS); + let without = false; + sim.withoutFolderConfig = () => without; + const story = new Story(sim, { yourRequestFirst: true }); + story.openWorkspace(REPO); + const before = story.hire('claude'); + without = true; + const eli = story.hire('claude'); + const kit = story.hire('codex'); + const notices = (id: string) => sim.log.filter((e) => e.agent_id === id && e.kind.type === 'notice'); + expect(notices(before.id)).toEqual([]); + expect(notices(kit.id)).toEqual([]); + expect(notices(eli.id).map((e) => [e.kind.type === 'notice' && e.kind.text, e.run_id])).toEqual([[WITHOUT_FOLDER_CONFIG, eli.run_id]]); + expect(startedWithoutFolderConfig(sim.log, eli.id, sim.agents.get(eli.id)!.run_id)).toBe(true); + // The agent that started before keeps its run as it was; its next run says it. + expect(startedWithoutFolderConfig(sim.log, before.id, before.run_id)).toBe(false); + story.interrupt(before.id, true); + sim.patchAgent(before.id, { permission_mode: 'accept_edits' }); + story.userChat(`agent:${before.id}`, 'Add a line about the changelog.'); + await until(() => notices(before.id).length === 1); + expect(startedWithoutFolderConfig(sim.log, before.id, sim.agents.get(before.id)!.run_id)).toBe(true); + }); +}); + +describe('the demo’s agents', () => { + it('get the same ids on every page load of the same office, and ids of their own', () => { + const office = (id: string) => { + const sim = new Sim({ speed: 1, skipMs: 0, autoplay: false }, DEFAULT_SETTINGS); + sim.workspace = { id } as Workspace; + return ['Ada', 'Ada', 'Bo'].map((name) => sim.newAgent({ name, provider: 'claude', model: null, role: 'worker', color: 0, billing: 'subscription' }).id); + }; + const first = office('ws-0198-7abc'); + expect(office('ws-0198-7abc')).toEqual(first); + expect(new Set(first).size).toBe(3); + expect(office('ws-0199-1234').some((id) => first.includes(id))).toBe(false); + }); +}); + +describe('the Git tab of a worker on a task', () => { + it('lists the files it wrote for the task, with their text, until Codly commits them', async () => { + const { sim, story } = demo({ autoplay: true }); + await until(() => !!named(sim, 'Bo') && events(sim, 'files_changed', named(sim, 'Bo')!.id).length === 2); + const bo = named(sim, 'Bo')!; + const files = mockAgentGit(bo, sim.now(), sim.log).files.map((f) => f.path); + expect(files).toEqual(['prisma/schema.prisma', 'prisma/migrations/20261025093000_add_theme/migration.sql']); + const t2 = sim.tasks.get(bo.task_id!)!; + const diff = parseDiff(mockAgentDiff(bo, sim.log, story.taskFiles(t2))); + expect(diff.map((f) => f.path)).toEqual(files); + expect(diff[0].added).toBeGreaterThan(0); + // Committed: nothing is left in its worktree. + await until(() => events(sim, 'committed', bo.id).length === 1); + expect(mockAgentGit(sim.agents.get(bo.id)!, sim.now(), sim.log).files).toEqual([]); + }); +}); + +describe('`?cards=3`: three cards wait in one thread', () => { + it('three workers of one plan ask within seconds of each other, and the fourth finishes while all three wait', async () => { + const { sim, story } = demo({ autoplay: true, story: { threeCards: true } }); + const plan = () => planOf(sim, 'lead'); + const t = (key: string) => task(sim, plan()!.id, key)!; + await until(() => !!plan() && task(sim, plan()!.id, 't4')?.status === 'done'); + expect(sim.chats.filter((c) => c.author === 'user').map((c) => c.text)).toEqual([REQUEST_CARDS]); + expect([...sim.tasks.values()].filter((x) => x.plan_id === plan()!.id).map((x) => [x.key, x.depends_on])).toEqual([['t1', []], ['t2', []], ['t3', []], ['t4', []]]); + // The three requests, one of each kind, all before the fourth task is done, and all three wait. + const asked = sim.log.filter((e) => e.kind.type === 'approval_requested'); + const done = sim.log.findIndex((e) => e.kind.type === 'task_changed' && e.kind.task.id === t('t4').id && e.kind.task.status === 'done'); + expect(asked.map((e) => (e.kind.type === 'approval_requested' ? e.kind.approval.subject.kind : null)).sort()).toEqual(['command', 'file_change', 'question']); + expect(asked.every((e) => sim.log.indexOf(e) < done)).toBe(true); + expect(asked[2].ts - asked[0].ts).toBeLessThan(5000); + const waiting = requests(sim, (a) => a.status === 'pending'); + expect(waiting.map((a) => sim.tasks.get(a.task_id!)!.key).sort()).toEqual(['t1', 't2', 't3']); + // A worker that waits with a file written has a diff on its unfinished task. + expect(parseDiff(story.taskDiff(t('t1').id)).map((f) => f.path)).toEqual(['.lintstagedrc.json']); + expect(parseDiff(story.taskDiff(t('t2').id)).map((f) => f.path)).toEqual(['docs/env.md']); + // Autoplay ran the plan, and leaves the three cards to you. + await vi.advanceTimersByTimeAsync(20_000); + expect(requests(sim, (a) => a.status === 'pending')).toHaveLength(3); + for (const a of waiting) story.resolveApproval(a.id, 'allow_once', null, a.subject.kind === 'question' ? { 'The licence says 2024. Which years should it name?': '2026' } : null); + await until(() => plan()!.status === 'done'); + expect(parseDiff(story.taskDiff(t('t2').id)).map((f) => f.path)).toEqual(['docs/env.md', 'README.md']); + expect(story.taskDiff(t('t3').id)).toContain('+Copyright (c) 2026 Acme Inc.'); + }); + + it('changes nothing in the script without the parameter', async () => { + const { sim } = demo(); + await until(() => sim.chats.some((c) => c.author === 'user')); + expect(sim.chats.filter((c) => c.author === 'user').map((c) => c.text)).toEqual([REQUEST]); + }); +}); diff --git a/src/lib/__tests__/demoWorkspaceId.test.ts b/src/lib/__tests__/demoWorkspaceId.test.ts index 1a021bdf..50d46b58 100644 --- a/src/lib/__tests__/demoWorkspaceId.test.ts +++ b/src/lib/__tests__/demoWorkspaceId.test.ts @@ -1,5 +1,5 @@ // The browser demo keeps one id for its repo per browser profile (demo/workspaceId.ts): after a -// reload it opens on the request you left, and the storage keeps no office look of the demo. +// reload it opens on the request you left, and the office keeps its look under that id only. import { afterEach, describe, expect, it, vi } from 'vitest'; import { demoWorkspaceId } from '../demo/workspaceId'; @@ -29,7 +29,7 @@ describe('the demo repo’s id', () => { expect(kept.get('codly.demo.workspace')).toBe(first); }); - it('takes away the office look of every load, its own id’s too, and keeps every other key', () => { + it('keeps the office look of its own id, takes away that of every other demo id, and keeps every other key', () => { const kept = fakeStorage({ 'codly.demo.workspace': 'ws-0198-7abc', 'codly.sims.ws-0198-7abc': 'mine', @@ -40,9 +40,10 @@ describe('the demo repo’s id', () => { 'codly.theme': 'dark', }); expect(demoWorkspaceId()).toBe('ws-0198-7abc'); - // The demo's agents get new ids on each load: nothing of an earlier load's look applies, - // and a kept key would grow by each load's agents. The request you were on is kept. - expect([...kept.keys()].sort()).toEqual(['codly.demo.workspace', 'codly.request.ws-0198-7abc', 'codly.sims.demo', 'codly.theme']); + // The demo's agents keep their ids from one load to the next: the look is theirs again. + // The looks an older demo left under an id of each load go; the request you were on is kept. + expect([...kept.keys()].sort()).toEqual(['codly.demo.workspace', 'codly.request.ws-0198-7abc', 'codly.sims.demo', 'codly.sims.ws-0198-7abc', 'codly.theme']); + expect(kept.get('codly.sims.ws-0198-7abc')).toBe('mine'); }); it('is a new one for the page when the browser keeps nothing', () => { diff --git a/src/lib/__tests__/demoWorktreeFiles.test.ts b/src/lib/__tests__/demoWorktreeFiles.test.ts index 717ba206..55de478d 100644 --- a/src/lib/__tests__/demoWorktreeFiles.test.ts +++ b/src/lib/__tests__/demoWorktreeFiles.test.ts @@ -44,6 +44,35 @@ describe('the demo agent’s worktree', () => { expect(files.every((f) => f.added === 2 && f.removed === 0)).toBe(true); }); + it('a worker on a task lists what it wrote for that task since Codly last committed it, not its other work', () => { + const fay = { id: 'w1', name: 'Fay', role: 'worker', task_id: 't2', worktree: '/demo/.codly/worktrees/t2-fay' } as Agent; + const log = [ + wrote('w1', 't1', 'src/old.ts'), + wrote('w1', null, 'notes.md'), + wrote('w1', 't2', 'src/first.ts'), + row('w1', 't2', { type: 'committed', sha: 'abc', files: ['src/first.ts'], message: 't2: first' }), + wrote('w1', 't2', 'src/second.ts', 'src/third.ts'), + wrote('w2', 't2', 'src/someone-else.ts'), + ]; + expect(mockAgentGit(fay, 0, log).files.map((f) => f.path)).toEqual(['src/second.ts', 'src/third.ts']); + // The files the task knows show their text; the diff has exactly the files the Git tab lists. + const known = [{ path: 'src/second.ts', before: 'a\n', after: 'a\nb\n' }]; + const files = parseDiff(mockAgentDiff(fay, log, known)); + expect(files.map((f) => [f.path, f.added, f.removed])).toEqual([['src/second.ts', 1, 0], ['src/third.ts', 2, 0]]); + // Off its task, it is back to its own changes outside any task. + expect(ownFiles({ ...fay, task_id: null }, log)).toEqual(['notes.md']); + }); + + it('a 1:1 agent’s edit shows the lines its call wrote, the ones its card showed', () => { + const edit = (call: string, input: unknown) => row('s1', null, { type: 'tool_started', call_id: call, name: 'Edit', activity: 'edit', target: { path: 'README.md', paths: [], command: null, query: null, url: null, server: null, tool: null }, input: input as never, confidence: 'observed' }); + const log = [ + edit('c1', { file_path: 'README.md', old_string: '- npm test', new_string: '- npm test\n\n## Notes\n\n- Theming' }), + row('s1', null, { type: 'files_changed', call_id: 'c1', paths: ['README.md'], source: 'tool_input' }), + ]; + const [file] = parseDiff(mockAgentDiff(eli, log)); + expect(file.hunks[0].lines.map((l) => [l.kind, l.text])).toEqual([['ctx', '- npm test'], ['add', ''], ['add', '## Notes'], ['add', ''], ['add', '- Theming']]); + }); + it('an agent with no worktree has neither', () => { const none = { ...eli, worktree: null } as Agent; expect(mockAgentGit(none, 0, [wrote('s1', null, 'a.ts')]).worktree).toBeNull(); diff --git a/src/lib/__tests__/mockTransport.test.ts b/src/lib/__tests__/mockTransport.test.ts index af361f8f..dc9149fa 100644 --- a/src/lib/__tests__/mockTransport.test.ts +++ b/src/lib/__tests__/mockTransport.test.ts @@ -19,6 +19,7 @@ import type { Snapshot } from '../gen/Snapshot'; import type { Task } from '../gen/Task'; import type { Workspace } from '../gen/Workspace'; import { HELD, REQUEST, REQUEST_B, REQUEST_B_THREAD } from '../demo/story'; +import { REPO } from '../demo/sim'; import { MockTransport } from '../mock'; import { intakeUi } from '../state/intake.svelte'; import { ofLiveRun, withMcpServer, type McpServer } from '../state/session'; @@ -460,6 +461,74 @@ describe('the demo transport', () => { expect((await call<{ query: string }>(open('?ws=1'), 'search_code', { query: 'theme' })).query).toBe('theme'); }); + it('`?merge=checks`: the merge is refused for a check that fails on the merge result, and "merge anyway" merges', async () => { + const t = open('?merge=checks&autoplay=1'); + const plan = await finished(t); + expect((await call(t, 'merge_state', { source: { kind: 'plan', id: plan.id } })).behind).toBe(1); + await expect(call(t, 'merge_plan', { planId: plan.id, into: null, unchecked: false })).rejects.toThrow('`npx playwright test settings-theme` failed, so nothing was merged'); + expect((await call(t, 'repo_sync')).ahead).toBe(0); + expect(await call(t, 'merge_plan', { planId: plan.id, into: null, unchecked: true })).toMatch(/^[0-9a-f]{40}$/); + // Without the parameter nothing fails on the merge. + const plain = open('?autoplay=1&ws=1'); + expect(await call(plain, 'merge_plan', { planId: (await finished(plain)).id, into: null, unchecked: false })).toMatch(/^[0-9a-f]{40}$/); + }); + + it('`?turn=failed`: the first turn of the 1:1 agent you hire fails; without it, it does not', async () => { + /** Hire a Codex agent (it only answers), send it a message, and read how its first turn ended. */ + const firstTurn = async (search: string) => { + const t = open(search); + const manifest = { ...reviewHire(demoDraft('Keep the docs up to date')).manifest, provider: 'codex' }; + const agent = await call(t, 'hire_from_manifest', { manifest, confirmShell: false }); + await call(t, 'send_chat', { thread: `agent:${agent.id}`, text: 'Are you free?' }); + let ended: EventRow | undefined; + for (let i = 0; i < 30 && !ended; i++) { + await vi.advanceTimersByTimeAsync(1000); + ended = (await snapshot(t)).events.find((e) => e.agent_id === agent.id && e.kind.type === 'turn_completed'); + } + return ended?.kind.type === 'turn_completed' ? ended.kind.status : null; + }; + expect(await firstTurn('?turn=failed')).toBe('failed'); + expect(await firstTurn('?intake=issue')).toBe('completed'); + }); + + it('merging a 1:1 agent’s branch with no commit of its own brings no commit onto main', async () => { + const t = open('?intake=issue'); + const agent = await call(t, 'hire_from_manifest', { manifest: reviewHire(demoDraft('Keep the docs up to date')).manifest, confirmShell: false }); + expect(await call(t, 'merge_agent', { agentId: agent.id })).toMatch(/^[0-9a-f]{10}$/); + expect((await call(t, 'repo_sync')).ahead).toBe(0); + }); + + it('`?cards=3&autoplay=1`: three cards of one plan wait, and its fourth task finishes meanwhile', async () => { + const t = open('?cards=3&autoplay=1'); + let s = await snapshot(t); + for (let i = 0; i < 60 && !s.tasks.some((x) => x.plan_id && x.key === 't4' && x.status === 'done'); i++) { + await vi.advanceTimersByTimeAsync(1000); + s = await snapshot(t); + } + const plan = s.plans.find((p) => p.thread === 'lead')!; + expect(plan.summary).toBe('Release checklist'); + expect(s.approvals.filter((a) => a.status === 'pending').map((a) => s.tasks.find((x) => x.id === a.task_id)?.key).sort()).toEqual(['t1', 't2', 't3']); + }); + + it('`?trust=ask`: after "Open without…", a Claude agent’s run says it started without the repo’s own configuration', async () => { + const t = open('?trust=ask'); + const asked = await call<{ state: string }>(t, 'workspace_trust', { set: null }); + expect(asked.state).toBe('ask'); + expect((await call<{ state: string }>(t, 'workspace_trust', { set: { trust: null } })).state).toBe('without'); + await call(t, 'open_workspace', { repoPath: REPO }); + let notice: EventRow | undefined; + for (let i = 0; i < 10 && !notice; i++) { + await vi.advanceTimersByTimeAsync(1000); + notice = (await snapshot(t)).events.find((e) => e.kind.type === 'notice' && e.kind.text.startsWith('Started without this folder')); + } + const lead = (await snapshot(t)).agents.find((a) => a.role === 'lead')!; + expect(notice).toMatchObject({ agent_id: lead.id, run_id: lead.run_id }); + // Trusted (the plain demo): no run says so. + const plain = open('?ws=1'); + await vi.advanceTimersByTimeAsync(5000); + expect((await snapshot(plain)).events.some((e) => e.kind.type === 'notice')).toBe(false); + }); + // The last test of this file: the demo's neighbourhood is one for the page, and an office that closed stays closed. it('answers Close office: the open office closes once its tasks are over, and its plot is free', async () => { // (`?intake=issue` opens the repo and starts no scripted request: no agent is in a turn) diff --git a/src/lib/demo/agentgit.ts b/src/lib/demo/agentgit.ts index 2fc2fdd3..dbd032a6 100644 --- a/src/lib/demo/agentgit.ts +++ b/src/lib/demo/agentgit.ts @@ -1,26 +1,38 @@ // The browser demo's answer to `agent_git` and `agent_diff`: an agent's worktree as the demo -// agent left it. Its changed files are the ones it wrote in its own conversation (its file -// changes outside any task, from the event log), so an agent that changed nothing lists no file -// and has an empty diff, and the diff has exactly the files the Git tab lists. Commits and -// branches are derived from its name, so each agent shows different (but stable) ones. +// agent left it. Its changed files are the ones it wrote there (from the event log): a 1:1 +// agent's are its file changes outside any task, and a worker's, while it is on a task, are its +// changes for that task since Codly last committed them (the worktree it works in is the +// task's). So an agent that changed nothing lists no file and has an empty diff, and the diff has +// exactly the files the Git tab lists. Commits and branches are derived from its name, so each +// agent shows different (but stable) ones. import type { Agent } from '../gen/Agent'; import type { AgentGit } from '../gen/AgentGit'; import type { EventRow } from '../gen/EventRow'; +import { unifiedDiff, type RepoFile } from './repo'; const MIN = 60_000; /** A stable 7-letter hex name for the `n`th object of the agent's worktree. */ const sha = (agent: Agent, n: number) => Array.from({ length: 7 }, (_, i) => '0123456789abcdef'[(agent.name.charCodeAt(i % agent.name.length) * (n + 3) + i * 7) % 16]).join(''); -/** The files the agent changed in its own worktree, in the order it first wrote them: its file - * changes outside any task (a task's work is in the task's worktree), relative to the worktree. - * A path outside it (another repository it was allowed to write) is not in its git status. */ +/** The rows of the log that count for the agent's worktree now: those after Codly last committed the task it is on. */ +function sinceCommit(agent: Agent, log: readonly EventRow[]): readonly EventRow[] { + if (!agent.task_id) return log; + for (let i = log.length - 1; i >= 0; i--) if (log[i].task_id === agent.task_id && log[i].kind.type === 'committed') return log.slice(i + 1); + return log; +} + +/** The files the agent changed in its worktree, in the order it first wrote them, relative to + * the worktree: a 1:1 agent's changes outside any task, a worker's for the task it is on (not + * committed yet). A path outside it (another repository it was allowed to write) is not in + * its git status. */ export function ownFiles(agent: Agent, log: readonly EventRow[]): string[] { const root = agent.worktree?.replace(/\/+$/, ''); if (!root) return []; + const task = agent.task_id ?? null; const out = new Set(); - for (const row of log) { - if (row.agent_id !== agent.id || row.task_id || row.kind.type !== 'files_changed') continue; + for (const row of sinceCommit(agent, log)) { + if (row.agent_id !== agent.id || row.task_id !== task || row.kind.type !== 'files_changed') continue; for (const p of row.kind.paths) { const rel = p.startsWith(`${root}/`) ? p.slice(root.length + 1) : p; if (!rel.startsWith('/') && !rel.split('/').includes('..')) out.add(rel); @@ -53,20 +65,53 @@ export function mockAgentGit(agent: Agent | undefined, now: number, log: readonl /** How a line of a note starts in a file of this kind. */ const noteMark = (path: string) => (/\.(md|txt)$/i.test(path) ? '' : /\.(py|sh|ya?ml|toml)$/i.test(path) ? '# ' : '// '); -/** `agent_diff`: one small change per file the Git tab lists (`mockAgentGit`), nothing for an agent that changed nothing. */ -export function mockAgentDiff(agent: Agent | undefined, log: readonly EventRow[]): string { +/** + * The lines of the agent's last Claude `Edit` (or `Write`) of `path`, from the call's input as + * Claude Code sends it (`old_string` and `new_string`, or `content`): the lines both strings + * start with stay, the rest is taken out and put in. Null when no call of it carries the text. + */ +function editLines(agent: Agent, log: readonly EventRow[], path: string): string[] | null { + const inputs = new Map(); + let last: unknown = null; + for (const row of log) { + if (row.agent_id !== agent.id) continue; + if (row.kind.type === 'tool_started' && row.kind.call_id) inputs.set(row.kind.call_id, row.kind.input); + if (row.kind.type === 'files_changed' && row.kind.call_id && row.kind.paths.includes(path)) last = inputs.get(row.kind.call_id) ?? null; + } + const input = last && typeof last === 'object' && !Array.isArray(last) ? (last as Record) : null; + if (typeof input?.content === 'string') return input.content.replace(/\n$/, '').split('\n').map((l) => `+${l}`); + if (typeof input?.old_string !== 'string' || typeof input.new_string !== 'string') return null; + const before = input.old_string.split('\n'); + const after = input.new_string.split('\n'); + let same = 0; + while (same < before.length && same < after.length && before[same] === after[same]) same++; + return [...before.slice(0, same).map((l) => ` ${l}`), ...before.slice(same).map((l) => `-${l}`), ...after.slice(same).map((l) => `+${l}`)]; +} + +/** + * `agent_diff`: one change per file the Git tab lists (`mockAgentGit`), nothing for an agent + * that changed nothing. `known`: the files of the task the agent is on, as the task's diff has + * them; a file it edited with a call that carries the text shows that text (the change you saw + * on its card); any other file a short note. + */ +export function mockAgentDiff(agent: Agent | undefined, log: readonly EventRow[], known: readonly RepoFile[] = []): string { if (!agent?.worktree) return ''; return ownFiles(agent, log) .map((path, i) => { + const file = known.find((f) => f.path === path); + if (file) return `${unifiedDiff(file)}\n`; + const edit = editLines(agent, log, path); const mark = noteMark(path); + const lines = edit ?? [`+${mark}${agent.name}: a change from its 1:1 conversation.`, `+${mark}Not committed yet.`]; + const removed = lines.filter((l) => !l.startsWith('+')).length; + const added = lines.filter((l) => !l.startsWith('-')).length; return [ `diff --git a/${path} b/${path}`, `index ${sha(agent, 2 * i)}..${sha(agent, 2 * i + 1)} 100644`, `--- a/${path}`, `+++ b/${path}`, - '@@ -1,0 +2,2 @@', - `+${mark}${agent.name}: a change from its 1:1 conversation.`, - `+${mark}Not committed yet.`, + edit ? `@@ -1,${removed} +1,${added} @@` : '@@ -1,0 +2,2 @@', + ...lines, '', ].join('\n'); }) diff --git a/src/lib/demo/controls.ts b/src/lib/demo/controls.ts index 0507ea6b..39e3a550 100644 --- a/src/lib/demo/controls.ts +++ b/src/lib/demo/controls.ts @@ -23,6 +23,9 @@ export const DEMO_MCP: { name: string; status: McpServerStatus; error: string | { name: 'postgres', status: 'failed', error: 'MCP error -32000: Connection closed' }, ]; +/** The refusal of a stop for an id that names nothing running beside the agent (adapters/claude.rs `NOT_RUNNING`). */ +export const NOT_RUNNING = 'that work is not running any more'; + /** The name the agent panel gives each mode (the core's `PermissionMode::label`). */ export const MODE_LABEL: Record = { ask: 'ask for edits', accept_edits: 'accept edits', plan: 'plan first' }; @@ -229,8 +232,8 @@ export class MockControls { * A helper is stopped the same way, and the agent is then told in a turn of its own * (demo/background.ts). `taskId`: the id the agent's list gives the one to stop, or the call * id of a helper whose call waits for it (in no list): that helper ends, and the agent's turn - * goes on. Like Claude Code, a stop of something that is over already answers and changes - * nothing. */ + * goes on. Like the core, an id that names neither (or something that is over already) is + * refused, and nothing reaches the CLI. */ stopTask(id: string, taskId: string): null { const a = this.agent(id); if (!taskId.trim()) throw new Error('which background command?'); @@ -242,7 +245,7 @@ export class MockControls { return null; } const helper = background.waiting(id, taskId); - if (helper === null) return null; + if (helper === null) throw new Error(NOT_RUNNING); this.note(id, `asked ${a.name} to stop its helper: ${helper}`); background.stopWaited(id, taskId); return null; diff --git a/src/lib/demo/sim.ts b/src/lib/demo/sim.ts index c2745e51..f10d8b3c 100644 --- a/src/lib/demo/sim.ts +++ b/src/lib/demo/sim.ts @@ -61,6 +61,10 @@ export function uid(prefix = ''): string { return `${prefix}${t.slice(0, 8)}-${t.slice(8, 12)}-7${r.slice(0, 3)}-${r.slice(3, 7)}-${r.slice(7)}${Math.random().toString(16).slice(2, 6)}`; } +/** The core's notice for a Claude run that started without the folder's own configuration (orchestrator/runs.rs, with `provider.label()`). */ +export const WITHOUT_FOLDER_CONFIG = + "Started without this folder's Claude Code configuration (its settings, hooks and MCP servers): you have not trusted these files. See Settings → Safety."; + export const sha = () => Array.from({ length: 40 }, () => '0123456789abcdef'[Math.floor(Math.random() * 16)]).join(''); const PRICES: Record = { @@ -117,6 +121,10 @@ export class Sim { afterStep: ((act: Actor) => Promise) | null = null; /** Runs when an agent's turn was stopped, after its `turn_completed` (the story sets it). */ turnStopped: ((act: Actor) => void) | null = null; + /** Runs when an agent's process starts again, for a turn (the story sets it: the CLI's session line). */ + runStarts: ((act: Actor) => void) | null = null; + /** Whether a Claude run that starts now leaves out the folder's own CLI configuration: you opened the repo without it (mock.ts sets it). */ + withoutFolderConfig: () => boolean = () => false; /** The offices of this machine that the demo plays, this one included (`sameMachineAs`). */ machine: Sim[] = [this]; private waiters = new Set(); @@ -184,10 +192,12 @@ export class Sim { /** * The agent's process starts: a run of its own, as in the core. Like Claude Code at the start - * of a session, it says again where each of its MCP servers stands (here: as it last stood). + * of a session, it says which session it is, then where each of its MCP servers stands (here: + * as it last stood). */ startRun(agentId: string) { const a = this.patchAgent(agentId, { run_id: uid('r-') }); + this.runStarts?.(this.actor(agentId)); for (const [key, row] of [...this.session]) if (key.startsWith(`${agentId}:mcp:`)) this.emit(row.kind, { agent: a.id, task: a.task_id, run: a.run_id }); } @@ -245,8 +255,13 @@ export class Sim { // ───────────── entities ───────────── putAgent(a: Agent) { + const before = this.agents.get(a.id)?.run_id ?? null; this.agents.set(a.id, a); this.emit({ type: 'agent_changed', agent: a }, { agent: a.id, task: a.task_id, run: a.run_id }); + // Like the core (orchestrator/runs.rs), once per run: a Claude run that leaves out the folder's own configuration says so. + if (a.run_id && a.run_id !== before && a.provider === 'claude' && this.withoutFolderConfig()) { + this.emit({ type: 'notice', text: WITHOUT_FOLDER_CONFIG }, { agent: a.id, task: a.task_id, run: a.run_id }); + } return a; } @@ -374,10 +389,31 @@ export class Sim { return null; } + /** By name: how many agents of that name this office made so far (`agentId`). */ + private named = new Map(); + + /** + * A new agent's id: the same on every page load for the same office, name and count of that + * name, as a real office keeps its agents. What the office keeps of an agent by its id (its + * look, in the browser's storage) is then its own again after a reload. + */ + private agentId(name: string): string { + const n = (this.named.get(name) ?? 0) + 1; + this.named.set(name, n); + const key = `${this.workspace?.id ?? ''}\u0000${name}\u0000${n}`; + // Two FNV-1a hashes of the key (the second of it read backwards): 64 bits, as 16 hex letters. + const fnv = (s: string) => { + let h = 2166136261; + for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619); + return (h >>> 0).toString(16).padStart(8, '0'); + }; + return `a-${fnv(key)}${fnv([...key].reverse().join(''))}`; + } + newAgent(o: { name: string; provider: Provider; model: string | null; role: Role; color: number; billing: Billing; taskId?: string | null; worktree?: string | null; status?: AgentStatus; thread?: string }): Agent { const now = this.now(); return { - id: uid('a-'), + id: this.agentId(o.name), thread: o.role === 'lead' ? (o.thread ?? 'lead') : null, account: this.signIns.pick(o.provider, o.role, this.settings, this.clis, [...this.agents.values()], now), name: o.name, diff --git a/src/lib/demo/states.ts b/src/lib/demo/states.ts index ffff682b..d3aea381 100644 --- a/src/lib/demo/states.ts +++ b/src/lib/demo/states.ts @@ -41,6 +41,8 @@ export type DemoStates = { searchFails: boolean; /** `?requests=two`: both scripted requests are there when the page loads. */ twoRequests: boolean; + /** `?cards=3`: the request is a plan of four tasks, and three of its workers ask you within seconds of each other. */ + threeCards: boolean; }; export function demoStates(params: URLSearchParams): DemoStates { @@ -64,6 +66,7 @@ export function demoStates(params: URLSearchParams): DemoStates { prOpen: params.get('pr') === 'open', searchFails: params.get('search') === 'fail', twoRequests: params.get('requests') === 'two', + threeCards: params.get('cards') === '3', }; } @@ -74,6 +77,6 @@ export function demoStates(params: URLSearchParams): DemoStates { export function opensRepo(s: DemoStates): boolean { return ( s.mergeConflict || s.mergeChecks || s.previewRunning || s.checksOn || s.slowHelper || s.planMode || s.intake !== null || s.approval !== null || s.resumeAsk || s.background || - s.turnFailed || s.prOpen || s.searchFails || s.twoRequests + s.turnFailed || s.prOpen || s.searchFails || s.twoRequests || s.threeCards ); } diff --git a/src/lib/demo/story.ts b/src/lib/demo/story.ts index 30403a84..eaba0be9 100644 --- a/src/lib/demo/story.ts +++ b/src/lib/demo/story.ts @@ -50,6 +50,8 @@ export const AMEND = 'Also make the toggle fully keyboard-accessible: arrow keys export const REQUEST_B = 'Lock sign-in for 15 minutes after 5 failed attempts, and tell people clearly when they’re locked out.'; /** The second request's thread: the same on every page load, so a reload can open on it (`?requests=two`). */ export const REQUEST_B_THREAD = 'lead:lockout'; +/** `?cards=3`: the request whose plan has four tasks that wait on nothing; three of its workers ask you within seconds of each other. */ +export const REQUEST_CARDS = 'Get the repo ready for the release: lint staged files before each commit, document the environment variables, update the licence year, and add the release to the changelog.'; /** The one request of the demo's second office, billing-api: asked before you opened it. */ export const REQUEST_BILLING = 'Try a failed invoice payment again, once a day and three times at most. After the last try, email the customer.'; @@ -64,8 +66,8 @@ const WORKER_MODELS: Record = { }; const PROVIDER_NAME: Record = { claude: 'Claude Code', codex: 'Codex', gemini: 'Gemini CLI', opencode: 'OpenCode', cursor: 'Cursor', copilot: 'Copilot' }; -/** The plans the demo scripts: two in acme/web, and `retries` in billing-api. */ -type Spec = 'theme' | 'lockout' | 'retries'; +/** The plans the demo scripts: two in acme/web (and `cards` there with `?cards=3`), and `retries` in billing-api. */ +type Spec = 'theme' | 'lockout' | 'retries' | 'cards'; /** Who takes each planned task, and why (the route decision says it). */ const ROUTES: Record> = { theme: { @@ -81,10 +83,16 @@ const ROUTES: Record = { theme: 'codly/dark-mode', lockout: 'codly/sign-in-lockout', retries: 'codly/payment-retries' }; -/** Task key → the demo files it writes (the key of `filesOf`). */ -const FILES: Record> = { theme: { t1: 't1', t2: 't2', t3: 't3' }, lockout: { t1: 'l1', t2: 'l2' }, retries: { t1: 'b1', t2: 'b2' } }; +const BRANCH: Record = { theme: 'codly/dark-mode', lockout: 'codly/sign-in-lockout', retries: 'codly/payment-retries', cards: 'codly/release-checklist' }; +/** Task key → the demo files it writes (the key of `filesOf`). The `cards` tasks write files whose text they decide as they work (`Story.written`). */ +const FILES: Record> = { theme: { t1: 't1', t2: 't2', t3: 't3' }, lockout: { t1: 'l1', t2: 'l2' }, retries: { t1: 'b1', t2: 'b2' }, cards: {} }; /** The demo files of a task, by its file key (acme/web's, or billing-api's). */ const filesOf = (key: string): RepoFile[] | undefined => TASK_FILES[key] ?? BILLING_FILES[key]; /** A plan that is done: what its Lead offers when you write again. */ @@ -92,12 +100,15 @@ const FOLLOW_UP: Record = { theme: 'A good next step is rendering the theme on the server so the first paint never flashes', lockout: 'A good next step is an admin unlock and an email to the account owner after a lockout', retries: 'A good next step is a page where the customer can pay an unpaid invoice with another card', + cards: 'A good next step is a release script that runs these checks and tags the version', }; /** The tool a CLI runs a shell command with, as its other calls in the story name it. */ const shellTool = (provider: Provider) => (provider === 'claude' ? 'Bash' : provider === 'codex' ? 'commandExecution' : 'run_shell_command'); const KEYBOARD = /keyboard|arrow|a11y|accessib/i; /** Why a task does not start while the work of the last run waits for your Resume: the core's words (orchestrator/resume.rs `HELD`). */ export const HELD = "paused: Codly restarted. Nothing starts until you press 'Resume work' at the top of the window"; +/** Who answered a request that `?autoplay=1` answered: its rows read "Approved by autoplay", not "by you". */ +export const AUTOPLAY = 'autoplay'; const NO_TARGET: Target = { path: null, paths: [], command: null, query: null, url: null, server: null, tool: null }; /** Claude Code and Codex take a message into the turn that runs; the other CLIs run it as the next turn (state/queue.ts). */ const readsMidTurn = (provider: Provider) => provider === 'claude' || provider === 'codex'; @@ -128,6 +139,56 @@ const soloPlan = (ask: string, note: string | null) => '2. Run `npm test`.', '3. Tell you what changed.', ...(note ? ['', `Changed as you asked: ${note}`] : []), '', 'Nothing changes before you accept this plan.', ].join('\n'); +/** The demo repo's README.md, as the agents read it. */ +const README = '# Acme web\n\nNext.js 16 (app router) · Prisma · Postgres · vitest · Playwright\n\n## Scripts\n- npm run dev\n- npm test\n- npx playwright test\n'; +/** Its last line: where an agent adds to it. */ +const README_TAIL = '- npx playwright test'; +/** The preview of a Claude `Edit` on its card: the old lines taken out, the new ones put in (adapters/claude.rs `edit_preview`). */ +const editPreview = (before: string, after: string) => `${before.split('\n').map((l) => `-${l}`).join('\n')}\n${after.split('\n').map((l) => `+${l}`).join('\n')}`; + +/** + * `?merge=checks`: why a check of a demo plan fails on its merge with your branch, said as the + * check prints it, and the line of its test file that the agent's fix changes. A plan fails with + * the last of these checks that its finished tasks ran (`failingChecks`); a check of no entry + * here passes on the merge (billing-api's plan has none: that office never starts with it). + */ +export const MERGE_FAILURES: Record = { + 'npm test -- theme': { + files: 't1', path: 'src/theme/ThemeProvider.test.tsx', test: 'ThemeProvider › follows the system by default', why: 'expected “system:dark”, got “system:light”', + from: ' beforeEach(() => localStorage.clear());', + to: ' beforeEach(() => {\n localStorage.clear();\n delete document.documentElement.dataset.theme;\n });', + }, + 'npm test -- settings': { + files: 't2', path: 'src/server/settings/route.test.ts', test: '/api/settings › returns defaults for a new user', why: 'expected 3 fields, got 4', + from: " expect(await res.json()).toEqual({ locale: 'en', emailDigest: true, theme: 'system' });", + to: " expect(await res.json()).toMatchObject({ locale: 'en', emailDigest: true, theme: 'system' });", + }, + 'npx playwright test settings-theme': { + files: 't3', path: 'tests/e2e/settings-theme.spec.ts', test: 'settings · theme › dark mode persists after reload', why: 'expected “dark”, got “light”', + from: ' await page.reload();', + to: " await page.waitForResponse((res) => res.url().endsWith('/api/settings'));\n await page.reload();", + }, + 'npm test -- rate-limit': { + files: 'l1', path: 'src/server/rate-limit.test.ts', test: 'sign-in lockout › lifts after the window', why: 'expected 0, got 1', + from: ' vi.advanceTimersByTime(LOCKOUT.windowSec * 1000 + 1);', + to: ' await vi.advanceTimersByTimeAsync(LOCKOUT.windowSec * 1000 + 1);', + }, + 'npx playwright test auth-lockout': { + files: 'l2', path: 'tests/e2e/auth-lockout.spec.ts', test: 'five wrong passwords lock the account for 15 minutes', why: 'expected “Too many attempts”, got “Too many sign-in attempts”', + from: "toContainText('Too many attempts')", + to: "toContainText('Too many sign-in attempts')", + }, +}; + +/** `?cards=3`: the files the release checklist's tasks write. */ +const LINT_STAGED = '{\n "*.{ts,tsx}": ["eslint --fix", "prettier --write"]\n}\n'; +const PRE_COMMIT = 'npx lint-staged\n'; +const ENV_DOC = '# Environment variables\n\n| Name | What it is |\n| --- | --- |\n| `DATABASE_URL` | The Postgres database |\n| `SESSION_SECRET` | Signs the session cookie |\n| `STRIPE_TEST_KEY` | Stripe in tests (never the live key) |\n'; +const README_ENV = `${README}\n## Environment\n\nEvery variable is in [docs/env.md](docs/env.md).\n`; +const licence = (years: string) => `MIT License\n\nCopyright (c) ${years} Acme Inc.\n`; +const CHANGELOG_BEFORE = '# Changelog\n\n## 2.4.0\n\n- Bumped Next.js to 16.1.\n'; +const CHANGELOG_AFTER = '# Changelog\n\n## 2.5.0\n\n- Lint runs on staged files before each commit.\n- The environment variables are in docs/env.md.\n\n## 2.4.0\n\n- Bumped Next.js to 16.1.\n'; + function stats(files: RepoFile[]) { const d = diffOf(files).split('\n'); return { @@ -166,12 +227,16 @@ export type StoryOptions = { failFirstTurn?: boolean; /** `?requests=two`: both scripted requests are there when the repo opens, not 1.6 and 24 seconds later. */ twoRequests?: boolean; + /** `?cards=3`: the one request is the release checklist (`REQUEST_CARDS`), not the scripted two. */ + threeCards?: boolean; }; /** * `?approval=…`: who asks (a 1:1 agent of that CLI), and what you asked it. `plan` and `file` * are a 1:1 Claude agent in its mode (`soloWork`). The names are none of the plans' workers - * (`ROUTES`): a plan takes a free agent with its worker's name. + * (`ROUTES`). A plan's task goes to the worker started for it, else to a free worker of the + * route's name, and never to a 1:1 agent: one you hired with a worker's name makes the plan + * start " 2" (`startPlanned`). */ const ASKERS: Record, { provider: Provider; name: string; title: string; text: string }[]> = { // Claude Code's shell sandbox asks for a host on behalf of a command (adapters/claude.rs `SANDBOX_NETWORK`). @@ -231,6 +296,10 @@ export class Story { private failNext: boolean; /** The tasks that go on after your Resume: their worker of the last run takes them again, at the same attempt. */ private resumed = new Set(); + /** ":" → the worker the plan's route chose for that task: it takes the task again. */ + private routed = new Map(); + /** task id → the files it wrote whose text it decided as it worked (a fix, the release checklist): its diff. */ + private written = new Map(); constructor(private sim: Sim, private opts: StoryOptions = {}) { this.rules = new MockApprovalRules(sim, this); @@ -239,6 +308,7 @@ export class Story { this.failNext = opts.failFirstTurn ?? false; sim.afterStep = (act) => this.readMidTurn(act); sim.turnStopped = (act) => demoBackground(sim).turnStopped(act); + sim.runStarts = (act) => this.sessionStarted(act); } // ───────────── workspace ───────────── @@ -295,6 +365,10 @@ export class Story { if (this.opts.background) this.seedBackground(); if (this.opts.resumeAsk) this.seedHeld(); if (this.opts.yourRequestFirst) return sim.workspace; + if (this.opts.threeCards) { + void sim.sleep(1600).then(() => this.userChat('lead', REQUEST_CARDS)); + return sim.workspace; + } // The demo's "you": ask for the feature, add a detail while the Lead is still planning (it // reads it after its current step, or it queues), then open a second request in parallel. const first = () => { @@ -437,11 +511,7 @@ export class Story { color: [6, 5, 1, 0][n % 4], billing: 'subscription', worktree: null, thread, })); const act = sim.actor(lead.id); - act.emit({ - type: 'session_started', provider, model: lead.model, cwd: sim.workspace?.repo_path ?? REPO, cli_version: '2.1.309', - session_id: lead.session_id, billing: 'subscription', - tools: ['Read', 'Grep', 'Glob', 'WebFetch', 'mcp__codly__codly_search', 'mcp__codly__codly_submit_plan', 'mcp__codly__codly_memory_search'], - }); + this.sessionStarted(act); // Like Claude Code when a session starts: where each of its MCP servers stands. The office's // first Lead has one of each kind, so its sheet shows the section "MCP servers". if (!n && provider === 'claude') for (const server of DEMO_MCP) act.emit({ type: 'mcp_server', ...server }); @@ -478,6 +548,7 @@ export class Story { // billing-api has its one plan: the demo scripts no other there. if (this.opts.billing) return null; const used = new Set([...this.reqs.values()].map((r) => r.spec).filter(Boolean)); + if (this.opts.threeCards && thread === 'lead' && !used.has('cards')) return 'cards'; if (/lock|sign.?in|login|password|attempt|brute/i.test(text) && !used.has('lockout')) return 'lockout'; if (/dark|theme|toggle|appearance/i.test(text) && !used.has('theme')) return 'theme'; if (thread === 'lead' && !used.has('theme') && !/explain|how does|how do|flaky|checkout/i.test(text)) return 'theme'; @@ -491,6 +562,7 @@ export class Story { // everything you said so far. r.words.push(text); if (r.spec === 'theme') await this.planTheme(lead, r); + else if (r.spec === 'cards') await this.planCards(lead, r); else await this.planLockout(lead, r); return; } @@ -570,7 +642,9 @@ export class Story { assignee: null, agent_hint: null, account_hint: null, consultant: null, fresh_session: false, branch: null, worktree: null, attempt: 0, status_reason: 'Plan awaiting your go', summary: null, created_at: now, updated_at: now, ...o, }); - this.fileKeys.set(t.id, FILES[spec][key]); + // (one with no demo files of its own gets a key of its own: plans reuse t1, t2…) + const files: string | undefined = FILES[spec][key]; + this.fileKeys.set(t.id, files ?? `${spec}:${key}`); return t; } @@ -593,8 +667,7 @@ export class Story { 'The user wants a theme toggle that persists per user and defaults to the system. I need to know how tokens are defined, ' + 'whether anything already switches themes, and where settings are stored. Read before planning.', ); - await lead.tool({ name: 'Read', activity: 'read', target: { path: 'README.md' }, ms: 900, - output: '# Acme web\n\nNext.js 16 (app router) · Prisma · Postgres · vitest · Playwright\n\n## Scripts\n- npm run dev\n- npm test\n- npx playwright test' }); + await lead.tool({ name: 'Read', activity: 'read', target: { path: 'README.md' }, ms: 900, output: README }); await lead.tool({ name: 'Glob', activity: 'search', target: { query: 'src/**/*theme*' }, ms: 700, output: 'No files found' }); await lead.tool({ name: 'Grep', activity: 'search', target: { query: 'dark|prefers-color-scheme|data-theme' }, ms: 1300, output: 'src/styles/tokens.css:11:.dark {\nsrc/hooks/useMediaQuery.ts:4: const mql = window.matchMedia(query);' }); @@ -710,6 +783,143 @@ export class Story { return sim.patchPlan(plan.id, { status: 'awaiting_approval' }); } + // ───────────── `?cards=3`: the release checklist ───────────── + + private async planCards(lead: Actor, r: Req) { + await lead.sleep(500); + await lead.turn(r.words[r.words.length - 1], async () => { + await lead.think('Four small chores that touch different files: each can be its own task, and none waits for another.'); + await lead.tool({ name: 'Read', activity: 'read', target: { path: 'README.md' }, ms: 700, output: README }); + await lead.tool({ name: 'Glob', activity: 'search', target: { query: '{LICENSE,CHANGELOG.md,.husky/*}' }, ms: 600, output: 'LICENSE\nCHANGELOG.md' }); + await lead.tool({ name: 'mcp__codly__codly_submit_plan', activity: 'plan', target: { server: 'codly', tool: 'codly_submit_plan' }, ms: 900 }); + const plan = this.submitCards(lead, r); + this.postPlanReady(r, plan, 4); + await lead.say('Four tasks, and none waits for another, so all four start at once: **t1** the lint hook, **t2** the environment docs, **t3** the licence year and **t4** the changelog.', { thread: r.thread }); + }); + lead.status('idle'); + void this.autoRun(r); + } + + private submitCards(lead: Actor, r: Req): Plan { + const sim = this.sim; + const plan = this.newPlan(r, 'cards', { + summary: 'Release checklist', + assumptions: ['The release is 2.5.0', 'The licence keeps its holder, Acme Inc.'], + open_questions: [], + }); + const tasks = [ + this.newTask(plan, 'cards', 't1', 'Lint staged files before each commit', 'Add a lint-staged config and a pre-commit hook that runs it.', { + acceptance: ['A commit runs eslint and prettier on the staged files only'], write_scope: ['.lintstagedrc.json', '.husky/**'], verify: ['npx lint-staged --diff HEAD'], agent_hint: 'claude', + }), + this.newTask(plan, 'cards', 't2', 'Document the environment variables', 'List every environment variable in `docs/env.md`, and point to it from the README.', { + acceptance: ['Each variable the code reads is listed, with what it is'], write_scope: ['docs/env.md', 'README.md'], verify: ['npx markdownlint docs/env.md README.md'], agent_hint: 'codex', + }), + this.newTask(plan, 'cards', 't3', 'Update the licence year', 'The licence still says 2024: make it name the years the code was written in.', { + acceptance: ['LICENSE names this year'], write_scope: ['LICENSE'], verify: ['grep -q 2026 LICENSE'], agent_hint: 'claude', + }), + this.newTask(plan, 'cards', 't4', 'Add the release to the changelog', 'Add a `2.5.0` section on top of `CHANGELOG.md` with what this release brings.', { + acceptance: ['CHANGELOG.md starts with the 2.5.0 section'], write_scope: ['CHANGELOG.md'], verify: ['npx markdownlint CHANGELOG.md'], agent_hint: 'gemini', + }), + ]; + sim.decision('plan_validated', 'rule', 'Plan is a valid DAG: 4 tasks, no dependencies, no cycles', { plan_id: plan.id, tasks: 4, edges: 0 }, { agent: lead.id }); + sim.decision('scope_check', 'rule', 'Write scopes are disjoint, so all four tasks can run in parallel', { plan_id: plan.id, ...Object.fromEntries(tasks.map((t) => [t.key, t.write_scope])) }, { agent: lead.id }); + return sim.patchPlan(plan.id, { status: 'awaiting_approval' }); + } + + /** A file a task writes, with the text its worker decided on: it is in the task's diff from then on. */ + private wrote(task: Task, file: RepoFile) { + this.written.set(task.id, [...(this.written.get(task.id) ?? []).filter((f) => f.path !== file.path), file]); + } + + /** The paths a task wrote with a text of its own (`wrote`), for its commit. */ + private writtenPaths(task: Task): string[] { + return (this.written.get(task.id) ?? []).map((f) => f.path); + } + + /** The release checklist's t1. Max writes the config, then asks before the command that adds the git hook. */ + private async trackC1(max: Actor, task: Task) { + const steps = ['Write the lint-staged config', 'Add the pre-commit hook', 'Tell the Lead']; + await max.sleep(900); + await max.turn(`Task t1 · ${task.title}\n\n${task.goal}`, async () => { + max.plan(listAt(steps, 0)); + await max.think('A config for lint-staged first, then husky adds the hook that runs it.', { pace: 40 }); + this.wrote(task, { path: '.lintstagedrc.json', before: null, after: LINT_STAGED }); + await max.tool({ name: 'Write', activity: 'create', target: { path: '.lintstagedrc.json' }, input: { file_path: '.lintstagedrc.json', content: LINT_STAGED }, ms: 1200, files: ['.lintstagedrc.json'], taskKey: task.id }); + max.plan(listAt(steps, 1)); + // Left for you, also with `?autoplay=1`: the three cards are there to look at. + const hook = await this.approval(max, 'npx husky init', 'Adds a pre-commit hook in .husky/ that runs lint-staged before each commit.', ['changes the git hooks'], ['husky - Git hooks set up in .husky/'], null); + if (hook === 'approved') { + this.wrote(task, { path: '.husky/pre-commit', before: null, after: PRE_COMMIT }); + await max.tool({ name: 'Write', activity: 'create', target: { path: '.husky/pre-commit' }, input: { file_path: '.husky/pre-commit', content: PRE_COMMIT }, ms: 800, files: ['.husky/pre-commit'], taskKey: task.id }); + } + max.plan(listAt(steps, 2)); + await max.say(hook === 'approved' ? 'A commit now runs eslint and prettier on the staged files.' : 'The config is there; without the hook it runs only when you call `npx lint-staged`.'); + }); + await this.gate(max, task, { + files: this.writtenPaths(task), message: `t1: ${task.title}`, verify: task.verify.join(' && '), tail: 'ok', + summary: 'lint-staged runs eslint and prettier on the staged files.', integration: true, + }); + } + + /** The release checklist's t2. Noa writes the docs, then asks before it changes the README, with the change. */ + private async trackC2(noa: Actor, task: Task) { + const readme: RepoFile = { path: 'README.md', before: README, after: README_ENV }; + const steps = ['List the variables in docs/env.md', 'Point to it from the README']; + await noa.sleep(900); + await noa.turn(`Task t2 · ${task.title}\n\n${task.goal}`, async () => { + noa.plan(listAt(steps, 0)); + await noa.think('Three variables are read in the code: the database, the session secret and the Stripe test key.', { pace: 40 }); + this.wrote(task, { path: 'docs/env.md', before: null, after: ENV_DOC }); + await noa.tool({ name: 'fileChange', activity: 'create', target: { path: 'docs/env.md' }, ms: 1200, files: ['docs/env.md'], taskKey: task.id }); + noa.plan(listAt(steps, 1)); + const no = await this.editApproval(noa, readme.path, diffOf([readme]), null); + if (no === null) { + this.wrote(task, readme); + await noa.tool({ name: 'fileChange', activity: 'edit', target: { path: readme.path }, ms: 900, files: [readme.path], taskKey: task.id }); + } + noa.plan(listAt(steps, 2)); + await noa.say(no === null ? 'The variables are in `docs/env.md`, and the README points there.' : 'The variables are in `docs/env.md`; the README stays as it was.'); + }); + await this.gate(noa, task, { + files: this.writtenPaths(task), message: `t2: ${task.title}`, verify: task.verify.join(' && '), tail: 'ok', + summary: 'docs/env.md lists the environment variables.', integration: true, + }); + } + + /** The release checklist's t3. Rio asks which years the licence names before it changes it. */ + private async trackC3(rio: Actor, task: Task) { + const options = [ + { label: '2024–2026', description: 'Every year the code was written in (recommended)' }, + { label: '2026', description: 'This year only' }, + ]; + await rio.sleep(900); + await rio.turn(`Task t3 · ${task.title}\n\n${task.goal}`, async () => { + await rio.think('A licence can name the first year or every year: that is the owner’s choice, so ask.', { pace: 40 }); + const years = (await this.question(rio, 'The licence says 2024. Which years should it name?', 'Licence', options, null)) ?? options[0].label; + this.wrote(task, { path: 'LICENSE', before: licence('2024'), after: licence(years) }); + await rio.tool({ name: 'Edit', activity: 'edit', target: { path: 'LICENSE' }, input: { file_path: 'LICENSE', old_string: 'Copyright (c) 2024', new_string: `Copyright (c) ${years}` }, ms: 700, files: ['LICENSE'], taskKey: task.id }); + await rio.say(`The licence names ${years} now.`); + }); + await this.gate(rio, task, { + files: ['LICENSE'], message: `t3: ${task.title}`, verify: task.verify.join(' && '), tail: 'ok', summary: 'LICENSE names the years of the code.', integration: true, + }); + } + + /** The release checklist's t4: Sam asks nothing, and finishes while the other three wait for you. */ + private async trackC4(sam: Actor, task: Task) { + await sam.sleep(900); + await sam.turn(`Task t4 · ${task.title}\n\n${task.goal}`, async () => { + await sam.think('The changelog keeps the newest release on top.', { pace: 40 }); + await sam.tool({ name: 'read_file', activity: 'read', target: { path: 'CHANGELOG.md' }, ms: 600, output: CHANGELOG_BEFORE }); + this.wrote(task, { path: 'CHANGELOG.md', before: CHANGELOG_BEFORE, after: CHANGELOG_AFTER }); + await sam.tool({ name: 'replace', activity: 'edit', target: { path: 'CHANGELOG.md' }, ms: 1200, files: ['CHANGELOG.md'], taskKey: task.id }); + await sam.say('`CHANGELOG.md` starts with the 2.5.0 section.'); + }); + await this.gate(sam, task, { + files: ['CHANGELOG.md'], message: `t4: ${task.title}`, verify: task.verify.join(' && '), tail: 'ok', summary: 'CHANGELOG.md has the 2.5.0 section.', integration: true, + }); + } + private async leadChat(lead: Actor, r: Req, text: string) { const sim = this.sim; const plan = this.plan(r); @@ -919,14 +1129,36 @@ export class Story { for (const t of tasks) { if (!t.depends_on.length) sim.patchTask(t.id, { status: 'ready', status_reason: 'Dependencies met; starting' }); else { - const waits = t.depends_on.map((d) => sim.tasks.get(d)?.key).join(', '); - sim.patchTask(t.id, { status: 'pending', status_reason: `Waiting on ${waits}` }); - sim.decision('schedule', 'rule', `${t.key} waits for ${waits} (dependencies not merged yet)`, { plan_id: planId, task: t.key, waiting_on: waits }, { task: t.id }); + sim.patchTask(t.id, { status: 'pending' }); + this.sayWait(t.id); } } void this.coordinate(planId); } + /** + * Why a pending task waits for the tasks it depends on, in the core's words (orchestrator/ + * scheduler.rs): one of them that cannot finish by itself (failed, blocked, cancelled) is named + * with its status. Null: it waits on none any more. + */ + private waitReason(t: Task): string | null { + const undone = t.depends_on.flatMap((d) => this.sim.tasks.get(d) ?? []).filter((d) => d.status !== 'done'); + if (!undone.length) return t.depends_on.every((d) => this.sim.tasks.get(d)?.status === 'done') ? null : 'waiting: depends on a task that no longer exists'; + const stuck = undone.filter((d) => d.status === 'failed' || d.status === 'blocked' || d.status === 'cancelled'); + if (stuck.length) return `blocked: depends on ${stuck.map((d) => `${d.key} (${d.status})`).join(', ')}`; + return `waiting: depends on ${undone.map((d) => d.key).join(', ')}`; + } + + /** Like each pass of the core's scheduler: a pending task says why it waits, and the record says so each time that changes. */ + private sayWait(taskId: string) { + const sim = this.sim; + const t = sim.tasks.get(taskId); + const reason = t?.status === 'pending' ? this.waitReason(t) : null; + if (!t || !reason || reason === t.status_reason) return; + sim.patchTask(t.id, { status_reason: reason }); + sim.decision('schedule', 'rule', reason, { task: t.key, plan_id: t.plan_id, reason }, { task: t.id }); + } + /** * `home`: where a 1:1 agent works. A worker on a task works in that task's worktree: the one * the task has already (a task on its plan's own branch works in the plan's), else a new one. @@ -939,16 +1171,28 @@ export class Story { taskId: task?.id ?? null, worktree, })); const act = sim.actor(a.id); - const transport = provider === 'claude' ? 'stream-json' : provider === 'codex' ? 'app-server' : 'acp'; + this.sessionStarted(act); + return act; + } + + /** + * Like a CLI when its process starts (a new agent, or one that starts again for a turn): its + * session, in the folder it works in, with its tools. A Lead plans in the repo. + */ + private sessionStarted(act: Actor) { + const sim = this.sim; + const a = act.a; + const transport = a.provider === 'claude' ? 'stream-json' : a.provider === 'codex' ? 'app-server' : 'acp'; + const lead = a.role === 'lead'; act.emit({ - type: 'session_started', provider, model: a.model, cwd: worktree ?? sim.workspace?.repo_path ?? REPO, - cli_version: provider === 'claude' ? '2.1.309' : provider === 'codex' ? '0.161.0' : provider === 'gemini' ? '0.62.0' : '1.18.31', + type: 'session_started', provider: a.provider, model: a.model, cwd: (lead ? null : a.worktree) ?? sim.workspace?.repo_path ?? REPO, + cli_version: lead || a.provider === 'claude' ? '2.1.309' : a.provider === 'codex' ? '0.161.0' : a.provider === 'gemini' ? '0.62.0' : '1.18.31', session_id: a.session_id, billing: a.billing, - tools: transport === 'stream-json' ? ['Bash', 'Read', 'Edit', 'Write', 'Grep', 'Glob', 'TodoWrite', 'mcp__codly__codly_search', 'mcp__codly__codly_post_note'] + tools: lead ? ['Read', 'Grep', 'Glob', 'WebFetch', 'mcp__codly__codly_search', 'mcp__codly__codly_submit_plan', 'mcp__codly__codly_memory_search'] + : transport === 'stream-json' ? ['Bash', 'Read', 'Edit', 'Write', 'Grep', 'Glob', 'TodoWrite', 'mcp__codly__codly_search', 'mcp__codly__codly_post_note'] : transport === 'app-server' ? ['shell', 'apply_patch', 'update_plan', 'codly.codly_search'] : ['read_file', 'write_file', 'replace', 'run_shell_command', 'glob', 'search_file_content', 'codly_search'], }); - return act; } /** @@ -981,14 +1225,18 @@ export class Story { const preassigned = task.assignee ? sim.agents.get(task.assignee) : null; if (!act && preassigned && !this.running.has(preassigned.id)) act = sim.actor(preassigned.id); if (!act) { - // A worker of the route's name takes it again; a 1:1 agent you hired is never given a plan's task. - const existing = sim.agentByName(route.name); - act = existing?.role === 'worker' && !this.running.has(existing.id) ? sim.actor(existing.id) : null; + // The worker the plan's route chose for this task before takes it again (it may have a + // second name: "Fay 2" when you hired a "Fay"), else a worker of the route's name. A 1:1 + // agent you hired is never given a plan's task. + const before = this.routed.get(`${planId}:${key}`); + const takes = [before ? sim.agents.get(before) : null, sim.agentByName(route.name)].find((x) => x?.role === 'worker' && !this.running.has(x.id)); + act = takes ? sim.actor(takes.id) : null; } const chosenByYou = !!(preassigned && act && act.id === preassigned.id && this.userAssigned.has(task.id)); // After your Resume the task's worker of the last run goes on: no new route. const again = this.resumed.delete(task.id) && !!preassigned && act?.id === preassigned.id; if (!act) act = this.spawnWorker(route.provider, this.unusedName(route.name), route.color, task); + this.routed.set(`${planId}:${key}`, act.id); const a = act.a; const label = `${a.name} · ${PROVIDER_NAME[a.provider]}`; if (!again) { @@ -1002,6 +1250,7 @@ export class Story { theme: { t1: () => this.trackT1(worker, task), t2: () => this.trackT2(worker, task), t3: () => this.trackT3(worker, task) }, lockout: { t1: () => this.trackL1(worker, task), t2: () => this.trackL2(worker, task) }, retries: { t1: () => this.trackB1(worker, task), t2: () => this.trackB2(worker, task) }, + cards: { t1: () => this.trackC1(worker, task), t2: () => this.trackC2(worker, task), t3: () => this.trackC3(worker, task), t4: () => this.trackC4(worker, task) }, }; const body = tracks[spec][key]; if (body) void this.runTrack(act, task, body); @@ -1069,21 +1318,22 @@ export class Story { } /** - * Wait for your answer to a request that is on screen. With `?autoplay=1` it is allowed after - * `auto` ms (`answers`: what autoplay picks for a question). + * Wait for your answer to a request that is on screen. With `?autoplay=1` autoplay allows it + * after `auto` ms, and the request says so (`answers`: what autoplay picks for a question); + * `auto` null: it waits for you all the same. */ - private async answered(act: Actor, ap: Approval, label: string, auto: number, answers: unknown = null): Promise { + private async answered(act: Actor, ap: Approval, label: string, auto: number | null, answers: unknown = null): Promise { const sim = this.sim; act.status('waiting_approval', 'await_approval', label); while (sim.approvals.get(ap.id)!.status === 'pending') { await act.sleep(250); - if (sim.opts.autoplay && sim.now() - ap.created_at > auto) this.resolveApproval(ap.id, 'allow_once', null, answers); + if (sim.opts.autoplay && auto !== null && sim.now() - ap.created_at > auto) this.resolveApproval(ap.id, 'allow_once', null, answers, AUTOPLAY); } return sim.approvals.get(ap.id)!.status; } - /** A command that asks first. `output`: what it prints once it is allowed. */ - private async approval(act: Actor, command: string, reason: string, risks: string[], output: string[]): Promise<'approved' | 'denied'> { + /** A command that asks first. `output`: what it prints once it is allowed. `auto`: as for `answered`. */ + private async approval(act: Actor, command: string, reason: string, risks: string[], output: string[], auto: number | null = 3500): Promise<'approved' | 'denied'> { const sim = this.sim; const a = act.a; const call = uid('call-'); @@ -1105,7 +1355,7 @@ export class Story { act.emit({ type: 'approval_resolved', approval_id: ap.id, status: 'approved', by: 'policy' }); sim.decision('approval_policy', 'rule', `auto-allowed your rule for this repo: ${describeRule(rule)}`, { approval_id: ap.id, rule: rule.id }, { agent: a.id, task: a.task_id }); } - const st = rule ? 'approved' : await this.answered(act, ap, `${command.split(' ').slice(0, 3).join(' ')}…`, 3500); + const st = rule ? 'approved' : await this.answered(act, ap, `${command.split(' ').slice(0, 3).join(' ')}…`, auto); if (st === 'approved') { act.status('working', 'execute', command.split(' ').slice(0, 3).join(' ')); for (const l of output) { @@ -1124,8 +1374,8 @@ export class Story { /** approval id → the note you sent with a "no". */ private notes = new Map(); - /** AskUserQuestion-style question; resolves with the chosen label (or null when skipped). */ - private async question(act: Actor, question: string, header: string, options: { label: string; description: string }[]): Promise { + /** AskUserQuestion-style question; resolves with the chosen label (or null when skipped). `auto`: as for `answered`. */ + private async question(act: Actor, question: string, header: string, options: { label: string; description: string }[], auto: number | null = 4000): Promise { const sim = this.sim; const a = act.a; const ap: Approval = { @@ -1135,7 +1385,7 @@ export class Story { }; sim.approvals.set(ap.id, ap); act.emit({ type: 'approval_requested', approval: ap }); - const st = await this.answered(act, ap, header, 4000, { [question]: options[0].label }); + const st = await this.answered(act, ap, header, auto, { [question]: options[0].label }); act.status('working', 'thinking'); if (st !== 'approved') return null; const ans = this.answers.get(ap.id) as Record | undefined; @@ -1176,9 +1426,9 @@ export class Story { /** * In "ask for edits" a 1:1 Claude agent asks before an edit, with the change it wants to make. - * Resolves null when you allow it, and your note ("" for none) when you say no. + * Resolves null when you allow it, and your note ("" for none) when you say no. `auto`: as for `answered`. */ - private async editApproval(act: Actor, path: string, diff: string): Promise { + private async editApproval(act: Actor, path: string, diff: string, auto: number | null = 3500): Promise { const sim = this.sim; const a = act.a; const ap: Approval = { @@ -1188,7 +1438,7 @@ export class Story { }; sim.approvals.set(ap.id, ap); act.emit({ type: 'approval_requested', approval: ap }); - const st = await this.answered(act, ap, path.split('/').pop() ?? path, 3500); + const st = await this.answered(act, ap, path.split('/').pop() ?? path, auto); act.status('working', 'thinking'); if (st === 'cancelled') throw new Cancelled(); return st === 'approved' ? null : (this.notes.get(ap.id) ?? ''); @@ -1353,15 +1603,16 @@ export class Story { act.set({ permission_mode: 'ask' }); sim.decision('permission_mode', 'rule', `Claude Code changed its mode to "${MODE_LABEL.ask}"`, { mode: 'ask' }, { agent: act.id }); } - const added = `## Notes\n\n- ${ask.replace(/\s+/g, ' ').slice(0, 200)}`; + // As Claude Code edits: the README's last line, and that line with the note after it. + const added = `${README_TAIL}\n\n## Notes\n\n- ${ask.replace(/\s+/g, ' ').slice(0, 200)}`; const asks = (act.a.permission_mode ?? 'ask') === 'ask'; - const denied = asks ? await this.editApproval(act, path, `@@ ${path} @@\n${added.split('\n').map((l) => `+${l}`).join('\n')}`) : null; + const denied = asks ? await this.editApproval(act, path, editPreview(README_TAIL, added)) : null; if (denied !== null) { // Your note says what to do instead: the agent takes it up. await act.say(denied ? `Understood: ${quoted(denied, 120)}. I will do that.` : 'Understood: I changed nothing. Tell me what to do instead.', { thread }); return; } - await act.tool({ name: 'Edit', activity: 'edit', target: { path }, ms: 1200, files: [path] }); + await act.tool({ name: 'Edit', activity: 'edit', target: { path }, input: { file_path: path, old_string: README_TAIL, new_string: added }, ms: 1200, files: [path] }); act.plan(listAt(steps, 2)); await act.tool({ name: 'Bash', activity: 'test', target: { command: 'npm test' }, ms: 2400, passed: 41, failed: 0, @@ -1485,18 +1736,19 @@ export class Story { asker.emit({ type: 'tool_completed', call_id: call, ok: true, output: answer, exit_code: null, duration_ms: sim.now() - started, tests_passed: null, tests_failed: null }); } - resolveApproval(id: string, choice: string, message: string | null, answers: unknown = null) { + /** `by`: who answered (`AUTOPLAY` for `?autoplay=1`'s answers), as the request's rows say it. */ + resolveApproval(id: string, choice: string, message: string | null, answers: unknown = null, by = 'user') { const sim = this.sim; const ap = sim.approvals.get(id); if (!ap || ap.status !== 'pending') throw new Error('This request was already answered.'); if (answers != null) this.answers.set(id, answers); if (message) this.notes.set(id, message); const status = choice === 'deny' || choice === 'cancel' ? (choice === 'cancel' ? 'cancelled' : 'denied') : 'approved'; - sim.approvals.set(id, { ...ap, status, decided_by: 'user' }); + sim.approvals.set(id, { ...ap, status, decided_by: by }); // Like the core: what you said with the answer is a row of its own, just before the answer. const said = saidWith(ap, sim.agents.get(ap.agent_id)?.provider, choice, message, answers); if (said) sim.emit({ type: 'approval_said', approval_id: id, ...said }, { agent: ap.agent_id, task: ap.task_id, run: ap.run_id }); - sim.emit({ type: 'approval_resolved', approval_id: id, status, by: 'user' }, { agent: ap.agent_id, task: ap.task_id, run: ap.run_id }); + sim.emit({ type: 'approval_resolved', approval_id: id, status, by }, { agent: ap.agent_id, task: ap.task_id, run: ap.run_id }); if (message) sim.decision('approval', 'human', `You denied ${'command' in ap.subject ? '`' + ap.subject.command + '`' : 'the request'}: “${message}”`, { approval: id }, { agent: ap.agent_id, task: ap.task_id }); } @@ -1793,6 +2045,7 @@ export class Story { await sim.sleep(700); while (tasks().some((t) => t.status !== 'done')) { if (cancelled()) return; + for (const t of tasks()) this.sayWait(t.id); for (const { id } of tasks().sort((a, b) => a.key.localeCompare(b.key, undefined, { numeric: true }))) { // As it is now: this pass waits between two tasks, and you can cancel one meanwhile. const t = sim.tasks.get(id); @@ -1816,7 +2069,7 @@ export class Story { sim.patchPlan(planId, { status: 'integrating' }); await sim.sleep(1500); const plan = sim.plans.get(planId)!; - const all = tasks().flatMap((t) => filesOf(this.fileKey(t)) ?? []); + const all = tasks().flatMap((t) => this.taskFiles(t)); const s = stats(all); const n = tasks().length; sim.decision('plan_done', 'rule', `All ${n} tasks merged into ${plan.integration_branch}: ${s.files} files, +${s.added} −${s.removed}`, { plan_id: planId, ...s }); @@ -1828,6 +2081,13 @@ export class Story { '- **t2** `theme` column with a migration, validated in `PATCH /api/settings` · 8 API tests\n' + '- **t3** System / Light / Dark toggle on Settings · 3 e2e tests (Cy caught and fixed a reload race)\n\n' + '`main` is untouched. Review the diff, then merge when you’re ready.' + : spec === 'cards' + ? `All four tasks are merged into \`${plan.integration_branch}\` — ${s.files} files, +${s.added} −${s.removed}.\n\n` + + '- **t1** lint-staged runs on the staged files before each commit\n' + + '- **t2** the environment variables are in `docs/env.md`\n' + + '- **t3** the licence names its years\n' + + '- **t4** `CHANGELOG.md` starts with the 2.5.0 section\n\n' + + '`main` is untouched until you merge.' : spec === 'retries' ? `Both tasks are merged into \`${plan.integration_branch}\` — ${s.files} files, +${s.added} −${s.removed}.\n\n` + '- **t1** a failed payment is tried again one day later, three times at most · 2 unit tests\n' + @@ -1872,11 +2132,22 @@ export class Story { sim.decision('plan_cancelled', 'human', 'You cancelled the plan; finished work stays on the integration branch', { plan_id: planId }); } + /** + * Before a plan is merged, in the core's words and order (orchestrator/workspace.rs + * `merge_plan`): a running plan is not merged, nor one that never ran. A cancelled plan + * merges the work it finished. + */ + mergeable(planId: string): Plan { + const plan = this.sim.plans.get(planId); + if (!plan) throw new Error('Unknown plan'); + if (plan.status === 'running' || plan.status === 'integrating') throw new Error('the plan is still running; wait until it is done (or cancel it)'); + if (!plan.integration_branch) throw new Error('the plan never ran, so there is nothing to merge'); + return plan; + } + mergePlan(planId: string): string { const sim = this.sim; - const plan = sim.plans.get(planId); - if (!plan) throw new Error('Unknown plan'); - if (plan.status !== 'done') throw new Error('The plan is still running; merge when every task is done.'); + const plan = this.mergeable(planId); const head = sha(); if (sim.workspace) sim.workspace = { ...sim.workspace, head }; sim.patchPlan(planId, { merged_sha: head }); @@ -1890,7 +2161,7 @@ export class Story { */ conflictFiles(planId: string): string[] { const done = [...this.sim.tasks.values()].filter((t) => t.plan_id === planId && t.status === 'done'); - const edited = done.flatMap((t) => filesOf(this.fileKey(t)) ?? []).filter((f) => f.before !== null); + const edited = done.flatMap((t) => this.taskFiles(t)).filter((f) => f.before !== null); return edited.slice(-1).map((f) => f.path); } @@ -1919,11 +2190,12 @@ export class Story { /** * `?merge=checks`: the checks of the plan's finished work that fail on its merge with your - * branch. In the demo that is the last check of the last task the plan finished. + * branch. In the demo that is the last check of its finished tasks that `MERGE_FAILURES` + * knows why it fails; none, when it knows none of them. */ failingChecks(planId: string): string[] { const done = [...this.sim.tasks.values()].filter((t) => t.plan_id === planId && t.status === 'done'); - return done.flatMap((t) => t.verify).slice(-1); + return done.flatMap((t) => t.verify).filter((c) => c in MERGE_FAILURES).slice(-1); } /** @@ -1939,7 +2211,7 @@ export class Story { const list = failed.map((c) => `\`${c}\``).join(', '); // Its write scope is the files the plan changed. const done = [...sim.tasks.values()].filter((t) => t.plan_id === planId && t.status === 'done'); - const scope = [...new Set(done.flatMap((t) => (filesOf(this.fileKey(t)) ?? []).map((f) => f.path)))]; + const scope = [...new Set(done.flatMap((t) => this.taskFiles(t).map((f) => f.path)))]; const task = this.mergeTask(plan, 'fix-checks', { title: `Fix the checks with ${target} merged in`, goal: `The plan is finished, and ${target} (your branch) got new commits meanwhile. The two merge without a conflict, but on the result of that merge these checks fail: ${list}. Codly merged ${target} into this worktree, which holds the plan’s finished work. Find out why the checks fail now, and fix it so that the plan’s work and the changes on ${target} are both kept and work together.`, @@ -2040,18 +2312,24 @@ export class Story { }); } - /** `check`: the plan's check that fails with `target` merged in. */ + /** `check`: the plan's check that fails with `target` merged in (one of `MERGE_FAILURES`). */ private async trackFix(act: Actor, task: Task, target: string, check: string) { - const path = task.write_scope[task.write_scope.length - 1] ?? 'package.json'; + const failure = MERGE_FAILURES[check]; + // The test file as the plan's task left it, and as the fix leaves it. + const theirs = filesOf(failure.files)?.find((f) => f.path === failure.path)?.after; + if (!theirs?.includes(failure.from)) throw new Error(`the demo cannot fix ${check}: ${failure.path} has no line to change`); + const fixed: RepoFile = { path: failure.path, before: theirs, after: theirs.replace(failure.from, failure.to) }; + const path = failure.path; const steps = ['Run the check that fails', 'Fix it on the merge', 'Run the checks again']; await act.sleep(800); await act.turn(`Task ${task.key} · ${task.title}\n\n${task.goal}`, async () => { act.plan(listAt(steps, 0)); await act.think(`${target} merged in without a conflict, but \`${check}\` fails now. Find what changed under the plan’s work.`); - await act.tool({ name: 'Bash', activity: 'test', target: { command: check }, ms: 2400, ok: false, exit: 1, passed: 2, failed: 1, lines: [`$ ${check}`, ` ✘ ${path}: expected the value ${target} changed`, ' 1 failed', ' 2 passed'] }); + await act.tool({ name: 'Bash', activity: 'test', target: { command: check }, ms: 2400, ok: false, exit: 1, passed: 2, failed: 1, lines: [`$ ${check}`, ` ✘ ${path}: ${failure.test}: ${failure.why}`, ' 1 failed', ' 2 passed'] }); act.plan(listAt(steps, 1)); await act.tool({ name: 'Read', activity: 'read', target: { path }, ms: 600 }); - await act.tool({ name: 'Edit', activity: 'edit', target: { path }, ms: 1400, files: [path] }); + this.wrote(task, fixed); + await act.tool({ name: 'Edit', activity: 'edit', target: { path }, input: { file_path: path, old_string: failure.from, new_string: failure.to }, ms: 1400, files: [path], taskKey: task.id }); act.plan(listAt(steps, 2)); await act.tool({ name: 'Bash', activity: 'test', target: { command: check }, ms: 2600, lines: [`$ ${check}`, 'ok'] }); act.plan(listAt(steps, 3)); @@ -2401,19 +2679,26 @@ export class Story { // ───────────── diffs ───────────── + /** The files a task writes, with their text: the ones it decided as it worked (`wrote`), else its demo files. */ + taskFiles(t: Task): RepoFile[] { + return this.written.get(t.id) ?? filesOf(this.fileKey(t)) ?? []; + } + taskDiff(id: string): string { const t = this.sim.tasks.get(id); if (!t) throw new Error('Unknown task'); if (t.key === 'a3' && !t.plan_id) return diffOf(NEXT_BUMP); - const fk = this.fileKey(t); - const files = filesOf(fk) ?? TASK_FILES.adhoc; + // (a task that wrote files of its own text grows its diff by its id: plans reuse keys) + const own = this.written.get(id); + const fk = own ? id : this.fileKey(t); + const files = own ?? filesOf(fk) ?? TASK_FILES.adhoc; const touched = this.sim.touched.get(fk) ?? new Set(); return diffOf(files.filter((f) => touched.has(f.path))); } planDiff(id: string): string { const tasks = [...this.sim.tasks.values()].filter((t) => t.plan_id === id && t.status === 'done'); - return diffOf(tasks.flatMap((t) => filesOf(this.fileKey(t)) ?? [])); + return diffOf(tasks.flatMap((t) => this.taskFiles(t))); } searchIndex() { diff --git a/src/lib/demo/workspaceId.ts b/src/lib/demo/workspaceId.ts index 5141a53c..940c254c 100644 --- a/src/lib/demo/workspaceId.ts +++ b/src/lib/demo/workspaceId.ts @@ -3,9 +3,9 @@ // under it (`codly.request.`), so with `?requests=two` (both scripted requests there when the // page loads) a reload opens on the request you left. // -// The office's look (`codly.sims.`) is not kept: the demo's agents get new ids on each load, -// so nothing kept under an earlier load applies, and keeping it would add that load's agents to -// the key on every reload. Every `codly.sims.ws-…` key goes when the page loads. +// The office's look (`codly.sims.`) is kept under that id too: the demo's agents keep their +// ids from one load to the next (sim.ts `agentId`), so the look is theirs again. The look of any +// other demo id (one an older demo made at each load) goes when the page loads. import { uid } from './sim'; const KEY = 'codly.demo.workspace'; @@ -24,7 +24,7 @@ export function demoWorkspaceId(): string { } for (let i = localStorage.length - 1; i >= 0; i--) { const key = localStorage.key(i); - if (key?.startsWith(`${LOOK}ws-`)) localStorage.removeItem(key); + if (key?.startsWith(`${LOOK}ws-`) && key !== `${LOOK}${id}`) localStorage.removeItem(key); } return id; } catch { diff --git a/src/lib/mock.ts b/src/lib/mock.ts index 55dc89b8..6cb01cc8 100644 --- a/src/lib/mock.ts +++ b/src/lib/mock.ts @@ -198,14 +198,17 @@ function makeDesk(sim: Sim, states: DemoStates, billing = false): Desk { const checks = new ChecksDemo(states.checksOn); const story = new Story(sim, { checks, slowHelper: states.slowHelper, planMode: states.planMode, yourRequestFirst: states.intake !== null, ask: states.approval, billing, - resumeAsk: states.resumeAsk, background: states.background, failFirstTurn: states.turnFailed, twoRequests: states.twoRequests, + resumeAsk: states.resumeAsk, background: states.background, failFirstTurn: states.turnFailed, twoRequests: states.twoRequests, threeCards: states.threeCards, }); const trouble = states.mergeConflict ? 'conflict' : states.mergeChecks ? 'checks' : null; + const workspaceTrust = new WorkspaceTrustDemo(states.trustAsk); + // Like the core: a Claude run leaves out the repo's own configuration while you have not trusted it, unless "Use my own CLI setup" is off. + sim.withoutFolderConfig = () => sim.settings.use_my_claude_setup && workspaceTrust.trust(null).state === 'without'; return { sim, story, checks, ctl: new MockControls(sim), breaker: new MockBreaker(sim), askMe: new MockAskMe(sim, !billing), conflicts: new MergeConflictDemo(trouble, sim, story), previews: new PreviewDemo(states.previewRunning), - workspaceTrust: new WorkspaceTrustDemo(states.trustAsk), pullRequests: new PullRequestDemo(states.prOpen), checkpoints: new DemoCheckpoints((id) => sim.edited.has(id)), + workspaceTrust, pullRequests: new PullRequestDemo(states.prOpen), checkpoints: new DemoCheckpoints((id) => sim.edited.has(id)), takeovers: new DemoTakeovers(), worktrees: new WorktreeDemo(), hk: undefined, pushed: false, ahead: 0, closed: [], merge: null, mergeCommits: 0, }; } @@ -459,6 +462,8 @@ export class MockTransport implements Transport { } case 'merge_plan': { const planId = String(a.planId); + // Like the core: a plan that cannot be merged is refused before its checks run. + story.mergeable(planId); this.conflicts.refuse(planId, a.unchecked === true); const sha = story.mergePlan(planId); // The commit of each finished task, and the merge commit. @@ -803,8 +808,12 @@ export class MockTransport implements Transport { } case 'agent_git': return mockAgentGit(sim.agents.get(String(a.agentId)), sim.now(), sim.log); - case 'agent_diff': - return mockAgentDiff(sim.agents.get(String(a.agentId)), sim.log); + case 'agent_diff': { + // A worker on a task: the files it wrote for the task, with their text as the task's diff has it. + const agent = sim.agents.get(String(a.agentId)); + const task = agent?.task_id ? sim.tasks.get(agent.task_id) : undefined; + return mockAgentDiff(agent, sim.log, task ? story.taskFiles(task) : []); + } case 'agent_checkpoints': return this.checkpoints.list(sim.agents.get(String(a.agentId)), sim.now()); case 'restore_checkpoint': From b11dd34ed952ea76a4f7e16fb4f00c477625f2c2 Mon Sep 17 00:00:00 2001 From: julienwuthrich-ant Date: Mon, 23 Nov 2026 17:43:44 -0800 Subject: [PATCH 070/120] Toasts: a dismissal under your pointer moves nothing, and no toast lies on a waiting card The toast stack closed the gap of a toast you dismissed, so the ones under it jumped under your pointer. Its "less than 8 px is not covering" rule was applied to boxes already grown by the 4 px air, so the real limit was 4 px. With no free place a folded stack stayed where it last looked, also on a card that waits for your answer. A toast offering "Merge anyway" stayed after the plan was merged. Settings rows lost their label, a room header cut its one sentence, and the Resume bar dropped its second line at every width. - A toast dismissed while the pointer or focus is on the stack leaves an empty place of its height; the places close when you leave ("Dismiss all" leaves none). Pure rule: stackRows. - Covering counts 8 px of the real boxes; a move keeps 4 px of air from every control near the stack. A waiting card is never covered while the window leaves room: the stack takes the last place off the cards it tried, or goes under them. - The fit of a stack higher than the window is a pure function (stackFit). - A toast action can say it is gone; the plan merge toasts use it. Toast text starts with a capital and draws backticked code as code. - Settings: the switch's name and first paragraph are its label again; "More about this" is not. Hard stop shows its last sentence; the watchdog tool row shows one sentence and opens the rest. Own-key check for links. The trust dialog names Settings -> Safety -> Trust. - Room headers: one fact wraps to two lines; several facts keep one line each, and a cut one shows its whole text as a tooltip. - The Resume bar hides its second line only in a room under 600 px. - The Plan room says "on hold since Codly restarted" for a held plan. Co-Authored-By: Claude Fable 5.2 --- src/components/ResumeWork.svelte | 54 ++-- src/components/Toasts.svelte | 206 +++++++++---- src/lib/__tests__/resumeWork.test.ts | 42 ++- src/lib/__tests__/toasts.test.ts | 19 ++ src/lib/__tests__/watchdog.test.ts | 16 +- src/lib/state/actions.ts | 13 +- src/lib/state/toasts.svelte.ts | 9 +- src/lib/util/__tests__/cutTip.test.ts | 22 ++ src/lib/util/__tests__/mergeOffer.test.ts | 40 +++ src/lib/util/__tests__/planHold.test.ts | 33 +++ src/lib/util/__tests__/toastPlace.test.ts | 296 +++++++++++++++---- src/lib/util/__tests__/toastText.test.ts | 40 +++ src/lib/util/cutTip.ts | 11 + src/lib/util/mergeOffer.ts | 21 ++ src/lib/util/planHold.ts | 19 ++ src/lib/util/resumeWork.ts | 10 + src/lib/util/toastPlace.ts | 160 +++++++--- src/lib/util/toastText.ts | 22 ++ src/lib/util/watchdog.ts | 6 +- src/overlays/BreakerSection.svelte | 8 +- src/overlays/RequiredChecksSection.svelte | 29 +- src/overlays/SettingsSheet.svelte | 26 +- src/overlays/TrustDialog.svelte | 4 +- src/overlays/WatchdogSection.svelte | 5 +- src/overlays/WorktreeSection.svelte | 29 +- src/overlays/__tests__/settingsPages.test.ts | 8 + src/overlays/settingsPages.ts | 3 +- src/rooms/RoomHead.svelte | 41 ++- src/rooms/plan/PlanRoom.svelte | 3 +- 29 files changed, 946 insertions(+), 249 deletions(-) create mode 100644 src/lib/util/__tests__/cutTip.test.ts create mode 100644 src/lib/util/__tests__/mergeOffer.test.ts create mode 100644 src/lib/util/__tests__/planHold.test.ts create mode 100644 src/lib/util/__tests__/toastText.test.ts create mode 100644 src/lib/util/cutTip.ts create mode 100644 src/lib/util/mergeOffer.ts create mode 100644 src/lib/util/planHold.ts create mode 100644 src/lib/util/toastText.ts diff --git a/src/components/ResumeWork.svelte b/src/components/ResumeWork.svelte index d3a20922..3a9ae9e9 100644 --- a/src/components/ResumeWork.svelte +++ b/src/components/ResumeWork.svelte @@ -7,9 +7,10 @@ The bar is not a toast: it is there from the launch until you answer. It has room of its own under the top bar: while it shows, the stage starts below it (shell/Shell.svelte), so it covers nothing of the page, and it is as wide as the stage at most. It lies on no sheet and - not on the Ask me panel: while one of them is open the bar ends left of it, the question takes - both lines and the line under it goes (the whole text is in the tooltip), its buttons stay. It is drawn above the first-run - quest, so the question can be answered there too. + not on the Ask me panel: while one of them is open the bar ends left of it. In a room too + narrow for both lines (`showsBothLines`: a small window, a sheet beside it) the question takes + both lines and the line under it goes (the whole text is in the tooltip); its buttons stay. It + is drawn above the first-run quest, so the question can be answered there too. -->

    {eyebrow}

    {title}

    - {#if sub}
    {@render sub()}
    {/if} + {#if sub}
    {@render sub()}
    {/if}
    {#if right}
    {@render right()}
    {/if}
    @@ -26,6 +60,9 @@ .l { flex: 1 1 320px; min-width: 0; display: flex; flex-direction: column; gap: 4px; } h1 { font-size: var(--d-lg); line-height: 1.05; color: var(--ink-1); } .sub { font-size: var(--t-md); color: var(--ink-3); display: flex; align-items: center; gap: 0 8px; flex-wrap: wrap; min-width: 0; } + /* Several facts: one line each. */ .sub > :global(*) { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + /* One fact: two lines at most. */ + .sub > :global(:only-child) { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; white-space: normal; overflow-wrap: anywhere; } .r { display: flex; align-items: center; gap: 8px; flex-shrink: 0; } diff --git a/src/rooms/plan/PlanRoom.svelte b/src/rooms/plan/PlanRoom.svelte index f88d1650..b1f26720 100644 --- a/src/rooms/plan/PlanRoom.svelte +++ b/src/rooms/plan/PlanRoom.svelte @@ -10,6 +10,7 @@ import { ui, type PlanLens } from '../../lib/state/ui.svelte'; import { clock } from '../../lib/util/format'; import { GLOSSARY, PLAN_STATUS_LABEL } from '../../lib/util/labels'; + import { ON_HOLD, onHold } from '../../lib/util/planHold'; import EmptyState from '../../components/EmptyState.svelte'; import Icon from '../../components/Icon.svelte'; import WaitReason from '../../home/cards/WaitReason.svelte'; @@ -50,7 +51,7 @@ } - + {#snippet sub()} {#if plan} {done} of {tasks.length} done From d48fd241eb478ab69ffa1af8a5b17971d6caa2d1 Mon Sep 17 00:00:00 2001 From: julienwuthrich-ant Date: Mon, 23 Nov 2026 17:51:24 -0800 Subject: [PATCH 071/120] Research: twelve more Claude Code answers, recorded (part 6) Twelve pieces of code waited for a fact about Claude Code 2.1.311 that no recording showed. Part 6 records them: 102 sanitized fixtures (r8-*), the driver scripts r8_*.py and the builder make_notes_part6.py, which checks every number and word it states against the fixtures. The first answer changes a plan: without --strict-mcp-config and with --setting-sources user,local, a repo's .claude/settings.local.json can turn on a plugin that the user had turned off, and its MCP server starts. Under "user" alone it does not, and the repo's .mcp.json server started in no form recorded. Also: rewind and fork of a conversation, the CLI's own file rewind (only the CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING variable turns it on), stops in the last moment of a turn, what happens after a budget stop, the status words of a Bash task, slow HTTP MCP tools, a shutdown with a turn running and effort changes during a turn. The MCP switch during a turn is not recorded: it needs a throw-away HOME with a login. Driver fixes: r5_lib.Procs matches the whole command text, so a script no longer finds (or ends) a sleep of another duration. The sanitizer replaces file names made from a pid, a hash or the clock, and was run again over the six r7-mcp-toggle-saved fixtures. The part 5 builder states the resumed process's init correctly and checks the budget stop's subtype in both forms. mcp_http_ping_server notes every answer and can answer with an event stream. Co-Authored-By: Claude Fable 5.2 --- .../cli-claude-stream-json-2.1.311-part5.md | 8 +- .../cli-claude-stream-json-2.1.311-part6.md | 910 ++++++++++++++++ .../drivers/claude-stream-json/README.md | 61 +- .../claude-stream-json/make_notes_part5.py | 12 +- .../claude-stream-json/make_notes_part6.py | 981 ++++++++++++++++++ .../mcp_http_ping_server.py | 88 +- .../claude-stream-json/r5_a4_stop_sequence.py | 2 +- .../claude-stream-json/r5_b1_stop_subagent.py | 2 +- .../r5_f15_background_wording.py | 2 +- .../drivers/claude-stream-json/r5_lib.py | 19 +- .../r6_a1_interrupt_helper.py | 4 +- .../r6_a2_shutdown_helper.py | 2 +- .../claude-stream-json/r6_a3_helper_fails.py | 2 +- .../r7_a4_interrupt_two_helpers.py | 3 +- .../r7_a5_shutdown_helper_and_command.py | 2 +- .../r7_b11_stop_helper_mid_turn.py | 2 +- .../r7_b3_failed_turn_helper.py | 2 +- .../r7_f10_budget_during_call.py | 2 +- .../drivers/claude-stream-json/r7_lib.py | 5 - .../claude-stream-json/r8_a11_shutdown_all.py | 73 ++ .../r8_b10_http_slow_kinds.py | 52 + .../r8_b5_stop_last_moment.py | 74 ++ .../r8_b7_bash_task_fails.py | 46 + .../r8_c12_effort_mid_turn.py | 48 + .../claude-stream-json/r8_c9_bash_set_mode.py | 76 ++ .../r8_e1_untrusted_mcp_user_flags.py | 84 ++ .../r8_e8_cannot_start_saved.py | 61 ++ .../claude-stream-json/r8_f2_rewind.py | 70 ++ .../drivers/claude-stream-json/r8_f3_fork.py | 66 ++ .../claude-stream-json/r8_f4_file_rewind.py | 56 + .../claude-stream-json/r8_f6_after_budget.py | 132 +++ .../drivers/claude-stream-json/r8_lib.py | 82 ++ .../drivers/claude-stream-json/sanitize.py | 34 +- .../claude-stream-json/test_sanitize.py | 20 + .../r7-mcp-toggle-saved-1-a.ndjson | 2 +- .../r7-mcp-toggle-saved-1-b.ndjson | 2 +- .../r7-mcp-toggle-saved-1-c.ndjson | 2 +- .../r7-mcp-toggle-saved-2-a.ndjson | 2 +- .../r7-mcp-toggle-saved-2-b.ndjson | 2 +- .../r7-mcp-toggle-saved-2-c.ndjson | 2 +- ...after-budget-helper-goes-on-1-calib.ndjson | 129 +++ ...r8-after-budget-helper-goes-on-1-t1.ndjson | 121 +++ ...r8-after-budget-helper-goes-on-1-t2.ndjson | 105 ++ ...r8-after-budget-helper-goes-on-1-t3.ndjson | 110 ++ ...after-budget-helper-goes-on-2-calib.ndjson | 121 +++ ...r8-after-budget-helper-goes-on-2-t1.ndjson | 121 +++ ...r8-after-budget-helper-goes-on-2-t2.ndjson | 89 ++ .../r8-after-budget-interrupt-1-calib.ndjson | 95 ++ .../r8-after-budget-interrupt-1-t1.ndjson | 89 ++ .../r8-after-budget-interrupt-1-t2.ndjson | 74 ++ .../r8-after-budget-interrupt-2-calib.ndjson | 97 ++ .../r8-after-budget-interrupt-2-t1.ndjson | 93 ++ .../r8-after-budget-interrupt-2-t2.ndjson | 75 ++ .../r8-after-budget-stop-task-1-calib.ndjson | 93 ++ .../r8-after-budget-stop-task-1-t1.ndjson | 79 ++ .../r8-after-budget-stop-task-2-calib.ndjson | 83 ++ .../r8-after-budget-stop-task-2-t1.ndjson | 87 ++ .../r8-after-budget-stop-task-2-t2.ndjson | 78 ++ .../r8-bash-set-mode-all-1.ndjson | 135 +++ .../r8-bash-set-mode-all-2.ndjson | 134 +++ .../r8-bash-set-mode-dont-ask-1.ndjson | 178 ++++ .../r8-bash-set-mode-dont-ask-2.ndjson | 209 ++++ .../r8-bash-set-mode-only-set-mode-1.ndjson | 131 +++ .../r8-bash-set-mode-only-set-mode-2.ndjson | 134 +++ .../r8-bash-set-mode-plan-1.ndjson | 133 +++ .../r8-bash-set-mode-plan-2.ndjson | 134 +++ .../r8-bash-task-fails-1.ndjson | 79 ++ .../r8-bash-task-fails-2.ndjson | 74 ++ .../r8-effort-mid-turn-high-1.ndjson | 73 ++ .../r8-effort-mid-turn-high-2.ndjson | 71 ++ .../r8-effort-mid-turn-null-1.ndjson | 74 ++ .../r8-effort-mid-turn-null-2.ndjson | 70 ++ .../r8-file-rewind-env-1.ndjson | 150 +++ .../r8-file-rewind-env-2.ndjson | 149 +++ .../r8-file-rewind-off-1.ndjson | 150 +++ .../r8-file-rewind-off-2.ndjson | 150 +++ .../r8-file-rewind-setting-1.ndjson | 153 +++ .../r8-file-rewind-setting-2.ndjson | 151 +++ .../claude-2.1.311/r8-fork-1-a.ndjson | 34 + .../claude-2.1.311/r8-fork-1-b.ndjson | 19 + .../claude-2.1.311/r8-fork-1-c.ndjson | 19 + .../claude-2.1.311/r8-fork-1-d.ndjson | 19 + .../claude-2.1.311/r8-fork-2-a.ndjson | 31 + .../claude-2.1.311/r8-fork-2-b.ndjson | 19 + .../claude-2.1.311/r8-fork-2-c.ndjson | 20 + .../claude-2.1.311/r8-fork-2-d.ndjson | 19 + .../r8-http-slow-json-env-1.ndjson | 37 + .../r8-http-slow-json-env-2.ndjson | 37 + .../r8-http-slow-json-timeout-1.ndjson | 37 + .../r8-http-slow-json-timeout-2.ndjson | 36 + .../r8-http-slow-progress-1.ndjson | 37 + .../r8-http-slow-progress-2.ndjson | 37 + .../claude-2.1.311/r8-http-slow-sse-1.ndjson | 37 + .../claude-2.1.311/r8-http-slow-sse-2.ndjson | 36 + .../r8-mcp-cannot-start-saved-1-a.ndjson | 12 + .../r8-mcp-cannot-start-saved-1-b.ndjson | 17 + .../r8-mcp-cannot-start-saved-1-c.ndjson | 7 + .../r8-mcp-cannot-start-saved-2-a.ndjson | 12 + .../r8-mcp-cannot-start-saved-2-b.ndjson | 17 + .../r8-mcp-cannot-start-saved-2-c.ndjson | 7 + .../claude-2.1.311/r8-rewind-1-a.ndjson | 61 ++ .../claude-2.1.311/r8-rewind-1-b.ndjson | 20 + .../claude-2.1.311/r8-rewind-1-c.ndjson | 19 + .../claude-2.1.311/r8-rewind-1-d.ndjson | 9 + .../claude-2.1.311/r8-rewind-2-a.ndjson | 56 + .../claude-2.1.311/r8-rewind-2-b.ndjson | 20 + .../claude-2.1.311/r8-rewind-2-c.ndjson | 19 + .../claude-2.1.311/r8-rewind-2-d.ndjson | 9 + .../claude-2.1.311/r8-shutdown-all-1.ndjson | 111 ++ .../claude-2.1.311/r8-shutdown-all-2.ndjson | 118 +++ .../r8-stop-command-last-request-1.ndjson | 220 ++++ .../r8-stop-command-last-request-2.ndjson | 178 ++++ .../r8-stop-command-mid-turn-1.ndjson | 104 ++ .../r8-stop-command-mid-turn-2.ndjson | 120 +++ .../r8-stop-command-mid-turn-3.ndjson | 100 ++ .../r8-stop-command-mid-turn-4.ndjson | 89 ++ .../r8-stop-helper-last-request-1.ndjson | 247 +++++ .../r8-stop-helper-last-request-2.ndjson | 286 +++++ .../r8-untrusted-mcp-enable-all-user-1.ndjson | 11 + .../r8-untrusted-mcp-enable-all-user-2.ndjson | 11 + ...trusted-mcp-enable-all-user-local-1.ndjson | 11 + ...trusted-mcp-enable-all-user-local-2.ndjson | 11 + ...-untrusted-mcp-enabled-named-user-1.ndjson | 11 + ...-untrusted-mcp-enabled-named-user-2.ndjson | 11 + ...sted-mcp-enabled-named-user-local-1.ndjson | 11 + ...sted-mcp-enabled-named-user-local-2.ndjson | 11 + ...rusted-mcp-plugin-repo-local-user-1.ndjson | 11 + ...rusted-mcp-plugin-repo-local-user-2.ndjson | 11 + ...-mcp-plugin-repo-local-user-local-1.ndjson | 11 + ...-mcp-plugin-repo-local-user-local-2.ndjson | 11 + ...sted-mcp-plugin-repo-project-user-1.ndjson | 11 + ...sted-mcp-plugin-repo-project-user-2.ndjson | 11 + ...cp-plugin-repo-project-user-local-1.ndjson | 11 + ...cp-plugin-repo-project-user-local-2.ndjson | 11 + ...r8-untrusted-mcp-plugin-repo-user-1.ndjson | 11 + ...r8-untrusted-mcp-plugin-repo-user-2.ndjson | 11 + ...rusted-mcp-plugin-repo-user-local-1.ndjson | 11 + ...rusted-mcp-plugin-repo-user-local-2.ndjson | 11 + .../r8-untrusted-mcp-plugin-user-1.ndjson | 11 + .../r8-untrusted-mcp-plugin-user-2.ndjson | 11 + ...8-untrusted-mcp-plugin-user-local-1.ndjson | 11 + ...8-untrusted-mcp-plugin-user-local-2.ndjson | 11 + 142 files changed, 9893 insertions(+), 69 deletions(-) create mode 100644 docs/research/cli-claude-stream-json-2.1.311-part6.md create mode 100644 docs/research/drivers/claude-stream-json/make_notes_part6.py create mode 100644 docs/research/drivers/claude-stream-json/r8_a11_shutdown_all.py create mode 100644 docs/research/drivers/claude-stream-json/r8_b10_http_slow_kinds.py create mode 100644 docs/research/drivers/claude-stream-json/r8_b5_stop_last_moment.py create mode 100644 docs/research/drivers/claude-stream-json/r8_b7_bash_task_fails.py create mode 100644 docs/research/drivers/claude-stream-json/r8_c12_effort_mid_turn.py create mode 100644 docs/research/drivers/claude-stream-json/r8_c9_bash_set_mode.py create mode 100644 docs/research/drivers/claude-stream-json/r8_e1_untrusted_mcp_user_flags.py create mode 100644 docs/research/drivers/claude-stream-json/r8_e8_cannot_start_saved.py create mode 100644 docs/research/drivers/claude-stream-json/r8_f2_rewind.py create mode 100644 docs/research/drivers/claude-stream-json/r8_f3_fork.py create mode 100644 docs/research/drivers/claude-stream-json/r8_f4_file_rewind.py create mode 100644 docs/research/drivers/claude-stream-json/r8_f6_after_budget.py create mode 100644 docs/research/drivers/claude-stream-json/r8_lib.py create mode 100644 docs/research/fixtures/claude-2.1.311/r8-after-budget-helper-goes-on-1-calib.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-after-budget-helper-goes-on-1-t1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-after-budget-helper-goes-on-1-t2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-after-budget-helper-goes-on-1-t3.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-after-budget-helper-goes-on-2-calib.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-after-budget-helper-goes-on-2-t1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-after-budget-helper-goes-on-2-t2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-after-budget-interrupt-1-calib.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-after-budget-interrupt-1-t1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-after-budget-interrupt-1-t2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-after-budget-interrupt-2-calib.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-after-budget-interrupt-2-t1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-after-budget-interrupt-2-t2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-after-budget-stop-task-1-calib.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-after-budget-stop-task-1-t1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-after-budget-stop-task-2-calib.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-after-budget-stop-task-2-t1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-after-budget-stop-task-2-t2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-bash-set-mode-all-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-bash-set-mode-all-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-bash-set-mode-dont-ask-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-bash-set-mode-dont-ask-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-bash-set-mode-only-set-mode-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-bash-set-mode-only-set-mode-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-bash-set-mode-plan-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-bash-set-mode-plan-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-bash-task-fails-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-bash-task-fails-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-effort-mid-turn-high-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-effort-mid-turn-high-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-effort-mid-turn-null-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-effort-mid-turn-null-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-file-rewind-env-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-file-rewind-env-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-file-rewind-off-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-file-rewind-off-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-file-rewind-setting-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-file-rewind-setting-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-fork-1-a.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-fork-1-b.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-fork-1-c.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-fork-1-d.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-fork-2-a.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-fork-2-b.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-fork-2-c.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-fork-2-d.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-http-slow-json-env-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-http-slow-json-env-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-http-slow-json-timeout-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-http-slow-json-timeout-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-http-slow-progress-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-http-slow-progress-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-http-slow-sse-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-http-slow-sse-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-mcp-cannot-start-saved-1-a.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-mcp-cannot-start-saved-1-b.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-mcp-cannot-start-saved-1-c.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-mcp-cannot-start-saved-2-a.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-mcp-cannot-start-saved-2-b.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-mcp-cannot-start-saved-2-c.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-rewind-1-a.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-rewind-1-b.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-rewind-1-c.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-rewind-1-d.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-rewind-2-a.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-rewind-2-b.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-rewind-2-c.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-rewind-2-d.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-shutdown-all-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-shutdown-all-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-stop-command-last-request-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-stop-command-last-request-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-stop-command-mid-turn-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-stop-command-mid-turn-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-stop-command-mid-turn-3.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-stop-command-mid-turn-4.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-stop-helper-last-request-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-stop-helper-last-request-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-untrusted-mcp-enable-all-user-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-untrusted-mcp-enable-all-user-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-untrusted-mcp-enable-all-user-local-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-untrusted-mcp-enable-all-user-local-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-untrusted-mcp-enabled-named-user-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-untrusted-mcp-enabled-named-user-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-untrusted-mcp-enabled-named-user-local-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-untrusted-mcp-enabled-named-user-local-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-untrusted-mcp-plugin-repo-local-user-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-untrusted-mcp-plugin-repo-local-user-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-untrusted-mcp-plugin-repo-local-user-local-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-untrusted-mcp-plugin-repo-local-user-local-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-untrusted-mcp-plugin-repo-project-user-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-untrusted-mcp-plugin-repo-project-user-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-untrusted-mcp-plugin-repo-project-user-local-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-untrusted-mcp-plugin-repo-project-user-local-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-untrusted-mcp-plugin-repo-user-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-untrusted-mcp-plugin-repo-user-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-untrusted-mcp-plugin-repo-user-local-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-untrusted-mcp-plugin-repo-user-local-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-untrusted-mcp-plugin-user-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-untrusted-mcp-plugin-user-2.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-untrusted-mcp-plugin-user-local-1.ndjson create mode 100644 docs/research/fixtures/claude-2.1.311/r8-untrusted-mcp-plugin-user-local-2.ndjson diff --git a/docs/research/cli-claude-stream-json-2.1.311-part5.md b/docs/research/cli-claude-stream-json-2.1.311-part5.md index 4d7fd994..083503bc 100644 --- a/docs/research/cli-claude-stream-json-2.1.311-part5.md +++ b/docs/research/cli-claude-stream-json-2.1.311-part5.md @@ -81,9 +81,11 @@ What the adapter can rely on (n=2, the two labels agree step for step): the user's own `~/.claude.json`). The folder's entry there (under `projects`, keyed by the folder's path) gets `"disabledMcpServers":["ping-live"]`. The entry's MCP keys: `disabledMcpServers`, `disabledMcpjsonServers`, `enabledMcpjsonServers`, `mcpContextUris`, `mcpServers`. - It holds for EVERY later process in that folder that reads that HOME: a new session (b) and a resumed one (c) both - report the server `disabled` in `mcp_status` and in `init.mcp_servers` (`"source":"dynamic"`), its tool is not in - `init.tools`, and the server is NOT started (no new line in `started.txt`). The saved list is read with - `--strict-mcp-config --setting-sources local` (all six processes; other setting sources were not tried). + report the server `disabled` in `mcp_status` at their start, and the server is NOT started (no new line in + `started.txt`). The new session's `init.mcp_servers` says `disabled` too (`"source":"dynamic"`), and its tool is not + in `init.tools`. The resumed process's only `init` comes after the switch back on, and says `connected`. The saved + list is read with `--strict-mcp-config --setting-sources local` (all six processes; other setting sources were not + tried). - The switch goes by the server's NAME in that folder: the server came from `--mcp-config` (Codly's way), so any server of that name in that folder stays off, also one that Codly passes in a later run. - Only `mcp_toggle` on undoes it: the list is `[]` again in the same step, and the server starts (`connected`). diff --git a/docs/research/cli-claude-stream-json-2.1.311-part6.md b/docs/research/cli-claude-stream-json-2.1.311-part6.md new file mode 100644 index 00000000..7901dcc9 --- /dev/null +++ b/docs/research/cli-claude-stream-json-2.1.311-part6.md @@ -0,0 +1,910 @@ +# Claude Code CLI stream-json: recorded protocol shapes, part 6 + +**QUESTION 1 FIRST. UNDER `--setting-sources user,local`, WITHOUT `--strict-mcp-config`, A FILE OF THE REPO +(`.claude/settings.local.json` WITH `"enabledPlugins": {"": true}`) SWITCHES ON A PLUGIN THAT THE USER HAD +INSTALLED AND TURNED OFF, AND THE PLUGIN'S MCP SERVER STARTS (4 of 4 recordings of that form, `r8-untrusted-mcp-plugin-repo-local-user-local-1`, `r8-untrusted-mcp-plugin-repo-local-user-local-2`, `r8-untrusted-mcp-plugin-repo-user-local-1`, `r8-untrusted-mcp-plugin-repo-user-local-2`). UNDER `user` ALONE +IT DOES NOT. THE REPO'S OWN `.mcp.json` SERVER STARTED IN NONE OF THE 24 RECORDINGS OF SECTION 1, ALSO WHEN THE USER +SETTINGS FILE SAYS `enableAllProjectMcpServers` OR NAMES THE SERVER IN `enabledMcpjsonServers`.** So the item of package +`claude-part5-truth` (drop `--strict-mcp-config` in a folder you have not trusted when "Use my Claude setup" is on) +holds for `--setting-sources user` and must be taken back for `user,local`: there the repo can turn on code (a +plugin's server; a plugin can also bring hooks, not recorded) that the user had turned off. + +- CLI: `claude` 2.1.311 (the same version as parts 1 to 5; checked with `claude --version` before the runs). +- Recorded: 2026-11-23, macOS, `--model haiku` (`claude-haiku-5-5`), subscription login (`"apiKeySource":"none"`). +- Method, base command, fixture line format and sanitizing: as in part 1 ("Base command", "Files", "Sanitizing") with + the additions of parts 2 to 5. Fixtures of this part are `fixtures/claude-2.1.311/r8-*.ndjson`; the scripts are + `drivers/claude-stream-json/r8_*.py` (README there says how to record again). +- Cost of the 102 recordings at list price: 0.1608 USD, the sum of each turn's own model requests + (`model_usage_since_last_result`). `cost.py` prints 0.1704: it sums each session's last `total_cost_usd` per + recording, and a resumed or forked session carries its earlier cost (sections 2 and 3). The runs in a throw-away HOME + have no login and cost nothing. +- Everything below was observed in these recordings. Each answer says how many runs it rests on (n) and says no more + than the recordings show. Statements marked "bundle" were read in the CLI's program file (`bgrep.py`), not recorded. +- The sections are numbered as the 12 questions this part was recorded for; the last two tables have them in the same + order. + +Differences from the part 5 method: +- `r5_lib.Procs` now matches the whole command text (`Procs("sleep 41")` no longer matches `sleep 410` or + `sleep 41.5`), and every script uses it that way. Part 6 scripts give each scenario's `sleep` a duration no other + script uses. +- Plugins: section 1 installs a plugin of the scenario (`ping-plugin`, from a local marketplace folder) with the CLI's + own `claude plugin` commands in a throw-away HOME. The sanitizer keeps that plugin (and its server + `plugin:ping-plugin:ping-plugged`) in `init`, and removes every other plugin. +- New sanitizing: file names the CLI makes from a process id, a hash or the clock (`.claude/sessions/..key`, + `.claude/sessions/.json`, `.claude.json.backup.
    @@ -174,6 +226,7 @@ .title { font-size: var(--t-md); font-weight: var(--w-semi); color: var(--ink-1); } .sub { font-size: var(--t-sm); color: var(--ink-3); } .small { padding: 4px 10px 8px; font-size: var(--t-sm); line-height: var(--lh-sm); color: var(--ink-3); } + .where { padding-top: 0; } .bad { padding: 4px 10px 8px; font-size: var(--t-sm); line-height: var(--lh-sm); color: var(--bad); } .row { display: flex; align-items: center; gap: 8px; width: 100%; min-height: 40px; padding: 0 6px 0 0; border-radius: var(--r-md); text-align: left; } .row.active { background: var(--surface-3); } @@ -189,7 +242,8 @@ .files { margin: 0 0 4px 16px; } .row.file { min-height: 32px; padding-left: 10px; } .path { flex: 1; min-width: 0; font-size: 11.5px; color: var(--ink-1); } - .ask { margin: 2px 6px 6px 10px; padding: 8px 10px; border-radius: var(--r-md); background: var(--surface-2); font-size: var(--t-sm); line-height: var(--lh-sm); color: var(--ink-1); } + .ask { display: flex; flex-direction: column; gap: 6px; margin: 2px 6px 6px 10px; padding: 8px 10px; border-radius: var(--r-md); background: var(--surface-2); font-size: var(--t-sm); line-height: var(--lh-sm); color: var(--ink-1); } + .acts { display: flex; justify-content: flex-end; align-items: center; gap: 6px; min-height: 26px; } .keys { color: var(--ink-3); white-space: nowrap; } .all { min-height: 34px; padding-left: 10px; font-size: var(--t-sm); color: var(--ink-2); } diff --git a/src/home/__tests__/composerSend.test.ts b/src/home/__tests__/composerSend.test.ts index 5ec679f2..da22e58a 100644 --- a/src/home/__tests__/composerSend.test.ts +++ b/src/home/__tests__/composerSend.test.ts @@ -1,9 +1,12 @@ -import { describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it } from 'vitest'; import { sendState } from '../composerSend'; +import { rewindLayer } from '../rewindLayer.svelte'; const typed = { text: 'Fix the header', files: 0, saving: false, unknown: false, inTerminal: null }; describe('may the composer send', () => { + afterEach(() => rewindLayer.close()); + it('sends text or attached files', () => { expect(sendState(typed)).toEqual({ ok: true }); expect(sendState({ ...typed, text: '', files: 1 })).toEqual({ ok: true }); @@ -22,4 +25,12 @@ describe('may the composer send', () => { it('has nothing to send on an empty line, which needs no word', () => { expect(sendState({ ...typed, text: ' ' })).toEqual({ ok: false, why: null }); }); + + it('sends nothing while "Undo a turn" is open over the composer: a ↵ meant for the list starts no turn', () => { + rewindLayer.open('ada'); + expect(sendState(typed)).toEqual({ ok: false, why: 'Close “Undo a turn” to send' }); + expect(sendState({ ...typed, text: '', files: 1 })).toEqual({ ok: false, why: 'Close “Undo a turn” to send' }); + rewindLayer.close(); + expect(sendState(typed)).toEqual({ ok: true }); + }); }); diff --git a/src/home/__tests__/rewind.test.ts b/src/home/__tests__/rewind.test.ts index 5e7b5cda..132b7ed0 100644 --- a/src/home/__tests__/rewind.test.ts +++ b/src/home/__tests__/rewind.test.ts @@ -3,7 +3,8 @@ import { describe, expect, it } from 'vitest'; import type { AgentCheckpoints } from '../../lib/gen/AgentCheckpoints'; import type { Checkpoint } from '../../lib/gen/Checkpoint'; -import { confirmLine, namesLine, pick, putBackTitle, REWIND_ROWS, rewindItems, rewindKey, rewindOff, rewindRows, rewindStart, toggleFiles, turnPoint, type RewindNav } from '../rewind'; +import { ESC_PAIR_WINDOW } from '../../lib/state/esc'; +import { confirmLine, focusRow, heldAfterClose, leftOutLine, namesLine, pick, putBackTitle, REWIND_ROWS, rewindItems, rewindKey, rewindOff, rewindRows, rewindStart, rewindWhere, toggleFiles, turnPoint, type RewindNav } from '../rewind'; const NOW = 1_760_000_000_000; const MIN = 60_000; @@ -119,6 +120,56 @@ describe('the keys of the list', () => { }); }); +describe('the keys and the focus are on one row', () => { + const rows = rewindRows(kept([point(3, { changed: 0, files: [] }), point(2, { changed: 2, files: ['a.ts', 'b.ts'] }), point(1)]), NOW); + const start = rewindStart(rows); + + it('Tab or a press onto another row moves the keys there: ↵ acts on the row that has the focus', () => { + const tabbed = focusRow(start, rows, 2); + expect(tabbed).toEqual({ ...start, at: 2 }); + const asked = rewindKey(tabbed, rows, 'Enter'); + expect(asked.nav.asking).toEqual({ n: 1, path: null }); + expect(rewindKey(asked.nav, rows, 'Enter').act).toEqual({ kind: 'restore', n: 1, path: null }); + }); + + it('the focus leaving a row that asks closes its confirm line: a later ↵ never restores that row', () => { + const asked = rewindKey(start, rows, 'Enter').nav; + expect(asked.asking).toEqual({ n: 2, path: null }); + const moved = focusRow(asked, rows, 2); + expect(moved).toEqual({ at: 2, open: null, asking: null }); + expect(rewindKey(moved, rows, 'Enter').act).toBeNull(); + // On the same row (its file count, its "Put back"), the confirm line stays. + expect(focusRow(asked, rows, asked.at)).toBe(asked); + }); + + it('a file row can take the keys; a turn with nothing to put back, or no row, cannot', () => { + const open = toggleFiles(start, rows, 2); + const file = focusRow(open, rows, 3); + expect(rewindItems(rows, file.open)[file.at]).toEqual({ kind: 'file', n: 2, path: 'b.ts' }); + expect(rewindKey(rewindKey(file, rows, 'Enter').nav, rows, 'Enter').act).toEqual({ kind: 'restore', n: 2, path: 'b.ts' }); + expect(focusRow(start, rows, 0)).toBe(start); + expect(focusRow(start, rows, 99)).toBe(start); + }); +}); + +describe('the head of the list', () => { + it('says when the turns are of a task’s worktree, and names the files too big to keep', () => { + expect(rewindWhere(kept([], { task: 'T-4' }))).toBe('Turns of task T-4, in its worktree'); + expect(rewindWhere(kept([]))).toBeNull(); + expect(leftOutLine(kept([], { left_out: ['node_modules/ (20000 new files)', 'dist/app.bin'] }))).toBe('Not kept, too big: node_modules/ (20000 new files), dist/app.bin'); + expect(leftOutLine(kept([]))).toBeNull(); + }); +}); + +describe('the Esc right after the one that closed the list', () => { + it('is held for the pair window only: it begins no pair that opens the list again', () => { + expect(heldAfterClose(NOW, NOW + 4)).toBe(true); + expect(heldAfterClose(NOW, NOW + ESC_PAIR_WINDOW)).toBe(true); + expect(heldAfterClose(NOW, NOW + ESC_PAIR_WINDOW + 1)).toBe(false); + expect(heldAfterClose(NOW, NOW - 1)).toBe(false); + }); +}); + describe('the checkpoint of "Put this file back" in Last turn', () => { const turn = { ts: NOW - 3 * MIN, task: null }; diff --git a/src/home/composerSend.ts b/src/home/composerSend.ts index b39fb469..ad905da5 100644 --- a/src/home/composerSend.ts +++ b/src/home/composerSend.ts @@ -1,5 +1,6 @@ // May the composer send what it holds, and if not, why: the send button's state and its hint. // ↵ follows the same rule: while sending is off it keeps the text and does nothing else. +import { rewindLayer } from './rewindLayer.svelte'; export type SendState = { ok: true } | { ok: false; why: string | null }; @@ -7,8 +8,11 @@ export type SendState = { ok: true } | { ok: false; why: string | null }; * `inTerminal`: the name of the agent of this chat while it is in your terminal (Codly sends * it nothing until you give it back), else null. `unknown`: the first word is a slash command * Codly does not have (`unknownSlash`). `why` null: there is nothing to send, which needs no word. + * While "Undo a turn" is open over the composer nothing is sent: a ↵ meant for the list must + * never start a turn under it (RewindMenu.svelte). */ export function sendState(s: { text: string; files: number; saving: boolean; unknown: boolean; inTerminal: string | null }): SendState { + if (rewindLayer.agentId !== null) return { ok: false, why: 'Close “Undo a turn” to send' }; if (s.inTerminal) return { ok: false, why: `${s.inTerminal} is in your terminal: give it back to send` }; if (s.unknown) return { ok: false, why: 'No such command: change the text to send it' }; if (s.saving) return { ok: false, why: 'Wait until the files are attached' }; diff --git a/src/home/rewind.ts b/src/home/rewind.ts index a31dcb0f..59283828 100644 --- a/src/home/rewind.ts +++ b/src/home/rewind.ts @@ -5,6 +5,7 @@ // inside the CLI stays, and the core tells the agent which files went back. import type { AgentCheckpoints } from '../lib/gen/AgentCheckpoints'; import type { LastTurn } from '../lib/gen/LastTurn'; +import { ESC_PAIR_WINDOW } from '../lib/state/esc'; import { ago, plural } from '../lib/util/format'; import { noTurn } from './agentTurns'; @@ -39,6 +40,12 @@ export function rewindOff(kept: Pick, n return noTurn({ off: kept.off, checkpoints: kept.checkpoints.filter((c) => c.kind === 'turn') }, name); } +/** The line under the list's title when the turns are not of the agent's own worktree: a 1:1 agent on a task works in the task's. */ +export const rewindWhere = (kept: Pick): string | null => (kept.task ? `Turns of task ${kept.task}, in its worktree` : null); + +/** The files too big for a checkpoint, which a restore leaves as they are; null: none. */ +export const leftOutLine = (kept: Pick): string | null => (kept.left_out.length ? `Not kept, too big: ${kept.left_out.join(', ')}` : null); + /** The first file names, cut: "a.ts, b.ts, c.ts and 2 more". `changed`: how many files there are in all. */ export function namesLine(files: string[], changed: number): string { const shown = files.slice(0, NAMES); @@ -106,6 +113,17 @@ export function pick(nav: RewindNav, rows: RewindRow[], at: number): { nav: Rewi return { nav: { ...nav, at, asking: { n: it.n, path: it.kind === 'file' ? it.path : null } }, act: null }; } +/** + * The focus moved onto row `at` (Tab, a press, the keys): the keys are there now, so ↵ acts on + * the row that has the focus. The confirm line of another row closes: it asked about that row. + * A row that cannot be picked takes no focus, and changes nothing. + */ +export function focusRow(nav: RewindNav, rows: RewindRow[], at: number): RewindNav { + const it = rewindItems(rows, nav.open)[at]; + if (!it || !pickable(rows, it) || at === nav.at) return nav; + return { ...nav, at, asking: null }; +} + /** * A key in the list. ↑ ↓ move over the rows that can be picked, → lists the files of the turn * (← and Esc close them), ↵ shows the confirm line in place and a second ↵ restores. Esc closes @@ -134,6 +152,13 @@ export function rewindKey(nav: RewindNav, rows: RewindRow[], key: string): { nav return { nav, act: null }; } +/** + * Is an Esc at `now` held by the list that an Esc closed at `closedAt`: it only leaves the + * composer the focus went back to. It must not begin a pair (esc.ts `escPair`): three fast + * presses would close the list and open it again. + */ +export const heldAfterClose = (closedAt: number, now: number): boolean => now >= closedAt && now - closedAt <= ESC_PAIR_WINDOW; + /** * The checkpoint "Put this file back" of the sheet's Last turn restores from: the newest turn * checkpoint of the list, only when the list is of the worktree the turn shown was read in (the diff --git a/src/home/rewindLayer.svelte.ts b/src/home/rewindLayer.svelte.ts index ee51ac14..8988af80 100644 --- a/src/home/rewindLayer.svelte.ts +++ b/src/home/rewindLayer.svelte.ts @@ -1,9 +1,11 @@ // Whose "Undo a turn" list is open over the composer (Esc Esc, `/undo`, the palette's row), and // the restore that list and the sheet's Last turn share: a toast says what went back, with Undo. +import { on } from 'svelte/events'; import { api } from '../lib/api'; +import { ESC_PAIR_WINDOW } from '../lib/state/esc'; import { toast } from '../lib/state/toasts.svelte'; import { plural } from '../lib/util/format'; -import { putBackTitle } from './rewind'; +import { heldAfterClose, putBackTitle } from './rewind'; /** How long the toast after a restore offers Undo. Later, Checkpoints in the agent's sheet still can. */ const UNDO_MS = 10_000; @@ -34,6 +36,28 @@ class RewindLayer { export const rewindLayer = new RewindLayer(); +/** + * An Esc closed the list, and the focus went back to the composer. The next Esc there, within + * `ESC_PAIR_WINDOW`, only leaves the composer: it begins no pair in keys.ts, so a third fast press + * does not open the list again (`heldAfterClose`). It runs after the composer's own Esc (a menu, + * a toast that waits), on the document, before keys.ts on the window. Armed after the closing + * Esc is done, so that one is not counted. + */ +export function closedByEsc() { + const closedAt = Date.now(); + setTimeout(() => { + const off = on(document, 'keydown', (e) => { + if (e.key !== 'Escape') return; + off(); + const field = e.target as HTMLElement; + if (!heldAfterClose(closedAt, Date.now()) || field.tagName !== 'TEXTAREA' || !field.closest('[aria-label="Composer"]')) return; + e.stopPropagation(); + if (!e.defaultPrevented) field.blur(); + }); + setTimeout(off, ESC_PAIR_WINDOW); + }); +} + const words = (e: unknown) => (e instanceof Error ? e.message : String(e)); /** diff --git a/src/lib/__tests__/checkpoints.test.ts b/src/lib/__tests__/checkpoints.test.ts deleted file mode 100644 index 9dc9ec33..00000000 --- a/src/lib/__tests__/checkpoints.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { DemoCheckpoints } from '../demo/checkpoints'; -import type { Agent } from '../gen/Agent'; - -const NOW = 1_760_000_000_000; -const agent = (o: Partial) => ({ id: 'a1', name: 'Ada', status: 'idle', worktree: '/demo/wt/ada', ...o }) as Agent; - -// The demo follows the rules of orchestrator/checkpoints.rs; these are the same cases. -describe('DemoCheckpoints', () => { - it('lists the points of an agent with a worktree, newest first', () => { - const view = new DemoCheckpoints().list(agent({}), NOW); - expect(view.off).toBeNull(); - expect(view.checkpoints.map((c) => c.n)).toEqual([3, 2, 1]); - expect(view.checkpoints.every((c) => c.kind === 'turn' && c.changed === c.files.length && c.ts < NOW)).toBe(true); - }); - - it('says why an agent without a worktree has none, and restores nothing there', () => { - const demo = new DemoCheckpoints(); - const lead = agent({ name: 'Lead', worktree: null }); - expect(demo.list(lead, NOW)).toEqual({ off: 'Lead has no worktree now, so there are no checkpoints.', checkpoints: [], task: null, left_out: [] }); - expect(() => demo.restore(lead, 1, NOW)).toThrow('no worktree'); - expect(demo.list(undefined, NOW).checkpoints).toEqual([]); - }); - - it('a restore keeps the way back as the newest point', () => { - const demo = new DemoCheckpoints(); - const ada = agent({}); - const before = demo.list(ada, NOW).checkpoints.find((c) => c.n === 2)!; - const done = demo.restore(ada, 2, NOW + 1); - expect(done).toEqual({ files: before.files, undo: 4 }); - const after = demo.list(ada, NOW + 2).checkpoints; - expect(after.map((c) => [c.n, c.kind])).toEqual([[4, 'restore'], [3, 'turn'], [2, 'turn'], [1, 'turn']]); - expect(after[0]).toMatchObject({ label: before.label, changed: before.changed, ts: NOW + 1 }); - expect(after[2]).toMatchObject({ changed: 0, files: [] }); - // The files are as at that point now: nothing to restore there, and the undo is possible. - expect(() => demo.restore(ada, 2, NOW + 3)).toThrow('already as they were'); - expect(demo.restore(ada, 4, NOW + 3).undo).toBe(5); - }); - - it('one file goes back alone, and the other files of the point still differ', () => { - const demo = new DemoCheckpoints(); - const ada = agent({}); - const done = demo.restore(ada, 2, NOW + 1, 'src/theme/useTheme.ts'); - expect(done).toEqual({ files: ['src/theme/useTheme.ts'], undo: 4 }); - const after = demo.list(ada, NOW + 2).checkpoints; - expect(after[0]).toMatchObject({ n: 4, kind: 'restore', changed: 1, files: ['src/theme/useTheme.ts'] }); - expect(after.find((c) => c.n === 2)).toMatchObject({ changed: 1, files: ['src/theme/ThemeProvider.tsx'] }); - // That file is as it was at the point now; a file the point never listed was never different. - expect(() => demo.restore(ada, 2, NOW + 3, 'src/theme/useTheme.ts')).toThrow('src/theme/useTheme.ts is already as it was at that point'); - expect(() => demo.restore(ada, 2, NOW + 3, 'README.md')).toThrow('README.md is already as it was at that point'); - expect(() => demo.restore(agent({ status: 'working' }), 2, NOW + 3, 'src/theme/ThemeProvider.tsx')).toThrow('Ada is still working'); - }); - - it('the last turn is the newest point taken before a turn, with what differs from it now', () => { - const demo = new DemoCheckpoints(); - const ada = agent({}); - const turn = demo.lastTurn(ada, NOW)!; - expect(turn).toMatchObject({ label: 'Wire the theme toggle into the header', ts: NOW - 4 * 60_000, task: null }); - expect(turn.diff).toContain('diff --git a/src/theme/ThemeProvider.tsx b/src/theme/ThemeProvider.tsx'); - // Its files went back: the turn is still the last one, and nothing of it is left. - demo.restore(ada, 3, NOW + 1); - expect(demo.lastTurn(ada, NOW + 2)).toMatchObject({ label: 'Wire the theme toggle into the header', diff: '' }); - expect(demo.lastTurn(agent({ worktree: null }), NOW)).toBeNull(); - expect(demo.lastTurn(undefined, NOW)).toBeNull(); - }); - - it('refuses while the agent works, and for a point that is gone', () => { - const demo = new DemoCheckpoints(); - expect(() => demo.restore(agent({ status: 'working' }), 2, NOW)).toThrow('Ada is still working; restore files when its turn ends'); - expect(() => demo.restore(agent({}), 99, NOW)).toThrow('that point is gone'); - expect(demo.list(agent({}), NOW).checkpoints).toHaveLength(3); - }); - - it('an agent that changed nothing yet has no point and no last turn', () => { - const changed = new Set(); - const demo = new DemoCheckpoints((id) => changed.has(id)); - const ada = agent({}); - expect(demo.list(ada, NOW)).toEqual({ off: null, checkpoints: [], task: null, left_out: [] }); - expect(demo.lastTurn(ada, NOW)).toBeNull(); - expect(() => demo.restore(ada, 1, NOW)).toThrow('that point is gone'); - // Once a turn changed a file, it has its points. - changed.add(ada.id); - expect(demo.list(ada, NOW).checkpoints).toHaveLength(3); - }); -}); diff --git a/src/lib/__tests__/demoCheckpoints.test.ts b/src/lib/__tests__/demoCheckpoints.test.ts new file mode 100644 index 00000000..85aa28d6 --- /dev/null +++ b/src/lib/__tests__/demoCheckpoints.test.ts @@ -0,0 +1,148 @@ +import { describe, expect, it, vi } from 'vitest'; +import { DemoCheckpoints } from '../demo/checkpoints'; +import { editedTurns } from '../demo/sim'; +import type { Agent } from '../gen/Agent'; +import type { EventKind } from '../gen/EventKind'; +import type { EventRow } from '../gen/EventRow'; +import type { Task } from '../gen/Task'; + +const NOW = 1_760_000_000_000; +const MIN = 60_000; +const agent = (o: Partial = {}) => ({ id: 'a1', name: 'Ada', role: 'solo', status: 'idle', worktree: '/demo/wt/ada', task_id: null, ...o }) as Agent; + +/** The parts of the demo's Sim the checkpoints read and write, with a log of turns. */ +function demo() { + const log: EventRow[] = []; + const emit = (agentId: string, task: string | null, ts: number, kind: EventKind) => log.push({ id: log.length + 1, ts, agent_id: agentId, task_id: task, run_id: null, kind }); + /** A turn of `agentId` that started with `input` and changed each list of `files` in one tool call. */ + const turn = (input: string | null, files: string[][], o: { agentId?: string; ts?: number; task?: string } = {}) => { + const id = o.agentId ?? 'a1'; + const ts = o.ts ?? NOW; + const task = o.task ?? null; + emit(id, task, ts, { type: 'turn_started', input }); + for (const paths of files) emit(id, task, ts + 1, { type: 'files_changed', call_id: null, paths, source: 'tool_input' } as EventKind); + emit(id, task, ts + 2, { type: 'turn_completed', status: 'completed', result_text: null, duration_ms: 2 }); + }; + const sim = { log, tasks: new Map([['t-id', { key: 'T-4' } as Task]]), chat: vi.fn(), decision: vi.fn() }; + return { sim, turn, points: new DemoCheckpoints(sim) }; +} + +describe('the turns the demo keeps points of', () => { + it('are the agent’s own turns that changed files, oldest first, named as the core names them', () => { + const { sim, turn } = demo(); + turn('[User] Add the form\n to the page', [['src/form.ts'], ['src/form.ts', 'src/page.ts']], { ts: NOW - 9 * MIN }); + turn('Read the README', [], { ts: NOW - 8 * MIN }); + turn('Fix the label', [['src/form.ts']], { agentId: 'a2', ts: NOW - 7 * MIN }); + turn(null, [['src/page.ts']], { ts: NOW - 6 * MIN }); + turn('x'.repeat(130), [['a.ts']], { ts: NOW - 5 * MIN }); + const turns = editedTurns(sim, 'a1'); + expect(turns.map((t) => [t.label, t.files, t.ts])).toEqual([ + ['Add the form to the page', ['src/form.ts', 'src/page.ts'], NOW - 9 * MIN], + ['a turn', ['src/page.ts'], NOW - 6 * MIN], + [`${'x'.repeat(119)}…`, ['a.ts'], NOW - 5 * MIN], + ]); + expect(editedTurns(sim, 'a2').map((t) => t.label)).toEqual(['Fix the label']); + }); +}); + +describe('DemoCheckpoints', () => { + it('lists the agent’s own turns, newest first, each with the files that differ from it now; later turns join', () => { + const { turn, points } = demo(); + turn('Add the form', [['a.ts', 'b.ts']], { ts: NOW - 9 * MIN }); + turn('Fix the label', [['b.ts']], { ts: NOW - 5 * MIN }); + const view = points.list(agent(), NOW); + expect(view).toMatchObject({ off: null, task: null, left_out: [] }); + expect(view.checkpoints).toEqual([ + { n: 2, kind: 'turn', ts: NOW - 5 * MIN, label: 'Fix the label', changed: 1, files: ['b.ts'] }, + { n: 1, kind: 'turn', ts: NOW - 9 * MIN, label: 'Add the form', changed: 2, files: ['a.ts', 'b.ts'] }, + ]); + turn('Add a test', [['c.ts']], { ts: NOW - MIN }); + expect(points.list(agent(), NOW).checkpoints.map((c) => [c.n, c.label, c.changed])).toEqual([ + [3, 'Add a test', 1], + [2, 'Fix the label', 2], + [1, 'Add the form', 3], + ]); + }); + + it('says why an agent without a worktree has none, and restores nothing there', () => { + const { points } = demo(); + const lead = agent({ name: 'Lead', worktree: null }); + expect(points.list(lead, NOW)).toEqual({ off: 'Lead has no worktree now, so there are no checkpoints.', checkpoints: [], task: null, left_out: [] }); + expect(() => points.restore(lead, 1, NOW)).toThrow('no worktree'); + expect(points.list(undefined, NOW).checkpoints).toEqual([]); + }); + + it('a restore keeps the way back as the newest point, and says so in the conversation and in History', () => { + const { sim, turn, points } = demo(); + turn('Add the form', [['a.ts', 'b.ts']], { ts: NOW - 9 * MIN }); + turn('Fix the label', [['b.ts']], { ts: NOW - 5 * MIN }); + expect(points.restore(agent(), 2, NOW)).toEqual({ files: ['b.ts'], undo: 3 }); + expect(points.list(agent(), NOW).checkpoints.map((c) => [c.n, c.kind, c.label, c.changed])).toEqual([ + [3, 'restore', 'Fix the label', 1], + [2, 'turn', 'Fix the label', 0], + [1, 'turn', 'Add the form', 2], + ]); + expect(sim.decision).toHaveBeenLastCalledWith('checkpoint', 'human', 'you put 1 file of Ada back to before “Fix the label”', { agent_id: 'a1', checkpoint: 2, undo: 3, files: ['b.ts'] }); + expect(sim.chat).toHaveBeenLastCalledWith('agent:a1', 'codly', 'Put 1 file of Ada back to before “Fix the label”. Files only: Ada still remembers the later turns. To undo, restore the newest point.'); + // The files are as at that point now: nothing to restore there. The undo puts them back. + expect(() => points.restore(agent(), 2, NOW)).toThrow('already as they were'); + expect(points.restore(agent(), 3, NOW + 1)).toEqual({ files: ['b.ts'], undo: 4 }); + expect(sim.decision).toHaveBeenLastCalledWith('checkpoint', 'human', 'you put 1 file of Ada back to before an earlier restore', { agent_id: 'a1', checkpoint: 3, undo: 4, files: ['b.ts'] }); + expect(points.list(agent(), NOW).checkpoints.find((c) => c.n === 2)).toMatchObject({ changed: 1, files: ['b.ts'] }); + }); + + it('one file goes back alone, and the counts of the other points follow', () => { + const { sim, turn, points } = demo(); + turn('Add the form', [['a.ts', 'b.ts']], { ts: NOW - 9 * MIN }); + turn('Fix the label', [['b.ts']], { ts: NOW - 5 * MIN }); + expect(points.restore(agent(), 1, NOW, 'a.ts')).toEqual({ files: ['a.ts'], undo: 3 }); + expect(sim.chat).toHaveBeenLastCalledWith('agent:a1', 'codly', 'Put a.ts of Ada back to before “Add the form”. The other files stay as they are, and Ada still remembers the later turns. To undo, restore the newest point.'); + const after = points.list(agent(), NOW).checkpoints; + expect(after[0]).toMatchObject({ n: 3, kind: 'restore', changed: 1, files: ['a.ts'] }); + expect(after.find((c) => c.n === 1)).toMatchObject({ changed: 1, files: ['b.ts'] }); + // a.ts was as "Add the form" left it before "Fix the label": it differs from that point now. + expect(after.find((c) => c.n === 2)).toMatchObject({ changed: 2, files: ['a.ts', 'b.ts'] }); + expect(() => points.restore(agent(), 1, NOW, 'a.ts')).toThrow('a.ts is already as it was at that point'); + expect(() => points.restore(agent(), 1, NOW, 'README.md')).toThrow('README.md is already as it was at that point'); + expect(() => points.restore(agent({ status: 'working' }), 1, NOW, 'b.ts')).toThrow('Ada is still working'); + }); + + it('a 1:1 agent on a task: the turns of the task’s worktree, and the list says which task', () => { + const { turn, points } = demo(); + turn('Own work', [['a.ts']], { ts: NOW - 9 * MIN }); + turn('Task T-4: Dark mode', [['theme.ts']], { ts: NOW - 5 * MIN, task: 't-id' }); + const onTask = agent({ task_id: 't-id' }); + const view = points.list(onTask, NOW); + expect(view.task).toBe('T-4'); + expect(view.checkpoints.map((c) => c.label)).toEqual(['Task T-4: Dark mode']); + expect(points.lastTurn(onTask, NOW)).toMatchObject({ label: 'Task T-4: Dark mode', task: 'T-4' }); + // Its own worktree again: its own turns. + expect(points.list(agent(), NOW).checkpoints.map((c) => c.label)).toEqual(['Own work']); + // A team member's worktree is the task's: the list names no other one. + expect(points.list(agent({ role: 'worker', task_id: 't-id' }), NOW).task).toBeNull(); + }); + + it('the last turn is the newest point taken before a turn, with what differs from it now', () => { + const { turn, points } = demo(); + turn('Add the form', [['a.ts', 'b.ts']], { ts: NOW - 9 * MIN }); + turn('Fix the label', [['b.ts']], { ts: NOW - 5 * MIN }); + const last = points.lastTurn(agent(), NOW)!; + expect(last).toMatchObject({ label: 'Fix the label', ts: NOW - 5 * MIN, task: null }); + expect(last.diff).toContain('diff --git a/b.ts b/b.ts'); + expect(last.diff).not.toContain('a.ts'); + // Its files went back: the turn is still the last one, and nothing of it is left. + points.restore(agent(), 2, NOW); + expect(points.lastTurn(agent(), NOW)).toMatchObject({ label: 'Fix the label', diff: '' }); + expect(points.lastTurn(agent({ worktree: null }), NOW)).toBeNull(); + expect(points.lastTurn(undefined, NOW)).toBeNull(); + }); + + it('an agent that changed nothing yet has no point and no last turn; a point that is gone cannot be restored', () => { + const { turn, points } = demo(); + turn('Read the README', []); + expect(points.list(agent(), NOW)).toEqual({ off: null, checkpoints: [], task: null, left_out: [] }); + expect(points.lastTurn(agent(), NOW)).toBeNull(); + expect(() => points.restore(agent(), 1, NOW)).toThrow('that point is gone'); + expect(() => points.restore(agent({ status: 'working' }), 1, NOW)).toThrow('Ada is still working; restore files when its turn ends'); + }); +}); diff --git a/src/lib/__tests__/toasts.test.ts b/src/lib/__tests__/toasts.test.ts index e7b3f93c..1d0473f3 100644 --- a/src/lib/__tests__/toasts.test.ts +++ b/src/lib/__tests__/toasts.test.ts @@ -289,3 +289,50 @@ describe('a toast whose action can no longer be done', () => { expect(titles()).toEqual(['Push failed', 'Saved']); }); }); + +describe('while the page is out of view', () => { + beforeEach(() => vi.useFakeTimers()); + afterEach(() => { + for (const t of [...toasts.list]) toasts.dismiss(t.id); + toasts.seen(true); + vi.useRealTimers(); + }); + + it('a toast that came meanwhile has its whole time from when the page is seen', () => { + toasts.seen(false); + toasts.show({ kind: 'success', title: 'Saved' }); + vi.advanceTimersByTime(60_000); + expect(titles()).toEqual(['Saved']); + toasts.seen(true); + vi.advanceTimersByTime(3999); + expect(titles()).toEqual(['Saved']); + vi.advanceTimersByTime(1); + expect(titles()).toEqual([]); + }); + + it('a toast that showed goes on with the time it had left, 1.2 s at least', () => { + toasts.show({ kind: 'success', title: 'Saved' }); + toasts.show({ kind: 'info', title: 'Ada joined' }); + vi.advanceTimersByTime(3500); + toasts.seen(false); + vi.advanceTimersByTime(60_000); + expect(titles()).toEqual(['Saved', 'Ada joined']); + toasts.seen(true); + vi.advanceTimersByTime(1199); + expect(titles()).toEqual(['Saved', 'Ada joined']); + vi.advanceTimersByTime(1); + expect(titles()).toEqual(['Ada joined']); + vi.advanceTimersByTime(1299); + expect(titles()).toEqual(['Ada joined']); + vi.advanceTimersByTime(1); + expect(titles()).toEqual([]); + }); + + it('at most three stay in the list, and one that is dismissed leaves it at once', () => { + toasts.seen(false); + const ids = ['a', 'b', 'c', 'd', 'e'].map((title) => toasts.show({ kind: 'info', title })); + expect(titles()).toEqual(['c', 'd', 'e']); + toasts.dismiss(ids[3]); + expect(titles()).toEqual(['c', 'e']); + }); +}); diff --git a/src/lib/demo/checkpoints.ts b/src/lib/demo/checkpoints.ts index 2ce856e4..fcbf8fbc 100644 --- a/src/lib/demo/checkpoints.ts +++ b/src/lib/demo/checkpoints.ts @@ -1,77 +1,122 @@ -// The browser demo's answer to `agent_checkpoints`, `restore_checkpoint` and `last_turn_diff`: a -// few points for an agent with a worktree, a restore that follows the rules of the real core -// (orchestrator/checkpoints.rs): refused while the agent works, files only, one file or all of -// them, and the state it replaces becomes the newest point, so it can be undone. The last turn is -// the newest point taken before a turn, with a small diff while files differ from it. +// The browser demo's answer to `agent_checkpoints`, `restore_checkpoint` and `last_turn_diff`. +// The points are the agent's own turns that changed files (sim.ts `editedTurns`), each kept +// before its turn, in the worktree it works in now: the turns of the task it is on, or of its +// own work. A restore follows the rules of the real core (orchestrator/checkpoints.rs): refused +// while the agent works, files only, one file or all of them, and the state it replaces becomes +// the newest point, so it can be undone. Like the core it leaves a row in the agent's +// conversation and one in History. Each point counts the files that differ between it and the +// files now, so a restore or a later turn changes the counts of the other points too. The last +// turn is the newest point taken before a turn, with a small diff of the files that differ from it. import type { Agent } from '../gen/Agent'; import type { AgentCheckpoints } from '../gen/AgentCheckpoints'; import type { Checkpoint } from '../gen/Checkpoint'; import type { CheckpointRestore } from '../gen/CheckpointRestore'; import type { LastTurn } from '../gen/LastTurn'; +import { editedTurns, type Sim } from './sim'; -const MIN = 60_000; const RESTING = ['idle', 'done', 'failed', 'offline']; -/** What the demo's last turn did to the one file its newest point lists. */ -const TURN_DIFF = `diff --git a/src/theme/ThemeProvider.tsx b/src/theme/ThemeProvider.tsx -index 3f1c2aa..9d0e4b7 100644 ---- a/src/theme/ThemeProvider.tsx -+++ b/src/theme/ThemeProvider.tsx -@@ -12,6 +12,7 @@ export function ThemeProvider({ children }: Props) { - const [theme, setTheme] = useState(initial); - useEffect(() => { - document.documentElement.dataset.theme = theme; -+ localStorage.setItem('theme', theme); - }, [theme]); - return {children}; - } -`; +/** The core keeps the last 50 points of an agent. */ +const KEPT = 50; +/** A file as it was before the demo's first turn. */ +const ORIGINAL = 'original'; + +/** Each file's state: which turn wrote it last (`turn `), or `ORIGINAL`. A file not named is `ORIGINAL`. */ +type Files = Map; +/** A restore you made: the files it put back, and the state each one went back to. */ +type Restore = { n: number; ts: number; label: string; task: string | null; put: Files }; + +const state = (files: Files, f: string) => files.get(f) ?? ORIGINAL; + +/** The files that differ between `a` and `b`, by name. */ +function differ(a: Files, b: Files): string[] { + return [...new Set([...a.keys(), ...b.keys()])].filter((f) => state(a, f) !== state(b, f)).sort(); +} export class DemoCheckpoints { - private byAgent = new Map(); - /** `changed`: has the agent changed a file yet? Codly takes a point only when a turn changed something: an agent that changed nothing has none. */ - constructor(private changed: (agentId: string) => boolean = () => true) {} + /** The number of each agent's turn (by its row id), given once in order: a later point has a higher one. */ + private numbers = new Map>(); + private last = new Map(); + private restores = new Map(); + + constructor(private sim: Pick) {} + + private take(agentId: string): number { + const n = (this.last.get(agentId) ?? 0) + 1; + this.last.set(agentId, n); + return n; + } + + /** The key of the task whose worktree this is, when it is not the agent's own: a 1:1 agent on a task works there. */ + private taskKey(agent: Agent): string | null { + return agent.role === 'solo' && agent.task_id ? (this.sim.tasks.get(agent.task_id)?.key ?? null) : null; + } - private points(agent: Agent, now: number): Checkpoint[] { - if (!this.changed(agent.id)) return []; - let list = this.byAgent.get(agent.id); - if (!list) { - list = [ - { n: 3, kind: 'turn', ts: now - 4 * MIN, label: 'Wire the theme toggle into the header', changed: 1, files: ['src/theme/ThemeProvider.tsx'] }, - { n: 2, kind: 'turn', ts: now - 19 * MIN, label: 'Add a useTheme hook that follows the system setting', changed: 2, files: ['src/theme/ThemeProvider.tsx', 'src/theme/useTheme.ts'] }, - { n: 1, kind: 'turn', ts: now - 47 * MIN, label: 'Task t1: Dark mode', changed: 3, files: ['src/theme/ThemeProvider.tsx', 'src/theme/theme.test.tsx', 'src/theme/useTheme.ts'] }, - ]; - this.byAgent.set(agent.id, list); + /** The points of the worktree the agent works in now, newest first, the files at each, and the files now. */ + private points(agent: Agent): { list: Checkpoint[]; at: Map; now: Files } { + const numbers = this.numbers.get(agent.id) ?? new Map(); + this.numbers.set(agent.id, numbers); + const turns = editedTurns(this.sim, agent.id); + for (const t of turns) if (!numbers.has(t.id)) numbers.set(t.id, this.take(agent.id)); + type Step = { n: number; ts: number; label: string; kind: 'turn'; files: string[] } | ({ kind: 'restore' } & Restore); + const steps: Step[] = [ + ...turns.filter((t) => t.task === agent.task_id).map((t) => ({ n: numbers.get(t.id)!, ts: t.ts, label: t.label, kind: 'turn' as const, files: t.files })), + ...(this.restores.get(agent.id) ?? []).filter((r) => r.task === agent.task_id).map((r) => ({ kind: 'restore' as const, ...r })), + ].sort((a, b) => a.n - b.n); + const now: Files = new Map(); + const at = new Map(); + for (const s of steps) { + at.set(s.n, new Map(now)); + if (s.kind === 'turn') for (const f of s.files) now.set(f, `turn ${s.n}`); + else for (const [f, was] of s.put) now.set(f, was); } - return list; + const list = steps + .map((s): Checkpoint => { + const files = differ(at.get(s.n)!, now); + return { n: s.n, kind: s.kind, ts: s.ts, label: s.label, changed: files.length, files }; + }) + .reverse() + .slice(0, KEPT); + return { list, at, now }; } - list(agent: Agent | undefined, now: number): AgentCheckpoints { + // `_now` (list, lastTurn): the mock passes its clock to each call; the points carry the times of their turns. + list(agent: Agent | undefined, _now: number): AgentCheckpoints { if (!agent?.worktree) return { off: `${agent?.name ?? 'This agent'} has no worktree now, so there are no checkpoints.`, checkpoints: [], task: null, left_out: [] }; - return { off: null, checkpoints: this.points(agent, now), task: null, left_out: [] }; + return { off: null, checkpoints: this.points(agent).list, task: this.taskKey(agent), left_out: [] }; } /** `path`: put back that one file of the point; null: all of them. */ restore(agent: Agent | undefined, n: number, now: number, path: string | null = null): CheckpointRestore { if (!agent?.worktree) throw new Error(this.list(agent, now).off ?? 'No checkpoints.'); if (!RESTING.includes(agent.status)) throw new Error(`${agent.name} is still working; restore files when its turn ends`); - const list = this.points(agent, now); + const { list, at } = this.points(agent); const target = list.find((c) => c.n === n); if (!target) throw new Error('that point is gone: Codly keeps the last 50 of an agent'); if (!target.changed) throw new Error('the files are already as they were at that point'); if (path != null && !target.files.includes(path)) throw new Error(`${path} is already as it was at that point`); const files = path == null ? target.files : [path]; - const undo = Math.max(...list.map((c) => c.n)) + 1; - // The files that went back are now as at `target`; what they were is the new point on top. - const left = target.files.filter((f) => !files.includes(f)); - const rest = list.map((c) => (c.n === n ? { ...c, changed: left.length, files: left } : c)); - this.byAgent.set(agent.id, [{ n: undo, kind: 'restore', ts: now, label: target.label, changed: files.length, files }, ...rest]); + const was = at.get(n)!; + const undo = this.take(agent.id); + // What the files are now is the new point on top: restoring it undoes this. + const restores = this.restores.get(agent.id) ?? []; + restores.push({ n: undo, ts: now, label: target.label, task: agent.task_id, put: new Map(files.map((f) => [f, state(was, f)])) }); + this.restores.set(agent.id, restores); + // As the core says it, in its record and in the agent's conversation. + const point = target.kind === 'turn' ? `before “${target.label}”` : 'before an earlier restore'; + const what = `${path ?? `${files.length} ${files.length === 1 ? 'file' : 'files'}`} of ${agent.name} back to ${point}`; + this.sim.decision('checkpoint', 'human', `you put ${what}`, { agent_id: agent.id, checkpoint: n, undo, files }); + const rest = path != null ? 'The other files stay as they are, and' : 'Files only:'; + this.sim.chat(`agent:${agent.id}`, 'codly', `Put ${what}. ${rest} ${agent.name} still remembers the later turns. To undo, restore the newest point.`); return { files, undo }; } /** The agent's last turn: the newest point taken before a turn, and what differs from it now. */ - lastTurn(agent: Agent | undefined, now: number): LastTurn | null { + lastTurn(agent: Agent | undefined, _now: number): LastTurn | null { if (!agent?.worktree) return null; - const turn = this.points(agent, now).find((c) => c.kind === 'turn'); - return turn ? { label: turn.label, ts: turn.ts, diff: turn.changed ? TURN_DIFF : '', task: null } : null; + const turn = this.points(agent).list.find((c) => c.kind === 'turn'); + if (!turn) return null; + // The demo has no file contents: each file that differs shows one line the turn added. + const diff = turn.files.map((f) => `diff --git a/${f} b/${f}\n--- a/${f}\n+++ b/${f}\n@@ -1,0 +1,1 @@\n+// ${turn.label}\n`).join(''); + return { label: turn.label, ts: turn.ts, diff, task: this.taskKey(agent) }; } } diff --git a/src/lib/demo/sim.ts b/src/lib/demo/sim.ts index f10d8b3c..2510b175 100644 --- a/src/lib/demo/sim.ts +++ b/src/lib/demo/sim.ts @@ -644,3 +644,37 @@ export class Actor { this.emit({ type: 'rate_limit', window: w.window, used_fraction: w.used_fraction, resets_at: w.resets_at, status: w.status }); } } + +/** One turn of an agent that changed files (`editedTurns`). */ +export type EditedTurn = { + /** The id of its `turn_started` row: a later turn has a higher one. */ + id: number; + /** The task the agent was on (its id), null: its own work. */ + task: string | null; + ts: number; + /** As the core names a turn's checkpoint (orchestrator/checkpoints.rs `turn_label`): the prompt on one line, without its tag, cut at 120. */ + label: string; + /** The files it changed, in the order it first changed them. */ + files: string[]; +}; + +/** + * The turns of agent `agentId` that changed files, oldest first, as the log tells them: the + * demo's checkpoints follow them (demo/checkpoints.ts). The log is cut: its oldest turns go. + */ +export function editedTurns(sim: Pick, agentId: string): EditedTurn[] { + const turns: EditedTurn[] = []; + let at: EditedTurn | undefined; + for (const row of sim.log) { + if (row.agent_id !== agentId) continue; + const k = row.kind; + if (k.type === 'turn_started') { + const line = (k.input ?? '').trim().replace(/^\[(User|Codly|Lead)\]/, '').split(/\s+/).filter(Boolean).join(' '); + at = { id: row.id, task: row.task_id, ts: row.ts, label: !line ? 'a turn' : line.length > 120 ? `${line.slice(0, 119)}…` : line, files: [] }; + turns.push(at); + } else if (k.type === 'files_changed' && at) { + for (const p of k.paths) if (!at.files.includes(p)) at.files.push(p); + } + } + return turns.filter((t) => t.files.length); +} diff --git a/src/lib/mock.ts b/src/lib/mock.ts index 6126a763..aab4dd62 100644 --- a/src/lib/mock.ts +++ b/src/lib/mock.ts @@ -210,7 +210,7 @@ function makeDesk(sim: Sim, states: DemoStates, billing = false): Desk { sim, story, checks, ctl: new MockControls(sim), breaker: new MockBreaker(sim), askMe: new MockAskMe(sim, !billing), conflicts: new MergeConflictDemo(trouble, sim, story), previews: new PreviewDemo(states.previewRunning), - workspaceTrust, pullRequests: new PullRequestDemo(states.prOpen), checkpoints: new DemoCheckpoints((id) => sim.edited.has(id)), + workspaceTrust, pullRequests: new PullRequestDemo(states.prOpen), checkpoints: new DemoCheckpoints(sim), takeovers: new DemoTakeovers(), worktrees: new WorktreeDemo(), hk: undefined, pushed: false, ahead: 0, closed: [], merge: null, mergeCommits: 0, }; } diff --git a/src/lib/state/toasts.svelte.ts b/src/lib/state/toasts.svelte.ts index 52f6a706..b89e31e7 100644 --- a/src/lib/state/toasts.svelte.ts +++ b/src/lib/state/toasts.svelte.ts @@ -32,6 +32,8 @@ class Toasts { private startedAt = new Map(); /** The toasts that are put away now (`putAway`): none of them counts down. */ private away = new Set(); + /** The page is out of view (`seen`): no toast counts down. */ + private hidden = false; /** * Shows a toast, and gives its id. A toast with the kind, the title and the text of one that @@ -107,8 +109,9 @@ class Toasts { } resume(id: number) { - // Not one that is put away (the pointer can leave it at the moment the stack folds), and not one that went. - if (this.away.has(id) || !this.list.some((t) => t.id === id)) return; + // Not one that is put away (the pointer can leave it at the moment the stack folds), not one + // that went, and none while the page is out of view. + if (this.hidden || this.away.has(id) || !this.list.some((t) => t.id === id)) return; const rem = this.remaining.get(id); if (rem != null && !this.timers.has(id)) this.arm(id, rem); } @@ -126,6 +129,20 @@ class Toasts { for (const id of before) if (!this.away.has(id)) this.resume(id); } + /** + * The page is in view (`visible`) or not (another tab or window is in front). While it is not, + * no toast counts down, so none goes before you could see it: one that came meanwhile starts + * its time when the page is seen, one that showed goes on with the time it had left, 1.2 s at least. + */ + seen(visible: boolean) { + if (this.hidden === !visible) return; + this.hidden = !visible; + for (const t of this.list) { + if (this.hidden) this.pause(t.id); + else this.resume(t.id); + } + } + /** Its time starts again. One that stands still now (the pointer is on it, or it is put away) gets the whole time when it goes on. */ private restart(id: number, ms: number) { if (ms && !this.timers.has(id) && this.remaining.has(id)) this.remaining.set(id, ms); @@ -141,8 +158,8 @@ class Toasts { return; } this.remaining.set(id, ms); - // Put away: its time starts when it shows again. - if (this.away.has(id)) return; + // Put away, or the page is out of view: its time starts when it shows again. + if (this.away.has(id) || this.hidden) return; this.startedAt.set(id, Date.now()); this.timers.set(id, setTimeout(() => this.dismiss(id), ms)); } diff --git a/src/sheet/AgentCheckpoints.svelte b/src/sheet/AgentCheckpoints.svelte index 0981955c..ea04c21a 100644 --- a/src/sheet/AgentCheckpoints.svelte +++ b/src/sheet/AgentCheckpoints.svelte @@ -20,7 +20,6 @@ import { ui } from '../lib/state/ui.svelte'; import { ago, plural } from '../lib/util/format'; import { oneAtATime } from '../lib/util/oneAtATime'; - import { rewindLayer } from '../home/rewindLayer.svelte'; import Icon from '../components/Icon.svelte'; interface Props { @@ -56,11 +55,11 @@ if (id === agent.id) error = e instanceof Error ? e.message : String(e); } }); - // Only `refresh` starts a read, and files put back elsewhere ("Undo a turn", Last turn, their - // Undo). The agent object is new on every step of its turn (each tool call, each usage - // report): that alone must not start git. + // Only `refresh` starts a read: the Git tab reads the worktree again also when files were put + // back elsewhere ("Undo a turn", Last turn, their Undo). The agent object is new on every step + // of its turn (each tool call, each usage report): that alone must not start git. $effect(() => { - void [refresh, rewindLayer.restored]; + void refresh; untrack(() => { if (resting || !view) void load(); }); @@ -109,9 +108,10 @@ + onclick={() => { if (resting && c.changed) asking = { n: c.n, path: null }; }}>Restore files
    {#if c.changed} + onclick={() => { if (resting) asking = { n: c.n, path: f }; }}>Restore this file {/each} {#if c.changed > c.files.length}
  • … and {c.changed - c.files.length} more. “Restore files” puts all of them back.
  • {/if} @@ -166,6 +167,8 @@