@pi-chamber/web 0.9.3 → 0.9.4

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 (47) hide show
  1. package/README.md +1 -1
  2. package/dist/assets/{DiagramView-CV-iReyY.js → DiagramView-CHy1Glsl.js} +1 -1
  3. package/dist/assets/{DiffView-DVd1MLPB.js → DiffView-CBOrV4hS.js} +1 -1
  4. package/dist/assets/{FilesView-CPnW4I90.js → FilesView-CK2YVs_W.js} +1 -1
  5. package/dist/assets/{GitView-Dj_7hgX_.js → GitView-BEFLOv_7.js} +3 -3
  6. package/dist/assets/{JsonTreeView-Cyy0lEZR.js → JsonTreeView-CKWGm5MS.js} +1 -1
  7. package/dist/assets/{MarkdownRendererImpl-BXN78Wu_.js → MarkdownRendererImpl-hE_nmSqe.js} +1 -1
  8. package/dist/assets/{PatchDiff-C7dA3U29.js → PatchDiff-BagRxMON.js} +1 -1
  9. package/dist/assets/{SessionSwitcherContent-dr3g9DR7.js → SessionSwitcherContent-z9VYCXrT.js} +1 -1
  10. package/dist/assets/{SessionSwitcherDropdown-C3zdd82V.js → SessionSwitcherDropdown-icxJk_lT.js} +2 -2
  11. package/dist/assets/{SessionUnreadDot-qeik5qtT.js → SessionUnreadDot-Bv-5KguB.js} +1 -1
  12. package/dist/assets/SettingsView-Ck0qxtKP.js +2 -0
  13. package/dist/assets/{SettingsWindow-Bbay2W76.js → SettingsWindow-GQRL2CdD.js} +1 -1
  14. package/dist/assets/{ToolOutputDialog-CRTiN1CH.js → ToolOutputDialog-CxJUXVZW.js} +1 -1
  15. package/dist/assets/{ToolPartDiffPreview-CqnNcLPk.js → ToolPartDiffPreview-BXuLRWHT.js} +1 -1
  16. package/dist/assets/{VirtualizedFileDiff-iqwryMNU.js → VirtualizedFileDiff-DfaXovGB.js} +1 -1
  17. package/dist/assets/{computeVirtualFileMetrics-Bbugxxtp.js → computeVirtualFileMetrics-DG_E6iaN.js} +1 -1
  18. package/dist/assets/{contextFileOpenGuard-BC3ie230.js → contextFileOpenGuard-DPBE3ELv.js} +1 -1
  19. package/dist/assets/{gitStatusPredicates-DbThKVSf.js → gitStatusPredicates-OljV4Bb2.js} +1 -1
  20. package/dist/assets/{index-v6K3L94m.js → index-DmexVlTQ.js} +1 -1
  21. package/dist/assets/{isDiffPlainText-Dl0RBjPZ.js → isDiffPlainText-aikgiqLb.js} +1 -1
  22. package/dist/assets/{isFilePlainText-CbrmvrM6.js → isFilePlainText-D-Dl6LqX.js} +1 -1
  23. package/dist/assets/{main-4PkIvzf4.js → main-BXdraZTZ.js} +3 -3
  24. package/dist/assets/{main-DMyWi0qs.js → main-DG1oZ0Wj.js} +2 -2
  25. package/dist/assets/{markdownCore-BD5WkOKU.js → markdownCore-DUjQU2i0.js} +1 -1
  26. package/dist/assets/{miniChat-CLMNhna4.js → miniChat-BEAtOkr9.js} +2 -2
  27. package/dist/assets/{mobile-rWMDwhtQ.js → mobile-DOFBBQg2.js} +2 -2
  28. package/dist/assets/{renderElectronMiniChatApp-BRhGNRJ8.js → renderElectronMiniChatApp-B0K72YnS.js} +2 -2
  29. package/dist/assets/{renderMobileApp-DLy2YoQg.js → renderMobileApp-Ca_BO_s4.js} +3 -3
  30. package/dist/assets/{runtimeEndpointReset-Z9YtcHxZ.js → runtimeEndpointReset-Cx2tsgTo.js} +3 -3
  31. package/dist/assets/{useAppFontEffects-DfuJVB15.js → useAppFontEffects-C4JL1x7k.js} +84 -84
  32. package/dist/assets/{useFilesViewSearch-BZBHrZ90.js → useFilesViewSearch-Du0DnmKs.js} +1 -1
  33. package/dist/assets/{usePushVisibilityBeacon-BxTkEajM.js → usePushVisibilityBeacon-BnHxIv4r.js} +1 -1
  34. package/dist/assets/{useSwitcherItems-jITqE8PV.js → useSwitcherItems-C91mwPJD.js} +1 -1
  35. package/dist/assets/{vendor-codemirror-language-data-CDdfwzlS.js → vendor-codemirror-language-data-C493X_9w.js} +2 -2
  36. package/dist/assets/{web-components-C9wXMuCp.js → web-components-B2Rw__yK.js} +1 -1
  37. package/dist/index.html +1 -1
  38. package/dist/mini-chat.html +1 -1
  39. package/dist/mobile.html +1 -1
  40. package/package.json +1 -1
  41. package/server/lib/pi/routes.js +13 -3
  42. package/server/lib/pi/routes.test.js +55 -1
  43. package/server/lib/pi/session-daemon/DOCUMENTATION.md +1 -2
  44. package/server/lib/pi/session-daemon/prompt-operations.test.js +51 -0
  45. package/server/lib/pi/session-daemon/session-daemon.js +189 -54
  46. package/server/lib/pi/session-daemon/session-daemon.test.js +186 -0
  47. package/dist/assets/SettingsView-C57uV1YS.js +0 -2
