@pi-chamber/web 0.1.9 → 0.2.1

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 (86) hide show
  1. package/README.md +1 -1
  2. package/bin/cli.test.js +48 -0
  3. package/bin/lib/DOCUMENTATION.md +2 -2
  4. package/bin/lib/cli-args.js +38 -11
  5. package/bin/lib/cli-startup.js +60 -13
  6. package/bin/lib/commands-startup.js +20 -5
  7. package/bin/lib/commands-update.js +91 -34
  8. package/bin/lib/commands-update.test.js +57 -42
  9. package/dist/assets/CommitSection-BQBmpPVE.js +1 -0
  10. package/dist/assets/DiagramEditor-Cp22TGpq.js +1 -0
  11. package/dist/assets/DiagramView-E4HJ4ZPU.js +1 -0
  12. package/dist/assets/{DiffView-k3lX2PiV.js → DiffView-d23o9CKP.js} +2 -2
  13. package/dist/assets/{FilesView-C39IOFfs.js → FilesView-DIDB-xK7.js} +6 -6
  14. package/dist/assets/{GitView-CkztSaT7.js → GitView-CkUONO1-.js} +4 -4
  15. package/dist/assets/JsonTreeView-By2oGMNK.js +1 -0
  16. package/dist/assets/{MarkdownRendererImpl-CF12jEtB.js → MarkdownRendererImpl-DUghE55t.js} +2 -2
  17. package/dist/assets/PatchDiff-BjN6zMtK.js +1 -0
  18. package/dist/assets/{PierreDiffViewer-DSQwk05R.js → PierreDiffViewer-B38_7NnU.js} +2 -2
  19. package/dist/assets/{useAppFontEffects-DqOhrZWx.js → SessionSwitcherDropdown-NbVfnqQQ.js} +102 -102
  20. package/dist/assets/{SettingsView-Bf4vWwVK.js → SettingsView-C2dCv0r7.js} +1 -1
  21. package/dist/assets/SettingsWindow-DsMhdX5H.js +1 -0
  22. package/dist/assets/{ToolOutputDialog-Brg2Humk.js → ToolOutputDialog-DVesARmI.js} +6 -6
  23. package/dist/assets/ToolPartDiffPreview-C2N_oIO-.js +8 -0
  24. package/dist/assets/{VirtualizedFileDiff-BELx71mz.js → VirtualizedFileDiff-B7eVR6Pt.js} +1 -1
  25. package/dist/assets/collapsible-CPkWB1VR.js +1 -0
  26. package/dist/assets/computeVirtualFileMetrics-BsZulefS.js +3 -0
  27. package/dist/assets/contextFileOpenGuard-BmmlK5E3.js +1 -0
  28. package/dist/assets/index-BZXqJcua.css +1 -0
  29. package/dist/assets/{index-Dnby-sDS.js → index-BhXma4dv.js} +2 -2
  30. package/dist/assets/index-C84KrQoy.js +1 -0
  31. package/dist/assets/isDiffPlainText-DsuyxFXo.js +1 -0
  32. package/dist/assets/isFilePlainText-CCYoe7us.js +1 -0
  33. package/dist/assets/main-ClYgYVm1.js +2 -0
  34. package/dist/assets/main-CmrF_CaW.js +133 -0
  35. package/dist/assets/{markdownCore-BK98alzY.js → markdownCore-D2uqals1.js} +2 -2
  36. package/dist/assets/miniChat-DmX9SjxM.js +2 -0
  37. package/dist/assets/mobile-C-PCxN62.js +2 -0
  38. package/dist/assets/renderElectronMiniChatApp-BhXZtZlU.js +1 -0
  39. package/dist/assets/renderMobileApp-DUSTAPWw.js +23 -0
  40. package/dist/assets/{runtimeSurface-DMXukysz.js → runtimeSurface-CouGjZ3A.js} +1 -1
  41. package/dist/assets/{useInlineCommentController-ruw8wb2Y.js → useInlineCommentController-buNJ3xB4.js} +2 -2
  42. package/dist/assets/usePanelSlide-BRwyEEzi.js +47 -0
  43. package/dist/assets/{useWindowTitle-qt23iibv.js → useWindowTitle-CnF4pKz0.js} +3 -3
  44. package/dist/assets/{vendor-codemirror-language-data-DVYP3hf_.js → vendor-codemirror-language-data-qBLdzwMc.js} +2 -2
  45. package/dist/assets/{web-components-P2py0R8j.js → web-components-BhO08KaW.js} +4 -4
  46. package/dist/index.html +4 -4
  47. package/dist/mini-chat.html +3 -3
  48. package/dist/mobile.html +3 -3
  49. package/package.json +1 -1
  50. package/server/index.js +6 -1
  51. package/server/lib/package-manager.js +44 -65
  52. package/server/lib/package-manager.test.js +27 -0
  53. package/server/lib/pi/routes.js +19 -1
  54. package/server/lib/pi/routes.test.js +36 -0
  55. package/server/lib/pi/session-daemon/DOCUMENTATION.md +6 -5
  56. package/server/lib/pi/session-daemon/daemon-process.js +4 -1
  57. package/server/lib/pi/session-daemon/session-daemon.js +149 -24
  58. package/server/lib/pi/session-daemon/session-daemon.test.js +232 -0
  59. package/server/lib/pi/session-daemon/session-jsonl.js +258 -6
  60. package/server/lib/pi/session-daemon/session-jsonl.test.js +69 -1
  61. package/server/lib/pi/session-daemon/supervisor.js +41 -21
  62. package/server/lib/pi/session-daemon/supervisor.test.js +28 -0
  63. package/dist/assets/CommitSection-DSFuOWuL.js +0 -1
  64. package/dist/assets/DiagramEditor-D6W6zeV7.js +0 -1
  65. package/dist/assets/DiagramView-r89Qi5ON.js +0 -1
  66. package/dist/assets/JsonTreeView-C6qt2uIj.js +0 -1
  67. package/dist/assets/PatchDiff-D6In_lUU.js +0 -1
  68. package/dist/assets/SessionSwitcherDropdown-CvE7hsxG.js +0 -1
  69. package/dist/assets/SettingsWindow-B8IV35H4.js +0 -1
  70. package/dist/assets/ToolPartDiffPreview-rlz2ipa2.js +0 -8
  71. package/dist/assets/collapsible-QoPrpZP_.js +0 -1
  72. package/dist/assets/computeVirtualFileMetrics-CInbUZiB.js +0 -3
  73. package/dist/assets/contextFileOpenGuard-BOtkNMZy.js +0 -1
  74. package/dist/assets/index-4sRd3SSM.js +0 -1
  75. package/dist/assets/index-NYG3k04a.css +0 -1
  76. package/dist/assets/isDiffPlainText-BquUayus.js +0 -1
  77. package/dist/assets/isFilePlainText-D4iUTBdr.js +0 -1
  78. package/dist/assets/main-Cp3YZZm1.js +0 -2
  79. package/dist/assets/main-CyshB9VI.js +0 -134
  80. package/dist/assets/miniChat-C_A4lnrT.js +0 -2
  81. package/dist/assets/mobile-2dXx6cUI.js +0 -2
  82. package/dist/assets/renderElectronMiniChatApp-HL15h5xo.js +0 -1
  83. package/dist/assets/renderMobileApp-w6YFCJhq.js +0 -23
  84. package/dist/assets/runtimeEndpointReset-DiVqZFZB.js +0 -46
  85. package/dist/assets/useOpenInAppsStore-DVr2oGEm.js +0 -1
  86. /package/dist/assets/{runtimeEndpointReset-BV3KOtdA.css → usePanelSlide-BV3KOtdA.css} +0 -0
