@pi-chamber/web 0.9.5 → 0.9.7
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/dist/assets/DiagramView-BvrCkm_z.js +1 -0
- package/dist/assets/{DiffView-BmIVvheE.js → DiffView-DMvRLRN1.js} +1 -1
- package/dist/assets/FileSaveConflictDialog-DGa9u43J.js +3 -0
- package/dist/assets/FilesView-CNHu4RnC.js +6 -0
- package/dist/assets/{GitView-BNkzec7G.js → GitView-Cbepz-bR.js} +3 -3
- package/dist/assets/{JsonTreeView-C1Kzaybf.js → JsonTreeView-C2X5oXQm.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-qmKiFVpO.js → MarkdownRendererImpl-BanSCkPy.js} +2 -2
- package/dist/assets/{PatchDiff-D9JesZL1.js → PatchDiff-i_9BIlgo.js} +1 -1
- package/dist/assets/{SessionSwitcherContent-DplV_ApH.js → SessionSwitcherContent-DxS_rFuS.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-DdgDKT6K.js → SessionSwitcherDropdown-AVghToww.js} +2 -2
- package/dist/assets/{SessionUnreadDot-BdSDgvhC.js → SessionUnreadDot-CDRZswx-.js} +1 -1
- package/dist/assets/SettingsView-hyAGp836.js +2 -0
- package/dist/assets/SettingsWindow-BfPUzBbq.js +1 -0
- package/dist/assets/{ToolOutputDialog-DaF1xcM0.js → ToolOutputDialog-CJ87b80H.js} +5 -5
- package/dist/assets/{ToolPartDiffPreview-Di6Uo0Dt.js → ToolPartDiffPreview-bF486Lz1.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-wqcrY0yr.js → VirtualizedFileDiff-CFpvcZ1g.js} +1 -1
- package/dist/assets/{collapsible-DBQnXTNm.js → collapsible-DesjbW8a.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-Cr3jh0d6.js → computeVirtualFileMetrics-CsAu9rOt.js} +2 -2
- package/dist/assets/{contextFileOpenGuard-C_AOTYQD.js → contextFileOpenGuard-rILslsBJ.js} +1 -1
- package/dist/assets/{gitStatusPredicates-BvPOjeOy.js → gitStatusPredicates-D_31YElh.js} +1 -1
- package/dist/assets/index-BXgR2dKM.css +1 -0
- package/dist/assets/index-BZpvAhrX.js +8 -0
- package/dist/assets/{index-B8Wt2aN3.js → index-CXLVW_GG.js} +1 -1
- package/dist/assets/{isDiffPlainText-L9uvgz2F.js → isDiffPlainText-BX609Lau.js} +1 -1
- package/dist/assets/{isFilePlainText-C4yk5BOo.js → isFilePlainText-FgBWqu9b.js} +1 -1
- package/dist/assets/{main-DCK6lLCo.js → main-C_pL2r_k.js} +2 -2
- package/dist/assets/{main-C1OSzD-E.js → main-tv2uysSs.js} +7 -7
- package/dist/assets/{markdownCore-Czb_lINQ.js → markdownCore-D3Ibaffd.js} +1 -1
- package/dist/assets/{miniChat-CXiSlptL.js → miniChat-B0xQlBzZ.js} +2 -2
- package/dist/assets/{mobile-D0HVxiyJ.js → mobile-BmSlVuhn.js} +2 -2
- package/dist/assets/renderElectronMiniChatApp-C4xZzAnn.js +2 -0
- package/dist/assets/renderMobileApp-Bi8wTGd5.js +11 -0
- package/dist/assets/runtimeEndpointReset-B6_gFvBD.js +53 -0
- package/dist/assets/{runtimeSurface-vilE4xyj.js → runtimeSurface-egSD9pqj.js} +1 -1
- package/dist/assets/{useAppFontEffects-BP07Vl6M.js → useAppFontEffects-C9QQrBIx.js} +104 -104
- package/dist/assets/useFilesViewSearch-BTZutbn-.js +7 -0
- package/dist/assets/{usePushVisibilityBeacon-CChMvoTL.js → usePushVisibilityBeacon-BZcHxSo-.js} +1 -1
- package/dist/assets/useSwitcherItems-Dw5tHQh8.js +1 -0
- package/dist/assets/{vendor-codemirror-language-data-BJrrV83E.js → vendor-codemirror-language-data-0f_rLdj_.js} +2 -2
- package/dist/assets/{web-components-B5sMa_kC.js → web-components-CYngz9Ml.js} +1 -1
- 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/fs/DOCUMENTATION.md +15 -3
- package/server/lib/fs/routes.js +369 -51
- package/server/lib/fs/routes.test.js +565 -3
- package/server/lib/fs/search.js +74 -29
- 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 +132 -28
- package/server/lib/pi/routes.test.js +213 -4
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +6 -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-operations.test.js +9 -3
- package/server/lib/pi/session-daemon/prompt-preflight.test.js +556 -0
- package/server/lib/pi/session-daemon/send-operation-dedup.test.js +331 -0
- package/server/lib/pi/session-daemon/send-operation-registry.js +264 -0
- package/server/lib/pi/session-daemon/send-operation-registry.test.js +205 -0
- package/server/lib/pi/session-daemon/session-daemon-epoch.test.js +349 -0
- package/server/lib/pi/session-daemon/session-daemon-extensions.e2e.test.js +16 -5
- package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +3 -1
- package/server/lib/pi/session-daemon/session-daemon.js +339 -37
- package/server/lib/pi/session-daemon/session-daemon.test.js +47 -17
- package/server/lib/pi/session-daemon/session-idle-residency.test.js +8 -1
- package/server/lib/pi/session-daemon/session-replay.test.js +11 -4
- 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 +1 -1
- package/server/lib/pi/ui-settings-store.test.js +3 -1
- package/server/lib/server/core-routes.js +11 -1
- package/server/lib/server/cors.js +6 -0
- package/server/lib/server/cors.test.js +3 -0
- 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 +9 -3
- package/server/lib/workspace/host.test.js +15 -0
- package/dist/assets/DiagramEditor-BPDkGHsj.js +0 -1
- package/dist/assets/DiagramView-D_EfDz2d.js +0 -1
- package/dist/assets/FilesView-CJytSUAX.js +0 -6
- package/dist/assets/SettingsView-z8uf0XyM.js +0 -2
- package/dist/assets/SettingsWindow-CPDmgNg2.js +0 -1
- package/dist/assets/index-DIF8b4bh.css +0 -1
- package/dist/assets/index-jrfQYSvP.js +0 -8
- package/dist/assets/renderElectronMiniChatApp-BcG209a4.js +0 -2
- package/dist/assets/renderMobileApp-B5x_PWlc.js +0 -11
- package/dist/assets/runtimeEndpointReset-CUiPe6dQ.js +0 -53
- package/dist/assets/useFilesViewSearch-oxIKk-ea.js +0 -7
- package/dist/assets/useSwitcherItems-_RSo3F-A.js +0 -1
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
createSendOperationRegistry,
|
|
5
|
+
isValidSendOperationId,
|
|
6
|
+
stableFingerprint,
|
|
7
|
+
} from './send-operation-registry.js';
|
|
8
|
+
|
|
9
|
+
describe('send operation registry', () => {
|
|
10
|
+
const baseClaim = {
|
|
11
|
+
kind: 'prompt',
|
|
12
|
+
sessionId: 'sess-1',
|
|
13
|
+
operationId: 'op-1',
|
|
14
|
+
fingerprint: '{"text":"hello"}',
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
it('accepts a new claim and settles the acceptance receipt', () => {
|
|
18
|
+
const registry = createSendOperationRegistry();
|
|
19
|
+
const claim = registry.claim(baseClaim);
|
|
20
|
+
expect(claim.outcome).toBe('new');
|
|
21
|
+
claim.entry.settle({ accepted: true, receipt: { accepted: true, messageId: 'msg-1' } });
|
|
22
|
+
const retry = registry.claim(baseClaim);
|
|
23
|
+
expect(retry.outcome).toBe('accepted');
|
|
24
|
+
expect(retry.receipt).toEqual({ accepted: true, messageId: 'msg-1' });
|
|
25
|
+
expect(retry.deduplicated).toBe(true);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it('shares the original receipt with a concurrent pending duplicate', async () => {
|
|
29
|
+
const registry = createSendOperationRegistry();
|
|
30
|
+
const first = registry.claim(baseClaim);
|
|
31
|
+
expect(first.outcome).toBe('new');
|
|
32
|
+
|
|
33
|
+
const duplicate = registry.claim(baseClaim);
|
|
34
|
+
expect(duplicate.outcome).toBe('pending');
|
|
35
|
+
|
|
36
|
+
const duplicateResult = duplicate.settled.then((result) => result);
|
|
37
|
+
first.entry.settle({ accepted: true, receipt: { accepted: true, messageId: 'msg-original' } });
|
|
38
|
+
await expect(duplicateResult).resolves.toEqual({
|
|
39
|
+
accepted: true,
|
|
40
|
+
receipt: { accepted: true, messageId: 'msg-original' },
|
|
41
|
+
});
|
|
42
|
+
// The late duplicate resolves against the retained receipt afterwards.
|
|
43
|
+
expect(registry.claim(baseClaim).outcome).toBe('accepted');
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it('shares the original rejection with a concurrent pending duplicate and frees the id', async () => {
|
|
47
|
+
const registry = createSendOperationRegistry();
|
|
48
|
+
const first = registry.claim(baseClaim);
|
|
49
|
+
const duplicate = registry.claim(baseClaim);
|
|
50
|
+
expect(duplicate.outcome).toBe('pending');
|
|
51
|
+
|
|
52
|
+
first.entry.settle({ accepted: false, error: new Error('busy') });
|
|
53
|
+
await expect(duplicate.settled).rejects.toThrow('busy');
|
|
54
|
+
// A rejection happened before Pi ran, so the id is free for a retry.
|
|
55
|
+
expect(registry.claim(baseClaim).outcome).toBe('new');
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('rejects a payload mismatch for the same id', () => {
|
|
59
|
+
const registry = createSendOperationRegistry();
|
|
60
|
+
const first = registry.claim(baseClaim);
|
|
61
|
+
first.entry.settle({ accepted: true, receipt: { accepted: true, messageId: 'msg-1' } });
|
|
62
|
+
expect(registry.claim({ ...baseClaim, fingerprint: '{"text":"different"}' }).outcome).toBe('mismatch');
|
|
63
|
+
expect(registry.claim({ ...baseClaim, kind: 'steer' }).outcome).toBe('new');
|
|
64
|
+
expect(registry.claim({ ...baseClaim, sessionId: 'sess-2' }).outcome).toBe('new');
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it('expires accepted receipts after the ttl so the same id can never auto-replay', () => {
|
|
68
|
+
let time = 1_000;
|
|
69
|
+
const registry = createSendOperationRegistry({ now: () => time, ttlMs: 50 });
|
|
70
|
+
const claim = registry.claim(baseClaim);
|
|
71
|
+
claim.entry.settle({ accepted: true, receipt: { accepted: true, messageId: 'msg-1' } });
|
|
72
|
+
expect(registry.claim(baseClaim).outcome).toBe('accepted');
|
|
73
|
+
|
|
74
|
+
time += 49;
|
|
75
|
+
expect(registry.claim(baseClaim).outcome).toBe('accepted');
|
|
76
|
+
time += 2;
|
|
77
|
+
// Retention gone: the same id is rejected as expired (never a silent
|
|
78
|
+
// re-execution). Callers must use a new operation id after expiry.
|
|
79
|
+
expect(registry.claim(baseClaim).outcome).toBe('expired');
|
|
80
|
+
expect(registry.query({ kind: 'prompt', sessionId: 'sess-1', operationId: 'op-1' }).status).toBe('expired');
|
|
81
|
+
// A distinct id is still a distinct intent and executes.
|
|
82
|
+
expect(registry.claim({ ...baseClaim, operationId: 'op-2' }).outcome).toBe('new');
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it('bounds retention by evicting the oldest accepted receipts', () => {
|
|
86
|
+
const registry = createSendOperationRegistry({ maxEntries: 2 });
|
|
87
|
+
const one = registry.claim({ ...baseClaim, operationId: 'op-1' });
|
|
88
|
+
one.entry.settle({ accepted: true, receipt: { accepted: true, messageId: 'm1' } });
|
|
89
|
+
const two = registry.claim({ ...baseClaim, operationId: 'op-2' });
|
|
90
|
+
two.entry.settle({ accepted: true, receipt: { accepted: true, messageId: 'm2' } });
|
|
91
|
+
const three = registry.claim({ ...baseClaim, operationId: 'op-3' });
|
|
92
|
+
three.entry.settle({ accepted: true, receipt: { accepted: true, messageId: 'm3' } });
|
|
93
|
+
|
|
94
|
+
// Evicted acceptances leave an expired tombstone: never a false
|
|
95
|
+
// acceptance and never an automatic re-execution with the same id.
|
|
96
|
+
expect(registry.claim({ ...baseClaim, operationId: 'op-1' }).outcome).toBe('expired');
|
|
97
|
+
expect(registry.claim({ ...baseClaim, operationId: 'op-2' }).outcome).toBe('accepted');
|
|
98
|
+
expect(registry.claim({ ...baseClaim, operationId: 'op-3' }).outcome).toBe('accepted');
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it('never evicts a pending claim so concurrent duplicates keep sharing the outcome', () => {
|
|
102
|
+
const registry = createSendOperationRegistry({ maxEntries: 2 });
|
|
103
|
+
const pending = registry.claim({ ...baseClaim, operationId: 'op-pending' });
|
|
104
|
+
expect(pending.outcome).toBe('new');
|
|
105
|
+
for (let index = 0; index < 5; index += 1) {
|
|
106
|
+
const claim = registry.claim({ ...baseClaim, operationId: `op-fill-${index}` });
|
|
107
|
+
claim.entry.settle({ accepted: true, receipt: { accepted: true, messageId: `m-${index}` } });
|
|
108
|
+
}
|
|
109
|
+
const duplicate = registry.claim({ ...baseClaim, operationId: 'op-pending' });
|
|
110
|
+
expect(duplicate.outcome).toBe('pending');
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it('produces order-independent stable fingerprints', () => {
|
|
114
|
+
expect(stableFingerprint({ a: 1, b: 'x' })).toBe(stableFingerprint({ b: 'x', a: 1 }));
|
|
115
|
+
expect(stableFingerprint({ a: 1 })).not.toBe(stableFingerprint({ a: 2 }));
|
|
116
|
+
expect(stableFingerprint({ a: undefined })).toBe(stableFingerprint({}));
|
|
117
|
+
expect(stableFingerprint(['x', 1])).toBe(stableFingerprint(['x', 1]));
|
|
118
|
+
expect(stableFingerprint(null)).toBe('null');
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it('validates operation ids without wildcard or control characters', () => {
|
|
122
|
+
expect(isValidSendOperationId('op_1')).toBe(true);
|
|
123
|
+
expect(isValidSendOperationId('qm:abc.def-2')).toBe(true);
|
|
124
|
+
expect(isValidSendOperationId('')).toBe(false);
|
|
125
|
+
expect(isValidSendOperationId('-leading-symbol')).toBe(false);
|
|
126
|
+
expect(isValidSendOperationId('has spaces')).toBe(false);
|
|
127
|
+
expect(isValidSendOperationId(`x${'y'.repeat(128)}`)).toBe(false);
|
|
128
|
+
expect(isValidSendOperationId(undefined)).toBe(false);
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
it('query() distinguishes pending, accepted, unknown, and expired with no false acceptance', () => {
|
|
132
|
+
let time = 1_000;
|
|
133
|
+
const registry = createSendOperationRegistry({ now: () => time, ttlMs: 50, maxEntries: 10 });
|
|
134
|
+
const key = { kind: 'prompt', sessionId: 'sess-1', operationId: 'op-q' };
|
|
135
|
+
expect(registry.query(key).status).toBe('unknown');
|
|
136
|
+
|
|
137
|
+
const fresh = registry.claim({ kind: 'prompt', sessionId: 'sess-1', operationId: 'op-q', fingerprint: baseClaim.fingerprint });
|
|
138
|
+
expect(fresh.outcome).toBe('new');
|
|
139
|
+
expect(registry.query(key).status).toBe('pending');
|
|
140
|
+
|
|
141
|
+
fresh.entry.settle({ accepted: true, receipt: { accepted: true, messageId: 'm1' } });
|
|
142
|
+
expect(registry.query(key)).toMatchObject({ status: 'accepted', receipt: { accepted: true, messageId: 'm1' } });
|
|
143
|
+
|
|
144
|
+
// Exact identity: wrong kind/session/operation is unknown, never accepted.
|
|
145
|
+
expect(registry.query({ ...key, kind: 'steer' }).status).toBe('unknown');
|
|
146
|
+
expect(registry.query({ ...key, sessionId: 'sess-2' }).status).toBe('unknown');
|
|
147
|
+
expect(registry.query({ ...key, operationId: 'op-other' }).status).toBe('unknown');
|
|
148
|
+
|
|
149
|
+
time += 51;
|
|
150
|
+
// After TTL the receipt is gone: expired, never a stale acceptance.
|
|
151
|
+
expect(registry.query(key).status).toBe('expired');
|
|
152
|
+
expect(registry.query(key).receipt).toBeUndefined();
|
|
153
|
+
// A retry after expiry is rejected as expired — it must not
|
|
154
|
+
// automatically re-execute. The caller needs a new operation id.
|
|
155
|
+
const retry = registry.claim({ kind: 'prompt', sessionId: 'sess-1', operationId: 'op-q', fingerprint: baseClaim.fingerprint });
|
|
156
|
+
expect(retry.outcome).toBe('expired');
|
|
157
|
+
expect(registry.query(key).status).toBe('expired');
|
|
158
|
+
expect(registry.query(key).receipt).toBeUndefined();
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
it('rejections before Pi leave no tombstone while evicted acceptances expire', () => {
|
|
162
|
+
const registry = createSendOperationRegistry({ maxEntries: 2 });
|
|
163
|
+
const rejected = registry.claim({ ...baseClaim, operationId: 'op-reject' });
|
|
164
|
+
rejected.entry.settle({ accepted: false, error: new Error('busy') });
|
|
165
|
+
// Nothing executed: unknown (reusable), not expired.
|
|
166
|
+
expect(registry.query({ kind: 'prompt', sessionId: 'sess-1', operationId: 'op-reject' }).status).toBe('unknown');
|
|
167
|
+
|
|
168
|
+
const one = registry.claim({ ...baseClaim, operationId: 'op-1' });
|
|
169
|
+
one.entry.settle({ accepted: true, receipt: { accepted: true, messageId: 'm1' } });
|
|
170
|
+
const two = registry.claim({ ...baseClaim, operationId: 'op-2' });
|
|
171
|
+
two.entry.settle({ accepted: true, receipt: { accepted: true, messageId: 'm2' } });
|
|
172
|
+
const three = registry.claim({ ...baseClaim, operationId: 'op-3' });
|
|
173
|
+
three.entry.settle({ accepted: true, receipt: { accepted: true, messageId: 'm3' } });
|
|
174
|
+
// Oldest acceptance evicted: expired tombstone, never a false acceptance.
|
|
175
|
+
expect(registry.query({ kind: 'prompt', sessionId: 'sess-1', operationId: 'op-1' }).status).toBe('expired');
|
|
176
|
+
expect(registry.query({ kind: 'prompt', sessionId: 'sess-1', operationId: 'op-2' }).status).toBe('accepted');
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
it('never expires an active pending claim so duplicates cannot double-execute', async () => {
|
|
180
|
+
let time = 1_000;
|
|
181
|
+
const registry = createSendOperationRegistry({ now: () => time, pendingTtlMs: 20, maxEntries: 4, maxPending: 2 });
|
|
182
|
+
const first = registry.claim({ ...baseClaim, operationId: 'op-leak-1' });
|
|
183
|
+
const second = registry.claim({ ...baseClaim, operationId: 'op-leak-2' });
|
|
184
|
+
expect(first.outcome).toBe('new');
|
|
185
|
+
expect(second.outcome).toBe('new');
|
|
186
|
+
// Pending bound: a third distinct pending claim is overloaded, never executed.
|
|
187
|
+
expect(registry.claim({ ...baseClaim, operationId: 'op-leak-3' }).outcome).toBe('overloaded');
|
|
188
|
+
time += 21;
|
|
189
|
+
// Active ownership survives past pendingTtlMs: expiring here would let a
|
|
190
|
+
// duplicate re-execute the same operation, so duplicates still share.
|
|
191
|
+
expect(registry.claim({ ...baseClaim, operationId: 'op-leak-1' }).outcome).toBe('pending');
|
|
192
|
+
expect(registry.query({ kind: 'prompt', sessionId: 'sess-1', operationId: 'op-leak-1' }).status).toBe('pending');
|
|
193
|
+
expect(registry.claim({ ...baseClaim, operationId: 'op-after' }).outcome).toBe('overloaded');
|
|
194
|
+
// Settling frees the slot: a busy rejection shares with its duplicate
|
|
195
|
+
// and leaves the id reusable (nothing executed).
|
|
196
|
+
const duplicate = registry.claim({ ...baseClaim, operationId: 'op-leak-1' });
|
|
197
|
+
expect(duplicate.outcome).toBe('pending');
|
|
198
|
+
first.entry.settle({ accepted: false, error: Object.assign(new Error('busy'), { code: 'SESSION_BUSY' }) });
|
|
199
|
+
await expect(duplicate.settled).rejects.toMatchObject({ code: 'SESSION_BUSY' });
|
|
200
|
+
expect(registry.query({ kind: 'prompt', sessionId: 'sess-1', operationId: 'op-leak-1' }).status).toBe('unknown');
|
|
201
|
+
expect(registry.claim({ ...baseClaim, operationId: 'op-leak-1' }).outcome).toBe('new');
|
|
202
|
+
expect(registry.pendingSize).toBeLessThanOrEqual(2);
|
|
203
|
+
expect(registry.expiredSize).toBeLessThanOrEqual(4);
|
|
204
|
+
});
|
|
205
|
+
});
|
|
@@ -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
|
+
});
|
|
@@ -149,7 +149,11 @@ describe('pi extensions end-to-end through the real SDK', () => {
|
|
|
149
149
|
expect(list.result.commands.map((command) => command.name)).toContain('demo-dialog');
|
|
150
150
|
|
|
151
151
|
// Invoke the extension command: it blocks on a dialog over the stream.
|
|
152
|
-
|
|
152
|
+
// True preflight acceptance for extension commands fires after the command
|
|
153
|
+
// handler completes (post-dialog), so the prompt request stays open while
|
|
154
|
+
// the dialog is answered on a separate connection — matching production
|
|
155
|
+
// where each HTTP route uses its own daemon socket.
|
|
156
|
+
const dialogPrompt = client.request('sessions.prompt', {
|
|
153
157
|
sessionId: created.result.session.id,
|
|
154
158
|
text: '/demo-dialog',
|
|
155
159
|
});
|
|
@@ -160,10 +164,17 @@ describe('pi extensions end-to-end through the real SDK', () => {
|
|
|
160
164
|
const settled = client.next((message) => message.kind === 'event'
|
|
161
165
|
&& message.event === 'session.lifecycle'
|
|
162
166
|
&& message.payload.state === 'idle');
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
+
const respondClient = connectClient(endpoint);
|
|
168
|
+
await respondClient.authenticate();
|
|
169
|
+
try {
|
|
170
|
+
await respondClient.request('extensions.respond', {
|
|
171
|
+
requestId: dialog.payload.requestId,
|
|
172
|
+
confirmed: true,
|
|
173
|
+
});
|
|
174
|
+
} finally {
|
|
175
|
+
await respondClient.close().catch(() => {});
|
|
176
|
+
}
|
|
177
|
+
await dialogPrompt;
|
|
167
178
|
|
|
168
179
|
// Extension saw the answer and emitted its GUI card + custom message.
|
|
169
180
|
const card = await client.next((message) => message.kind === 'event' && message.event === 'extension.entry');
|