Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222// 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 = [], uploads = [], 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 = []; uploads = []; 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 async function uploadMedia(session, id, bytes, mime) { uploads.push({ session, id, mime, bytes: [...new Uint8Array(await bytes.arrayBuffer())] }); } export function uuidv7() { return 'input-' + (++nextId); } export const held = [], released = [], edits = [], drops = []; let holdAnswer, editAnswer, dropError; export async function holdInput(session, id) { held.push({ session, id }); return holdAnswer ? holdAnswer() : { lease_ms: 30000 }; } export async function releaseInput(session, id) { released.push({ session, id }); } export async function editInput(session, id, text, images, files) { edits.push({ session, id, text, images, files }); if (editAnswer) await editAnswer(); return { input: {} }; } export async function dropQueued(session, id) { drops.push({ session, id }); if (dropError) throw dropError; return { items: [], total: 0, limit: 1000, page: null }; } export function failEdits(hold, edit, drop) { held.length = released.length = edits.length = drops.length = 0; holdAnswer = hold && (() => { throw hold; }); editAnswer = edit && (() => { throw edit; }); dropError = drop; } export function answerEdits(hold, edit) { holdAnswer = hold; editAnswer = edit; }`);const attachmentsURL = moduleURL( stripTypeScriptTypes( await readFile( new URL('../src/lib/chat/attachments.ts', import.meta.url), 'utf8', ), ),);const draftsURL = moduleURL( stripTypeScriptTypes( await readFile( new URL('../src/lib/chat/drafts.ts', import.meta.url), 'utf8', ), { mode: 'transform' }, ) .replace( "'svelte/reactivity'", JSON.stringify(import.meta.resolve('svelte/reactivity')), ) .replace("'./attachments'", JSON.stringify(attachmentsURL)),);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, thumbnailSource } = 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, upload 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]); const [{ upload }] = api.inputs[1].images; assert.deepEqual(api.inputs[1], { session: 'session', id, text, images: [{ upload }], files: [{ name: 'binary.dat', data: 'AP8=' }], }); const sent = { session: 'session', id: upload, mime: 'image/png', bytes: [0], }; assert.deepEqual(api.uploads, [sent, sent]); 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: { mime_type: 'image/png', 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, mime: 'image/png', }, ]);});
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({ kind: 'reset', events: [], 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({ kind: 'reset', events: [], 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({ kind: 'reset', events: [], 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: { high_water: 3, 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: { high_water: 4, 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, session = 'session') { 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, [{ session: 'session', id }]); assert.equal(transcript.editing.id, id); assert.equal(transcript.editing.draft.text, 'fix the parser'); assert.equal(draft.text, 'half typed'); await transcript.saveEdit('fix the lexer', [], []); assert.deepEqual(api.edits.at(-1), { session: 'session', 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, [{ session: 'session', 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, /no longer waiting/);});
test('a pending hold admits only one edit and releases a late hold after detach', async () => { api.reset([]); api.failEdits(null, null, null); const original = await queuedSend('original', 'source'); const other = await queuedSend('unrelated', 'destination'); const hold = Promise.withResolvers(); api.answerEdits(() => hold.promise, null); const opening = original.transcript.beginEdit(original.id); void original.transcript.beginEdit(original.id); original.draft.text = 'typed while waiting'; other.draft.text = 'other session'; original.transcript.detach(); hold.resolve({ lease_ms: 30000 }); await opening; assert.deepEqual(api.held, [{ session: 'source', id: original.id }]); assert.deepEqual(api.released, [{ session: 'source', id: original.id }]); assert.equal(original.transcript.editing, null); assert.equal(original.draft.text, 'typed while waiting'); assert.equal(other.draft.text, 'other session');});
test('a late save failure restores the edit to its own session after detach', async () => { api.reset([]); api.failEdits(null, null, null); const { transcript, id, draft } = await queuedSend('original', 'source'); draft.text = 'ordinary draft'; await transcript.beginEdit(id); const answer = Promise.withResolvers(); api.answerEdits(null, () => answer.promise); const saving = transcript.saveEdit('correction', [], []); void transcript.saveEdit('duplicate', [], []); transcript.cancelEdit(); transcript.detach(); draft.text = 'continued in a reopened source chat'; answer.reject(new Error('connection lost')); await saving; assert.deepEqual( api.edits.map(({ session, text }) => [session, text]), [['source', 'correction']], ); assert.equal(draft.text, 'continued in a reopened source chat\n\ncorrection'); assert.match(draft.notice, /connection lost/); assert.equal(transcript.editing, null);});
test('save waits for an in-flight renewal of the same input', async (t) => { t.mock.timers.enable({ apis: ['setTimeout'] }); api.reset([]); api.failEdits(null, null, null); const { transcript, id, draft } = await queuedSend('original', 'renewing'); draft.text = 'ordinary'; const renewal = Promise.withResolvers(); api.answerEdits( () => (api.held.length === 1 ? { lease_ms: 3000 } : renewal.promise), null, ); await transcript.beginEdit(id); transcript.editing.draft.text = 'corrected'; t.mock.timers.tick(1000); const saving = transcript.saveEdit('corrected', [], []); await Promise.resolve(); assert.equal(transcript.editPending, 'saving'); assert.equal(transcript.editing.draft.text, 'corrected'); assert.equal(api.edits.length, 0); renewal.resolve({ lease_ms: 3000 }); await saving; t.mock.timers.tick(10000); assert.equal(api.held.length, 2); assert.equal(api.edits.length, 1); assert.equal(transcript.editPending, null); assert.equal(draft.text, 'ordinary');});
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', external: false, answer: true, }, }, ]); 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', external: false, answer: true, }); assert.equal(agent.turnType, 'agent'); assert.equal(transcript.receipt, null);});
test('live stream notes render in place, ignore agent progress, and deduplicate by entry_id', async () => { api.reset(conversation()); const transcript = new Transcript('session'); await transcript.load(); transcript.attach(); stream.emit({ generation: 'g1', cursor: 1, events: [ { type: 'note', sequence: 1, data: { entry_id: 'n-agent', origin: 'agent', text: 'checking files' }, }, { type: 'note', sequence: 2, data: { entry_id: 'n-1', origin: 'daemon', text: 'python kernel reattached; its variables and jobs carried on', }, }, { type: 'note', sequence: 3, data: { entry_id: 'n-1', origin: 'daemon', text: 'python kernel reattached; its variables and jobs carried on', }, }, ], }); assert.deepEqual( transcript.blocks.map((b) => b.kind), ['user', 'assistant', 'end', 'note'], ); assert.equal( transcript.blocks.at(-1).text, 'python kernel reattached; its variables and jobs carried on', ); api.answerHistory(() => Promise.resolve({ items: [ message('user', 3, 3, 'next', 'model-two'), message('assistant', 4, 4, 'done', 'model-two'), ], newer: null, }), ); await transcript.poll(); assert.deepEqual( transcript.blocks.map((b) => b.kind), ['user', 'assistant', 'end', 'note', 'user', 'assistant', 'end'], ); transcript.detach();});
test('thumbnailSource requests 256/512 edge variants only when the image exceeds them', () => { assert.deepEqual( thumbnailSource({ src: 'data:image/png;base64,AA==', width: 2880, height: 1800, }), { src: 'data:image/png;base64,AA==' }, ); assert.deepEqual( thumbnailSource({ src: '/api/sessions/s/history/1/image-0', width: 200, height: 150, }), { src: '/api/sessions/s/history/1/image-0' }, ); assert.deepEqual( thumbnailSource({ src: '/api/sessions/s/history/1/image-0', width: 400, height: 300, }), { src: '/api/sessions/s/history/1/image-0?edge=256', srcset: '/api/sessions/s/history/1/image-0?edge=256 1x, /api/sessions/s/history/1/image-0 2x', }, ); assert.deepEqual( thumbnailSource({ src: '/api/sessions/s/history/1/image-0', width: 2880, height: 1800, }), { src: '/api/sessions/s/history/1/image-0?edge=256', srcset: '/api/sessions/s/history/1/image-0?edge=256 1x, /api/sessions/s/history/1/image-0?edge=512 2x', }, );});
test('history and commit notifications can arrive independently for identical replies', async () => { api.reset([]); const transcript = new Transcript('session'); transcript.entries = conversation(); transcript.attach(); const event = (type, data) => stream.emit({ events: [{ type, data }] }); const keys = () => transcript.groups .filter((row) => row.kind === 'assistant' && row.text === 'yes') .map((row) => row.key); try { event('text', { message_id: 'a', text: 'yes' }); const first = { ...message('assistant', 3, 3, 'yes'), id: '3' }; const second = { ...message('assistant', 4, 4, 'yes'), id: '4' }; api.answerHistory(async () => ({ items: [first], newer: null })); await transcript.poll(); assert.deepEqual(keys(), ['live:a']); event('committed', { high_water: 3, replaces_live_ids: ['a'] }); event('text', { message_id: 'b', text: 'yes' }); api.answerHistory(async () => ({ items: [second], newer: null })); await transcript.poll(); assert.deepEqual(keys(), ['3', 'live:b']); event('committed', { high_water: 4, replaces_live_ids: ['b'] }); await transcript.poll(); assert.deepEqual(keys(), ['3', '4']); } finally { transcript.detach(); }});
test('a page split mid-turn keeps its first rows when the earlier half arrives', async () => { api.reset([]); api.answerHistory(async (at) => at?.before ? { items: [ message('user', 1, 1, 'prompt', 'turn-one'), message('thinking', 2, 2, 'earlier thought', 'turn-one'), ], older: null, } : { items: [ message('thinking', 3, 3, 'later thought', 'turn-one'), message('assistant', 4, 4, 'answer', 'turn-one'), message('user', 5, 5, 'next prompt', 'turn-two'), ], older: 3, }, ); const transcript = new Transcript('session'); await transcript.load(); const keys = transcript.groups.map((row) => row.key); await transcript.loadOlder(); assert.deepEqual( transcript.groups.map((row) => row.key), ['entry-1', ...keys], ); assert.equal(transcript.groups[1].steps.length, 2); transcript.detach();});
test('a poll recovers a failed initial history read with earlier pages still available', async () => { api.reset([]); const first = message('user', 1, 1, 'first', 'first-turn'); const second = message('user', 2, 2, 'second', 'second-turn'); const third = message('user', 3, 3, 'third', 'third-turn'); let reachable = false; api.answerHistory(async (at) => { if (!reachable) throw new Error('history unavailable'); if (at?.before === 2) return { items: [first], older: null, newer: 2 }; if (at?.after === 3) return { items: [], older: null, newer: null }; return { items: [second, third], older: 2, newer: null }; });
const transcript = new Transcript('session'); await transcript.load(); assert.equal(transcript.error, 'history unavailable');
reachable = true; await transcript.poll(); await transcript.poll(); await transcript.loadOlder(); assert.deepEqual( transcript.groups.map((row) => row.key), ['entry-1', 'entry-2', 'entry-3'], ); assert.equal(transcript.error, null); assert.equal(transcript.more, false);});