Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

fix: address Amp turn opening regressions and Pi transcript tailing gaps by updating event handling and file-backed replay logic.

0xken150f3e6149a0f7
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 649436534..6667257bb 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -509,6 +509,18 @@ async function runForeground(token: string): Promise<void> {
const cursorNormalizers = new Map<string, CursorNormalizer>()
const opencodeReaders = new Map<string, OpencodeReader>()
const kiloReaders = new Map<string, KiloReader>()
+ /**
+ * Sessions that attached before their transcript existed, so nothing was folded and nothing has ever
+ * been streamed for them.
+ *
+ * `bornAfterAgent` was supposed to cover this and does not always fire — measured on pi, whose agent is
+ * discovered the instant the engine starts but whose session file only materialises once the first
+ * answer is written: the re-attach that finally brought the path tailed from the file's END, so the
+ * entire first turn — prompt, tools and answer — was read as history and never reached web or device.
+ * A session that folded NOTHING can replay its whole file live without double-showing anything, which
+ * is the one case where starting at byte 0 is unambiguously right.
+ */
+ const neverFoldedHistory = new Set<string>()
const piNormalizers = new Map<string, PiNormalizer>()
const museNormalizers = new Map<string, MuseNormalizer>()
const ampNormalizers = new Map<string, AmpNormalizer>()
@@ -623,9 +635,10 @@ async function runForeground(token: string): Promise<void> {
|| commandcodeNormalizers.has(session.sessionId)
)) {
if (session.transcriptPath) {
+ const unseen = neverFoldedHistory.delete(session.sessionId)
await watcher.addSession(
{ ...session, transcriptPath: session.transcriptPath },
- { fromStart: replayFromStart || (session.engine === 'cursor' && replayCursorFromStart) },
+ { fromStart: replayFromStart || unseen || (session.engine === 'cursor' && replayCursorFromStart) },
)
}
else if (session.engine === 'cursor') await cursorDiscovery.add(session.sessionId)
@@ -752,9 +765,17 @@ async function runForeground(token: string): Promise<void> {
turnStates.set(session.sessionId, state)
}
if (session.transcriptPath) {
- await watcher.addSession({ ...session, transcriptPath: session.transcriptPath })
+ neverFoldedHistory.delete(session.sessionId)
+ await watcher.addSession(
+ { ...session, transcriptPath: session.transcriptPath },
+ { fromStart: replayFromStart },
+ )
} else if (session.engine === 'cursor') {
await cursorDiscovery.add(session.sessionId)
+ } else {
+ // No transcript to fold: whatever this session writes later is its FIRST content, so the re-attach
+ // that brings the path must read the file whole rather than from its end.
+ neverFoldedHistory.add(session.sessionId)
}
if (initialCursorEvents.length) emitSessionEvents(session.sessionId, initialCursorEvents)
console.log(`[agent] ${sid(session.agentId)} attached · engine=${session.engine} · pane=${session.tmuxPane} · session=${sid(session.sessionId)} · lines=${lines.length}`)
@@ -1027,6 +1048,7 @@ async function runForeground(token: string): Promise<void> {
opencodeReaders.delete(sessionId)
kiloReaders.get(sessionId)?.stop()
kiloReaders.delete(sessionId)
+ neverFoldedHistory.delete(sessionId)
piNormalizers.delete(sessionId)
museNormalizers.delete(sessionId)
ampNormalizers.delete(sessionId)
diff --git a/cli/src/engines/kilo/askQuestion.spec.ts b/cli/src/engines/kilo/askQuestion.spec.ts
index ecb7b7b6b..096b49bc5 100644
--- a/cli/src/engines/kilo/askQuestion.spec.ts
+++ b/cli/src/engines/kilo/askQuestion.spec.ts
@@ -57,3 +57,32 @@ describe('kilo permission dialog', () => {
expect(parseKiloQuestionPane('┃ △ Permission required\n┃ Access external directory /tmp')).toBeNull()
})
})
+
+/**
+ * kilo 7.4.22 added a right-hand status column, and it shares the PHYSICAL LINE with the dialog text.
+ * The fixture above is 7.4.20, which had no such column — so the first capture of this dialog looked
+ * clean and the pollution only showed up after the engine was upgraded. Lines below are the measured
+ * 7.4.22 shape.
+ */
+describe('kilo 7.4.22 status column', () => {
+ const pane = [
+ ' ┃ △ Permission required',
+ ' ┃ ← Access external directory /private/etc • Personal credits $0.00',
+ ' ┃',
+ ' ┃ Patterns /private/tmp/example/work-kilo2',
+ ' ┃',
+ ' ┃ - /private/etc/*',
+ ' ┃',
+ ' ┃ Allow once Allow always Reject ctrl+f fullscreen ⇆ select enter confirm',
+ ].join('\n')
+
+ it('keeps the credit balance out of what the user is asked to approve', () => {
+ const view = parseKiloQuestionPane(pane) as QuestionView
+ expect(view.question).toBe('Access external directory /private/etc')
+ })
+
+ it('still reads the options, which never shared a line with the column', () => {
+ const view = parseKiloQuestionPane(pane) as QuestionView
+ expect(view.rows.map((r) => r.label)).toEqual(['Allow once', 'Allow always', 'Reject'])
+ })
+})
diff --git a/cli/src/engines/kilo/askQuestion.ts b/cli/src/engines/kilo/askQuestion.ts
index dbef166be..246b2053c 100644
--- a/cli/src/engines/kilo/askQuestion.ts
+++ b/cli/src/engines/kilo/askQuestion.ts
@@ -118,9 +118,15 @@ export function parseKiloQuestionPane(capture: string): PaneView {
// What is being permitted: the first content line under the title, minus the `←` bullet kilo draws on
// it. Best-effort — the row list is what the answer actually depends on.
+ //
+ // Cut at the first run of 2+ spaces, the same way `labelsFrom` cuts the options line. Kilo 7.4.22
+ // paints a right-hand status column on the SAME physical line as the dialog text — measured live:
+ // `← Access external directory /private/etc • Personal credits $0.00` — so without the cut
+ // the device is asked to approve something with the user's credit balance stapled to it. 7.4.20 had no
+ // such column, which is exactly why the first capture of this dialog looked clean.
let question = ''
for (let i = title + 1; i < footer; i++) {
- const line = unbox(raw[i]).trim().replace(/^[←→‣>•-]\s*/, '').trim()
+ const line = unbox(raw[i]).trim().replace(/^[←→‣>•-]\s*/, '').split(/\s{2,}/)[0].trim()
if (!line) continue
question = line
break
diff --git a/cli/src/lib/hooks.ts b/cli/src/lib/hooks.ts
index d602c1c74..eb600bf58 100644
--- a/cli/src/lib/hooks.ts
+++ b/cli/src/lib/hooks.ts
@@ -629,11 +629,17 @@ const AMP_PLUGIN_PATH = join(env.AMP_PLUGIN_DIR, 'launcher-register.ts')
* `amp threads export` can fetch the content, but it is a ~1.5s network round trip that never shows a
* message before it is complete — useless for a live tail.
*
- * The plugin API is the way in. Five events fire (measured, in the TUI, not read off a doc):
- * `session.start`, `agent.start`, `tool.call`, `tool.result`, `agent.end`. So this plugin writes the
- * JSONL the watcher tails, and from there Amp is an ordinary file-backed engine.
+ * The plugin API is the way in. Four events fire (measured in the TUI by registering for sixteen
+ * candidate names on 0.0.1786681855 and logging what arrived, not read off a doc): `session.start`,
+ * `tool.call`, `tool.result`, `agent.end`. So this plugin writes the JSONL the watcher tails, and from
+ * there Amp is an ordinary file-backed engine.
*
- * Two details are load-bearing:
+ * `agent.start` used to be a fifth, and was how a turn opened. It no longer fires, and `agent.end` — the
+ * only event that still carries the prompt — arrives at the END of the turn, far too late to open one.
+ * The prompt is therefore read from the thread instead (see `drain`). The handler for `agent.start` is
+ * kept anyway: it costs nothing on a version that never emits it, and an older Amp still works.
+ *
+ * Three details are load-bearing:
*
* - **Text comes from `ctx.thread.messages()`, not from the events.** No event carries assistant text.
* But the thread handle reads the client's own local state, and at `tool.call` it ALREADY contains
@@ -641,6 +647,8 @@ const AMP_PLUGIN_PATH = join(env.AMP_PLUGIN_DIR, 'launcher-register.ts')
* BEFORE the tool it called, which is the order a transcript has to be in. Nothing is fetched.
* - **Blocks are emitted once, keyed `<messageId>#<index>`.** Each snapshot re-reads the same recent
* messages, so without that key every event would re-emit the whole tail of the conversation.
+ * - **The turn opens from the user's own text block**, not from an event — the only place the prompt
+ * is available while the turn is still running.
*
* Being a SYSTEM plugin it loads in every `amp` the user runs, including ones this adapter knows nothing
* about. The `TMUX_PANE` guard keeps standalone sessions inert; the daemon additionally proves that the
@@ -739,18 +747,51 @@ export default function (amp: any) {
// it, the next prompt replayed the whole recent history as if it had just happened.
const seed = !seeded
seeded = true
+ // The seed pass would swallow the very prompt the turn needs to open on. Measured: \`session.start\`
+ // does NOT fire when Amp launches — it fires on the first submit, and by then the thread already
+ // holds one \`user\` message. So the seed has to tell history from the live prompt, and the test is
+ // whether anything answered it: the LAST user text block with no assistant message after it is
+ // waiting, not past. On a resumed thread the last message is an assistant one, so nothing opens.
+ let liveUserId = ''
+ for (const message of messages) {
+ if (message.role === 'assistant') { liveUserId = ''; continue }
+ const parts = Array.isArray(message.content) ? message.content : []
+ const hasText = parts.some((b: any) => b && b.type === 'text' && typeof b.text === 'string' && b.text)
+ if (hasText) liveUserId = String(message.id)
+ }
for (const message of messages) {
const blocks = Array.isArray(message.content) ? message.content : []
for (let i = 0; i < blocks.length; i++) {
const block = blocks[i]
if (!block) continue
if (block.type === 'text' || block.type === 'thinking') {
- if (message.role !== 'assistant') continue
const key = String(message.id) + '#' + i
if (emitted.has(key)) continue
const text = typeof block.text === 'string' ? block.text : block.thinking
if (typeof text !== 'string' || !text) continue
emitted.add(key)
+ // A user TEXT block opens the turn.
+ //
+ // Amp used to announce that with an \`agent.start\` event, and the handler below wrote
+ // \`turn_start\` from it. That event no longer fires — probed with a plugin that registered for
+ // sixteen candidate names on amp 0.0.1786681855 and saw only \`session.start\`, \`tool.call\`,
+ // \`tool.result\` and \`agent.end\`. The prompt now reaches a plugin no earlier than
+ // \`agent.end\`, which is the END of the turn, far too late to open one.
+ //
+ // So it is taken from the thread instead, where drain was already reading it and dropping it:
+ // measured at the first \`tool.call\` of a turn, \`messages()\` already returns the prompt, oldest
+ // first. Without this the turn opens with an empty question on web and device, and the recap
+ // loses what was asked.
+ //
+ // Only a TEXT block qualifies: a tool_result is also carried on a \`user\` message, so matching
+ // the role alone would open a turn on every tool that returned.
+ if (message.role !== 'assistant') {
+ const turnId = String(message.id)
+ if (turnsStarted.has(turnId)) continue
+ turnsStarted.add(turnId)
+ if (!seed || turnId === liveUserId) line({ t: 'turn_start', id: turnId, message: text, at: Date.now() })
+ continue
+ }
if (!seed) line({ t: block.type, id: message.id, i, text })
} else if (block.type === 'tool_use') {
const id = String(block.id || '')
diff --git a/cli/src/watcher/watcher.spec.ts b/cli/src/watcher/watcher.spec.ts
index f646ec0c8..46b70dfed 100644
--- a/cli/src/watcher/watcher.spec.ts
+++ b/cli/src/watcher/watcher.spec.ts
@@ -68,4 +68,44 @@ describe('Watcher.pollAll', () => {
expect(lines).toEqual(['{"n":1}', '{"n":2}'])
await watcher.stop()
})
+
+ it('emits a file-backed transcript from the start when nothing was folded', async () => {
+ // The generic byte-tail branch, which every JSONL engine uses. `fromStart` was only ever covered for
+ // cursor, and the gap was live: pi's agent is discovered the moment the engine starts but its session
+ // file only materialises once the first answer is written, so the re-attach that finally brought the
+ // path tailed from the file's END and the whole first turn — prompt, tools and answer — was read as
+ // history that never reached web or device.
+ const dir = await mkdtemp(join(tmpdir(), 'machine-first-turn-'))
+ cleanup.push(dir)
+ const transcriptPath = join(dir, 'session.jsonl')
+ await writeFile(transcriptPath, '{"a":1}\n{"a":2}\n{"a":3}\n')
+ const watcher = new Watcher()
+ const lines: string[] = []
+ watcher.on('line', (event: LineEvent) => lines.push(event.text))
+
+ await watcher.addSession({ sessionId: 'p1', engine: 'pi', transcriptPath }, { fromStart: true })
+ await watcher.pollSession('p1')
+
+ expect(lines).toEqual(['{"a":1}', '{"a":2}', '{"a":3}'])
+ await watcher.stop()
+ })
+
+ it('still starts at the end by default, so a resumed session does not replay', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'machine-resume-'))
+ cleanup.push(dir)
+ const transcriptPath = join(dir, 'session.jsonl')
+ await writeFile(transcriptPath, '{"old":1}\n{"old":2}\n')
+ const watcher = new Watcher()
+ const lines: string[] = []
+ watcher.on('line', (event: LineEvent) => lines.push(event.text))
+
+ await watcher.addSession({ sessionId: 'p2', engine: 'pi', transcriptPath })
+ await watcher.pollSession('p2')
+ expect(lines).toEqual([])
+
+ await writeFile(transcriptPath, '{"old":1}\n{"old":2}\n{"new":3}\n')
+ await watcher.pollSession('p2')
+ expect(lines).toEqual(['{"new":3}'])
+ await watcher.stop()
+ })
})