@@ -89,14 +89,14 @@
89
89
  }
90
90
  </style>
91
91
 
92
- <script type="module" crossorigin src="/assets/miniChat-C_A4lnrT.js"></script>
92
+ <script type="module" crossorigin src="/assets/miniChat-DmX9SjxM.js"></script>
93
93
  <link rel="modulepreload" crossorigin href="/assets/vendor-vite-runtime-DD1OZmLC.js">
94
94
  <link rel="modulepreload" crossorigin href="/assets/vendor-scheduler-7OC5HNn7.js">
95
95
  <link rel="modulepreload" crossorigin href="/assets/vendor-react-DYyjh7Q0.js">
96
96
  <link rel="modulepreload" crossorigin href="/assets/vendor-zustand-CnsBKjP5.js">
97
- <link rel="modulepreload" crossorigin href="/assets/index-Dnby-sDS.js">
97
+ <link rel="modulepreload" crossorigin href="/assets/index-BhXma4dv.js">
98
98
  <link rel="modulepreload" crossorigin href="/assets/vendor-katex-CHD9BdDO.js">
99
- <link rel="stylesheet" crossorigin href="/assets/index-NYG3k04a.css">
99
+ <link rel="stylesheet" crossorigin href="/assets/index-BZXqJcua.css">
100
100
  <link rel="stylesheet" crossorigin href="/assets/vendor-katex-Cp579UoJ.css">
101
101
  </head>
102
102
  <body class="h-full bg-background text-foreground">
package/dist/mobile.html CHANGED
@@ -63,14 +63,14 @@
63
63
  })();
64
64
  </script>
65
65
 
66
- <script type="module" crossorigin src="/assets/mobile-2dXx6cUI.js"></script>
66
+ <script type="module" crossorigin src="/assets/mobile-C-PCxN62.js"></script>
67
67
  <link rel="modulepreload" crossorigin href="/assets/vendor-vite-runtime-DD1OZmLC.js">
68
68
  <link rel="modulepreload" crossorigin href="/assets/vendor-scheduler-7OC5HNn7.js">
69
69
  <link rel="modulepreload" crossorigin href="/assets/vendor-react-DYyjh7Q0.js">
70
70
  <link rel="modulepreload" crossorigin href="/assets/vendor-zustand-CnsBKjP5.js">
