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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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-BYJjPlpz.js} +1 -1
  9. package/dist/assets/{DiffView-BUOaq70P.js → DiffView-vh-y2oQz.js} +1 -1
  10. package/dist/assets/{FileSaveConflictDialog-B3wIsdE1.js → FileSaveConflictDialog-CwemI5n5.js} +1 -1
  11. package/dist/assets/{FilesView-DPwCE-XA.js → FilesView-DR3d1K1V.js} +1 -1
  12. package/dist/assets/{GitView-CGk98LhV.js → GitView-BWGX4RzN.js} +3 -3
  13. package/dist/assets/{JsonTreeView-HNtRoqVA.js → JsonTreeView-W-fnMq-A.js} +1 -1
  14. package/dist/assets/{MarkdownRendererImpl-DUYL-Wn3.js → MarkdownRendererImpl-DUVe8Jgr.js} +1 -1
  15. package/dist/assets/{PatchDiff-Bluz53zj.js → PatchDiff-BOQB83iO.js} +1 -1
  16. package/dist/assets/{SessionSwitcherContent-DDncCwpE.js → SessionSwitcherContent-CM0g0Dpg.js} +1 -1
  17. package/dist/assets/{SessionSwitcherDropdown-Cw_g3ai3.js → SessionSwitcherDropdown-CY3BW56O.js} +2 -2
  18. package/dist/assets/{SessionUnreadDot-CT5M3-qK.js → SessionUnreadDot-C5HBuQ4W.js} +1 -1
  19. package/dist/assets/SettingsView-A76k5FgH.js +2 -0
  20. package/dist/assets/{SettingsWindow-B_oA1yV4.js → SettingsWindow-CN8AWf_3.js} +1 -1
  21. package/dist/assets/{ToolOutputDialog-C3xiVDyE.js → ToolOutputDialog-CkdWr3lC.js} +1 -1
  22. package/dist/assets/{ToolPartDiffPreview-xrxYTK3l.js → ToolPartDiffPreview-B3aR120P.js} +1 -1
  23. package/dist/assets/{VirtualizedFileDiff-Bpgyk3yt.js → VirtualizedFileDiff-D05_VUdJ.js} +1 -1
  24. package/dist/assets/{collapsible-_urywMu5.js → collapsible-B6bVtxgp.js} +1 -1
  25. package/dist/assets/{computeVirtualFileMetrics-DPPmLfoR.js → computeVirtualFileMetrics-DVysbU8X.js} +1 -1
  26. package/dist/assets/{contextFileOpenGuard-CV7L_UMk.js → contextFileOpenGuard-HuJGM1Zp.js} +1 -1
  27. package/dist/assets/{gitStatusPredicates-BTkHRMCD.js → gitStatusPredicates-Ben2Ocei.js} +1 -1
  28. package/dist/assets/{index-CrqlVJXp.js → index-BOtRfXre.js} +3 -3
  29. package/dist/assets/{index-C3PSe3Mq.js → index-CKU5yG8s.js} +1 -1
  30. package/dist/assets/{isDiffPlainText-Djb-erNZ.js → isDiffPlainText--C9XSjKy.js} +1 -1
  31. package/dist/assets/{isFilePlainText-BQ-Wnk8C.js → isFilePlainText-N64kYHDs.js} +1 -1
  32. package/dist/assets/{main-7I7_paNp.js → main-BPsZ4uEs.js} +3 -3
  33. package/dist/assets/{main-Dpqrd5dA.js → main-Uqvwxvkq.js} +2 -2
  34. package/dist/assets/{markdownCore-DOQQqV2i.js → markdownCore-C9WMRP3A.js} +1 -1
  35. package/dist/assets/{miniChat-b1O4Yu1o.js → miniChat-N1QvufvH.js} +2 -2
  36. package/dist/assets/{mobile-BTpbHrim.js → mobile-Dw6ZxnWP.js} +2 -2
  37. package/dist/assets/{renderElectronMiniChatApp-Cisrg0Iv.js → renderElectronMiniChatApp-DknVCBkh.js} +2 -2
  38. package/dist/assets/{renderMobileApp-CSBtWiZ2.js → renderMobileApp-D2FQRgzf.js} +3 -3
  39. package/dist/assets/runtimeEndpointReset-Df6K8cW6.js +53 -0
  40. package/dist/assets/{runtimeSurface-C9kx2zfD.js → runtimeSurface-CPm7KWaN.js} +1 -1
  41. package/dist/assets/{useAppFontEffects-BH5qeSfx.js → useAppFontEffects-BJ2NAj4u.js} +7 -7
  42. package/dist/assets/{useFilesViewSearch-Bdxwr4SZ.js → useFilesViewSearch-Dmu3k5Hy.js} +1 -1
  43. package/dist/assets/{usePushVisibilityBeacon-Czfhm8lw.js → usePushVisibilityBeacon-DR77-ud4.js} +1 -1
  44. package/dist/assets/{useSwitcherItems-CiTeIjW3.js → useSwitcherItems-B2_FeUCx.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-oNye2HID.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-WfQYNHJK.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
@@ -3,6 +3,8 @@ import fs from 'fs';
3
3
  import path from 'path';
4
4
  import { fileURLToPath } from 'url';
5
5
 
6
+ import { claimUpdateJob, updateUpdateJob } from './update-job-store.js';
7
+
6
8
  const __filename = fileURLToPath(import.meta.url);
7
9
  const __dirname = path.dirname(__filename);
8
10
 
@@ -21,6 +23,12 @@ const TRUSTED_UPDATE_REASONS = new Set([
21
23
  'cached',
22
24
  ]);
23
25
  const UPDATE_PACKAGE_MANAGERS = new Set(['npm', 'pnpm', 'yarn', 'bun']);
26
+ const SEMVER_PATTERN = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
27
+ const RELEASE_CANDIDATE_PATTERN = /^\d+\.\d+\.\d+-rc\.[1-9]\d*$/;
28
+
29
+ export function normalizeServerUpdateChannel(value) {
30
+ return value === 'rc' ? 'rc' : 'stable';
31
+ }
24
32
 
25
33
  function getSpawnSyncBaseOptions() {
26
34
  return process.platform === 'win32' ? { windowsHide: true } : {};
@@ -114,7 +122,7 @@ async function checkForUpdatesFromApi(currentVersion, options = {}) {
114
122
  deviceClass: normalizeDeviceClass(options.deviceClass),
115
123
  platform,
116
124
  arch,
117
- channel: 'stable',
125
+ channel: normalizeServerUpdateChannel(options.channel),
118
126
  currentVersion,
119
127
  instanceMode: options.instanceMode || 'unknown',
120
128
  };
@@ -477,6 +485,132 @@ export function resolveTrustedUpdatePackageManager(details = detectPackageManage
477
485
  return null;
478
486
  }
479
487
 
488
+ function isSourceCheckout(packagePath, existsSync = fs.existsSync) {
489
+ const parent = path.dirname(packagePath);
490
+ if (path.basename(packagePath) !== 'web' || path.basename(parent) !== 'packages') return false;
491
+ const repositoryRoot = path.dirname(parent);
492
+ return existsSync(path.join(repositoryRoot, 'package.json'))
493
+ && existsSync(path.join(repositoryRoot, 'packages', 'ui'));
494
+ }
495
+
496
+ export function detectSystemdServiceContext(options = {}) {
497
+ const env = options.env || process.env;
498
+ const markedUnit = env.PICHAMBER_SYSTEMD_UNIT === 'pichamber.service'
499
+ ? env.PICHAMBER_SYSTEMD_UNIT
500
+ : null;
501
+ if (markedUnit) {
502
+ const isRoot = options.isRoot ?? (typeof process.getuid === 'function' && process.getuid() === 0);
503
+ return { unit: markedUnit, scope: isRoot ? 'system' : 'user', managed: markedUnit === 'pichamber.service' };
504
+ }
505
+ if ((options.platform || process.platform) !== 'linux') return null;
506
+ try {
507
+ const cgroup = (options.readFileSync || fs.readFileSync)('/proc/self/cgroup', 'utf8');
508
+ for (const line of cgroup.split(/\r?\n/)) {
509
+ const cgroupPath = line.slice(line.lastIndexOf(':') + 1);
510
+ const unit = cgroupPath.split('/').filter(Boolean).at(-1);
511
+ if (!unit || !/^[A-Za-z0-9_.@-]+\.service$/.test(unit)) continue;
512
+ return {
513
+ unit,
514
+ scope: cgroupPath.includes('/user.slice/') ? 'user' : 'system',
515
+ managed: unit === 'pichamber.service',
516
+ };
517
+ }
518
+ return null;
519
+ } catch {
520
+ return null;
521
+ }
522
+ }
523
+
524
+ function canWriteOwnedInstall(details, options = {}) {
525
+ if (typeof options.installWritable === 'boolean') return options.installWritable;
526
+ const target = details.globalNodeModulesRoot || path.dirname(details.packagePath || '');
527
+ if (!target) return false;
528
+ try {
529
+ (options.accessSync || fs.accessSync)(target, fs.constants.W_OK);
530
+ return true;
531
+ } catch {
532
+ return false;
533
+ }
534
+ }
535
+
536
+ function customSystemdRestartCommand(context) {
537
+ return context.scope === 'user'
538
+ ? `systemctl --user restart ${context.unit}`
539
+ : `systemctl restart ${context.unit}`;
540
+ }
541
+
542
+ function customSystemdGuidance(context) {
543
+ if (context.unit.toLowerCase().includes('pichamber')) {
544
+ return `PiChamber is running under the custom systemd unit ${context.unit}. Automatic restart is supported only for pichamber.service. From a normal terminal, run: pichamber update. Then run: ${customSystemdRestartCommand(context)}`;
545
+ }
546
+ return `PiChamber is running inside ${context.unit}, but PiChamber cannot verify that this is the server's owning unit. From a normal terminal, run: pichamber update. Then restart PiChamber using your deployment configuration. Do not restart ${context.unit} unless you have verified that it is your PiChamber unit.`;
547
+ }
548
+
549
+ export function getUpdateCapability(options = {}) {
550
+ const env = options.env || process.env;
551
+ const isContainer = options.isContainer ?? (
552
+ fs.existsSync('/.dockerenv')
553
+ || fs.existsSync('/run/.containerenv')
554
+ || Boolean(env.CONTAINER)
555
+ || Boolean(env.container)
556
+ );
557
+ if (isContainer) {
558
+ return {
559
+ supported: false,
560
+ code: 'DOCKER_DEPLOYMENT',
561
+ error: 'PiChamber is running in a container and cannot replace its own image. Pull or build the newer image with your deployment tool, then recreate the container.',
562
+ };
563
+ }
564
+
565
+ const packagePath = options.packagePath || getCurrentPackagePath();
566
+ const context = options.systemdContext === undefined
567
+ ? detectSystemdServiceContext(options)
568
+ : options.systemdContext;
569
+ const shouldReportCustomUnit = context && !context.managed && (
570
+ options.serverProcess === true || env.PICHAMBER_SERVER_TERMINAL === '1'
571
+ );
572
+ if (isSourceCheckout(packagePath, options.existsSync)) {
573
+ const knownPiChamberUnit = shouldReportCustomUnit && context.unit.toLowerCase().includes('pichamber');
574
+ const restart = knownPiChamberUnit
575
+ ? ` Then restart ${context.unit} with: ${customSystemdRestartCommand(context)}`
576
+ : '';
577
+ return {
578
+ supported: false,
579
+ code: 'SOURCE_CHECKOUT',
580
+ error: `This PiChamber server is running from a source checkout and cannot update itself. Update the checkout, rebuild the web package, and restart the server.${restart}`,
581
+ commands: knownPiChamberUnit ? [customSystemdRestartCommand(context)] : [],
582
+ };
583
+ }
584
+ if (shouldReportCustomUnit) {
585
+ return {
586
+ supported: false,
587
+ code: 'CUSTOM_SYSTEMD_UNIT',
588
+ error: customSystemdGuidance(context),
589
+ commands: context.unit.toLowerCase().includes('pichamber')
590
+ ? ['pichamber update', customSystemdRestartCommand(context)]
591
+ : ['pichamber update'],
592
+ };
593
+ }
594
+
595
+ const details = options.details || detectPackageManagerDetails();
596
+ const packageManager = resolveTrustedUpdatePackageManager(details);
597
+ if (packageManager && canWriteOwnedInstall(details, options)) {
598
+ return { supported: true, code: 'SUPPORTED', packageManager };
599
+ }
600
+ if (packageManager || String(details?.reason || '').includes('visible-install')) {
601
+ return {
602
+ supported: false,
603
+ code: 'INSTALL_OWNERSHIP_MISMATCH',
604
+ error: 'This account cannot update the PiChamber installation used by the server. Run pichamber update as the account that installed PiChamber, or reinstall the global package under the service account and run pichamber startup enable again.',
605
+ };
606
+ }
607
+ return {
608
+ supported: false,
609
+ code: 'UNSUPPORTED_INSTALL',
610
+ error: 'This PiChamber copy is not a supported global package-manager install. Install @pi-chamber/web globally with Bun, npm, pnpm, or Yarn, then run pichamber startup enable again.',
611
+ };
612
+ }
613
+
480
614
  function detectPackageManagerFromInstallPath(pkgPath) {
481
615
  if (!pkgPath) return null;
482
616
  const normalized = pkgPath.replace(/\\/g, '/').toLowerCase();
@@ -593,17 +727,21 @@ function isPackageInstalledWith(pm) {
593
727
  /**
594
728
  * Get the update command for the detected package manager
595
729
  */
596
- export function getUpdateCommand(pm = detectPackageManager()) {
730
+ export function getUpdateCommand(pm = detectPackageManager(), targetVersion) {
731
+ if (!SEMVER_PATTERN.test(String(targetVersion))) {
732
+ throw new Error('Update target version is invalid.');
733
+ }
734
+ const packageSpec = `${PACKAGE_NAME}@${targetVersion}`;
597
735
  const pmCommand = quoteCommand(resolvePackageManagerCommand(pm));
598
736
  switch (pm) {
599
737
  case 'pnpm':
600
- return `${pmCommand} add -g ${PACKAGE_NAME}@latest`;
738
+ return `${pmCommand} add -g ${packageSpec}`;
601
739
  case 'yarn':
602
- return `${pmCommand} global add ${PACKAGE_NAME}@latest`;
740
+ return `${pmCommand} global add ${packageSpec}`;
603
741
  case 'bun':
604
- return `${pmCommand} add -g ${PACKAGE_NAME}@latest`;
742
+ return `${pmCommand} add -g ${packageSpec}`;
605
743
  default:
606
- return `${pmCommand} install -g ${PACKAGE_NAME}@latest`;
744
+ return `${pmCommand} install -g ${packageSpec}`;
607
745
  }
608
746
  }
609
747
 
@@ -620,6 +758,22 @@ export function getCurrentVersion() {
620
758
  }
621
759
  }
622
760
 
761
+ export function getInstalledVersion(pm) {
762
+ const candidates = [
763
+ ...getOwnedPackagePathsFromGlobalBins(pm),
764
+ ...getGlobalNodeModulesRoots(pm).map(getPackagePathForGlobalRoot),
765
+ ];
766
+ for (const packagePath of getUniquePaths(candidates)) {
767
+ try {
768
+ const pkg = JSON.parse(fs.readFileSync(path.join(packagePath, 'package.json'), 'utf8'));
769
+ if (pkg?.name === PACKAGE_NAME && typeof pkg.version === 'string') return pkg.version;
770
+ } catch {
771
+ // Try the next package-manager-owned path.
772
+ }
773
+ }
774
+ return getCurrentVersion();
775
+ }
776
+
623
777
  function getNpmRepositoryUrl(data) {
624
778
  const repository = data?.repository;
625
779
  if (typeof repository === 'string') return repository;
@@ -642,7 +796,7 @@ function isOfficialPiChamberRegistryPackage(data) {
642
796
  * Fetch latest version from npm only when `@pi-chamber/web` is this project's package.
643
797
  * Dist-tag alone is not enough if an unrelated package occupies the name.
644
798
  */
645
- async function getLatestVersion() {
799
+ async function getRegistryUpdateTarget(currentVersion, channel) {
646
800
  try {
647
801
  const response = await fetch(NPM_REGISTRY_URL, {
648
802
  headers: { Accept: 'application/json' },
@@ -658,7 +812,27 @@ async function getLatestVersion() {
658
812
  return null;
659
813
  }
660
814
  const latest = data['dist-tags']?.latest;
661
- return typeof latest === 'string' && latest.length > 0 ? latest : null;
815
+ const releaseCandidate = data['dist-tags']?.rc;
816
+ const stableVersion = typeof latest === 'string' && SEMVER_PATTERN.test(latest) && !latest.includes('-')
817
+ ? latest
818
+ : null;
819
+ const rcVersion = typeof releaseCandidate === 'string' && RELEASE_CANDIDATE_PATTERN.test(releaseCandidate)
820
+ ? releaseCandidate
821
+ : null;
822
+ if (normalizeServerUpdateChannel(channel) === 'rc') {
823
+ const stableTarget = stableVersion
824
+ ? { version: stableVersion, releaseChannel: 'stable' }
825
+ : null;
826
+ const rcTarget = rcVersion
827
+ ? { version: rcVersion, releaseChannel: 'rc' }
828
+ : null;
829
+ if (!stableTarget) return rcTarget;
830
+ if (!rcTarget) return stableTarget;
831
+ return compareVersions(rcTarget.version, stableTarget.version) > 0
832
+ ? rcTarget
833
+ : stableTarget;
834
+ }
835
+ return stableVersion ? { version: stableVersion, releaseChannel: 'stable' } : null;
662
836
  } catch {
663
837
  return null;
664
838
  }
@@ -668,35 +842,46 @@ async function getLatestVersion() {
668
842
  * Compare semver-like version strings.
669
843
  */
670
844
  function parseVersionForComparison(value) {
671
- const normalized = String(value || '').replace(/^v/, '').split('+')[0];
672
- const prereleaseIndex = normalized.indexOf('-');
673
- const core = prereleaseIndex >= 0 ? normalized.slice(0, prereleaseIndex) : normalized;
674
- const parts = core.split('.').map((part) => {
675
- const parsed = Number.parseInt(part || '0', 10);
676
- return Number.isFinite(parsed) ? parsed : 0;
677
- });
678
-
845
+ const match = SEMVER_PATTERN.exec(String(value || '').replace(/^v/, ''));
846
+ if (!match) return null;
679
847
  return {
680
- parts,
681
- prerelease: prereleaseIndex >= 0,
848
+ core: match.slice(1, 4).map(Number),
849
+ prerelease: match[4]?.split('.') || null,
682
850
  };
683
851
  }
684
852
 
685
- function compareVersions(left, right) {
686
- const a = parseVersionForComparison(left);
687
- const b = parseVersionForComparison(right);
688
- const length = Math.max(a.parts.length, b.parts.length);
689
-
853
+ function comparePrerelease(left, right) {
854
+ if (!left && !right) return 0;
855
+ if (!left) return 1;
856
+ if (!right) return -1;
857
+ const length = Math.max(left.length, right.length);
690
858
  for (let index = 0; index < length; index += 1) {
691
- const diff = (a.parts[index] || 0) - (b.parts[index] || 0);
692
- if (diff !== 0) return diff;
859
+ if (left[index] === undefined) return -1;
860
+ if (right[index] === undefined) return 1;
861
+ const leftNumeric = /^\d+$/.test(left[index]);
862
+ const rightNumeric = /^\d+$/.test(right[index]);
863
+ if (leftNumeric && rightNumeric) {
864
+ const difference = Number(left[index]) - Number(right[index]);
865
+ if (difference !== 0) return difference;
866
+ } else if (leftNumeric !== rightNumeric) {
867
+ return leftNumeric ? -1 : 1;
868
+ } else {
869
+ const difference = left[index].localeCompare(right[index]);
870
+ if (difference !== 0) return difference;
871
+ }
693
872
  }
873
+ return 0;
874
+ }
694
875
 
695
- if (a.prerelease !== b.prerelease) {
696
- return a.prerelease ? -1 : 1;
876
+ function compareVersions(left, right) {
877
+ const a = parseVersionForComparison(left);
878
+ const b = parseVersionForComparison(right);
879
+ if (!a || !b) return String(left || '').localeCompare(String(right || ''), undefined, { numeric: true });
880
+ for (let index = 0; index < a.core.length; index += 1) {
881
+ const difference = a.core[index] - b.core[index];
882
+ if (difference !== 0) return difference;
697
883
  }
698
-
699
- return 0;
884
+ return comparePrerelease(a.prerelease, b.prerelease);
700
885
  }
701
886
 
702
887
  /**
@@ -734,18 +919,26 @@ export async function checkForUpdates(options = {}) {
734
919
  const pm = detectPackageManager();
735
920
  const appType = normalizeAppType(options.appType);
736
921
  const platform = normalizePlatform(options.platform);
737
- const latestVersion = await getLatestVersion();
922
+ const channel = normalizeServerUpdateChannel(options.channel);
923
+ const target = currentVersion === 'unknown'
924
+ ? null
925
+ : await getRegistryUpdateTarget(currentVersion, channel);
926
+ const latestVersion = target?.version;
738
927
 
739
928
  if (!latestVersion || currentVersion === 'unknown') {
740
929
  return {
741
930
  available: false,
742
931
  currentVersion,
932
+ channel,
743
933
  error: 'Unable to determine versions',
744
934
  };
745
935
  }
746
936
 
747
937
  const available = compareVersions(latestVersion, currentVersion) > 0;
748
- const remote = await checkForUpdatesFromApi(currentVersion, options);
938
+ const remote = await checkForUpdatesFromApi(currentVersion, {
939
+ ...options,
940
+ channel: target.releaseChannel,
941
+ });
749
942
  const trustedRemote = remote?.version === latestVersion ? remote : null;
750
943
  let changelog = trustedRemote?.body;
751
944
  let downloadUrl;
@@ -762,6 +955,7 @@ export async function checkForUpdates(options = {}) {
762
955
  available,
763
956
  version: latestVersion,
764
957
  currentVersion,
958
+ channel,
765
959
  body: changelog,
766
960
  releaseUrl: `${GITHUB_RELEASES_URL}/tag/v${latestVersion}`,
767
961
  downloadUrl,
@@ -775,39 +969,113 @@ export async function checkForUpdates(options = {}) {
775
969
  /**
776
970
  * Execute the update (used by CLI)
777
971
  */
778
- export function launchUpdateCommand(options = {}) {
779
- const isContainer = options.isContainer ?? (fs.existsSync('/.dockerenv') || Boolean(process.env.CONTAINER) || process.env.container === 'docker');
780
- const isSystemd = options.isSystemd ?? Boolean(process.env.INVOCATION_ID || process.env.PICHAMBER_SYSTEMD_UNIT);
972
+ export function isInsidePiChamberSystemdService(options = {}) {
973
+ const env = options.env || process.env;
974
+ if (env.PICHAMBER_SYSTEMD_UNIT === 'pichamber.service') return true;
975
+ if ((options.platform || process.platform) !== 'linux') return false;
976
+ try {
977
+ const cgroup = (options.readFileSync || fs.readFileSync)('/proc/self/cgroup', 'utf8');
978
+ return /(?:^|\/)pichamber\.service(?:\/|$)/m.test(cgroup);
979
+ } catch {
980
+ return false;
981
+ }
982
+ }
983
+
984
+ function updateWorkerArgs(cliPath, jobId) {
985
+ return [cliPath, 'update', '--yes', '--quiet', '--update-worker', '--update-job-id', jobId];
986
+ }
987
+
988
+ function systemdRunArgs(cliPath, jobId, options = {}) {
989
+ const isRoot = options.isRoot ?? (typeof process.getuid === 'function' && process.getuid() === 0);
990
+ const args = [];
991
+ if (!isRoot) args.push('--user');
992
+ args.push(`--unit=pichamber-update-${jobId.replaceAll('-', '')}`, '--collect', '--quiet', '--property=Type=exec');
993
+ const env = options.env || process.env;
994
+ for (const key of ['HOME', 'PATH', 'PICHAMBER_DATA_DIR', 'PICHAMBER_PACKAGE_MANAGER']) {
995
+ const value = env[key];
996
+ if (typeof value === 'string' && value.length > 0) args.push(`--setenv=${key}=${value}`);
997
+ }
998
+ args.push('--', process.execPath, ...updateWorkerArgs(cliPath, jobId));
999
+ return args;
1000
+ }
1001
+
1002
+ export async function launchUpdateCommand(options = {}) {
1003
+ const isContainer = options.isContainer ?? (
1004
+ fs.existsSync('/.dockerenv')
1005
+ || fs.existsSync('/run/.containerenv')
1006
+ || Boolean(process.env.CONTAINER)
1007
+ || Boolean(process.env.container)
1008
+ );
781
1009
  if (isContainer) {
782
1010
  return {
783
1011
  success: false,
784
- error: 'Docker deployments must be updated by deploying a new container image. Run: pichamber update',
1012
+ error: 'Docker deployments must be updated by deploying a new container image.',
785
1013
  };
786
1014
  }
787
- if (isSystemd) {
1015
+
1016
+ const claimJob = options.claimUpdateJob || claimUpdateJob;
1017
+ const updateJob = options.updateUpdateJob || updateUpdateJob;
1018
+ const claimed = await claimJob({
1019
+ previousVersion: options.previousVersion,
1020
+ targetVersion: options.targetVersion,
1021
+ packageManager: options.packageManager,
1022
+ channel: normalizeServerUpdateChannel(options.channel),
1023
+ });
1024
+ if (!claimed.created) {
788
1025
  return {
789
- success: false,
790
- error: 'This PiChamber server runs as a systemd service. Run from a terminal: pichamber update',
1026
+ success: true,
1027
+ jobId: claimed.job.id,
1028
+ state: claimed.job.state,
1029
+ channel: claimed.job.channel,
1030
+ targetVersion: claimed.job.targetVersion,
1031
+ existing: true,
791
1032
  };
792
1033
  }
793
1034
 
1035
+ const jobId = claimed.job.id;
794
1036
  const cliPath = path.resolve(__dirname, '..', '..', 'bin', 'cli.js');
1037
+ const insideSystemd = options.isSystemd ?? isInsidePiChamberSystemdService(options);
795
1038
  try {
796
- const child = (options.spawnProcess || spawn)(process.execPath, [cliPath, 'update', '--quiet'], {
797
- detached: true,
798
- stdio: 'ignore',
799
- windowsHide: true,
800
- });
801
- child.once?.('error', () => {});
802
- child.unref();
803
- return { success: true };
804
- } catch {
805
- return { success: false, error: 'Could not start the updater. Run: pichamber update' };
1039
+ if (insideSystemd) {
1040
+ const result = (options.runProcess || spawnSync)('systemd-run', systemdRunArgs(cliPath, jobId, options), {
1041
+ encoding: 'utf8',
1042
+ stdio: 'pipe',
1043
+ windowsHide: true,
1044
+ });
1045
+ if (result.error || result.status !== 0) {
1046
+ const error = 'Could not start the systemd update worker. Run: pichamber update';
1047
+ await updateJob(jobId, { state: 'failed', error });
1048
+ return { success: false, jobId, error };
1049
+ }
1050
+ } else {
1051
+ const child = (options.spawnProcess || spawn)(process.execPath, updateWorkerArgs(cliPath, jobId), {
1052
+ detached: true,
1053
+ stdio: 'ignore',
1054
+ windowsHide: true,
1055
+ });
1056
+ child.once?.('error', (cause) => {
1057
+ const detail = cause instanceof Error ? cause.message : String(cause);
1058
+ void updateJob(jobId, { state: 'failed', error: `Could not start the updater: ${detail}` });
1059
+ });
1060
+ child.unref();
1061
+ }
1062
+ return {
1063
+ success: true,
1064
+ jobId,
1065
+ state: claimed.job.state,
1066
+ channel: claimed.job.channel,
1067
+ targetVersion: claimed.job.targetVersion,
1068
+ };
1069
+ } catch (cause) {
1070
+ const detail = cause instanceof Error ? cause.message : String(cause);
1071
+ const error = `Could not start the updater: ${detail}`;
1072
+ await updateJob(jobId, { state: 'failed', error });
1073
+ return { success: false, jobId, error };
806
1074
  }
807
1075
  }
808
1076
 
809
1077
  export function executeUpdate(pm = detectPackageManager(), options = {}) {
810
- const command = getUpdateCommand(pm);
1078
+ const command = getUpdateCommand(pm, options.targetVersion);
811
1079
  if (!options?.silent) {
812
1080
  console.log(`Updating ${PACKAGE_NAME} using ${pm}...`);
813
1081
  console.log(`Running: ${command}`);