@pi-chamber/web 0.9.4 → 0.9.6
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 +15 -0
- package/dist/assets/DiagramView-0Iq1ak1I.js +1 -0
- package/dist/assets/{DiffView-CBOrV4hS.js → DiffView-DD1AFRi3.js} +2 -2
- package/dist/assets/FileSaveConflictDialog-CoKwDovb.js +3 -0
- package/dist/assets/FilesView-B_BF39ef.js +6 -0
- package/dist/assets/GitView-LFEpCasf.js +8 -0
- package/dist/assets/{JsonTreeView-CKWGm5MS.js → JsonTreeView-Cwjgvh4g.js} +1 -1
- package/dist/assets/MarkdownRendererImpl-_7kV1yNw.js +12 -0
- package/dist/assets/PatchDiff-DG43C1HW.js +1 -0
- package/dist/assets/{SessionSwitcherContent-z9VYCXrT.js → SessionSwitcherContent-DCFXPY3d.js} +1 -1
- package/dist/assets/SessionSwitcherDropdown-QY7FKuEQ.js +2 -0
- package/dist/assets/SessionUnreadDot-DGT31A3z.js +1 -0
- package/dist/assets/SettingsView-eG-wN-yY.js +2 -0
- package/dist/assets/SettingsWindow-Dvnp8YrA.js +1 -0
- package/dist/assets/ToolOutputDialog-IlCrS6BR.js +8 -0
- package/dist/assets/ToolPartDiffPreview-D68JV0rR.js +1 -0
- package/dist/assets/{VirtualizedFileDiff-DfaXovGB.js → VirtualizedFileDiff-Bl-rAYeh.js} +3 -3
- package/dist/assets/collapsible-BjniCdZ5.js +1 -0
- package/dist/assets/computeVirtualFileMetrics-FSOm2VrW.js +3 -0
- package/dist/assets/contextFileOpenGuard-Bxb6AIPa.js +1 -0
- package/dist/assets/gitStatusPredicates-DxolDpMd.js +134 -0
- package/dist/assets/index-BpmGBboM.css +1 -0
- package/dist/assets/index-DZnzXhTs.js +8 -0
- package/dist/assets/index-Dh58uD3I.js +1 -0
- package/dist/assets/isDiffPlainText-D3_04XCh.js +1 -0
- package/dist/assets/isFilePlainText-CHouYQhH.js +1 -0
- package/dist/assets/{main-DG1oZ0Wj.js → main-CH3EqGJI.js} +2 -2
- package/dist/assets/main-HzTrVvbB.js +135 -0
- package/dist/assets/{markdownCore-DUjQU2i0.js → markdownCore-DJU4KvHP.js} +2 -2
- package/dist/assets/{miniChat-BEAtOkr9.js → miniChat-Ca3TpaaA.js} +2 -2
- package/dist/assets/{mobile-DOFBBQg2.js → mobile-lj4gpGsO.js} +2 -2
- package/dist/assets/renderElectronMiniChatApp-rUFfaD-T.js +2 -0
- package/dist/assets/renderMobileApp-CcWQ1sCf.js +11 -0
- package/dist/assets/runtimeEndpointReset-D2MmSbDk.js +53 -0
- package/dist/assets/{runtimeSurface-CySRuLbN.js → runtimeSurface-CE_VNjdH.js} +1 -1
- package/dist/assets/{useAppFontEffects-C4JL1x7k.js → useAppFontEffects-BvFAP9zG.js} +102 -103
- package/dist/assets/useFilesViewSearch-BD79p3A2.js +7 -0
- package/dist/assets/usePushVisibilityBeacon-CWg0j-Wg.js +10 -0
- package/dist/assets/useSwitcherItems-CazJ6Yox.js +1 -0
- package/dist/assets/{vendor-base-ui-vkqQ2P9o.js → vendor-base-ui-CdaWtC7e.js} +1 -1
- package/dist/assets/vendor-beautiful-mermaid-D3YCkKz7.js +111 -0
- package/dist/assets/{vendor-codemirror-commands-DYppkHEk.js → vendor-codemirror-commands-CNlncqrr.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-C493X_9w.js → vendor-codemirror-language-data-CP3j3-xu.js} +2 -2
- package/dist/assets/{vendor-replit-codemirror-vim-CGHHNQxC.js → vendor-replit-codemirror-vim-DaSwPsXt.js} +1 -1
- package/dist/assets/{web-components-B2Rw__yK.js → web-components-DWuadqra.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 +2 -2
- 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/routes.js +56 -3
- package/server/lib/pi/routes.test.js +165 -0
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +19 -6
- package/server/lib/pi/session-daemon/prompt-operations.test.js +151 -3
- package/server/lib/pi/session-daemon/prompt-preflight.test.js +556 -0
- package/server/lib/pi/session-daemon/sdk-upgrade.test.js +157 -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-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 +514 -107
- package/server/lib/pi/session-daemon/session-daemon.test.js +37 -13
- package/server/lib/pi/session-daemon/session-idle-residency.test.js +749 -0
- package/server/lib/pi/session-daemon/session-replay.js +98 -0
- package/server/lib/pi/session-daemon/session-replay.test.js +628 -0
- package/server/lib/pi/ui-settings-store.js +16 -10
- package/server/lib/pi/ui-settings-store.test.js +91 -0
- package/server/lib/server/cors.js +6 -0
- package/server/lib/server/cors.test.js +3 -0
- package/server/lib/stt/DOCUMENTATION.md +1 -1
- package/server/lib/stt/local/worker-client.js +11 -3
- package/server/lib/stt/local/worker-client.test.js +255 -0
- package/server/lib/workspace/host.js +6 -2
- package/server/lib/workspace/host.test.js +15 -0
- package/dist/assets/DiagramEditor-DuGmiPZ5.js +0 -1
- package/dist/assets/DiagramView-CHy1Glsl.js +0 -1
- package/dist/assets/FilesView-CK2YVs_W.js +0 -6
- package/dist/assets/GitView-BEFLOv_7.js +0 -8
- package/dist/assets/MarkdownRendererImpl-hE_nmSqe.js +0 -12
- package/dist/assets/PatchDiff-BagRxMON.js +0 -1
- package/dist/assets/SessionSwitcherDropdown-icxJk_lT.js +0 -2
- package/dist/assets/SessionUnreadDot-Bv-5KguB.js +0 -1
- package/dist/assets/SettingsView-Ck0qxtKP.js +0 -2
- package/dist/assets/SettingsWindow-GQRL2CdD.js +0 -1
- package/dist/assets/ToolOutputDialog-CxJUXVZW.js +0 -8
- package/dist/assets/ToolPartDiffPreview-BXuLRWHT.js +0 -1
- package/dist/assets/collapsible-szfZ0Syc.js +0 -1
- package/dist/assets/computeVirtualFileMetrics-DG_E6iaN.js +0 -3
- package/dist/assets/contextFileOpenGuard-DPBE3ELv.js +0 -1
- package/dist/assets/gitStatusPredicates-OljV4Bb2.js +0 -134
- package/dist/assets/index-DNoEeZ2U.css +0 -1
- package/dist/assets/index-DmexVlTQ.js +0 -1
- package/dist/assets/index-KIdiBFJs.js +0 -8
- package/dist/assets/isDiffPlainText-aikgiqLb.js +0 -1
- package/dist/assets/isFilePlainText-D-Dl6LqX.js +0 -1
- package/dist/assets/main-BXdraZTZ.js +0 -135
- package/dist/assets/renderElectronMiniChatApp-B0K72YnS.js +0 -2
- package/dist/assets/renderMobileApp-Ca_BO_s4.js +0 -11
- package/dist/assets/runtimeEndpointReset-Cx2tsgTo.js +0 -54
- package/dist/assets/useFilesViewSearch-Du0DnmKs.js +0 -7
- package/dist/assets/usePushVisibilityBeacon-BnHxIv4r.js +0 -10
- package/dist/assets/useSwitcherItems-C91mwPJD.js +0 -1
- package/dist/assets/vendor-beautiful-mermaid-DneUawHp.js +0 -119
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Send-intent deduplication registry.
|
|
3
|
+
*
|
|
4
|
+
* Owns the authoritative execution boundary for prompt/steer/followUp sends
|
|
5
|
+
* (finding #3). A client labels every send intent with a stable
|
|
6
|
+
* `operationId`; the daemon claims the id here BEFORE activating Pi or
|
|
7
|
+
* consuming anything. The registry guarantees:
|
|
8
|
+
*
|
|
9
|
+
* - One intent executes at most once within the bounded retention window
|
|
10
|
+
* (`ttlMs` and `maxEntries`; tombstones are FIFO-capped at `maxEntries`
|
|
11
|
+
* so `expired` can degrade to `unknown` under pressure, and a restart
|
|
12
|
+
* loses all receipts). There is no lifetime at-most-once guarantee: after
|
|
13
|
+
* expiry/eviction pressure or a restart the same id may report `expired`
|
|
14
|
+
* or `unknown` and the caller must use a new operation id. A retry of
|
|
15
|
+
* the same intent inside the window (transport retry, manual
|
|
16
|
+
* confirmation, queue backoff) returns the original acceptance receipt
|
|
17
|
+
* instead of invoking Pi again.
|
|
18
|
+
* - Concurrent duplicates of a still-pending intent share the original
|
|
19
|
+
* outcome: they await the first execution's settlement instead of racing it.
|
|
20
|
+
* Pending claims are never evicted while their owner is still active:
|
|
21
|
+
* expiring a still-executing claim would let a duplicate re-execute the
|
|
22
|
+
* same operation, so pending entries stay until their owner settles and
|
|
23
|
+
* duplicates always share (never re-execute a pending-expired operation).
|
|
24
|
+
* - The same id with a different payload (text, model, thinking, message id,
|
|
25
|
+
* or attachments) is rejected as `OPERATION_PAYLOAD_MISMATCH` — a
|
|
26
|
+
* duplicated id never silently executes unrelated work. Identity is
|
|
27
|
+
* `kind + sessionId + operationId`: the same id on a different session or
|
|
28
|
+
* delivery kind is a different intent and executes independently (never a
|
|
29
|
+
* mismatch). `streamEpoch` (stamped only by the stream-epoch split)
|
|
30
|
+
* is intentionally NOT fingerprinted, so adding or omitting it on a retry
|
|
31
|
+
* in the same lifetime never causes a mismatch. This split performs no
|
|
32
|
+
* epoch guard; the stream-epoch branch enforces `STALE_STREAM_EPOCH`
|
|
33
|
+
* before the claim.
|
|
34
|
+
*
|
|
35
|
+
* Retention is bounded and explicit: accepted receipts are kept for `ttlMs`
|
|
36
|
+
* and at most `maxEntries` accepted receipts are retained (oldest evicted).
|
|
37
|
+
* Evicted or TTL-expired acceptances leave a bounded `expired` tombstone
|
|
38
|
+
* (capped at `maxEntries`) so `query()` can distinguish `expired` — "was
|
|
39
|
+
* seen but retention is gone, outcome unknown, never assume success" —
|
|
40
|
+
* from `unknown` — "never seen in this retention window (including tombstone
|
|
41
|
+
* pressure and post-restart)". A later retry
|
|
42
|
+
* with the same id after expiry is rejected as `expired` (OPERATION_EXPIRED),
|
|
43
|
+
* never an automatic re-execution: callers must treat the retention window
|
|
44
|
+
* as the only safe retry window and use a new operation id afterwards.
|
|
45
|
+
* Pending claims are bounded separately by `maxPending` entries: an unsettled
|
|
46
|
+
* pending entry is never evicted (its duplicates share the outcome), and a
|
|
47
|
+
* new distinct pending claim past the bound is rejected as `overloaded`
|
|
48
|
+
* (SESSION_BUSY, retry with backoff) so the map cannot grow without bound
|
|
49
|
+
* while active ownership is preserved. `pendingTtlMs` is retained as a
|
|
50
|
+
* constructor-validated bound for future waiter timeouts, but pending entries
|
|
51
|
+
* are not auto-expired: a leaked claim occupies one of `maxPending` slots
|
|
52
|
+
* until restart instead of risking a duplicate execution. The registry is
|
|
53
|
+
* in-memory per daemon process: a daemon restart loses receipts, which is
|
|
54
|
+
* the documented crash-window — a client retry across a restart may
|
|
55
|
+
* re-execute an accepted intent, and clients must not replay uncertain
|
|
56
|
+
* sends across restarts (the stream-epoch split adds a verified-epoch guard
|
|
57
|
+
* for this window; this split documents the raw window without it). After `ttlMs` the receipt is
|
|
58
|
+
* gone: a retry with the same id is rejected as expired, never a silent
|
|
59
|
+
* deduplicated success nor an automatic re-execution — callers must treat
|
|
60
|
+
* the retention window as the only safe retry window and use a new
|
|
61
|
+
* operation id afterwards.
|
|
62
|
+
*
|
|
63
|
+
* Only acceptances are retained. Request-path rejections happen before Pi is
|
|
64
|
+
* invoked, so nothing executed and a later retry with the same id is safe;
|
|
65
|
+
* pending duplicates still share the original rejection so a concurrent
|
|
66
|
+
* duplicate never proceeds on its own. Every claim — including
|
|
67
|
+
* pending-overload (SESSION_BUSY) and validation rejections — must
|
|
68
|
+
* settle its entry; an unsettled pending entry is a hang, not a queue.
|
|
69
|
+
*/
|
|
70
|
+
|
|
71
|
+
const SEND_OPERATION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
72
|
+
|
|
73
|
+
export const isValidSendOperationId = (value) => (
|
|
74
|
+
typeof value === 'string' && SEND_OPERATION_ID_PATTERN.test(value)
|
|
75
|
+
);
|
|
76
|
+
|
|
77
|
+
/** Deterministic stringify so payload fingerprints are order-independent. */
|
|
78
|
+
export const stableFingerprint = (value) => {
|
|
79
|
+
if (value === null || typeof value !== 'object') return JSON.stringify(value ?? null);
|
|
80
|
+
if (Array.isArray(value)) return `[${value.map(stableFingerprint).join(',')}]`;
|
|
81
|
+
const keys = Object.keys(value).filter((key) => value[key] !== undefined).sort();
|
|
82
|
+
return `{${keys.map((key) => `${JSON.stringify(key)}:${stableFingerprint(value[key])}`).join(',')}}`;
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
const entryKey = ({ kind, sessionId, operationId }) => `${kind}\u0000${sessionId}\u0000${operationId}`;
|
|
86
|
+
|
|
87
|
+
export const createSendOperationRegistry = ({
|
|
88
|
+
now = () => Date.now(),
|
|
89
|
+
ttlMs = 10 * 60 * 1_000,
|
|
90
|
+
maxEntries = 1_024,
|
|
91
|
+
maxPending = 256,
|
|
92
|
+
pendingTtlMs = 30_000,
|
|
93
|
+
} = {}) => {
|
|
94
|
+
if (!Number.isFinite(ttlMs) || ttlMs <= 0) throw new Error('send operation ttlMs must be positive');
|
|
95
|
+
if (!Number.isFinite(maxEntries) || maxEntries <= 0) throw new Error('send operation maxEntries must be positive');
|
|
96
|
+
if (!Number.isFinite(maxPending) || maxPending <= 0) throw new Error('send operation maxPending must be positive');
|
|
97
|
+
if (!Number.isFinite(pendingTtlMs) || pendingTtlMs <= 0) throw new Error('send operation pendingTtlMs must be positive');
|
|
98
|
+
|
|
99
|
+
const entries = new Map();
|
|
100
|
+
// Bounded tombstones for ids whose acceptance is gone (TTL expiry or
|
|
101
|
+
// oldest-evicted). Lets `query()` report `expired` instead of falsely
|
|
102
|
+
// implying `unknown`/safe-to-retry or `accepted`. Rejections before Pi ran
|
|
103
|
+
// leave no tombstone: nothing executed, so the id is `unknown`/reusable.
|
|
104
|
+
// A fresh claim clears its tombstone; tombstones are FIFO-capped at
|
|
105
|
+
// `maxEntries` so `expired` degrades to `unknown` under pressure — both
|
|
106
|
+
// mean "no guarantee, outcome unknown", never a false acceptance.
|
|
107
|
+
const expiredKeys = new Map();
|
|
108
|
+
const rememberExpired = (key) => {
|
|
109
|
+
expiredKeys.delete(key);
|
|
110
|
+
expiredKeys.set(key, now());
|
|
111
|
+
while (expiredKeys.size > maxEntries) {
|
|
112
|
+
const oldest = expiredKeys.keys().next();
|
|
113
|
+
if (oldest.done) break;
|
|
114
|
+
expiredKeys.delete(oldest.value);
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
const countPending = () => {
|
|
119
|
+
let count = 0;
|
|
120
|
+
for (const entry of entries.values()) if (entry.state === 'pending') count += 1;
|
|
121
|
+
return count;
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
// Expired accepted receipts become `expired` tombstones. Pending claims
|
|
125
|
+
// are never auto-expired: evicting a still-executing claim would let a
|
|
126
|
+
// duplicate re-execute the same operation, and rejecting its waiters as
|
|
127
|
+
// SESSION_BUSY would falsely imply nothing executed. Pending entries stay
|
|
128
|
+
// until their owner settles; `maxPending` bounds the map instead.
|
|
129
|
+
const evictExpired = () => {
|
|
130
|
+
const timestamp = now();
|
|
131
|
+
for (const [key, entry] of entries) {
|
|
132
|
+
if (entry.state === 'accepted' && timestamp >= entry.expiresAt) {
|
|
133
|
+
entries.delete(key);
|
|
134
|
+
rememberExpired(key);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
const trimToBound = () => {
|
|
139
|
+
// The bound applies to retained receipts; pending claims are transient and
|
|
140
|
+
// must never evict an accepted receipt (their duplicates share the outcome).
|
|
141
|
+
while (entries.size > maxEntries) {
|
|
142
|
+
let accepted = 0;
|
|
143
|
+
let oldestAccepted;
|
|
144
|
+
for (const [key, entry] of entries) {
|
|
145
|
+
if (entry.state === 'accepted') {
|
|
146
|
+
accepted += 1;
|
|
147
|
+
if (!oldestAccepted) oldestAccepted = key;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
if (accepted <= maxEntries) break;
|
|
151
|
+
entries.delete(oldestAccepted);
|
|
152
|
+
rememberExpired(oldestAccepted);
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
const claim = ({ kind, sessionId, operationId, fingerprint }) => {
|
|
157
|
+
const key = entryKey({ kind, sessionId, operationId });
|
|
158
|
+
evictExpired();
|
|
159
|
+
const existing = entries.get(key);
|
|
160
|
+
if (existing) {
|
|
161
|
+
if (existing.fingerprint !== fingerprint) return { outcome: 'mismatch' };
|
|
162
|
+
if (existing.state === 'accepted') {
|
|
163
|
+
return { outcome: 'accepted', receipt: existing.receipt, deduplicated: true };
|
|
164
|
+
}
|
|
165
|
+
// Still pending: the duplicate shares the original outcome, even past
|
|
166
|
+
// `pendingTtlMs`. Expiring here would let a still-executing operation
|
|
167
|
+
// duplicate, so pending never becomes `expired` while active.
|
|
168
|
+
return { outcome: 'pending', settled: existing.settled };
|
|
169
|
+
}
|
|
170
|
+
// After retention the same id must not automatically re-execute: the
|
|
171
|
+
// tombstone blocks reuse and the caller must use a new operation id.
|
|
172
|
+
if (expiredKeys.has(key)) return { outcome: 'expired' };
|
|
173
|
+
if (countPending() >= maxPending) return { outcome: 'overloaded' };
|
|
174
|
+
let settleWaiters;
|
|
175
|
+
let rejectWaiters;
|
|
176
|
+
const settled = new Promise((resolve, reject) => {
|
|
177
|
+
settleWaiters = resolve;
|
|
178
|
+
rejectWaiters = reject;
|
|
179
|
+
});
|
|
180
|
+
// A claim whose id is rejected usually has no duplicate awaiting it; mark
|
|
181
|
+
// the shared promise handled so the rejection reaches only real waiters.
|
|
182
|
+
settled.then(undefined, () => {});
|
|
183
|
+
const entry = {
|
|
184
|
+
state: 'pending',
|
|
185
|
+
fingerprint,
|
|
186
|
+
settled,
|
|
187
|
+
rejectWaiters,
|
|
188
|
+
pendingExpiresAt: now() + pendingTtlMs,
|
|
189
|
+
settle: (result) => {
|
|
190
|
+
if (entry.state !== 'pending') return;
|
|
191
|
+
if (result.accepted) {
|
|
192
|
+
entry.state = 'accepted';
|
|
193
|
+
entry.receipt = result.receipt;
|
|
194
|
+
entry.expiresAt = now() + ttlMs;
|
|
195
|
+
delete entry.pendingExpiresAt;
|
|
196
|
+
trimToBound();
|
|
197
|
+
settleWaiters(result);
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
// A rejection happened before Pi ran: nothing executed, so forget
|
|
201
|
+
// the claim and let a later retry of the same id proceed.
|
|
202
|
+
entries.delete(key);
|
|
203
|
+
rejectWaiters(result.error);
|
|
204
|
+
},
|
|
205
|
+
};
|
|
206
|
+
entries.set(key, entry);
|
|
207
|
+
expiredKeys.delete(key);
|
|
208
|
+
trimToBound();
|
|
209
|
+
return { outcome: 'new', entry };
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
const getReceipt = ({ kind, sessionId, operationId }) => {
|
|
213
|
+
evictExpired();
|
|
214
|
+
if (typeof kind === 'string' && kind.length > 0) {
|
|
215
|
+
const entry = entries.get(entryKey({ kind, sessionId, operationId }));
|
|
216
|
+
if (entry?.state === 'accepted') return { receipt: entry.receipt, fingerprint: entry.fingerprint };
|
|
217
|
+
return undefined;
|
|
218
|
+
}
|
|
219
|
+
for (const [key, entry] of entries) {
|
|
220
|
+
if (entry.state !== 'accepted') continue;
|
|
221
|
+
// Keys are `kind + NUL + sessionId + NUL + operationId`; match the
|
|
222
|
+
// session+operation suffix when the caller did not specify a kind.
|
|
223
|
+
if (key.endsWith(`\u0000${sessionId}\u0000${operationId}`)) {
|
|
224
|
+
return { receipt: entry.receipt, fingerprint: entry.fingerprint, kind: key.slice(0, key.indexOf('\u0000')) };
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return undefined;
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
// Exact-identity receipt lookup for `sessions.sendReceipt`: requires the
|
|
231
|
+
// full `kind + sessionId + operationId` key. Returns one of
|
|
232
|
+
// `accepted` (retained receipt), `pending` (still-accepting claim),
|
|
233
|
+
// `expired` (seen but retention gone — outcome unknown, never assume
|
|
234
|
+
// success), or `unknown` (never seen in this retention window, evicted
|
|
235
|
+
// tombstone pressure, post-restart, or rejected before Pi ran so nothing
|
|
236
|
+
// executed). Never returns a receipt after expiry.
|
|
237
|
+
const query = ({ kind, sessionId, operationId }) => {
|
|
238
|
+
evictExpired();
|
|
239
|
+
if (typeof kind !== 'string' || kind.length === 0
|
|
240
|
+
|| typeof sessionId !== 'string' || sessionId.length === 0
|
|
241
|
+
|| typeof operationId !== 'string' || operationId.length === 0) {
|
|
242
|
+
return { status: 'unknown' };
|
|
243
|
+
}
|
|
244
|
+
const key = entryKey({ kind, sessionId, operationId });
|
|
245
|
+
const entry = entries.get(key);
|
|
246
|
+
if (entry?.state === 'accepted') {
|
|
247
|
+
return { status: 'accepted', receipt: entry.receipt, fingerprint: entry.fingerprint };
|
|
248
|
+
}
|
|
249
|
+
if (entry?.state === 'pending') {
|
|
250
|
+
return { status: 'pending', fingerprint: entry.fingerprint };
|
|
251
|
+
}
|
|
252
|
+
if (expiredKeys.has(key)) return { status: 'expired' };
|
|
253
|
+
return { status: 'unknown' };
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
return {
|
|
257
|
+
claim,
|
|
258
|
+
getReceipt,
|
|
259
|
+
query,
|
|
260
|
+
get size() { return entries.size; },
|
|
261
|
+
get pendingSize() { return countPending(); },
|
|
262
|
+
get expiredSize() { return expiredKeys.size; },
|
|
263
|
+
};
|
|
264
|
+
};
|
|
@@ -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
|
+
});
|
|
@@ -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');
|