71
- <link rel="modulepreload" crossorigin href="/assets/index-Dnby-sDS.js">
71
+ <link rel="modulepreload" crossorigin href="/assets/index-BhXma4dv.js">
72
72
  <link rel="modulepreload" crossorigin href="/assets/vendor-katex-CHD9BdDO.js">
73
- <link rel="stylesheet" crossorigin href="/assets/index-NYG3k04a.css">
73
+ <link rel="stylesheet" crossorigin href="/assets/index-BZXqJcua.css">
74
74
  <link rel="stylesheet" crossorigin href="/assets/vendor-katex-Cp579UoJ.css">
75
75
  </head>
76
76
  <body class="h-full bg-background text-foreground">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi-chamber/web",
3
- "version": "0.1.9",
3
+ "version": "0.2.1",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "repository": {
package/server/index.js CHANGED
@@ -163,7 +163,12 @@ export async function startWebUiServer(options = {}) {
163
163
  await listen(server, port, host);
164
164
  const resolvedPort = typeof server.address() === 'object' && server.address() ? server.address().port : null;
165
165
  if (typeof resolvedPort === 'number') process.send?.({ type: 'pichamber:ready', port: resolvedPort });
166
- await piSessionDaemonRuntime.start().catch((error) => console.warn(`[PiSessionDaemon] unavailable: ${error?.code ?? 'DAEMON_UNAVAILABLE'}`));
166
+ // Warm the detached daemon as soon as HTTP is listening. Requests arriving
167
+ // during cold start share the supervisor's startPromise; server readiness
168
+ // itself never waits for provider/model initialization in the child.
169
+ void piSessionDaemonRuntime.start().catch((error) => {
170
+ console.warn(`[PiSessionDaemon] unavailable: ${error?.code ?? 'DAEMON_UNAVAILABLE'}`);
171
+ });
167
172
  const controller = {
168
173
  expressApp: app,
169
174
  httpServer: server,
@@ -17,6 +17,13 @@ const CHANGELOG_URL = 'https://raw.githubusercontent.com/RyderAsKing/PiChamber/m
17
17
  const GITHUB_RELEASES_URL = 'https://github.com/RyderAsKing/PiChamber/releases';
18
18
  const GITHUB_RELEASES_API_URL = 'https://api.github.com/repos/RyderAsKing/PiChamber/releases';
19
19
  let cachedDetectedPm = null;
20
+ const TRUSTED_UPDATE_REASONS = new Set([
21
+ 'forced-env',
22
+ 'install-path-owner',
23
+ 'global-root-owner',
24
+ 'cached',
25
+ ]);
26
+ const UPDATE_PACKAGE_MANAGERS = new Set(['npm', 'pnpm', 'yarn', 'bun']);
20
27
 
21
28
  function getSpawnSyncBaseOptions() {
22
29
  return process.platform === 'win32' ? { windowsHide: true } : {};
@@ -373,6 +380,21 @@ function packageManagerOwnsCurrentInstall(pm) {
373
380
  return false;
374
381
  }
375
382
 
383
+ function detectionResult(packageManager, reason) {
384
+ return {
385
+ packageManager,
386
+ reason,
387
+ packagePath: getCurrentPackagePath(),
388
+ packageManagerCommand: resolvePackageManagerCommand(packageManager),
389
+ globalNodeModulesRoot: getGlobalNodeModulesRoots(packageManager)[0] || null,
390
+ };
391
+ }
392
+
393
+ function cacheTrustedDetection(packageManager, reason) {
394
+ cachedDetectedPm = packageManager;
395
+ return detectionResult(packageManager, reason);
396
+ }
397
+
376
398
  export function detectPackageManagerDetails() {
377
399
  // In desktop (Electron) runtime, package-manager detection is worthless —
378
400
  // the app ships as a .app bundle, not installed via npm/pnpm/yarn/bun, and
@@ -401,44 +423,23 @@ export function detectPackageManagerDetails() {
401
423
  }
402
424
 
403
425
  const forcedPm = process.env.PICHAMBER_PACKAGE_MANAGER?.trim();
404
- if (forcedPm && ['npm', 'pnpm', 'yarn', 'bun'].includes(forcedPm)) {
426
+ if (forcedPm && UPDATE_PACKAGE_MANAGERS.has(forcedPm)) {
405
427
  const forcedPmCommand = resolvePackageManagerCommand(forcedPm);
406
428
  if (isCommandAvailable(forcedPmCommand)) {
407
- cachedDetectedPm = forcedPm;
408
- return {
409
- packageManager: cachedDetectedPm,
410
- reason: 'forced-env',
411
- packagePath: getCurrentPackagePath(),
412
- packageManagerCommand: forcedPmCommand,
413
- globalNodeModulesRoot: getGlobalNodeModulesRoots(cachedDetectedPm)[0] || null,
414
- };
429
+ return cacheTrustedDetection(forcedPm, 'forced-env');
415
430
  }
416
431
  }
417
432
 
418
433
  // First prefer the package manager that demonstrably owns the current install.
419
434
  const installPathPm = detectPackageManagerFromCurrentInstallPath();
420
435
  if (installPathPm && packageManagerOwnsCurrentInstall(installPathPm)) {
421
- cachedDetectedPm = installPathPm;
422
- return {
423
- packageManager: cachedDetectedPm,
424
- reason: 'install-path-owner',
425
- packagePath: getCurrentPackagePath(),
426
- packageManagerCommand: resolvePackageManagerCommand(cachedDetectedPm),
427
- globalNodeModulesRoot: getGlobalNodeModulesRoots(cachedDetectedPm)[0] || null,
428
- };
436
+ return cacheTrustedDetection(installPathPm, 'install-path-owner');
429
437
  }
430
438
 
431
439
  const ownershipCandidates = ['pnpm', 'yarn', 'bun', 'npm'];
432
440
  for (const candidate of ownershipCandidates) {
433
441
  if (packageManagerOwnsCurrentInstall(candidate)) {
434
- cachedDetectedPm = candidate;
435
- return {
436
- packageManager: cachedDetectedPm,
437
- reason: 'global-root-owner',
438
- packagePath: getCurrentPackagePath(),
439
- packageManagerCommand: resolvePackageManagerCommand(cachedDetectedPm),
440
- globalNodeModulesRoot: getGlobalNodeModulesRoots(cachedDetectedPm)[0] || null,
441
- };
442
+ return cacheTrustedDetection(candidate, 'global-root-owner');
442
443
  }
443
444
  }
444
445
 
@@ -471,29 +472,14 @@ export function detectPackageManagerDetails() {
471
472
 
472
473
  // Validate the hint against package visibility, but only after ownership checks failed.
473
474
  if (hintedPm && isCommandAvailable(resolvePackageManagerCommand(hintedPm)) && isPackageInstalledWith(hintedPm)) {
474
- cachedDetectedPm = hintedPm;
475
- return {
476
- packageManager: cachedDetectedPm,
477
- reason: 'hinted-visible-install',
478
- packagePath: getCurrentPackagePath(),
479
- packageManagerCommand: resolvePackageManagerCommand(cachedDetectedPm),
480
- globalNodeModulesRoot: getGlobalNodeModulesRoots(cachedDetectedPm)[0] || null,
481
- };
475
+ return detectionResult(hintedPm, 'hinted-visible-install');
482
476
  }
483
477
 
484
478
  const runtimePm = detectPackageManagerFromRuntimePath(process.execPath);
485
479
  if (runtimePm && isCommandAvailable(resolvePackageManagerCommand(runtimePm)) && isPackageInstalledWith(runtimePm)) {
486
- cachedDetectedPm = runtimePm;
487
- return {
488
- packageManager: cachedDetectedPm,
489
- reason: 'runtime-visible-install',
490
- packagePath: getCurrentPackagePath(),
491
- packageManagerCommand: resolvePackageManagerCommand(cachedDetectedPm),
492
- globalNodeModulesRoot: getGlobalNodeModulesRoots(cachedDetectedPm)[0] || null,
493
- };
480
+ return detectionResult(runtimePm, 'runtime-visible-install');
494
481
  }
495
482
 
496
- // Last resort: pick a PM that can at least see the package.
497
483
  const pmChecks = [
498
484
  { name: 'pnpm', check: () => isCommandAvailable(resolvePackageManagerCommand('pnpm')) },
499
485
  { name: 'yarn', check: () => isCommandAvailable(resolvePackageManagerCommand('yarn')) },
@@ -502,35 +488,29 @@ export function detectPackageManagerDetails() {
502
488
  ];
503
489
 
504
490
  for (const { name, check } of pmChecks) {
505
- if (check()) {
506
- // Verify this PM actually has the package installed globally
507
- if (isPackageInstalledWith(name)) {
508
- cachedDetectedPm = name;
509
- return {
510
- packageManager: cachedDetectedPm,
511
- reason: 'last-resort-visible-install',
512
- packagePath: getCurrentPackagePath(),
513
- packageManagerCommand: resolvePackageManagerCommand(cachedDetectedPm),
514
- globalNodeModulesRoot: getGlobalNodeModulesRoots(cachedDetectedPm)[0] || null,
515
- };
516
- }
491
+ if (check() && isPackageInstalledWith(name)) {
492
+ return detectionResult(name, 'last-resort-visible-install');
517
493
  }
518
494
  }
519
495
 
520
- cachedDetectedPm = 'npm';
521
- return {
522
- packageManager: cachedDetectedPm,
523
- reason: 'default-fallback',
524
- packagePath: getCurrentPackagePath(),
525
- packageManagerCommand: resolvePackageManagerCommand(cachedDetectedPm),
526
- globalNodeModulesRoot: getGlobalNodeModulesRoots(cachedDetectedPm)[0] || null,
527
- };
496
+ return detectionResult('npm', 'default-fallback');
528
497
  }
529
498
 
530
499
  export function detectPackageManager() {
531
500
  return detectPackageManagerDetails().packageManager;
532
501
  }
533
502
 
503
+ export function resolveTrustedUpdatePackageManager(details = detectPackageManagerDetails()) {
504
+ if (
505
+ details
506
+ && TRUSTED_UPDATE_REASONS.has(details.reason)
507
+ && UPDATE_PACKAGE_MANAGERS.has(details.packageManager)
508
+ ) {
509
+ return details.packageManager;
510
+ }
511
+ return null;
512
+ }
513
+
534
514
  function detectPackageManagerFromInstallPath(pkgPath) {
535
515
  if (!pkgPath) return null;
536
516
  const normalized = pkgPath.replace(/\\/g, '/').toLowerCase();
@@ -547,9 +527,8 @@ function detectPackageManagerFromRuntimePath(runtimePath) {
547
527
  if (normalized.includes('/.bun/bin/bun') || normalized.endsWith('/bun') || normalized.endsWith('/bun.exe')) {
548
528
  return 'bun';
549
529
  }
550
- if (normalized.includes('/pnpm/')) return 'pnpm';
551
- if (normalized.includes('/yarn/')) return 'yarn';
552
- if (normalized.includes('/node') || normalized.endsWith('/node.exe')) return 'npm';
530
+ // `node` is the runtime for npm, pnpm, and yarn global bins. It is not an
531
+ // install owner.
553
532
  return null;
554
533
  }
555
534
 
@@ -11,6 +11,7 @@ const {
11
11
  detectPackageManager,
12
12
  executeUpdate,
13
13
  getCurrentVersion,
14
+ resolveTrustedUpdatePackageManager,
14
15
  } = await import('./package-manager.js');
15
16
 
16
17
  function officialRegistryPackage(latest) {
@@ -366,5 +367,31 @@ describe('CLI update exports', () => {
366
367
  it('exports package-manager helpers used by the update command', () => {
367
368
  expect(typeof detectPackageManager).toBe('function');
368
369
  expect(typeof executeUpdate).toBe('function');
370
+ expect(typeof resolveTrustedUpdatePackageManager).toBe('function');
371
+ });
372
+ });
373
+
374
+ describe('resolveTrustedUpdatePackageManager', () => {
375
+ it('accepts only installs that this process can prove it owns', () => {
376
+ expect(resolveTrustedUpdatePackageManager({
377
+ packageManager: 'pnpm',
378
+ reason: 'install-path-owner',
379
+ })).toBe('pnpm');
380
+ expect(resolveTrustedUpdatePackageManager({
381
+ packageManager: 'bun',
382
+ reason: 'forced-env',
383
+ })).toBe('bun');
384
+ expect(resolveTrustedUpdatePackageManager({
385
+ packageManager: 'npm',
386
+ reason: 'default-fallback',
387
+ })).toBeNull();
388
+ expect(resolveTrustedUpdatePackageManager({
389
+ packageManager: 'npm',
390
+ reason: 'runtime-visible-install',
391
+ })).toBeNull();
392
+ expect(resolveTrustedUpdatePackageManager({
393
+ packageManager: 'pnpm',
394
+ reason: 'last-resort-visible-install',
395
+ })).toBeNull();
369
396
  });
370
397
  });
@@ -181,7 +181,17 @@ const projectSessionDetail = (value) => {
181
181
  });
182
182
  return { message: projected, parts };
183
183
  });
184
- return { session: projectSession(value.session), messages, lastSequence: value.lastSequence };
184
+ const isStreaming = value.isStreaming === true;
185
+ const lifecycle = ['idle', 'busy', 'retry', 'error', 'interrupted'].includes(value.lifecycle)
186
+ ? value.lifecycle
187
+ : (isStreaming ? 'busy' : 'idle');
188
+ return {
189
+ session: projectSession(value.session),
190
+ messages,
191
+ lastSequence: value.lastSequence,
192
+ isStreaming,
193
+ lifecycle,
194
+ };
185
195
  };
186
196
 
187
197
  const projectProviders = (value) => {
@@ -343,6 +353,12 @@ const projectEventFrame = (frame) => {
343
353
  } } };
344
354
  }
345
355
  case 'session.lifecycle': return { ...common, payload: { state: frame.payload.state } };
356
+ case 'session.updated': {
357
+ if (typeof frame.payload.title !== 'string') return null;
358
+ const title = frame.payload.title.trim();
359
+ if (title.length === 0 || title.length > 256) return null;
360
+ return { ...common, payload: { title } };
361
+ }
346
362
  case 'assistant.message.start': return { ...common, payload: { messageId: frame.payload.messageId, role: frame.payload.role, startedAt: frame.payload.startedAt, ...(typeof frame.payload.parentId === 'string' ? { parentId: frame.payload.parentId } : {}), ...(typeof frame.payload.text === 'string' ? { text: frame.payload.text } : {}), ...(frame.payload.model ? { model: frame.payload.model } : {}) } };
347
363
  case 'assistant.message.delta':
348
364
  case 'assistant.thinking.delta': return { ...common, payload: { messageId: frame.payload.messageId, contentIndex: frame.payload.contentIndex, delta: frame.payload.delta, ...(typeof frame.payload.partId === 'string' ? { partId: frame.payload.partId } : {}) } };
@@ -946,6 +962,8 @@ export const registerPiRuntimeRoutes = (app, {
946
962
  session: projectSession(result.session),
947
963
  messages: [],
948
964
  lastSequence: result.lastSequence,
965
+ isStreaming: result.isStreaming === true,
966
+ lifecycle: result.isStreaming === true ? 'busy' : 'idle',
949
967
  });
950
968
  } catch (error) {
951
969
  writeDaemonError(res, error);
@@ -429,6 +429,8 @@ describe('Pi runtime route', () => {
429
429
  },
430
430
  messages: [],
431
431
  lastSequence: 7,
432
+ isStreaming: false,
433
+ lifecycle: 'idle',
432
434
  });
433
435
  });
434
436
 
@@ -465,6 +467,8 @@ describe('Pi runtime route', () => {
465
467
  parts: [{ type: 'text', id: 'entry-1:0', index: 0, text: 'hello' }],
466
468
  }],
467
469
  lastSequence: 9,
470
+ isStreaming: false,
471
+ lifecycle: 'idle',
468
472
  });
