@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
package/README.md CHANGED
@@ -39,7 +39,7 @@ tunnels, logs, pairing, and machine-readable output.
39
39
 
40
40
  - Pi session state and actions are served only through `/api/pi/*`. Session detail responses carry a bounded transcript tail; older history is available from `GET /api/pi/sessions/:sessionId/messages` with the opaque before-cursor returned by the previous page.
41
41
  - `POST /api/pi/attachments` accepts raw `application/octet-stream` bodies with bounded `X-PiChamber-Filename` and `X-PiChamber-Mime` metadata. It returns opaque attachment metadata plus `expiresAt`; filesystem paths remain private. The legacy base64 JSON body remains available for persisted clients. `DELETE /api/pi/attachments/:id` removes an unused upload. Prompt routes accept at most 20 attachment IDs and retire accepted uploads from the active 32-upload map while retaining their files until the one-hour expiry.
42
- - PiChamber-owned UI settings, snippets, custom themes, and updates use `/api/pi/ui-settings`, `/api/pi/snippets`, `/api/pi/themes`, `/api/pi/update-check`, and `/api/pi/update-install`. The settings route merges portable preferences from `settings.json` with host and device values from `runtime-state.json`; writes split fields through explicit allowlists. The Electron update-channel subscription is host-local, accepts only `stable` or `rc`, and defaults to `stable`. Pi-owned resource, trust, and provider-catalog changes are saved without interrupting active sessions and report deferred runtime activation when an idle edge is required. A flat legacy file migrates on first access. A scoped portable file never contributes paths, project registrations, device values, or secrets. Removed `/api/config/*` and `/api/pichamber/*` aliases are not required. Snippets persist in the PiChamber data root (`snippets.json`) and expand through literal `#name` replacement; Pi prompt templates remain Pi-owned `/name` commands in Pi's global and trusted-project prompt directories, discovered through the active runtime's resource loader and exposed through `/api/pi/resources`, `/api/pi/resources/prompts`, and `/api/pi/commands`. Pi skills invoke as `/skill:name` (bare `/name` never invokes a skill) and extension commands use their registered `/name` (including Pi-generated suffixes); `/api/pi/commands` exposes prompts as `name`, skills as `skill:name`, and extensions under their invocation names, executed via Pi's `session.prompt()` with extension-first precedence. Snippet, prompt-template, skill, and extension-command concepts stay distinct with separate Settings pages, stores, persistence, and caches; they share only `/` autocomplete presentation. New-session starters are pinned Pi prompt templates that insert `/name ` for editing (never submit or expand in PiChamber); legacy skill starters are removed without conversion.
42
+ - PiChamber-owned UI settings, snippets, custom themes, and updates use `/api/pi/ui-settings`, `/api/pi/snippets`, `/api/pi/themes`, `/api/pi/update-check`, `/api/pi/update-install`, and `/api/pi/update-install/:jobId`. Starting an update returns a persisted job ID; clients poll that job on the originating server across its restart, and concurrent requests reuse the active job. Polling stops if the client switches servers. Lost authentication leaves the outcome unknown until the client reauthenticates. For older servers without update jobs, fallback version polling reports version-check errors instead of treating them as successful updates. Status reads fail abandoned jobs after a bounded startup grace period or when the recorded worker exits. The settings route merges portable preferences from `settings.json` with host and device values from `runtime-state.json`; writes split fields through explicit allowlists. Electron and server update-channel subscriptions are separate host-local fields, each accepts only `stable` or `rc`, and each defaults to `stable`. The server RC channel compares `latest` and `rc` and selects the higher version; update jobs pin the selected version so restart or a moving dist-tag cannot change their target. Pi-owned resource, trust, and provider-catalog changes are saved without interrupting active sessions and report deferred runtime activation when an idle edge is required. A flat legacy file migrates on first access. A scoped portable file never contributes paths, project registrations, device values, or secrets. Removed `/api/config/*` and `/api/pichamber/*` aliases are not required. Snippets persist in the PiChamber data root (`snippets.json`) and expand through literal `#name` replacement; Pi prompt templates remain Pi-owned `/name` commands in Pi's global and trusted-project prompt directories, discovered through the active runtime's resource loader and exposed through `/api/pi/resources`, `/api/pi/resources/prompts`, and `/api/pi/commands`. Pi skills invoke as `/skill:name` (bare `/name` never invokes a skill) and extension commands use their registered `/name` (including Pi-generated suffixes); `/api/pi/commands` exposes prompts as `name`, skills as `skill:name`, and extensions under their invocation names, executed via Pi's `session.prompt()` with extension-first precedence. Snippet, prompt-template, skill, and extension-command concepts stay distinct with separate Settings pages, stores, persistence, and caches; they share only `/` autocomplete presentation. New-session starters are pinned Pi prompt templates that insert `/name ` for editing (never submit or expand in PiChamber); legacy skill starters are removed without conversion.
43
43
  - Final-only speech-to-text uses authenticated `/api/stt/*` routes and `/api/stt/ws`. Local model inference runs in a forked worker, while remote provider credentials remain in server configuration.
