@pi-chamber/web 0.9.5 → 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.
Files changed (72) hide show
  1. package/dist/assets/DiagramView-0Iq1ak1I.js +1 -0
  2. package/dist/assets/{DiffView-BmIVvheE.js → DiffView-DD1AFRi3.js} +1 -1
  3. package/dist/assets/FileSaveConflictDialog-CoKwDovb.js +3 -0
  4. package/dist/assets/FilesView-B_BF39ef.js +6 -0
  5. package/dist/assets/{GitView-BNkzec7G.js → GitView-LFEpCasf.js} +3 -3
  6. package/dist/assets/{JsonTreeView-C1Kzaybf.js → JsonTreeView-Cwjgvh4g.js} +1 -1
  7. package/dist/assets/{MarkdownRendererImpl-qmKiFVpO.js → MarkdownRendererImpl-_7kV1yNw.js} +2 -2
  8. package/dist/assets/{PatchDiff-D9JesZL1.js → PatchDiff-DG43C1HW.js} +1 -1
  9. package/dist/assets/{SessionSwitcherContent-DplV_ApH.js → SessionSwitcherContent-DCFXPY3d.js} +1 -1
  10. package/dist/assets/{SessionSwitcherDropdown-DdgDKT6K.js → SessionSwitcherDropdown-QY7FKuEQ.js} +2 -2
  11. package/dist/assets/{SessionUnreadDot-BdSDgvhC.js → SessionUnreadDot-DGT31A3z.js} +1 -1
  12. package/dist/assets/{SettingsView-z8uf0XyM.js → SettingsView-eG-wN-yY.js} +2 -2
  13. package/dist/assets/{SettingsWindow-CPDmgNg2.js → SettingsWindow-Dvnp8YrA.js} +1 -1
  14. package/dist/assets/{ToolOutputDialog-DaF1xcM0.js → ToolOutputDialog-IlCrS6BR.js} +1 -1
  15. package/dist/assets/{ToolPartDiffPreview-Di6Uo0Dt.js → ToolPartDiffPreview-D68JV0rR.js} +1 -1
  16. package/dist/assets/{VirtualizedFileDiff-wqcrY0yr.js → VirtualizedFileDiff-Bl-rAYeh.js} +1 -1
  17. package/dist/assets/{collapsible-DBQnXTNm.js → collapsible-BjniCdZ5.js} +1 -1
  18. package/dist/assets/{computeVirtualFileMetrics-Cr3jh0d6.js → computeVirtualFileMetrics-FSOm2VrW.js} +2 -2
  19. package/dist/assets/{contextFileOpenGuard-C_AOTYQD.js → contextFileOpenGuard-Bxb6AIPa.js} +1 -1
  20. package/dist/assets/{gitStatusPredicates-BvPOjeOy.js → gitStatusPredicates-DxolDpMd.js} +1 -1
  21. package/dist/assets/index-BpmGBboM.css +1 -0
  22. package/dist/assets/index-DZnzXhTs.js +8 -0
  23. package/dist/assets/{index-B8Wt2aN3.js → index-Dh58uD3I.js} +1 -1
  24. package/dist/assets/{isDiffPlainText-L9uvgz2F.js → isDiffPlainText-D3_04XCh.js} +1 -1
  25. package/dist/assets/{isFilePlainText-C4yk5BOo.js → isFilePlainText-CHouYQhH.js} +1 -1
  26. package/dist/assets/{main-DCK6lLCo.js → main-CH3EqGJI.js} +2 -2
  27. package/dist/assets/{main-C1OSzD-E.js → main-HzTrVvbB.js} +3 -3
  28. package/dist/assets/{markdownCore-Czb_lINQ.js → markdownCore-DJU4KvHP.js} +1 -1
  29. package/dist/assets/{miniChat-CXiSlptL.js → miniChat-Ca3TpaaA.js} +2 -2
  30. package/dist/assets/{mobile-D0HVxiyJ.js → mobile-lj4gpGsO.js} +2 -2
  31. package/dist/assets/{renderElectronMiniChatApp-BcG209a4.js → renderElectronMiniChatApp-rUFfaD-T.js} +2 -2
  32. package/dist/assets/{renderMobileApp-B5x_PWlc.js → renderMobileApp-CcWQ1sCf.js} +3 -3
  33. package/dist/assets/{runtimeEndpointReset-CUiPe6dQ.js → runtimeEndpointReset-D2MmSbDk.js} +8 -8
  34. package/dist/assets/{runtimeSurface-vilE4xyj.js → runtimeSurface-CE_VNjdH.js} +1 -1
  35. package/dist/assets/{useAppFontEffects-BP07Vl6M.js → useAppFontEffects-BvFAP9zG.js} +86 -86
  36. package/dist/assets/useFilesViewSearch-BD79p3A2.js +7 -0
  37. package/dist/assets/{usePushVisibilityBeacon-CChMvoTL.js → usePushVisibilityBeacon-CWg0j-Wg.js} +1 -1
  38. package/dist/assets/{useSwitcherItems-_RSo3F-A.js → useSwitcherItems-CazJ6Yox.js} +1 -1
  39. package/dist/assets/{vendor-codemirror-language-data-BJrrV83E.js → vendor-codemirror-language-data-CP3j3-xu.js} +2 -2
  40. package/dist/assets/{web-components-B5sMa_kC.js → web-components-DWuadqra.js} +1 -1
  41. package/dist/index.html +4 -4
  42. package/dist/mini-chat.html +3 -3
  43. package/dist/mobile.html +3 -3
  44. package/package.json +1 -1
  45. package/server/lib/fs/DOCUMENTATION.md +15 -3
  46. package/server/lib/fs/routes.js +369 -51
  47. package/server/lib/fs/routes.test.js +565 -3
  48. package/server/lib/fs/search.js +74 -29
  49. package/server/lib/pi/routes.js +56 -3
  50. package/server/lib/pi/routes.test.js +165 -0
  51. package/server/lib/pi/session-daemon/DOCUMENTATION.md +3 -2
  52. package/server/lib/pi/session-daemon/prompt-operations.test.js +9 -3
  53. package/server/lib/pi/session-daemon/prompt-preflight.test.js +556 -0
  54. package/server/lib/pi/session-daemon/send-operation-dedup.test.js +331 -0
  55. package/server/lib/pi/session-daemon/send-operation-registry.js +264 -0
  56. package/server/lib/pi/session-daemon/send-operation-registry.test.js +205 -0
  57. package/server/lib/pi/session-daemon/session-daemon-extensions.e2e.test.js +16 -5
  58. package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +3 -1
  59. package/server/lib/pi/session-daemon/session-daemon.js +284 -31
  60. package/server/lib/pi/session-daemon/session-daemon.test.js +37 -13
  61. package/server/lib/pi/session-daemon/session-idle-residency.test.js +8 -1
  62. package/server/lib/pi/session-daemon/session-replay.test.js +3 -1
  63. package/server/lib/server/cors.js +6 -0
  64. package/server/lib/server/cors.test.js +3 -0
  65. package/server/lib/workspace/host.js +6 -2
  66. package/server/lib/workspace/host.test.js +15 -0
  67. package/dist/assets/DiagramEditor-BPDkGHsj.js +0 -1
  68. package/dist/assets/DiagramView-D_EfDz2d.js +0 -1
  69. package/dist/assets/FilesView-CJytSUAX.js +0 -6
  70. package/dist/assets/index-DIF8b4bh.css +0 -1
  71. package/dist/assets/index-jrfQYSvP.js +0 -8
  72. package/dist/assets/useFilesViewSearch-oxIKk-ea.js +0 -7
