@pi-chamber/web 0.9.8 → 0.9.9-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +8 -6
  2. package/bin/cli.test.js +7 -0
  3. package/bin/lib/DOCUMENTATION.md +1 -1
  4. package/bin/lib/cli-args.js +44 -1
  5. package/bin/lib/cli-startup.js +4 -0
  6. package/bin/lib/commands-update.js +177 -77
  7. package/bin/lib/commands-update.test.js +203 -8
  8. package/dist/assets/{DiagramView-vaGEmGJn.js → DiagramView-BCSuO0vQ.js} +1 -1
  9. package/dist/assets/{DiffView-BUOaq70P.js → DiffView-CztvzY4T.js} +1 -1
  10. package/dist/assets/{FileSaveConflictDialog-B3wIsdE1.js → FileSaveConflictDialog-DaOy8774.js} +1 -1
  11. package/dist/assets/{FilesView-DPwCE-XA.js → FilesView-e_ocd6LL.js} +1 -1
  12. package/dist/assets/{GitView-CGk98LhV.js → GitView-C2A84zfY.js} +3 -3
  13. package/dist/assets/{JsonTreeView-HNtRoqVA.js → JsonTreeView-nFCKn3bk.js} +1 -1
  14. package/dist/assets/{MarkdownRendererImpl-DUYL-Wn3.js → MarkdownRendererImpl-0nbCRN9F.js} +1 -1
  15. package/dist/assets/{PatchDiff-Bluz53zj.js → PatchDiff-TSvJHd8z.js} +1 -1
  16. package/dist/assets/{SessionSwitcherContent-DDncCwpE.js → SessionSwitcherContent-p0GEx1or.js} +1 -1
  17. package/dist/assets/{SessionSwitcherDropdown-Cw_g3ai3.js → SessionSwitcherDropdown-D1K-Lc7X.js} +2 -2
  18. package/dist/assets/{SessionUnreadDot-CT5M3-qK.js → SessionUnreadDot-kMo29jr2.js} +1 -1
  19. package/dist/assets/SettingsView-BpkV0dfi.js +2 -0
  20. package/dist/assets/{SettingsWindow-B_oA1yV4.js → SettingsWindow-CZNBrUqU.js} +1 -1
  21. package/dist/assets/{ToolOutputDialog-C3xiVDyE.js → ToolOutputDialog-B9_ymjpZ.js} +1 -1
  22. package/dist/assets/{ToolPartDiffPreview-xrxYTK3l.js → ToolPartDiffPreview-47UtQBCn.js} +1 -1
  23. package/dist/assets/{VirtualizedFileDiff-Bpgyk3yt.js → VirtualizedFileDiff-BCbGwRPY.js} +1 -1
  24. package/dist/assets/{collapsible-_urywMu5.js → collapsible-B6bVtxgp.js} +1 -1
  25. package/dist/assets/{computeVirtualFileMetrics-DPPmLfoR.js → computeVirtualFileMetrics-DbKH9gNm.js} +1 -1
  26. package/dist/assets/{contextFileOpenGuard-CV7L_UMk.js → contextFileOpenGuard-GAHxagrv.js} +1 -1
  27. package/dist/assets/{gitStatusPredicates-BTkHRMCD.js → gitStatusPredicates-D9AQuzXM.js} +1 -1
  28. package/dist/assets/{index-C3PSe3Mq.js → index-6aQ1In_D.js} +1 -1
  29. package/dist/assets/{index-CrqlVJXp.js → index-BOtRfXre.js} +3 -3
  30. package/dist/assets/{isDiffPlainText-Djb-erNZ.js → isDiffPlainText-C8SQJqjX.js} +1 -1
  31. package/dist/assets/{isFilePlainText-BQ-Wnk8C.js → isFilePlainText-YbZGouYK.js} +1 -1
  32. package/dist/assets/{main-Dpqrd5dA.js → main-CULeQoKT.js} +2 -2
  33. package/dist/assets/{main-7I7_paNp.js → main-DQPe4vbe.js} +3 -3
  34. package/dist/assets/{markdownCore-DOQQqV2i.js → markdownCore-DZMIS_FB.js} +1 -1
  35. package/dist/assets/{miniChat-b1O4Yu1o.js → miniChat-Efo5qEoa.js} +2 -2
  36. package/dist/assets/{mobile-BTpbHrim.js → mobile-CwVpqlGB.js} +2 -2
  37. package/dist/assets/{renderElectronMiniChatApp-Cisrg0Iv.js → renderElectronMiniChatApp-COsbP106.js} +2 -2
  38. package/dist/assets/{renderMobileApp-CSBtWiZ2.js → renderMobileApp-aLM7KW0X.js} +3 -3
  39. package/dist/assets/runtimeEndpointReset-DDY4b0u9.js +53 -0
  40. package/dist/assets/{runtimeSurface-C9kx2zfD.js → runtimeSurface-CPm7KWaN.js} +1 -1
  41. package/dist/assets/{useAppFontEffects-BH5qeSfx.js → useAppFontEffects-DVk3fjRp.js} +7 -7
  42. package/dist/assets/{useFilesViewSearch-Bdxwr4SZ.js → useFilesViewSearch-Chw61crV.js} +1 -1
  43. package/dist/assets/{usePushVisibilityBeacon-Czfhm8lw.js → usePushVisibilityBeacon-DfYl_CdQ.js} +1 -1
  44. package/dist/assets/{useSwitcherItems-CiTeIjW3.js → useSwitcherItems-BonWORYM.js} +1 -1
  45. package/dist/assets/{vendor-base-ui-C60wdVnS.js → vendor-base-ui-DXSHfszQ.js} +1 -1
  46. package/dist/assets/{vendor-codemirror-language-data-BhPKX-r-.js → vendor-codemirror-language-data-CpwyVWiC.js} +2 -2
  47. package/dist/assets/{vendor-floating-ui-dom-Bkw82kL9.js → vendor-floating-ui-dom-WyXykhNi.js} +1 -1
  48. package/dist/assets/{vendor-floating-ui-react-dom-KLmnYDaG.js → vendor-floating-ui-react-dom-BZOGXAGe.js} +1 -1
  49. package/dist/assets/{web-components-CuVJfuw8.js → web-components-D_W34-Mr.js} +1 -1
  50. package/dist/index.html +3 -3
  51. package/dist/mini-chat.html +2 -2
  52. package/dist/mobile.html +2 -2
  53. package/package.json +1 -1
  54. package/server/lib/package-manager.js +317 -49
  55. package/server/lib/package-manager.test.js +321 -12
  56. package/server/lib/pi/routes.js +76 -12
  57. package/server/lib/pi/routes.test.js +73 -12
  58. package/server/lib/pi/ui-settings-store.js +7 -5
  59. package/server/lib/pi/ui-settings-store.test.js +6 -4
  60. package/server/lib/terminal/DOCUMENTATION.md +1 -1
  61. package/server/lib/terminal/runtime.js +1 -1
  62. package/server/lib/terminal/runtime.test.js +1 -0
  63. package/server/lib/update-job-store.js +173 -0
  64. package/server/lib/update-job-store.test.js +179 -0
  65. package/dist/assets/SettingsView-C26Mwkzp.js +0 -2
  66. package/dist/assets/runtimeEndpointReset-sDOkJ0dT.js +0 -53