469
473
  const promptResponse = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/sessions/pi-session-4/prompt`, {
470
474
  method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sessionId: 'other', text: 'hello' }),
@@ -563,6 +567,38 @@ describe('Pi runtime route', () => {
563
567
  expect(text).not.toContain('/private/socket');
564
568
  });
565
569
 
570
+ it('projects session.updated titles onto the public event stream', async () => {
571
+ const runtime = {
572
+ health: async () => ({ state: 'ready', protocolVersion: 1, capabilities: [] }),
573
+ subscribe: async ({ onEvent }) => {
574
+ onEvent({
575
+ protocolVersion: 1,
576
+ kind: 'event',
577
+ event: 'session.updated',
578
+ sequence: 8,
579
+ payload: { sessionId: 'pi-session-5', directory: '/workspace', title: ' Fix the parser ', endpoint: '/private/socket' },
580
+ });
581
+ return () => {};
582
+ },
583
+ };
584
+ const app = express();
585
+ registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime });
586
+ server = await listen(app);
587
+ const response = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/events?sessionId=pi-session-5&fromSequence=7`);
588
+ const reader = response.body.getReader();
589
+ const first = await reader.read();
590
+ let text = new TextDecoder().decode(first.value);
591
+ while (!text.includes('"session.updated"')) {
592
+ const next = await reader.read();
593
+ if (next.done) break;
594
+ text += new TextDecoder().decode(next.value);
595
+ }
596
+ await reader.cancel();
597
+ expect(text).toContain('"name":"session.updated"');
598
+ expect(text).toContain('"title":"Fix the parser"');
599
+ expect(text).not.toContain('/private/socket');
600
+ });
601
+
566
602
  it('projects Pi usage through the public session and event envelopes', async () => {
567
603
  const sampleUsage = {
568
604
  input: 120, output: 80, cacheRead: 30, cacheWrite: 5, totalTokens: 235,
@@ -7,13 +7,13 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
7
7
  ## Entrypoints
8
8
 
9
9
  - `session-daemon.js`
10
- - `createPiSessionRuntime({ cwd, agentDir })` creates a persistent Pi runtime using the selected server-side cwd and Pi agent directory. It uses Pi's normal settings, credentials, models, sessions, skills, prompts, and context discovery, with native extensions explicitly disabled for the core milestone. Sessions created outside PiChamber (Pi CLI or any other writer of the cwd-scoped JSONL directory) are the same records: `sessions.list`/`open` hydrate from `getEntries()`, and a later prompt must overlay live turns onto that log rather than replace it.
10
+ - `createPiSessionRuntime({ cwd, agentDir })` creates a persistent Pi runtime using the selected server-side cwd and Pi agent directory. It uses Pi's normal settings, credentials, models, sessions, skills, prompts, and context discovery, with native extensions explicitly disabled for the core milestone. Sessions created outside PiChamber (Pi CLI or any other writer of the cwd-scoped JSONL directory) are the same records: `sessions.list`/`open` hydrate from `getEntries()`, then overlay the live `session.messages` / `state.streamingMessage` turn while `isStreaming` is true, including an unpersisted user prompt that has not flushed to JSONL yet. A later prompt must overlay live turns onto that log rather than replace it. An unmatched `toolCall` projects as `running` only while `isStreaming` is authoritative; the same unmatched call in an idle persisted turn projects as a timestamped interruption error instead of malformed `completed` state. `getSession` also reports `isStreaming` and `lifecycle` so a restarted UI can restore the working/tooling state without waiting for the next token.
11
11
  - `createSessionDaemon(options)` starts/stops the authenticated local socket daemon and validates its endpoint and setup inputs.
12
12
  - `daemon-process.js` is the detached private-process entrypoint. It reads the daemon credential from its owner-only sidecar, starts the socket, writes non-secret identity state only after readiness, and removes only its own state on signal shutdown.
13
13
  - `ipc-client.js` is the server-only authenticated request client. It owns JSONL framing and never exposes endpoint or credential values to callers.
14
14
  - `runtime-registry.js` owns active runtime identities and session-local subscriptions. It rebinds the subscription after an SDK session replacement, rejects identity conflicts rather than displacing another runtime, and attempts every tracked disposal even when another disposal fails.
15
- - `session-jsonl.js` validates the cwd-scoped Pi JSONL directory before session discovery. Pi's SDK deliberately skips malformed discovery entries; this boundary maps malformed, missing, and unreadable candidates to stable explicit failures instead of an empty result. Directory names match Pi's SessionManager encoding, including Windows drive letters and Git Bash/MSYS/Cygwin/WSL `/c/...` paths so PiChamber and the Pi CLI share the same JSONL sessions.
16
- - `supervisor.js` resolves server-only overrides, creates the credential, serializes start/reuse/stop through an owner-only lock, validates daemon identity through `runtime.health`, forwards server-owned commands only after that identity check, and starts or stops the detached process. When the parent is Electron, the child is spawned with `ELECTRON_RUN_AS_NODE=1` so packaged Windows/macOS/Linux apps run the daemon as Node instead of a hidden second Electron GUI process.
15
+ - `session-jsonl.js` validates cwd-scoped Pi JSONL before discovery. List, create, and daemon startup require a valid session header per file; they do not read whole transcripts. `sessions.list` uses `listPiSessionJsonlDirectory` (header, first user prompt, latest rename from the file tail). Full-file validation remains on open of a specific session so a malformed body still fails that chat. Pi's SDK list is not the production list path because it scans every line of every log. Directory names match Pi's SessionManager encoding, including Windows drive letters and Git Bash/MSYS/Cygwin/WSL `/c/...` paths so PiChamber and the Pi CLI share the same JSONL sessions.
16
+ - `supervisor.js` resolves server-only overrides, creates the credential, serializes start/reuse/stop through an owner-only lock, validates daemon identity through `runtime.health`, forwards server-owned commands only after that identity check, and starts or stops the detached process. Reuse requires the ready-state sidecar `entrypoint` to match this checkout's `daemon-process.js`; a healthy daemon from another install (or an older daemon that never recorded an entrypoint) is stopped and replaced so local `bun run dev` cannot keep answering `getSession` without the live-turn overlay. When the parent is Electron, the child is spawned with `ELECTRON_RUN_AS_NODE=1` so packaged Windows/macOS/Linux apps run the daemon as Node instead of a hidden second Electron GUI process.
17
17
  - `../routes.js` registers authenticated public adapters before the generic proxy. It exposes only whitelisted runtime, project, session, provider-auth/configuration, settings, resource, and SSE event shapes; no browser response contains daemon paths, credentials, PIDs, headers, or socket framing. Session actions are path-selected, so an identity supplied in a request body cannot redirect a mutation. `archive-store.js` persists PiChamber-only opaque session archive metadata atomically beneath the PiChamber data root and never edits Pi JSONL. `settings-store.js` keeps PiChamber new-session defaults separate from Pi settings.json. `GET /api/pi/settings` copies leftover UI/desktop `defaultModel` / small / walkthrough strings into that sidecar when those sidecar fields are unset, then Sessions settings is the only editor. Sidecar `defaultThinkingByModel` is the per-model thinking map (`provider/model` keys). A stored global `defaultThinking` with a default model is copied onto that map key and dropped; global thinking without a default model remains a clamp-only fallback. `ui-settings-store.js` atomically owns shared PiChamber UI preferences at the data-root `settings.json`; it is exposed as `/api/pi/ui-settings`, not through removed `/api/config/*` aliases. `session-folders-store.js` validates and atomically persists the restored sidebar's folder snapshot at `/api/pi/session-folders`; a missing snapshot is distinct from an empty one. `custom-themes.js` serves validated custom-theme candidates from `/api/pi/themes` with per-file partial-failure isolation. `model-config-store.js` atomically updates Pi's credential-blind `models.json`; literal keys continue through Pi auth and headers are write-only. `providers.config.get` returns `config: null` for a provider that is not in `models.json` (built-in catalog entries) and fails only when that file is present but malformed.
18
18
  - `*.test.js` uses temporary cwd, agent, data, and runtime directories; it never loads a developer's Pi home, credentials, or sessions. On Windows the private endpoint is a named pipe, not a `.sock` file, and POSIX mode-bit assertions are skipped.
19
19
 
@@ -21,17 +21,18 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
21
21
 
22
22
  - The endpoint is a Unix domain socket on POSIX or a Windows named pipe. TCP endpoints are rejected. Listeners and clients connect with IPC `path` options so Windows `\\.\pipe\pichamber-pi-session-daemon-<owner-key>` works the same as a POSIX socket path.
23
23
  - POSIX socket parent directories are mode `0700`; the socket is created mode `0600`. An existing endpoint fails startup rather than being unlinked without daemon-identity verification. Windows named-pipe ACLs are not yet equivalent owner-only OS permissions; credential authentication remains mandatory.
24
- - The daemon credential and non-secret state sidecars are mode `0600`; their PiChamber parent directory and the operation lock serialize start/reuse/stop. Exclusive lock create writes the owner pid in the same step. A leftover empty or malformed lock, a dead owner pid, or Windows `EPERM`/`EACCES` on exclusive create is retried and stolen after a short freshness window instead of failing as `DAEMON_LOCK_UNAVAILABLE`. Sidecar `chmod` failures on Windows are ignored after the file exists so readiness is still recorded. Health identity includes the daemon PID and must match the state sidecar before the supervisor reuses or signals a process.
24
+ - The daemon credential and non-secret state sidecars are mode `0600`; their PiChamber parent directory and the operation lock serialize start/reuse/stop. Exclusive lock create writes the owner pid in the same step. A leftover empty or malformed lock, a dead owner pid, or Windows `EPERM`/`EACCES` on exclusive create is retried and stolen after a short freshness window instead of failing as `DAEMON_LOCK_UNAVAILABLE`. Sidecar `chmod` failures on Windows are ignored after the file exists so readiness is still recorded. Health identity includes the daemon PID and must match the state sidecar before the supervisor reuses or signals a process. Reuse also requires the ready-state `entrypoint` to equal this host's `daemon-process.js`; a missing or different path is not identity-compatible and is replaced.
25
25
  - 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`.
26
26
  - 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.
27
27
  - Frames are LF-delimited JSON. They have a 1 MiB maximum buffered size. A malformed, oversized, unauthenticated, or invalid request closes the connection.
28
- - 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.delete`, 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. 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; extensions remain disabled regardless of trust. 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` revalidates the selected cwd's JSONL directory before SDK discovery and returns no JSONL paths. 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. 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. The daemon maps Pi message lifecycle, deltas, tools, queue changes, model/thinking, compaction, and interruption state to canonical events. Tool events carry redacted input arguments, cumulative partial-output snapshots, final output, error text, renderer metadata (edit diffs, truncation notes), and start/end timestamps. 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 remain attached to the latest user turn. 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.
28
+ - 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.delete`, 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. 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; extensions remain disabled regardless of trust. 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` resolves an id by Pi's `timestamp_<id>.jsonl` filename first so a missing deep link 404s without listing or fully reading every transcript in every cwd; SDK list and header scan remain the fallback for non-standard names. 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. 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. Tool events carry redacted input arguments, cumulative partial-output snapshots, final output, error text, renderer metadata (edit diffs, truncation notes), and start/end timestamps. 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 remain attached to the latest user turn. 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.
29
29
  - 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.
30
30
  - 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`. A later prompt on the same session invalidates that 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 completion is never held behind the 30-second public/private request budgets.
31
31
  - Registry keys combine the SDK session ID with its cwd. A replacement subscription is rebound to the replacement session so old-session events cannot be published under the new identity. A collision is a visible error; it never replaces or disposes an unrelated runtime.
32
32
  - After `agent_settled`, the daemon disposes an idle runtime after five minutes (injectable for tests). Disposal never deletes Pi JSONL; the daemon remembers the selected session file and recreates that runtime on the next private prompt. A new agent start cancels a pending disposal.
33
33
  - A startup validation failure writes only a stable failure code to the owner-only non-secret state sidecar. It never records a transcript, session path, or credential. The supervisor surfaces that code as unavailable instead of claiming an empty or idle session.
34
34
  - After a forced crash, the next health, request, or subscription probe re-runs supervised startup. Daemon readiness has its own 15-second bounded budget, separate from the shorter lock and shutdown budget, because loading Pi settings and provider/model catalogs can legitimately exceed five seconds. The supervisor removes an existing POSIX socket only when its recorded daemon PID is dead, the endpoint is a socket, and authenticated IPC deterministically refuses or times out. An endpoint that responds, authenticates incorrectly, returns malformed protocol data, or cannot be classified remains `DAEMON_ENDPOINT_UNVERIFIED`.
35
+ - The web server starts warming the supervisor immediately after HTTP listen without awaiting Pi provider/model initialization. A first request arriving during that warmup shares the supervisor's `startPromise`.
35
36
  - The daemon owns the runtime after clients disconnect. Disconnecting the web-server client cannot stop active Pi work.
36
37
 
37
38
  ## Deliberate limits
@@ -1,8 +1,10 @@
1
1
  import { readFile, chmod, rename, rm, writeFile } from 'node:fs/promises';
2
- import { dirname } from 'node:path';
2
+ import { fileURLToPath } from 'node:url';
3
3
 
4
4
  import { createSessionDaemon } from './session-daemon.js';
5
5
 
6
+ const DAEMON_ENTRYPOINT = fileURLToPath(import.meta.url);
7
+
6
8
  const argument = (name) => {
7
9
  const index = process.argv.indexOf(name);
8
10
  return index === -1 ? undefined : process.argv[index + 1];
@@ -41,6 +43,7 @@ const writeReadyState = () => writeState({
41
43
  protocolVersion: 1,
42
44
  pid: process.pid,
43
45
  endpoint,
46
+ entrypoint: DAEMON_ENTRYPOINT,
44
47
  startedAt: new Date().toISOString(),
45
48
  });
46
49