@@ -35,6 +35,11 @@ import {
35
35
  } from './ipc-protocol.js';
36
36
  import { createMessageEntryAliases } from './message-entry-aliases.js';
37
37
  import { createSessionReplayLog } from './session-replay.js';
38
+ import {
39
+ createSendOperationRegistry,
40
+ isValidSendOperationId,
41
+ stableFingerprint,
42
+ } from './send-operation-registry.js';
38
43
  import { resolveEffectiveRetryLimitFromDataDir as resolveEffectiveRetryLimit } from './session-retry-limits.js';
39
44
  import { createSkillReadClassifier } from './skill-read-classifier.js';
40
45
  import { createSessionRuntimeRegistry } from './runtime-registry.js';
@@ -164,6 +169,7 @@ export function createSessionDaemon({
164
169
  onOwnershipClaim,
165
170
  onShutdown,
166
171
  idleTimeoutMs = 5 * 60 * 1_000,
172
+ sendOperationTtlMs = 10 * 60 * 1_000,
167
173
  listSessions = ({ cwd: sessionCwd, agentDir: sessionAgentDir = agentDir }) => listPiSessionJsonlDirectory({
168
174
  cwd: sessionCwd,
169
175
  agentDir: sessionAgentDir,
@@ -201,6 +207,9 @@ export function createSessionDaemon({
201
207
  if (!Number.isFinite(idleTimeoutMs) || idleTimeoutMs < 0) {
202
208
  throw new SessionDaemonProtocolError('INVALID_IDLE_TIMEOUT', 'The session daemon idle timeout is invalid.');
203
209
  }
210
+ if (!Number.isFinite(sendOperationTtlMs) || sendOperationTtlMs <= 0) {
211
+ throw new SessionDaemonProtocolError('INVALID_SEND_OPERATION_TTL', 'The session daemon send operation ttl is invalid.');
212
+ }
204
213
 
205
214
  let server;
206
215
  let runtime;
@@ -304,6 +313,16 @@ export function createSessionDaemon({
304
313
  // runtimes dirty and reload them at the next safe lifecycle edge. Other
305
314
  // Pi configuration writes queue resident-runtime recreation at that edge.
306
315
  const activeSessionInputs = new Map();
316
+ // Send-intent deduplication (finding #3): one stable operation id per send
317
+ // intent; the registry is the authoritative execution boundary before Pi.
318
+ // Identity is `kind + sessionId + operationId`: the same id on a different
319
+ // kind or session is a different intent, never a payload mismatch.
320
+ // Retention is bounded (ttlMs/maxEntries, tombstones capped) and in-memory
321
+ // per daemon process — a restart loses receipts, which is the documented
322
+ // crash window. This split performs no stream-epoch guard and no
323
+ // per-session config/acceptance lock; every claim settles so pending
324
+ // duplicates never hang.
325
+ const sendOperations = createSendOperationRegistry({ ttlMs: sendOperationTtlMs });
307
326
  const pendingResourceReloads = new Set();
308
327
  const resourceReloadsByRuntime = new Map();
309
328
  let resourceReloadQueue = Promise.resolve();
@@ -315,26 +334,70 @@ export function createSessionDaemon({
315
334
  let runtimeRecreationRevision = 0;
316
335
  let runtimeRecreationTask = null;
317
336
  // Pi emits each user message start before its persisted entry is readable.
318
- // Keep prompt metadata in send order so queued follow-ups cannot attach the
319
- // next prompt's files to an earlier user message.
337
+ // Keep prompt file metadata keyed by delivery kind so a queued followUp
338
+ // that a later steer overtakes cannot swap attachment footers. Steering
339
+ // drains before followUp in the SDK loop regardless of send order, so a
340
+ // single FIFO would attach the wrong files. SDK `queue_update` is the
341
+ // authoritative ownership signal: the queue that shrank owns the next
342
+ // user start. Direct (non-queued) starts emit no shrink and fall back to
343
+ // oldest-by-generation across kinds. No text/content heuristics are used.
320
344
  const pendingUserStartsBySession = new Map();
321
- const enqueueUserStart = (sessionId, generation, files) => {
322
- const pending = pendingUserStartsBySession.get(sessionId) ?? [];
323
- pending.push({ generation, files });
324
- pendingUserStartsBySession.set(sessionId, pending);
345
+ const queueSizesBySession = new Map();
346
+ const queueShrinkBySession = new Map();
347
+ const pendingBucketsFor = (sessionId) => {
348
+ let buckets = pendingUserStartsBySession.get(sessionId);
349
+ if (!buckets) {
350
+ buckets = { prompt: [], steer: [], followUp: [] };
351
+ pendingUserStartsBySession.set(sessionId, buckets);
352
+ }
353
+ return buckets;
354
+ };
355
+ const hasPendingUserStarts = (buckets) => (
356
+ buckets.prompt.length > 0 || buckets.steer.length > 0 || buckets.followUp.length > 0
357
+ );
358
+ const enqueueUserStart = (sessionId, generation, files, deliveryKind) => {
359
+ const buckets = pendingBucketsFor(sessionId);
360
+ const bucket = deliveryKind === 'steer' || deliveryKind === 'followUp' ? deliveryKind : 'prompt';
361
+ buckets[bucket].push({ generation, files, deliveryKind: bucket });
362
+ };
363
+ const takeOldestUserStart = (buckets) => {
364
+ let oldestBucket;
365
+ let oldestGeneration = Infinity;
366
+ for (const bucket of ['prompt', 'steer', 'followUp']) {
367
+ const first = buckets[bucket][0];
368
+ if (first && first.generation < oldestGeneration) {
369
+ oldestGeneration = first.generation;
370
+ oldestBucket = bucket;
371
+ }
372
+ }
373
+ if (!oldestBucket) return undefined;
374
+ const next = buckets[oldestBucket].shift();
375
+ return next;
325
376
  };
326
377
  const takeUserStart = (sessionId) => {
327
- const pending = pendingUserStartsBySession.get(sessionId);
328
- const next = pending?.shift();
329
- if (!pending?.length) pendingUserStartsBySession.delete(sessionId);
378
+ const buckets = pendingUserStartsBySession.get(sessionId);
379
+ if (!buckets) return undefined;
380
+ const shrink = queueShrinkBySession.get(sessionId);
381
+ queueShrinkBySession.delete(sessionId);
382
+ let next;
383
+ if ((shrink === 'steer' || shrink === 'followUp') && buckets[shrink].length > 0) {
384
+ next = buckets[shrink].shift();
385
+ } else {
386
+ next = takeOldestUserStart(buckets);
387
+ }
388
+ if (!hasPendingUserStarts(buckets)) {
389
+ pendingUserStartsBySession.delete(sessionId);
390
+ }
330
391
  return next;
331
392
  };
332
393
  const removeUserStart = (sessionId, generation) => {
333
- const pending = pendingUserStartsBySession.get(sessionId);
334
- if (!pending) return;
335
- const remaining = pending.filter((entry) => entry.generation !== generation);
336
- if (remaining.length > 0) pendingUserStartsBySession.set(sessionId, remaining);
337
- else pendingUserStartsBySession.delete(sessionId);
394
+ const buckets = pendingUserStartsBySession.get(sessionId);
395
+ if (!buckets) return;
396
+ for (const bucket of ['prompt', 'steer', 'followUp']) {
397
+ const filtered = buckets[bucket].filter((entry) => entry.generation !== generation);
398
+ buckets[bucket] = filtered;
399
+ }
400
+ if (!hasPendingUserStarts(buckets)) pendingUserStartsBySession.delete(sessionId);
338
401
  };
339
402
  const shutdownRequestedBySession = new Set();
340
403
  const disposingSessionIds = new Set();
@@ -2658,7 +2721,75 @@ export function createSessionDaemon({
2658
2721
  return { text: text.join('\n'), images, files };
2659
2722
  };
2660
2723
 
2724
+ const sendOperationFingerprint = ({ kind, payload }) => ({
2725
+ kind,
2726
+ text: payload.text,
2727
+ model: payload.model ?? null,
2728
+ thinking: payload.thinking ?? null,
2729
+ messageId: payload.messageId ?? null,
2730
+ attachments: Array.isArray(payload.attachments)
2731
+ ? payload.attachments.map((attachment) => ({
2732
+ id: attachment?.id ?? null,
2733
+ name: attachment?.name ?? null,
2734
+ mime: attachment?.mime ?? null,
2735
+ size: attachment?.size ?? null,
2736
+ }))
2737
+ : null,
2738
+ });
2739
+
2661
2740
  const sessionInput = async (payload, delivery) => {
2741
+ if (!payload || typeof payload !== 'object' || typeof payload.sessionId !== 'string'
2742
+ || typeof payload.text !== 'string' || payload.text.length === 0 || Buffer.byteLength(payload.text) > 64 * 1024) {
2743
+ throw new SessionDaemonProtocolError('INVALID_PROMPT', 'The session prompt is invalid.');
2744
+ }
2745
+ if (payload.thinking !== undefined) validateThinking(payload.thinking);
2746
+ const kind = delivery ?? 'prompt';
2747
+ // Finding #3: claim the stable operation id at the authoritative
2748
+ // execution boundary — before Pi activation and before any attachment
2749
+ // side effect. A duplicate returns the original receipt; a payload
2750
+ // mismatch (same kind + session + id, different text/model/thinking/
2751
+ // message/attachments) rejects. A different kind or session is a
2752
+ // different intent, never a mismatch. Every claim settles so pending
2753
+ // duplicates never hang: acceptance retains the receipt, request-path
2754
+ // rejection frees the id (nothing executed).
2755
+ let claimEntry = null;
2756
+ if (payload.operationId !== undefined) {
2757
+ if (!isValidSendOperationId(payload.operationId)) {
2758
+ throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The send operation id is invalid.');
2759
+ }
2760
+ const claimed = sendOperations.claim({
2761
+ kind,
2762
+ sessionId: payload.sessionId,
2763
+ operationId: payload.operationId,
2764
+ fingerprint: stableFingerprint(sendOperationFingerprint({ kind, payload })),
2765
+ });
2766
+ if (claimed.outcome === 'mismatch') {
2767
+ throw new SessionDaemonProtocolError('OPERATION_PAYLOAD_MISMATCH', 'This operation id was already used with a different payload.');
2768
+ }
2769
+ if (claimed.outcome === 'expired') {
2770
+ throw new SessionDaemonProtocolError('OPERATION_EXPIRED', 'This operation id expired after the retention window; retry with a new operation id.');
2771
+ }
2772
+ if (claimed.outcome === 'overloaded') {
2773
+ throw new SessionDaemonProtocolError('SESSION_BUSY', 'The daemon is accepting too many sends; retry with backoff.');
2774
+ }
2775
+ if (claimed.outcome === 'accepted') return { ...claimed.receipt, deduplicated: true };
2776
+ if (claimed.outcome === 'pending') {
2777
+ const shared = await claimed.settled;
2778
+ return { ...shared.receipt, deduplicated: true };
2779
+ }
2780
+ claimEntry = claimed.entry;
2781
+ }
2782
+ try {
2783
+ const result = await runSessionInput(payload, delivery);
2784
+ claimEntry?.settle({ accepted: true, receipt: { accepted: true, messageId: result.messageId } });
2785
+ return result;
2786
+ } catch (error) {
2787
+ claimEntry?.settle({ accepted: false, error });
2788
+ throw error;
2789
+ }
2790
+ };
2791
+
2792
+ const runSessionInput = async (payload, delivery) => {
2662
2793
  if (!payload || typeof payload !== 'object' || typeof payload.sessionId !== 'string'
2663
2794
  || typeof payload.text !== 'string' || payload.text.length === 0 || Buffer.byteLength(payload.text) > 64 * 1024) {
2664
2795
  throw new SessionDaemonProtocolError('INVALID_PROMPT', 'The session prompt is invalid.');
@@ -2678,10 +2809,15 @@ export function createSessionDaemon({
2678
2809
  }
2679
2810
  if (recreated) activeRuntime = await activateSession(payload.sessionId, payload.directory);
2680
2811
  await flushPendingResourceReload(activeRuntime);
2812
+ // Requested delivery always travels as SDK `streamingBehavior`; the SDK
2813
+ // ignores it while idle and queues while streaming. Sampling
2814
+ // `isStreaming` before the model/attachment awaits would drop a queued
2815
+ // followUp/steer that arrives idle but races another sender that starts
2816
+ // during those awaits, so never gate the option on that early sample.
2681
2817
  // After a provider stream dies, Pi can report idle while the UI still
2682
2818
  // retries as steer/follow-up. Start a new turn instead of rejecting.
2683
- const deliverAs = delivery && activeRuntime.session.isStreaming ? delivery : undefined;
2684
- if (!deliverAs && activeRuntime.session.isStreaming) {
2819
+ const requestedDelivery = delivery ?? undefined;
2820
+ if (!requestedDelivery && activeRuntime.session.isStreaming) {
2685
2821
  throw new SessionDaemonProtocolError('SESSION_BUSY', 'The Pi session already has an active run.');
2686
2822
  }
2687
2823
  beginSessionInput(activeRuntime);
@@ -2723,9 +2859,8 @@ export function createSessionDaemon({
2723
2859
 
2724
2860
  const attachments = await prepareAttachmentContent(payload.attachments);
2725
2861
  const text = [payload.text, attachments.text].filter(Boolean).join('\n\n');
2726
- const content = attachments.images.length > 0
2727
- ? [{ type: 'text', text }, ...attachments.images]
2728
- : text;
2862
+ const images = attachments.images.length > 0 ? attachments.images : undefined;
2863
+ const isSlashPrompt = typeof text === 'string' && text.startsWith('/');
2729
2864
  const messageId = typeof payload.messageId === 'string' && payload.messageId.length > 0
2730
2865
  ? payload.messageId
2731
2866
  : activeRuntime.session.sessionManager?.getLeafId?.() ?? `msg_${randomUUID()}`;
@@ -2736,9 +2871,11 @@ export function createSessionDaemon({
2736
2871
  const generation = (sendGenerationBySession.get(payload.sessionId) ?? 0) + 1;
2737
2872
  sendGenerationBySession.set(payload.sessionId, generation);
2738
2873
  // Slash-prefixed input dispatches extension commands and skill/template
2739
- // expansion exactly like the pi CLI and RPC modes; plain text keeps the
2740
- // sendUserMessage path so it is never expanded.
2741
- enqueueUserStart(payload.sessionId, generation, attachments.files);
2874
+ // expansion exactly like the pi CLI and RPC modes; plain text uses
2875
+ // prompt() with template expansion disabled and source "extension",
2876
+ // matching sendUserMessage() semantics while exposing the SDK
2877
+ // preflightResult acceptance signal.
2878
+ enqueueUserStart(payload.sessionId, generation, attachments.files, requestedDelivery);
2742
2879
  // Pi's `session.setModel()` notifies extensions (`model_select`) but not
2743
2880
  // session subscribers, so an extension-driven model switch would otherwise
2744
2881
  // never publish `session.model`. Snapshot the live model to reconcile
@@ -2747,20 +2884,81 @@ export function createSessionDaemon({
2747
2884
  const prevModel = activeRuntime.session?.model
2748
2885
  ? { provider: activeRuntime.session.model.provider, id: activeRuntime.session.model.id }
2749
2886
  : null;
2750
- let sendCall;
2887
+ let promptPromise;
2888
+ // True SDK acceptance: await the prompt preflight signal, not the full
2889
+ // agent turn. preflightResult(true) means accepted, queued, or handled;
2890
+ // preflightResult(false) is followed by a prompt rejection that must
2891
+ // propagate to the caller so dedup does not cache it as accepted.
2892
+ let preflightOutcome = null;
2893
+ let notifyPreflight;
2894
+ const preflightGate = new Promise((resolve) => { notifyPreflight = resolve; });
2895
+ const onPreflightResult = (accepted) => {
2896
+ if (preflightOutcome !== null) return;
2897
+ preflightOutcome = accepted === true;
2898
+ notifyPreflight(preflightOutcome);
2899
+ };
2751
2900
  try {
2752
- sendCall = typeof content === 'string' && content.startsWith('/')
2753
- ? activeRuntime.session.prompt(content, {
2901
+ promptPromise = isSlashPrompt
2902
+ ? activeRuntime.session.prompt(text, {
2754
2903
  source: 'rpc',
2755
- ...(deliverAs ? { streamingBehavior: deliverAs } : {}),
2904
+ ...(images ? { images } : {}),
2905
+ ...(requestedDelivery ? { streamingBehavior: requestedDelivery } : {}),
2906
+ preflightResult: onPreflightResult,
2756
2907
  })
2757
- : activeRuntime.session.sendUserMessage(content, deliverAs ? { deliverAs } : undefined);
2908
+ : activeRuntime.session.prompt(text, {
2909
+ expandPromptTemplates: false,
2910
+ source: 'extension',
2911
+ ...(images ? { images } : {}),
2912
+ ...(requestedDelivery ? { streamingBehavior: requestedDelivery } : {}),
2913
+ preflightResult: onPreflightResult,
2914
+ });
2758
2915
  } catch (error) {
2759
2916
  removeUserStart(payload.sessionId, generation);
2760
2917
  throw error;
2761
2918
  }
2762
- Promise.resolve(sendCall).then(() => {
2919
+ // A settlement without a preflight signal resolves the gate so a missing
2920
+ // callback cannot hang acceptance. Resolve implies acceptance; reject
2921
+ // implies preflight failure whose real error is propagated below. The
2922
+ // installed SDK always signals, so this only covers test doubles.
2923
+ Promise.resolve(promptPromise).then(
2924
+ () => { if (preflightOutcome === null) { preflightOutcome = true; notifyPreflight(true); } },
2925
+ () => { if (preflightOutcome === null) { preflightOutcome = false; notifyPreflight(false); } },
2926
+ );
2927
+ const preflightAccepted = await preflightGate;
2928
+ if (!preflightAccepted) {
2929
+ let preflightError;
2930
+ try {
2931
+ await promptPromise;
2932
+ preflightError = new Error('The Pi session rejected the prompt before acceptance.');
2933
+ } catch (error) {
2934
+ preflightError = error;
2935
+ }
2763
2936
  removeUserStart(payload.sessionId, generation);
2937
+ throw preflightError;
2938
+ }
2939
+ Promise.resolve(promptPromise).then(() => {
2940
+ // Queued sends resolve on queueing, before the queued user message
2941
+ // starts. Keep that file metadata until the per-delivery
2942
+ // `message_start` consumes it. Retention is decided at resolution
2943
+ // time from authoritative runtime state, not from the early
2944
+ // `requestedDelivery` flag alone: an idle followUp/steer that the SDK
2945
+ // ignored (new turn, no queue) and any handled extension command
2946
+ // (never emits a user start) must not retain forever. Only a still-
2947
+ // streaming session or a non-empty SDK queue proves the send is
2948
+ // queued; handled extension commands never retain even while
2949
+ // streaming.
2950
+ const stillStreaming = Boolean(activeRuntime.session?.isStreaming);
2951
+ let hasQueuedMessages = false;
2952
+ try {
2953
+ hasQueuedMessages = (activeRuntime.session?.getSteeringMessages?.().length ?? 0) > 0
2954
+ || (activeRuntime.session?.getFollowUpMessages?.().length ?? 0) > 0;
2955
+ } catch {
2956
+ hasQueuedMessages = false;
2957
+ }
2958
+ const shouldRetain = !isExtensionCommand && (stillStreaming || hasQueuedMessages);
2959
+ if (!shouldRetain) {
2960
+ removeUserStart(payload.sessionId, generation);
2961
+ }
2764
2962
  if (sendGenerationBySession.get(payload.sessionId) !== generation) return;
2765
2963
  if (settledSendGenerationBySession.get(payload.sessionId) === generation) return;
2766
2964
  const curModel = activeRuntime.session?.model;
@@ -2865,6 +3063,8 @@ export function createSessionDaemon({
2865
3063
  sendGenerationBySession.delete(sessionId);
2866
3064
  settledSendGenerationBySession.delete(sessionId);
2867
3065
  pendingUserStartsBySession.delete(sessionId);
3066
+ queueSizesBySession.delete(sessionId);
3067
+ queueShrinkBySession.delete(sessionId);
2868
3068
  latestUserMessageIds.delete(sessionId);
2869
3069
  latestAssistantMessageIds.delete(sessionId);
2870
3070
  toolInputBySession.delete(sessionId);
@@ -3071,9 +3271,24 @@ export function createSessionDaemon({
3071
3271
  }, sessionId, directory);
3072
3272
  break;
3073
3273
  }
3074
- case 'queue_update':
3075
- publish('session.queue', { steering: event.steering.length, followUp: event.followUp.length }, sessionId, directory);
3274
+ case 'queue_update': {
3275
+ const steeringLength = Array.isArray(event.steering) ? event.steering.length : 0;
3276
+ const followUpLength = Array.isArray(event.followUp) ? event.followUp.length : 0;
3277
+ // Authoritative ownership for the next user start: only a shrink
3278
+ // tells which SDK queue owns it. Enqueues grow; dequeues shrink
3279
+ // immediately before their `message_start`. No text matching.
3280
+ const previous = queueSizesBySession.get(sessionId);
3281
+ if (previous) {
3282
+ const steeringShrank = steeringLength < previous.steering;
3283
+ const followUpShrank = followUpLength < previous.followUp;
3284
+ if (steeringShrank && !followUpShrank) queueShrinkBySession.set(sessionId, 'steer');
3285
+ else if (followUpShrank && !steeringShrank) queueShrinkBySession.set(sessionId, 'followUp');
3286
+ else if (steeringShrank || followUpShrank) queueShrinkBySession.delete(sessionId);
3287
+ }
3288
+ queueSizesBySession.set(sessionId, { steering: steeringLength, followUp: followUpLength });
3289
+ publish('session.queue', { steering: steeringLength, followUp: followUpLength }, sessionId, directory);
3076
3290
  break;
3291
+ }
3077
3292
  case 'agent_start':
3078
3293
  clearIdleDisposal(sessionId);
3079
3294
  retryStateBySession.delete(sessionId);
@@ -3222,7 +3437,7 @@ export function createSessionDaemon({
3222
3437
  'runtime.claim', 'runtime.shutdown',
3223
3438
  'projects.list', 'projects.select', 'sessions.list', 'sessions.create', 'sessions.open', 'sessions.messages', 'sessions.rename', 'sessions.delete',
3224
3439
  'sessions.tree', 'sessions.navigate', 'sessions.fork', 'sessions.clone', 'sessions.prompt',
3225
- 'sessions.steer', 'sessions.followUp', 'sessions.abort', 'sessions.setModel',
3440
+ 'sessions.steer', 'sessions.followUp', 'sessions.sendReceipt', 'sessions.abort', 'sessions.setModel',
3226
3441
  'sessions.setThinking', 'sessions.compact', 'providers.list', 'providers.refresh', 'providers.config.get', 'providers.models.set', 'providers.status', 'providers.login',
3227
3442
  'providers.login.respond', 'providers.login.status', 'providers.logout', 'settings.get', 'settings.set',
3228
3443
  'resources.list', 'resources.update', 'resources.prompts.create', 'resources.prompts.update', 'resources.prompts.delete',
@@ -3539,6 +3754,42 @@ export function createSessionDaemon({
3539
3754
  writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result });
3540
3755
  return;
3541
3756
  }
3757
+ case 'sessions.sendReceipt': {
3758
+ // Exact read-only receipt lookup for an uncertain send. Requires the
3759
+ // full `kind + sessionId + operationId` identity; never invokes Pi,
3760
+ // never mutates the registry except bounded expiry eviction inside
3761
+ // `query()`. Returns `accepted` (retained receipt), `pending`
3762
+ // (still-accepting claim), `expired` (seen but retention gone —
3763
+ // outcome unknown, never assume success), or `unknown` (never seen
3764
+ // in this retention window, tombstone pressure, post-restart, or
3765
+ // rejected before Pi ran so nothing executed).
3766
+ const payload = message.payload ?? {};
3767
+ const kind = payload.kind;
3768
+ const sessionId = payload.sessionId;
3769
+ const operationId = payload.operationId;
3770
+ if ((kind !== 'prompt' && kind !== 'steer' && kind !== 'followUp')
3771
+ || typeof sessionId !== 'string' || sessionId.length === 0
3772
+ || !isValidSendOperationId(operationId)) {
3773
+ throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The send receipt lookup is invalid.');
3774
+ }
3775
+ const lookup = sendOperations.query({ kind, sessionId, operationId });
3776
+ if (lookup.status === 'accepted') {
3777
+ writeFrame(socket, {
3778
+ protocolVersion: PROTOCOL_VERSION,
3779
+ kind: 'response',
3780
+ requestId: message.requestId,
3781
+ result: { status: 'accepted', receipt: lookup.receipt },
3782
+ });
3783
+ return;
3784
+ }
3785
+ writeFrame(socket, {
3786
+ protocolVersion: PROTOCOL_VERSION,
3787
+ kind: 'response',
3788
+ requestId: message.requestId,
3789
+ result: { status: lookup.status },
3790
+ });
3791
+ return;
3792
+ }
3542
3793
  case 'sessions.abort': {
3543
3794
  const activeRuntime = await activateSession(message.payload?.sessionId, message.payload?.directory || message.payload?.cwd);
3544
3795
  const streaming = activeRuntime.session.isStreaming;
@@ -3739,6 +3990,8 @@ export function createSessionDaemon({
3739
3990
  sendGenerationBySession.clear();
3740
3991
  settledSendGenerationBySession.clear();
3741
3992
  pendingUserStartsBySession.clear();
3993
+ queueSizesBySession.clear();
3994
+ queueShrinkBySession.clear();
3742
3995
  latestUserMessageIds.clear();
3743
3996
  latestAssistantMessageIds.clear();
3744
3997
  for (const client of clients) client.destroy();
@@ -24,6 +24,7 @@ class FakeSession {
24
24
  this.names = [];
25
25
  this.entries = [];
26
26
  this.sent = [];
27
+ this.promptCalls = [];
27
28
  this.aborted = 0;
28
29
  this.compacted = 0;
29
30
  this.model = { provider: 'test', id: 'model' };
@@ -65,7 +66,12 @@ class FakeSession {
65
66
  for (const listener of this.listeners) listener(event);
66
67
  }
67
68
 
68
- async prompt() {}
69
+ async prompt(text, options) {
70
+ this.promptCalls.push({ text, options });
71
+ options?.preflightResult?.(true);
72
+ const deliverAs = options?.streamingBehavior;
73
+ this.sent.push({ text, options: deliverAs ? { deliverAs } : undefined });
74
+ }
69
75
 
70
76
  async sendUserMessage(text, options) { this.sent.push({ text, options }); }
71
77
 
@@ -2250,8 +2256,11 @@ describe('Pi session daemon spike', () => {
2250
2256
  await writeFile(sessionFile, `{"type":"session","id":"session-1","cwd":"${root}"}\n`);
2251
2257
  const session = new FakeSession('session-1', sessionFile);
2252
2258
  let finishTurn;
2253
- session.sendUserMessage = (text, options) => {
2254
- session.sent.push({ text, options });
2259
+ session.prompt = (text, options) => {
2260
+ session.promptCalls.push({ text, options });
2261
+ options?.preflightResult?.(true);
2262
+ const deliverAs = options?.streamingBehavior;
2263
+ session.sent.push({ text, options: deliverAs ? { deliverAs } : undefined });
2255
2264
  return new Promise((resolve) => {
2256
2265
  finishTurn = resolve;
2257
2266
  });
@@ -2290,8 +2299,11 @@ describe('Pi session daemon spike', () => {
2290
2299
  await writeFile(imageFile, Buffer.from('fake-png-data'));
2291
2300
  const session = new FakeSession('session-1', sessionFile);
2292
2301
  const finishSends = [];
2293
- session.sendUserMessage = (content, options) => {
2294
- session.sent.push({ text: content, options });
2302
+ session.prompt = (text, options) => {
2303
+ session.promptCalls.push({ text, options });
2304
+ options?.preflightResult?.(true);
2305
+ const deliverAs = options?.streamingBehavior;
2306
+ session.sent.push({ text, options: deliverAs ? { deliverAs } : undefined });
2295
2307
  return new Promise((resolve) => finishSends.push(resolve));
2296
2308
  };
2297
2309
  daemon = createSessionDaemon({
@@ -2341,9 +2353,15 @@ describe('Pi session daemon spike', () => {
2341
2353
  },
2342
2354
  });
2343
2355
  expect(session.sent).toHaveLength(2);
2344
- expect(Array.isArray(session.sent[1].text)).toBe(true);
2345
- expect(session.sent[1].text[0]).toEqual({ type: 'text', text: 'what is this?' });
2346
- expect(session.sent[1].text[1]).toEqual({ type: 'image', mimeType: 'image/png', data: Buffer.from('fake-png-data').toString('base64') });
2356
+ expect(session.promptCalls).toHaveLength(2);
2357
+ expect(session.promptCalls[0]).toMatchObject({
2358
+ text: 'first without a file',
2359
+ options: expect.objectContaining({ expandPromptTemplates: false, source: 'extension' }),
2360
+ });
2361
+ expect(session.promptCalls[0].options.images).toBeUndefined();
2362
+ expect(session.promptCalls[1].text).toBe('what is this?');
2363
+ expect(session.promptCalls[1].options).toMatchObject({ expandPromptTemplates: false, source: 'extension' });
2364
+ expect(session.promptCalls[1].options.images).toEqual([{ type: 'image', mimeType: 'image/png', data: Buffer.from('fake-png-data').toString('base64') }]);
2347
2365
  for (const finish of finishSends) finish();
2348
2366
  await client.close();
2349
2367
  });
@@ -2374,7 +2392,9 @@ describe('Pi session daemon spike', () => {
2374
2392
 
2375
2393
  expect(response.result.accepted).toBe(true);
2376
2394
  expect(session.sent).toHaveLength(1);
2377
- expect(session.sent[0].options).toBeUndefined();
2395
+ // Requested delivery always travels as SDK `streamingBehavior`; the SDK
2396
+ // ignores it while idle and starts a new turn.
2397
+ expect(session.sent[0].options).toEqual({ deliverAs: 'followUp' });
2378
2398
  await client.close();
2379
2399
  });
2380
2400
 
@@ -2387,8 +2407,10 @@ describe('Pi session daemon spike', () => {
2387
2407
  let rejectFirst;
2388
2408
  let finishSecond;
2389
2409
  let sendCount = 0;
2390
- session.sendUserMessage = (text, options) => {
2391
- session.sent.push({ text, options });
2410
+ session.prompt = (text, options) => {
2411
+ session.promptCalls.push({ text, options });
2412
+ options?.preflightResult?.(true);
2413
+ session.sent.push({ text, options: options?.streamingBehavior ? { deliverAs: options.streamingBehavior } : undefined });
2392
2414
  sendCount += 1;
2393
2415
  if (sendCount === 1) return new Promise((_, reject) => { rejectFirst = reject; });
2394
2416
  return new Promise((resolve) => { finishSecond = resolve; });
@@ -2420,8 +2442,10 @@ describe('Pi session daemon spike', () => {
2420
2442
  const sessionFile = join(root, 'session-1.jsonl');
2421
2443
  await writeFile(sessionFile, `{"type":"session","id":"session-1","cwd":"${root}"}\n`);
2422
2444
  const session = new FakeSession('session-1', sessionFile);
2423
- session.sendUserMessage = (text, options) => {
2424
- session.sent.push({ text, options });
2445
+ session.prompt = (text, options) => {
2446
+ session.promptCalls.push({ text, options });
2447
+ options?.preflightResult?.(true);
2448
+ session.sent.push({ text, options: options?.streamingBehavior ? { deliverAs: options.streamingBehavior } : undefined });
2425
2449
  session.isStreaming = true;
2426
2450
  return Promise.reject(new Error('Stream ended without finish_reason'));
2427
2451
  };
@@ -87,7 +87,14 @@ class FakeSession {
87
87
  }
88
88
  }
89
89
 
90
- async prompt() {}
90
+ async prompt(text, options) {
91
+ options?.preflightResult?.(true);
92
+ const deliverAs = options?.streamingBehavior;
93
+ this.sent.push({ text, options: deliverAs ? { deliverAs } : undefined });
94
+ if (this.pendingSend) {
95
+ await this.pendingSend;
96
+ }
97
+ }
91
98
 
92
99
  async sendUserMessage(text, options) {
93
100
  this.sent.push({ text, options });
@@ -46,7 +46,9 @@ class FakeSession {
46
46
  }
47
47
  }
48
48
 
49
- async prompt() {}
49
+ async prompt(text, options) {
50
+ options?.preflightResult?.(true);
51
+ }
50
52
 
51
53
  async sendUserMessage() {}
52
54
 
@@ -26,6 +26,11 @@ const DEFAULT_ALLOWED_CORS_HEADERS = [
26
26
  'x-pichamber-mime',
27
27
  ].join(',');
28
28
 
29
+ const EXPOSED_UI_CORS_HEADERS = [
30
+ 'x-pichamber-file-revision',
31
+ 'x-pichamber-file-exists',
32
+ ].join(',');
33
+
29
34
  export const isAllowedUiCorsOrigin = (origin) => (
30
35
  typeof origin === 'string'
31
36
  && (ALLOWED_UI_CORS_ORIGINS.has(origin) || LOOPBACK_HTTP_ORIGIN.test(origin))
@@ -48,6 +53,7 @@ export const applyUiCorsHeaders = (req, res) => {
48
53
  res.setHeader('Access-Control-Allow-Credentials', 'true');
49
54
  res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');
50
55
  res.setHeader('Access-Control-Allow-Headers', resolveAllowedCorsHeaders(req.headers?.['access-control-request-headers']));
56
+ res.setHeader('Access-Control-Expose-Headers', EXPOSED_UI_CORS_HEADERS);
51
57
  res.setHeader('Vary', 'Origin');
52
58
  return req.method === 'OPTIONS';
53
59
  };
@@ -36,5 +36,8 @@ describe('packaged UI CORS', () => {
36
36
  expect(ended).toBe(true);
37
37
  expect(headers['Access-Control-Allow-Origin']).toBe('pichamber-ui://app');
38
38
  expect(headers['Access-Control-Allow-Headers']).toBe('x-pichamber-directory,x-pichamber-filename,x-pichamber-mime,authorization');
39
+ expect(headers['Access-Control-Expose-Headers']).toBe(
40
+ 'x-pichamber-file-revision,x-pichamber-file-exists',
41
+ );
39
42
  });
40
43
  });
@@ -13,7 +13,11 @@ import { createTerminalRuntime } from '../terminal/runtime.js';
13
13
  import { createSttRuntime } from '../stt/runtime.js';
14
14
  import { getExecutableSearchDirectories } from '../tunnels/executable-search.js';
15
15
 
16
- const normalizeDirectoryPath = (value) => (typeof value === 'string' ? path.resolve(value.trim()) : '');
16
+ export const normalizeDirectoryPath = (value) => {
17
+ if (typeof value !== 'string') return '';
18
+ const requested = value.trim();
19
+ return path.resolve(requested === '~' ? os.homedir() : requested);
20
+ };
17
21
 
18
22
  const buildAugmentedPath = () => mergePathValues(process.env.PATH || '', process.env.Path || '', path.delimiter);
19
23
 
@@ -40,7 +44,7 @@ const resolveProjectDirectory = async (req) => {
40
44
  const requested = typeof query === 'string' && query.trim() ? query.trim() : (typeof header === 'string' ? header.trim() : '');
41
45
  if (!requested) return { directory: process.cwd(), error: null };
42
46
  try {
43
- const resolved = path.resolve(requested);
47
+ const resolved = normalizeDirectoryPath(requested);
44
48
  const stats = await fs.promises.stat(resolved);
45
49
  if (!stats.isDirectory()) return { directory: null, error: 'Specified path is not a directory' };
46
50
  return { directory: await fs.promises.realpath(resolved), error: null };
@@ -0,0 +1,15 @@
1
+ import os from 'node:os';
2
+ import path from 'node:path';
3
+ import { describe, expect, it } from 'vitest';
4
+
5
+ import { normalizeDirectoryPath } from './host.js';
6
+
7
+ describe('workspace directory normalization', () => {
8
+ it('expands the global-session home sentinel', () => {
9
+ expect(normalizeDirectoryPath('~')).toBe(path.resolve(os.homedir()));
10
+ });
11
+
12
+ it('keeps ordinary path resolution behavior', () => {
13
+ expect(normalizeDirectoryPath('./workspace')).toBe(path.resolve('./workspace'));
14
+ });
15
+ });
@@ -1 +0,0 @@
1
- import{R as e,j as h}from"./vendor-react-B5Z1Mdn3.js";import{D as E}from"./vendor-react-drawio-BYDptOsj.js";import{m as x}from"./index-jrfQYSvP.js";const D='<mxfile><diagram id="new" name="Page-1"><mxGraphModel dx="0" dy="0" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0"><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel></diagram></mxfile>';function g(){if(typeof document>"u")return!1;const o=document.documentElement.getAttribute("data-theme");return o==="dark"||!o&&window.matchMedia("(prefers-color-scheme: dark)").matches}const X=e.forwardRef(function({xml:t,readOnly:a,className:R,onChange:c},v){const s=e.useRef(t),i=e.useRef(null),m=e.useRef(!1),[n,k]=e.useState(g),u=e.useRef(t),d=e.useRef(t);d.current!==t&&(d.current=t,u.current=t,s.current=t);const f=e.useRef(n);f.current!==n&&(f.current=n,u.current=s.current);const l=e.useRef(null);e.useEffect(()=>{const r=()=>k(g());r();const p=new MutationObserver(r);return p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),()=>p.disconnect()},[]),e.useEffect(()=>{const r=setTimeout(()=>{l.current?.querySelector(".diagrams-iframe")?.focus()},600);return()=>clearTimeout(r)},[]),e.useImperativeHandle(v,()=>({getXml:()=>s.current}));const b=e.useCallback(()=>{!t&&!m.current&&(m.current=!0,setTimeout(()=>{i.current?.template({})},500))},[t]),w=e.useCallback(r=>{s.current=r.xml,c?.(r.xml)},[c]);return h.jsx("div",{ref:l,className:x("h-full w-full",R),children:h.jsx(E,{ref:i,xml:u.current||D,autosave:!0,urlParameters:{ui:a?"simple":n?"dark":"kennedy",spin:!0,libraries:!a,chrome:a,nav:a,layers:a,noSaveBtn:!0,noExitBtn:!0,saveAndExit:!1},onLoad:b,onAutoSave:w},n?"dark":"light")})});export{X as D};