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: ensure turn_started event is emitted when KiloReader attaches to an active turn

0xken1574a34c0a721b
diff --git a/cli/src/engines/kilo/reader.spec.ts b/cli/src/engines/kilo/reader.spec.ts
new file mode 100644
index 000000000..e8e8cc7e2
--- /dev/null
+++ b/cli/src/engines/kilo/reader.spec.ts
@@ -0,0 +1,107 @@
+import { afterEach, describe, expect, it } from 'vitest'
+import { execFileSync } from 'child_process'
+import { mkdtempSync, rmSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+import { KiloReader } from './reader.js'
+import type { LiveEvent } from '../../lib/normalize.js'
+
+/**
+ * A first message through `harness kilo` produced no turn frames and no recap, every time:
+ *
+ * [agent] c5c6227b re-attached · engine=kilo · pane=%10 · session=ses_014f
+ * [turn] ses_014f ended
+ * [recap] DROPPED (no turn_started was ever seen for this session)
+ *
+ * Kilo creates its session only when the FIRST message is submitted, and the discovery plugin fires on
+ * `session.created` — so the daemon ALWAYS attaches with a turn already in flight. A silent hydrate then
+ * left that turn with a close and no open, and the recap was dropped for want of the opening frame.
+ *
+ * These run against a real SQLite file through the same `sqlite3` path the daemon uses, because the bug
+ * lived in what hydrate did with the rows, not in the parsing.
+ */
+
+const dirs: string[] = []
+afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }) })
+
+const SESSION = 'ses_test01'
+
+/** message.data / part.data are JSON TEXT columns, exactly as kilo writes them. */
+function db(rows: Array<{ role: string; parts: Array<Record<string, unknown>> }>): string {
+ const dir = mkdtempSync(join(tmpdir(), 'kilo-reader-'))
+ dirs.push(dir)
+ const path = join(dir, 'kilo.db')
+ const sql: string[] = [
+ 'CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT, time_created INTEGER, data TEXT);',
+ 'CREATE TABLE part (id TEXT PRIMARY KEY, message_id TEXT, session_id TEXT, time_created INTEGER, data TEXT);',
+ ]
+ const q = (v: unknown): string => `'${JSON.stringify(v).replace(/'/g, "''")}'`
+ rows.forEach((row, m) => {
+ sql.push(`INSERT INTO message VALUES ('msg_${m}','${SESSION}',${1000 + m},${q({ role: row.role })});`)
+ row.parts.forEach((part, p) => {
+ sql.push(`INSERT INTO part VALUES ('prt_${m}_${p}','msg_${m}','${SESSION}',${1000 + m * 10 + p},${q(part)});`)
+ })
+ })
+ execFileSync('sqlite3', [path, sql.join('\n')])
+ return path
+}
+
+async function attach(dbPath: string): Promise<LiveEvent[]> {
+ const seen: LiveEvent[] = []
+ // A very long poll interval: these assertions are about what ATTACHING emits, not about polling.
+ const reader = new KiloReader({ dbPath, sessionId: SESSION, onEvents: (e) => seen.push(...e), pollMs: 600_000 })
+ await reader.start()
+ reader.stop()
+ return seen
+}
+
+const userMsg = (text: string) => ({ role: 'user', parts: [{ type: 'text', text }] })
+const working = { role: 'assistant', parts: [{ type: 'step-start' }, { type: 'text', text: 'thinking…' }] }
+const finished = {
+ role: 'assistant',
+ parts: [{ type: 'text', text: 'done' }, { type: 'step-finish', reason: 'stop' }],
+}
+
+describe('KiloReader attaching mid-turn', () => {
+ /**
+ * The shape that broke a first message. The plugin posts the moment the user row lands, which is
+ * BEFORE kilo has written any assistant row — so the old check ("is the tail an unfinished
+ * assistant") said no turn was open, and the user id was already in `seenUser`, meaning the poll
+ * could never emit the opening frame for it either. Two ways to lose the same turn.
+ */
+ it('opens the turn when only the user row exists yet', async () => {
+ const events = await attach(db([userMsg('gia eth di')]))
+
+ expect(events).toEqual([{ type: 'turn_started', payload: { userMessage: 'gia eth di' } }])
+ })
+
+ it('opens the turn when the assistant is already working', async () => {
+ const events = await attach(db([userMsg('price eth now'), working]))
+
+ expect(events).toEqual([{ type: 'turn_started', payload: { userMessage: 'price eth now' } }])
+ })
+
+ /** Re-attaching to an idle session must stay silent, or every daemon restart invents a turn. */
+ it('says nothing when the last turn already finished', async () => {
+ expect(await attach(db([userMsg('hi'), finished]))).toEqual([])
+ })
+
+ it('says nothing for a session with no rows at all', async () => {
+ expect(await attach(db([]))).toEqual([])
+ })
+
+ /**
+ * The backstop must not double-fire. Every user row present at attach is seeded into `seenUser`, so
+ * the first poll that re-reads the same rows has nothing new to open.
+ */
+ it('does not open the same turn twice when the poll re-reads it', async () => {
+ const path = db([userMsg('once'), working])
+ const seen: LiveEvent[] = []
+ const reader = new KiloReader({ dbPath: path, sessionId: SESSION, onEvents: (e) => seen.push(...e), pollMs: 10 })
+ await reader.start()
+ await new Promise((r) => setTimeout(r, 120))
+ reader.stop()
+
+ expect(seen.filter((e) => e.type === 'turn_started')).toHaveLength(1)
+ })
+})
diff --git a/cli/src/engines/kilo/reader.ts b/cli/src/engines/kilo/reader.ts
index c61771678..11cbbe9ec 100644
--- a/cli/src/engines/kilo/reader.ts
+++ b/cli/src/engines/kilo/reader.ts
@@ -144,7 +144,8 @@ export class KiloReader {
async start(): Promise<void> {
try {
const all = await readKiloMessages(this.deps.dbPath, this.deps.sessionId, null)
- this.hydrate(all)
+ const opening = this.hydrate(all)
+ if (opening.length) this.deps.onEvents(opening)
} catch (err) {
if (err instanceof KiloSqliteMissing) { this.deps.onFatal?.(err); return }
}
@@ -155,9 +156,35 @@ export class KiloReader {
if (this.timer) { clearInterval(this.timer); this.timer = null }
}
- /** Seed state from existing rows without emitting, so we only stream NEW activity after attach. */
- private hydrate(messages: KiloMessage[]): void {
- if (messages.length === 0) return
+ /**
+ * Seed state from existing rows without replaying them, so we only stream NEW activity after attach —
+ * and return the one event that MUST still be emitted: a `turn_started` when we attached mid-turn.
+ *
+ * Kilo only creates its session when the FIRST message is submitted, and the discovery plugin fires on
+ * `session.created`. So on a brand-new agent the daemon always attaches with a turn already running,
+ * and a silent hydrate left that turn with no opening frame. Measured on a real pane:
+ *
+ * [agent] c5c6227b re-attached · engine=kilo · pane=%10 · session=ses_014f
+ * [turn] ses_014f ended ← close with nothing to close
+ * [recap] DROPPED (no turn_started was ever seen for this session)
+ *
+ * Two distinct shapes reach here mid-turn and BOTH were broken, which is why the check is not simply
+ * "is the tail an unfinished assistant":
+ *
+ * - tail is an in-flight assistant → `open` was set to true, but silently, so `everOpened` on the
+ * daemon side never flipped and the close was dropped;
+ * - tail is the USER row, with no assistant row written yet → `open` stayed false AND the user id
+ * went into `seenUser`, so `processMessage` could never emit the opening frame for it either.
+ * This is the common one for a first message, because the plugin fires the moment the row lands.
+ *
+ * Emitting the frame here costs nothing on a re-attach to an idle session (the tail is a finished
+ * assistant, so nothing is emitted) and cannot double-fire: every existing user id is in `seenUser`
+ * before the poll loop starts. The content that predates the attach stays unreplayed on purpose —
+ * re-emitting it would duplicate the transcript after a daemon restart, and the recap does not need
+ * it, because the recap reads kilo's own store (`source=session-json`) rather than the stream.
+ */
+ private hydrate(messages: KiloMessage[]): LiveEvent[] {
+ if (messages.length === 0) return []
// Find the last closed boundary; everything up to it is "already seen".
let boundary = -1
for (let i = messages.length - 1; i >= 0; i--) { if (isDone(messages[i])) { boundary = i; break } }
@@ -167,9 +194,18 @@ export class KiloReader {
if (msg.role === 'user') this.seenUser.add(msg.id)
for (const part of msg.parts) this.seedPart(part)
}
- // A trailing in-flight assistant means a turn is open (attached mid-turn).
+ // Attached mid-turn: either the assistant is still working, or the user row landed and the assistant
+ // has not started yet. See the note above for why both count.
const tail = messages[messages.length - 1]
- this.open = tail.role === 'assistant' && !isDone(tail)
+ this.open = tail.role === 'user' || (tail.role === 'assistant' && !isDone(tail))
+ if (!this.open) return []
+ let userMessage = ''
+ for (let i = messages.length - 1; i >= 0; i--) {
+ if (messages[i].role !== 'user') continue
+ userMessage = userMessageText(messages[i])
+ break
+ }
+ return [{ type: 'turn_started', payload: { userMessage } }]
}
private seedPart(part: KiloPart): void {