@pi-chamber/web 0.9.0 → 0.9.3

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 (106) hide show
  1. package/README.md +24 -8
  2. package/bin/cli.js +11 -1
  3. package/bin/cli.test.js +18 -0
  4. package/bin/lib/DOCUMENTATION.md +3 -3
  5. package/bin/lib/cli-args.js +7 -3
  6. package/bin/lib/cli-lifecycle.js +3 -0
  7. package/bin/lib/cli-paths.js +28 -6
  8. package/bin/lib/cli-process.js +1 -0
  9. package/bin/lib/cli-tunnel-profiles.js +15 -10
  10. package/bin/lib/commands-connect-url.js +9 -1
  11. package/bin/lib/commands-logs.js +22 -4
  12. package/bin/lib/commands-serve.js +10 -2
  13. package/bin/lib/commands-tunnel.js +14 -0
  14. package/bin/lib/commands-update.js +18 -14
  15. package/bin/lib/commands-update.test.js +2 -1
  16. package/dist/assets/{DiagramEditor-CcbnMl1H.js → DiagramEditor-DuGmiPZ5.js} +1 -1
  17. package/dist/assets/{DiagramView-DTW5jwK3.js → DiagramView-CV-iReyY.js} +1 -1
  18. package/dist/assets/{DiffView-CZyHHAOB.js → DiffView-DVd1MLPB.js} +6 -6
  19. package/dist/assets/{FilesView-BJYLFR3H.js → FilesView-CPnW4I90.js} +1 -1
  20. package/dist/assets/{GitView-Cg_5UU7E.js → GitView-Dj_7hgX_.js} +3 -3
  21. package/dist/assets/JsonTreeView-Cyy0lEZR.js +1 -0
  22. package/dist/assets/{MarkdownRendererImpl-WqBwxlso.js → MarkdownRendererImpl-BXN78Wu_.js} +1 -1
  23. package/dist/assets/{PatchDiff-BRi23N1l.js → PatchDiff-C7dA3U29.js} +1 -1
  24. package/dist/assets/{SessionSwitcherContent-7VAU5pwZ.js → SessionSwitcherContent-dr3g9DR7.js} +1 -1
  25. package/dist/assets/{SessionSwitcherDropdown-BslRtccE.js → SessionSwitcherDropdown-C3zdd82V.js} +2 -2
  26. package/dist/assets/{SessionUnreadDot-1nV0Z2ZA.js → SessionUnreadDot-qeik5qtT.js} +1 -1
  27. package/dist/assets/SettingsView-C57uV1YS.js +2 -0
  28. package/dist/assets/{SettingsWindow-D4jZHl8X.js → SettingsWindow-Bbay2W76.js} +1 -1
  29. package/dist/assets/ToolOutputDialog-CRTiN1CH.js +8 -0
  30. package/dist/assets/{ToolPartDiffPreview-9FLv2fWD.js → ToolPartDiffPreview-CqnNcLPk.js} +1 -1
  31. package/dist/assets/{VirtualizedFileDiff-ywmPBXAG.js → VirtualizedFileDiff-iqwryMNU.js} +3 -3
  32. package/dist/assets/{collapsible-6mCYf7Ky.js → collapsible-szfZ0Syc.js} +1 -1
  33. package/dist/assets/computeVirtualFileMetrics-Bbugxxtp.js +3 -0
  34. package/dist/assets/{contextFileOpenGuard-CKyf-TZ7.js → contextFileOpenGuard-BC3ie230.js} +1 -1
  35. package/dist/assets/{gitStatusPredicates-UsytDMy_.js → gitStatusPredicates-DbThKVSf.js} +1 -1
  36. package/dist/assets/{index-C8NYcA8-.css → index-DNoEeZ2U.css} +1 -1
  37. package/dist/assets/{index-yWgKW2Fx.js → index-KIdiBFJs.js} +4 -4
  38. package/dist/assets/{index-D1IaU-Q7.js → index-v6K3L94m.js} +1 -1
  39. package/dist/assets/{isDiffPlainText-DPCilEx_.js → isDiffPlainText-Dl0RBjPZ.js} +1 -1
  40. package/dist/assets/{isFilePlainText-XdCAgm8R.js → isFilePlainText-CbrmvrM6.js} +1 -1
  41. package/dist/assets/{main-DcAMXRSi.js → main-4PkIvzf4.js} +7 -7
  42. package/dist/assets/{main-DhvLreEl.js → main-DMyWi0qs.js} +2 -2
  43. package/dist/assets/{markdownCore-BF0Dqwm4.js → markdownCore-BD5WkOKU.js} +1 -1
  44. package/dist/assets/{miniChat-DsCx0dsW.js → miniChat-CLMNhna4.js} +2 -2
  45. package/dist/assets/{mobile-C-IN49xX.js → mobile-rWMDwhtQ.js} +2 -2
  46. package/dist/assets/renderElectronMiniChatApp-BRhGNRJ8.js +2 -0
  47. package/dist/assets/{renderMobileApp-xCdVzvyf.js → renderMobileApp-DLy2YoQg.js} +3 -3
  48. package/dist/assets/{runtimeEndpointReset-CT3WShpj.js → runtimeEndpointReset-Z9YtcHxZ.js} +15 -15
  49. package/dist/assets/{runtimeSurface-C_3mcJ01.js → runtimeSurface-CySRuLbN.js} +1 -1
  50. package/dist/assets/{useAppFontEffects-BgK55NDM.js → useAppFontEffects-DfuJVB15.js} +102 -102
  51. package/dist/assets/{useFilesViewSearch-CWx24PZg.js → useFilesViewSearch-BZBHrZ90.js} +1 -1
  52. package/dist/assets/usePushVisibilityBeacon-BxTkEajM.js +10 -0
  53. package/dist/assets/{useSwitcherItems-CrS-F6DY.js → useSwitcherItems-jITqE8PV.js} +1 -1
  54. package/dist/assets/{vendor-codemirror-language-data-BzeePAPn.js → vendor-codemirror-language-data-CDdfwzlS.js} +2 -2
  55. package/dist/assets/{web-components-DAkBDXRk.js → web-components-C9wXMuCp.js} +2 -2
  56. package/dist/index.html +4 -4
  57. package/dist/mini-chat.html +3 -3
  58. package/dist/mobile.html +3 -3
  59. package/package.json +3 -3
  60. package/server/index.js +26 -7
  61. package/server/lib/client-auth/pairing.js +13 -2
  62. package/server/lib/client-auth/remote-clients.js +13 -2
  63. package/server/lib/fs/DOCUMENTATION.md +3 -1
  64. package/server/lib/fs/routes.test.js +74 -0
  65. package/server/lib/git/DOCUMENTATION.md +1 -1
  66. package/server/lib/git/identity-storage.js +10 -1
  67. package/server/lib/package-manager.js +1 -1
  68. package/server/lib/package-manager.test.js +11 -0
  69. package/server/lib/pi/archive-store.js +3 -2
  70. package/server/lib/pi/model-config-store.js +6 -2
  71. package/server/lib/pi/routes.js +46 -3
  72. package/server/lib/pi/routes.test.js +53 -0
  73. package/server/lib/pi/session-daemon/DOCUMENTATION.md +15 -9
  74. package/server/lib/pi/session-daemon/daemon-process.js +48 -13
  75. package/server/lib/pi/session-daemon/ipc-client.js +20 -9
  76. package/server/lib/pi/session-daemon/ipc-client.test.js +88 -0
  77. package/server/lib/pi/session-daemon/ipc-protocol.js +9 -0
  78. package/server/lib/pi/session-daemon/session-daemon.js +353 -66
  79. package/server/lib/pi/session-daemon/session-daemon.test.js +348 -0
  80. package/server/lib/pi/session-daemon/session-lease.js +151 -0
  81. package/server/lib/pi/session-daemon/session-lease.test.js +108 -0
  82. package/server/lib/pi/session-daemon/supervisor.js +244 -54
  83. package/server/lib/pi/session-daemon/supervisor.test.js +202 -6
  84. package/server/lib/pi/session-folders-store.js +20 -2
  85. package/server/lib/pi/session-folders-store.test.js +17 -0
  86. package/server/lib/pi/settings-store.js +3 -2
  87. package/server/lib/pi/snippets-store.js +4 -1
  88. package/server/lib/pi/ui-settings-store.js +130 -24
  89. package/server/lib/pi/ui-settings-store.test.js +58 -7
  90. package/server/lib/server/cross-process-lock.js +112 -0
  91. package/server/lib/server/cross-process-lock.test.js +70 -0
  92. package/server/lib/server/server-profile.js +110 -0
  93. package/server/lib/server/server-profile.test.js +58 -0
  94. package/server/lib/server/tunnel-service.DOCUMENTATION.md +7 -8
  95. package/server/lib/server/tunnel-service.js +8 -1
  96. package/server/lib/stt/config-store.js +3 -2
  97. package/server/lib/terminal/DOCUMENTATION.md +1 -1
  98. package/server/lib/tunnels/DOCUMENTATION.md +38 -18
  99. package/server/lib/ui-auth/ui-auth.js +9 -2
  100. package/server/lib/ui-auth/ui-passkeys.js +9 -1
  101. package/dist/assets/JsonTreeView-GTdKGEdy.js +0 -1
  102. package/dist/assets/SettingsView-UIaAyjTo.js +0 -2
  103. package/dist/assets/ToolOutputDialog-BoeJONiR.js +0 -8
  104. package/dist/assets/computeVirtualFileMetrics-3H6mg13G.js +0 -3
  105. package/dist/assets/renderElectronMiniChatApp-C13HXGZL.js +0 -2
  106. package/dist/assets/usePushVisibilityBeacon-swMQLm-i.js +0 -10
