@pi-chamber/web 0.8.2 → 0.9.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.
- package/README.md +22 -6
- package/bin/cli.js +16 -3
- package/bin/cli.test.js +62 -0
- package/bin/lib/DOCUMENTATION.md +6 -6
- package/bin/lib/cli-args.js +26 -7
- package/bin/lib/cli-lifecycle.js +3 -0
- package/bin/lib/cli-paths.js +6 -0
- package/bin/lib/cli-process.js +1 -0
- package/bin/lib/cli-tunnel-profiles.js +15 -10
- package/bin/lib/commands-connect-url.js +9 -1
- package/bin/lib/commands-lifecycle.js +14 -0
- package/bin/lib/commands-logs.js +24 -5
- package/bin/lib/commands-serve.js +176 -4
- package/bin/lib/commands-tunnel.js +35 -0
- package/bin/lib/commands-update.js +107 -39
- package/bin/lib/commands-update.test.js +97 -1
- package/dist/assets/{DiagramEditor-DerMrS6m.js → DiagramEditor-DoEOH0hY.js} +1 -1
- package/dist/assets/{DiagramView-DdipXAq8.js → DiagramView-y9Ystuhv.js} +1 -1
- package/dist/assets/DiffView-ScM4XoqZ.js +18 -0
- package/dist/assets/{FilesView-BXp0yc0j.js → FilesView-CjkhMFqJ.js} +3 -3
- package/dist/assets/GitView-Bqi6H8I-.js +8 -0
- package/dist/assets/JsonTreeView-DWhlH6NK.js +1 -0
- package/dist/assets/{MarkdownRendererImpl-DNZQgQua.js → MarkdownRendererImpl-CEOKZ1qH.js} +1 -1
- package/dist/assets/{PatchDiff-B_NFEIX7.js → PatchDiff-ClnfJJ2J.js} +1 -1
- package/dist/assets/{SessionSwitcherContent-Q4P2TGBr.js → SessionSwitcherContent-e6JzUXD_.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-Cgw2mQIO.js → SessionSwitcherDropdown-C4etG8dv.js} +2 -2
- package/dist/assets/{SessionUnreadDot-BxtTkvHB.js → SessionUnreadDot-BVTSwRiG.js} +1 -1
- package/dist/assets/SettingsView-C0S0Sx-S.js +2 -0
- package/dist/assets/{SettingsWindow-BEjHL1ET.js → SettingsWindow-Cy9tmnMg.js} +1 -1
- package/dist/assets/ToolOutputDialog-Csrc0Uk2.js +8 -0
- package/dist/assets/{ToolPartDiffPreview-ClV785zX.js → ToolPartDiffPreview-6oH6KD44.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-DrxkW2WQ.js → VirtualizedFileDiff-DJNcTQNp.js} +4 -4
- package/dist/assets/{collapsible-CR3-hRMy.js → collapsible-DxgVLhi9.js} +1 -1
- package/dist/assets/computeVirtualFileMetrics-B-WoeBMW.js +3 -0
- package/dist/assets/{contextFileOpenGuard-BRc5Z0g-.js → contextFileOpenGuard-DQ4U9xRH.js} +1 -1
- package/dist/assets/gitStatusPredicates-CIFSGjJs.js +134 -0
- package/dist/assets/index-D2C3q2xD.js +8 -0
- package/dist/assets/index-DNoEeZ2U.css +1 -0
- package/dist/assets/{index-CMfiVUIr.js → index-DmNPBaSo.js} +1 -1
- package/dist/assets/{isDiffPlainText-MmBA1REG.js → isDiffPlainText-CrvpUauF.js} +1 -1
- package/dist/assets/{isFilePlainText-bQAPxqO9.js → isFilePlainText-CKvhS32g.js} +1 -1
- package/dist/assets/{main-zZrKd3hZ.js → main-BFv8slLp.js} +2 -2
- package/dist/assets/main-CjM7g4Gq.js +135 -0
- package/dist/assets/{markdownCore-B9jXCPry.js → markdownCore-DKrraAqT.js} +1 -1
- package/dist/assets/{miniChat-Di2oVS5o.js → miniChat-hQnLS5mt.js} +2 -2
- package/dist/assets/{mobile-VU_G_SgX.js → mobile-DuXOBGs_.js} +2 -2
- package/dist/assets/renderElectronMiniChatApp-ClJBZVGy.js +2 -0
- package/dist/assets/renderMobileApp-DofX2wjB.js +11 -0
- package/dist/assets/runtimeEndpointReset-BZeYg6eN.js +54 -0
- package/dist/assets/{runtimeSurface-CBaS2Ank.js → runtimeSurface-C7CBxDbh.js} +1 -1
- package/dist/assets/{useAppFontEffects-8ZU-TTIW.js → useAppFontEffects-Cs0f1dKn.js} +102 -102
- package/dist/assets/{useFilesViewSearch-COow9O9x.js → useFilesViewSearch-D1hcbBEc.js} +1 -1
- package/dist/assets/usePushVisibilityBeacon-DqHkuVS5.js +10 -0
- package/dist/assets/{useSwitcherItems-DOQqhi-e.js → useSwitcherItems-BEoW7LlC.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-B_0wrsbo.js → vendor-codemirror-language-data-B8Ac62S_.js} +2 -2
- package/dist/assets/{vendor-dnd-kit-core-CP8ck10N.js → vendor-dnd-kit-core-C9qcAm_1.js} +1 -1
- package/dist/assets/{vendor-dnd-kit-sortable-B-Icjoj4.js → vendor-dnd-kit-sortable-D8ozj8M-.js} +1 -1
- package/dist/assets/vendor-xterm-addon-fit-DX4qG4td.js +1 -0
- package/dist/assets/vendor-xterm-xterm-CrXqRur4.js +16 -0
- package/dist/assets/vendor-xterm-xterm-DDGTF8rc.css +1 -0
- package/dist/assets/{web-components-C9ENH49P.js → web-components-Dy-Tz_LJ.js} +3 -3
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +3 -4
- package/server/index.js +26 -7
- package/server/lib/client-auth/pairing.js +13 -2
- package/server/lib/client-auth/remote-clients.js +13 -2
- package/server/lib/fs/DOCUMENTATION.md +3 -1
- package/server/lib/fs/routes.test.js +74 -0
- package/server/lib/git/DOCUMENTATION.md +1 -1
- package/server/lib/git/identity-storage.js +10 -1
- package/server/lib/package-manager.js +1 -1
- package/server/lib/package-manager.test.js +11 -0
- package/server/lib/pi/archive-store.js +3 -2
- package/server/lib/pi/model-config-store.js +6 -2
- package/server/lib/pi/routes.js +11 -2
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +12 -6
- package/server/lib/pi/session-daemon/daemon-process.js +48 -13
- package/server/lib/pi/session-daemon/session-daemon.js +226 -40
- package/server/lib/pi/session-daemon/session-daemon.test.js +207 -0
- package/server/lib/pi/session-daemon/session-lease.js +151 -0
- package/server/lib/pi/session-daemon/session-lease.test.js +108 -0
- package/server/lib/pi/session-daemon/supervisor.js +244 -54
- package/server/lib/pi/session-daemon/supervisor.test.js +202 -6
- package/server/lib/pi/session-folders-store.js +20 -2
- package/server/lib/pi/session-folders-store.test.js +17 -0
- package/server/lib/pi/settings-store.js +3 -2
- package/server/lib/pi/snippets-store.js +4 -1
- package/server/lib/pi/ui-settings-store.js +3 -2
- package/server/lib/server/cross-process-lock.js +112 -0
- package/server/lib/server/cross-process-lock.test.js +70 -0
- package/server/lib/server/server-profile.js +110 -0
- package/server/lib/server/server-profile.test.js +58 -0
- package/server/lib/server/tunnel-service.DOCUMENTATION.md +7 -8
- package/server/lib/server/tunnel-service.js +8 -1
- package/server/lib/stt/DOCUMENTATION.md +1 -1
- package/server/lib/stt/config-store.js +3 -2
- package/server/lib/terminal/DOCUMENTATION.md +3 -3
- package/server/lib/tunnels/DOCUMENTATION.md +38 -18
- package/server/lib/ui-auth/ui-auth.js +9 -2
- package/server/lib/ui-auth/ui-passkeys.js +9 -1
- package/dist/assets/DiffView-Gh9wjthp.js +0 -18
- package/dist/assets/GitView-BmNCkkoC.js +0 -8
- package/dist/assets/JsonTreeView-CxXRXXzk.js +0 -1
- package/dist/assets/SettingsView-CFzxRzUq.js +0 -2
- package/dist/assets/ToolOutputDialog-C_7vJLEq.js +0 -8
- package/dist/assets/computeVirtualFileMetrics-D0mQcleY.js +0 -3
- package/dist/assets/gitStatusPredicates-DBGDfr1K.js +0 -134
- package/dist/assets/index-CzO3ooje.css +0 -1
- package/dist/assets/index-ivrh3jfy.js +0 -8
- package/dist/assets/main-BoVfUG73.js +0 -135
- package/dist/assets/renderElectronMiniChatApp-Bi1927c8.js +0 -2
- package/dist/assets/renderMobileApp-D9mxhuaM.js +0 -11
- package/dist/assets/runtimeEndpointReset-DImT35Ug.js +0 -54
- package/dist/assets/usePushVisibilityBeacon-zYd3ppNh.js +0 -10
- package/dist/assets/vendor-ghostty-web-CrxinGGH.js +0 -13
|
@@ -103,6 +103,7 @@ describe('Pi session daemon supervisor', () => {
|
|
|
103
103
|
}
|
|
104
104
|
expect(JSON.stringify(await supervisor.health())).not.toContain(credential.trim());
|
|
105
105
|
|
|
106
|
+
await expect(supervisor.stop()).resolves.toEqual({ state: 'stopped' });
|
|
106
107
|
await expect(supervisor.stop()).resolves.toEqual({ state: 'stopped' });
|
|
107
108
|
await expect(supervisor.health()).resolves.toMatchObject({
|
|
108
109
|
state: 'unavailable',
|
|
@@ -191,13 +192,44 @@ describe('Pi session daemon supervisor', () => {
|
|
|
191
192
|
cwd: join(tmpdir(), 'pichamber-win-project'),
|
|
192
193
|
platform: 'win32',
|
|
193
194
|
});
|
|
194
|
-
expect(windowsSupervisor.paths.endpoint).toMatch(/^\\\\\.\\pipe\\pichamber-pi-session-daemon-[0-9a-f]{16}$/);
|
|
195
|
+
expect(windowsSupervisor.paths.endpoint).toMatch(/^\\\\\.\\pipe\\pichamber-pi-session-daemon-[0-9a-f]{16}-web$/);
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
it('namespaces daemon sidecars per server profile', () => {
|
|
199
|
+
const root = join(tmpdir(), 'pichamber-pi-supervisor-profiles-');
|
|
200
|
+
const installed = createPiSessionDaemonSupervisor({
|
|
201
|
+
env: { PICHAMBER_DATA_DIR: join(root, 'data') },
|
|
202
|
+
cwd: join(root, 'project'),
|
|
203
|
+
port: 3000,
|
|
204
|
+
});
|
|
205
|
+
const dev = createPiSessionDaemonSupervisor({
|
|
206
|
+
env: { PICHAMBER_DATA_DIR: join(root, 'data'), PICHAMBER_SERVER_PROFILE_KIND: 'dev' },
|
|
207
|
+
cwd: join(root, 'project'),
|
|
208
|
+
port: 3000,
|
|
209
|
+
});
|
|
210
|
+
const otherPort = createPiSessionDaemonSupervisor({
|
|
211
|
+
env: { PICHAMBER_DATA_DIR: join(root, 'data') },
|
|
212
|
+
cwd: join(root, 'project'),
|
|
213
|
+
port: 3902,
|
|
214
|
+
});
|
|
215
|
+
expect(installed.paths.profileKey).toBe('web-p3000');
|
|
216
|
+
expect(dev.paths.profileKey).toBe('web-dev-p3000');
|
|
217
|
+
for (const supervisor of [installed, dev, otherPort]) {
|
|
218
|
+
expect(supervisor.paths.credentialFile).toContain(supervisor.paths.profileKey);
|
|
219
|
+
expect(supervisor.paths.stateFile).toContain(supervisor.paths.profileKey);
|
|
220
|
+
expect(supervisor.paths.lockFile).toContain(supervisor.paths.profileKey);
|
|
221
|
+
expect(supervisor.paths.logFile).toContain(supervisor.paths.profileKey);
|
|
222
|
+
}
|
|
223
|
+
const paths = [installed, dev, otherPort].map((item) => item.paths.stateFile);
|
|
224
|
+
expect(new Set(paths).size).toBe(3);
|
|
225
|
+
expect(installed.paths.endpoint).not.toBe(dev.paths.endpoint);
|
|
226
|
+
expect(installed.paths.credentialFile).not.toBe(otherPort.paths.credentialFile);
|
|
195
227
|
});
|
|
196
228
|
|
|
197
229
|
it('bounds an unresponsive Windows daemon probe by the supervisor operation timeout', async () => {
|
|
198
230
|
const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-supervisor-hung-win-'));
|
|
199
231
|
const dataDir = join(root, 'data');
|
|
200
|
-
const piDataDir = join(dataDir, 'pi');
|
|
232
|
+
const piDataDir = join(dataDir, 'pi', 'daemons', 'web');
|
|
201
233
|
await mkdir(piDataDir, { recursive: true });
|
|
202
234
|
const daemonPid = 7_331;
|
|
203
235
|
const processLike = {
|
|
@@ -226,6 +258,9 @@ describe('Pi session daemon supervisor', () => {
|
|
|
226
258
|
protocolVersion: 1,
|
|
227
259
|
pid: daemonPid,
|
|
228
260
|
endpoint: windowsSupervisor.paths.endpoint,
|
|
261
|
+
profileKey: windowsSupervisor.paths.profileKey,
|
|
262
|
+
daemonId: 'daemon-hung',
|
|
263
|
+
serverInstanceId: windowsSupervisor.paths.serverInstanceId,
|
|
229
264
|
startedAt: new Date().toISOString(),
|
|
230
265
|
}));
|
|
231
266
|
|
|
@@ -242,8 +277,8 @@ describe('Pi session daemon supervisor', () => {
|
|
|
242
277
|
const cwd = join(root, 'project');
|
|
243
278
|
const agentDir = join(root, 'agent');
|
|
244
279
|
const dataDir = join(root, 'data');
|
|
245
|
-
await Promise.all([mkdir(cwd), mkdir(agentDir), mkdir(join(dataDir, 'pi'), { recursive: true })]);
|
|
246
|
-
const lockFile = join(dataDir, 'pi', '
|
|
280
|
+
await Promise.all([mkdir(cwd), mkdir(agentDir), mkdir(join(dataDir, 'pi', 'daemons', 'web'), { recursive: true })]);
|
|
281
|
+
const lockFile = join(dataDir, 'pi', 'daemons', 'web', 'operation.lock');
|
|
247
282
|
await writeFile(lockFile, '');
|
|
248
283
|
const past = new Date(Date.now() - 1_000);
|
|
249
284
|
await utimes(lockFile, past, past);
|
|
@@ -264,8 +299,8 @@ describe('Pi session daemon supervisor', () => {
|
|
|
264
299
|
const cwd = join(root, 'project');
|
|
265
300
|
const agentDir = join(root, 'agent');
|
|
266
301
|
const dataDir = join(root, 'data');
|
|
267
|
-
await Promise.all([mkdir(cwd), mkdir(agentDir), mkdir(join(dataDir, 'pi'), { recursive: true })]);
|
|
268
|
-
const lockFile = join(dataDir, 'pi', '
|
|
302
|
+
await Promise.all([mkdir(cwd), mkdir(agentDir), mkdir(join(dataDir, 'pi', 'daemons', 'web'), { recursive: true })]);
|
|
303
|
+
const lockFile = join(dataDir, 'pi', 'daemons', 'web', 'operation.lock');
|
|
269
304
|
await writeFile(lockFile, '{');
|
|
270
305
|
const past = new Date(Date.now() - 1_000);
|
|
271
306
|
await utimes(lockFile, past, past);
|
|
@@ -280,4 +315,165 @@ describe('Pi session daemon supervisor', () => {
|
|
|
280
315
|
supervisor = createPiSessionDaemonSupervisor({ env, cwd });
|
|
281
316
|
await expect(supervisor.start()).resolves.toMatchObject({ state: 'ready', reused: false });
|
|
282
317
|
}, 20_000);
|
|
318
|
+
|
|
319
|
+
it('keeps per-profile daemons independent across one data directory', async () => {
|
|
320
|
+
const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-supervisor-profiles-run-'));
|
|
321
|
+
const cwd = join(root, 'project');
|
|
322
|
+
const agentDir = join(root, 'agent');
|
|
323
|
+
await Promise.all([mkdir(cwd), mkdir(agentDir)]);
|
|
324
|
+
const baseEnv = {
|
|
325
|
+
...process.env,
|
|
326
|
+
PI_OFFLINE: '1',
|
|
327
|
+
PICHAMBER_DATA_DIR: join(root, 'data'),
|
|
328
|
+
PICHAMBER_PI_AGENT_DIR: agentDir,
|
|
329
|
+
XDG_RUNTIME_DIR: join(root, 'runtime'),
|
|
330
|
+
};
|
|
331
|
+
|
|
332
|
+
const installed = createPiSessionDaemonSupervisor({ env: baseEnv, cwd, port: 3000 });
|
|
333
|
+
const dev = createPiSessionDaemonSupervisor({
|
|
334
|
+
env: { ...baseEnv, PICHAMBER_SERVER_PROFILE_KIND: 'dev' },
|
|
335
|
+
cwd,
|
|
336
|
+
port: 3000,
|
|
337
|
+
});
|
|
338
|
+
try {
|
|
339
|
+
await installed.start();
|
|
340
|
+
await dev.start();
|
|
341
|
+
const installedState = JSON.parse(await readFile(installed.paths.stateFile, 'utf8'));
|
|
342
|
+
const devState = JSON.parse(await readFile(dev.paths.stateFile, 'utf8'));
|
|
343
|
+
expect(installedState.pid).not.toBe(devState.pid);
|
|
344
|
+
expect(installedState.profileKey).toBe('web-p3000');
|
|
345
|
+
expect(devState.profileKey).toBe('web-dev-p3000');
|
|
346
|
+
|
|
347
|
+
const created = await installed.request('sessions.create', { cwd });
|
|
348
|
+
const sessionDirectory = getPiSessionDirectory({ cwd, agentDir });
|
|
349
|
+
await mkdir(sessionDirectory, { recursive: true });
|
|
350
|
+
await writeFile(join(sessionDirectory, `lease_${created.session.id}.jsonl`), `${JSON.stringify({
|
|
351
|
+
type: 'session',
|
|
352
|
+
version: 3,
|
|
353
|
+
id: created.session.id,
|
|
354
|
+
timestamp: new Date().toISOString(),
|
|
355
|
+
cwd,
|
|
356
|
+
})}\n`);
|
|
357
|
+
await expect(dev.request('sessions.open', { sessionId: created.session.id, directory: cwd }))
|
|
358
|
+
.rejects.toMatchObject({ code: 'SESSION_IN_USE' });
|
|
359
|
+
await expect(dev.request('sessions.delete', { sessionId: created.session.id, directory: cwd }))
|
|
360
|
+
.rejects.toMatchObject({ code: 'SESSION_IN_USE' });
|
|
361
|
+
|
|
362
|
+
// Stopping one profile must release only its own leases and leave the
|
|
363
|
+
// other daemon running.
|
|
364
|
+
await installed.stop();
|
|
365
|
+
await expect(dev.health()).resolves.toMatchObject({ state: 'ready' });
|
|
366
|
+
await expect(dev.request('sessions.open', { sessionId: created.session.id, directory: cwd }))
|
|
367
|
+
.resolves.toMatchObject({ session: { id: created.session.id } });
|
|
368
|
+
await dev.stop();
|
|
369
|
+
await expect(dev.health()).resolves.toMatchObject({ state: 'unavailable' });
|
|
370
|
+
} finally {
|
|
371
|
+
await installed.stop().catch(() => {});
|
|
372
|
+
await dev.stop().catch(() => {});
|
|
373
|
+
}
|
|
374
|
+
}, 60_000);
|
|
375
|
+
|
|
376
|
+
it('refuses to claim a same-profile daemon while its server owner is alive', async () => {
|
|
377
|
+
const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-supervisor-live-owner-'));
|
|
378
|
+
const cwd = join(root, 'project');
|
|
379
|
+
const agentDir = join(root, 'agent');
|
|
380
|
+
await Promise.all([mkdir(cwd), mkdir(agentDir)]);
|
|
381
|
+
const env = {
|
|
382
|
+
...process.env,
|
|
383
|
+
PI_OFFLINE: '1',
|
|
384
|
+
PICHAMBER_DATA_DIR: join(root, 'data'),
|
|
385
|
+
PICHAMBER_PI_AGENT_DIR: agentDir,
|
|
386
|
+
XDG_RUNTIME_DIR: join(root, 'runtime'),
|
|
387
|
+
};
|
|
388
|
+
|
|
389
|
+
const first = createPiSessionDaemonSupervisor({ env, cwd, port: 3000 });
|
|
390
|
+
const peer = createPiSessionDaemonSupervisor({ env, cwd, port: 3000 });
|
|
391
|
+
try {
|
|
392
|
+
await first.start();
|
|
393
|
+
await expect(peer.start()).rejects.toMatchObject({ code: 'DAEMON_PROFILE_IN_USE' });
|
|
394
|
+
await expect(first.health()).resolves.toMatchObject({ state: 'ready' });
|
|
395
|
+
} finally {
|
|
396
|
+
await first.stop().catch(() => {});
|
|
397
|
+
await peer.stop().catch(() => {});
|
|
398
|
+
}
|
|
399
|
+
}, 30_000);
|
|
400
|
+
|
|
401
|
+
it('replaces a same-profile daemon when the PiChamber build changes', async () => {
|
|
402
|
+
const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-supervisor-build-'));
|
|
403
|
+
const cwd = join(root, 'project');
|
|
404
|
+
const agentDir = join(root, 'agent');
|
|
405
|
+
await Promise.all([mkdir(cwd), mkdir(agentDir)]);
|
|
406
|
+
const env = {
|
|
407
|
+
...process.env,
|
|
408
|
+
PI_OFFLINE: '1',
|
|
409
|
+
PICHAMBER_DATA_DIR: join(root, 'data'),
|
|
410
|
+
PICHAMBER_PI_AGENT_DIR: agentDir,
|
|
411
|
+
XDG_RUNTIME_DIR: join(root, 'runtime'),
|
|
412
|
+
};
|
|
413
|
+
const departedServerProcess = {
|
|
414
|
+
pid: 987_654_321,
|
|
415
|
+
execPath: process.execPath,
|
|
416
|
+
versions: process.versions,
|
|
417
|
+
kill(pid, signal) {
|
|
418
|
+
return process.kill(pid, signal);
|
|
419
|
+
},
|
|
420
|
+
};
|
|
421
|
+
const first = createPiSessionDaemonSupervisor({ env, cwd, port: 3000, version: '1.0.0', processLike: departedServerProcess });
|
|
422
|
+
const upgraded = createPiSessionDaemonSupervisor({ env, cwd, port: 3000, version: '2.0.0' });
|
|
423
|
+
try {
|
|
424
|
+
await first.start();
|
|
425
|
+
const firstState = JSON.parse(await readFile(first.paths.stateFile, 'utf8'));
|
|
426
|
+
await expect(upgraded.start()).resolves.toMatchObject({ state: 'ready', reused: false });
|
|
427
|
+
await waitForExit(firstState.pid);
|
|
428
|
+
const upgradedState = JSON.parse(await readFile(upgraded.paths.stateFile, 'utf8'));
|
|
429
|
+
expect(upgradedState.pid).not.toBe(firstState.pid);
|
|
430
|
+
expect(upgradedState.buildId).toBe('2.0.0');
|
|
431
|
+
} finally {
|
|
432
|
+
await first.stop().catch(() => {});
|
|
433
|
+
await upgraded.stop().catch(() => {});
|
|
434
|
+
}
|
|
435
|
+
}, 60_000);
|
|
436
|
+
|
|
437
|
+
it('refuses a stale same-profile server stop after a newer instance claims the daemon', async () => {
|
|
438
|
+
const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-supervisor-claim-'));
|
|
439
|
+
const cwd = join(root, 'project');
|
|
440
|
+
const agentDir = join(root, 'agent');
|
|
441
|
+
await Promise.all([mkdir(cwd), mkdir(agentDir)]);
|
|
442
|
+
const env = {
|
|
443
|
+
...process.env,
|
|
444
|
+
PI_OFFLINE: '1',
|
|
445
|
+
PICHAMBER_DATA_DIR: join(root, 'data'),
|
|
446
|
+
PICHAMBER_PI_AGENT_DIR: agentDir,
|
|
447
|
+
XDG_RUNTIME_DIR: join(root, 'runtime'),
|
|
448
|
+
};
|
|
449
|
+
|
|
450
|
+
const departedServerProcess = {
|
|
451
|
+
pid: 987_654_321,
|
|
452
|
+
execPath: process.execPath,
|
|
453
|
+
versions: process.versions,
|
|
454
|
+
kill(pid, signal) {
|
|
455
|
+
return process.kill(pid, signal);
|
|
456
|
+
},
|
|
457
|
+
};
|
|
458
|
+
const first = createPiSessionDaemonSupervisor({ env, cwd, port: 3000, processLike: departedServerProcess });
|
|
459
|
+
const second = createPiSessionDaemonSupervisor({ env, cwd, port: 3000 });
|
|
460
|
+
try {
|
|
461
|
+
await first.start();
|
|
462
|
+
const firstState = JSON.parse(await readFile(first.paths.stateFile, 'utf8'));
|
|
463
|
+
|
|
464
|
+
// A restarted server on the same profile claims the live daemon.
|
|
465
|
+
await expect(second.start()).resolves.toMatchObject({ state: 'ready', reused: true });
|
|
466
|
+
const claimedState = JSON.parse(await readFile(second.paths.stateFile, 'utf8'));
|
|
467
|
+
expect(claimedState.pid).toBe(firstState.pid);
|
|
468
|
+
expect(claimedState.serverInstanceId).toBe(second.paths.serverInstanceId);
|
|
469
|
+
|
|
470
|
+
// The stale first server must not terminate the claimed daemon.
|
|
471
|
+
await expect(first.stop()).rejects.toMatchObject({ code: 'DAEMON_OWNERSHIP_MISMATCH' });
|
|
472
|
+
await expect(second.health()).resolves.toMatchObject({ state: 'ready' });
|
|
473
|
+
await expect(second.stop()).resolves.toEqual({ state: 'stopped' });
|
|
474
|
+
} finally {
|
|
475
|
+
await first.stop().catch(() => {});
|
|
476
|
+
await second.stop().catch(() => {});
|
|
477
|
+
}
|
|
478
|
+
}, 60_000);
|
|
283
479
|
});
|
|
@@ -3,6 +3,7 @@ import { chmod, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
|
3
3
|
import { dirname, join } from 'node:path';
|
|
4
4
|
|
|
5
5
|
import { resolvePiChamberDataDir } from '../pichamber-data-dir.js';
|
|
6
|
+
import { withCrossProcessLock } from '../server/cross-process-lock.js';
|
|
6
7
|
|
|
7
8
|
const MAX_FILE_BYTES = 2 * 1024 * 1024;
|
|
8
9
|
const MAX_KEY_LENGTH = 2_048;
|
|
@@ -57,7 +58,24 @@ export const createPiSessionFoldersStore = ({
|
|
|
57
58
|
|
|
58
59
|
const write = async (value) => {
|
|
59
60
|
const snapshot = validateSnapshot(value);
|
|
60
|
-
const operation = mutation.then(async () => {
|
|
61
|
+
const operation = mutation.then(async () => withCrossProcessLock(`${file}.lock`, async () => {
|
|
62
|
+
// Stale snapshots must not silently overwrite newer folders: concurrent
|
|
63
|
+
// servers share this file and only the lock serializes them.
|
|
64
|
+
try {
|
|
65
|
+
const raw = await fs.readFile(file, 'utf8');
|
|
66
|
+
const current = validateSnapshot(JSON.parse(raw));
|
|
67
|
+
const sameRevision = current.updatedAt === snapshot.updatedAt;
|
|
68
|
+
const sameSnapshot = sameRevision && JSON.stringify(current) === JSON.stringify(snapshot);
|
|
69
|
+
if (current.updatedAt > snapshot.updatedAt || (sameRevision && !sameSnapshot)) {
|
|
70
|
+
const stale = new Error('SESSION_FOLDERS_STALE');
|
|
71
|
+
stale.code = 'SESSION_FOLDERS_STALE';
|
|
72
|
+
throw stale;
|
|
73
|
+
}
|
|
74
|
+
if (sameSnapshot) return { exists: true, ...current };
|
|
75
|
+
} catch (error) {
|
|
76
|
+
if (error?.code === 'ENOENT') { /* first write wins */ } else if (error?.code === 'SESSION_FOLDERS_STALE') throw error;
|
|
77
|
+
else throw invalid();
|
|
78
|
+
}
|
|
61
79
|
const parent = dirname(file);
|
|
62
80
|
await fs.mkdir(parent, { recursive: true, mode: 0o700 });
|
|
63
81
|
const temporary = `${file}.tmp-${process.pid}-${randomUUID()}`;
|
|
@@ -65,7 +83,7 @@ export const createPiSessionFoldersStore = ({
|
|
|
65
83
|
await fs.rename(temporary, file);
|
|
66
84
|
if (process.platform !== 'win32') await fs.chmod(file, 0o600);
|
|
67
85
|
return { exists: true, ...snapshot };
|
|
68
|
-
});
|
|
86
|
+
}));
|
|
69
87
|
mutation = operation.catch(() => {});
|
|
70
88
|
return operation;
|
|
71
89
|
};
|
|
@@ -33,6 +33,23 @@ describe('Pi session folders store', () => {
|
|
|
33
33
|
expect(JSON.parse(await readFile(file, 'utf8'))).toEqual(snapshot);
|
|
34
34
|
});
|
|
35
35
|
|
|
36
|
+
it('rejects stale and conflicting same-revision snapshots', async () => {
|
|
37
|
+
const directory = await mkdtemp(join(tmpdir(), 'pichamber-session-folders-'));
|
|
38
|
+
directories.push(directory);
|
|
39
|
+
const store = createPiSessionFoldersStore({ file: join(directory, 'session-folders.json') });
|
|
40
|
+
await store.write(snapshot);
|
|
41
|
+
|
|
42
|
+
await expect(store.write({ ...snapshot, updatedAt: 1 })).rejects.toMatchObject({ code: 'SESSION_FOLDERS_STALE' });
|
|
43
|
+
await expect(store.write({
|
|
44
|
+
...snapshot,
|
|
45
|
+
foldersMap: {
|
|
46
|
+
'/workspace': [{ ...snapshot.foldersMap['/workspace'][0], name: 'Conflicting' }],
|
|
47
|
+
},
|
|
48
|
+
})).rejects.toMatchObject({ code: 'SESSION_FOLDERS_STALE' });
|
|
49
|
+
await expect(store.write(snapshot)).resolves.toEqual({ exists: true, ...snapshot });
|
|
50
|
+
await expect(store.read()).resolves.toEqual({ exists: true, ...snapshot });
|
|
51
|
+
});
|
|
52
|
+
|
|
36
53
|
it('rejects malformed snapshots without replacing valid data', async () => {
|
|
37
54
|
const directory = await mkdtemp(join(tmpdir(), 'pichamber-session-folders-'));
|
|
38
55
|
directories.push(directory);
|
|
@@ -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
|
import { isPiThinkingLevel } from './thinking-levels.js';
|
|
6
7
|
|
|
7
8
|
const invalidSettings = () => {
|
|
@@ -123,7 +124,7 @@ export const createPiSettingsStore = ({ file = join(resolvePiChamberDataDir(), '
|
|
|
123
124
|
|
|
124
125
|
const update = async (patch) => {
|
|
125
126
|
if (!patch || typeof patch !== 'object' || Array.isArray(patch)) throw invalidSettings();
|
|
126
|
-
const operation = writeChain.then(async () => {
|
|
127
|
+
const operation = writeChain.then(() => withCrossProcessLock(`${file}.lock`, async () => {
|
|
127
128
|
const current = await read();
|
|
128
129
|
const next = normalize({
|
|
129
130
|
...current,
|
|
@@ -141,7 +142,7 @@ export const createPiSettingsStore = ({ file = join(resolvePiChamberDataDir(), '
|
|
|
141
142
|
await writeFile(temporary, JSON.stringify(next), { mode: 0o600 });
|
|
142
143
|
await rename(temporary, file);
|
|
143
144
|
return next;
|
|
144
|
-
});
|
|
145
|
+
}));
|
|
145
146
|
writeChain = operation.catch(() => {});
|
|
146
147
|
return operation;
|
|
147
148
|
};
|
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
import { dirname, isAbsolute, join, normalize } from "node:path";
|
|
11
11
|
|
|
12
12
|
import { resolvePiChamberDataDir } from "../pichamber-data-dir.js";
|
|
13
|
+
import { withCrossProcessLock } from "../server/cross-process-lock.js";
|
|
13
14
|
|
|
14
15
|
const MAX_FILE_BYTES = 2 * 1024 * 1024;
|
|
15
16
|
const MAX_CONTENT_CHARS = 200_000;
|
|
@@ -238,7 +239,9 @@ export const createPiSnippetsStore = ({
|
|
|
238
239
|
};
|
|
239
240
|
|
|
240
241
|
const transact = (operation) => {
|
|
241
|
-
|
|
242
|
+
// The in-process chain orders one server; the file lock orders every
|
|
243
|
+
// server sharing this data directory.
|
|
244
|
+
const pending = mutation.then(() => withCrossProcessLock(`${file}.lock`, operation));
|
|
242
245
|
mutation = pending.catch(() => {});
|
|
243
246
|
return pending;
|
|
244
247
|
};
|
|
@@ -3,6 +3,7 @@ import { chmod, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
|
3
3
|
import { dirname, join } from 'node:path';
|
|
4
4
|
|
|
5
5
|
import { resolvePiChamberDataDir } from '../pichamber-data-dir.js';
|
|
6
|
+
import { withCrossProcessLock } from '../server/cross-process-lock.js';
|
|
6
7
|
|
|
7
8
|
const MAX_SETTINGS_BYTES = 2 * 1024 * 1024;
|
|
8
9
|
|
|
@@ -47,7 +48,7 @@ export const createPiUiSettingsStore = ({
|
|
|
47
48
|
|
|
48
49
|
const write = async (changes) => {
|
|
49
50
|
validateRecord(changes);
|
|
50
|
-
const operation = mutation.then(async () => {
|
|
51
|
+
const operation = mutation.then(() => withCrossProcessLock(`${file}.lock`, async () => {
|
|
51
52
|
const current = await read();
|
|
52
53
|
const next = { ...current, ...changes };
|
|
53
54
|
const serialized = `${JSON.stringify(next, null, 2)}\n`;
|
|
@@ -59,7 +60,7 @@ export const createPiUiSettingsStore = ({
|
|
|
59
60
|
await fs.rename(temporary, file);
|
|
60
61
|
if (process.platform !== 'win32') await fs.chmod(file, 0o600);
|
|
61
62
|
return next;
|
|
62
|
-
});
|
|
63
|
+
}));
|
|
63
64
|
mutation = operation.catch(() => {});
|
|
64
65
|
return operation;
|
|
65
66
|
};
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { dirname } from 'node:path';
|
|
4
|
+
|
|
5
|
+
const RETRYABLE_CODES = new Set(['EEXIST', 'EPERM', 'EACCES', 'EBUSY', 'EAGAIN']);
|
|
6
|
+
const FRESH_LOCK_MS = 250;
|
|
7
|
+
|
|
8
|
+
export class CrossProcessLockError extends Error {
|
|
9
|
+
constructor(code, message = 'The cross-process lock is unavailable.') {
|
|
10
|
+
super(message);
|
|
11
|
+
this.code = code;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const delay = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
|
|
16
|
+
|
|
17
|
+
const isPidAlive = (processLike, pid) => {
|
|
18
|
+
try {
|
|
19
|
+
processLike.kill(pid, 0);
|
|
20
|
+
return true;
|
|
21
|
+
} catch (error) {
|
|
22
|
+
return error?.code === 'EPERM';
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const readClaim = async (lockFile) => {
|
|
27
|
+
try {
|
|
28
|
+
const claim = JSON.parse(await readFile(lockFile, 'utf8'));
|
|
29
|
+
if (Number.isInteger(claim?.pid) && claim.pid > 0 && typeof claim.nonce === 'string' && claim.nonce.length > 0) {
|
|
30
|
+
return { claim };
|
|
31
|
+
}
|
|
32
|
+
return { malformed: true };
|
|
33
|
+
} catch (error) {
|
|
34
|
+
if (error?.code === 'ENOENT') return { missing: true };
|
|
35
|
+
return { malformed: true };
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const isFreshLock = async (lockFile) => {
|
|
40
|
+
try {
|
|
41
|
+
const info = await stat(lockFile);
|
|
42
|
+
return Date.now() - info.mtimeMs < FRESH_LOCK_MS;
|
|
43
|
+
} catch (error) {
|
|
44
|
+
return error?.code !== 'ENOENT';
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Serialize one critical section across processes sharing a filesystem.
|
|
50
|
+
*
|
|
51
|
+
* The lock file holds an owner pid plus a random nonce. Only the owner nonce
|
|
52
|
+
* may release the lock. A dead owner pid may be stolen; a live owner never is.
|
|
53
|
+
*/
|
|
54
|
+
export const withCrossProcessLock = async (
|
|
55
|
+
lockFile,
|
|
56
|
+
operation,
|
|
57
|
+
{ timeoutMs = 5_000, retryDelayMs = 50, processLike = process, wait = delay } = {},
|
|
58
|
+
) => {
|
|
59
|
+
if (typeof lockFile !== 'string' || lockFile.length === 0) {
|
|
60
|
+
throw new CrossProcessLockError('INVALID_LOCK_FILE');
|
|
61
|
+
}
|
|
62
|
+
if (typeof operation !== 'function') {
|
|
63
|
+
throw new CrossProcessLockError('INVALID_OPERATION');
|
|
64
|
+
}
|
|
65
|
+
const deadline = Date.now() + timeoutMs;
|
|
66
|
+
await mkdir(dirname(lockFile), { recursive: true, mode: 0o700 });
|
|
67
|
+
const nonce = randomUUID();
|
|
68
|
+
|
|
69
|
+
while (true) {
|
|
70
|
+
try {
|
|
71
|
+
await writeFile(
|
|
72
|
+
lockFile,
|
|
73
|
+
JSON.stringify({ pid: processLike.pid, nonce, claimedAt: new Date().toISOString() }),
|
|
74
|
+
{ flag: 'wx', mode: 0o600 },
|
|
75
|
+
);
|
|
76
|
+
} catch (error) {
|
|
77
|
+
if (!RETRYABLE_CODES.has(error?.code)) throw new CrossProcessLockError('LOCK_UNAVAILABLE');
|
|
78
|
+
const observed = await readClaim(lockFile);
|
|
79
|
+
if (observed.claim) {
|
|
80
|
+
if (isPidAlive(processLike, observed.claim.pid)) {
|
|
81
|
+
if (Date.now() >= deadline) throw new CrossProcessLockError('LOCK_TIMEOUT');
|
|
82
|
+
await wait(retryDelayMs);
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
await rm(lockFile, { force: true });
|
|
86
|
+
} else if (observed.malformed) {
|
|
87
|
+
if (await isFreshLock(lockFile)) {
|
|
88
|
+
if (Date.now() >= deadline) throw new CrossProcessLockError('LOCK_TIMEOUT');
|
|
89
|
+
await wait(retryDelayMs);
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
await rm(lockFile, { force: true });
|
|
93
|
+
}
|
|
94
|
+
if (Date.now() >= deadline) throw new CrossProcessLockError('LOCK_TIMEOUT');
|
|
95
|
+
await wait(retryDelayMs);
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
try {
|
|
100
|
+
return await operation();
|
|
101
|
+
} finally {
|
|
102
|
+
try {
|
|
103
|
+
const current = JSON.parse(await readFile(lockFile, 'utf8'));
|
|
104
|
+
if (current?.pid === processLike.pid && current?.nonce === nonce) {
|
|
105
|
+
await rm(lockFile, { force: true });
|
|
106
|
+
}
|
|
107
|
+
} catch {
|
|
108
|
+
// A missing, replaced, or unreadable lock must never remove another owner.
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
};
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
|
|
6
|
+
import { withCrossProcessLock } from './cross-process-lock.js';
|
|
7
|
+
|
|
8
|
+
describe('cross-process lock', () => {
|
|
9
|
+
it('serializes concurrent critical sections', async () => {
|
|
10
|
+
const root = await mkdtemp(join(tmpdir(), 'pichamber-lock-'));
|
|
11
|
+
const lockFile = join(root, 'write.lock');
|
|
12
|
+
let releaseFirst;
|
|
13
|
+
const firstMayFinish = new Promise((resolve) => { releaseFirst = resolve; });
|
|
14
|
+
let firstEntered;
|
|
15
|
+
const firstDidEnter = new Promise((resolve) => { firstEntered = resolve; });
|
|
16
|
+
let active = 0;
|
|
17
|
+
let maximumActive = 0;
|
|
18
|
+
const enter = async (waitFor) => {
|
|
19
|
+
active += 1;
|
|
20
|
+
maximumActive = Math.max(maximumActive, active);
|
|
21
|
+
firstEntered?.();
|
|
22
|
+
await waitFor;
|
|
23
|
+
active -= 1;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const first = withCrossProcessLock(lockFile, () => enter(firstMayFinish));
|
|
27
|
+
await firstDidEnter;
|
|
28
|
+
const second = withCrossProcessLock(lockFile, () => enter(Promise.resolve()));
|
|
29
|
+
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
30
|
+
expect(maximumActive).toBe(1);
|
|
31
|
+
releaseFirst();
|
|
32
|
+
await Promise.all([first, second]);
|
|
33
|
+
expect(maximumActive).toBe(1);
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
it('does not remove a replacement lock owned by another nonce', async () => {
|
|
37
|
+
const root = await mkdtemp(join(tmpdir(), 'pichamber-lock-'));
|
|
38
|
+
const lockFile = join(root, 'owner.lock');
|
|
39
|
+
const replacement = { pid: process.pid, nonce: 'replacement-owner' };
|
|
40
|
+
await withCrossProcessLock(lockFile, async () => {
|
|
41
|
+
const claim = JSON.parse(await readFile(lockFile, 'utf8'));
|
|
42
|
+
expect(claim.pid).toBe(process.pid);
|
|
43
|
+
expect(typeof claim.nonce).toBe('string');
|
|
44
|
+
await writeFile(lockFile, JSON.stringify(replacement));
|
|
45
|
+
});
|
|
46
|
+
await expect(readFile(lockFile, 'utf8')).resolves.toBe(JSON.stringify(replacement));
|
|
47
|
+
await rm(lockFile, { force: true });
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it('reclaims a lock whose owner pid is dead', async () => {
|
|
51
|
+
const root = await mkdtemp(join(tmpdir(), 'pichamber-lock-'));
|
|
52
|
+
const lockFile = join(root, 'dead.lock');
|
|
53
|
+
const deadPid = 987_654_321;
|
|
54
|
+
await writeFile(lockFile, JSON.stringify({ pid: deadPid, nonce: 'dead-owner' }));
|
|
55
|
+
const processLike = {
|
|
56
|
+
pid: process.pid,
|
|
57
|
+
kill(pid, signal) {
|
|
58
|
+
if (pid === deadPid && signal === 0) {
|
|
59
|
+
const error = new Error('ESRCH');
|
|
60
|
+
error.code = 'ESRCH';
|
|
61
|
+
throw error;
|
|
62
|
+
}
|
|
63
|
+
return process.kill(pid, signal);
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
await expect(withCrossProcessLock(lockFile, async () => 'acquired', { processLike })).resolves.toBe('acquired');
|
|
68
|
+
await expect(readFile(lockFile, 'utf8')).rejects.toMatchObject({ code: 'ENOENT' });
|
|
69
|
+
});
|
|
70
|
+
});
|