@pi-chamber/web 0.9.6 → 0.9.8-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/assets/{DiagramView-0Iq1ak1I.js → DiagramView-BMBrrFLy.js} +1 -1
- package/dist/assets/{DiffView-DD1AFRi3.js → DiffView-yVBxHkBI.js} +1 -1
- package/dist/assets/{FileSaveConflictDialog-CoKwDovb.js → FileSaveConflictDialog-D0siEm8l.js} +1 -1
- package/dist/assets/FilesView-CkcKBKkT.js +6 -0
- package/dist/assets/{GitView-LFEpCasf.js → GitView-CfuhQOfc.js} +3 -3
- package/dist/assets/{JsonTreeView-Cwjgvh4g.js → JsonTreeView-6kRdE1BO.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-_7kV1yNw.js → MarkdownRendererImpl-CRWbN_Jc.js} +2 -2
- package/dist/assets/{PatchDiff-DG43C1HW.js → PatchDiff-B0ssv8Aw.js} +1 -1
- package/dist/assets/{SessionSwitcherContent-DCFXPY3d.js → SessionSwitcherContent-NmfI4B0Z.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-QY7FKuEQ.js → SessionSwitcherDropdown-DmE2hYTN.js} +2 -2
- package/dist/assets/SessionUnreadDot-LDTswryg.js +1 -0
- package/dist/assets/SettingsView-D0iw6y_H.js +2 -0
- package/dist/assets/SettingsWindow-BT2TzUBK.js +1 -0
- package/dist/assets/{ToolOutputDialog-IlCrS6BR.js → ToolOutputDialog-Bnl51bva.js} +4 -4
- package/dist/assets/{ToolPartDiffPreview-D68JV0rR.js → ToolPartDiffPreview-DgPtLS_h.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-Bl-rAYeh.js → VirtualizedFileDiff-D3zBpYIS.js} +4 -4
- package/dist/assets/collapsible-_urywMu5.js +1 -0
- package/dist/assets/{computeVirtualFileMetrics-FSOm2VrW.js → computeVirtualFileMetrics-y2AJzpKw.js} +2 -2
- package/dist/assets/{contextFileOpenGuard-Bxb6AIPa.js → contextFileOpenGuard-DYUFkrPT.js} +1 -1
- package/dist/assets/{gitStatusPredicates-DxolDpMd.js → gitStatusPredicates-CbFfOlbV.js} +1 -1
- package/dist/assets/index-BXgR2dKM.css +1 -0
- package/dist/assets/index-CrqlVJXp.js +8 -0
- package/dist/assets/{index-Dh58uD3I.js → index-DwJJarzh.js} +1 -1
- package/dist/assets/{isDiffPlainText-D3_04XCh.js → isDiffPlainText-kXPOivsq.js} +1 -1
- package/dist/assets/{isFilePlainText-CHouYQhH.js → isFilePlainText-BBIPqnLo.js} +1 -1
- package/dist/assets/{main-HzTrVvbB.js → main-BshSYpnV.js} +7 -7
- package/dist/assets/{main-CH3EqGJI.js → main-RrPyfmCA.js} +2 -2
- package/dist/assets/{markdownCore-DJU4KvHP.js → markdownCore-BxXmpZtB.js} +1 -1
- package/dist/assets/{miniChat-Ca3TpaaA.js → miniChat-DRNgmC-q.js} +2 -2
- package/dist/assets/{mobile-lj4gpGsO.js → mobile-CdmgVKW4.js} +2 -2
- package/dist/assets/renderElectronMiniChatApp-B80Jqq8b.js +2 -0
- package/dist/assets/renderMobileApp-CLcBvRiy.js +11 -0
- package/dist/assets/runtimeEndpointReset-DHHCemOu.js +53 -0
- package/dist/assets/{runtimeSurface-CE_VNjdH.js → runtimeSurface-C9kx2zfD.js} +1 -1
- package/dist/assets/{useAppFontEffects-BvFAP9zG.js → useAppFontEffects-Dp6vM-Zr.js} +104 -104
- package/dist/assets/{useFilesViewSearch-BD79p3A2.js → useFilesViewSearch-Bc8PTYrg.js} +2 -2
- package/dist/assets/{usePushVisibilityBeacon-CWg0j-Wg.js → usePushVisibilityBeacon-DMcKyNtE.js} +1 -1
- package/dist/assets/{useSwitcherItems-CazJ6Yox.js → useSwitcherItems-DEvsORZ_.js} +1 -1
- package/dist/assets/{vendor-base-ui-CdaWtC7e.js → vendor-base-ui-C60wdVnS.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-CP3j3-xu.js → vendor-codemirror-language-data-DLimsiRH.js} +2 -2
- package/dist/assets/{vendor-floating-ui-dom-WyXykhNi.js → vendor-floating-ui-dom-Bkw82kL9.js} +1 -1
- package/dist/assets/{vendor-floating-ui-react-dom-BZOGXAGe.js → vendor-floating-ui-react-dom-KLmnYDaG.js} +1 -1
- package/dist/assets/{web-components-DWuadqra.js → web-components-05Oa3k7a.js} +3 -3
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +1 -1
- package/server/index.js +17 -3
- package/server/lib/client-auth/DOCUMENTATION.md +184 -0
- package/server/lib/client-auth/live-revocation.test.js +567 -0
- package/server/lib/client-auth/principal-tracker.js +383 -0
- package/server/lib/client-auth/principal-tracker.test.js +321 -0
- package/server/lib/client-auth/remote-clients.js +31 -0
- package/server/lib/client-auth/remote-clients.test.js +44 -0
- package/server/lib/pi/event-stream.js +269 -0
- package/server/lib/pi/event-stream.test.js +776 -0
- package/server/lib/pi/routes.js +88 -31
- package/server/lib/pi/routes.test.js +92 -20
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +5 -4
- package/server/lib/pi/session-daemon/ipc-client.js +19 -15
- package/server/lib/pi/session-daemon/ipc-client.test.js +113 -1
- package/server/lib/pi/session-daemon/prompt-preflight.test.js +5 -1
- package/server/lib/pi/session-daemon/send-operation-dedup.test.js +15 -5
- package/server/lib/pi/session-daemon/send-operation-registry.js +26 -23
- package/server/lib/pi/session-daemon/send-operation-registry.test.js +26 -20
- package/server/lib/pi/session-daemon/session-daemon-epoch.test.js +349 -0
- package/server/lib/pi/session-daemon/session-daemon.js +79 -18
- package/server/lib/pi/session-daemon/session-daemon.test.js +10 -4
- package/server/lib/pi/session-daemon/session-replay.test.js +8 -3
- package/server/lib/pi/session-daemon/supervisor.js +30 -5
- package/server/lib/pi/session-daemon/supervisor.test.js +4 -3
- package/server/lib/pi/ui-settings-store.js +7 -1
- package/server/lib/pi/ui-settings-store.test.js +19 -1
- package/server/lib/server/core-routes.js +11 -1
- package/server/lib/stt/DOCUMENTATION.md +2 -0
- package/server/lib/stt/runtime.js +39 -2
- package/server/lib/stt/runtime.test.js +53 -0
- package/server/lib/terminal/DOCUMENTATION.md +2 -0
- package/server/lib/terminal/runtime.js +48 -2
- package/server/lib/terminal/runtime.test.js +35 -0
- package/server/lib/ui-auth/DOCUMENTATION.md +13 -4
- package/server/lib/ui-auth/ui-auth.js +98 -0
- package/server/lib/ui-auth/ui-auth.test.js +249 -0
- package/server/lib/workspace/host.js +3 -1
- package/dist/assets/FilesView-B_BF39ef.js +0 -6
- package/dist/assets/SessionUnreadDot-DGT31A3z.js +0 -1
- package/dist/assets/SettingsView-eG-wN-yY.js +0 -2
- package/dist/assets/SettingsWindow-Dvnp8YrA.js +0 -1
- package/dist/assets/collapsible-BjniCdZ5.js +0 -1
- package/dist/assets/index-BpmGBboM.css +0 -1
- package/dist/assets/index-DZnzXhTs.js +0 -8
- package/dist/assets/renderElectronMiniChatApp-rUFfaD-T.js +0 -2
- package/dist/assets/renderMobileApp-CcWQ1sCf.js +0 -11
- package/dist/assets/runtimeEndpointReset-D2MmSbDk.js +0 -53
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it } from 'vitest';
|
|
2
|
+
import { mkdir, mkdtemp } from 'node:fs/promises';
|
|
3
|
+
import { createConnection } from 'node:net';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
7
|
+
|
|
8
|
+
import { createSessionDaemon } from './session-daemon.js';
|
|
9
|
+
|
|
10
|
+
const credential = 'a-private-daemon-credential';
|
|
11
|
+
|
|
12
|
+
class FakeSession {
|
|
13
|
+
constructor(sessionId = 'pi-session-1') {
|
|
14
|
+
this.sessionId = sessionId;
|
|
15
|
+
this.isStreaming = false;
|
|
16
|
+
this.listeners = new Set();
|
|
17
|
+
this.entries = [];
|
|
18
|
+
this.model = { provider: 'test', id: 'model' };
|
|
19
|
+
this.thinkingLevel = 'low';
|
|
20
|
+
this.sessionManager = {
|
|
21
|
+
getSessionFile: () => undefined,
|
|
22
|
+
getHeader: () => ({ timestamp: '2026-01-01T00:00:00.000Z' }),
|
|
23
|
+
getEntries: () => this.entries,
|
|
24
|
+
getEntry: (id) => this.entries.find((entry) => entry.id === id),
|
|
25
|
+
getLeafId: () => 'fake-entry',
|
|
26
|
+
getTree: () => [],
|
|
27
|
+
appendSessionInfo: () => undefined,
|
|
28
|
+
getSessionName: () => undefined,
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
subscribe(listener) {
|
|
33
|
+
this.listeners.add(listener);
|
|
34
|
+
return () => this.listeners.delete(listener);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
emit(event) {
|
|
38
|
+
for (const listener of this.listeners) listener(event);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async prompt() {}
|
|
42
|
+
|
|
43
|
+
async sendUserMessage() {}
|
|
44
|
+
|
|
45
|
+
async abort() {}
|
|
46
|
+
|
|
47
|
+
async compact() {}
|
|
48
|
+
|
|
49
|
+
getSteeringMessages() { return []; }
|
|
50
|
+
|
|
51
|
+
getFollowUpMessages() { return []; }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function testDaemonEndpoint(root) {
|
|
55
|
+
return process.platform === 'win32'
|
|
56
|
+
? `\\\\.\\pipe\\pichamber-pi-daemon-epoch-test-${Math.random().toString(36).slice(2)}`
|
|
57
|
+
: join(root, 'daemon.sock');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function connectClient(endpoint) {
|
|
61
|
+
const socket = createConnection(endpoint);
|
|
62
|
+
const decoder = new StringDecoder('utf8');
|
|
63
|
+
let buffer = '';
|
|
64
|
+
const messages = [];
|
|
65
|
+
const waiters = [];
|
|
66
|
+
|
|
67
|
+
socket.on('data', (chunk) => {
|
|
68
|
+
buffer += decoder.write(chunk);
|
|
69
|
+
while (true) {
|
|
70
|
+
const newline = buffer.indexOf('\n');
|
|
71
|
+
if (newline === -1) break;
|
|
72
|
+
const line = buffer.slice(0, newline).replace(/\r$/, '');
|
|
73
|
+
buffer = buffer.slice(newline + 1);
|
|
74
|
+
if (!line) continue;
|
|
75
|
+
const message = JSON.parse(line);
|
|
76
|
+
messages.push(message);
|
|
77
|
+
for (let index = waiters.length - 1; index >= 0; index -= 1) {
|
|
78
|
+
const waiter = waiters[index];
|
|
79
|
+
if (waiter.predicate(message)) {
|
|
80
|
+
waiters.splice(index, 1);
|
|
81
|
+
waiter.resolve(message);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
const next = (predicate) => {
|
|
88
|
+
const existing = messages.find(predicate);
|
|
89
|
+
if (existing) return Promise.resolve(existing);
|
|
90
|
+
return new Promise((resolve, reject) => {
|
|
91
|
+
const timer = setTimeout(() => {
|
|
92
|
+
const index = waiters.findIndex((waiter) => waiter.resolve === resolve);
|
|
93
|
+
if (index !== -1) waiters.splice(index, 1);
|
|
94
|
+
reject(new Error('Timed out waiting for daemon message'));
|
|
95
|
+
}, 2_000);
|
|
96
|
+
waiters.push({ predicate, reject, resolve: (message) => { clearTimeout(timer); resolve(message); } });
|
|
97
|
+
});
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
let closed = false;
|
|
101
|
+
return {
|
|
102
|
+
socket,
|
|
103
|
+
async authenticate({ fromSequence, streamEpoch } = {}) {
|
|
104
|
+
await new Promise((resolve, reject) => {
|
|
105
|
+
socket.once('connect', resolve);
|
|
106
|
+
socket.once('error', reject);
|
|
107
|
+
});
|
|
108
|
+
socket.write(`${JSON.stringify({
|
|
109
|
+
kind: 'authenticate',
|
|
110
|
+
credential,
|
|
111
|
+
...(fromSequence !== undefined ? { fromSequence } : {}),
|
|
112
|
+
...(streamEpoch ? { streamEpoch } : {}),
|
|
113
|
+
})}\n`);
|
|
114
|
+
await next((message) => message.kind === 'authenticated');
|
|
115
|
+
},
|
|
116
|
+
request(command, payload = {}) {
|
|
117
|
+
const requestId = `request-${Math.random()}`;
|
|
118
|
+
socket.write(`${JSON.stringify({ protocolVersion: 1, kind: 'request', requestId, command, payload })}\n`);
|
|
119
|
+
return next((message) => message.kind === 'response' && message.requestId === requestId);
|
|
120
|
+
},
|
|
121
|
+
next,
|
|
122
|
+
async close() {
|
|
123
|
+
if (closed) return;
|
|
124
|
+
closed = true;
|
|
125
|
+
socket.end();
|
|
126
|
+
await new Promise((resolve) => {
|
|
127
|
+
if (socket.destroyed) { resolve(); return; }
|
|
128
|
+
socket.once('close', resolve);
|
|
129
|
+
setTimeout(resolve, 250);
|
|
130
|
+
});
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const startDaemon = async (root, session) => {
|
|
136
|
+
const endpoint = testDaemonEndpoint(root);
|
|
137
|
+
const daemon = createSessionDaemon({
|
|
138
|
+
endpoint,
|
|
139
|
+
credential,
|
|
140
|
+
cwd: root,
|
|
141
|
+
agentDir: join(root, 'agent'),
|
|
142
|
+
createRuntime: async () => ({ session, async dispose() {} }),
|
|
143
|
+
});
|
|
144
|
+
await daemon.start();
|
|
145
|
+
return { daemon, endpoint };
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
describe('session daemon stream epoch', () => {
|
|
149
|
+
const daemons = [];
|
|
150
|
+
const sockets = [];
|
|
151
|
+
|
|
152
|
+
const track = async (root, session) => {
|
|
153
|
+
const started = await startDaemon(root, session);
|
|
154
|
+
daemons.push(started.daemon);
|
|
155
|
+
return started;
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
afterEach(async () => {
|
|
159
|
+
for (const socket of sockets.splice(0)) await socket.close().catch(() => {});
|
|
160
|
+
for (const daemon of daemons.splice(0)) await daemon.stop().catch(() => {});
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
it('stamps a stable opaque streamEpoch on health, snapshots, events, and session reads', async () => {
|
|
164
|
+
const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-epoch-'));
|
|
165
|
+
await mkdir(join(root, 'agent'), { recursive: true });
|
|
166
|
+
const session = new FakeSession();
|
|
167
|
+
const { endpoint } = await track(root, session);
|
|
168
|
+
|
|
169
|
+
const client = connectClient(endpoint);
|
|
170
|
+
sockets.push(client);
|
|
171
|
+
await client.authenticate();
|
|
172
|
+
const snapshot = await client.next((message) => message.kind === 'event' && message.event === 'session.snapshot');
|
|
173
|
+
// Register the injected runtime so live session events are published.
|
|
174
|
+
await client.request('sessions.create', { cwd: root });
|
|
175
|
+
|
|
176
|
+
expect(typeof snapshot.streamEpoch).toBe('string');
|
|
177
|
+
expect(snapshot.streamEpoch.length).toBeGreaterThanOrEqual(16);
|
|
178
|
+
expect(snapshot.streamEpoch).not.toMatch(/pi-session|credential|agent/);
|
|
179
|
+
expect(snapshot.payload.resync).toBeUndefined();
|
|
180
|
+
|
|
181
|
+
const health = await client.request('runtime.health');
|
|
182
|
+
expect(health.result.streamEpoch).toBe(snapshot.streamEpoch);
|
|
183
|
+
expect(health.result.capabilities).toContain('events.streamEpoch');
|
|
184
|
+
|
|
185
|
+
const eventPromise = client.next((message) => message.kind === 'event' && message.event === 'session.updated');
|
|
186
|
+
session.emit({ type: 'session_info_changed', name: 'renamed' });
|
|
187
|
+
const event = await eventPromise;
|
|
188
|
+
expect(event.streamEpoch).toBe(snapshot.streamEpoch);
|
|
189
|
+
|
|
190
|
+
const opened = await client.request('sessions.open', { sessionId: session.sessionId, cwd: root });
|
|
191
|
+
expect(opened.result.streamEpoch).toBe(snapshot.streamEpoch);
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
it('replays contiguously at the same epoch without a resync snapshot', async () => {
|
|
195
|
+
const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-epoch-'));
|
|
196
|
+
await mkdir(join(root, 'agent'), { recursive: true });
|
|
197
|
+
const session = new FakeSession();
|
|
198
|
+
const { endpoint } = await track(root, session);
|
|
199
|
+
|
|
200
|
+
const first = connectClient(endpoint);
|
|
201
|
+
sockets.push(first);
|
|
202
|
+
await first.authenticate();
|
|
203
|
+
const snapshot = await first.next((message) => message.kind === 'event' && message.event === 'session.snapshot');
|
|
204
|
+
await first.request('sessions.create', { cwd: root });
|
|
205
|
+
const renamed = first.next((message) => message.kind === 'event' && message.event === 'session.updated');
|
|
206
|
+
session.emit({ type: 'session_info_changed', name: 'one' });
|
|
207
|
+
const renameEvent = await renamed;
|
|
208
|
+
|
|
209
|
+
// Reconnect from the rename cursor, stamping the cursor's stream epoch:
|
|
210
|
+
// the retained suffix replays without a snapshot, and the epoch is
|
|
211
|
+
// unchanged.
|
|
212
|
+
const second = connectClient(endpoint);
|
|
213
|
+
sockets.push(second);
|
|
214
|
+
await second.authenticate({ fromSequence: renameEvent.sequence, streamEpoch: snapshot.streamEpoch });
|
|
215
|
+
session.emit({ type: 'session_info_changed', name: 'two' });
|
|
216
|
+
const replayed = await second.next((message) => message.kind === 'event');
|
|
217
|
+
expect(replayed.event).toBe('session.updated');
|
|
218
|
+
expect(replayed.payload.title).toBe('two');
|
|
219
|
+
expect(replayed.streamEpoch).toBe(snapshot.streamEpoch);
|
|
220
|
+
expect(replayed.sequence).toBeGreaterThan(renameEvent.sequence);
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
it('a restart changes the epoch and a stale cursor resyncs from a lower snapshot baseline', async () => {
|
|
224
|
+
const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-epoch-'));
|
|
225
|
+
await mkdir(join(root, 'agent'), { recursive: true });
|
|
226
|
+
const firstSession = new FakeSession();
|
|
227
|
+
const first = await track(root, firstSession);
|
|
228
|
+
|
|
229
|
+
const oldClient = connectClient(first.endpoint);
|
|
230
|
+
sockets.push(oldClient);
|
|
231
|
+
await oldClient.authenticate();
|
|
232
|
+
const oldSnapshot = await oldClient.next((message) => message.kind === 'event' && message.event === 'session.snapshot');
|
|
233
|
+
await oldClient.request('sessions.create', { cwd: root });
|
|
234
|
+
const renameWait = oldClient.next((message) => message.kind === 'event' && message.event === 'session.updated');
|
|
235
|
+
firstSession.emit({ type: 'session_info_changed', name: 'before restart' });
|
|
236
|
+
const renameEvent = await renameWait;
|
|
237
|
+
expect(renameEvent.sequence).toBeGreaterThan(oldSnapshot.sequence);
|
|
238
|
+
const oldEpoch = renameEvent.streamEpoch;
|
|
239
|
+
|
|
240
|
+
// Restart: a brand new daemon process owns the endpoint's role. Its
|
|
241
|
+
// sequence space starts over, so the old epoch must differ and the old
|
|
242
|
+
// cursor must be unreplayable.
|
|
243
|
+
await oldClient.close();
|
|
244
|
+
await first.daemon.stop();
|
|
245
|
+
const secondSession = new FakeSession();
|
|
246
|
+
const second = await startDaemon(root, secondSession);
|
|
247
|
+
daemons.push(second.daemon);
|
|
248
|
+
|
|
249
|
+
const newClient = connectClient(second.endpoint);
|
|
250
|
+
sockets.push(newClient);
|
|
251
|
+
// The client stamps its cursor with the retired epoch, so the daemon can
|
|
252
|
+
// tell the sequence space reset even before looking at the numbers.
|
|
253
|
+
await newClient.authenticate({ fromSequence: renameEvent.sequence, streamEpoch: oldEpoch });
|
|
254
|
+
const resyncSnapshot = await newClient.next((message) => message.kind === 'event');
|
|
255
|
+
expect(resyncSnapshot.event).toBe('session.snapshot');
|
|
256
|
+
expect(resyncSnapshot.payload.resync).toBe(true);
|
|
257
|
+
expect(resyncSnapshot.streamEpoch).toBeTruthy();
|
|
258
|
+
expect(resyncSnapshot.streamEpoch).not.toBe(oldEpoch);
|
|
259
|
+
expect(resyncSnapshot.sequence).toBeLessThan(renameEvent.sequence);
|
|
260
|
+
expect(resyncSnapshot.payload.lastSequence).toBeLessThan(renameEvent.sequence);
|
|
261
|
+
|
|
262
|
+
// Register the restarted runtime so live session events are published.
|
|
263
|
+
await newClient.request('sessions.create', { cwd: root });
|
|
264
|
+
|
|
265
|
+
// Live events after the resync share the new epoch and grow from the
|
|
266
|
+
// lower baseline.
|
|
267
|
+
const liveWait = newClient.next((message) => message.kind === 'event' && message.event === 'session.updated');
|
|
268
|
+
secondSession.emit({ type: 'session_info_changed', name: 'after restart' });
|
|
269
|
+
const live = await liveWait;
|
|
270
|
+
expect(live.streamEpoch).toBe(resyncSnapshot.streamEpoch);
|
|
271
|
+
expect(live.sequence).toBeGreaterThan(resyncSnapshot.sequence);
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
it('rejects a replay cursor without its stream epoch as a protocol mismatch', async () => {
|
|
275
|
+
const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-epoch-'));
|
|
276
|
+
await mkdir(join(root, 'agent'), { recursive: true });
|
|
277
|
+
const session = new FakeSession();
|
|
278
|
+
const { endpoint } = await track(root, session);
|
|
279
|
+
|
|
280
|
+
const first = connectClient(endpoint);
|
|
281
|
+
sockets.push(first);
|
|
282
|
+
await first.authenticate();
|
|
283
|
+
const snapshot = await first.next((message) => message.kind === 'event' && message.event === 'session.snapshot');
|
|
284
|
+
await first.request('sessions.create', { cwd: root });
|
|
285
|
+
const renameWait = first.next((message) => message.kind === 'event' && message.event === 'session.updated');
|
|
286
|
+
session.emit({ type: 'session_info_changed', name: 'one' });
|
|
287
|
+
const renameEvent = await renameWait;
|
|
288
|
+
|
|
289
|
+
// An old client reconnects with a replayable cursor but cannot epoch-
|
|
290
|
+
// verify it (no streamEpoch marker). The daemon must reject the resume
|
|
291
|
+
// rather than silently replaying or substituting a snapshot.
|
|
292
|
+
const legacy = connectClient(endpoint);
|
|
293
|
+
sockets.push(legacy);
|
|
294
|
+
await legacy.authenticate({ fromSequence: renameEvent.sequence });
|
|
295
|
+
const legacyFrame = await legacy.next((message) => message.kind === 'error');
|
|
296
|
+
expect(legacyFrame.error).toEqual({ code: 'DAEMON_PROTOCOL_MISMATCH' });
|
|
297
|
+
expect(snapshot.streamEpoch).toBeTruthy();
|
|
298
|
+
});
|
|
299
|
+
|
|
300
|
+
it('a new daemon whose sequence overtook the old cursor resyncs instead of replaying the wrong window', async () => {
|
|
301
|
+
const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-epoch-'));
|
|
302
|
+
await mkdir(join(root, 'agent'), { recursive: true });
|
|
303
|
+
const firstSession = new FakeSession();
|
|
304
|
+
const first = await track(root, firstSession);
|
|
305
|
+
|
|
306
|
+
const oldClient = connectClient(first.endpoint);
|
|
307
|
+
sockets.push(oldClient);
|
|
308
|
+
await oldClient.authenticate();
|
|
309
|
+
await oldClient.next((message) => message.kind === 'event' && message.event === 'session.snapshot');
|
|
310
|
+
await oldClient.request('sessions.create', { cwd: root });
|
|
311
|
+
const renameWait = oldClient.next((message) => message.kind === 'event' && message.event === 'session.updated');
|
|
312
|
+
firstSession.emit({ type: 'session_info_changed', name: 'before restart' });
|
|
313
|
+
const renameEvent = await renameWait;
|
|
314
|
+
const oldEpoch = renameEvent.streamEpoch;
|
|
315
|
+
const oldCursor = renameEvent.sequence;
|
|
316
|
+
await oldClient.close();
|
|
317
|
+
await first.daemon.stop();
|
|
318
|
+
|
|
319
|
+
// The restarted daemon emits several events, so its new sequence space
|
|
320
|
+
// numerically OVERTAKES the old client's cursor before it reconnects.
|
|
321
|
+
const secondSession = new FakeSession();
|
|
322
|
+
const second = await startDaemon(root, secondSession);
|
|
323
|
+
daemons.push(second.daemon);
|
|
324
|
+
const warmup = connectClient(second.endpoint);
|
|
325
|
+
sockets.push(warmup);
|
|
326
|
+
await warmup.authenticate();
|
|
327
|
+
await warmup.request('sessions.create', { cwd: root });
|
|
328
|
+
for (let index = 0; index < Math.max(4, oldCursor + 2); index += 1) {
|
|
329
|
+
const wait = warmup.next((message) => message.kind === 'event' && message.event === 'session.updated');
|
|
330
|
+
secondSession.emit({ type: 'session_info_changed', name: `warmup-${index}` });
|
|
331
|
+
await wait;
|
|
332
|
+
}
|
|
333
|
+
const warmupState = await warmup.request('runtime.health');
|
|
334
|
+
const newEpoch = warmupState.result.streamEpoch;
|
|
335
|
+
expect(newEpoch).not.toBe(oldEpoch);
|
|
336
|
+
|
|
337
|
+
// The old cursor is numerically replayable on the new daemon, but the
|
|
338
|
+
// epoch marker proves it belongs to the retired sequence space: the
|
|
339
|
+
// daemon must resync rather than replay events 1..cursor of the new
|
|
340
|
+
// epoch the client never saw.
|
|
341
|
+
const returning = connectClient(second.endpoint);
|
|
342
|
+
sockets.push(returning);
|
|
343
|
+
await returning.authenticate({ fromSequence: oldCursor, streamEpoch: oldEpoch });
|
|
344
|
+
const resync = await returning.next((message) => message.kind === 'event');
|
|
345
|
+
expect(resync.event).toBe('session.snapshot');
|
|
346
|
+
expect(resync.payload.resync).toBe(true);
|
|
347
|
+
expect(resync.streamEpoch).toBe(newEpoch);
|
|
348
|
+
});
|
|
349
|
+
});
|
|
@@ -38,6 +38,7 @@ import { createSessionReplayLog } from './session-replay.js';
|
|
|
38
38
|
import {
|
|
39
39
|
createSendOperationRegistry,
|
|
40
40
|
isValidSendOperationId,
|
|
41
|
+
isValidStreamEpoch,
|
|
41
42
|
stableFingerprint,
|
|
42
43
|
} from './send-operation-registry.js';
|
|
43
44
|
import { resolveEffectiveRetryLimitFromDataDir as resolveEffectiveRetryLimit } from './session-retry-limits.js';
|
|
@@ -257,6 +258,13 @@ export function createSessionDaemon({
|
|
|
257
258
|
let idleDisposeTimer;
|
|
258
259
|
let dormantSession;
|
|
259
260
|
let sequence = 0;
|
|
261
|
+
// Opaque, random, public stream-lifetime identifier. It regenerates on every
|
|
262
|
+
// daemon process start (restart, crash, or replacement), so clients can
|
|
263
|
+
// distinguish "same daemon, contiguous sequence" from "new daemon, sequence
|
|
264
|
+
// restarted from zero". It is deliberately NOT derived from the daemon id,
|
|
265
|
+
// profile key, pid, or any other private identity: it exists only to be
|
|
266
|
+
// compared for equality on the public wire.
|
|
267
|
+
const streamEpoch = randomUUID().replace(/-/g, '');
|
|
260
268
|
let started = false;
|
|
261
269
|
let stopping = false;
|
|
262
270
|
const knownDirectories = new Set([cwd]);
|
|
@@ -315,14 +323,11 @@ export function createSessionDaemon({
|
|
|
315
323
|
const activeSessionInputs = new Map();
|
|
316
324
|
// Send-intent deduplication (finding #3): one stable operation id per send
|
|
317
325
|
// intent; the registry is the authoritative execution boundary before Pi.
|
|
318
|
-
// Identity is `kind + sessionId + operationId
|
|
319
|
-
//
|
|
320
|
-
//
|
|
321
|
-
//
|
|
322
|
-
|
|
323
|
-
// per-session config/acceptance lock; every claim settles so pending
|
|
324
|
-
// duplicates never hang.
|
|
325
|
-
const sendOperations = createSendOperationRegistry({ ttlMs: sendOperationTtlMs });
|
|
326
|
+
// Identity is `kind + sessionId + operationId + streamEpoch`. The epoch is
|
|
327
|
+
// checked before activation, so an intent captured before a daemon restart
|
|
328
|
+
// cannot execute in the replacement process. Retention remains bounded and
|
|
329
|
+
// in-memory; every claim settles so pending duplicates never hang.
|
|
330
|
+
const sendOperations = createSendOperationRegistry({ streamEpoch, ttlMs: sendOperationTtlMs });
|
|
326
331
|
const pendingResourceReloads = new Set();
|
|
327
332
|
const resourceReloadsByRuntime = new Map();
|
|
328
333
|
let resourceReloadQueue = Promise.resolve();
|
|
@@ -531,6 +536,7 @@ export function createSessionDaemon({
|
|
|
531
536
|
protocolVersion: PROTOCOL_VERSION,
|
|
532
537
|
kind: 'event',
|
|
533
538
|
event,
|
|
539
|
+
streamEpoch,
|
|
534
540
|
sequence: ++sequence,
|
|
535
541
|
payload: {
|
|
536
542
|
sessionId,
|
|
@@ -607,7 +613,7 @@ export function createSessionDaemon({
|
|
|
607
613
|
};
|
|
608
614
|
};
|
|
609
615
|
|
|
610
|
-
const publishSnapshot = (socket, requestedSessionId) => {
|
|
616
|
+
const publishSnapshot = (socket, requestedSessionId, { resync = false } = {}) => {
|
|
611
617
|
const targetRuntime = requestedSessionId ? runtimeRegistry?.findBySessionId(requestedSessionId) : runtime;
|
|
612
618
|
const session = targetRuntime?.session
|
|
613
619
|
? { sessionId: targetRuntime.session.sessionId, isStreaming: targetRuntime.session.isStreaming }
|
|
@@ -629,10 +635,15 @@ export function createSessionDaemon({
|
|
|
629
635
|
protocolVersion: PROTOCOL_VERSION,
|
|
630
636
|
kind: 'event',
|
|
631
637
|
event: 'session.snapshot',
|
|
638
|
+
streamEpoch,
|
|
632
639
|
sequence: snapshotSequence,
|
|
633
640
|
payload: {
|
|
634
641
|
...(session.sessionId ? { sessionId: session.sessionId } : {}),
|
|
635
642
|
directory: targetDirectory,
|
|
643
|
+
// `resync` tells the client the requested cursor could not be replayed
|
|
644
|
+
// (replay window expired or a daemon restart reset the sequence), so
|
|
645
|
+
// this snapshot is a recovery baseline rather than a routine attach.
|
|
646
|
+
...(resync ? { resync: true } : {}),
|
|
636
647
|
isStreaming: session.isStreaming ?? false,
|
|
637
648
|
lifecycle: retry ? 'retry' : session.isStreaming ? 'busy' : 'idle',
|
|
638
649
|
...(retry ? { retry } : {}),
|
|
@@ -1564,7 +1575,10 @@ export function createSessionDaemon({
|
|
|
1564
1575
|
protocolVersion: PROTOCOL_VERSION,
|
|
1565
1576
|
kind: 'response',
|
|
1566
1577
|
requestId,
|
|
1567
|
-
|
|
1578
|
+
// Stamp the stream lifetime so a client can reject a detail response
|
|
1579
|
+
// that was generated by a previous daemon process (stale sequence
|
|
1580
|
+
// space) after observing an epoch change.
|
|
1581
|
+
result: { ...detail, streamEpoch },
|
|
1568
1582
|
};
|
|
1569
1583
|
if (Buffer.byteLength(JSON.stringify(frame)) > MAX_FRAME_BYTES) {
|
|
1570
1584
|
throw new SessionDaemonProtocolError(
|
|
@@ -2744,7 +2758,15 @@ export function createSessionDaemon({
|
|
|
2744
2758
|
}
|
|
2745
2759
|
if (payload.thinking !== undefined) validateThinking(payload.thinking);
|
|
2746
2760
|
const kind = delivery ?? 'prompt';
|
|
2747
|
-
|
|
2761
|
+
if (payload.operationId !== undefined || payload.streamEpoch !== undefined) {
|
|
2762
|
+
if (!isValidStreamEpoch(payload.streamEpoch)) {
|
|
2763
|
+
throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The send stream epoch is invalid.');
|
|
2764
|
+
}
|
|
2765
|
+
if (payload.streamEpoch !== streamEpoch) {
|
|
2766
|
+
throw new SessionDaemonProtocolError('STALE_STREAM_EPOCH', 'The send belongs to a retired daemon stream epoch.');
|
|
2767
|
+
}
|
|
2768
|
+
}
|
|
2769
|
+
// Claim the stable operation id at the authoritative
|
|
2748
2770
|
// execution boundary — before Pi activation and before any attachment
|
|
2749
2771
|
// side effect. A duplicate returns the original receipt; a payload
|
|
2750
2772
|
// mismatch (same kind + session + id, different text/model/thinking/
|
|
@@ -2761,8 +2783,12 @@ export function createSessionDaemon({
|
|
|
2761
2783
|
kind,
|
|
2762
2784
|
sessionId: payload.sessionId,
|
|
2763
2785
|
operationId: payload.operationId,
|
|
2786
|
+
streamEpoch: payload.streamEpoch,
|
|
2764
2787
|
fingerprint: stableFingerprint(sendOperationFingerprint({ kind, payload })),
|
|
2765
2788
|
});
|
|
2789
|
+
if (claimed.outcome === 'stale') {
|
|
2790
|
+
throw new SessionDaemonProtocolError('STALE_STREAM_EPOCH', 'The send belongs to a retired daemon stream epoch.');
|
|
2791
|
+
}
|
|
2766
2792
|
if (claimed.outcome === 'mismatch') {
|
|
2767
2793
|
throw new SessionDaemonProtocolError('OPERATION_PAYLOAD_MISMATCH', 'This operation id was already used with a different payload.');
|
|
2768
2794
|
}
|
|
@@ -3069,7 +3095,10 @@ export function createSessionDaemon({
|
|
|
3069
3095
|
latestAssistantMessageIds.delete(sessionId);
|
|
3070
3096
|
toolInputBySession.delete(sessionId);
|
|
3071
3097
|
clearToolTimingsForSession(sessionId);
|
|
3072
|
-
|
|
3098
|
+
// Explicit typed deletion: every connected and replaying client drops
|
|
3099
|
+
// catalog, transcript, activity, and caches. Archive and directory moves
|
|
3100
|
+
// keep the session id and never publish this event.
|
|
3101
|
+
publish('session.deleted', {}, sessionId, targetDir);
|
|
3073
3102
|
};
|
|
3074
3103
|
|
|
3075
3104
|
const publishSessionEvent = (sessionId, event, directory = activeDirectory || cwd) => {
|
|
@@ -3433,7 +3462,12 @@ export function createSessionDaemon({
|
|
|
3433
3462
|
state: 'ready',
|
|
3434
3463
|
sessionId: getSessionState().sessionId,
|
|
3435
3464
|
lastSequence: sequence,
|
|
3465
|
+
streamEpoch,
|
|
3436
3466
|
capabilities: [
|
|
3467
|
+
// Public stream-lifetime identification: every event, snapshot,
|
|
3468
|
+
// and health result carries `streamEpoch`, and session read
|
|
3469
|
+
// responses stamp it so clients can reject stale-epoch data.
|
|
3470
|
+
'events.streamEpoch',
|
|
3437
3471
|
'runtime.claim', 'runtime.shutdown',
|
|
3438
3472
|
'projects.list', 'projects.select', 'sessions.list', 'sessions.create', 'sessions.open', 'sessions.messages', 'sessions.rename', 'sessions.delete',
|
|
3439
3473
|
'sessions.tree', 'sessions.navigate', 'sessions.fork', 'sessions.clone', 'sessions.prompt',
|
|
@@ -3654,7 +3688,9 @@ export function createSessionDaemon({
|
|
|
3654
3688
|
protocolVersion: PROTOCOL_VERSION,
|
|
3655
3689
|
kind: 'response',
|
|
3656
3690
|
requestId: message.requestId,
|
|
3657
|
-
|
|
3691
|
+
// Stamp the stream lifetime so clients can reject a listing that a
|
|
3692
|
+
// previous daemon process generated after an epoch change.
|
|
3693
|
+
result: { sessions, streamEpoch },
|
|
3658
3694
|
});
|
|
3659
3695
|
return;
|
|
3660
3696
|
}
|
|
@@ -3756,7 +3792,7 @@ export function createSessionDaemon({
|
|
|
3756
3792
|
}
|
|
3757
3793
|
case 'sessions.sendReceipt': {
|
|
3758
3794
|
// Exact read-only receipt lookup for an uncertain send. Requires the
|
|
3759
|
-
// full `kind + sessionId + operationId` identity; never invokes Pi,
|
|
3795
|
+
// full `kind + sessionId + operationId + streamEpoch` identity; never invokes Pi,
|
|
3760
3796
|
// never mutates the registry except bounded expiry eviction inside
|
|
3761
3797
|
// `query()`. Returns `accepted` (retained receipt), `pending`
|
|
3762
3798
|
// (still-accepting claim), `expired` (seen but retention gone —
|
|
@@ -3767,12 +3803,14 @@ export function createSessionDaemon({
|
|
|
3767
3803
|
const kind = payload.kind;
|
|
3768
3804
|
const sessionId = payload.sessionId;
|
|
3769
3805
|
const operationId = payload.operationId;
|
|
3806
|
+
const requestedEpoch = payload.streamEpoch;
|
|
3770
3807
|
if ((kind !== 'prompt' && kind !== 'steer' && kind !== 'followUp')
|
|
3771
3808
|
|| typeof sessionId !== 'string' || sessionId.length === 0
|
|
3772
|
-
|| !isValidSendOperationId(operationId)
|
|
3809
|
+
|| !isValidSendOperationId(operationId)
|
|
3810
|
+
|| (requestedEpoch !== undefined && !isValidStreamEpoch(requestedEpoch))) {
|
|
3773
3811
|
throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The send receipt lookup is invalid.');
|
|
3774
3812
|
}
|
|
3775
|
-
const lookup = sendOperations.query({ kind, sessionId, operationId });
|
|
3813
|
+
const lookup = sendOperations.query({ kind, sessionId, operationId, streamEpoch: requestedEpoch });
|
|
3776
3814
|
if (lookup.status === 'accepted') {
|
|
3777
3815
|
writeFrame(socket, {
|
|
3778
3816
|
protocolVersion: PROTOCOL_VERSION,
|
|
@@ -3902,14 +3940,37 @@ export function createSessionDaemon({
|
|
|
3902
3940
|
writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'authenticated' });
|
|
3903
3941
|
const requestedSessionId = typeof message.sessionId === 'string' && message.sessionId.length > 0 ? message.sessionId : undefined;
|
|
3904
3942
|
const fromSequence = Number.isSafeInteger(message.fromSequence) && message.fromSequence >= 0 ? message.fromSequence : undefined;
|
|
3943
|
+
// Stream-lifetime identity the client's cursor was established
|
|
3944
|
+
// under (capability negotiation). A cursor stamped with a
|
|
3945
|
+
// different epoch belongs to a retired sequence space: even when
|
|
3946
|
+
// this daemon's sequence numerically overtook it, replaying from
|
|
3947
|
+
// it would silently skip the head of the new sequence space.
|
|
3948
|
+
// Subscribers without the marker cannot prove which sequence
|
|
3949
|
+
// space their cursor belongs to. Reject that shape instead of
|
|
3950
|
+
// silently treating it as a valid resume.
|
|
3951
|
+
const requestedEpoch = typeof message.streamEpoch === 'string' && message.streamEpoch.length > 0 && message.streamEpoch.length <= 128
|
|
3952
|
+
? message.streamEpoch
|
|
3953
|
+
: undefined;
|
|
3954
|
+
if (fromSequence !== undefined && requestedEpoch === undefined) {
|
|
3955
|
+
throw new SessionDaemonProtocolError(
|
|
3956
|
+
'DAEMON_PROTOCOL_MISMATCH',
|
|
3957
|
+
'A replay cursor requires its stream epoch.',
|
|
3958
|
+
);
|
|
3959
|
+
}
|
|
3960
|
+
const epochMismatch = requestedEpoch !== undefined && requestedEpoch !== streamEpoch;
|
|
3905
3961
|
// Contiguity is judged on the global retained suffix while delivery
|
|
3906
3962
|
// stays session-filtered, so a filtered client never replays through
|
|
3907
3963
|
// a gap left by eviction, an oversized event, an empty ring, or a
|
|
3908
3964
|
// future cursor: all of those take the snapshot fallback below.
|
|
3909
|
-
|
|
3965
|
+
// Replay additionally requires the epoch marker. The validation
|
|
3966
|
+
// above rejects a cursor that cannot be tied to an epoch.
|
|
3967
|
+
if (fromSequence !== undefined && requestedEpoch !== undefined && !epochMismatch && replayLog.canReplay(fromSequence, sequence)) {
|
|
3910
3968
|
for (const cachedLine of replayLog.linesAfter(fromSequence, requestedSessionId)) writeLine(socket, cachedLine);
|
|
3911
3969
|
} else {
|
|
3912
|
-
|
|
3970
|
+
// A supplied cursor that cannot be replayed is a resync: the
|
|
3971
|
+
// snapshot is the client's recovery baseline for a missed replay
|
|
3972
|
+
// window, a daemon restart, or a cursor from a retired epoch.
|
|
3973
|
+
publishSnapshot(socket, requestedSessionId, { resync: fromSequence !== undefined || epochMismatch === true });
|
|
3913
3974
|
}
|
|
3914
3975
|
continue;
|
|
3915
3976
|
}
|
|
@@ -195,12 +195,12 @@ function connectClient(endpoint) {
|
|
|
195
195
|
|
|
196
196
|
return {
|
|
197
197
|
socket,
|
|
198
|
-
async authenticate(value = credential, { sessionId, fromSequence } = {}) {
|
|
198
|
+
async authenticate(value = credential, { sessionId, fromSequence, streamEpoch } = {}) {
|
|
199
199
|
await new Promise((resolve, reject) => {
|
|
200
200
|
socket.once('connect', resolve);
|
|
201
201
|
socket.once('error', reject);
|
|
202
202
|
});
|
|
203
|
-
socket.write(`${JSON.stringify({ kind: 'authenticate', credential: value, ...(sessionId ? { sessionId } : {}), ...(fromSequence !== undefined ? { fromSequence } : {}) })}\n`);
|
|
203
|
+
socket.write(`${JSON.stringify({ kind: 'authenticate', credential: value, ...(sessionId ? { sessionId } : {}), ...(fromSequence !== undefined ? { fromSequence } : {}), ...(streamEpoch ? { streamEpoch } : {}) })}\n`);
|
|
204
204
|
await next((message) => message.kind === 'authenticated');
|
|
205
205
|
if (fromSequence !== undefined) return undefined;
|
|
206
206
|
return next((message) => message.kind === 'event' && message.event === 'session.snapshot');
|
|
@@ -378,12 +378,12 @@ describe('Pi session daemon spike', () => {
|
|
|
378
378
|
await first.close();
|
|
379
379
|
|
|
380
380
|
const replay = connectClient(endpoint);
|
|
381
|
-
await replay.authenticate(credential, { sessionId: 'pi-session-1', fromSequence: snapshot.sequence });
|
|
381
|
+
await replay.authenticate(credential, { sessionId: 'pi-session-1', fromSequence: snapshot.sequence, streamEpoch: snapshot.streamEpoch });
|
|
382
382
|
await expect(replay.next((frame) => frame.event === 'assistant.message.delta')).resolves.toMatchObject({ sequence: delta.sequence, payload: { delta: 'replay' } });
|
|
383
383
|
await replay.close();
|
|
384
384
|
|
|
385
385
|
const stale = connectClient(endpoint);
|
|
386
|
-
await stale.authenticate(credential, { sessionId: 'pi-session-1', fromSequence: 0 });
|
|
386
|
+
await stale.authenticate(credential, { sessionId: 'pi-session-1', fromSequence: 0, streamEpoch: snapshot.streamEpoch });
|
|
387
387
|
await expect(stale.next((frame) => frame.event === 'session.snapshot')).resolves.toMatchObject({ payload: { lastSequence: expect.any(Number) } });
|
|
388
388
|
await stale.close();
|
|
389
389
|
});
|
|
@@ -418,6 +418,7 @@ describe('Pi session daemon spike', () => {
|
|
|
418
418
|
await late.authenticate(credential, {
|
|
419
419
|
sessionId: 'pi-session-1',
|
|
420
420
|
fromSequence: detail.result.lastSequence,
|
|
421
|
+
streamEpoch: detail.result.streamEpoch,
|
|
421
422
|
});
|
|
422
423
|
const firstDelta = first.next((frame) => frame.event === 'assistant.message.delta');
|
|
423
424
|
const lateDelta = late.next((frame) => frame.event === 'assistant.message.delta');
|
|
@@ -447,6 +448,7 @@ describe('Pi session daemon spike', () => {
|
|
|
447
448
|
await resumed.authenticate(credential, {
|
|
448
449
|
sessionId: 'pi-session-1',
|
|
449
450
|
fromSequence: lateDeltaFrame.sequence,
|
|
451
|
+
streamEpoch: detail.result.streamEpoch,
|
|
450
452
|
});
|
|
451
453
|
const resumedEndFrame = await resumed.next((frame) => frame.event === 'assistant.message.end');
|
|
452
454
|
expect(resumedEndFrame.sequence).toBe(firstEndFrame.sequence);
|
|
@@ -1229,7 +1231,11 @@ describe('Pi session daemon spike', () => {
|
|
|
1229
1231
|
await expect(client.request('sessions.abort', { sessionId: 'pi-session-forked' })).resolves.toMatchObject({ result: {} });
|
|
1230
1232
|
expect(runtime.session.aborted).toBe(1);
|
|
1231
1233
|
runtime.session.isStreaming = false;
|
|
1234
|
+
const deletedEvent = client.next((frame) => frame.event === 'session.deleted');
|
|
1232
1235
|
await expect(client.request('sessions.delete', { sessionId: 'pi-session-forked' })).resolves.toMatchObject({ result: {} });
|
|
1236
|
+
await expect(deletedEvent).resolves.toMatchObject({
|
|
1237
|
+
payload: { sessionId: 'pi-session-forked', directory: root },
|
|
1238
|
+
});
|
|
1233
1239
|
await client.close();
|
|
1234
1240
|
});
|
|
1235
1241
|
|
|
@@ -155,7 +155,7 @@ function connectDaemonClient(endpoint) {
|
|
|
155
155
|
socket,
|
|
156
156
|
messages,
|
|
157
157
|
waitForMessage,
|
|
158
|
-
async authenticate(credentialOverride = credential, { sessionId, fromSequence } = {}) {
|
|
158
|
+
async authenticate(credentialOverride = credential, { sessionId, fromSequence, streamEpoch } = {}) {
|
|
159
159
|
await new Promise((resolve, reject) => {
|
|
160
160
|
if (socket.connecting === false && socket.pending === false) {
|
|
161
161
|
return resolve();
|
|
@@ -168,6 +168,7 @@ function connectDaemonClient(endpoint) {
|
|
|
168
168
|
credential: credentialOverride,
|
|
169
169
|
...(sessionId ? { sessionId } : {}),
|
|
170
170
|
...(fromSequence !== undefined ? { fromSequence } : {}),
|
|
171
|
+
...(streamEpoch ? { streamEpoch } : {}),
|
|
171
172
|
};
|
|
172
173
|
socket.write(`${JSON.stringify(frame)}\n`);
|
|
173
174
|
await waitForMessage((message) => message.kind === 'authenticated');
|
|
@@ -327,20 +328,24 @@ describe('session replay log bounds', () => {
|
|
|
327
328
|
|
|
328
329
|
describe('daemon byte-bounded reconnect', () => {
|
|
329
330
|
let daemon;
|
|
331
|
+
let latestEpoch;
|
|
330
332
|
const temporaryRoots = [];
|
|
331
333
|
const connectedClients = new Set();
|
|
332
334
|
|
|
333
335
|
const connectLiveClient = async (endpoint) => {
|
|
334
336
|
const client = connectDaemonClient(endpoint);
|
|
335
337
|
connectedClients.add(client);
|
|
336
|
-
await client.authenticate();
|
|
338
|
+
const snapshot = await client.authenticate();
|
|
339
|
+
// Track the live daemon epoch so resuming clients can stamp their cursor
|
|
340
|
+
// (replay requires the stream-epoch marker).
|
|
341
|
+
latestEpoch = snapshot.streamEpoch;
|
|
337
342
|
return client;
|
|
338
343
|
};
|
|
339
344
|
|
|
340
345
|
const connectResumingClient = async (endpoint, fromSequence) => {
|
|
341
346
|
const client = connectDaemonClient(endpoint);
|
|
342
347
|
connectedClients.add(client);
|
|
343
|
-
await client.authenticate(credential, { sessionId: 'pi-session-1', fromSequence });
|
|
348
|
+
await client.authenticate(credential, { sessionId: 'pi-session-1', fromSequence, streamEpoch: latestEpoch });
|
|
344
349
|
return client;
|
|
345
350
|
};
|
|
346
351
|
|