package/server/index.js CHANGED
@@ -48,10 +48,10 @@ let signalsAttached = false;
48
48
 
49
49
  const isEnvFlagEnabled = (value) => value === true || value === 1 || (typeof value === 'string' && ['1', 'true'].includes(value.trim().toLowerCase()));
50
50
 
51
- // Serve-time tunnel startup was removed with the OpenChamber migration; the
52
- // standalone `pichamber tunnel` command still manages cloudflared. Options
53
- // parsed for the removed integration must fail loudly instead of being
54
- // silently ignored — a user passing --tunnel expects an exposed URL.
51
+ // Serve-time tunnel startup is intentionally separate from server startup; the
52
+ // standalone `pichamber tunnel` command manages cloudflared. Options parsed for
53
+ // the unsupported serve integration must fail loudly instead of being silently
54
+ // ignored. A user passing --tunnel expects an exposed URL.
55
55
  const IGNORED_TUNNEL_OPTION_NAMES = ['tryCfTunnel', 'tunnelProvider', 'tunnelMode', 'tunnelConfigPath', 'tunnelToken', 'tunnelHostname'];
56
56
  const warnIgnoredTunnelOptions = (options) => {
57
57
  const ignored = IGNORED_TUNNEL_OPTION_NAMES.filter((name) => options[name] !== undefined && options[name] !== false && options[name] !== null && options[name] !== '');
@@ -126,7 +126,10 @@ export async function startWebUiServer(options = {}) {
126
126
  const clientPairingRuntime = createClientPairingRuntime({ fsPromises: fs.promises, path, crypto: await import('node:crypto'), storePath: dataPath('client-pairing-sessions.json'), remoteClientAuthRuntime });
127
127
  const tunnelAuthController = createTunnelAuth();
128
128
  const uiAuthController = createUiAuth({ password: uiPassword, readSettingsFromDiskMigrated: async () => ({}) , clientAuthController: remoteClientAuthRuntime });
129
- const piSessionDaemonRuntime = createPiSessionDaemonSupervisor({ dataDir: PICHAMBER_DATA_DIR });
129
+ // One daemon per server profile. The supervisor is created after HTTP
130
+ // listen so the profile key uses the bound port; routes observe it through
131
+ // the getter and report unavailable until it exists.
132
+ let piSessionDaemonRuntime = null;
130
133
  const tunnelService = createTunnelService({
131
134
  dataDir: PICHAMBER_DATA_DIR,
132
135
  getPort: () => {
@@ -217,7 +220,18 @@ export async function startWebUiServer(options = {}) {
217
220
 
218
221
  await listen(server, port, host);
219
222
  const resolvedPort = typeof server.address() === 'object' && server.address() ? server.address().port : null;
220
- if (typeof resolvedPort === 'number') process.send?.({ type: 'pichamber:ready', port: resolvedPort });
223
+ piSessionDaemonRuntime = createPiSessionDaemonSupervisor({
224
+ dataDir: PICHAMBER_DATA_DIR,
225
+ port: typeof resolvedPort === 'number' ? resolvedPort : port,
226
+ version: PICHAMBER_VERSION,
227
+ });
228
+ if (typeof resolvedPort === 'number') {
229
+ process.send?.({
230
+ type: 'pichamber:ready',
231
+ port: resolvedPort,
232
+ profileKey: piSessionDaemonRuntime.paths.profileKey,
233
+ });
234
+ }
221
235
  // Warm the detached daemon as soon as HTTP is listening. Requests arriving
222
236
  // during cold start share the supervisor's startPromise; server readiness
223
237
  // itself never waits for provider/model initialization in the child.
@@ -232,13 +246,18 @@ export async function startWebUiServer(options = {}) {
232
246
  return typeof address === 'object' && address ? address.port : null;
233
247
  },
234
248
  getTunnelUrl: () => null,
249
+ getDaemonProfileKey: () => piSessionDaemonRuntime?.paths?.profileKey ?? null,
235
250
  getQuitRiskStatus: () => ({ tunnel: { active: false } }),
236
251
  isReady: () => !stopped,
237
252
  stop: async ({ exitProcess = false } = {}) => {
238
253
  if (stopped) return;
239
254
  stopped = true;
240
255
  if (activeController === controller) activeController = null;
241
- await Promise.allSettled([workspaceRuntime.shutdown(), piSessionDaemonRuntime.stop(), close(server)]);
256
+ await Promise.allSettled([
257
+ workspaceRuntime.shutdown(),
258
+ piSessionDaemonRuntime ? piSessionDaemonRuntime.stop() : Promise.resolve(),
259
+ close(server),
260
+ ]);
242
261
  uiAuthController.dispose?.();
243
262
  if (exitProcess) process.exit(0);
244
263
  },
@@ -1,3 +1,5 @@
1
+ import { withCrossProcessLock } from '../server/cross-process-lock.js';
2
+
1
3
  const STORE_VERSION = 1;
2
4
  const PAIRING_ID_PREFIX = 'pair_';
3
5
  const SECRET_BYTES = 32;
@@ -114,7 +116,9 @@ export const createClientPairingRuntime = ({
114
116
  });
115
117
  await previous;
116
118
  try {
117
- return await fn();
119
+ // The queue orders one server; the file lock orders every server
120
+ // sharing this data directory.
121
+ return await withCrossProcessLock(`${storePath}.lock`, fn);
118
122
  } finally {
119
123
  release();
120
124
  }
@@ -155,7 +159,14 @@ export const createClientPairingRuntime = ({
155
159
 
156
160
  const writeStore = async (store) => {
157
161
  await fsPromises.mkdir(path.dirname(storePath), { recursive: true, mode: 0o700 });
158
- await fsPromises.writeFile(storePath, JSON.stringify(normalizeStore(store), null, 2), { mode: 0o600 });
162
+ const temporary = `${storePath}.tmp-${process.pid}-${crypto.randomBytes(8).toString('hex')}`;
163
+ try {
164
+ await fsPromises.writeFile(temporary, JSON.stringify(normalizeStore(store), null, 2), { mode: 0o600 });
165
+ await fsPromises.rename(temporary, storePath);
166
+ } catch (error) {
167
+ await fsPromises.rm?.(temporary, { force: true }).catch(() => {});
168
+ throw error;
169
+ }
159
170
  if (typeof fsPromises.chmod === 'function') {
160
171
  await fsPromises.chmod(storePath, 0o600).catch(() => {});
161
172
  }
@@ -1,3 +1,5 @@
1
+ import { withCrossProcessLock } from '../server/cross-process-lock.js';
2
+
1
3
  const STORE_VERSION = 1;
2
4
  const TOKEN_PREFIX = 'oc_client_';
3
5
  const TOKEN_BYTES = 32;
@@ -65,7 +67,9 @@ export const createRemoteClientAuthRuntime = ({ fsPromises, path, crypto, storeP
65
67
  });
66
68
  await previous;
67
69
  try {
68
- return await fn();
70
+ // The queue orders one server; the file lock orders every server
71
+ // sharing this data directory.
72
+ return await withCrossProcessLock(`${storePath}.lock`, fn);
69
73
  } finally {
70
74
  release();
71
75
  }
@@ -106,7 +110,14 @@ export const createRemoteClientAuthRuntime = ({ fsPromises, path, crypto, storeP
106
110
 
107
111
  const writeStore = async (store) => {
108
112
  await fsPromises.mkdir(path.dirname(storePath), { recursive: true, mode: 0o700 });
109
- await fsPromises.writeFile(storePath, JSON.stringify(normalizeStore(store), null, 2), { mode: 0o600 });
113
+ const temporary = `${storePath}.tmp-${process.pid}-${crypto.randomBytes(8).toString('hex')}`;
114
+ try {
115
+ await fsPromises.writeFile(temporary, JSON.stringify(normalizeStore(store), null, 2), { mode: 0o600 });
116
+ await fsPromises.rename(temporary, storePath);
117
+ } catch (error) {
118
+ await fsPromises.rm?.(temporary, { force: true }).catch(() => {});
119
+ throw error;
120
+ }
110
121
  if (typeof fsPromises.chmod === 'function') {
111
122
  await fsPromises.chmod(storePath, 0o600).catch(() => {});
112
123
  }
@@ -12,6 +12,7 @@ Own filesystem API behavior for the web server runtime, including workspace-boun
12
12
  - Registers all filesystem routes:
13
13
  - `GET /api/fs/home`
14
14
  - `POST /api/fs/mkdir`
15
+ - `POST /api/fs/clone`
15
16
  - `GET /api/fs/read`
16
17
  - `GET /api/fs/raw`
17
18
  - `GET /api/fs/serve/:path(*)`
@@ -36,4 +37,5 @@ Own filesystem API behavior for the web server runtime, including workspace-boun
36
37
  - Keep filesystem policy (workspace root checks, error mapping, exec timeout behavior) inside this module, not in the composition root.
37
38
  - Filesystem `EPERM`/`EACCES` failures use the stable `reason: "os-permission"` response marker. Policy denials such as workspace-boundary or missing-grant failures must not use that marker because a native folder picker cannot remediate them.
38
39
  - If adding new `/api/fs/*` endpoints, add them in `routes.js` and extend this document.
39
- - `GET /api/fs/list` may resolve symlinks with `realpath` to read directory contents, but the response `path` and each entry `path` must stay in the caller's requested path space (`path.join(requestedPath, name)`). Returning real paths breaks file-tree expansion for directories reached through workspace symlinks.
40
+ - `POST /api/fs/clone` clones a repository into the requested destination and can apply a stored Git identity. It returns the cloned path and rejects an existing destination with HTTP 409.
41
+ - `GET /api/fs/list` may resolve symlinks with `realpath` to read directory contents, but the response `path` and each entry `path` must stay in the caller’s requested path space (`path.join(requestedPath, name)`). Returning real paths breaks file-tree expansion for directories reached through workspace symlinks.
@@ -200,6 +200,26 @@ const registerMkdir = (fsPromises) => {
200
200
  return getRoute('POST', '/api/fs/mkdir');
201
201
  };
202
202
 
203
+ const registerClone = ({ fsPromises, spawn }) => {
204
+ const { app, getRoute } = createRouteRegistry();
205
+ registerFsRoutes(app, {
206
+ os: { homedir: () => '/home/user' },
207
+ path: path.posix,
208
+ fsPromises: {
209
+ realpath: async (targetPath) => targetPath,
210
+ ...fsPromises,
211
+ },
212
+ spawn,
213
+ crypto: { randomUUID: () => 'job-0' },
214
+ normalizeDirectoryPath: (p) => p,
215
+ resolveProjectDirectory: async () => ({ directory: '/repo' }),
216
+ buildAugmentedPath: () => '/usr/bin',
217
+ resolveGitBinaryForSpawn: () => 'git',
218
+ pichamberUserConfigRoot: '/home/user/.config',
219
+ });
220
+ return getRoute('POST', '/api/fs/clone');
221
+ };
222
+
203
223
  const registerReveal = ({ fsPromises, spawn, platform = 'linux' }) => {
204
224
  const { app, getRoute } = createRouteRegistry();
205
225
  registerFsRoutes(app, {
@@ -251,6 +271,12 @@ const callMkdir = async (handler, body) => {
251
271
  return res;
252
272
  };
253
273
 
274
+ const callClone = async (handler, body) => {
275
+ const res = createMockResponse();
276
+ await handler({ body }, res);
277
+ return res;
278
+ };
279
+
254
280
  const callReveal = async (handler, body) => {
255
281
  const res = createMockResponse();
256
282
  await handler({ body }, res);
@@ -458,6 +484,54 @@ describe('fs read', () => {
458
484
  });
459
485
  });
460
486
 
487
+ describe('fs clone', () => {
488
+ it('clones into a new destination through the registered route', async () => {
489
+ const notFound = () => Promise.reject(Object.assign(new Error('not found'), { code: 'ENOENT' }));
490
+ const fsPromises = {
491
+ stat: vi.fn(notFound),
492
+ access: vi.fn(notFound),
493
+ mkdir: vi.fn(async () => undefined),
494
+ };
495
+ const { spawn } = createSpawn();
496
+ const handler = registerClone({ fsPromises, spawn });
497
+
498
+ const res = await callClone(handler, {
499
+ remoteUrl: 'https://github.com/example/repository.git',
500
+ destinationPath: '/home/user/projects/repository',
501
+ });
502
+
503
+ expect(res.statusCode).toBe(200);
504
+ expect(res.body).toEqual({
505
+ success: true,
506
+ path: '/home/user/projects/repository',
507
+ output: '',
508
+ });
509
+ expect(fsPromises.mkdir).toHaveBeenCalledWith('/home/user/projects', { recursive: true });
510
+ expect(spawn).toHaveBeenCalledWith(
511
+ 'git',
512
+ ['clone', '--', 'https://github.com/example/repository.git', 'repository'],
513
+ expect.objectContaining({
514
+ cwd: '/home/user/projects',
515
+ env: expect.objectContaining({ GIT_TERMINAL_PROMPT: '0' }),
516
+ }),
517
+ );
518
+ });
519
+
520
+ it('rejects a clone request without a repository URL', async () => {
521
+ const { spawn } = createSpawn();
522
+ const handler = registerClone({
523
+ fsPromises: { stat: vi.fn(), access: vi.fn(), mkdir: vi.fn() },
524
+ spawn,
525
+ });
526
+
527
+ const res = await callClone(handler, { destinationPath: '/home/user/projects/repository' });
528
+
529
+ expect(res.statusCode).toBe(400);
530
+ expect(res.body).toEqual({ error: 'Repository URL is required' });
531
+ expect(spawn).not.toHaveBeenCalled();
532
+ });
533
+ });
534
+
461
535
  describe('fs reveal', () => {
462
536
  it.each([
463
537
  ['linux', 'xdg-open', ['/repo']],
@@ -125,7 +125,7 @@ The following functions are internal helpers used by exported functions:
125
125
  Authenticated `GET /api/git/worktrees`, `POST /api/git/worktrees/validate`, `POST /api/git/worktrees`, `DELETE /api/git/worktrees`, and `GET /api/git/worktrees/bootstrap-status` expose worktree discovery and lifecycle operations to the shared web runtime. Electron, hosted mobile, and Capacitor clients use the same server implementation. The delete route requires a registered non-primary worktree and only forces removal when the caller explicitly sends `force: true`; the shared UI obtains confirmation for dirty files and refuses removal while a session is active. The user-facing route never deletes local branches, so unpushed commits remain recoverable.
126
126
 
127
127
  ### Runtime availability of range diffs
128
- - `GET /api/git/range-diff` is served by the PiChamber web server, so it is available to web, desktop, and mobile clients. The shared `GitAPI.getGitRangeDiff` is therefore optional: web supplies the HTTP implementation, and VS Code does not implement it because the extension host serves Git through its own bridge rather than these routes. Features built on range diffs (currently the AI diff walkthrough) are not offered in VS Code.
128
+ - `GET /api/git/range-diff` is served by the PiChamber web server, so it is available to web, desktop, hosted mobile, and Capacitor clients. The shared `GitAPI.getGitRangeDiff` is optional because the web runtime supplies the HTTP implementation.
129
129
 
130
130
  ### Staged and unstaged change handling
131
131
  - `status.files` exposes both `index` and `working_dir` codes. Shared UI uses these as separate scopes: staged rows are derived from non-empty `index` statuses, while unstaged rows are derived from `working_dir` statuses and untracked files.
@@ -33,7 +33,16 @@ export function saveProfiles(data) {
33
33
  ensureStorageDir();
34
34
 
35
35
  try {
36
- fs.writeFileSync(STORAGE_FILE, JSON.stringify(data, null, 2), 'utf8');
36
+ // Atomic replace so a concurrent server never reads a torn file. Identity
37
+ // edits remain last-writer-wins across servers.
38
+ const temporary = `${STORAGE_FILE}.tmp-${process.pid}-${Date.now()}`;
39
+ try {
40
+ fs.writeFileSync(temporary, JSON.stringify(data, null, 2), 'utf8');
41
+ fs.renameSync(temporary, STORAGE_FILE);
42
+ } catch (error) {
43
+ try { fs.rmSync(temporary, { force: true }); } catch {}
44
+ throw error;
45
+ }
37
46
  return true;
38
47
  } catch (error) {
39
48
  console.error('Failed to save git identity profiles:', error);
@@ -814,7 +814,7 @@ export function executeUpdate(pm = detectPackageManager(), options = {}) {
814
814
  }
815
815
 
816
816
  const result = spawnSync(command, {
817
- stdio: 'inherit',
817
+ stdio: options?.silent === true ? 'ignore' : 'inherit',
818
818
  shell: true,
819
819
  ...getSpawnSyncBaseOptions(),
820
820
  });
@@ -390,6 +390,17 @@ describe('CLI update exports', () => {
390
390
  expect(typeof executeUpdate).toBe('function');
391
391
  expect(typeof resolveTrustedUpdatePackageManager).toBe('function');
392
392
  });
393
+
394
+ it('does not inherit package-manager output in silent mode', async () => {
395
+ const { spawnSync } = await import('node:child_process');
396
+ spawnSync.mockClear();
397
+
398
+ expect(executeUpdate('npm', { silent: true })).toEqual({ success: true, exitCode: 0 });
399
+ expect(spawnSync).toHaveBeenLastCalledWith(
400
+ expect.stringContaining('@pi-chamber/web@latest'),
401
+ expect.objectContaining({ shell: true, stdio: 'ignore' }),
402
+ );
403
+ });
393
404
  });
394
405
 
395
406
  describe('resolveTrustedUpdatePackageManager', () => {
@@ -2,6 +2,7 @@ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
2
2
  import { dirname, join } from 'node:path';
3
3
 
4
4
  import { resolvePiChamberDataDir } from '../pichamber-data-dir.js';
5
+ import { withCrossProcessLock } from '../server/cross-process-lock.js';
5
6
 
6
7
  const invalidArchive = () => {
7
8
  const error = new Error('Pi archive metadata is invalid.');
@@ -34,7 +35,7 @@ export const createPiArchiveStore = ({ file = join(resolvePiChamberDataDir(), 'p
34
35
  error.code = 'INVALID_ARGUMENT';
35
36
  throw error;
36
37
  }
37
- const operation = writeChain.then(async () => {
38
+ const operation = writeChain.then(() => withCrossProcessLock(`${file}.lock`, async () => {
38
39
  const current = await read();
39
40
  if (archived) current[sessionId] = Date.now();
40
41
  else delete current[sessionId];
@@ -43,7 +44,7 @@ export const createPiArchiveStore = ({ file = join(resolvePiChamberDataDir(), 'p
43
44
  await writeFile(temporary, JSON.stringify(current), { mode: 0o600 });
44
45
  await rename(temporary, file);
45
46
  return archived ? current[sessionId] : undefined;
46
- });
47
+ }));
47
48
  writeChain = operation.catch(() => {});
48
49
  return operation;
49
50
  };
@@ -1,6 +1,8 @@
1
1
  import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
2
2
  import { dirname, join } from 'node:path';
3
3
 
4
+ import { withCrossProcessLock } from '../server/cross-process-lock.js';
5
+
4
6
  const PROVIDER_ID = /^[a-z0-9][a-z0-9-_]*$/;
5
7
  const API_KEY_REFERENCE = /^\{env:[A-Za-z_][A-Za-z0-9_]*\}$/;
6
8
  const API_TYPES = new Set(['openai-completions', 'openai-responses', 'anthropic-messages', 'google-generative-ai']);
@@ -146,7 +148,9 @@ export const createPiModelConfigStore = ({ file }) => {
146
148
 
147
149
  const update = async (input) => {
148
150
  const nextProvider = normalizeUpdate(input);
149
- const operation = writeChain.then(async () => {
151
+ // models.json lives under the shared Pi agent directory, so concurrent
152
+ // daemons serialize here rather than in-process only.
153
+ const operation = writeChain.then(() => withCrossProcessLock(`${file}.lock`, async () => {
150
154
  const config = await readConfig();
151
155
  const previous = config.providers[nextProvider.providerId];
152
156
  const provider = {
@@ -164,7 +168,7 @@ export const createPiModelConfigStore = ({ file }) => {
164
168
  await writeFile(temporary, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
165
169
  await rename(temporary, file);
166
170
  return publicProvider(nextProvider.providerId, provider);
167
- });
171
+ }));
168
172
  writeChain = operation.catch(() => {});
169
173
  return operation;
170
174
  };
@@ -35,6 +35,9 @@ const UNAVAILABLE_CODES = new Set([
35
35
  'DAEMON_CREDENTIAL_UNAVAILABLE',
36
36
  'DAEMON_LOCK_UNAVAILABLE',
37
37
  'DAEMON_LOCK_TIMEOUT',
38
+ 'DAEMON_OWNERSHIP_MISMATCH',
39
+ 'DAEMON_PROFILE_IN_USE',
40
+ 'SESSION_LEASE_UNAVAILABLE',
38
41
  'INVALID_DAEMON_ENDPOINT',
39
42
  'PROVIDER_UNAVAILABLE',
40
43
  'MALFORMED_SESSION_JSONL',
@@ -42,13 +45,22 @@ const UNAVAILABLE_CODES = new Set([
42
45
  'ARCHIVE_METADATA_INVALID',
43
46
  ]);
44
47
 
48
+ const BAD_GATEWAY_CODES = new Set([
49
+ 'MALFORMED_DAEMON_RESPONSE',
50
+ 'DAEMON_RESPONSE_TOO_LARGE',
51
+ ]);
52
+
45
53
  const writeDaemonError = (res, error) => {
46
54
  const code = typeof error?.code === 'string' ? error.code : 'DAEMON_REQUEST_FAILED';
47
55
  const status = UNAVAILABLE_CODES.has(code)
48
56
  ? 503
57
+ : BAD_GATEWAY_CODES.has(code)
58
+ ? 502
49
59
  : code === 'INVALID_SESSION'
50
60
  ? 404
51
- : code === 'ATTACHMENT_TOO_LARGE'
61
+ : code === 'SESSION_IN_USE'
62
+ ? 409
63
+ : code === 'ATTACHMENT_TOO_LARGE'
52
64
  ? 413
53
65
  : code === 'ATTACHMENT_LIMIT_REACHED'
54
66
  ? 429
@@ -207,7 +219,8 @@ const projectFilePart = (part) => {
207
219
  };
208
220
 
209
221
  const projectSessionDetail = (value) => {
210
- if (!value || typeof value !== 'object' || !Array.isArray(value.messages) || !Number.isSafeInteger(value.lastSequence)) throw protocolMismatch();
222
+ if (!value || typeof value !== 'object' || !Array.isArray(value.messages) || !Number.isSafeInteger(value.lastSequence)
223
+ || (value.hasMoreBefore === true && (typeof value.beforeCursor !== 'string' || value.beforeCursor.length === 0))) throw protocolMismatch();
211
224
  const messages = value.messages.map((item) => {
212
225
  if (!item || typeof item !== 'object' || !item.message || !Array.isArray(item.parts)) throw protocolMismatch();
213
226
  const message = item.message;
@@ -265,6 +278,11 @@ const projectSessionDetail = (value) => {
265
278
  return {
266
279
  session: projectSession(value.session),
267
280
  messages,
281
+ ...(value.hasMoreBefore === true && typeof value.beforeCursor === 'string' && value.beforeCursor.length > 0
282
+ ? { hasMoreBefore: true, beforeCursor: value.beforeCursor }
283
+ : value.hasMoreBefore === false
284
+ ? { hasMoreBefore: false }
285
+ : {}),
268
286
  lastSequence: value.lastSequence,
269
287
  isStreaming,
270
288
  lifecycle,
@@ -801,7 +819,11 @@ export const registerPiRuntimeRoutes = (app, {
801
819
  app.put('/api/pi/session-folders', async (req, res) => {
802
820
  try {
803
821
  res.json(await sessionFoldersStore.write(req.body));
804
- } catch {
822
+ } catch (error) {
823
+ if (error?.code === 'SESSION_FOLDERS_STALE') {
824
+ res.status(409).json({ error: 'Session folders changed on another instance; reload and retry' });
825
+ return;
826
+ }
805
827
  res.status(400).json({ error: 'Invalid session folders' });
806
828
  }
807
829
  });
@@ -1477,6 +1499,27 @@ export const registerPiRuntimeRoutes = (app, {
1477
1499
  app.get('/api/pi/sessions/:sessionId', sendSessionDetail);
1478
1500
  app.get('/api/pi/sessions/:sessionId/snapshot', sendSessionDetail);
1479
1501
 
1502
+ app.get('/api/pi/sessions/:sessionId/messages', async (req, res) => {
1503
+ const before = req.query?.before;
1504
+ const rawLimit = req.query?.limit;
1505
+ const limit = rawLimit === undefined ? undefined : Number(rawLimit);
1506
+ if ((before !== undefined && (typeof before !== 'string' || before.length === 0))
1507
+ || (rawLimit !== undefined && (typeof rawLimit !== 'string' || !Number.isSafeInteger(limit) || limit < 1 || limit > 100))) {
1508
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
1509
+ return;
1510
+ }
1511
+ const result = await requestSessionOperation(req, res, getPiSessionDaemonRuntime, 'sessions.messages', {
1512
+ ...(typeof before === 'string' ? { before } : {}),
1513
+ ...(limit !== undefined ? { limit } : {}),
1514
+ });
1515
+ if (result === undefined) return;
1516
+ try {
1517
+ res.json(projectSessionDetail(result));
1518
+ } catch (error) {
1519
+ writeDaemonError(res, error);
1520
+ }
1521
+ });
1522
+
1480
1523
  app.delete('/api/pi/sessions/:sessionId', async (req, res) => {
1481
1524
  const result = await requestSessionOperation(req, res, getPiSessionDaemonRuntime, 'sessions.delete');
1482
1525
  if (result !== undefined) res.status(204).end();
@@ -582,6 +582,59 @@ describe('Pi runtime route', () => {
582
582
  ]);
583
583
  });
584
584
 
585
+ it('maps malformed and oversized daemon responses to distinct gateway errors', async () => {
586
+ for (const code of ['MALFORMED_DAEMON_RESPONSE', 'DAEMON_RESPONSE_TOO_LARGE']) {
587
+ const runtime = {
588
+ request: async () => {
589
+ const error = new Error(code);
590
+ error.code = code;
591
+ throw error;
592
+ },
593
+ };
594
+ const app = express();
595
+ registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime });
596
+ server = await listen(app);
597
+ const response = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/sessions/session-1`);
598
+ expect(response.status).toBe(502);
599
+ await expect(response.json()).resolves.toEqual({ error: { code } });
600
+ await close(server);
601
+ server = undefined;
602
+ }
603
+ });
604
+
605
+ it('validates and forwards older transcript page requests', async () => {
606
+ const calls = [];
607
+ const detail = {
608
+ session: { id: 'pi-session-pages', directory: '/workspace', createdAt: 1, updatedAt: 2 },
609
+ messages: [],
610
+ hasMoreBefore: false,
611
+ lastSequence: 5,
612
+ isStreaming: false,
613
+ lifecycle: 'idle',
614
+ };
615
+ const runtime = {
616
+ request: async (command, payload) => {
617
+ calls.push({ command, payload });
618
+ return detail;
619
+ },
620
+ };
621
+ const app = express();
622
+ app.use(express.json());
623
+ registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime, archiveStore: { read: async () => ({}) } });
624
+ server = await listen(app);
625
+ const base = `http://127.0.0.1:${server.address().port}/api/pi/sessions/pi-session-pages/messages`;
626
+
627
+ const response = await fetch(`${base}?directory=${encodeURIComponent('/workspace')}&before=entry-5&limit=25`);
628
+ expect(response.status).toBe(200);
629
+ await expect(response.json()).resolves.toMatchObject({ hasMoreBefore: false, messages: [] });
630
+ expect(calls).toEqual([{
631
+ command: 'sessions.messages',
632
+ payload: { sessionId: 'pi-session-pages', directory: '/workspace', before: 'entry-5', limit: 25 },
633
+ }]);
634
+ expect((await fetch(`${base}?limit=0`)).status).toBe(400);
635
+ expect((await fetch(`${base}?limit=101`)).status).toBe(400);
636
+ });
637
+
585
638
  it('adapts every path-selected session operation and archives without selecting a Pi runtime', async () => {
586
639
  const calls = [];
587
640
  const detail = { session: { id: 'pi-session-7', directory: '/workspace', createdAt: 1, updatedAt: 2 }, messages: [], lastSequence: 5 };