// A daemon E2E cannot see client-only grouping or whether the web client hydrates // referenced history, or when live output yields to history its reads have not // returned yet. Compile the real Svelte state, stubbing only its transports: // shell outcomes must survive reload and stay outside the preceding model turn. import assert from 'node:assert/strict'; import { readFile } from 'node:fs/promises'; import { stripTypeScriptTypes } from 'node:module'; import test from 'node:test'; import { compileModule } from 'svelte/compiler'; const moduleURL = (code) => `data:text/javascript;base64,${Buffer.from(code).toString('base64')}`; const apiURL = moduleURL(` export let page, fields, reads, batches = 0, shells = new Map(), shellReads = [], continues = [], nextId = 0, history, inputs = [], inputError = null; export function reset(items, content = {}) { page = { items, older: null }; fields = content; reads = []; batches = 0; shells = new Map(); shellReads = []; continues = []; nextId = 0; history = null; inputs = []; inputError = null; } export function failInput(error) { inputError = error; } export function answerHistory(read) { history = read; } export async function getShellCommand(session, id, signal) { shellReads.push({ id, signal }); if (!shells.has(id)) throw new Error("missing test receipt"); return shells.get(id); } export async function readHistory(session, at) { return history ? history(at) : page; } export async function readEntryContent(url) { reads.push(url); return fields[url]; } export async function readContentBatch(session, ids) { batches++; const found = new Map(); for (const id of ids) { const url = '/sessions/' + session + '/history/' + id; reads.push(url); if (fields[url]) found.set(id, fields[url]); } return found; } export async function readRequests() { return { items: [], next: null }; } export async function readQueue() { return { items: [], total: 0, limit: 1000 }; } export async function sendContinue(session, id) { continues.push({ session, id }); } export async function sendMessage(session, id, text, images, files) { inputs.push({ session, id, text, images, files }); if (inputError) throw inputError; } export function uuidv7() { return 'input-' + (++nextId); } export const held = [], released = [], edits = [], drops = []; export let holdError = null, editError = null, dropError = null; export async function holdInput(session, id) { held.push(id); if (holdError) throw holdError; return { lease_ms: 30000 }; } export async function releaseInput(session, id) { released.push(id); } export async function editInput(session, id, text, images, files) { edits.push({ id, text, images, files }); if (editError) throw editError; return { input: {} }; } export async function dropQueued(session, id) { drops.push(id); if (dropError) throw dropError; return { items: [], total: 0, limit: 1000, page: null }; } export function failEdits(hold, edit, drop) { holdError = hold; editError = edit; dropError = drop; } `); const draftsURL = moduleURL(` export const drafts = new Map(); export function draftOf(session) { let draft = drafts.get(session); if (!draft) { draft = { text: '', notice: '', images: new Map(), files: new Map(), next: 0, loads: [], restores: [], focus: null, focusRequested: false, snapshot() { return { text: this.text, images: new Map(this.images), files: new Map(this.files), next: this.next }; }, load(snapshot) { this.loads.push(snapshot); this.text = snapshot.text; this.images = new Map(snapshot.images); this.files = new Map(snapshot.files); this.next = snapshot.next; }, restore(sends) { this.restores.push(sends); this.text = [this.text, ...sends.map((send) => send.text)].filter(Boolean).join('\\n\\n'); }, }; drafts.set(session, draft); } return draft; } `); const attachmentsURL = moduleURL(` export function resolve(text, images) { return { text, images: [...images.values()] }; } `); const queueEditURL = moduleURL( stripTypeScriptTypes( await readFile(new URL('../src/lib/queueEdit.ts', import.meta.url), 'utf8'), ), ); const api = await import(apiURL); const streamURL = moduleURL(` let receiver; export function follow(session, onBatch) { receiver = onBatch; return () => { receiver = null; }; } export function emit(batch) { receiver?.(batch); } `); const stream = await import(streamURL); const moodsURL = moduleURL( stripTypeScriptTypes( await readFile(new URL('../src/lib/moods.ts', import.meta.url), 'utf8'), ), ); const burstURL = moduleURL( stripTypeScriptTypes( await readFile(new URL('../src/lib/burst.ts', import.meta.url), 'utf8'), ), ); const imports = new Map([ ['./api', apiURL], ['./stream', streamURL], ['./moods', moodsURL], ['./burst', burstURL], ['./chat/drafts', draftsURL], ['./chat/attachments', attachmentsURL], ['./queueEdit', queueEditURL], ]); const source = await readFile( new URL('../src/lib/transcript.svelte.ts', import.meta.url), 'utf8', ); let code = compileModule(stripTypeScriptTypes(source, { mode: 'transform' }), { filename: 'transcript.svelte.js', generate: 'client', }).js.code; code = code.replace( /from (['"])(.*?)\1/g, (_, _quote, path) => `from ${JSON.stringify(imports.get(path) ?? import.meta.resolve(path))}`, ); const { Transcript, displayedIn } = await import(moduleURL(code)); const { summarize } = await import(burstURL); const displaySource = await readFile( new URL('../src/lib/display.ts', import.meta.url), 'utf8', ); let displayCode = stripTypeScriptTypes(displaySource, { mode: 'transform' }); displayCode = displayCode.replace( /from (['"])(.*?)\1/g, (_, _quote, path) => `from ${JSON.stringify(imports.get(path) ?? import.meta.resolve(path))}`, ); const { parseDisplay } = await import(moduleURL(displayCode)); function entry(kind, position, seconds, turn = 'model-one', content = []) { return { id: `entry-${position}`, kind, position, turn_id: turn, created_at: new Date(seconds * 1000).toISOString(), content, content_complete: true, }; } function message(kind, position, seconds, text, turn = 'model-one') { return entry(kind, position, seconds, turn, [{ kind: 'text', text }]); } function shell(position, seconds, id = `shell-${position}`) { return entry('shell_command', position, seconds, null, [ { kind: 'json', field: 'shell_command', value: { id, command: 'echo hello', status: 'completed', exit_code: 0, output: 'hello\n', output_bytes: 6, truncated: false, error: null, history_seq: position, }, }, ]); } const conversation = () => [ message('user', 1, 1, 'hello'), message('assistant', 2, 2, 'ready'), ]; test('retry keeps file bytes and input identity; cancellation hands both attachment kinds back to the draft', async () => { api.reset([]); api.failInput(new Error('offline')); const transcript = new Transcript('session'); const image = { mime_type: 'image/png', data: 'AA==', preview: 'data:image/png;base64,AA==', }; const file = { name: 'binary.dat', data: 'AP8=', size: 2 }; const text = 'inspect [Image #1], as in [File #1: example.txt]'; await transcript.send(text, [image], [file]); assert.match(transcript.pending[0].error, /offline/); const pending = transcript.blocks.find((block) => block.kind === 'user'); assert.equal(pending.text, text, 'typed words are shown as typed'); assert.deepEqual( pending.files.map(({ name, size }) => ({ name, size })), [{ name: 'binary.dat', size: 2 }], ); assert.equal(pending.images.length, 1); const id = transcript.pending[0].id; api.failInput(null); await transcript.retry(id); assert.deepEqual(api.inputs[0], api.inputs[1]); assert.deepEqual(api.inputs[1], { session: 'session', id, text, images: [{ mime_type: 'image/png', data: 'AA==' }], files: [{ name: 'binary.dat', data: 'AP8=' }], }); assert.deepEqual( transcript .take([id]) .map(({ text, images, files }) => ({ text, images, files })), [{ text, images: [image], files: [file] }], ); assert.equal(transcript.pending.length, 0); }); test('history shows file cards only from entry metadata and keeps label-like words', async () => { const literal = message('user', 1, 1, 'Explain [File #1: example.txt]'); const attached = { ...message('user', 2, 2, 'inspect [Image #1]'), files: [{ name: 'report.pdf', size: 12 }], }; attached.content.push({ kind: 'image', image: { reference: { url: '/image-one' } }, }); api.reset([literal, attached]); const transcript = new Transcript('session'); await transcript.load(); const [first, second] = transcript.blocks.filter( (block) => block.kind === 'user', ); assert.equal(first.text, 'Explain [File #1: example.txt]'); assert.deepEqual(first.files, []); assert.equal(second.text, 'inspect [Image #1]'); assert.deepEqual(second.files, [{ name: 'report.pdf', size: 12 }]); assert.deepEqual(second.images, [ { src: '/api/image-one', width: undefined, height: undefined }, ]); }); test('a dot with generic files is a message, while a bare dot still continues', async () => { api.reset([]); const transcript = new Transcript('session'); const file = { name: 'LICENSE', data: '', size: 0 }; await transcript.send('.', [], [file]); assert.equal(api.inputs.length, 1); assert.deepEqual(api.inputs[0].files, [{ name: 'LICENSE', data: '' }]); assert.equal(api.continues.length, 0); await transcript.send('.'); assert.equal(api.continues.length, 1); }); test('idle shell commands follow one model sign-off without extending its duration', () => { const transcript = new Transcript('session'); transcript.entries = [ ...conversation(), shell(3, 120), shell(4, 180), message('user', 5, 240, 'next', 'model-two'), message('assistant', 6, 241, 'again', 'model-two'), ]; assert.deepEqual( transcript.blocks.map((b) => b.kind), ['user', 'assistant', 'end', 'shell', 'shell', 'user', 'assistant', 'end'], ); const ends = transcript.blocks.filter((b) => b.kind === 'end'); assert.deepEqual( ends.map((b) => b.elapsedMs), [1000, 1000], ); assert.equal(ends[0].text, 'ready'); }); test('collapsed traces fold prose once work follows it, and keep the newest prose out while it streams', () => { const transcript = new Transcript('session', () => true); const steps = [ message('user', 1, 1, 'hello'), message('assistant', 2, 2, 'looking'), message('thinking', 3, 3, 'hmm'), message('assistant', 4, 4, 'done'), ]; transcript.entries = steps; transcript.running = true; assert.deepEqual( transcript.groups.map((g) => g.kind), ['user', 'work', 'assistant'], ); assert.deepEqual( transcript.groups[1].steps.map((s) => s.text), ['looking', 'hmm'], ); transcript.entries = [...steps, message('thinking', 5, 5, 'more')]; assert.deepEqual( transcript.groups.map((g) => g.kind), ['user', 'work'], ); assert.deepEqual( transcript.groups[1].steps.map((s) => s.text), ['looking', 'hmm', 'done', 'more'], ); transcript.entries = steps; transcript.running = false; assert.deepEqual( transcript.groups.map((g) => g.kind), ['user', 'work', 'assistant', 'end'], ); assert.equal(transcript.groups[2].text, 'done'); }); test('collapsed traces follow the daemon labels over position', () => { const transcript = new Transcript('session', () => true); const labelled = (position, text, phase) => ({ ...message('assistant', position, position, text), phase, }); transcript.entries = [ message('user', 1, 1, 'hello'), labelled(2, 'early answer', 'final'), message('thinking', 3, 3, 'hmm'), labelled(4, 'one more look', 'commentary'), ]; assert.deepEqual( transcript.groups.map((g) => g.kind), ['user', 'assistant', 'work', 'end'], ); assert.equal(transcript.groups[1].text, 'early answer'); assert.deepEqual( transcript.groups[2].steps.map((s) => s.text), ['hmm', 'one more look'], ); }); test('a turn signs off below its answer once the live text commits', () => { const transcript = new Transcript('session'); const ran = { ...entry('tool_result', 2, 3), tool: { tool_call_id: 'call', name: 'python' }, }; transcript.entries = [message('user', 1, 1, 'hello'), ran]; transcript.live = [{ id: 'm', kind: 'text', text: 'the answer' }]; assert.deepEqual( transcript.blocks.map((b) => b.kind), ['user', 'tool', 'assistant'], ); transcript.entries = [ ...transcript.entries, message('assistant', 3, 5, 'the answer'), ]; transcript.live = []; assert.deepEqual( transcript.blocks.map((b) => b.kind), ['user', 'tool', 'assistant', 'end'], ); assert.equal(transcript.blocks.at(-1).elapsedMs, 4000); }); test('a concurrent transient shell does not sign off an active model turn', () => { const transcript = new Transcript('session'); transcript.entries = conversation(); transcript.running = true; transcript.trackShell(shell(3, 120).content[0].value); assert.deepEqual( transcript.blocks.map((b) => b.kind), ['user', 'assistant', 'shell'], ); transcript.running = false; assert.deepEqual( transcript.blocks.map((b) => b.kind), ['user', 'assistant', 'end', 'shell'], ); }); test('referenced shell receipts hydrate on load without fetching unrelated tool output', async () => { const receipt = shell(3, 120); receipt.content[0].value.output = 'x'.repeat(64 * 1024); receipt.content[0].value.output_bytes = 128 * 1024; const url = '/sessions/session/history/3'; const toolURL = '/sessions/session/history/4'; const referenced = { ...receipt, content_complete: false, content: [ { kind: 'reference', reference: { url, field: 'shell_command', bytes: 65000 }, }, ], }; const tool = { ...entry('tool_result', 4, 121, null), content_complete: false, content: [ { kind: 'reference', reference: { url: toolURL, field: 'result', bytes: 1000000 }, }, ], }; api.reset([...conversation(), referenced, tool], { [url]: { shell_command: JSON.stringify(receipt.content[0].value) }, }); const transcript = new Transcript('session'); await transcript.load(); assert.equal(transcript.error, null); assert.deepEqual(api.reads, [url]); assert.equal( transcript.blocks.find((b) => b.kind === 'shell')?.command.command, 'echo hello', ); assert.equal( transcript.entries.find((e) => e.id === receipt.id).content_complete, true, ); }); test("a page's referenced messages load in one batch read", async () => { const long = (position) => ({ ...message('assistant', position, position, ''), content_complete: false, content: [ { kind: 'reference', reference: { url: `/sessions/session/history/${position}`, field: 'text', bytes: 70000, }, }, ], }); api.reset([message('user', 1, 1, 'hello'), long(2), long(3)], { '/sessions/session/history/2': { text: 'first' }, '/sessions/session/history/3': { text: 'second' }, }); const transcript = new Transcript('session'); await transcript.load(); assert.equal(api.batches, 1); assert.deepEqual( transcript.blocks.filter((b) => b.kind === 'assistant').map((b) => b.text), ['first', 'second'], ); }); test('rows that did not change keep their objects when a page arrives or text streams in', () => { const transcript = new Transcript('session'); transcript.entries = conversation(); transcript.running = true; const before = transcript.groups; // Equal entries as new objects, as a poll or an expansion hands over. transcript.entries = [ ...conversation(), message('user', 3, 3, 'more', 'model-two'), ]; transcript.live = [{ id: 'live-1', kind: 'text', text: 'stream' }]; const after = transcript.groups; assert.deepEqual( after.map((group) => group.kind), ['user', 'assistant', 'end', 'user', 'assistant'], ); before.forEach((group, index) => assert.equal(after[index], group)); }); test('a mid-turn committed receipt does not split the turn or duplicate its sign-off', () => { const transcript = new Transcript('session'); const receipt = { ...shell(3, 4), turn_id: 'model-one' }; transcript.entries = [ ...conversation(), receipt, message('assistant', 4, 9, 'used the shell result'), ]; assert.deepEqual( transcript.blocks.map((b) => b.kind), ['user', 'assistant', 'shell', 'assistant', 'end'], ); const [end] = transcript.blocks.filter((b) => b.kind === 'end'); assert.equal(end.elapsedMs, 8000); assert.equal(end.text, 'used the shell result'); }); test('delivery events overlay stale history without losing preview or accepting a late admission downgrade', () => { const transcript = new Transcript('session'); const receipt = shell(3, 4); const command = { ...receipt.content[0].value, delivery: 'pending', output: 'a richer history preview\n', }; receipt.content[0].value = command; transcript.entries = [...conversation(), receipt]; transcript.attach(); try { assert.equal( transcript.blocks.find((b) => b.kind === 'shell').command.delivery, 'pending', ); stream.emit({ events: [ { type: 'shell_command', data: { shell_command: { ...command, delivery: 'delivered', output: 'a' }, }, }, ], }); transcript.trackShell({ ...command, status: 'running', exit_code: null, history_seq: null, delivery: 'pending', output: '', }); const blocks = transcript.blocks.filter((b) => b.kind === 'shell'); assert.equal(blocks.length, 1); assert.equal(blocks[0].command.delivery, 'delivered'); assert.equal(blocks[0].command.status, 'completed'); assert.equal(blocks[0].command.output, command.output); assert.equal(blocks[0].command.history_seq, 3); } finally { transcript.detach(); } }); test('reset refreshes an older pending history receipt whose ACK was missed offline', async () => { const receipt = shell(3, 4); receipt.content[0].value.delivery = 'pending'; api.reset([receipt]); api.shells.set('shell-3', { ...receipt.content[0].value, delivery: 'delivered', }); const transcript = new Transcript('session'); transcript.entries = [receipt]; transcript.attach(); try { stream.emit({ events: [{ type: 'reset', data: {} }], snapshot: { shell_commands: [] }, }); await new Promise((resolve) => setImmediate(resolve)); assert.equal(transcript.blocks[0].command.delivery, 'delivered'); assert.equal( transcript.blocks[0].command.output, receipt.content[0].value.output, ); assert.deepEqual( api.shellReads.map((read) => read.id), ['shell-3'], ); } finally { transcript.detach(); } }); test('initial hydration finishing after reset still refreshes a pending receipt', async () => { const receipt = shell(3, 4); receipt.content[0].value.delivery = 'pending'; api.reset([receipt]); api.shells.set('shell-3', { ...receipt.content[0].value, delivery: 'delivered', }); const transcript = new Transcript('session'); const loading = transcript.load(); transcript.attach(); try { stream.emit({ events: [{ type: 'reset', data: {} }], snapshot: { shell_commands: [] }, }); await loading; await new Promise((resolve) => setImmediate(resolve)); assert.equal(transcript.blocks[0].command.delivery, 'delivered'); assert.deepEqual( api.shellReads.map((read) => read.id), ['shell-3'], ); } finally { transcript.detach(); } }); test('reset restores delivery over older canonical metadata and legacy rows stay unknown', () => { const transcript = new Transcript('session'); const receipt = shell(3, 4); transcript.entries = [receipt]; assert.equal(transcript.blocks[0].command.delivery, 'unknown'); transcript.attach(); try { for (const delivery of ['pending', 'delivered']) { stream.emit({ events: [{ type: 'reset', data: {} }], snapshot: { shell_commands: [{ ...receipt.content[0].value, delivery }], }, }); assert.equal(transcript.blocks[0].command.delivery, delivery); assert.equal( transcript.blocks.filter((b) => b.kind === 'shell').length, 1, ); } } finally { transcript.detach(); } }); test('sending a lone dot submits a continue input without adding a user bubble or restoring on cancel', async () => { api.reset([]); const transcript = new Transcript('session'); transcript.entries = conversation(); await transcript.send('.'); assert.deepEqual(api.continues, [{ session: 'session', id: 'input-1' }]); assert.deepEqual( transcript.blocks.map((b) => b.kind), ['user', 'assistant', 'end'], ); assert.deepEqual(transcript.take(['input-1']), []); assert.equal(transcript.pending.length, 0); }); /** History reads that answer only when the test says so, in the order they were asked. */ function heldReads() { const asked = []; api.answerHistory( (at) => new Promise((resolve, reject) => asked.push({ at, resolve, reject })), ); return asked; } const settle = () => new Promise((resolve) => setTimeout(resolve, 80)); const liveIds = (transcript) => transcript.live.map((item) => item.id); test('a reply committed while an earlier read is in flight stays live until a later read brings its entry', async () => { api.reset([]); const asked = heldReads(); const transcript = new Transcript('session'); transcript.entries = conversation(); transcript.attach(); try { stream.emit({ events: [ { type: 'text', data: { message_id: 'm1', text: 'first' } }, { type: 'committed', data: { replaces_live_ids: ['m1'] } }, ], }); await settle(); assert.equal(asked.length, 1); stream.emit({ events: [ { type: 'text', data: { message_id: 'm2', text: 'second' } }, { type: 'committed', data: { replaces_live_ids: ['m2'] } }, ], }); await settle(); assert.deepEqual(liveIds(transcript), ['m1', 'm2']); // The first read went out before m2 committed, so its answer lacks m2. asked[0].resolve({ items: [message('assistant', 3, 3, 'first')], newer: null, }); await settle(); assert.deepEqual(liveIds(transcript), ['m2']); assert.equal( asked.length, 2, 'the shared poll reads again for the commit that came during it', ); assert.deepEqual(asked[1].at, { after: 3 }); asked[1].resolve({ items: [message('assistant', 4, 4, 'second')], newer: null, }); await settle(); assert.deepEqual(liveIds(transcript), []); assert.deepEqual( transcript.entries.map((e) => e.position), [1, 2, 3, 4], ); } finally { transcript.detach(); } }); test('a failed history read keeps the committed reply live, even once the session rests', async () => { api.reset([]); const asked = heldReads(); const transcript = new Transcript('session'); transcript.entries = conversation(); transcript.attach(); try { stream.emit({ events: [ { type: 'tool_progress', data: { progress: { call_id: 'pending-tool', name: 'python' } }, }, { type: 'text', data: { message_id: 'm1', text: 'answer' } }, { type: 'committed', data: { replaces_all_live: true } }, { type: 'status', data: { phase: 'idle' } }, ], }); await settle(); asked[0].reject(new Error('daemon unreachable')); await settle(); assert.deepEqual(liveIds(transcript), ['m1']); assert.deepEqual(transcript.progress, []); // The next poll that succeeds is what retires it. const poll = transcript.poll(); await settle(); asked[1].resolve({ items: [message('assistant', 3, 3, 'answer')], newer: null, }); await poll; assert.deepEqual(liveIds(transcript), []); assert.deepEqual(transcript.progress, []); } finally { transcript.detach(); } }); test('display activities surface on live poll, summarize in bursts, and parse markdown, code, and diff modes', async () => { const trace = { activities: [ { kind: 'display', target: 'design notes', detail: '**design notes**\nsummary\n\n### Architecture\n- item', }, { kind: 'display', target: 'main.go', detail: '**main.go**\n\npackage main\nfunc main() {}', }, { kind: 'display', target: 'patch', detail: '**patch**\nupdated exports\n\n--- a/src/app.ts\n+++ b/src/app.ts\n@@ -1 +1 @@\n-const x = 1;\n+const x = 2;', }, ], changes: [], truncated: false, }; assert.equal( summarize([{ kind: 'tool', name: 'python', trace }], '').text, 'displayed “design notes”, “main.go”, “patch”', ); assert.deepEqual( displayedIn('entry-2', trace).map((item) => [ item.entryId, item.index, item.title, ]), [ ['entry-2', 0, 'design notes'], ['entry-2', 1, 'main.go'], ['entry-2', 2, 'patch'], ], ); assert.deepEqual(parseDisplay('design notes', trace.activities[0].detail), { header: 'summary', body: '### Architecture\n- item', natural: 'markdown', fileName: 'design notes', files: [], }); assert.deepEqual(parseDisplay('main.go', trace.activities[1].detail), { header: '', body: 'package main\nfunc main() {}', natural: 'code', fileName: 'main.go', files: [], }); assert.deepEqual(parseDisplay('patch', trace.activities[2].detail), { header: 'updated exports', body: '--- a/src/app.ts\n+++ b/src/app.ts\n@@ -1 +1 @@\n-const x = 1;\n+const x = 2;', natural: 'diff', fileName: 'src/app.ts', files: [ { path: 'src/app.ts', diff: '--- a/src/app.ts\n+++ b/src/app.ts\n@@ -1 +1 @@\n-const x = 1;\n+const x = 2;', added: 1, removed: 1, }, ], }); const tool = { ...entry('tool_result', 3, 3, 'model-one', [ { kind: 'reference', reference: { url: '/sessions/session/history/3', field: 'trace', bytes: 500, }, }, ]), content_complete: false, tool: { tool_call_id: 'call-1', name: 'python' }, }; api.reset(conversation(), { '/sessions/session/history/3': { trace: JSON.stringify(trace) }, }); const transcript = new Transcript('session'); await transcript.load(); assert.deepEqual(transcript.displayed, []); api.answerHistory(() => Promise.resolve({ items: [tool], newer: null })); await transcript.poll(); assert.equal(transcript.displayed.length, 3); assert.equal(transcript.displayed[0].title, 'design notes'); }); const { draftOf } = await import(draftsURL); const queued = (id) => ({ items: [{ id, text: '' }], total: 1, limit: 1000, page: null, }); async function queuedSend(text) { const transcript = new Transcript('session'); await transcript.load(); await transcript.send(text); const [{ id }] = transcript.pending; transcript.applyQueue(queued(id)); const draft = draftOf('session'); Object.assign(draft, { text: '', notice: '' }); return { transcript, id, draft }; } test('editing a queued message holds it, loads it, and saves it in place', async () => { api.reset([]); api.failEdits(null, null, null); const { transcript, id, draft } = await queuedSend('fix the parser'); draft.text = 'half typed'; await transcript.beginEdit(id); assert.deepEqual(api.held, [id]); assert.equal(transcript.editing.id, id); assert.equal(draft.text, 'fix the parser'); await transcript.saveEdit('fix the lexer', [], []); assert.deepEqual(api.edits.at(-1), { id, text: 'fix the lexer', images: [], files: [], }); assert.equal(transcript.editing, null); assert.equal(draft.text, 'half typed', 'the stashed draft comes back'); assert.equal(transcript.pending[0].text, 'fix the lexer'); }); test('submitting an empty edit cancels the queued message', async () => { api.reset([]); api.failEdits(null, null, null); const { transcript, id, draft } = await queuedSend('drop me'); await transcript.beginEdit(id); await transcript.saveEdit('', [], []); assert.deepEqual(api.drops, [id]); assert.equal(transcript.pending.length, 0); assert.equal(transcript.editing, null); assert.equal(draft.text, ''); }); test('a hold the agent already refused changes nothing and says so', async () => { api.reset([]); api.failEdits( Object.assign(new Error('read'), { code: 'input_not_waiting' }), null, null, ); const { transcript, id, draft } = await queuedSend('too late'); await transcript.beginEdit(id); assert.equal(transcript.editing, null); assert.equal(draft.text, ''); assert.match(draft.notice, /already read/); }); test('an edit refused as already read keeps what was typed as a draft', async () => { api.reset([]); api.failEdits( null, Object.assign(new Error('read'), { code: 'input_not_waiting' }), null, ); const { transcript, id, draft } = await queuedSend('original'); await transcript.beginEdit(id); await transcript.saveEdit('my correction', [], []); assert.equal(transcript.editing, null); assert.match(draft.text, /my correction/); assert.match(draft.notice, /already read/); }); test('user blocks keep mail sender metadata and do not carry user read receipts', async () => { api.reset([ { ...message('user', 1, 1, 'hello', 't1'), turn_type: 'user', }, message('assistant', 2, 2, 'on it', 't1'), { ...message('user', 3, 3, 'finished the check', 't2'), turn_type: 'agent', mail: { mail_id: 'mail-1', sender_session_id: 'child-1', sender_label: 'Scout', kind: 'result', }, }, ]); const transcript = new Transcript('session'); await transcript.load(); const [human, agent] = transcript.blocks.filter((b) => b.kind === 'user'); assert.equal(human.from, null); assert.equal(human.mail, null); assert.equal(human.turnType, 'user'); assert.equal(agent.from, 'scout'); assert.deepEqual(agent.mail, { senderId: 'child-1', kind: 'result' }); assert.equal(agent.turnType, 'agent'); assert.equal(transcript.receipt, null); });