Skip to content

Commit 1502493

Browse files
Read complete Workbench history events in replay regression (#10105)
* Start Workbench managed Core through the installed entrypoint Signed-off-by: lusendong.6789 <lusendong.6789@bytedance.com> * Defer staged Reward Memory on ordinary quota settlement Signed-off-by: lusendong.6789 <lusendong.6789@bytedance.com> * Load Reward Memory configuration owners only when configuring a route Signed-off-by: lusendong.6789 <lusendong.6789@bytedance.com> * Review the scope of blocked work before deferring a Goal outcome Signed-off-by: huangruiteng <huangrt01@163.com> * Find Node installed in the Python tool environment Signed-off-by: lusendong.6789 <lusendong.6789@bytedance.com> * Recheck linked Todo class when observing Goal coverage Signed-off-by: huangruiteng <huangrt01@163.com> * Recheck open dependency waits after independent work ends Signed-off-by: huangruiteng <huangrt01@163.com> * Review outcome coverage before parking PR-dependent work Signed-off-by: huangruiteng <huangrt01@163.com> * Read complete Workbench history events in replay regression Signed-off-by: lusendong.6789 <lusendong.6789@bytedance.com> * Yield while seeding long Workbench history fixtures Signed-off-by: lusendong.6789 <lusendong.6789@bytedance.com> * Invalidate a settled wait scope when its evidence changes Signed-off-by: huangruiteng <huangrt01@163.com> --------- Signed-off-by: lusendong.6789 <lusendong.6789@bytedance.com> Signed-off-by: huangruiteng <huangrt01@163.com> Co-authored-by: huangruiteng <huangrt01@163.com>
1 parent 41c66f4 commit 1502493

2 files changed

Lines changed: 70 additions & 31 deletions

File tree

‎apps/workbench/packages/daemon/test/api.test.ts‎

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { dirname, join, relative } from 'node:path';
77
import { fileURLToPath } from 'node:url';
88
import { get, type Server } from 'node:http';
99
import type { AddressInfo } from 'node:net';
10+
import { setImmediate } from 'node:timers/promises';
1011
import { gunzipSync } from 'node:zlib';
1112
import { AgentRegistry, defaultInstances } from '../src/agents.js';
1213
import { AgyAdapter } from '../src/adapters/agy.js';
@@ -3012,11 +3013,16 @@ test('agents: rename, hide, restore and removal leave a used instance in place',
30123013
}
30133014
});
30143015