@@ -9,15 +9,19 @@ vi.mock('node:child_process', () => ({
9
9
  const {
10
10
  checkForUpdates,
11
11
  detectPackageManager,
12
+ detectSystemdServiceContext,
12
13
  executeUpdate,
13
14
  getCurrentVersion,
15
+ getInstalledVersion,
16
+ getUpdateCapability,
14
17
  launchUpdateCommand,
18
+ isInsidePiChamberSystemdService,
15
19
  resolveTrustedUpdatePackageManager,
16
20
  } = await import('./package-manager.js');
17
21
 
18
- function officialRegistryPackage(latest) {
22
+ function officialRegistryPackage(latest, rc) {
19
23
  return {
20
- 'dist-tags': { latest },
24
+ 'dist-tags': { latest, ...(rc ? { rc } : {}) },
21
25
  repository: { url: 'git+https://github.com/RyderAsKing/PiChamber.git' },
22
26
  };
23
27
  }
@@ -94,6 +98,82 @@ describe('checkForUpdates (no hosted API by default)', () => {
94
98
  });
95
99
  });
96
100
 
101
+ it('selects a newer RC when the latest stable matches the current version', async () => {
102
+ await withNoHostedApi(async () => {
103
+ fetchMock
104
+ .when('registry.npmjs.org', {
105
+ ok: true,
106
+ json: async () => officialRegistryPackage('1.9.10', '2.0.0-rc.2'),
107
+ })
108
+ .when('raw.githubusercontent.com', { ok: true, text: async () => '' });
109
+ const result = await checkForUpdates({ currentVersion: '1.9.10', channel: 'rc' });
110
+ expect(result).toMatchObject({ available: true, version: '2.0.0-rc.2', channel: 'rc' });
111
+ });
112
+ });
113
+
114
+ it('selects an RC when it is newer than the latest stable release', async () => {
115
+ await withNoHostedApi(async () => {
116
+ fetchMock
117
+ .when('registry.npmjs.org', {
118
+ ok: true,
119
+ json: async () => officialRegistryPackage('2.0.0', '2.1.0-rc.1'),
120
+ })
121
+ .when('raw.githubusercontent.com', { ok: true, text: async () => '' });
122
+ const result = await checkForUpdates({ currentVersion: '1.9.10', channel: 'rc' });
123
+ expect(result).toMatchObject({ available: true, version: '2.1.0-rc.1', channel: 'rc' });
124
+ });
125
+ });
126
+
127
+ it('selects a final stable release over its prerelease', async () => {
128
+ await withNoHostedApi(async () => {
129
+ fetchMock
130
+ .when('registry.npmjs.org', {
131
+ ok: true,
132
+ json: async () => officialRegistryPackage('2.1.0', '2.1.0-rc.2'),
133
+ })
134
+ .when('raw.githubusercontent.com', { ok: true, text: async () => '' });
135
+ const result = await checkForUpdates({ currentVersion: '1.9.10', channel: 'rc' });
136
+ expect(result).toMatchObject({ available: true, version: '2.1.0', channel: 'rc' });
137
+ });
138
+ });
139
+
140
+ it('selects stable when the RC dist-tag is older', async () => {
141
+ await withNoHostedApi(async () => {
142
+ fetchMock
143
+ .when('registry.npmjs.org', {
144
+ ok: true,
145
+ json: async () => officialRegistryPackage('2.0.0', '1.9.0-rc.5'),
146
+ })
147
+ .when('raw.githubusercontent.com', { ok: true, text: async () => '' });
148
+ const result = await checkForUpdates({ currentVersion: '1.9.10', channel: 'rc' });
149
+ expect(result).toMatchObject({ available: true, version: '2.0.0', channel: 'rc' });
150
+ });
151
+ });
152
+
153
+ it('compares numbered release candidates using semver precedence', async () => {
154
+ await withNoHostedApi(async () => {
155
+ fetchMock
156
+ .when('registry.npmjs.org', {
157
+ ok: true,
158
+ json: async () => officialRegistryPackage('1.9.10', '2.0.0-rc.10'),
159
+ })
160
+ .when('raw.githubusercontent.com', { ok: true, text: async () => '' });
161
+ const result = await checkForUpdates({ currentVersion: '2.0.0-rc.2', channel: 'rc' });
162
+ expect(result).toMatchObject({ available: true, version: '2.0.0-rc.10' });
163
+ });
164
+ });
165
+
166
+ it('keeps stable subscribers on the latest stable release', async () => {
167
+ await withNoHostedApi(async () => {
168
+ fetchMock.when('registry.npmjs.org', {
169
+ ok: true,
170
+ json: async () => officialRegistryPackage('1.9.10', '2.0.0-rc.1'),
171
+ });
172
+ const result = await checkForUpdates({ currentVersion: '1.9.10', channel: 'stable' });
173
+ expect(result).toMatchObject({ available: false, version: '1.9.10', channel: 'stable' });
174
+ });
175
+ });
176
+
97
177
  it('returns available=false when npm `latest` matches current version', async () => {
98
178
  await withNoHostedApi(async () => {
99
179
  fetchMock.when('registry.npmjs.org', {
@@ -175,6 +255,8 @@ describe('checkForUpdates (no hosted API by default)', () => {
175
255
  expect(result.version).toBe('1.11.0');
176
256
  const urls = fetchMock.calls.map((c) => c.url);
177
257
  expect(urls.some((u) => u.includes('updates.example.test'))).toBe(true);
258
+ const hostedCall = fetchMock.calls.find((call) => call.url.includes('updates.example.test'));
259
+ expect(JSON.parse(hostedCall.options.body)).toMatchObject({ channel: 'stable' });
178
260
  expect(urls.some((u) => u.includes('api.pichamber.dev'))).toBe(false);
179
261
  } finally {
180
262
  if (typeof previous === 'string') {
@@ -185,6 +267,36 @@ describe('checkForUpdates (no hosted API by default)', () => {
185
267
  }
186
268
  });
187
269
 
270
+ it('requests hosted notes for the higher RC target', async () => {
271
+ const previous = process.env.PICHAMBER_UPDATE_API_URL;
272
+ process.env.PICHAMBER_UPDATE_API_URL = 'https://updates.example.test/api/check';
273
+ try {
274
+ fetchMock
275
+ .when('updates.example.test', {
276
+ ok: true,
277
+ json: async () => ({
278
+ latestVersion: '2.1.0-rc.1',
279
+ updateAvailable: true,
280
+ }),
281
+ })
282
+ .when('registry.npmjs.org', {
283
+ ok: true,
284
+ json: async () => officialRegistryPackage('2.0.0', '2.1.0-rc.1'),
285
+ });
286
+
287
+ const result = await checkForUpdates({ currentVersion: '1.9.10', channel: 'rc' });
288
+ expect(result).toMatchObject({ available: true, version: '2.1.0-rc.1', channel: 'rc' });
289
+ const hostedCall = fetchMock.calls.find((call) => call.url.includes('updates.example.test'));
290
+ expect(JSON.parse(hostedCall.options.body)).toMatchObject({ channel: 'rc' });
291
+ } finally {
292
+ if (typeof previous === 'string') {
293
+ process.env.PICHAMBER_UPDATE_API_URL = previous;
294
+ } else {
295
+ delete process.env.PICHAMBER_UPDATE_API_URL;
296
+ }
297
+ }
298
+ });
299
+
188
300
  it('ignores a configured hosted update that disagrees with npm latest', async () => {
189
301
  const previous = process.env.PICHAMBER_UPDATE_API_URL;
190
302
  process.env.PICHAMBER_UPDATE_API_URL = 'https://updates.example.test/api/check';
@@ -360,27 +472,216 @@ describe('package-manager ownership detection', () => {
360
472
  describe('getCurrentVersion', () => {
361
473
  it('is exported for the CLI update command', () => {
362
474
  expect(typeof getCurrentVersion).toBe('function');
475
+ expect(typeof getInstalledVersion).toBe('function');
363
476
  expect(getCurrentVersion()).toMatch(/^\d+\.\d+\.\d+|unknown$/);
364
477
  });
365
478
  });
366
479
 
480
+ describe('update capability reporting', () => {
481
+ const trustedDetails = {
482
+ packageManager: 'npm',
483
+ reason: 'install-path-owner',
484
+ packagePath: '/home/test/node_modules/@pi-chamber/web',
485
+ globalNodeModulesRoot: '/home/test/node_modules',
486
+ };
487
+
488
+ it('gives deployment-specific instructions for containers and source checkouts', () => {
489
+ expect(getUpdateCapability({ isContainer: true })).toMatchObject({
490
+ supported: false,
491
+ code: 'DOCKER_DEPLOYMENT',
492
+ });
493
+ expect(getUpdateCapability({
494
+ isContainer: false,
495
+ packagePath: '/work/PiChamber/packages/web',
496
+ existsSync: (candidate) => ['/work/PiChamber/package.json', '/work/PiChamber/packages/ui'].includes(candidate),
497
+ systemdContext: null,
498
+ })).toMatchObject({
499
+ supported: false,
500
+ code: 'SOURCE_CHECKOUT',
501
+ });
502
+ });
503
+
504
+ it('reports the exact custom user unit and restart command for servers and browser terminals', () => {
505
+ const contextOptions = {
506
+ platform: 'linux',
507
+ env: {},
508
+ readFileSync: () => '0::/user.slice/user-1000.slice/user@1000.service/app.slice/my-pichamber.service',
509
+ };
510
+ expect(detectSystemdServiceContext(contextOptions)).toEqual({
511
+ unit: 'my-pichamber.service',
512
+ scope: 'user',
513
+ managed: false,
514
+ });
515
+ const capability = getUpdateCapability({
516
+ ...contextOptions,
517
+ isContainer: false,
518
+ serverProcess: true,
519
+ packagePath: trustedDetails.packagePath,
520
+ details: trustedDetails,
521
+ installWritable: true,
522
+ });
523
+ expect(capability).toMatchObject({ supported: false, code: 'CUSTOM_SYSTEMD_UNIT' });
524
+ expect(capability.error).toContain('systemctl --user restart my-pichamber.service');
525
+ });
526
+
527
+ it('ignores ancestor user-manager services when the process belongs to a session scope', () => {
528
+ expect(detectSystemdServiceContext({
529
+ platform: 'linux',
530
+ env: {},
531
+ readFileSync: () => '0::/user.slice/user-1000.slice/user@1000.service/session.slice/session-2.scope',
532
+ })).toBeNull();
533
+ });
534
+
535
+ it('does not mistake an ordinary SSH service for a custom PiChamber deployment', () => {
536
+ expect(getUpdateCapability({
537
+ isContainer: false,
538
+ serverProcess: false,
539
+ platform: 'linux',
540
+ env: { INVOCATION_ID: 'ssh-invocation' },
541
+ readFileSync: () => '0::/system.slice/ssh.service',
542
+ packagePath: trustedDetails.packagePath,
543
+ details: trustedDetails,
544
+ installWritable: true,
545
+ })).toEqual({ supported: true, code: 'SUPPORTED', packageManager: 'npm' });
546
+ });
547
+
548
+ it('distinguishes ownership failures from unsupported installs', () => {
549
+ expect(getUpdateCapability({
550
+ isContainer: false,
551
+ systemdContext: null,
552
+ packagePath: trustedDetails.packagePath,
553
+ details: trustedDetails,
554
+ installWritable: false,
555
+ })).toMatchObject({ supported: false, code: 'INSTALL_OWNERSHIP_MISMATCH' });
556
+ expect(getUpdateCapability({
557
+ isContainer: false,
558
+ systemdContext: null,
559
+ packagePath: '/temporary/pichamber',
560
+ existsSync: () => false,
561
+ details: { packageManager: 'npm', reason: 'default-fallback' },
562
+ })).toMatchObject({ supported: false, code: 'UNSUPPORTED_INSTALL' });
563
+ });
564
+ });
565
+
367
566
  describe('launchUpdateCommand', () => {
368
- it('starts the CLI updater detached so the live server can respond before shutdown', () => {
369
- const unref = vi.fn();
370
- const spawnProcess = vi.fn(() => ({ unref }));
567
+ const job = { id: '10000000-0000-4000-8000-000000000001', state: 'queued' };
568
+ const jobOptions = () => ({
569
+ claimUpdateJob: vi.fn(async () => ({ job, created: true })),
570
+ updateUpdateJob: vi.fn(async () => job),
571
+ });
371
572
 
372
- expect(launchUpdateCommand({ isContainer: false, isSystemd: false, spawnProcess })).toEqual({ success: true });
573
+ it('starts the CLI updater detached so the live server can respond before shutdown', async () => {
574
+ const unref = vi.fn();
575
+ const once = vi.fn();
576
+ const spawnProcess = vi.fn(() => ({ once, unref }));
577
+
578
+ await expect(launchUpdateCommand({
579
+ isContainer: false,
580
+ isSystemd: false,
581
+ spawnProcess,
582
+ ...jobOptions(),
583
+ })).resolves.toMatchObject({ success: true, jobId: job.id, state: 'queued' });
373
584
  expect(spawnProcess).toHaveBeenCalledWith(
374
585
  process.execPath,
375
- [expect.stringMatching(/bin[\\/]cli\.js$/), 'update', '--quiet'],
586
+ [expect.stringMatching(/bin[\\/]cli\.js$/), 'update', '--yes', '--quiet', '--update-worker', '--update-job-id', job.id],
376
587
  { detached: true, stdio: 'ignore', windowsHide: true },
377
588
  );
589
+ expect(once).toHaveBeenCalledWith('error', expect.any(Function));
378
590
  expect(unref).toHaveBeenCalledOnce();
379
591
  });
380
592
 
381
- it('refuses deployment types that the CLI cannot safely replace in-process', () => {
382
- expect(launchUpdateCommand({ isContainer: true, isSystemd: false }).success).toBe(false);
383
- expect(launchUpdateCommand({ isContainer: false, isSystemd: true }).success).toBe(false);
593
+ it('pins the selected channel and target in the worker job', async () => {
594
+ const options = jobOptions();
595
+ await launchUpdateCommand({
596
+ isContainer: false,
597
+ isSystemd: false,
598
+ targetVersion: '2.0.0-rc.3',
599
+ channel: 'rc',
600
+ spawnProcess: () => ({ once: vi.fn(), unref: vi.fn() }),
601
+ ...options,
602
+ });
603
+ expect(options.claimUpdateJob).toHaveBeenCalledWith(expect.objectContaining({
604
+ targetVersion: '2.0.0-rc.3',
605
+ channel: 'rc',
606
+ }));
607
+ });
608
+
609
+ it('starts a transient worker outside the PiChamber systemd unit', async () => {
610
+ const runProcess = vi.fn(() => ({ status: 0 }));
611
+
612
+ await expect(launchUpdateCommand({
613
+ isContainer: false,
614
+ isSystemd: true,
615
+ isRoot: false,
616
+ runProcess,
617
+ env: {
618
+ HOME: '/home/test',
619
+ PATH: '/test/bin',
620
+ PICHAMBER_DATA_DIR: '/home/test/.config/pichamber',
621
+ PICHAMBER_PACKAGE_MANAGER: 'npm',
622
+ PICHAMBER_UI_PASSWORD: 'must-not-be-forwarded',
623
+ },
624
+ ...jobOptions(),
625
+ })).resolves.toMatchObject({ success: true, jobId: job.id });
626
+
627
+ expect(runProcess).toHaveBeenCalledWith(
628
+ 'systemd-run',
629
+ expect.arrayContaining([
630
+ '--user',
631
+ expect.stringMatching(/^--unit=pichamber-update-/),
632
+ '--collect',
633
+ '--setenv=PICHAMBER_PACKAGE_MANAGER=npm',
634
+ '--',
635
+ process.execPath,
636
+ expect.stringMatching(/bin[\\/]cli\.js$/),
637
+ 'update',
638
+ '--update-worker',
639
+ '--update-job-id',
640
+ job.id,
641
+ ]),
642
+ expect.objectContaining({ stdio: 'pipe' }),
643
+ );
644
+ expect(runProcess.mock.calls[0][1].join(' ')).not.toContain('must-not-be-forwarded');
645
+ });
646
+
647
+ it('records a failed job when systemd cannot start the worker', async () => {
648
+ const updateUpdateJob = vi.fn(async () => job);
649
+ const result = await launchUpdateCommand({
650
+ isContainer: false,
651
+ isSystemd: true,
652
+ runProcess: () => ({ status: 1 }),
653
+ ...jobOptions(),
654
+ updateUpdateJob,
655
+ });
656
+
657
+ expect(result).toMatchObject({ success: false, jobId: job.id });
658
+ expect(updateUpdateJob).toHaveBeenCalledWith(job.id, expect.objectContaining({ state: 'failed' }));
659
+ });
660
+
661
+ it('refuses container replacement without creating a job', async () => {
662
+ await expect(launchUpdateCommand({ isContainer: true })).resolves.toMatchObject({ success: false });
663
+ });
664
+ });
665
+
666
+ describe('isInsidePiChamberSystemdService', () => {
667
+ it('does not treat a generic systemd invocation such as SSH as PiChamber-owned', () => {
668
+ expect(isInsidePiChamberSystemdService({
669
+ platform: 'linux',
670
+ env: { INVOCATION_ID: 'ssh-service-invocation' },
671
+ readFileSync: () => '0::/system.slice/ssh.service',
672
+ })).toBe(false);
673
+ });
674
+
675
+ it('recognizes generated units and their child terminals', () => {
676
+ expect(isInsidePiChamberSystemdService({
677
+ platform: 'linux',
678
+ env: { PICHAMBER_SYSTEMD_UNIT: 'pichamber.service' },
679
+ })).toBe(true);
680
+ expect(isInsidePiChamberSystemdService({
681
+ platform: 'linux',
682
+ env: {},
683
+ readFileSync: () => '0::/user.slice/user-1000.slice/user@1000.service/app.slice/pichamber.service',
684
+ })).toBe(true);
384
685
  });
385
686
  });
386
687
 
@@ -395,12 +696,20 @@ describe('CLI update exports', () => {
395
696
  const { spawnSync } = await import('node:child_process');
396
697
  spawnSync.mockClear();
397
698
 
398
- expect(executeUpdate('npm', { silent: true })).toEqual({ success: true, exitCode: 0 });
699
+ expect(executeUpdate('npm', { silent: true, targetVersion: '2.0.0-rc.3' })).toEqual({ success: true, exitCode: 0 });
399
700
  expect(spawnSync).toHaveBeenLastCalledWith(
400
- expect.stringContaining('@pi-chamber/web@latest'),
701
+ expect.stringContaining('@pi-chamber/web@2.0.0-rc.3'),
401
702
  expect.objectContaining({ shell: true, stdio: 'ignore' }),
402
703
  );
403
704
  });
705
+
706
+ it('rejects an unsafe package target before spawning a package manager', async () => {
707
+ const { spawnSync } = await import('node:child_process');
708
+ spawnSync.mockClear();
709
+ expect(() => executeUpdate('npm', { silent: true, targetVersion: 'latest; touch /tmp/nope' }))
710
+ .toThrow('Update target version is invalid.');
711
+ expect(spawnSync).not.toHaveBeenCalled();
712
+ });
404
713
  });
405
714
 
406
715
  describe('resolveTrustedUpdatePackageManager', () => {
@@ -7,10 +7,13 @@ import { createPiArchiveStore } from './archive-store.js';
7
7
  import { createPiAttachmentStore } from './attachment-store.js';
8
8
  import {
9
9
  checkForUpdates,
10
+ getCurrentVersion,
11
+ getUpdateCapability,
10
12
  launchUpdateCommand,
11
- resolveTrustedUpdatePackageManager,
13
+ normalizeServerUpdateChannel,
12
14
  } from '../package-manager.js';
13
15
  import { listPiCustomThemes } from './custom-themes.js';
16
+ import { readUpdateJob } from '../update-job-store.js';
14
17
  import { createPiSettingsStore } from './settings-store.js';
15
18
  import { isPiThinkingLevel } from './thinking-levels.js';
16
19
  import { createPiSessionFoldersStore } from './session-folders-store.js';
@@ -823,7 +826,9 @@ export const registerPiRuntimeRoutes = (app, {
823
826
  listCustomThemes = listPiCustomThemes,
824
827
  updateChecker = checkForUpdates,
825
828
  updateLauncher = launchUpdateCommand,
826
- resolveUpdatePackageManager = resolveTrustedUpdatePackageManager,
829
+ currentVersionReader = getCurrentVersion,
830
+ updateJobReader = readUpdateJob,
831
+ updateCapabilityResolver = getUpdateCapability,
827
832
  smallModelGenerator = async (input) => (await import('./small-model-generation.js')).generateWithSmallModel(input),
828
833
  eventHeartbeatMs = 15_000,
829
834
  eventStreamMaxBufferedBytes = DEFAULT_EVENT_STREAM_MAX_BUFFERED_BYTES,
@@ -873,35 +878,94 @@ export const registerPiRuntimeRoutes = (app, {
873
878
  }
874
879
  });
875
880
 
881
+ const readServerUpdateChannel = async () => {
882
+ const settings = await uiSettingsStore.read();
883
+ return normalizeServerUpdateChannel(settings.serverUpdateChannel);
884
+ };
885
+
876
886
  app.get('/api/pi/update-check', async (req, res) => {
877
887
  try {
888
+ const appType = typeof req.query.appType === 'string' ? req.query.appType : undefined;
889
+ const channel = appType === undefined || appType === 'web'
890
+ ? await readServerUpdateChannel()
891
+ : 'stable';
878
892
  res.json(await updateChecker({
879
893
  currentVersion: typeof req.query.currentVersion === 'string' ? req.query.currentVersion : undefined,
880
- appType: typeof req.query.appType === 'string' ? req.query.appType : undefined,
894
+ appType,
895
+ deviceClass: typeof req.query.deviceClass === 'string' ? req.query.deviceClass : undefined,
896
+ arch: typeof req.query.arch === 'string' ? req.query.arch : undefined,
881
897
  platform: typeof req.query.platform === 'string' ? req.query.platform : undefined,
882
898
  instanceMode: typeof req.query.instanceMode === 'string' ? req.query.instanceMode : undefined,
899
+ channel,
883
900
  }));
884
901
  } catch {
885
902
  res.status(503).json({ error: 'Update check unavailable' });
886
903
  }
887
904
  });
888
905
 
889
- app.post('/api/pi/update-install', (_req, res) => {
890
- const packageManager = resolveUpdatePackageManager();
891
- if (!packageManager) {
906
+ app.post('/api/pi/update-install', async (_req, res) => {
907
+ const capability = updateCapabilityResolver({ serverProcess: true });
908
+ if (!capability.supported) {
892
909
  res.status(409).json({
893
910
  success: false,
894
- error: 'This PiChamber copy is not a supported global package-manager install. Run: pichamber update',
911
+ code: capability.code,
912
+ error: capability.error,
913
+ commands: capability.commands || [],
895
914
  });
896
915
  return;
897
916
  }
898
917
 
899
- const result = updateLauncher();
900
- if (!result.success) {
901
- res.status(409).json({ success: false, error: result.error });
902
- return;
918
+ try {
919
+ const previousVersion = currentVersionReader();
920
+ const channel = await readServerUpdateChannel();
921
+ const updateInfo = await updateChecker({
922
+ currentVersion: previousVersion,
923
+ appType: 'web',
924
+ instanceMode: 'server',
925
+ channel,
926
+ });
927
+ if (updateInfo.error) {
928
+ res.status(503).json({ success: false, error: updateInfo.error });
929
+ return;
930
+ }
931
+ if (!updateInfo.available || typeof updateInfo.version !== 'string') {
932
+ res.status(409).json({ success: false, code: 'UP_TO_DATE', error: 'This PiChamber server is already up to date.', commands: [] });
933
+ return;
934
+ }
935
+ const result = await updateLauncher({
936
+ packageManager: capability.packageManager,
937
+ previousVersion,
938
+ targetVersion: updateInfo.version,
939
+ channel,
940
+ });
941
+ if (!result.success) {
942
+ res.status(409).json({ success: false, jobId: result.jobId, error: result.error });
943
+ return;
944
+ }
945
+ res.status(result.existing ? 200 : 202).json({
946
+ success: true,
947
+ autoRestart: true,
948
+ jobId: result.jobId,
949
+ state: result.state,
950
+ channel: result.channel || channel,
951
+ targetVersion: result.targetVersion || updateInfo.version,
952
+ });
953
+ } catch {
954
+ res.status(500).json({ success: false, error: 'Could not start the updater. Run: pichamber update' });
955
+ }
956
+ });
957
+
958
+ app.get('/api/pi/update-install/:jobId', async (req, res) => {
959
+ try {
960
+ const job = await updateJobReader(req.params.jobId);
961
+ if (!job) {
962
+ res.status(404).json({ error: 'Update job was not found' });
963
+ return;
964
+ }
965
+ res.json(job);
966
+ } catch {
967
+ res.status(503).json({ error: 'Update status is unavailable' });
903
968
  }
904
- res.json({ success: true, autoRestart: true });
905
969
  });
906
970
 
907
971
  app.get('/api/pi/runtime', async (_req, res) => {
@@ -1,4 +1,4 @@
1
- import { afterEach, describe, expect, it } from 'vitest';
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
2
  import express from 'express';
3
3
 
4
4
  import { projectEventFrame, registerPiRuntimeRoutes } from './routes.js';
@@ -118,8 +118,16 @@ describe('Pi runtime route', () => {
118
118
  });
119
119
 
120
120
  it('serves PiChamber UI settings, session folders, custom themes, and update metadata without removed routes', async () => {
121
- let settings = { themeMode: 'dark' };
121
+ let settings = { themeMode: 'dark', serverUpdateChannel: 'rc' };
122
122
  let sessionFolders = { exists: false };
123
+ const updateChecker = vi.fn(async (options) => options.instanceMode === 'server'
124
+ ? { available: true, currentVersion: '1.0.0', version: '1.1.0-rc.2', channel: 'rc' }
125
+ : { available: false, currentVersion: '1.0.0', channel: options.channel });
126
+ const updateLauncher = vi.fn(() => ({
127
+ success: true,
128
+ jobId: '10000000-0000-4000-8000-000000000001',
129
+ state: 'queued',
130
+ }));
123
131
  const app = express();
124
132
  app.use(express.json());
125
133
  registerPiRuntimeRoutes(app, {
@@ -133,33 +141,84 @@ describe('Pi runtime route', () => {
133
141
  write: async (snapshot) => (sessionFolders = { exists: true, ...snapshot }),
134
142
  },
135
143
  listCustomThemes: async () => [{ metadata: { id: 'custom' } }],
136
- updateChecker: async () => ({ available: false, currentVersion: '1.0.0' }),
137
- resolveUpdatePackageManager: () => 'npm',
138
- updateLauncher: () => ({ success: true }),
144
+ updateChecker,
145
+ updateCapabilityResolver: () => ({ supported: true, code: 'SUPPORTED', packageManager: 'npm' }),
146
+ updateLauncher,
147
+ updateJobReader: async (id) => ({ id, state: 'installing', startedAt: 1, updatedAt: 2 }),
139
148
  });
140
149
  server = await listen(app);
141
150
  const base = `http://127.0.0.1:${server.address().port}`;
142
151
 
143
- await expect((await fetch(`${base}/api/pi/ui-settings`)).json()).resolves.toEqual({ themeMode: 'dark' });
152
+ await expect((await fetch(`${base}/api/pi/ui-settings`)).json()).resolves.toEqual({ themeMode: 'dark', serverUpdateChannel: 'rc' });
144
153
  await expect((await fetch(`${base}/api/pi/ui-settings`, {
145
154
  method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ language: 'en' }),
146
- })).json()).resolves.toEqual({ themeMode: 'dark', language: 'en' });
155
+ })).json()).resolves.toEqual({ themeMode: 'dark', serverUpdateChannel: 'rc', language: 'en' });
147
156
  await expect((await fetch(`${base}/api/pi/session-folders`)).json()).resolves.toEqual({ exists: false });
148
157
  await expect((await fetch(`${base}/api/pi/session-folders`, {
149
158
  method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ version: 1, foldersMap: {}, collapsedFolderIds: [], updatedAt: 1 }),
150
159
  })).json()).resolves.toEqual({ exists: true, version: 1, foldersMap: {}, collapsedFolderIds: [], updatedAt: 1 });
151
160
  await expect((await fetch(`${base}/api/pi/themes`)).json()).resolves.toEqual({ themes: [{ metadata: { id: 'custom' } }] });
152
- await expect((await fetch(`${base}/api/pi/update-check`)).json()).resolves.toEqual({ available: false, currentVersion: '1.0.0' });
161
+ await expect((await fetch(`${base}/api/pi/update-check?appType=web`)).json()).resolves.toEqual({ available: false, currentVersion: '1.0.0', channel: 'rc' });
162
+ await expect((await fetch(`${base}/api/pi/update-check?appType=mobile-capacitor`)).json()).resolves.toEqual({ available: false, currentVersion: '1.0.0', channel: 'stable' });
153
163
  const installResponse = await fetch(`${base}/api/pi/update-install`, { method: 'POST' });
154
- expect(installResponse.status).toBe(200);
155
- await expect(installResponse.json()).resolves.toEqual({ success: true, autoRestart: true });
164
+ expect(installResponse.status).toBe(202);
165
+ await expect(installResponse.json()).resolves.toEqual({
166
+ success: true,
167
+ autoRestart: true,
168
+ jobId: '10000000-0000-4000-8000-000000000001',
169
+ state: 'queued',
170
+ channel: 'rc',
171
+ targetVersion: '1.1.0-rc.2',
172
+ });
173
+ expect(updateChecker).toHaveBeenCalledWith(expect.objectContaining({ channel: 'rc', instanceMode: 'server' }));
174
+ expect(updateLauncher).toHaveBeenCalledWith(expect.objectContaining({
175
+ channel: 'rc',
176
+ targetVersion: '1.1.0-rc.2',
177
+ }));
178
+ const statusResponse = await fetch(`${base}/api/pi/update-install/10000000-0000-4000-8000-000000000001`);
179
+ expect(statusResponse.status).toBe(200);
180
+ await expect(statusResponse.json()).resolves.toMatchObject({ state: 'installing' });
181
+ });
182
+
183
+ it('returns updater launch failures and missing job status explicitly', async () => {
184
+ const app = express();
185
+ registerPiRuntimeRoutes(app, {
186
+ getPiSessionDaemonRuntime: () => null,
187
+ updateCapabilityResolver: () => ({ supported: true, code: 'SUPPORTED', packageManager: 'npm' }),
188
+ currentVersionReader: () => '1.0.0',
189
+ uiSettingsStore: { read: async () => ({ serverUpdateChannel: 'stable' }), write: async () => ({}) },
190
+ updateChecker: async () => ({ available: true, version: '2.0.0', currentVersion: '1.0.0', channel: 'stable' }),
191
+ updateLauncher: async (options) => ({
192
+ success: false,
193
+ jobId: '10000000-0000-4000-8000-000000000001',
194
+ error: `Could not start ${options.packageManager} updater for ${options.previousVersion}`,
195
+ }),
196
+ updateJobReader: async () => null,
197
+ });
198
+ server = await listen(app);
199
+ const base = `http://127.0.0.1:${server.address().port}`;
200
+
201
+ const installResponse = await fetch(`${base}/api/pi/update-install`, { method: 'POST' });
202
+ expect(installResponse.status).toBe(409);
203
+ await expect(installResponse.json()).resolves.toMatchObject({
204
+ success: false,
205
+ jobId: '10000000-0000-4000-8000-000000000001',
206
+ error: 'Could not start npm updater for 1.0.0',
207
+ });
208
+
209
+ const statusResponse = await fetch(`${base}/api/pi/update-install/10000000-0000-4000-8000-000000000001`);
210
+ expect(statusResponse.status).toBe(404);
156
211
  });
157
212
 
158
213
  it('rejects web updates when the current install is not owned by a trusted package manager', async () => {
159
214
  const app = express();
160
215
  registerPiRuntimeRoutes(app, {
161
216
  getPiSessionDaemonRuntime: () => null,
162
- resolveUpdatePackageManager: () => null,
217
+ updateCapabilityResolver: () => ({
218
+ supported: false,
219
+ code: 'UNSUPPORTED_INSTALL',
220
+ error: 'This PiChamber copy is not a supported global package-manager install.',
221
+ }),
163
222
  updateLauncher: () => { throw new Error('must not run'); },
164
223
  });
165
224
  server = await listen(app);
@@ -168,7 +227,9 @@ describe('Pi runtime route', () => {
168
227
  expect(response.status).toBe(409);
169
228
  await expect(response.json()).resolves.toEqual({
170
229
  success: false,
171
- error: 'This PiChamber copy is not a supported global package-manager install. Run: pichamber update',
230
+ code: 'UNSUPPORTED_INSTALL',
231
+ error: 'This PiChamber copy is not a supported global package-manager install.',
232
+ commands: [],
172
233
  });
173
234
  });
174
235