@pi-chamber/web 0.8.0 → 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 (64) hide show
  1. package/dist/assets/{DiagramEditor-YPSKccgo.js → DiagramEditor-DerMrS6m.js} +1 -1
  2. package/dist/assets/{DiagramView-C-PbBHce.js → DiagramView-DdipXAq8.js} +1 -1
  3. package/dist/assets/{DiffView-DfltyfN2.js → DiffView-Gh9wjthp.js} +1 -1
  4. package/dist/assets/FilesView-BXp0yc0j.js +6 -0
  5. package/dist/assets/{GitView-B_zTaXX4.js → GitView-BmNCkkoC.js} +3 -3
  6. package/dist/assets/{JsonTreeView-9p4txyB_.js → JsonTreeView-CxXRXXzk.js} +1 -1
  7. package/dist/assets/{MarkdownRendererImpl-CbRPLK2x.js → MarkdownRendererImpl-DNZQgQua.js} +1 -1
  8. package/dist/assets/{PatchDiff-rKjeUBRl.js → PatchDiff-B_NFEIX7.js} +1 -1
  9. package/dist/assets/{SessionSwitcherContent-C_VxKFJy.js → SessionSwitcherContent-Q4P2TGBr.js} +1 -1
  10. package/dist/assets/{SessionSwitcherDropdown-_k4P32o9.js → SessionSwitcherDropdown-Cgw2mQIO.js} +2 -2
  11. package/dist/assets/{SessionUnreadDot-bT_0MixU.js → SessionUnreadDot-BxtTkvHB.js} +1 -1
  12. package/dist/assets/SettingsView-CFzxRzUq.js +2 -0
  13. package/dist/assets/{SettingsWindow-C7vVE35-.js → SettingsWindow-BEjHL1ET.js} +1 -1
  14. package/dist/assets/{ToolOutputDialog-GBbzATa6.js → ToolOutputDialog-C_7vJLEq.js} +1 -1
  15. package/dist/assets/{ToolPartDiffPreview-Bdb9p5uS.js → ToolPartDiffPreview-ClV785zX.js} +1 -1
  16. package/dist/assets/{VirtualizedFileDiff-CA8hQyz9.js → VirtualizedFileDiff-DrxkW2WQ.js} +1 -1
  17. package/dist/assets/{collapsible-uwSKBy-K.js → collapsible-CR3-hRMy.js} +1 -1
  18. package/dist/assets/{computeVirtualFileMetrics-9LNCLvAG.js → computeVirtualFileMetrics-D0mQcleY.js} +1 -1
  19. package/dist/assets/{contextFileOpenGuard-CZSqdEHk.js → contextFileOpenGuard-BRc5Z0g-.js} +1 -1
  20. package/dist/assets/{gitStatusPredicates-CRmbLl-x.js → gitStatusPredicates-DBGDfr1K.js} +1 -1
  21. package/dist/assets/{index-BeJEipxi.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-YYyZNTdb.js → isDiffPlainText-MmBA1REG.js} +1 -1
  25. package/dist/assets/{isFilePlainText-C70Z71bG.js → isFilePlainText-bQAPxqO9.js} +1 -1
  26. package/dist/assets/{main-CsdVAKy_.js → main-BoVfUG73.js} +8 -8
  27. package/dist/assets/{main-GMQIZjuQ.js → main-zZrKd3hZ.js} +2 -2
  28. package/dist/assets/{markdownCore-BgVcDt0q.js → markdownCore-B9jXCPry.js} +1 -1
  29. package/dist/assets/{miniChat-W6YsdiWR.js → miniChat-Di2oVS5o.js} +2 -2
  30. package/dist/assets/{mobile-BFR9CR5w.js → mobile-VU_G_SgX.js} +2 -2
  31. package/dist/assets/{renderElectronMiniChatApp-B8ZiW-3E.js → renderElectronMiniChatApp-Bi1927c8.js} +2 -2
  32. package/dist/assets/{renderMobileApp-C5CdsYP6.js → renderMobileApp-D9mxhuaM.js} +3 -3
  33. package/dist/assets/runtimeEndpointReset-DImT35Ug.js +54 -0
  34. package/dist/assets/{runtimeSurface-B818u-_c.js → runtimeSurface-CBaS2Ank.js} +1 -1
  35. package/dist/assets/{useAppFontEffects-CYzYRbLp.js → useAppFontEffects-8ZU-TTIW.js} +111 -111
  36. package/dist/assets/{useFilesViewSearch-C--GWtn-.js → useFilesViewSearch-COow9O9x.js} +1 -1
  37. package/dist/assets/{usePushVisibilityBeacon-D9lajdAc.js → usePushVisibilityBeacon-zYd3ppNh.js} +1 -1
  38. package/dist/assets/{useSwitcherItems-DOoi3x_8.js → useSwitcherItems-DOQqhi-e.js} +1 -1
  39. package/dist/assets/{vendor-codemirror-language-data-DS_4W5G4.js → vendor-codemirror-language-data-B_0wrsbo.js} +2 -2
  40. package/dist/assets/vendor-framer-motion-CfplGuM0.js +1 -0
  41. package/dist/assets/{vendor-motion-dom-DJLgZh4Q.js → vendor-motion-dom-DhJ-sYS5.js} +1 -1
  42. package/dist/assets/{vendor-motion-utils-BGh8QBgx.js → vendor-motion-utils-CKEGc_YG.js} +1 -1
  43. package/dist/assets/{web-components-C2cMNPqE.js → web-components-C9ENH49P.js} +1 -1
  44. package/dist/index.html +4 -4
  45. package/dist/mini-chat.html +3 -3
  46. package/dist/mobile.html +3 -3
  47. package/package.json +1 -1
  48. package/server/lib/pi/routes.test.js +39 -0
  49. package/server/lib/pi/session-daemon/DOCUMENTATION.md +1 -1
  50. package/server/lib/pi/session-daemon/extension-bridge.js +14 -11
  51. package/server/lib/pi/session-daemon/prompt-operations.test.js +73 -6
  52. package/server/lib/pi/session-daemon/session-daemon.js +163 -21
  53. package/server/lib/relay/host-client.test.js +3 -1
  54. package/server/lib/server/cors.js +2 -0
  55. package/server/lib/server/cors.test.js +5 -3
  56. package/server/lib/ui-auth/DOCUMENTATION.md +1 -1
  57. package/server/lib/ui-auth/ui-auth.js +23 -26
  58. package/server/lib/ui-auth/ui-auth.test.js +27 -0
  59. package/dist/assets/FilesView-BEjbLiK2.js +0 -6
  60. package/dist/assets/SettingsView-CqZ1ZAWG.js +0 -2
  61. package/dist/assets/index-CaP8oFLB.js +0 -8
  62. package/dist/assets/index-Dq8CnRYM.css +0 -1
  63. package/dist/assets/runtimeEndpointReset-D3AZYuoF.js +0 -54
  64. package/dist/assets/vendor-framer-motion-BUygY0oN.js +0 -1
