@pi-chamber/web 0.8.1 → 0.8.2

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 (58) hide show
  1. package/dist/assets/{DiagramEditor-D_3eJVSw.js → DiagramEditor-DerMrS6m.js} +1 -1
  2. package/dist/assets/{DiagramView-pGYm0-DR.js → DiagramView-DdipXAq8.js} +1 -1
  3. package/dist/assets/{DiffView-BApPTLGp.js → DiffView-Gh9wjthp.js} +1 -1
  4. package/dist/assets/FilesView-BXp0yc0j.js +6 -0
  5. package/dist/assets/{GitView-uW3w_LlQ.js → GitView-BmNCkkoC.js} +3 -3
  6. package/dist/assets/{JsonTreeView-CpgqCk9_.js → JsonTreeView-CxXRXXzk.js} +1 -1
  7. package/dist/assets/{MarkdownRendererImpl-fI6n3kqT.js → MarkdownRendererImpl-DNZQgQua.js} +1 -1
  8. package/dist/assets/{PatchDiff-BRloGXPs.js → PatchDiff-B_NFEIX7.js} +1 -1
  9. package/dist/assets/{SessionSwitcherContent-BQc-vW4s.js → SessionSwitcherContent-Q4P2TGBr.js} +1 -1
  10. package/dist/assets/{SessionSwitcherDropdown-v_8TaIZm.js → SessionSwitcherDropdown-Cgw2mQIO.js} +2 -2
  11. package/dist/assets/{SessionUnreadDot-A7vSfll2.js → SessionUnreadDot-BxtTkvHB.js} +1 -1
  12. package/dist/assets/SettingsView-CFzxRzUq.js +2 -0
  13. package/dist/assets/{SettingsWindow-D7UDhYd4.js → SettingsWindow-BEjHL1ET.js} +1 -1
  14. package/dist/assets/{ToolOutputDialog-wpU0ylYS.js → ToolOutputDialog-C_7vJLEq.js} +1 -1
  15. package/dist/assets/{ToolPartDiffPreview-BvoQK5Gm.js → ToolPartDiffPreview-ClV785zX.js} +1 -1
  16. package/dist/assets/{VirtualizedFileDiff-DdPbLdh7.js → VirtualizedFileDiff-DrxkW2WQ.js} +1 -1
  17. package/dist/assets/{collapsible-BO6FIjvn.js → collapsible-CR3-hRMy.js} +1 -1
  18. package/dist/assets/{computeVirtualFileMetrics-DMvXzUJh.js → computeVirtualFileMetrics-D0mQcleY.js} +1 -1
  19. package/dist/assets/{contextFileOpenGuard-BwXQVjtS.js → contextFileOpenGuard-BRc5Z0g-.js} +1 -1
  20. package/dist/assets/{gitStatusPredicates-CgNk6M2_.js → gitStatusPredicates-DBGDfr1K.js} +1 -1
  21. package/dist/assets/{index-C3SyF-cA.js → index-CMfiVUIr.js} +1 -1
  22. package/dist/assets/index-CzO3ooje.css +1 -0
  23. package/dist/assets/index-ivrh3jfy.js +8 -0
  24. package/dist/assets/{isDiffPlainText-BboRbmcm.js → isDiffPlainText-MmBA1REG.js} +1 -1
  25. package/dist/assets/{isFilePlainText-BpTnLRyI.js → isFilePlainText-bQAPxqO9.js} +1 -1
  26. package/dist/assets/{main-CMOAwZnJ.js → main-BoVfUG73.js} +8 -8
  27. package/dist/assets/{main-xLwCWLu-.js → main-zZrKd3hZ.js} +2 -2
  28. package/dist/assets/{markdownCore-CmFv4H-w.js → markdownCore-B9jXCPry.js} +1 -1
  29. package/dist/assets/{miniChat-Vwo4K1IK.js → miniChat-Di2oVS5o.js} +2 -2
  30. package/dist/assets/{mobile-BRaxtEoC.js → mobile-VU_G_SgX.js} +2 -2
  31. package/dist/assets/{renderElectronMiniChatApp-DM4rRUUz.js → renderElectronMiniChatApp-Bi1927c8.js} +2 -2
  32. package/dist/assets/{renderMobileApp-DWWewNhc.js → renderMobileApp-D9mxhuaM.js} +3 -3
  33. package/dist/assets/runtimeEndpointReset-DImT35Ug.js +54 -0
  34. package/dist/assets/{runtimeSurface-SmPSdfop.js → runtimeSurface-CBaS2Ank.js} +1 -1
  35. package/dist/assets/{useAppFontEffects-Bg-8jtrQ.js → useAppFontEffects-8ZU-TTIW.js} +105 -105
  36. package/dist/assets/{useFilesViewSearch-GLcYNIUV.js → useFilesViewSearch-COow9O9x.js} +1 -1
  37. package/dist/assets/{usePushVisibilityBeacon-VSYBfNoY.js → usePushVisibilityBeacon-zYd3ppNh.js} +1 -1
  38. package/dist/assets/{useSwitcherItems-BkEt9K-N.js → useSwitcherItems-DOQqhi-e.js} +1 -1
  39. package/dist/assets/{vendor-codemirror-language-data-B5cJDWBR.js → vendor-codemirror-language-data-B_0wrsbo.js} +2 -2
  40. package/dist/assets/{web-components-0H9kvZwn.js → web-components-C9ENH49P.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/pi/routes.test.js +39 -0
  46. package/server/lib/pi/session-daemon/DOCUMENTATION.md +1 -1
  47. package/server/lib/pi/session-daemon/extension-bridge.js +14 -11
  48. package/server/lib/pi/session-daemon/prompt-operations.test.js +73 -6
  49. package/server/lib/pi/session-daemon/session-daemon.js +163 -21
  50. package/server/lib/relay/host-client.test.js +3 -1
  51. package/server/lib/ui-auth/DOCUMENTATION.md +1 -1
  52. package/server/lib/ui-auth/ui-auth.js +23 -26
  53. package/server/lib/ui-auth/ui-auth.test.js +27 -0
  54. package/dist/assets/FilesView-CiPpuGiF.js +0 -6
  55. package/dist/assets/SettingsView-CphlZvfd.js +0 -2
  56. package/dist/assets/index-BebQicw3.css +0 -1
  57. package/dist/assets/index-Bkz23mZq.js +0 -8
  58. package/dist/assets/runtimeEndpointReset-BF60eHSx.js +0 -54
@@ -28,7 +28,7 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
28
28
  - The public health route deliberately whitelists its response fields. It never returns a daemon endpoint, credential, PID, cwd, agent directory, or transcript data. Public transcript and event projections preserve daemon-redacted assistant error messages so the UI can distinguish provider/runtime failures instead of reducing every failure to `ASSISTANT_ERROR`.
29
29
  - A client must send an `authenticate` frame carrying the host-private daemon credential before it can issue a request. Credentials are never logged or returned.
30
30
  - Frames are LF-delimited JSON. They have a 1 MiB maximum buffered size. A malformed, oversized, unauthenticated, or invalid request closes the connection.
31
- - The private core commands are `runtime.health`, `projects.list/select`, `providers.list/config.get/models.set/status/login/login.respond/login.status/logout`, `settings.get/set`, `resources.list/update/prompts.create/prompts.update/prompts.delete`, `extensions.list/respond`, and session list/create/open/rename/delete/tree/navigate/fork/clone/prompt/steer/followUp/abort/model/thinking/compact operations. Resource lists use opaque IDs and never disclose server paths. Only top-level Pi prompt templates and applicable AGENTS.md sources are editable; package/path resources and skills are browse-only. Prompt-template mutations resolve against the caller's explicit effective directory, reject stale and cross-directory opaque IDs, enforce project trust for project prompts, are rejected while a session streams, serialize create/update/delete operations, preserve existing files on validation or write failure, atomically reserve new destinations without overwriting concurrent writers, use temporary-file persistence with cleanup, preserve unknown frontmatter fields (for example `argument-hint`) when editing description or content, and for rename validate the destination name and scope, reject collisions, write the destination atomically, remove the source only after success, roll back the destination when source removal fails, then recreate the idle runtime and clear the service cache so `/api/pi/commands` reflects the change. Resource writes are rejected while a session streams, use an atomic replace, then recreate the idle runtime. Project trust changes are persisted in Pi trust.json and likewise recreate an idle runtime; project-local extensions load through Pi's own trust flow once trust is resolved. Provider login submits API keys only across authenticated private IPC or brokers Pi's OAuth/device/manual-code interaction; public projections contain only opaque login IDs, prompts, URLs/device codes, model catalog/configuration, and stable states, never credentials or write-only headers. `providers.models.set` is rejected while a session streams, atomically persists Pi's `models.json`, then rehydrates the idle runtime so the catalog is authoritative immediately. `providers.list` projects only catalog and authentication-status metadata, including Pi-supported `thinkingLevels` (`null` map entries hidden, `xhigh`/`max` opt-in). Session thinking overrides are clamped to the live model's supported levels. `sessions.list` checks each cwd JSONL header (not the full transcript) so a project with large session logs cannot spend tens of seconds on startup. SDK `SessionManager.list` is not used for that path; `listPiSessionJsonlDirectory` reads a header, a bounded prefix for the first user prompt, and a tail for the latest rename. Concurrent lists of the same directory share one in-flight result. Concurrent `sessions.open` of the same id share one in-flight runtime create; a duplicate that finishes later disposes itself and returns the registered runtime instead of `SESSION_RUNTIME_CONFLICT`. Full-file JSONL validation stays on open of a chosen session. The browser explicitly selects an existing user-chosen project directory before listing it; the daemon's startup cwd is an internal fallback, not a user-visible default project. Unnamed persisted sessions use their first prompt as a readable list title when available. `sessions.open` and `getSession` project the last assistant `provider`/`model`/`thinkingLevel` onto the session record so reopening a chat keeps that cache identity. Session selection validates a persisted JSONL path before Pi opens it; inactive mutations are never directed by a browser-supplied path. `sessions.open` first checks a caller-supplied directory through its bounded header list, so an ordinary project-scoped open neither walks every directory in the agent store nor adopts a same-id session from another directory. Directory-less deep links resolve by Pi's `timestamp_<id>.jsonl` filename before broader SDK-list and header-scan fallbacks. Directory-wide JSONL checks on list/create/startup are header-only; full-file validation stays on open of a chosen transcript. Attachment paths originate in the server-local upload map and cross only private IPC into Pi's tool context. Pi may persist or echo those paths in its authoritative JSONL transcript, so every public projection redacts them recursively: session titles/previews, user and assistant text/thinking, tool arguments, errors, snapshots, and live message events never expose the server-local path. Persisted projection first checks for the attachment marker, then redacts matching tokens with a delimiter scan whose work stays linear for large encoded strings and tool payloads. The daemon maps Pi message lifecycle, deltas, tools, queue changes, model/thinking, compaction, interruption state, and session title updates (`session.updated` on create-with-title, first-prompt auto-title, and rename) to canonical events. Pi `model_select`, `thinking_level_changed`, and `session_info_changed` events are authoritative for model, thinking, and session-name changes made by extensions, the TUI, or another client. The bridge observes Pi provider registration and label writes because Pi 0.84.1 emits no corresponding session events: provider mutations publish a catalog invalidation, and label mutations invalidate the bounded session-tree projection. `ctx.reload()` clears old extension UI state, reloads Pi resources, and invalidates provider/resource/command catalogs. `ctx.shutdown()` disposes only the requesting idle session runtime after its command or turn settles; it never stops the shared daemon or unrelated sessions. Compaction events preserve Pi's manual/threshold/overflow reason, active/retrying/terminal phase, retry timing, redacted failure, compact-and-retry intent, and pre/post token estimates. The latest state is included in `getSession` and reconnect snapshots; after daemon restart, the latest persisted Pi `CompactionEntry` restores completed feedback without treating history as live work. Tool events carry redacted input arguments, cumulative partial-output snapshots, final output, error text, renderer metadata (edit diffs, truncation notes), and start/end timestamps. Pi loads skills with the ordinary `read` tool. The daemon matches those read paths against the active runtime's authoritative `resourceLoader.getSkills()` catalog and adds path-free `metadata.pichamber.skill.name` for live events, hydrated history, and reconnect snapshots. PiChamber uses that metadata for its compact Skill row and Settings navigation; an arbitrary file named `SKILL.md` remains a normal read. Persisted `toolResult` entries merge into their assistant `toolCall` parts as output/error/end time so hydrated sessions render complete tool cards; tool-result entries never surface as standalone messages. Assistant message projections and start events carry the owning user-message id so the restored turn renderer can group and display replies; all assistant entries in a tool loop and every retry/compaction continuation remain attached to the latest user turn until `agent_settled` closes the run. Assistant message projections also pass through Pi's per-turn `Usage` (input, output, cacheRead, cacheWrite, totalTokens, and the same five numeric cost fields). The daemon sanitizes the raw payload through `projectUsage` before publication: every numeric must be finite and non-negative, the whole object is omitted when any field is missing or wrong type, and unknown keys are never copied. The `assistant.message.end` event carries the same sanitized usage so the last turn updates without waiting for a full `getSession` refetch. The public route whitelist re-applies the same sanitizer on each projection so a stale or malformed payload from a different daemon version cannot surface as `NaN` or `Infinity` in the reducer.
31
+ - The private core commands are `runtime.health`, `projects.list/select`, `providers.list/config.get/models.set/status/login/login.respond/login.status/logout`, `settings.get/set`, `resources.list/update/prompts.create/prompts.update/prompts.delete`, `extensions.list/respond`, and session list/create/open/rename/delete/tree/navigate/fork/clone/prompt/steer/followUp/abort/model/thinking/compact operations. Resource lists use opaque IDs and never disclose server paths. Only top-level Pi prompt templates and applicable AGENTS.md sources are editable; package/path resources and skills are browse-only. Prompt-template mutations resolve against the caller's explicit effective directory, reject stale and cross-directory opaque IDs, enforce project trust for project prompts, serialize create/update/delete operations, preserve existing files on validation or write failure, atomically reserve new destinations without overwriting concurrent writers, use temporary-file persistence with cleanup, preserve unknown frontmatter fields (for example `argument-hint`) when editing description or content, and for rename validate the destination name and scope, reject collisions, write the destination atomically, remove the source only after success, and roll back the destination when source removal fails. A committed prompt mutation never disposes a session runtime: affected idle sessions use Pi's identity-preserving `session.reload()`, while streaming, compacting, and extension-command sessions finish first and reload at their next safe lifecycle edge. Global prompts refresh every resident runtime; project prompts refresh only runtimes in that directory. Mutation responses merge freshly discovered editable prompts with live package/path/extension resources so the Settings page reflects the committed file even while runtime activation is deferred. Generic non-prompt resource writes remain rejected while the active session streams, use an atomic replace, then recreate the idle runtime. Project trust changes are persisted in Pi trust.json and likewise recreate an idle runtime; project-local extensions load through Pi's own trust flow once trust is resolved. Provider login submits API keys only across authenticated private IPC or brokers Pi's OAuth/device/manual-code interaction; public projections contain only opaque login IDs, prompts, URLs/device codes, model catalog/configuration, and stable states, never credentials or write-only headers. `providers.models.set` is rejected while a session streams, atomically persists Pi's `models.json`, then rehydrates the idle runtime so the catalog is authoritative immediately. `providers.list` projects only catalog and authentication-status metadata, including Pi-supported `thinkingLevels` (`null` map entries hidden, `xhigh`/`max` opt-in). Session thinking overrides are clamped to the live model's supported levels. `sessions.list` checks each cwd JSONL header (not the full transcript) so a project with large session logs cannot spend tens of seconds on startup. SDK `SessionManager.list` is not used for that path; `listPiSessionJsonlDirectory` reads a header, a bounded prefix for the first user prompt, and a tail for the latest rename. Concurrent lists of the same directory share one in-flight result. Concurrent `sessions.open` of the same id share one in-flight runtime create; a duplicate that finishes later disposes itself and returns the registered runtime instead of `SESSION_RUNTIME_CONFLICT`. Full-file JSONL validation stays on open of a chosen session. The browser explicitly selects an existing user-chosen project directory before listing it; the daemon's startup cwd is an internal fallback, not a user-visible default project. Unnamed persisted sessions use their first prompt as a readable list title when available. `sessions.open` and `getSession` project the last assistant `provider`/`model`/`thinkingLevel` onto the session record so reopening a chat keeps that cache identity. Session selection validates a persisted JSONL path before Pi opens it; inactive mutations are never directed by a browser-supplied path. `sessions.open` first checks a caller-supplied directory through its bounded header list, so an ordinary project-scoped open neither walks every directory in the agent store nor adopts a same-id session from another directory. Directory-less deep links resolve by Pi's `timestamp_<id>.jsonl` filename before broader SDK-list and header-scan fallbacks. Directory-wide JSONL checks on list/create/startup are header-only; full-file validation stays on open of a chosen transcript. Attachment paths originate in the server-local upload map and cross only private IPC into Pi's tool context. Pi may persist or echo those paths in its authoritative JSONL transcript, so every public projection redacts them recursively: session titles/previews, user and assistant text/thinking, tool arguments, errors, snapshots, and live message events never expose the server-local path. Persisted projection first checks for the attachment marker, then redacts matching tokens with a delimiter scan whose work stays linear for large encoded strings and tool payloads. The daemon maps Pi message lifecycle, deltas, tools, queue changes, model/thinking, compaction, interruption state, and session title updates (`session.updated` on create-with-title, first-prompt auto-title, and rename) to canonical events. Pi `model_select`, `thinking_level_changed`, and `session_info_changed` events are authoritative for model, thinking, and session-name changes made by extensions, the TUI, or another client. The bridge observes Pi provider registration and label writes because Pi 0.84.1 emits no corresponding session events: provider mutations publish a catalog invalidation, and label mutations invalidate the bounded session-tree projection. `ctx.reload()` clears old extension UI state, reloads Pi resources, and invalidates provider/resource/command catalogs. `ctx.shutdown()` disposes only the requesting idle session runtime after its command or turn settles; it never stops the shared daemon or unrelated sessions. Compaction events preserve Pi's manual/threshold/overflow reason, active/retrying/terminal phase, retry timing, redacted failure, compact-and-retry intent, and pre/post token estimates. The latest state is included in `getSession` and reconnect snapshots; after daemon restart, the latest persisted Pi `CompactionEntry` restores completed feedback without treating history as live work. Tool events carry redacted input arguments, cumulative partial-output snapshots, final output, error text, renderer metadata (edit diffs, truncation notes), and start/end timestamps. Pi loads skills with the ordinary `read` tool. The daemon matches those read paths against the active runtime's authoritative `resourceLoader.getSkills()` catalog and adds path-free `metadata.pichamber.skill.name` for live events, hydrated history, and reconnect snapshots. PiChamber uses that metadata for its compact Skill row and Settings navigation; an arbitrary file named `SKILL.md` remains a normal read. Persisted `toolResult` entries merge into their assistant `toolCall` parts as output/error/end time so hydrated sessions render complete tool cards; tool-result entries never surface as standalone messages. Assistant message projections and start events carry the owning user-message id so the restored turn renderer can group and display replies; all assistant entries in a tool loop and every retry/compaction continuation remain attached to the latest user turn until `agent_settled` closes the run. Assistant message projections also pass through Pi's per-turn `Usage` (input, output, cacheRead, cacheWrite, totalTokens, and the same five numeric cost fields). The daemon sanitizes the raw payload through `projectUsage` before publication: every numeric must be finite and non-negative, the whole object is omitted when any field is missing or wrong type, and unknown keys are never copied. The `assistant.message.end` event carries the same sanitized usage so the last turn updates without waiting for a full `getSession` refetch. The public route whitelist re-applies the same sanitizer on each projection so a stale or malformed payload from a different daemon version cannot surface as `NaN` or `Infinity` in the reducer.
32
32
  - Live `message_start` events use daemon-generated browser message IDs because Pi has not appended the corresponding session entry yet. Pi agent-core emits streaming assistant starts as shallow copies, not as the finalized object it later persists. At `message_end`, `message-entry-aliases.js` therefore rebinds the synthetic ID to the finalized event object, then maps that object by identity to Pi's appended entry in a microtask. `sessions.navigate` and `sessions.fork` resolve the mapping after stripping any part suffix. Alias keys include cwd and session ID, survive idle runtime disposal, and clear only on explicit session deletion or daemon shutdown. Hydrated message projections continue to use the Pi entry ID directly.
33
33
  - Each event and reconnect snapshot has a monotonic sequence. A reconnect receives a bounded contiguous replay after its cursor when available, otherwise an authoritative `session.snapshot`; unavailable runtimes are not represented as empty sessions.
34
34
  - Prompt, steer, and follow-up requests acknowledge acceptance immediately after Pi accepts the call; the daemon owns the still-running send promise and publishes any asynchronous rejection as `session.error`. Pi can emit the live user-message start before that message is branch-readable, so the daemon queues each accepted prompt's path-free file metadata and adds it to the matching user start in send order. The browser can render the attachment footer immediately without exposing bytes or server paths, while later hydration remains authoritative. An extension command may resolve without starting an agent turn, so completion of its non-streaming prompt promise publishes the idle lifecycle boundary that Pi does not emit as `agent_settled`. Pi notifies extensions of model switches (`model_select`) but not session subscribers, so that same completion edge also reconciles a changed live model into `session.model` before the idle boundary; thinking already emits `thinking_level_changed` to subscribers and needs no reconciliation. A registered extension invocation is not used for automatic first-prompt naming: an extension-only empty session remains unnamed unless the extension names it, and the first later conversation prompt supplies the derived title. Classification uses the active Pi runtime's registered extension commands, not a browser claim. Manual compact requests likewise acknowledge startup instead of holding the public/private request open for the summarization call; the daemon-owned promise reports its outcome through `session.compaction`. A second compact request while Pi is compacting fails as `SESSION_BUSY`, and optional `/compact` instructions pass to `AgentSession.compact(customInstructions)`. A later prompt on the same session invalidates an older send rejection so it cannot error the new turn. If the rejected send left Pi streaming, the daemon aborts it. Steer/follow-up against an idle session starts a new prompt instead of `SESSION_NOT_RUNNING`. Agent and compaction completion are never held behind the 30-second public/private request budgets. Pi retryable provider failures remain live: an `agent_end` with `willRetry` does not publish terminal `session.error`, and `auto_retry_start` projects Pi's attempt, next-attempt time, and redacted error text through `session.lifecycle: retry`. Retry metadata is retained in reconnect and `getSession` snapshots until the next `agent_start` begins the attempt. `agent_settled` remains the authoritative idle boundary after retry success, exhaustion, or cancellation and clears the run's user/assistant ownership.
@@ -278,6 +278,18 @@ export const createExtensionBridge = ({
278
278
  strikethrough: (text) => text,
279
279
  };
280
280
 
281
+ const reloadSession = async (session) => {
282
+ clearExtensionState(session.sessionId);
283
+ const providerObserver = session.modelRuntime?.[PROVIDER_OBSERVER];
284
+ if (providerObserver) providerObserver.suppress = true;
285
+ try {
286
+ await session.reload();
287
+ } finally {
288
+ if (providerObserver) providerObserver.suppress = false;
289
+ }
290
+ publishCatalogChange(session.sessionId, { providers: true, resources: true, commands: true });
291
+ };
292
+
281
293
  const buildExtensionBindings = (session) => {
282
294
  installMutationObservers(session);
283
295
  return {
@@ -310,17 +322,7 @@ export const createExtensionBridge = ({
310
322
  if (!owner) throw new Error('Session runtime is no longer available.');
311
323
  return owner.switchSession(sessionPath, switchOptions);
312
324
  },
313
- reload: async () => {
314
- clearExtensionState(session.sessionId);
315
- const providerObserver = session.modelRuntime?.[PROVIDER_OBSERVER];
316
- if (providerObserver) providerObserver.suppress = true;
317
- try {
318
- await session.reload();
319
- } finally {
320
- if (providerObserver) providerObserver.suppress = false;
321
- }
322
- publishCatalogChange(session.sessionId, { providers: true, resources: true, commands: true });
323
- },
325
+ reload: () => reloadSession(session),
324
326
  },
325
327
  shutdownHandler: () => requestSessionShutdown?.(session.sessionId),
326
328
  onError: (error) => {
@@ -483,6 +485,7 @@ export const createExtensionBridge = ({
483
485
  mirrorExtensionApp,
484
486
  mirrorExtensionPanel,
485
487
  publishExtensionCustomMessage,
488
+ reloadSession,
486
489
  resolveExtensionDialog,
487
490
  };
488
491
  };
@@ -36,9 +36,20 @@ class FakeSession {
36
36
  constructor() {
37
37
  this.sessionId = 'sess-1';
38
38
  this.isStreaming = false;
39
+ this.isCompacting = false;
39
40
  this.listeners = new Set();
41
+ this.reloadCount = 0;
42
+ this.reloadError = null;
43
+ this.promptImpl = async () => {};
40
44
  }
41
45
  subscribe(l) { this.listeners.add(l); return () => this.listeners.delete(l); }
46
+ emit(event) { for (const listener of this.listeners) listener(event); }
47
+ async reload() {
48
+ this.reloadCount += 1;
49
+ if (this.reloadError) throw this.reloadError;
50
+ }
51
+ prompt(...args) { return this.promptImpl(...args); }
52
+ async sendUserMessage() {}
42
53
  async dispose() {}
43
54
  }
44
55
 
@@ -105,18 +116,25 @@ describe('prompt template daemon operations', () => {
105
116
  await mkdir(cwd, { recursive: true });
106
117
  const sess = session ?? new FakeSession();
107
118
  const baseLoader = loader;
119
+ const runtimeState = { createCount: 0, disposeCount: 0 };
108
120
  daemon = createSessionDaemon({
109
121
  endpoint, credential, cwd, agentDir,
110
122
  createRuntime: async (opts) => {
123
+ runtimeState.createCount += 1;
111
124
  const dir = typeof opts?.cwd === "string" && opts.cwd.length > 0 ? opts.cwd : cwd;
112
125
  const runtimeLoader = baseLoader ?? makeLoader(agentDir, () => dir);
113
- return { cwd: dir, session: sess, services: { resourceLoader: runtimeLoader }, async dispose() {} };
126
+ return {
127
+ cwd: dir,
128
+ session: sess,
129
+ services: { resourceLoader: runtimeLoader },
130
+ async dispose() { runtimeState.disposeCount += 1; },
131
+ };
114
132
  },
115
133
  });
116
134
  await daemon.start();
117
135
  const request = (command, payload = {}) =>
118
136
  requestSessionDaemon({ endpoint, credential, command, payload });
119
- return { root, endpoint, agentDir, cwd, session: sess, request };
137
+ return { root, endpoint, agentDir, cwd, session: sess, runtimeState, request };
120
138
  };
121
139
 
122
140
  it('creates, reads, updates, renames, and deletes a global prompt', async () => {
@@ -283,14 +301,63 @@ describe('prompt template daemon operations', () => {
283
301
  expect(after.prompts.some((p) => p.name === 'renamed')).toBe(false);
284
302
  });
285
303
 
286
- it('blocks mutations while streaming', async () => {
304
+ it('persists mutations while streaming and reloads without disposing after settlement', async () => {
287
305
  const session = new FakeSession();
288
306
  const ctx = await startDaemon({ session });
289
307
  await ctx.request('resources.list', { directory: ctx.cwd });
290
308
  session.isStreaming = true;
291
- await expect(ctx.request('resources.prompts.create', {
292
- name: 'blocked', description: 'Blocked', content: 'x', location: 'global', directory: ctx.cwd,
293
- })).rejects.toMatchObject({ code: 'SESSION_BUSY' });
309
+ const created = await ctx.request('resources.prompts.create', {
310
+ name: 'during-run', description: 'During run', content: 'x', location: 'global', directory: ctx.cwd,
311
+ });
312
+ expect(created.prompts.some((prompt) => prompt.name === 'during-run')).toBe(true);
313
+ expect(session.reloadCount).toBe(0);
314
+ expect(ctx.runtimeState).toEqual({ createCount: 1, disposeCount: 0 });
315
+
316
+ session.isStreaming = false;
317
+ session.emit({ type: 'agent_settled' });
318
+ await expect.poll(() => session.reloadCount).toBe(1);
319
+ expect(ctx.runtimeState).toEqual({ createCount: 1, disposeCount: 0 });
320
+ });
321
+
322
+ it('reloads idle prompt resources in place without replacing the runtime', async () => {
323
+ const ctx = await startDaemon();
324
+ await ctx.request('resources.list', { directory: ctx.cwd });
325
+ await ctx.request('resources.prompts.create', {
326
+ name: 'stable', description: 'Stable', content: 'x', location: 'global', directory: ctx.cwd,
327
+ });
328
+ expect(ctx.session.reloadCount).toBe(1);
329
+ expect(ctx.runtimeState).toEqual({ createCount: 1, disposeCount: 0 });
330
+ });
331
+
332
+ it('defers reload while a non-streaming slash command is still executing', async () => {
333
+ const session = new FakeSession();
334
+ let finishPrompt;
335
+ session.promptImpl = () => new Promise((resolve) => { finishPrompt = resolve; });
336
+ const ctx = await startDaemon({ session });
337
+ await ctx.request('resources.list', { directory: ctx.cwd });
338
+ await ctx.request('sessions.prompt', { sessionId: session.sessionId, text: '/hold', directory: ctx.cwd });
339
+
340
+ const created = await ctx.request('resources.prompts.create', {
341
+ name: 'after-command', description: 'After command', content: 'x', location: 'global', directory: ctx.cwd,
342
+ });
343
+ expect(created.prompts.some((prompt) => prompt.name === 'after-command')).toBe(true);
344
+ expect(session.reloadCount).toBe(0);
345
+
346
+ finishPrompt();
347
+ await expect.poll(() => session.reloadCount).toBe(1);
348
+ expect(ctx.runtimeState).toEqual({ createCount: 1, disposeCount: 0 });
349
+ });
350
+
351
+ it('reports the committed prompt even when runtime reload fails', async () => {
352
+ const ctx = await startDaemon();
353
+ await ctx.request('resources.list', { directory: ctx.cwd });
354
+ ctx.session.reloadError = new Error('reload failed');
355
+ const created = await ctx.request('resources.prompts.create', {
356
+ name: 'committed', description: 'Committed', content: 'x', location: 'global', directory: ctx.cwd,
357
+ });
358
+ expect(created.prompts.some((prompt) => prompt.name === 'committed')).toBe(true);
359
+ await expect(readFile(join(ctx.agentDir, 'prompts', 'committed.md'), 'utf8')).resolves.toContain('x');
360
+ expect(ctx.runtimeState).toEqual({ createCount: 1, disposeCount: 0 });
294
361
  });
295
362
 
296
363
  it('keeps package prompts read-only', async () => {
@@ -5,7 +5,7 @@ import { createReadStream, existsSync, readFileSync } from 'node:fs';
5
5
  import { homedir } from 'node:os';
6
6
  import { fileURLToPath } from 'node:url';
7
7
  import { createInterface } from 'node:readline';
8
- import { basename, dirname, isAbsolute, join, relative } from 'node:path';
8
+ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
9
9
  import { hasTrustRequiringProjectResources } from '@earendil-works/pi-coding-agent';
10
10
  import { StringDecoder } from 'node:string_decoder';
11
11
  import {
@@ -205,6 +205,13 @@ export function createSessionDaemon({
205
205
  const activeRunStartedAt = new Map();
206
206
  const sendGenerationBySession = new Map();
207
207
  const settledSendGenerationBySession = new Map();
208
+ // Pi's reload() is identity-preserving but is not safe during a turn,
209
+ // compaction, or an extension command. Prompt writes mark affected busy
210
+ // runtimes dirty and reload them at the next safe lifecycle edge.
211
+ const activeSessionInputs = new Map();
212
+ const pendingResourceReloads = new Set();
213
+ const resourceReloadsByRuntime = new Map();
214
+ let resourceReloadQueue = Promise.resolve();
208
215
  // Pi emits each user message start before its persisted entry is readable.
209
216
  // Keep prompt metadata in send order so queued follow-ups cannot attach the
210
217
  // next prompt's files to an earlier user message.
@@ -388,6 +395,7 @@ export function createSessionDaemon({
388
395
  mirrorExtensionApp,
389
396
  mirrorExtensionPanel,
390
397
  publishExtensionCustomMessage,
398
+ reloadSession,
391
399
  resolveExtensionDialog,
392
400
  } = extensionBridge;
393
401
 
@@ -497,6 +505,10 @@ export function createSessionDaemon({
497
505
 
498
506
  const disposeRuntime = async () => {
499
507
  clearIdleDisposal();
508
+ activeSessionInputs.clear();
509
+ pendingResourceReloads.clear();
510
+ await resourceReloadQueue.catch(() => {});
511
+ resourceReloadsByRuntime.clear();
500
512
  clearExtensionState(undefined);
501
513
  if (runtimeRegistry) {
502
514
  const hadTrackedRuntime = runtimeRegistry.size > 0;
@@ -537,6 +549,77 @@ export function createSessionDaemon({
537
549
  return runtimeStartPromise;
538
550
  };
539
551
 
552
+ const beginSessionInput = (targetRuntime) => {
553
+ activeSessionInputs.set(targetRuntime, (activeSessionInputs.get(targetRuntime) ?? 0) + 1);
554
+ };
555
+
556
+ const endSessionInput = (targetRuntime) => {
557
+ const remaining = (activeSessionInputs.get(targetRuntime) ?? 0) - 1;
558
+ if (remaining > 0) activeSessionInputs.set(targetRuntime, remaining);
559
+ else activeSessionInputs.delete(targetRuntime);
560
+ };
561
+
562
+ const isRuntimeReloadSafe = (targetRuntime) => {
563
+ const session = targetRuntime?.session;
564
+ return Boolean(
565
+ session?.sessionId
566
+ && session.isStreaming !== true
567
+ && session.isCompacting !== true
568
+ && !activeSessionInputs.has(targetRuntime)
569
+ );
570
+ };
571
+
572
+ const reloadRuntimeResources = (targetRuntime) => {
573
+ const existing = resourceReloadsByRuntime.get(targetRuntime);
574
+ if (existing) return existing;
575
+ clearIdleDisposal(targetRuntime.session?.sessionId);
576
+ const task = resourceReloadQueue.then(async () => {
577
+ if (!pendingResourceReloads.has(targetRuntime) || !isRuntimeReloadSafe(targetRuntime)) return false;
578
+ await reloadSession(targetRuntime.session);
579
+ skillReadClassifierByRuntime.delete(targetRuntime);
580
+ return true;
581
+ });
582
+ resourceReloadQueue = task.catch(() => {});
583
+ const tracked = task.finally(() => {
584
+ resourceReloadsByRuntime.delete(targetRuntime);
585
+ });
586
+ resourceReloadsByRuntime.set(targetRuntime, tracked);
587
+ return tracked;
588
+ };
589
+
590
+ const flushPendingResourceReload = async (targetRuntime) => {
591
+ if (!pendingResourceReloads.has(targetRuntime) || !isRuntimeReloadSafe(targetRuntime)) return false;
592
+ try {
593
+ const reloaded = await reloadRuntimeResources(targetRuntime);
594
+ if (!reloaded) return false;
595
+ pendingResourceReloads.delete(targetRuntime);
596
+ return true;
597
+ } catch {
598
+ publish('extension.error', {
599
+ source: '<runtime>',
600
+ event: 'reload',
601
+ message: 'Pi resources could not be reloaded.',
602
+ }, targetRuntime.session?.sessionId, targetRuntime.cwd);
603
+ return false;
604
+ }
605
+ };
606
+
607
+ const refreshAffectedPromptRuntimes = async (locations, targetDir) => {
608
+ const affectsGlobal = locations.includes('global');
609
+ const candidates = new Set(
610
+ affectsGlobal
611
+ ? (runtimeRegistry?.listAll?.() ?? [])
612
+ : (runtimeRegistry?.listByDirectory?.(targetDir) ?? [])
613
+ );
614
+ if (runtime && (affectsGlobal || resolve(runtime.cwd || activeDirectory || cwd) === resolve(targetDir))) {
615
+ candidates.add(runtime);
616
+ }
617
+ await Promise.all([...candidates].map(async (targetRuntime) => {
618
+ pendingResourceReloads.add(targetRuntime);
619
+ await flushPendingResourceReload(targetRuntime);
620
+ }));
621
+ };
622
+
540
623
  const disposeIdleSessionRuntime = async (sessionId) => {
541
624
  if (disposingSessionIds.has(sessionId)) return;
542
625
  const targetRuntime = runtimeRegistry?.findBySessionId(sessionId);
@@ -544,9 +627,18 @@ export function createSessionDaemon({
544
627
  shutdownRequestedBySession.delete(sessionId);
545
628
  return;
546
629
  }
547
- if (targetRuntime.session?.isStreaming || targetRuntime.session?.isCompacting) return;
630
+ if (
631
+ targetRuntime.session?.isStreaming
632
+ || targetRuntime.session?.isCompacting
633
+ || activeSessionInputs.has(targetRuntime)
634
+ || pendingResourceReloads.has(targetRuntime)
635
+ || resourceReloadsByRuntime.has(targetRuntime)
636
+ ) return;
548
637
  disposingSessionIds.add(sessionId);
549
638
  clearIdleDisposal(sessionId);
639
+ activeSessionInputs.delete(targetRuntime);
640
+ pendingResourceReloads.delete(targetRuntime);
641
+ resourceReloadsByRuntime.delete(targetRuntime);
550
642
  try {
551
643
  if (targetRuntime === runtime) rememberRuntimeSession();
552
644
  clearExtensionState(sessionId);
@@ -1561,6 +1653,14 @@ export function createSessionDaemon({
1561
1653
  return 'path';
1562
1654
  };
1563
1655
 
1656
+ const promptResourcesFromLoader = (loader) => loader.getPrompts().prompts.map((prompt) => ({
1657
+ id: resourceId('prompt', prompt.filePath),
1658
+ kind: 'prompt', name: prompt.name, ...(prompt.description ? { description: prompt.description } : {}),
1659
+ location: resourceLocation(prompt.sourceInfo), content: prompt.content,
1660
+ editable: prompt.sourceInfo?.origin === 'top-level' && ['user', 'project'].includes(prompt.sourceInfo?.scope),
1661
+ filePath: prompt.filePath,
1662
+ }));
1663
+
1564
1664
  const resourceCatalog = async (requestedDirectory) => {
1565
1665
  const targetDir = requestedDirectory ? await resolveDirectory(requestedDirectory) : (activeDirectory || cwd);
1566
1666
  const activeRuntime = await ensureRuntime(targetDir);
@@ -1584,13 +1684,7 @@ export function createSessionDaemon({
1584
1684
  filePath: skill.filePath,
1585
1685
  };
1586
1686
  }));
1587
- const prompts = loader.getPrompts().prompts.map((prompt) => ({
1588
- id: resourceId('prompt', prompt.filePath),
1589
- kind: 'prompt', name: prompt.name, ...(prompt.description ? { description: prompt.description } : {}),
1590
- location: resourceLocation(prompt.sourceInfo), content: prompt.content,
1591
- editable: prompt.sourceInfo?.origin === 'top-level' && ['user', 'project'].includes(prompt.sourceInfo?.scope),
1592
- filePath: prompt.filePath,
1593
- }));
1687
+ const prompts = promptResourcesFromLoader(loader);
1594
1688
  const agents = loader.getAgentsFiles().agentsFiles.map((agent) => ({
1595
1689
  id: resourceId('agents', agent.path), kind: 'agents', name: basename(agent.path),
1596
1690
  location: agent.path.startsWith(agentDir) ? 'global' : 'project', content: agent.content, editable: true, filePath: agent.path,
@@ -1611,8 +1705,35 @@ export function createSessionDaemon({
1611
1705
  agents: catalog.agents.map(({ filePath, ...resource }) => resource),
1612
1706
  });
1613
1707
 
1708
+ // A busy session keeps its current Pi resource loader until its turn settles.
1709
+ // Mutation responses still need to reflect the committed file immediately,
1710
+ // so replace only editable top-level prompts from a fresh standalone loader.
1711
+ // Package/path/extension-contributed resources remain owned by the live session.
1712
+ const resourcesAfterPromptMutation = async (targetDir) => {
1713
+ const current = await resourceCatalog(targetDir);
1714
+ servicesCache.delete(targetDir);
1715
+ const freshServices = await getServices(targetDir);
1716
+ const freshEditable = promptResourcesFromLoader(freshServices.resourceLoader)
1717
+ .filter((prompt) => prompt.editable === true);
1718
+ return publicResources({
1719
+ ...current,
1720
+ prompts: [
1721
+ ...current.prompts.filter((prompt) => prompt.editable !== true),
1722
+ ...freshEditable,
1723
+ ],
1724
+ });
1725
+ };
1726
+
1727
+ const finishPromptMutation = async (locations, targetDir) => {
1728
+ servicesCache.delete(targetDir);
1729
+ await refreshAffectedPromptRuntimes([...new Set(locations)], targetDir);
1730
+ return resourcesAfterPromptMutation(targetDir);
1731
+ };
1732
+
1614
1733
  const requireIdleResourceMutation = () => {
1615
- if (runtime?.session?.isStreaming) throw new SessionDaemonProtocolError('SESSION_BUSY', 'Resources cannot change during an active session.');
1734
+ if (runtime?.session?.isStreaming || runtime?.session?.isCompacting) {
1735
+ throw new SessionDaemonProtocolError('SESSION_BUSY', 'Resources cannot change during an active session.');
1736
+ }
1616
1737
  };
1617
1738
 
1618
1739
  let resourceMutation = Promise.resolve();
@@ -1663,11 +1784,11 @@ export function createSessionDaemon({
1663
1784
  if (!payload || typeof payload.resourceId !== 'string' || typeof payload.content !== 'string' || payload.content.length > 200_000) {
1664
1785
  throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The Pi resource update is invalid.');
1665
1786
  }
1666
- requireIdleResourceMutation();
1667
1787
  const targetDir = payload.directory ? await resolveDirectory(payload.directory) : (activeDirectory || cwd);
1668
1788
  const catalog = await resourceCatalog(targetDir);
1669
1789
  const resource = [...catalog.prompts, ...catalog.agents].find((item) => item.id === payload.resourceId && item.editable === true);
1670
1790
  if (!resource?.filePath) throw new SessionDaemonProtocolError('RESOURCE_NOT_FOUND', 'The requested Pi resource is not editable.');
1791
+ if (resource.kind !== 'prompt') requireIdleResourceMutation();
1671
1792
  let content = payload.content;
1672
1793
  if (resource.kind === 'prompt') {
1673
1794
  const previous = await readFile(resource.filePath, 'utf8').catch((error) => error?.code === 'ENOENT' ? '' : Promise.reject(error));
@@ -1675,6 +1796,7 @@ export function createSessionDaemon({
1675
1796
  content = `${frontmatter}${content}`;
1676
1797
  }
1677
1798
  await writeResourceFile(resource.filePath, content);
1799
+ if (resource.kind === 'prompt') return finishPromptMutation([resource.location], targetDir);
1678
1800
  return refreshResources(targetDir);
1679
1801
  };
1680
1802
 
@@ -1684,7 +1806,6 @@ export function createSessionDaemon({
1684
1806
  || !/^[a-z0-9][a-z0-9_-]{0,63}$/i.test(payload.name)) {
1685
1807
  throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The Pi prompt template is invalid.');
1686
1808
  }
1687
- requireIdleResourceMutation();
1688
1809
  if (payload.location === 'project' && !payload.directory) {
1689
1810
  throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'Project prompt templates require an explicit directory.');
1690
1811
  }
@@ -1699,12 +1820,11 @@ export function createSessionDaemon({
1699
1820
  if (error?.code !== 'ENOENT') throw error;
1700
1821
  }
1701
1822
  await writeNewResourceFile(filePath, `---\ndescription: ${JSON.stringify(payload.description)}\n---\n${payload.content}`);
1702
- return refreshResources(targetDir);
1823
+ return finishPromptMutation([payload.location], targetDir);
1703
1824
  });
1704
1825
 
1705
1826
  const deletePrompt = (payload) => transactResourceMutation(async () => {
1706
1827
  if (!payload || typeof payload.resourceId !== 'string') throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The Pi prompt template is invalid.');
1707
- requireIdleResourceMutation();
1708
1828
  const targetDir = payload.directory ? await resolveDirectory(payload.directory) : (activeDirectory || cwd);
1709
1829
  const catalog = await resourceCatalog(targetDir);
1710
1830
  const resource = catalog.prompts.find((item) => item.id === payload.resourceId && item.editable === true);
@@ -1722,7 +1842,7 @@ export function createSessionDaemon({
1722
1842
  if (trust !== true) throw new SessionDaemonProtocolError('PROJECT_UNTRUSTED', 'The project is not trusted.');
1723
1843
  }
1724
1844
  await rm(resource.filePath);
1725
- return refreshResources(targetDir);
1845
+ return finishPromptMutation([resource.location], targetDir);
1726
1846
  });
1727
1847
 
1728
1848
  const PROMPT_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/i;
@@ -1781,7 +1901,6 @@ export function createSessionDaemon({
1781
1901
  if (hasLocation && payload.location !== 'global' && payload.location !== 'project') {
1782
1902
  throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The Pi prompt template location is invalid.');
1783
1903
  }
1784
- requireIdleResourceMutation();
1785
1904
  const targetDir = payload.directory ? await resolveDirectory(payload.directory) : (activeDirectory || cwd);
1786
1905
  const catalog = await resourceCatalog(targetDir);
1787
1906
  const resource = catalog.prompts.find((item) => item.id === payload.resourceId && item.editable === true);
@@ -1818,7 +1937,7 @@ export function createSessionDaemon({
1818
1937
  const nextFileContent = `${nextFrontmatter}${nextBody}`;
1819
1938
  if (!needsNewFile) {
1820
1939
  await writeResourceFile(resource.filePath, nextFileContent);
1821
- return refreshResources(targetDir);
1940
+ return finishPromptMutation([sourceLocation], targetDir);
1822
1941
  }
1823
1942
  if (!PROMPT_NAME_PATTERN.test(destName)) {
1824
1943
  throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The Pi prompt template name is invalid.');
@@ -1826,7 +1945,7 @@ export function createSessionDaemon({
1826
1945
  const destPath = join(destLocation === 'global' ? agentDir : join(targetDir, '.pi'), 'prompts', `${destName}.md`);
1827
1946
  if (destPath === resource.filePath) {
1828
1947
  await writeResourceFile(resource.filePath, nextFileContent);
1829
- return refreshResources(targetDir);
1948
+ return finishPromptMutation([sourceLocation], targetDir);
1830
1949
  }
1831
1950
  try {
1832
1951
  await readFile(destPath, 'utf8');
@@ -1841,7 +1960,7 @@ export function createSessionDaemon({
1841
1960
  await rm(destPath, { force: true }).catch(() => {});
1842
1961
  throw error;
1843
1962
  }
1844
- return refreshResources(targetDir);
1963
+ return finishPromptMutation([sourceLocation, destLocation], targetDir);
1845
1964
  });
1846
1965
 
1847
1966
  const setSessionModel = async (activeRuntime, model) => {
@@ -2123,12 +2242,15 @@ export function createSessionDaemon({
2123
2242
  }
2124
2243
  if (payload.thinking !== undefined) validateThinking(payload.thinking);
2125
2244
  const activeRuntime = await activateSession(payload.sessionId, payload.directory);
2245
+ await flushPendingResourceReload(activeRuntime);
2126
2246
  // After a provider stream dies, Pi can report idle while the UI still
2127
2247
  // retries as steer/follow-up. Start a new turn instead of rejecting.
2128
2248
  const deliverAs = delivery && activeRuntime.session.isStreaming ? delivery : undefined;
2129
2249
  if (!deliverAs && activeRuntime.session.isStreaming) {
2130
2250
  throw new SessionDaemonProtocolError('SESSION_BUSY', 'The Pi session already has an active run.');
2131
2251
  }
2252
+ beginSessionInput(activeRuntime);
2253
+ try {
2132
2254
  if (payload.model !== undefined) {
2133
2255
  await setSessionModel(activeRuntime, payload.model);
2134
2256
  publishSessionModel(activeRuntime.session, payload.sessionId, activeRuntime.cwd);
@@ -2236,8 +2358,20 @@ export function createSessionDaemon({
2236
2358
  return;
2237
2359
  }
2238
2360
  Promise.resolve(activeRuntime.session.abort()).catch(() => {});
2361
+ }).finally(() => {
2362
+ endSessionInput(activeRuntime);
2363
+ void flushPendingResourceReload(activeRuntime).then((reloaded) => {
2364
+ if (reloaded && !shutdownRequestedBySession.has(payload.sessionId)) {
2365
+ scheduleIdleDisposal(payload.sessionId);
2366
+ }
2367
+ });
2239
2368
  });
2240
2369
  return { accepted: true, messageId };
2370
+ } catch (error) {
2371
+ endSessionInput(activeRuntime);
2372
+ void flushPendingResourceReload(activeRuntime);
2373
+ throw error;
2374
+ }
2241
2375
  };
2242
2376
 
2243
2377
  const treeForSession = async (sessionId, requestedDirectory) => {
@@ -2287,6 +2421,8 @@ export function createSessionDaemon({
2287
2421
  };
2288
2422
 
2289
2423
  const publishSessionEvent = (sessionId, event, directory = activeDirectory || cwd) => {
2424
+ const owningRuntime = runtimeRegistry?.get({ cwd: directory, sessionId })
2425
+ || (runtime?.session?.sessionId === sessionId ? runtime : undefined);
2290
2426
  switch (event.type) {
2291
2427
  case 'message_start': {
2292
2428
  if (event.message?.role === 'user') {
@@ -2514,7 +2650,11 @@ export function createSessionDaemon({
2514
2650
  latestAssistantMessageIds.delete(sessionId);
2515
2651
  toolInputBySession.delete(sessionId);
2516
2652
  publish('session.lifecycle', { state: 'idle', serverNow: Date.now() }, sessionId, directory);
2517
- if (!completeRequestedShutdown(sessionId)) scheduleIdleDisposal(sessionId);
2653
+ if (!completeRequestedShutdown(sessionId)) {
2654
+ void flushPendingResourceReload(owningRuntime).then(() => {
2655
+ if (!shutdownRequestedBySession.has(sessionId)) scheduleIdleDisposal(sessionId);
2656
+ });
2657
+ }
2518
2658
  break;
2519
2659
  case 'session_info_changed': {
2520
2660
  const title = typeof event.name === 'string' ? event.name.trim() : '';
@@ -2581,7 +2721,9 @@ export function createSessionDaemon({
2581
2721
  };
2582
2722
  compactionStateBySession.set(sessionId, compaction);
2583
2723
  publish('session.compaction', compaction, sessionId, directory);
2584
- if (!event.willRetry) scheduleIdleDisposal(sessionId);
2724
+ if (!event.willRetry) {
2725
+ void flushPendingResourceReload(owningRuntime).then(() => scheduleIdleDisposal(sessionId));
2726
+ }
2585
2727
  break;
2586
2728
  }
2587
2729
  default:
@@ -172,7 +172,6 @@ const runScriptedClient = async ({ relayUrl, serverId, hostEncPubJwk }) => {
172
172
  url.searchParams.set('role', 'client');
173
173
  url.searchParams.set('serverId', serverId);
174
174
  url.searchParams.set('connectionId', connectionId);
175
- const ws = new WebSocket(url.toString());
176
175
 
177
176
  const hostPub = await globalThis.crypto.subtle.importKey(
178
177
  'jwk',
@@ -183,6 +182,9 @@ const runScriptedClient = async ({ relayUrl, serverId, hostEncPubJwk }) => {
183
182
  );
184
183
  const ephemeral = await generateEcdhKeyPair();
185
184
  const nonce = generateHandshakeNonce();
185
+ // Finish async setup before dialing so the loopback socket cannot emit its
186
+ // one-shot open event before the scripted client attaches its listener.
187
+ const ws = new WebSocket(url.toString());
186
188
 
187
189
  let channel = null;
188
190
  const responseChunks = [];
@@ -7,7 +7,7 @@ Trusted-device access has one durable credential model: a remote client bearer t
7
7
 
8
8
  Pairing v2 is implemented by `packages/web/server/lib/client-auth/pairing.js`. It stores short-lived one-time pairing sessions with hashed secrets, exposes create/cancel/redeem routes under `/api/client-auth/pairing/*`, and redeems a valid pairing secret into the same remote client token used by password/passkey trusted-device flows.
9
9
 
10
- Browser WebSocket clients mint a 60-second `oc_url_token` through the authenticated `/auth/url-token` route because the WebSocket constructor cannot attach an Authorization header. The token is accepted only for the explicit WebSocket allowlist, currently `/api/terminal/ws` and `/api/stt/ws`; ordinary API routes and unknown upgrade paths reject it. The token resolves to the UI session or remote-client identity that minted it.
10
+ Browser WebSocket clients mint a 60-second `oc_url_token` through the authenticated `/auth/url-token` route because the WebSocket constructor cannot attach an Authorization header. The token is encrypted with a key derived from the server's persisted JWT secret, so an ordinary server restart does not invalidate a token that the browser may still use. Global sign-out rotates that secret and invalidates outstanding tokens. The token is accepted only for the explicit WebSocket allowlist, currently `/api/terminal/ws` and `/api/stt/ws`; ordinary API routes and unknown upgrade paths reject it. The token resolves to the UI session or remote-client identity that minted it.
11
11
 
12
12
  ## Entrypoints and structure
13
13
  - `packages/web/server/lib/ui-auth/ui-auth.js`: UI auth controller runtime, cookie/session issuance, rate limiting, and auth route handlers.