44
44
  - Browser and paired clients authenticate with UI sessions or scoped client credentials.
45
45
  - `connect-url` creates a one-time pairing link; credentials are not written to URLs or logs.
@@ -54,11 +54,13 @@ and overrides still apply to the updated catalog. If a saved default points to a
54
54
  removed model, select an available replacement; the upgrade does not rewrite
55
55
  your saved defaults or chat history.
56
56
 
57
- Restart the PiChamber server after updating. The normal update command restarts
58
- managed background instances; foreground instances must be stopped and started
59
- manually. Desktop users must relaunch the updated app. Hosted and mobile clients
60
- use their connected server's SDK, so updating only the client does not update its
61
- model catalog.
57
+ The normal update command restarts managed background instances. Linux servers
58
+ configured by `pichamber startup enable` run updates in a transient systemd unit,
59
+ so terminal and in-app updates survive the server restart and report status after
60
+ clients reconnect. Foreground instances must be stopped and started manually.
61
+ Desktop users must relaunch the updated app. Hosted and mobile clients use their
62
+ connected server's SDK, so updating only the client does not update its model
63
+ catalog.
62
64
 
63
65
  ## Development
64
66
 
package/bin/cli.test.js CHANGED
@@ -321,6 +321,13 @@ describe('cli args', () => {
321
321
  expect(parseArgs([]).explicitCommand).toBe(false);
322
322
  expect(parseArgs(['update', '--yes']).options.yes).toBe(true);
323
323
  expect(parseArgs(['update', '-y']).options.yes).toBe(true);
324
+ expect(parseArgs(['update', '--channel', 'rc']).options.channel).toBe('rc');
325
+ expect(() => parseArgs(['update', '--channel', 'nightly'])).toThrow(/stable or rc/);
326
+ expect(() => parseArgs(['serve', '--channel', 'rc'])).toThrow(/only be used with pichamber update/);
327
+ expect(parseArgs(['update', '--update-worker', '--update-job-id', 'job-id']).options).toMatchObject({
328
+ updateWorker: true,
329
+ updateJobId: 'job-id',
330
+ });
324
331
  });
325
332
 