@@ -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 = [];
@@ -11,6 +11,7 @@ const ALLOWED_CORS_HEADER_NAMES = new Set([
11
11
  'content-type',
12
12
  'x-pichamber-directory',
13
13
  'x-pichamber-filename',
14
+ 'x-pichamber-mime',
14
15
  'x-requested-with',
15
16
  ]);
16
17
 
@@ -22,6 +23,7 @@ const DEFAULT_ALLOWED_CORS_HEADERS = [
22
23
  'Cache-Control',
23
24
  'x-pichamber-directory',
24
25
  'x-pichamber-filename',
26
+ 'x-pichamber-mime',
25
27
  ].join(',');
26
28
 
27
29
  export const isAllowedUiCorsOrigin = (origin) => (
@@ -16,8 +16,10 @@ describe('packaged UI CORS', () => {
16
16
  expect(resolveAllowedCorsHeaders('x-pichamber-directory,authorization')).toBe('x-pichamber-directory,authorization');
17
17
  expect(resolveAllowedCorsHeaders('x-pichamber-directory')).toBe('x-pichamber-directory');
18
18
  expect(resolveAllowedCorsHeaders('x-pichamber-filename')).toBe('x-pichamber-filename');
19
+ expect(resolveAllowedCorsHeaders('x-pichamber-mime')).toBe('x-pichamber-mime');
20
+ expect(resolveAllowedCorsHeaders('x-pichamber-filename,x-pichamber-mime')).toBe('x-pichamber-filename,x-pichamber-mime');
19
21
  expect(resolveAllowedCorsHeaders('x-evil')).toBe(
20
- 'Content-Type,Authorization,Accept,X-Requested-With,Cache-Control,x-pichamber-directory,x-pichamber-filename',
22
+ 'Content-Type,Authorization,Accept,X-Requested-With,Cache-Control,x-pichamber-directory,x-pichamber-filename,x-pichamber-mime',
21
23
  );
22
24
  });
23
25
 
@@ -28,11 +30,11 @@ describe('packaged UI CORS', () => {
28
30
  method: 'OPTIONS',
29
31
  headers: {
30
32
  origin: 'pichamber-ui://app',
31
- 'access-control-request-headers': 'x-pichamber-directory,x-pichamber-filename,authorization',
33
+ 'access-control-request-headers': 'x-pichamber-directory,x-pichamber-filename,x-pichamber-mime,authorization',
32
34
  },
33
35
  }, res);
34
36
  expect(ended).toBe(true);
35
37
  expect(headers['Access-Control-Allow-Origin']).toBe('pichamber-ui://app');
36
- expect(headers['Access-Control-Allow-Headers']).toBe('x-pichamber-directory,x-pichamber-filename,authorization');
38
+ expect(headers['Access-Control-Allow-Headers']).toBe('x-pichamber-directory,x-pichamber-filename,x-pichamber-mime,authorization');
37
39
  });