@@ -258,6 +258,35 @@ export function createSessionDaemon({
258
258
  const latestAssistantMessageIds = new Map();
259
259
  const messageStartedAt = new Map();
260
260
  const toolStartedAt = new Map();
261
+ // Keep recent starts long enough for a second client or a browser reload to
262
+ // hydrate a just-finished tool, but do not let a long-lived daemon grow with
263
+ // every tool call.
264
+ const completedToolTimings = new Map();
265
+ const MAX_COMPLETED_TOOL_TIMINGS = 2048;
266
+ const toolTimingKey = (sessionId, toolCallId) => `${sessionId}\u0000${toolCallId}`;
267
+ const clearToolTimingsForSession = (sessionId, { keepCompleted = false } = {}) => {
268
+ const prefix = `${sessionId}\u0000`;
269
+ for (const key of toolStartedAt.keys()) {
270
+ if (key.startsWith(prefix)) toolStartedAt.delete(key);
271
+ }
272
+ if (!keepCompleted) {
273
+ for (const key of completedToolTimings.keys()) {
274
+ if (key.startsWith(prefix)) completedToolTimings.delete(key);
275
+ }
276
+ }
277
+ };
278
+ const rememberCompletedToolTiming = (sessionId, toolCallId, startedAt, endedAt) => {
279
+ if (!Number.isFinite(startedAt)) return;
280
+ completedToolTimings.set(toolTimingKey(sessionId, toolCallId), {
281
+ startedAt,
282
+ ...(Number.isFinite(endedAt) ? { endedAt } : {}),
283
+ });
284
+ while (completedToolTimings.size > MAX_COMPLETED_TOOL_TIMINGS) {
285
+ const oldest = completedToolTimings.keys().next();
286
+ if (oldest.done) break;
287
+ completedToolTimings.delete(oldest.value);
288
+ }
289
+ };
261
290
  const toolInputBySession = new Map();
262
291
  const latestUserMessageIds = new Map();
263
292
  const retryStateBySession = new Map();
@@ -267,11 +296,19 @@ export function createSessionDaemon({
267
296
  const settledSendGenerationBySession = new Map();
268
297
  // Pi's reload() is identity-preserving but is not safe during a turn,
269
298
  // compaction, or an extension command. Prompt writes mark affected busy
270
- // runtimes dirty and reload them at the next safe lifecycle edge.
299
+ // runtimes dirty and reload them at the next safe lifecycle edge. Other
300
+ // Pi configuration writes queue resident-runtime recreation at that edge.
271
301
  const activeSessionInputs = new Map();
272
302
  const pendingResourceReloads = new Set();
273
303
  const resourceReloadsByRuntime = new Map();
274
304
  let resourceReloadQueue = Promise.resolve();
305
+ // File-backed Pi configuration can be committed while a session is busy,
306
+ // but replacing all resident runtimes must wait until every active runtime
307
+ // is idle. The revision lets a second write that arrives during a rebuild
308
+ // trigger one more rebuild instead of being lost behind the first one.
309
+ let pendingRuntimeRecreation = false;
310
+ let runtimeRecreationRevision = 0;
311
+ let runtimeRecreationTask = null;
275
312
  // Pi emits each user message start before its persisted entry is readable.
276
313
  // Keep prompt metadata in send order so queued follow-ups cannot attach the
277
314
  // next prompt's files to an earlier user message.
@@ -659,6 +696,60 @@ export function createSessionDaemon({
659
696
  );
660
697
  };
661
698
 
699
+ const activeRuntimes = () => {
700
+ const runtimes = new Set(runtimeRegistry?.listAll?.() ?? []);
701
+ if (runtime) runtimes.add(runtime);
702
+ return [...runtimes];
703
+ };
704
+
705
+ const hasUnsafeRuntime = () => activeRuntimes().some((targetRuntime) => !isRuntimeReloadSafe(targetRuntime));
706
+
707
+ const flushPendingRuntimeRecreation = () => {
708
+ if (!pendingRuntimeRecreation || hasUnsafeRuntime()) return Promise.resolve(false);
709
+ if (runtimeRecreationTask) return runtimeRecreationTask;
710
+
711
+ const task = (async () => {
712
+ let recreated = false;
713
+ while (pendingRuntimeRecreation && !hasUnsafeRuntime()) {
714
+ const revision = runtimeRecreationRevision;
715
+ servicesCache.clear();
716
+ await disposeRuntime();
717
+ if (!pendingRuntimeRecreation) break;
718
+ await ensureRuntime();
719
+ recreated = true;
720
+ if (revision === runtimeRecreationRevision) pendingRuntimeRecreation = false;
721
+ }
722
+ return recreated;
723
+ })();
724
+ const tracked = task.finally(() => {
725
+ if (runtimeRecreationTask === tracked) runtimeRecreationTask = null;
726
+ });
727
+ runtimeRecreationTask = tracked;
728
+ return tracked;
729
+ };
730
+
731
+ const scheduleRuntimeRecreation = async () => {
732
+ const deferred = hasUnsafeRuntime();
733
+ pendingRuntimeRecreation = true;
734
+ runtimeRecreationRevision += 1;
735
+ if (deferred) {
736
+ void flushPendingRuntimeRecreation().catch(() => {});
737
+ return true;
738
+ }
739
+ try {
740
+ await flushPendingRuntimeRecreation();
741
+ while (pendingRuntimeRecreation && !hasUnsafeRuntime()) {
742
+ await flushPendingRuntimeRecreation();
743
+ }
744
+ } catch {
745
+ // The file write has already committed. Keep the recreation pending so a
746
+ // later lifecycle edge can retry, and report delayed activation instead
747
+ // of misreporting the mutation itself as failed.
748
+ return true;
749
+ }
750
+ return pendingRuntimeRecreation;
751
+ };
752
+
662
753
  const reloadRuntimeResources = (targetRuntime) => {
663
754
  const existing = resourceReloadsByRuntime.get(targetRuntime);
664
755
  if (existing) return existing;
@@ -708,6 +799,7 @@ export function createSessionDaemon({
708
799
  pendingResourceReloads.add(targetRuntime);
709
800
  await flushPendingResourceReload(targetRuntime);
710
801
  }));
802
+ return [...candidates].some((targetRuntime) => pendingResourceReloads.has(targetRuntime));
711
803
  };
712
804
 
713
805
  const disposeIdleSessionRuntime = async (sessionId) => {
@@ -1205,6 +1297,10 @@ export function createSessionDaemon({
1205
1297
  if (part?.type === 'thinking') return [{ type: 'thinking', id: `${entry.id}:thinking:${index}`, index, text: redactAttachmentPaths(part.thinking) }];
1206
1298
  if (part?.type === 'toolCall') {
1207
1299
  const result = toolResults.get(part.id);
1300
+ const timingKey = toolTimingKey(session.sessionId, part.id);
1301
+ const activeStartedAt = toolStartedAt.get(timingKey);
1302
+ const completedTiming = completedToolTimings.get(timingKey);
1303
+ const startedAt = activeStartedAt ?? completedTiming?.startedAt;
1208
1304
  const running = streaming && !result;
1209
1305
  const interrupted = !running && !result;
1210
1306
  const metadata = mergeToolPresentationMetadata(result?.metadata, activeRuntime, targetDir, part.name, part.arguments);
@@ -1224,11 +1320,14 @@ export function createSessionDaemon({
1224
1320
  : {}),
1225
1321
  ...(result?.isError || interrupted ? { isError: true } : {}),
1226
1322
  ...(metadata ? { metadata } : {}),
1323
+ ...(Number.isFinite(startedAt) ? { startedAt } : {}),
1227
1324
  ...(Number.isFinite(result?.endedAt)
1228
1325
  ? { endedAt: result.endedAt }
1229
- : interrupted
1230
- ? { endedAt: createdAt }
1231
- : {}),
1326
+ : Number.isFinite(completedTiming?.endedAt)
1327
+ ? { endedAt: completedTiming.endedAt }
1328
+ : interrupted
1329
+ ? { endedAt: createdAt }
1330
+ : {}),
1232
1331
  }];
1233
1332
  }
1234
1333
  return [];
@@ -1371,6 +1470,13 @@ export function createSessionDaemon({
1371
1470
  || (payload.model !== undefined && (!payload.model || typeof payload.model.providerId !== 'string' || typeof payload.model.modelId !== 'string'))) {
1372
1471
  throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The requested session creation options are invalid.');
1373
1472
  }
1473
+ try {
1474
+ await flushPendingRuntimeRecreation();
1475
+ } catch {
1476
+ // A committed write already queued recreation for a later edge. A
1477
+ // failed rebuild must not fail session creation; creation below
1478
+ // retries runtime startup directly.
1479
+ }
1374
1480
  const targetCwd = await resolveDirectory(payload.cwd);
1375
1481
  await validatePiSessionJsonlDirectory({ cwd: targetCwd, agentDir });
1376
1482
  const parent = payload.parentId === undefined ? undefined : (await findPersistedSession(payload.parentId, targetCwd)).target;
@@ -1446,6 +1552,11 @@ export function createSessionDaemon({
1446
1552
  };
1447
1553
 
1448
1554
  const listProviders = async (requestedDirectory) => {
1555
+ try {
1556
+ await flushPendingRuntimeRecreation();
1557
+ } catch {
1558
+ // A failed rebuild stays queued for a later edge; the ensure below retries startup.
1559
+ }
1449
1560
  const targetDir = requestedDirectory ? await resolveDirectory(requestedDirectory) : (activeDirectory || cwd);
1450
1561
  const activeRuntime = await ensureRuntime(targetDir);
1451
1562
  const modelRuntime = activeRuntime.session?.modelRuntime;
@@ -1476,6 +1587,11 @@ export function createSessionDaemon({
1476
1587
 
1477
1588
  let refreshProvidersInflight = null;
1478
1589
  const refreshProviders = async (requestedDirectory) => {
1590
+ try {
1591
+ await flushPendingRuntimeRecreation();
1592
+ } catch {
1593
+ // A failed rebuild stays queued for a later edge; the catalog refresh below retries startup.
1594
+ }
1479
1595
  if (refreshProvidersInflight) return refreshProvidersInflight;
1480
1596
  const task = (async () => {
1481
1597
  const signal = typeof AbortSignal.timeout === 'function' ? AbortSignal.timeout(15_000) : undefined;
@@ -1572,9 +1688,6 @@ export function createSessionDaemon({
1572
1688
  throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The provider configuration is invalid.');
1573
1689
  }
1574
1690
  const activeRuntime = await ensureRuntime();
1575
- if (activeRuntime?.session?.isStreaming) {
1576
- throw new SessionDaemonProtocolError('SESSION_BUSY', 'Provider configuration cannot change while a session is streaming.');
1577
- }
1578
1691
  if (typeof activeRuntime?.session?.modelRuntime?.getError?.() === 'string') {
1579
1692
  throw new SessionDaemonProtocolError('PI_MODEL_CONFIG_INVALID', 'Pi models configuration is invalid.');
1580
1693
  }
@@ -1587,15 +1700,10 @@ export function createSessionDaemon({
1587
1700
  }
1588
1701
  throw error;
1589
1702
  }
1590
- // ModelRuntime snapshots models.json at construction. Rehydrate only while
1591
- // idle so catalog changes are authoritative immediately and never race a turn.
1592
- servicesCache.clear();
1593
- if (activeRuntime) {
1594
- rememberRuntimeSession();
1595
- await disposeRuntime();
1596
- await ensureRuntime();
1597
- }
1598
- return { config };
1703
+ // ModelRuntime snapshots models.json at construction. Persist the new
1704
+ // catalog now, then recreate resident runtimes only at a safe edge.
1705
+ const deferred = await scheduleRuntimeRecreation();
1706
+ return { config, ...(deferred ? { deferred: true } : {}) };
1599
1707
  };
1600
1708
 
1601
1709
  const providerStatus = async (providerId) => {
@@ -1785,15 +1893,6 @@ export function createSessionDaemon({
1785
1893
  if (hasTrust && payload.trust !== null && typeof payload.trust !== 'boolean') {
1786
1894
  throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The project trust decision is invalid.');
1787
1895
  }
1788
- if (hasTrust) {
1789
- const targetRuntimes = runtimeRegistry?.listByDirectory?.(targetDir) ?? [];
1790
- const inheritsActive = runtime && runtime.cwd === targetDir ? [runtime] : [];
1791
- const allTarget = targetRuntimes.length > 0 ? targetRuntimes : inheritsActive;
1792
- const isTargetStreaming = allTarget.some((r) => r.session?.isStreaming);
1793
- if (isTargetStreaming) {
1794
- throw new SessionDaemonProtocolError('SESSION_BUSY', 'Project trust cannot change during an active session.');
1795
- }
1796
- }
1797
1896
  // Pi settings and trust live under the shared agent directory: read the
1798
1897
  // current files and commit inside the shared lock so concurrent daemons
1799
1898
  // cannot interleave read-modify-write cycles.
@@ -1830,11 +1929,13 @@ export function createSessionDaemon({
1830
1929
  }
1831
1930
  return isTrusted;
1832
1931
  });
1833
- if (hasTrust && runtime) {
1834
- await disposeRuntime();
1835
- await ensureRuntime();
1836
- }
1837
- return readPiSettings(targetDir);
1932
+ const deferred = hasTrust && activeRuntimes().length > 0
1933
+ ? await scheduleRuntimeRecreation()
1934
+ : false;
1935
+ return {
1936
+ ...readPiSettings(targetDir),
1937
+ ...(deferred ? { deferred: true } : {}),
1938
+ };
1838
1939
  };
1839
1940
 
1840
1941
  const resourceId = (kind, filePath) => `${kind}:${createHash('sha256').update(filePath).digest('base64url')}`;
@@ -1861,6 +1962,14 @@ export function createSessionDaemon({
1861
1962
 
1862
1963
  const resourceCatalog = async (requestedDirectory) => {
1863
1964
  const targetDir = requestedDirectory ? await resolveDirectory(requestedDirectory) : (activeDirectory || cwd);
1965
+ // A settings page may be the first caller after a turn settles without a
1966
+ // lifecycle event reaching this daemon, so give queued configuration a
1967
+ // chance to activate before reading the catalog.
1968
+ try {
1969
+ await flushPendingRuntimeRecreation();
1970
+ } catch {
1971
+ // A failed rebuild stays queued for a later edge; ensureRuntime below retries startup.
1972
+ }
1864
1973
  const activeRuntime = await ensureRuntime(targetDir);
1865
1974
  const loader = activeRuntime?.services?.resourceLoader;
1866
1975
  if (!loader || typeof loader.getSkills !== 'function' || typeof loader.getPrompts !== 'function' || typeof loader.getAgentsFiles !== 'function') {
@@ -1924,14 +2033,19 @@ export function createSessionDaemon({
1924
2033
 
1925
2034
  const finishPromptMutation = async (locations, targetDir) => {
1926
2035
  servicesCache.delete(targetDir);
1927
- await refreshAffectedPromptRuntimes([...new Set(locations)], targetDir);
1928
- return resourcesAfterPromptMutation(targetDir);
2036
+ const deferred = await refreshAffectedPromptRuntimes([...new Set(locations)], targetDir);
2037
+ const resources = await resourcesAfterPromptMutation(targetDir);
2038
+ return { ...resources, ...(deferred ? { deferred: true } : {}) };
1929
2039
  };
1930
2040
 
1931
- const requireIdleResourceMutation = () => {
1932
- if (runtime?.session?.isStreaming || runtime?.session?.isCompacting) {
1933
- throw new SessionDaemonProtocolError('SESSION_BUSY', 'Resources cannot change during an active session.');
1934
- }
2041
+ const resourcesWithUpdatedContent = (catalog, resource, content) => {
2042
+ const resources = publicResources(catalog);
2043
+ const key = resource.kind === 'agents' ? 'agents' : 'prompts';
2044
+ return {
2045
+ ...resources,
2046
+ [key]: resources[key].map((item) => item.id === resource.id ? { ...item, content } : item),
2047
+ deferred: true,
2048
+ };
1935
2049
  };
1936
2050
 
1937
2051
  let resourceMutation = Promise.resolve();
@@ -1978,16 +2092,7 @@ export function createSessionDaemon({
1978
2092
  await rm(temporary, { force: true }).catch(() => {});
1979
2093
  });
1980
2094
 
1981
- const refreshResources = async (targetDir) => {
1982
- servicesCache.delete(targetDir || activeDirectory || cwd);
1983
- if (runtime) {
1984
- await disposeRuntime();
1985
- await ensureRuntime();
1986
- }
1987
- return publicResources(await resourceCatalog(targetDir));
1988
- };
1989
-
1990
- const updateResource = async (payload) => {
2095
+ const updateResource = (payload) => transactResourceMutation(async () => {
1991
2096
  if (!payload || typeof payload.resourceId !== 'string' || typeof payload.content !== 'string' || payload.content.length > 200_000) {
1992
2097
  throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The Pi resource update is invalid.');
1993
2098
  }
@@ -1995,7 +2100,6 @@ export function createSessionDaemon({
1995
2100
  const catalog = await resourceCatalog(targetDir);
1996
2101
  const resource = [...catalog.prompts, ...catalog.agents].find((item) => item.id === payload.resourceId && item.editable === true);
1997
2102
  if (!resource?.filePath) throw new SessionDaemonProtocolError('RESOURCE_NOT_FOUND', 'The requested Pi resource is not editable.');
1998
- if (resource.kind !== 'prompt') requireIdleResourceMutation();
1999
2103
  let content = payload.content;
2000
2104
  if (resource.kind === 'prompt') {
2001
2105
  const previous = await readFile(resource.filePath, 'utf8').catch((error) => error?.code === 'ENOENT' ? '' : Promise.reject(error));
@@ -2004,8 +2108,11 @@ export function createSessionDaemon({
2004
2108
  }
2005
2109
  await writeResourceFile(resource.filePath, content);
2006
2110
  if (resource.kind === 'prompt') return finishPromptMutation([resource.location], targetDir);
2007
- return refreshResources(targetDir);
2008
- };
2111
+
2112
+ const deferred = await scheduleRuntimeRecreation();
2113
+ if (deferred) return resourcesWithUpdatedContent(catalog, resource, content);
2114
+ return publicResources(await resourceCatalog(targetDir));
2115
+ });
2009
2116
 
2010
2117
  const createPrompt = (payload) => transactResourceMutation(async () => {
2011
2118
  if (!payload || !['global', 'project'].includes(payload.location) || typeof payload.name !== 'string' || typeof payload.content !== 'string'
@@ -2448,7 +2555,16 @@ export function createSessionDaemon({
2448
2555
  throw new SessionDaemonProtocolError('INVALID_PROMPT', 'The session prompt is invalid.');
2449
2556
  }
2450
2557
  if (payload.thinking !== undefined) validateThinking(payload.thinking);
2451
- const activeRuntime = await activateSession(payload.sessionId, payload.directory);
2558
+ let activeRuntime = await activateSession(payload.sessionId, payload.directory);
2559
+ let recreated = false;
2560
+ try {
2561
+ recreated = await flushPendingRuntimeRecreation();
2562
+ } catch {
2563
+ // A failed rebuild stays queued for a later edge. Re-resolve the session so a
2564
+ // disposed runtime is retried instead of prompting on a stale handle.
2565
+ activeRuntime = await activateSession(payload.sessionId, payload.directory);
2566
+ }
2567
+ if (recreated) activeRuntime = await activateSession(payload.sessionId, payload.directory);
2452
2568
  await flushPendingResourceReload(activeRuntime);
2453
2569
  // After a provider stream dies, Pi can report idle while the UI still
2454
2570
  // retries as steer/follow-up. Start a new turn instead of rejecting.
@@ -2572,11 +2688,13 @@ export function createSessionDaemon({
2572
2688
  scheduleIdleDisposal(payload.sessionId);
2573
2689
  }
2574
2690
  });
2691
+ void flushPendingRuntimeRecreation().catch(() => {});
2575
2692
  });
2576
2693
  return { accepted: true, messageId };
2577
2694
  } catch (error) {
2578
2695
  endSessionInput(activeRuntime);
2579
2696
  void flushPendingResourceReload(activeRuntime);
2697
+ void flushPendingRuntimeRecreation().catch(() => {});
2580
2698
  throw error;
2581
2699
  }
2582
2700
  };
@@ -2631,6 +2749,7 @@ export function createSessionDaemon({
2631
2749
  latestUserMessageIds.delete(sessionId);
2632
2750
  latestAssistantMessageIds.delete(sessionId);
2633
2751
  toolInputBySession.delete(sessionId);
2752
+ clearToolTimingsForSession(sessionId);
2634
2753
  publish('session.lifecycle', { state: 'idle', deleted: true, serverNow: Date.now() }, sessionId, targetDir);
2635
2754
  };
2636
2755
 
@@ -2766,7 +2885,7 @@ export function createSessionDaemon({
2766
2885
  const startedAt = Date.now();
2767
2886
  const activeRuntime = runtimeRegistry?.get({ cwd: directory, sessionId }) || runtime;
2768
2887
  const metadata = mergeToolPresentationMetadata(undefined, activeRuntime, directory, event.toolName, event.args);
2769
- toolStartedAt.set(event.toolCallId, startedAt);
2888
+ toolStartedAt.set(toolTimingKey(sessionId, event.toolCallId), startedAt);
2770
2889
  rememberToolInput(sessionId, event.toolCallId, event.args);
2771
2890
  publish('session.tool.start', {
2772
2891
  toolCallId: event.toolCallId,
@@ -2778,11 +2897,14 @@ export function createSessionDaemon({
2778
2897
  ...(event.args !== undefined ? { input: redactAttachmentValues(event.args) } : {}),
2779
2898
  ...(metadata ? { metadata } : {}),
2780
2899
  startedAt,
2900
+ serverNow: startedAt,
2781
2901
  }, sessionId, directory);
2782
2902
  break;
2783
2903
  }
2784
2904
  case 'tool_execution_update': {
2785
2905
  const messageId = streamingMessageIds.get(sessionId) ?? latestAssistantMessageIds.get(sessionId) ?? `assistant-${sessionId}`;
2906
+ const startedAt = toolStartedAt.get(toolTimingKey(sessionId, event.toolCallId));
2907
+ const serverNow = Date.now();
2786
2908
  const activeRuntime = runtimeRegistry?.get({ cwd: directory, sessionId }) || runtime;
2787
2909
  const toolArgs = event.args ?? getToolInput(sessionId, event.toolCallId);
2788
2910
  const projected = projectToolResult(event.partialResult, false);
@@ -2797,14 +2919,19 @@ export function createSessionDaemon({
2797
2919
  ...(event.args !== undefined ? { input: redactAttachmentValues(event.args) } : {}),
2798
2920
  ...projected,
2799
2921
  ...(metadata ? { metadata } : {}),
2922
+ ...(Number.isFinite(startedAt) ? { startedAt } : {}),
2923
+ serverNow,
2800
2924
  }, sessionId, directory);
2801
2925
  break;
2802
2926
  }
2803
2927
  case 'tool_execution_end': {
2804
2928
  const messageId = streamingMessageIds.get(sessionId) ?? latestAssistantMessageIds.get(sessionId) ?? `assistant-${sessionId}`;
2805
- const startedAt = toolStartedAt.get(event.toolCallId);
2929
+ const timingKey = toolTimingKey(sessionId, event.toolCallId);
2930
+ const startedAt = toolStartedAt.get(timingKey);
2931
+ const endedAt = Date.now();
2806
2932
  const toolArgs = event.args ?? getToolInput(sessionId, event.toolCallId);
2807
- toolStartedAt.delete(event.toolCallId);
2933
+ rememberCompletedToolTiming(sessionId, event.toolCallId, startedAt, endedAt);
2934
+ toolStartedAt.delete(timingKey);
2808
2935
  forgetToolInput(sessionId, event.toolCallId);
2809
2936
  const activeRuntime = runtimeRegistry?.get({ cwd: directory, sessionId }) || runtime;
2810
2937
  const projected = projectToolResult(event.result, event.isError === true);
@@ -2820,7 +2947,8 @@ export function createSessionDaemon({
2820
2947
  ...projected,
2821
2948
  ...(metadata ? { metadata } : {}),
2822
2949
  ...(Number.isFinite(startedAt) ? { startedAt } : {}),
2823
- endedAt: Date.now(),
2950
+ endedAt,
2951
+ serverNow: endedAt,
2824
2952
  }, sessionId, directory);
2825
2953
  break;
2826
2954
  }
@@ -2863,12 +2991,14 @@ export function createSessionDaemon({
2863
2991
  latestUserMessageIds.delete(sessionId);
2864
2992
  latestAssistantMessageIds.delete(sessionId);
2865
2993
  toolInputBySession.delete(sessionId);
2994
+ clearToolTimingsForSession(sessionId, { keepCompleted: true });
2866
2995
  publish('session.lifecycle', { state: 'idle', serverNow: Date.now() }, sessionId, directory);
2867
2996
  if (!completeRequestedShutdown(sessionId)) {
2868
2997
  void flushPendingResourceReload(owningRuntime).then(() => {
2869
2998
  if (!shutdownRequestedBySession.has(sessionId)) scheduleIdleDisposal(sessionId);
2870
2999
  });
2871
3000
  }
3001
+ void flushPendingRuntimeRecreation().catch(() => {});
2872
3002
  break;
2873
3003
  case 'session_info_changed': {
2874
3004
  const title = typeof event.name === 'string' ? event.name.trim() : '';
@@ -2938,6 +3068,7 @@ export function createSessionDaemon({
2938
3068
  if (!event.willRetry) {
2939
3069
  void flushPendingResourceReload(owningRuntime).then(() => scheduleIdleDisposal(sessionId));
2940
3070
  }
3071
+ void flushPendingRuntimeRecreation().catch(() => {});
2941
3072
  break;
2942
3073
  }
2943
3074
  default:
@@ -3462,6 +3593,8 @@ export function createSessionDaemon({
3462
3593
  retryStateBySession.clear();
3463
3594
  compactionStateBySession.clear();
3464
3595
  activeRunStartedAt.clear();
3596
+ toolStartedAt.clear();
3597
+ completedToolTimings.clear();
3465
3598
  shutdownRequestedBySession.clear();
3466
3599
  disposingSessionIds.clear();
3467
3600
  sendGenerationBySession.clear();
@@ -3475,6 +3608,8 @@ export function createSessionDaemon({
3475
3608
  await new Promise((resolve, reject) => {
3476
3609
  server.close((error) => error ? reject(error) : resolve());
3477
3610
  });
3611
+ pendingRuntimeRecreation = false;
3612
+ runtimeRecreationRevision += 1;
3478
3613
  await disposeRuntime();
3479
3614
  server = undefined;
3480
3615
  started = false;
@@ -297,6 +297,66 @@ describe('Pi session daemon spike', () => {
297
297
  await reconnectingClient.close();
298
298
  });
299
299
 
300
+ it('projects the authoritative tool start through session hydration for active and completed calls', async () => {
301
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-'));
302
+ const endpoint = testDaemonEndpoint(root);
303
+ const session = new FakeSession();
304
+ daemon = createSessionDaemon({ endpoint, credential, cwd: root, createRuntime: async () => ({ session, async dispose() {} }) });
305
+ await daemon.start();
306
+
307
+ const client = connectClient(endpoint);
308
+ await client.authenticate();
309
+ await client.request('sessions.create', { cwd: root });
310
+ session.isStreaming = true;
311
+ session.entries = [{
312
+ type: 'message',
313
+ id: 'assistant-entry',
314
+ timestamp: '2026-01-01T00:00:01.000Z',
315
+ message: {
316
+ role: 'assistant',
317
+ provider: 'test',
318
+ model: 'model',
319
+ content: [{ type: 'toolCall', id: 'tool-1', name: 'read', arguments: { path: 'file.txt' } }],
320
+ },
321
+ }];
322
+
323
+ const toolStartPromise = client.next((message) => message.event === 'session.tool.start');
324
+ session.emit({ type: 'tool_execution_start', toolCallId: 'tool-1', toolName: 'read', args: { path: 'file.txt' } });
325
+ const toolStart = await toolStartPromise;
326
+ const activeDetail = await client.request('sessions.open', { sessionId: session.sessionId, directory: root });
327
+ const activeTool = activeDetail.result.messages[0].parts[0];
328
+ expect(activeTool).toMatchObject({
329
+ toolCallId: 'tool-1',
330
+ state: 'running',
331
+ startedAt: toolStart.payload.startedAt,
332
+ });
333
+
334
+ session.entries.push({
335
+ type: 'message',
336
+ id: 'tool-result-entry',
337
+ timestamp: new Date(Date.now()).toISOString(),
338
+ message: {
339
+ role: 'toolResult',
340
+ toolCallId: 'tool-1',
341
+ isError: false,
342
+ content: [{ type: 'text', text: 'file contents' }],
343
+ },
344
+ });
345
+ const toolEndPromise = client.next((message) => message.event === 'session.tool.end');
346
+ session.emit({ type: 'tool_execution_end', toolCallId: 'tool-1', toolName: 'read', result: { content: [{ type: 'text', text: 'file contents' }] }, isError: false });
347
+ const toolEnd = await toolEndPromise;
348
+ const completedDetail = await client.request('sessions.open', { sessionId: session.sessionId, directory: root });
349
+ const completedTool = completedDetail.result.messages[0].parts[0];
350
+ expect(completedTool).toMatchObject({
351
+ toolCallId: 'tool-1',
352
+ state: 'completed',
353
+ startedAt: toolStart.payload.startedAt,
354
+ endedAt: expect.any(Number),
355
+ });
356
+ expect(toolEnd.payload.startedAt).toBe(toolStart.payload.startedAt);
357
+ await client.close();
358
+ });
359
+
300
360
  it('replays a contiguous reconnect gap and sends a snapshot when the cursor predates retained events', async () => {
301
361
  const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-'));
302
362
  const endpoint = testDaemonEndpoint(root);
@@ -1407,6 +1467,80 @@ describe('Pi session daemon spike', () => {
1407
1467
  await client.close();
1408
1468
  });
1409
1469
 
1470
+ it('persists project trust while streaming and refreshes after settlement', async () => {
1471
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-settings-busy-'));
1472
+ const endpoint = testDaemonEndpoint(root);
1473
+ const session = new FakeSession();
1474
+ const runtimeState = { createCount: 0, disposeCount: 0 };
1475
+ daemon = createSessionDaemon({
1476
+ endpoint,
1477
+ credential,
1478
+ cwd: root,
1479
+ createRuntime: async () => {
1480
+ runtimeState.createCount += 1;
1481
+ return {
1482
+ cwd: root,
1483
+ session,
1484
+ async dispose() { runtimeState.disposeCount += 1; },
1485
+ };
1486
+ },
1487
+ });
1488
+ await daemon.start();
1489
+ const client = connectClient(endpoint);
1490
+ await client.authenticate();
1491
+ await client.request('sessions.create', { cwd: root });
1492
+
1493
+ session.isStreaming = true;
1494
+ const result = await client.request('settings.set', { scope: 'project', trust: true });
1495
+ expect(result.result).toMatchObject({ project: { trusted: true }, deferred: true });
1496
+ expect(runtimeState).toEqual({ createCount: 1, disposeCount: 0 });
1497
+
1498
+ session.isStreaming = false;
1499
+ session.emit({ type: 'agent_settled' });
1500
+ await expect.poll(() => runtimeState.disposeCount).toBe(1);
1501
+ expect(runtimeState.createCount).toBe(2);
1502
+ await client.close();
1503
+ });
1504
+
1505
+ it('reports deferred activation when an idle runtime cannot be recreated after trust commits', async () => {
1506
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-settings-recreate-failure-'));
1507
+ const endpoint = testDaemonEndpoint(root);
1508
+ let createCount = 0;
1509
+ daemon = createSessionDaemon({
1510
+ endpoint,
1511
+ credential,
1512
+ cwd: root,
1513
+ createRuntime: async () => {
1514
+ createCount += 1;
1515
+ if (createCount === 2) throw new Error('runtime recreation failed');
1516
+ return {
1517
+ cwd: root,
1518
+ session: new FakeSession(),
1519
+ services: {
1520
+ resourceLoader: {
1521
+ getSkills: () => ({ skills: [] }),
1522
+ getPrompts: () => ({ prompts: [] }),
1523
+ getAgentsFiles: () => ({ agentsFiles: [] }),
1524
+ },
1525
+ },
1526
+ async dispose() {},
1527
+ };
1528
+ },
1529
+ });
1530
+ await daemon.start();
1531
+ const client = connectClient(endpoint);
1532
+ await client.authenticate();
1533
+ await client.request('sessions.create', { cwd: root });
1534
+
1535
+ const result = await client.request('settings.set', { scope: 'project', trust: true });
1536
+ expect(result.result).toMatchObject({ project: { trusted: true }, deferred: true });
1537
+ expect(createCount).toBe(2);
1538
+
1539
+ await expect(client.request('resources.list')).resolves.toMatchObject({ result: { agents: expect.any(Array) } });
1540
+ expect(createCount).toBe(3);
1541
+ await client.close();
1542
+ });
1543
+
1410
1544
  it('lists and edits only opaque Pi resource identifiers without disclosing server paths', async () => {
1411
1545
  const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-resources-'));
1412
1546
  const cwd = join(root, 'project');
@@ -1511,6 +1645,58 @@ describe('Pi session daemon spike', () => {
1511
1645
  await client.close();
1512
1646
  });
1513
1647
 
1648
+ it('persists provider model changes while streaming and refreshes after settlement', async () => {
1649
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-provider-busy-'));
1650
+ const endpoint = testDaemonEndpoint(root);
1651
+ const session = new FakeSession();
1652
+ const runtimeState = { createCount: 0, disposeCount: 0 };
1653
+ const updates = [];
1654
+ const modelConfigStore = {
1655
+ get: async () => null,
1656
+ update: async (input) => {
1657
+ updates.push(input);
1658
+ return { providerId: input.providerId, label: input.label, baseUrl: input.baseUrl, api: input.api, models: input.models };
1659
+ },
1660
+ };
1661
+ daemon = createSessionDaemon({
1662
+ endpoint,
1663
+ credential,
1664
+ cwd: root,
1665
+ modelConfigStore,
1666
+ createRuntime: async () => {
1667
+ runtimeState.createCount += 1;
1668
+ return {
1669
+ cwd: root,
1670
+ session,
1671
+ async dispose() { runtimeState.disposeCount += 1; },
1672
+ };
1673
+ },
1674
+ });
1675
+ await daemon.start();
1676
+ const client = connectClient(endpoint);
1677
+ await client.authenticate();
1678
+
1679
+ await client.request('sessions.create', { cwd: root });
1680
+ session.isStreaming = true;
1681
+ const result = await client.request('providers.models.set', {
1682
+ providerId: 'custom',
1683
+ label: 'Custom',
1684
+ baseUrl: 'https://api.example.test/v1',
1685
+ api: 'openai-completions',
1686
+ models: [{ id: 'model', providerId: 'custom', label: 'Model' }],
1687
+ });
1688
+
1689
+ expect(result.result).toMatchObject({ config: { providerId: 'custom' }, deferred: true });
1690
+ expect(updates).toHaveLength(1);
1691
+ expect(runtimeState).toEqual({ createCount: 1, disposeCount: 0 });
1692
+
1693
+ session.isStreaming = false;
1694
+ session.emit({ type: 'agent_settled' });
1695
+ await expect.poll(() => runtimeState.disposeCount).toBe(1);
1696
+ expect(runtimeState.createCount).toBe(2);
1697
+ await client.close();
1698
+ });
1699
+
1514
1700
  it('runs persisted API-key and interactive OAuth logins without exposing credential values in daemon responses', async () => {
1515
1701
  const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-'));
1516
1702
  const endpoint = testDaemonEndpoint(root);