返回 CodeWhale
thread-events.test.mjs
根目录 / npm / runtime-sdk / test / thread-events.test.mjs
1 import assert from 'node:assert/strict';
2 import test from 'node:test';
3 import { CodeWhaleRuntimeClient, isThreadStreamEnd } from '../index.js';
4
5 function clientFor(chunks, inspect = () => {}, headers = {}) {
6 return new CodeWhaleRuntimeClient({ token: 'fixture-token', fetch: async (url, init) => {
7 inspect(url, init);
8 return new Response(new ReadableStream({ start(controller) {
9 for (const chunk of chunks) controller.enqueue(new TextEncoder().encode(chunk));
10 controller.close();
11 } }), { headers: { 'content-type': 'text/event-stream; charset=utf-8', ...headers } });
12 } });
13 }
14 const collect = async stream => { const out = []; for await (const value of stream) out.push(value); return out; };
15
16 test('thread journal reads preserve the Runtime cursor, GET, cancellation and redirect boundary', async () => {
17 const signal = new AbortController().signal;
18 const record = { seq: 17, previous_seq: 9, event: 'item.completed', thread_id: 't/a', timestamp: '2026-09-12T00:00:00Z', payload: {} };
19 const raw = `: keepalive\r\n\r\ndata: ${JSON.stringify(record)}\r\n\r\n`;
20 const client = clientFor([...raw], (url, init) => {
21 assert.equal(url.pathname, '/v1/threads/t%2Fa/events');
22 assert.equal(url.searchParams.get('since_seq'), '9'); assert.equal(url.searchParams.get('replay_limit'), '100');
23 assert.equal(init.method, 'GET'); assert.equal(init.redirect, 'error'); assert.equal(init.signal, signal);
24 assert.equal(init.headers.get('authorization'), 'Bearer fixture-token');
25 });
26 assert.deepEqual(await collect(client.threadEvents('t/a', { sinceSeq: 9, replayLimit: 100, signal })), [record]);
27 });
28
29 test('thread stream reads CR and mixed line endings across chunk boundaries', async () => {
30 const records = [
31 { seq: 17, event: 'item.started', thread_id: 't' },
32 { seq: 18, event: 'item.completed', thread_id: 't' },
33 ];
34 for (const [lineEnd, blankEnd] of [['\r', '\r'], ['\n', '\r\n'], ['\r\n', '\r\n']]) {
35 const raw = records.map(record =>
36 `id: ${record.seq}${lineEnd}data: ${JSON.stringify(record)}${lineEnd}${blankEnd}`,
37 ).join('');
38 const expected = records.map(record => ({ ...record, cursor: String(record.seq) }));
39 assert.deepEqual(await collect(clientFor([...raw]).threadEvents('t')), expected);
40 }
41 });
42
43 test('thread stream accepts an exact-limit frame with a split separator', async () => {
44 const limit = 2 * 1024 * 1024;
45 const record = { seq: 17, event: 'item.completed', text: '' };
46 const encode = (event) => `data: ${JSON.stringify(event)}`;
47 record.text = 'x'.repeat(limit - encode(record).length);
48 const frame = encode(record);
49 for (const lineEnding of ['\n', '\r', '\r\n']) {
50 assert.deepEqual(await collect(clientFor([`${frame}${lineEnding}`, lineEnding]).threadEvents('t')), [record]);
51 }
52 assert.deepEqual(
53 await collect(clientFor([frame, '\r', '\n', '\r', '\n'], () => {}, { 'content-type': 'text/event-stream ; charset=utf-8' }).threadEvents('t')),
54 [record],
55 );
56 await assert.rejects(collect(clientFor([`${frame} \r\n`, '\r\n']).threadEvents('t')), /size limit/);
57 });
58
59 test('thread stream refuses incomplete, oversized and invalid frames without emitting a partial event', async () => {
60 await assert.rejects(collect(clientFor(['data: {"seq":1}']).threadEvents('t')), /inside a frame/);
61 await assert.rejects(collect(clientFor(['data: ' + 'x'.repeat(2 * 1024 * 1024)]).threadEvents('t')), /size limit/);
62 await assert.rejects(collect(clientFor(['data: not-json\n\n']).threadEvents('t')), SyntaxError);
63 });
64 test('thread stream rejects invalid cursor arguments and a JSON response', async () => {
65 for (const sinceSeq of [-1, 1.5, Number.MAX_SAFE_INTEGER + 1])
66 await assert.rejects(collect(clientFor([]).threadEvents('t', { sinceSeq })), /safe integer/);
67 const client = new CodeWhaleRuntimeClient({ fetch: async () => new Response('{}', { headers: { 'content-type': 'application/json' } }) });
68 await assert.rejects(collect(client.threadEvents('t')), /not an event stream/);
69 });
70
71
72 test('thread progress is explicitly requested and remains separate from journal records at the same cursor', async () => {
73 const progress = { event: 'stream.progress', state: 'live', thread_id: 't', seq: 9 };
74 const client = clientFor([`data: ${JSON.stringify(progress)}\n\n`], (url) => {
75 assert.equal(url.searchParams.get('progress'), 'true');
76 }, { 'x-codewhale-event-progress': '1' });
77 assert.deepEqual(await collect(client.threadEvents('t', { sinceSeq: 9, includeProgress: true })), [progress]);
78 await assert.rejects(collect(client.threadEvents('t', { includeProgress: 'yes' })), /boolean/);
79 });
80
81 test('thread progress fails explicitly and closes the stream when an older Runtime does not advertise it', async () => {
82 let canceled = false;
83 const client = new CodeWhaleRuntimeClient({ fetch: async () => new Response(new ReadableStream({ cancel() { canceled = true; } }), { headers: { 'content-type': 'text/event-stream' } }) });
84 await assert.rejects(collect(client.threadEvents('t', { includeProgress: true })), error => error.capability === 'thread_event_progress' && error.status === 501);
85 assert.equal(canceled, true);
86 });
87
88 test('a server-ended thread stream yields its typed stream.end frame last', async () => {
89 const record = { seq: 17, previous_seq: 9, event: 'item.completed', thread_id: 't', timestamp: '2026-09-12T00:00:00Z', payload: {} };
90 const end = { schema_version: 1, event: 'stream.end', kind: 'stream.end', thread_id: 't', reason: 'replay_failed', last_seq: 17, retryable: true };
91 const raw = `event: item.completed\nid: 17\ndata: ${JSON.stringify(record)}\n\nevent: stream.end\ndata: ${JSON.stringify(end)}\n\n`;
92 const client = clientFor([raw], () => {}, { 'x-codewhale-stream-end': '1' });
93 // The journal frame's SSE id becomes its cursor; stream.end carries none.
94 assert.deepEqual(await collect(client.threadEvents('t', { sinceSeq: 9 })), [{ ...record, cursor: '17' }, end]);
95 });
96
97 test('isThreadStreamEnd distinguishes end frames from journal and progress events', async () => {
98 const record = { seq: 17, event: 'future.journal.event', thread_id: 't', timestamp: '2026-09-12T00:00:00Z', payload: {} };
99 const progress = { event: 'stream.progress', thread_id: 't', seq: 17, state: 'live' };
100 const end = { schema_version: 1, event: 'stream.end', kind: 'stream.end', thread_id: 't', reason: 'runtime_shutdown', last_seq: 17, retryable: true };
101 const raw = [record, progress, end].map(value => `data: ${JSON.stringify(value)}\n\n`).join('');
102 const client = clientFor([raw], () => {}, { 'x-codewhale-event-progress': '1' });
103 const events = await collect(client.threadEvents('t', { includeProgress: true }));
104 assert.deepEqual(events.map(isThreadStreamEnd), [false, false, true]);
105 assert.deepEqual(events.filter(isThreadStreamEnd), [end]);
106 });
107
107 lines Plain Text