38
40
  });
@@ -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.
@@ -1,6 +1,6 @@
1
1
  import crypto from 'crypto';
2
2
  import { promisify } from 'util';
3
- import { SignJWT, jwtVerify } from 'jose';
3
+ import { EncryptJWT, jwtDecrypt, SignJWT, jwtVerify } from 'jose';
4
4
  import fs from 'fs';
5
5
  import path from 'path';
6
6
  import { resolvePiChamberDataDir, resolvePiChamberDataPath } from '../pichamber-data-dir.js';
@@ -399,40 +399,39 @@ export const createUiAuth = ({
399
399
  requireClientAuth = false,
400
400
  } = {}) => {
401
401
  const normalizedPassword = normalizePassword(password);
402
- const urlAuthTokens = new Map();
402
+ let jwtSecret = getOrCreateJwtSecret();
403
403
 
404
- const sweepUrlAuthTokens = () => {
405
- const now = Date.now();
406
- for (const [token, entry] of urlAuthTokens.entries()) {
407
- if (!entry || entry.expiresAt <= now) {
408
- urlAuthTokens.delete(token);
409
- }
410
- }
411
- };
404
+ const getUrlAuthEncryptionKey = () => crypto.createHash('sha256').update(jwtSecret).digest();
412
405
 
413
- const issueUrlAuthTokenForSession = (sessionToken) => {
414
- sweepUrlAuthTokens();
415
- const token = `${URL_AUTH_TOKEN_PREFIX}${crypto.randomBytes(24).toString('base64url')}`;
406
+ const issueUrlAuthTokenForSession = async (sessionToken) => {
416
407
  const expiresAt = Date.now() + URL_AUTH_TOKEN_TTL_MS;
417
- urlAuthTokens.set(token, { sessionToken, expiresAt });
418
- return { token, expiresAt };
408
+ const encryptedToken = await new EncryptJWT({ type: 'url-auth', sessionToken })
409
+ .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' })
410
+ .setIssuedAt()
411
+ .setExpirationTime(Math.floor(expiresAt / 1000))
412
+ .encrypt(getUrlAuthEncryptionKey());
413
+ return { token: `${URL_AUTH_TOKEN_PREFIX}${encryptedToken}`, expiresAt };
419
414
  };
420
415
 
421
- const authenticateUrlAuthToken = (req) => {
416
+ const authenticateUrlAuthToken = async (req) => {
422
417
  if (!canUseUrlAuthTokenForRequest(req)) return null;
423
418
  const token = getUrlAuthTokenFromRequest(req);
424
419
  if (!token || !token.startsWith(URL_AUTH_TOKEN_PREFIX)) return null;
425
- const entry = urlAuthTokens.get(token);
426
- if (!entry || entry.expiresAt <= Date.now()) {
427
- urlAuthTokens.delete(token);
420
+ try {
421
+ const { payload } = await jwtDecrypt(token.slice(URL_AUTH_TOKEN_PREFIX.length), getUrlAuthEncryptionKey(), {
422
+ keyManagementAlgorithms: ['dir'],
423
+ contentEncryptionAlgorithms: ['A256GCM'],
424
+ });
425
+ if (payload.type !== 'url-auth' || typeof payload.sessionToken !== 'string' || !payload.sessionToken) return null;
426
+ return { ok: true, sessionToken: payload.sessionToken };
427
+ } catch {
428
428
  return null;
429
429
  }
430
- return { ok: true, sessionToken: entry.sessionToken || 'url:authenticated' };
431
430
  };
432
431
 
433
432
  const authenticateClientRequest = async (req, { allowUrlToken = true } = {}) => {
434
433
  if (allowUrlToken) {
435
- const urlAuth = authenticateUrlAuthToken(req);
434
+ const urlAuth = await authenticateUrlAuthToken(req);
436
435
  if (urlAuth) return urlAuth;
437
436
  }
438
437
  const token = getBearerTokenFromRequest(req);
@@ -554,14 +553,14 @@ export const createUiAuth = ({
554
553
  const clientAuth = await authenticateClientRequest(req, { allowUrlToken: false });
555
554
  if (clientAuth) {
556
555
  res.setHeader('Cache-Control', 'no-store');
557
- return res.json(issueUrlAuthTokenForSession(clientSessionToken(clientAuth)));
556
+ return res.json(await issueUrlAuthTokenForSession(clientSessionToken(clientAuth)));
558
557
  }
559
558
  if (requireClientAuth) {
560
559
  return res.status(401).json({ error: 'Client authentication required', locked: true, clientAuthRequired: true });
561
560
  }
562
561
  const sessionToken = await ensureSessionToken(req, res);
563
562
  res.setHeader('Cache-Control', 'no-store');
564
- return res.json(issueUrlAuthTokenForSession(sessionToken));
563
+ return res.json(await issueUrlAuthTokenForSession(sessionToken));
565
564
  },
566
565
  handlePasskeyStatus: (_req, res) => {
567
566
  res.json({ enabled: false, hasPasskeys: false, passkeyCount: 0, rpID: null });
@@ -600,7 +599,6 @@ export const createUiAuth = ({
600
599
 
601
600
  const salt = crypto.randomBytes(16);
602
601
  const expectedHash = crypto.scryptSync(normalizedPassword, salt, 64);
603
- let jwtSecret = getOrCreateJwtSecret();
604
602
  let passwordBinding = crypto.createHmac('sha256', jwtSecret).update(normalizedPassword).digest('hex');
605
603
  const resolveSessionTtlMs = (trustDevice) => (trustDevice ? TRUSTED_DEVICE_SESSION_TTL_MS : sessionTtlMs);
606
604
  let passkeyController = createUiPasskeys({
@@ -620,7 +618,6 @@ export const createUiAuth = ({
620
618
  const rotateJwtSecret = () => {
621
619
  const nextSecret = crypto.randomBytes(32).toString('hex');
622
620
  jwtSecret = persistJwtSecret(nextSecret);
623
- urlAuthTokens.clear();
624
621
  rebuildPasskeyController();
625
622
  };
626
623
 
@@ -793,7 +790,7 @@ export const createUiAuth = ({
793
790
  return respondUnauthorized(req, res);
794
791
  }
795
792
  res.setHeader('Cache-Control', 'no-store');
796
- return res.json(issueUrlAuthTokenForSession(sessionToken));
793
+ return res.json(await issueUrlAuthTokenForSession(sessionToken));
797
794
  };
798
795
 
799
796
  const handleSessionCreate = async (req, res) => {
@@ -228,6 +228,33 @@ describe('ui auth client credential seam', () => {
228
228
  }
229
229
  });
230
230
 
231
+ it('keeps terminal and dictation URL tokens valid across a server restart', async () => {
232
+ const createUiAuth = await loadCreateUiAuth();
233
+ const clientAuthController = {
234
+ authenticateBearerToken: async (token) => token === 'client-token' ? { ok: true, clientId: 'device-1' } : null,
235
+ };
236
+ const beforeRestart = createUiAuth({ password: 'secret', clientAuthController });
237
+ const mintRes = createResponse();
238
+ await beforeRestart.handleUrlAuthToken({
239
+ method: 'POST',
240
+ path: '/auth/url-token',
241
+ headers: { authorization: 'Bearer client-token', accept: 'application/json' },
242
+ }, mintRes);
243
+ beforeRestart.dispose();
244
+
245
+ const afterRestart = createUiAuth({ password: 'secret', clientAuthController });
246
+ for (const path of ['/api/terminal/ws', '/api/stt/ws']) {
247
+ const websocketReq = {
248
+ method: 'GET',
249
+ path,
250
+ url: `${path}?oc_url_token=${encodeURIComponent(mintRes.body.token)}`,
251
+ headers: { connection: 'Upgrade', upgrade: 'websocket' },
252
+ };
253
+ expect(await afterRestart.ensureSessionToken(websocketReq, createResponse())).toBe('client:device-1');
254
+ }
255
+ afterRestart.dispose();
256
+ });
257
+
231
258
  it('issues desktop client tokens with the UI session expiry', async () => {
232
259
  const createUiAuth = await loadCreateUiAuth();
233
260
  let createClientInput = null;