326
333
  it('rejects invalid log line counts instead of silently using the default', () => {
@@ -11,7 +11,7 @@ This directory contains non-entrypoint PiChamber CLI implementation. `../cli.js`
11
11
  - `commands-startup.js`: native startup service management. Interactive `startup enable` walks through access, port, authentication, and confirmation when no setup flags are supplied. Flag-driven, non-TTY, `--quiet`, and `--json` runs remain non-interactive. The command stores serve flags (`--port`, `--lan`/`--host`, `--ui-password`, `--api-only`) in the native service. Re-running enable rewrites and restarts a systemd unit so the new settings take effect immediately. LAN binds require a UI password, matching `pichamber serve`.
12
12
  - `commands-connect-url.js`: authenticated direct/relay pairing links. Auto-started servers run silently inside the command; `--json` and non-TTY output contain only the requested machine-readable/link result, and QR art is interactive-terminal-only.
13
13
  - `pichamber version` and `pichamber --version`: print the installed package version; `--json` returns the same value as JSON.
14
- - `commands-update.js`: package update and restart coordination. Interactive updates review the old and target versions and restart impact before installation; `--yes` skips confirmation. Updates only a global install owned by the running CLI. Package-manager output is suppressed for `--quiet`/`--json`; results distinguish the previous, installed, and latest versions and report partial restart failures with a non-zero CLI exit. A Linux user systemd unit is restarted in place; the command does not spawn a replacement server on the same port.
14
+ - `commands-update.js`: package update and restart coordination. Interactive updates review the old and target versions, selected server channel, and restart impact before installation; `--yes` skips confirmation. The host-local default channel is `stable`; `--channel stable|rc` overrides it for one run, and RC subscribers receive the highest available version across stable and numbered RC releases. Updates only a writable global install owned by the running CLI. Deployment preflight reports stable reason codes and instructions for containers, source checkouts, custom systemd units, ownership mismatches, and unsupported installs before changing files. Package-manager output is suppressed for `--quiet`/`--json`; results distinguish the previous, installed, and latest versions and report partial restart failures with a non-zero CLI exit. An update requested from the managed PiChamber systemd service, including its browser terminal, moves into a transient systemd unit before replacing the package and restarting `pichamber.service`. Update jobs persist non-secret progress, channel, and an exact registry-validated target version in the PiChamber run directory so clients can resume status polling after restart without a moving dist-tag changing the installation target. Installation must verify that exact version before any managed service or instance restart. Terminal job state is persisted before JSON, quiet, or interactive output, and status reads mark dead workers or workers that miss the startup grace period as failed.
15
15
  - `commands-tunnel.js`: tunnel lifecycle and profile management. Interactive tunnel setup ends with a review and confirmation; fully specified flag and profile runs remain direct. Auto-started servers never write nested output into the parent command's `--quiet` or `--json` result.
16
16
 
17
17
  ## Rules
@@ -105,6 +105,8 @@ function parseArgs(argv = process.argv.slice(2)) {
105
105
  lastAssistant: false,
106
106
  withStatus: false,
107
107
  yes: false,
108
+ updateWorker: false,
109
+ updateJobId: undefined,
108
110
  };
109
111
 
110
112
  const removedFlagErrors = [];
@@ -412,6 +414,27 @@ function parseArgs(argv = process.argv.slice(2)) {
412
414
  case 'y':
413
415
  options.yes = true;
414
416
  break;
417
+ case 'channel': {
418
+ const { value, nextIndex } = consumeValue(i, inlineValue);
419
+ i = nextIndex;
420
+ if (value !== 'stable' && value !== 'rc') {
421
+ throw new TunnelCliError('--channel must be stable or rc.', EXIT_CODE.USAGE_ERROR);
422
+ }
423
+ options.channel = value;
424
+ break;
425
+ }
426
+ case 'update-worker':
427
+ options.updateWorker = true;
428
+ break;
429
+ case 'update-job-id': {
430
+ const { value, nextIndex } = consumeValue(i, inlineValue);
431
+ i = nextIndex;
432
+ if (typeof value !== 'string' || value.length === 0) {
433
+ throw new TunnelCliError('Missing value for --update-job-id.', EXIT_CODE.USAGE_ERROR);
434
+ }
435
+ options.updateJobId = value;
436
+ break;
437
+ }
415
438
  case 'help':
416
439
  case 'h':
417
440
  helpRequested = true;
@@ -465,6 +488,10 @@ function parseArgs(argv = process.argv.slice(2)) {
465
488
  const tunnelAction = command === 'tunnel' ? (positional[2] || null) : null;
466
489
  const startupAction = command === 'startup' ? (positional[1] || 'status') : null;
467
490
 
491
+ if (options.channel && command !== 'update') {
492
+ throw new TunnelCliError('--channel can only be used with pichamber update.', EXIT_CODE.USAGE_ERROR);
493
+ }
494
+
468
495
  if (options.lan && typeof options.host !== 'string') {
469
496
  options.host = '0.0.0.0';
470
497
  }
@@ -517,6 +544,7 @@ OPTIONS:
517
544
  --foreground Run server in foreground (use with systemd/process managers)
518
545
  --no-daemon Alias for --foreground
519
546
  -y, --yes Confirm update without prompting
547
+ --channel <stable|rc> Override the saved server update channel
520
548
  -h, --help Show help
521
549
  -v, --version Show version
522
550
 
@@ -727,7 +755,7 @@ function generateCompletionScript(shell) {
727
755
  return `# Bash completion for pichamber tunnel
728
756
  # Add to ~/.bashrc: eval "$(pichamber tunnel completion bash)"
729
757
  _pichamber_tunnel() {
730
- local cur prev commands tunnel_commands profile_commands common_flags start_flags
758
+ local cur prev commands tunnel_commands profile_commands common_flags start_flags update_flags
731
759
  COMPREPLY=()
732
760
  cur="\${COMP_WORDS[COMP_CWORD]}"
733
761
  prev="\${COMP_WORDS[COMP_CWORD-1]}"
@@ -737,12 +765,22 @@ _pichamber_tunnel() {
737
765
  profile_commands="list show add remove"
738
766
  common_flags="--port --host --lan --ui-password --api-only --foreground --no-daemon --json --all --help --version --plain --quiet --yes"
739
767
  start_flags="--provider --mode --profile --config --token --token-file --token-stdin --hostname --connect-ttl --session-ttl --qr --no-qr --dry-run --show-secrets"
768
+ update_flags="--channel --yes"
740
769
 
741
770
  if [[ \${COMP_CWORD} -eq 1 ]]; then
742
771
  COMPREPLY=( $(compgen -W "\${commands}" -- "\${cur}") )
743
772
  return 0
744
773
  fi
745
774
 
775
+ if [[ "\${COMP_WORDS[1]}" == "update" ]]; then
776
+ if [[ "\${prev}" == "--channel" ]]; then
777
+ COMPREPLY=( $(compgen -W "stable rc" -- "\${cur}") )
778
+ return 0
779
+ fi
780
+ COMPREPLY=( $(compgen -W "\${update_flags} \${common_flags}" -- "\${cur}") )
781
+ return 0
782
+ fi
783
+
746
784
  if [[ "\${COMP_WORDS[1]}" == "tunnel" ]]; then
747
785
  if [[ \${COMP_CWORD} -eq 2 ]]; then
748
786
  COMPREPLY=( $(compgen -W "\${tunnel_commands}" -- "\${cur}") )
@@ -821,6 +859,9 @@ _pichamber() {
821
859
  ;;
822
860
  args)
823
861
  case \$words[1] in
862
+ update)
863
+ _arguments '--channel[override the saved server update channel]:channel:(stable rc)' '--yes[skip confirmation]'
864
+ ;;
824
865
  tunnel)
825
866
  if (( CURRENT == 2 )); then
826
867
  _describe 'tunnel command' tunnel_commands
@@ -856,6 +897,8 @@ complete -c pichamber -n '__fish_use_subcommand' -a 'connect-url' -d 'Generate a
856
897
  complete -c pichamber -n '__fish_use_subcommand' -a 'update' -d 'Check for updates'
857
898
  complete -c pichamber -n '__fish_use_subcommand' -a 'version' -d 'Show installed version'
858
899
 
900
+ complete -c pichamber -n '__fish_seen_subcommand_from update' -l channel -a 'stable rc' -d 'Override the saved server update channel'
901
+
859
902
  complete -c pichamber -n '__fish_seen_subcommand_from tunnel; and not __fish_seen_subcommand_from help providers ready doctor status start stop profile completion' -a 'help' -d 'Show tunnel help'
860
903
  complete -c pichamber -n '__fish_seen_subcommand_from tunnel; and not __fish_seen_subcommand_from help providers ready doctor status start stop profile completion' -a 'providers' -d 'Show providers'
861
904
  complete -c pichamber -n '__fish_seen_subcommand_from tunnel; and not __fish_seen_subcommand_from help providers ready doctor status start stop profile completion' -a 'ready' -d 'Check readiness'
@@ -129,6 +129,7 @@ function shouldPersistStartupEnv(key, value) {
129
129
  'HISTFILE',
130
130
  'HISTFILESIZE',
131
131
  'HISTSIZE',
132
+ 'INVOCATION_ID',
132
133
  'LINES',
133
134
  'OLDPWD',
134
135
  'PROMPT',
@@ -138,6 +139,8 @@ function shouldPersistStartupEnv(key, value) {
138
139
  'PS3',
139
140
  'PS4',
140
141
  'PWD',
142
+ 'PICHAMBER_SERVER_TERMINAL',
143
+ 'PICHAMBER_SYSTEMD_UNIT',
141
144
  'PYENV_VERSION',
142
145
  'SHLVL',
143
146
  'TERM',
@@ -286,6 +289,7 @@ After=network-online.target
286
289
 
287
290
  [Service]
288
291
  Type=simple
292
+ Environment=PICHAMBER_SYSTEMD_UNIT=pichamber.service
289
293
  EnvironmentFile=-${systemdEscapeArg(envFilePath)}
290
294
  ExecStart="${systemdEscapeArg(process.execPath)}" ${args}
291
295
  WorkingDirectory=${workingDir}
@@ -1,4 +1,3 @@
1
- import fs from 'fs';
2
1
  import { EXIT_CODE } from './cli-errors.js';
3
2
  import { requestServerShutdown } from './cli-http.js';
4
3
  import { discoverRunningInstances } from './cli-lifecycle.js';
@@ -11,6 +10,12 @@ import {
11
10
  isUserStartupServiceActive as defaultIsUserStartupServiceActive,
12
11
  restartUserStartupService as defaultRestartUserStartupService,
13
12
  } from './cli-startup.js';
13
+ import {
14
+ claimUpdateJob as defaultClaimUpdateJob,
15
+ readUpdateJob as defaultReadUpdateJob,
16
+ updateUpdateJob as defaultUpdateUpdateJob,
17
+ } from '../../server/lib/update-job-store.js';
18
+ import { createPiUiSettingsStore } from '../../server/lib/pi/ui-settings-store.js';
14
19
  import {
15
20
  intro as clackIntro,
16
21
  outro as clackOutro,
@@ -26,25 +31,25 @@ import {
26
31
  logStatus,
27
32
  } from '../cli-output.js';
28
33
 
29
- const UNOWNED_INSTALL_MESSAGE = [
30
- 'This PiChamber copy is not a global package-manager install.',
31
- 'Install one copy, then update that same copy:',
32
- ' bun add -g @pi-chamber/web',
33
- ' npm install -g @pi-chamber/web',
34
- ' pnpm add -g @pi-chamber/web',
35
- ' yarn global add @pi-chamber/web',
36
- ].join('\n');
34
+ const readConfiguredServerUpdateChannel = async () => {
35
+ const settings = await createPiUiSettingsStore().read();
36
+ return settings.serverUpdateChannel;
37
+ };
37
38
 
38
39
  function createUpdateCommand({
39
40
  importFromFilePath,
40
41
  packageManagerPath,
41
42
  serveCommand,
42
- isInsideSystemdService = () => Boolean(process.env.INVOCATION_ID) || Boolean(process.env.PICHAMBER_SYSTEMD_UNIT),
43
+ isInsideSystemdService,
43
44
  isUserStartupServiceActive = defaultIsUserStartupServiceActive,
44
45
  restartUserStartupService = defaultRestartUserStartupService,
45
46
  discoverInstances = discoverRunningInstances,
46
47
  requestShutdown = requestServerShutdown,
47
48
  stopProcess = stopInstanceProcess,
49
+ claimUpdateJob = defaultClaimUpdateJob,
50
+ readUpdateJob = defaultReadUpdateJob,
51
+ updateUpdateJob = defaultUpdateUpdateJob,
52
+ readServerUpdateChannel = readConfiguredServerUpdateChannel,
48
53
  }) {
49
54
  return async function updateCommand(options = {}) {
50
55
  const showOutput = shouldRenderHumanOutput(options);
@@ -53,11 +58,31 @@ function createUpdateCommand({
53
58
  const {
54
59
  checkForUpdates,
55
60
  executeUpdate,
56
- resolveTrustedUpdatePackageManager,
61
+ getUpdateCapability,
57
62
  getCurrentVersion,
63
+ getInstalledVersion,
64
+ isInsidePiChamberSystemdService,
65
+ launchUpdateCommand,
66
+ normalizeServerUpdateChannel,
58
67
  } = await importFromFilePath(packageManagerPath);
59
68
 
69
+ let jobId = options.updateJobId;
70
+ const writeJob = async (changes) => {
71
+ if (!jobId) return;
72
+ await updateUpdateJob(jobId, changes);
73
+ };
74
+
75
+ try {
60
76
  const currentVersion = getCurrentVersion();
77
+ const workerJob = options.updateWorker === true && jobId
78
+ ? await readUpdateJob(jobId)
79
+ : null;
80
+ if (options.updateWorker === true && (!workerJob || !workerJob.targetVersion)) {
81
+ throw new Error('The persisted update job is unavailable.');
82
+ }
83
+ const channel = normalizeServerUpdateChannel(
84
+ workerJob ? workerJob.channel : (options.channel ?? await readServerUpdateChannel()),
85
+ );
61
86
 
62
87
  if (showOutput) {
63
88
  clackIntro('PiChamber Update');
@@ -69,7 +94,14 @@ function createUpdateCommand({
69
94
 
70
95
  updateSpin?.start('Checking for updates...');
71
96
 
72
- const updateInfo = await checkForUpdates();
97
+ const updateInfo = workerJob
98
+ ? {
99
+ available: workerJob.targetVersion !== currentVersion,
100
+ version: workerJob.targetVersion,
101
+ currentVersion,
102
+ channel,
103
+ }
104
+ : await checkForUpdates({ channel });
73
105
  if (updateInfo.error) {
74
106
  updateSpin?.error('Update check failed');
75
107
  if (showOutput) {
@@ -79,10 +111,12 @@ function createUpdateCommand({
79
111
  }
80
112
 
81
113
  if (!updateInfo.available) {
114
+ await writeJob({ state: 'complete', currentVersion, targetVersion: updateInfo.version || currentVersion });
82
115
  if (isJsonMode(options)) {
83
116
  printJson({
84
117
  currentVersion,
85
118
  latestVersion: updateInfo.version || currentVersion,
119
+ channel,
86
120
  updated: false,
87
121
  });
88
122
  return;
@@ -99,66 +133,31 @@ function createUpdateCommand({
99
133
  return;
100
134
  }
101
135
 
102
- const isContainer =
103
- fs.existsSync('/.dockerenv') ||
104
- Boolean(process.env.CONTAINER) ||
105
- process.env.container === 'docker';
106
-
107
- if (isContainer) {
108
- const msg = 'Docker deployments must be updated using container image deployment (e.g. docker pull) rather than in-app replacement.';
109
- updateSpin?.error('Docker deployment detected');
110
- if (isJsonMode(options)) {
111
- printJson({
112
- currentVersion,
113
- latestVersion: updateInfo.version || 'latest',
114
- updated: false,
115
- error: msg,
116
- });
117
- return;
118
- }
119
- if (showOutput) {
120
- clackOutro('update skipped');
121
- }
122
- throw new Error(msg);
123
- }
124
-
125
- if (isInsideSystemdService()) {
126
- const msg = 'pichamber update cannot replace this process while it is running as a systemd service. Run it from a terminal instead.';
127
- updateSpin?.error('systemd service deployment detected');
136
+ const capability = getUpdateCapability();
137
+ if (!capability.supported) {
138
+ updateSpin?.error('This deployment requires a manual update');
128
139
  if (isJsonMode(options)) {
140
+ await writeJob({ state: 'failed', error: capability.error });
129
141
  printJson({
142
+ status: 'error',
130
143
  currentVersion,
131
144
  latestVersion: updateInfo.version || 'latest',
132
145
  updated: false,
133
- error: msg,
146
+ code: capability.code,
147
+ error: capability.error,
148
+ channel,
134
149
  });
135
- return;
150
+ return { exitCode: EXIT_CODE.GENERAL_ERROR };
136
151
  }
137
- if (showOutput) {
138
- clackOutro('update skipped');
139
- }
140
- throw new Error(msg);
152
+ if (showOutput) clackOutro('update skipped');
153
+ throw new Error(capability.error);
141
154
  }
155
+ const pm = capability.packageManager;
142
156
 
143
- const pm = resolveTrustedUpdatePackageManager();
144
- if (!pm) {
145
- updateSpin?.error('No global package-manager install');
146
- if (isJsonMode(options)) {
147
- printJson({
148
- currentVersion,
149
- latestVersion: updateInfo.version || 'latest',
150
- updated: false,
151
- error: UNOWNED_INSTALL_MESSAGE,
152
- });
153
- return;
154
- }
155
- if (showOutput) {
156
- clackOutro('update skipped');
157
- }
158
- throw new Error(UNOWNED_INSTALL_MESSAGE);
157
+ if (typeof updateInfo.version !== 'string' || updateInfo.version.length === 0) {
158
+ throw new Error('Update target version is unavailable.');
159
159
  }
160
-
161
- const latestVersion = updateInfo.version || 'latest';
160
+ const latestVersion = updateInfo.version;
162
161
  const startupServiceActive = isUserStartupServiceActive();
163
162
  const runningInstances = startupServiceActive ? [] : await discoverInstances();
164
163
 
@@ -166,6 +165,7 @@ function createUpdateCommand({
166
165
  updateSpin?.clear();
167
166
  logStatus('info', 'Review update', [
168
167
  `Version: ${currentVersion} -> ${latestVersion}`,
168
+ `Channel: ${channel}`,
169
169
  `Package manager: ${pm}`,
170
170
  startupServiceActive
171
171
  ? 'Restart: startup service'
@@ -181,12 +181,90 @@ function createUpdateCommand({
181
181
  }
182
182
  }
183
183
 
184
+ const insideManagedService = typeof isInsideSystemdService === 'function'
185
+ ? isInsideSystemdService()
186
+ : isInsidePiChamberSystemdService?.() === true;
187
+ if (insideManagedService && options.updateWorker !== true) {
188
+ updateSpin?.start('Starting systemd update worker...');
189
+ if (typeof launchUpdateCommand !== 'function') {
190
+ throw new Error('The systemd update worker is unavailable.');
191
+ }
192
+ const launched = await launchUpdateCommand({
193
+ previousVersion: currentVersion,
194
+ targetVersion: latestVersion,
195
+ packageManager: pm,
196
+ channel,
197
+ isSystemd: true,
198
+ });
199
+ if (!launched.success) throw new Error(launched.error || 'Could not start the systemd update worker.');
200
+ updateSpin?.clear();
201
+ if (isJsonMode(options)) {
202
+ printJson({
203
+ status: launched.existing ? 'in-progress' : 'started',
204
+ updated: false,
205
+ jobId: launched.jobId,
206
+ previousVersion: currentVersion,
207
+ latestVersion: launched.targetVersion || latestVersion,
208
+ channel: launched.channel || channel,
209
+ });
210
+ } else if (showOutput) {
211
+ logStatus('success', launched.existing ? 'an update is already in progress' : 'systemd update worker started');
212
+ clackOutro(launched.existing ? 'using the existing update job' : 'the server will restart when the update is installed');
213
+ } else if (isQuietMode(options)) {
214
+ process.stdout.write(launched.existing
215
+ ? `update-in-progress job:${launched.jobId}\n`
216
+ : `update-started ${currentVersion} -> ${latestVersion} job:${launched.jobId}\n`);
217
+ }
218
+ return;
219
+ }
220
+
221
+ if (!jobId) {
222
+ if (typeof claimUpdateJob !== 'function') throw new Error('Update coordination is unavailable.');
223
+ const claimed = await claimUpdateJob({
224
+ previousVersion: currentVersion,
225
+ targetVersion: latestVersion,
226
+ packageManager: pm,
227
+ channel,
228
+ });
229
+ if (!claimed.created) {
230
+ updateSpin?.clear();
231
+ if (isJsonMode(options)) {
232
+ printJson({
233
+ status: 'in-progress',
234
+ updated: false,
235
+ jobId: claimed.job.id,
236
+ previousVersion: claimed.job.previousVersion || currentVersion,
237
+ latestVersion: claimed.job.targetVersion || latestVersion,
238
+ channel: claimed.job.channel || channel,
239
+ });
240
+ } else if (showOutput) {
241
+ logStatus('info', 'another PiChamber update is already in progress');
242
+ clackOutro('update already running');
243
+ } else if (isQuietMode(options)) {
244
+ process.stdout.write(`update-in-progress job:${claimed.job.id}\n`);
245
+ }
246
+ return;
247
+ }
248
+ jobId = claimed.job.id;
249
+ }
250
+
184
251
  if (showOutput && !updateSpin) {
185
252
  logStatus('info', `updating ${currentVersion} -> ${latestVersion} with ${pm}`);
186
253
  }
187
254
  updateSpin?.start(`Updating ${currentVersion} -> ${latestVersion}...`);
255
+ await writeJob({
256
+ state: 'installing',
257
+ previousVersion: currentVersion,
258
+ targetVersion: latestVersion,
259
+ packageManager: pm,
260
+ channel,
261
+ workerPid: process.pid,
262
+ });
188
263
 
189
- const result = executeUpdate(pm, { silent: isJsonMode(options) || isQuietMode(options) });
264
+ const result = executeUpdate(pm, {
265
+ silent: isJsonMode(options) || isQuietMode(options),
266
+ targetVersion: latestVersion,
267
+ });
190
268
  if (!result.success) {
191
269
  updateSpin?.error('Update failed');
192
270
  if (showOutput) {
@@ -195,25 +273,42 @@ function createUpdateCommand({
195
273
  throw new Error(`Update failed with exit code ${result.exitCode}`);
196
274
  }
197
275
 
198
- const installedVersion = getCurrentVersion();
276
+ const installedVersion = typeof getInstalledVersion === 'function'
277
+ ? getInstalledVersion(pm)
278
+ : getCurrentVersion();
279
+ await writeJob({ state: 'verifying', currentVersion: installedVersion });
199
280
  const restartResults = [];
200
281
  let startupServiceRestarted = false;
282
+ const versionVerified = installedVersion === latestVersion;
283
+ const messages = [];
284
+ if (!versionVerified) {
285
+ messages.push({
286
+ level: 'warning',
287
+ code: 'VERSION_MISMATCH',
288
+ message: `Package manager completed, but this install reports ${installedVersion} instead of ${latestVersion}. Run pichamber update again or reinstall ${latestVersion} before restarting the server.`,
289
+ });
290
+ }
201
291
 
202
- if (startupServiceActive) {
203
- updateSpin?.message('Restarting systemd user service...');
292
+ if (versionVerified && startupServiceActive) {
293
+ await writeJob({ state: 'restarting' });
294
+ updateSpin?.message('Restarting systemd service...');
204
295
  try {
205
296
  restartUserStartupService();
206
297
  startupServiceRestarted = true;
207
298
  } catch (error) {
208
299
  const detail = error instanceof Error ? error.message : String(error);
209
- const msg = `Package updated but failed to restart pichamber.service. Run: systemctl --user restart pichamber.service (${detail})`;
300
+ const systemctl = typeof process.getuid === 'function' && process.getuid() === 0
301
+ ? 'systemctl restart pichamber.service'
302
+ : 'systemctl --user restart pichamber.service';
303
+ const msg = `Package updated but failed to restart pichamber.service. Run: ${systemctl} (${detail})`;
210
304
  updateSpin?.error('Startup service restart failed');
211
305
  if (showOutput) {
212
306
  clackOutro('update incomplete');
213
307
  }
214
308
  throw new Error(msg);
215
309
  }
216
- } else if (runningInstances.length > 0) {
310
+ } else if (versionVerified && runningInstances.length > 0) {
311
+ await writeJob({ state: 'restarting' });
217
312
  updateSpin?.message(`Restarting ${runningInstances.length} running instance(s)...`);
218
313
  for (const instance of runningInstances) {
219
314
  const storedOptions = readInstanceOptions(instance.instanceFilePath) || { port: instance.port };
@@ -257,15 +352,6 @@ function createUpdateCommand({
257
352
 
258
353
  const restartedCount = restartResults.filter((entry) => entry.ok).length;
259
354
  const failedRestartCount = restartResults.length - restartedCount;
260
- const versionVerified = latestVersion === 'latest' || installedVersion === latestVersion;
261
- const messages = [];
262
- if (!versionVerified) {
263
- messages.push({
264
- level: 'warning',
265
- code: 'VERSION_MISMATCH',
266
- message: `Package manager completed, but this install reports ${installedVersion} instead of ${latestVersion}.`,
267
- });
268
- }
269
355
  if (failedRestartCount > 0) {
270
356
  messages.push({
271
357
  level: 'warning',
@@ -281,6 +367,7 @@ function createUpdateCommand({
281
367
  previousVersion: currentVersion,
282
368
  currentVersion: installedVersion,
283
369
  latestVersion,
370
+ channel,
284
371
  versionVerified,
285
372
  updated: installedVersion !== currentVersion || versionVerified,
286
373
  packageManager: pm,
@@ -289,6 +376,11 @@ function createUpdateCommand({
289
376
  restartResults,
290
377
  messages,
291
378
  };
379
+ await writeJob({
380
+ state: messages.length > 0 ? 'failed' : 'complete',
381
+ currentVersion: installedVersion,
382
+ error: messages.length > 0 ? messages.map((message) => message.message).join(' ') : undefined,
383
+ });
292
384
  if (isJsonMode(options)) {
293
385
  printJson(resultPayload);
294
386
  return { exitCode };
@@ -303,6 +395,14 @@ function createUpdateCommand({
303
395
  process.stdout.write(`updated ${currentVersion} -> ${installedVersion} restarted:${restartedCount} failed:${failedRestartCount}\n`);
304
396
  }
305
397
  return { exitCode };
398
+ } catch (error) {
399
+ try {
400
+ await writeJob({ state: 'failed', error: error instanceof Error ? error.message : String(error) });
401
+ } catch {
402
+ // Preserve the update failure when status persistence also fails.
403
+ }
404
+ throw error;
405
+ }
306
406
  };
307
407
  }
308
408