3015-
/** Appends events straight to the log, the way a turn would have, without running an agent. */
3016-
function writeLog(threadId: string, turnId: string | null, entries: Array<[type: Parameters<Store['appendEvent']>[2], data: Record<string, unknown>]>) {
3017-
store.transaction(() => {
3018-
for (const [type, data] of entries) store.appendEvent(threadId, turnId, type, data);
3019-
});
3016+
/** Seeds the stored log without monopolizing the event loop shared with the HTTP fixture. */
3017+
async function writeLog(threadId: string, turnId: string | null, entries: Array<[type: Parameters<Store['appendEvent']>[2], data: Record<string, unknown>]>) {
3018+
const batchSize = 500;
3019+
for (let offset = 0; offset < entries.length; offset += batchSize) {
3020+
const batch = entries.slice(offset, offset + batchSize);
3021+
store.transaction(() => {
3022+
for (const [type, data] of batch) store.appendEvent(threadId, turnId, type, data);
3023+
});
3024+
await setImmediate();
3025+
}
30203026
}
30213027

30223028
type Logged = { seq: number; type: string; turnId: string | null; data: Record<string, any> };
@@ -3026,7 +3032,7 @@ test('events endpoint: a page begins where a turn begins, and streamed fragments
30263032
const page = async (query: string) => (await (await api(`/api/threads/${thread.id}/events?${query}`)).json()) as Logged[];
30273033

30283034
// A short turn, then one far longer than a page reaches back.
3029-
writeLog(thread.id, 'a', [
3035+
await writeLog(thread.id, 'a', [
30303036
['turn.started', { text: 'first' }],
30313037
['reasoning.delta', { text: 'th' }],
30323038
['reasoning.delta', { text: 'ink' }],
@@ -3037,7 +3043,7 @@ test('events endpoint: a page begins where a turn begins, and streamed fragments
30373043
['message.delta', { text: 'two' }],
30383044
['turn.done', { stopReason: 'end_turn' }],
30393045
]);
3040-
writeLog(thread.id, 'b', [
3046+
await writeLog(thread.id, 'b', [
30413047
['turn.started', { text: 'second' }],
30423048
...Array.from({ length: 21_000 }, (_, i): ['reasoning.delta', { text: string }] => ['reasoning.delta', { text: i % 2 ? 'b' : 'a' }]),
30433049
]);
@@ -3052,8 +3058,8 @@ test('events endpoint: a page begins where a turn begins, and streamed fragments
30523058
assert.equal(running[1].seq, all[0].seq, 'the first fragment keeps its own seq and time');
30533059
assert.equal(running.at(-1)!.seq, running[0].seq + 21_000, 'the merged rest carries the last seq, so a stream can resume after it');
30543060

3055-
writeLog(thread.id, 'b', [['turn.done', { stopReason: 'end_turn' }]]);
3056-
writeLog(thread.id, 'c', [
3061+
await writeLog(thread.id, 'b', [['turn.done', { stopReason: 'end_turn' }]]);
3062+
await writeLog(thread.id, 'c', [
30573063
['turn.started', { text: 'third' }],
30583064
['message.delta', { text: 'short' }],
30593065
['turn.done', { stopReason: 'end_turn' }],
@@ -3097,7 +3103,7 @@ test('events endpoint: a page begins where a turn begins, and streamed fragments
30973103
test('history pages limit short turns too, and paging back preserves every event needed for replay', async () => {
30983104
const thread = await newThread({ agent: 'pi', cwd: workdir });
30993105
for (let i = 0; i < 8; i++) {
3100-
writeLog(thread.id, `turn-${i}`, [
3106+
await writeLog(thread.id, `turn-${i}`, [
31013107
['turn.started', { text: `question ${i}` }],
31023108
['tool.start', { id: `tool-${i}`, kind: 'execute', title: 'check', status: 'in_progress' }],
31033109
...Array.from({ length: 30 }, (_, n): ['tool.update', Record<string, unknown>] => ['tool.update', { id: `tool-${i}`, output: `snapshot ${n}\n${'output\n'.repeat(1000)}` }]),
@@ -3132,7 +3138,7 @@ test('history pages limit short turns too, and paging back preserves every event
31323138
test('SSE stream replays everything after the cursor, however long, before going live', async () => {
31333139
const thread = await newThread({ agent: 'pi', cwd: workdir });
31343140
// More than one page of the stored log, none of it mergeable.
3135-
writeLog(thread.id, 'a', [
3141+
await writeLog(thread.id, 'a', [
31363142
['turn.started', { text: 'long' }],
31373143
...Array.from({ length: 6000 }, (_, i): ['tool.update', { id: string }] => ['tool.update', { id: `u${i}` }]),
31383144
['turn.done', { stopReason: 'end_turn' }],
@@ -3160,7 +3166,7 @@ test('sync: a hub turn deep in a long log is still known, and is not appended ag
31603166
await post(`/api/threads/${thread.id}/turns`, { text: 'hello' });
31613167
await untilIdle(thread.id);
31623168
// A long stretch of output, then a second turn far past the first page of the log.
3163-
writeLog(thread.id, null, Array.from({ length: 6000 }, (): ['thread.updated', {}] => ['thread.updated', {}]));
3169+
await writeLog(thread.id, null, Array.from({ length: 6000 }, (): ['thread.updated', {}] => ['thread.updated', {}]));
31643170
await post(`/api/threads/${thread.id}/turns`, { text: 'much later' });
31653171
await untilIdle(thread.id);
31663172
const sessionId = (await viewOf(thread.id)).agentSessionId!;
@@ -3186,14 +3192,14 @@ test('sync: a hub turn deep in a long log is still known, and is not appended ag
31863192

31873193
test('restart: a turn the last daemon left running is ended as interrupted', async () => {
31883194
const cut = await newThread({ agent: 'pi', cwd: workdir });
3189-
writeLog(cut.id, 'open', [
3195+
await writeLog(cut.id, 'open', [
31903196
['turn.started', { text: 'never finished' }],
31913197
['message.delta', { text: 'half an ans' }],
31923198
]);
31933199
store.updateThread(cut.id, { status: 'running' });
31943200
// Marked running, but its turn did end: only the mark is stale.
31953201
const stale = await newThread({ agent: 'pi', cwd: workdir });
3196-
writeLog(stale.id, 'closed', [
3202+
await writeLog(stale.id, 'closed', [
31973203
['turn.started', { text: 'finished' }],
31983204
['turn.done', { stopReason: 'end_turn' }],
31993205
]);
@@ -3216,7 +3222,7 @@ test('restart: a turn the last daemon left running is ended as interrupted', asy
32163222

32173223
test('a page of history collapses a tool call\'s update burst, and the payload travels gzipped', async () => {
32183224
const thread = await newThread({ agent: 'pi', cwd: workdir });
3219-
writeLog(thread.id, 'a1', [
3225+
await writeLog(thread.id, 'a1', [
32203226
['turn.started', { text: 'edit it' }],
32213227
['tool.start', { id: 'c1', kind: 'edit', title: 'Edit a.ts', status: 'in_progress' }],
32223228
...Array.from({ length: 40 }, (_, i) => [

‎apps/workbench/packages/daemon/test/history.test.ts‎

Lines changed: 49 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { tmpdir } from 'node:os';
55
import { join } from 'node:path';
66
import { Store } from '../src/store.js';
77
import type { EventType } from '../src/events.js';
8+
import type { HistoryEvent } from '../src/history.js';
89

910
function fixture() {
1011
const dir = mkdtempSync(join(tmpdir(), 'loochat-history-'));
@@ -104,6 +105,7 @@ test('history HTTP APIs validate scope/cursors and SSE catches up lightly then s
104105
const base = `http://127.0.0.1:${(server.address() as import('node:net').AddressInfo).port}`;
105106
const headers = { Authorization: 'Bearer history-test-token' };
106107
const request = (path: string) => fetch(base + path, { headers });
108+
const controller = new AbortController();
107109
try {
108110
f.add('a', 'turn.started', { text: 'question' });
109111
f.add('a', 'tool.start', { id: 'x', input: { private: true }, title: 'run' });
@@ -128,28 +130,59 @@ test('history HTTP APIs validate scope/cursors and SSE catches up lightly then s
128130
(manager as any).emitThreadEvent('thread', 'gap', 'tool.end', { id: 'gap-tool', output: 'GAP_OUTPUT', status: 'completed' });
129131
return snapshot;
130132
};
131-
const controller = new AbortController();
132-
const stream = await fetch(base + '/api/threads/thread/stream?view=history&after=0', { headers, signal: controller.signal });
133+
const stream = await fetch(base + '/api/threads/thread/stream?view=history&after=0', {
134+
headers,
135+
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(10_000)]),
136+
});
137+
assert.equal(stream.status, 200);
133138
const reader = stream.body!.getReader();
134-
const first = new TextDecoder().decode((await reader.read()).value);
135-
assert.ok(first.includes('history.reset'));
136-
assert.ok(first.includes('answer'));
137-
assert.ok(!first.includes('private output'));
138-
let gap = first;
139-
while (!gap.includes('GAP_OUTPUT')) gap += new TextDecoder().decode((await reader.read()).value);
140-
assert.equal(gap.split('GAP_OUTPUT').length - 1, 1);
141-
assert.ok(gap.includes('GAP_INPUT'));
139+
const decoder = new TextDecoder();
140+
let pending = '';
141+
// A read can yield the connection comment alone or part of an event.
142+
async function nextEvent(): Promise<HistoryEvent> {
143+
for (;;) {
144+
const end = pending.indexOf('\n\n');
145+
if (end < 0) {
146+
const { value, done } = await reader.read();
147+
assert.ok(!done, 'stream ended before the next history event');
148+
pending += decoder.decode(value, { stream: true });
149+
continue;
150+
}
151+
const frame = pending.slice(0, end);
152+
pending = pending.slice(end + 2);
153+
if (frame.startsWith(':')) continue;
154+
const [id, name, payload] = frame.split('\n');
155+
assert.ok(payload?.startsWith('data: '));
156+
const event = JSON.parse(payload.slice(6)) as HistoryEvent;
157+
assert.equal(id, `id: ${event.seq}`);
158+
assert.equal(name, `event: ${event.type}`);
159+
return event;
160+
}
161+
}
162+
async function nextTurn(turn: string) {
163+
const events = [await nextEvent(), await nextEvent(), await nextEvent()];
164+
assert.deepEqual(events.map(event => [event.turnId, event.type]),
165+
[[turn, 'turn.started'], [turn, 'tool.start'], [turn, 'tool.end']]);
166+
return events;
167+
}
168+
const reset = await nextEvent();
169+
assert.equal(reset.type, 'history.reset');
170+
assert.match(JSON.stringify(reset.data), /answer/);
171+
assert.doesNotMatch(JSON.stringify(reset.data), /private output/);
172+
const gap = await nextTurn('gap');
173+
assert.deepEqual(gap[1].data.input, { command: 'GAP_INPUT' });
174+
assert.equal(gap[2].data.output, 'GAP_OUTPUT');
142175
// The initial history omits outputs; an uninterrupted connection receives them in full.
143176
(manager as any).emitThreadEvent('thread', 'live', 'turn.started', { text: 'next' });
144177
(manager as any).emitThreadEvent('thread', 'live', 'tool.start', { id: 'live-tool', input: { command: 'LIVE_INPUT' } });
145178
(manager as any).emitThreadEvent('thread', 'live', 'tool.end', { id: 'live-tool', status: 'completed', output: 'LIVE_OUTPUT' });
146-
let live = '';
147-
while (!live.includes('LIVE_OUTPUT')) live += new TextDecoder().decode((await reader.read()).value);
148-
assert.ok(live.includes('event: tool.start'));
149-
assert.ok(live.includes('LIVE_INPUT'));
150-
assert.ok(live.includes('event: tool.end'));
151-
controller.abort();
179+
const live = await nextTurn('live');
180+
assert.deepEqual(live[1].data.input, { command: 'LIVE_INPUT' });
181+
assert.equal(live[2].data.output, 'LIVE_OUTPUT');
182+
assert.deepEqual([...gap, ...live].map(event => event.seq),
183+
[1, 2, 3, 4, 5, 6].map(offset => reset.seq + offset));
152184
} finally {
185+
controller.abort();
153186
server.closeAllConnections();
154187
await new Promise<void>(resolve => server.close(() => resolve()));
155188
f.close(); rmSync(dir, { recursive: true, force: true });

0 commit comments

Comments
 (0)