@pi-chamber/web 0.9.8-rc.1 → 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-BMBrrFLy.js → DiagramView-BYJjPlpz.js} +1 -1
  9. package/dist/assets/{DiffView-yVBxHkBI.js → DiffView-vh-y2oQz.js} +1 -1
  10. package/dist/assets/{FileSaveConflictDialog-D0siEm8l.js → FileSaveConflictDialog-CwemI5n5.js} +1 -1
  11. package/dist/assets/{FilesView-CkcKBKkT.js → FilesView-DR3d1K1V.js} +1 -1
  12. package/dist/assets/{GitView-CfuhQOfc.js → GitView-BWGX4RzN.js} +3 -3
  13. package/dist/assets/{JsonTreeView-6kRdE1BO.js → JsonTreeView-W-fnMq-A.js} +1 -1
  14. package/dist/assets/{MarkdownRendererImpl-CRWbN_Jc.js → MarkdownRendererImpl-DUVe8Jgr.js} +1 -1
  15. package/dist/assets/{PatchDiff-B0ssv8Aw.js → PatchDiff-BOQB83iO.js} +1 -1
  16. package/dist/assets/{SessionSwitcherContent-NmfI4B0Z.js → SessionSwitcherContent-CM0g0Dpg.js} +1 -1
  17. package/dist/assets/{SessionSwitcherDropdown-DmE2hYTN.js → SessionSwitcherDropdown-CY3BW56O.js} +2 -2
  18. package/dist/assets/{SessionUnreadDot-LDTswryg.js → SessionUnreadDot-C5HBuQ4W.js} +1 -1
  19. package/dist/assets/SettingsView-A76k5FgH.js +2 -0
  20. package/dist/assets/{SettingsWindow-BT2TzUBK.js → SettingsWindow-CN8AWf_3.js} +1 -1
  21. package/dist/assets/{ToolOutputDialog-Bnl51bva.js → ToolOutputDialog-CkdWr3lC.js} +1 -1
  22. package/dist/assets/{ToolPartDiffPreview-DgPtLS_h.js → ToolPartDiffPreview-B3aR120P.js} +1 -1
  23. package/dist/assets/{VirtualizedFileDiff-D3zBpYIS.js → VirtualizedFileDiff-D05_VUdJ.js} +1 -1
  24. package/dist/assets/{collapsible-_urywMu5.js → collapsible-B6bVtxgp.js} +1 -1
  25. package/dist/assets/{computeVirtualFileMetrics-y2AJzpKw.js → computeVirtualFileMetrics-DVysbU8X.js} +1 -1
  26. package/dist/assets/{contextFileOpenGuard-DYUFkrPT.js → contextFileOpenGuard-HuJGM1Zp.js} +1 -1
  27. package/dist/assets/{gitStatusPredicates-CbFfOlbV.js → gitStatusPredicates-Ben2Ocei.js} +1 -1
  28. package/dist/assets/{index-CrqlVJXp.js → index-BOtRfXre.js} +3 -3
  29. package/dist/assets/{index-DwJJarzh.js → index-CKU5yG8s.js} +1 -1
  30. package/dist/assets/{isDiffPlainText-kXPOivsq.js → isDiffPlainText--C9XSjKy.js} +1 -1
  31. package/dist/assets/{isFilePlainText-BBIPqnLo.js → isFilePlainText-N64kYHDs.js} +1 -1
  32. package/dist/assets/{main-BshSYpnV.js → main-BPsZ4uEs.js} +3 -3
  33. package/dist/assets/{main-RrPyfmCA.js → main-Uqvwxvkq.js} +2 -2
  34. package/dist/assets/{markdownCore-BxXmpZtB.js → markdownCore-C9WMRP3A.js} +1 -1
  35. package/dist/assets/{miniChat-DRNgmC-q.js → miniChat-N1QvufvH.js} +2 -2
  36. package/dist/assets/{mobile-CdmgVKW4.js → mobile-Dw6ZxnWP.js} +2 -2
  37. package/dist/assets/{renderElectronMiniChatApp-B80Jqq8b.js → renderElectronMiniChatApp-DknVCBkh.js} +2 -2
  38. package/dist/assets/{renderMobileApp-CLcBvRiy.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-Dp6vM-Zr.js → useAppFontEffects-BJ2NAj4u.js} +7 -7
  42. package/dist/assets/{useFilesViewSearch-Bc8PTYrg.js → useFilesViewSearch-Dmu3k5Hy.js} +1 -1
  43. package/dist/assets/{usePushVisibilityBeacon-DMcKyNtE.js → usePushVisibilityBeacon-DR77-ud4.js} +1 -1
  44. package/dist/assets/{useSwitcherItems-DEvsORZ_.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-DLimsiRH.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-05Oa3k7a.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-D0iw6y_H.js +0 -2
  66. package/dist/assets/runtimeEndpointReset-DHHCemOu.js +0 -53
@@ -55,7 +55,7 @@ const LOCAL_FIELDS = new Set([
55
55
  'terminalShell', 'terminalLoginShells', 'desktopLanAccessEnabled',
56
56
  'desktopKeepAwakeEnabled', 'desktopProcessPerformanceRecordingEnabled',
57
57
  'desktopMinimizeToTrayEnabled', 'desktopCloseToTrayEnabled', 'desktopMacMenuBarEnabled',
58
- 'desktopUpdateChannel',
58
+ 'desktopUpdateChannel', 'serverUpdateChannel',
59
59
  'desktopWindowState', 'desktopLocalPort', 'desktopInstallId', 'desktopHosts',
60
60
  'desktopDefaultHostId', 'desktopInitialHostChoiceCompleted',
61
61
  'pwaAppName', 'pwaOrientation', 'mobileKeyboardMode',
@@ -158,10 +158,12 @@ export const createPiUiSettingsStore = ({
158
158
 
159
159
  const write = async (changes) => {
160
160
  validateRecord(changes);
161
- if (Object.hasOwn(changes, 'desktopUpdateChannel')
162
- && changes.desktopUpdateChannel !== 'stable'
163
- && changes.desktopUpdateChannel !== 'rc') {
164
- throw new Error('UI_SETTINGS_INVALID');
161
+ for (const field of ['desktopUpdateChannel', 'serverUpdateChannel']) {
162
+ if (Object.hasOwn(changes, field)
163
+ && changes[field] !== 'stable'
164
+ && changes[field] !== 'rc') {
165
+ throw new Error('UI_SETTINGS_INVALID');
166
+ }
165
167
  }
166
168
  return runMutation(async () => {
167
169
  const current = await readLocked();
@@ -85,20 +85,22 @@ describe('Pi UI settings store', () => {
85
85
  });
86
86
  });
87
87
 
88
- it('persists the desktop update subscription locally and rejects unknown channels', async () => {
88
+ it('persists desktop and server update subscriptions locally and rejects unknown channels', async () => {
89
89
  const { file, runtimeFile, store } = await makeStore();
90
90
 
91
- await expect(store.write({ themeId: 'dark', desktopUpdateChannel: 'rc' })).resolves.toMatchObject({
91
+ await expect(store.write({ themeId: 'dark', desktopUpdateChannel: 'rc', serverUpdateChannel: 'stable' })).resolves.toMatchObject({
92
92
  themeId: 'dark',
93
93
  desktopUpdateChannel: 'rc',
94
+ serverUpdateChannel: 'stable',
94
95
  });
95
96
  await expect(readJson(file)).resolves.toEqual({
96
97
  __pichamberSettingsScope: 'portable-v1',
97
98
  themeId: 'dark',
98
99
  });
99
- await expect(readJson(runtimeFile)).resolves.toEqual({ desktopUpdateChannel: 'rc' });
100
+ await expect(readJson(runtimeFile)).resolves.toEqual({ desktopUpdateChannel: 'rc', serverUpdateChannel: 'stable' });
100
101
  await expect(store.write({ desktopUpdateChannel: 'beta' })).rejects.toThrow('UI_SETTINGS_INVALID');
101
- await expect(store.read()).resolves.toMatchObject({ desktopUpdateChannel: 'rc' });
102
+ await expect(store.write({ serverUpdateChannel: 'nightly' })).rejects.toThrow('UI_SETTINGS_INVALID');
103
+ await expect(store.read()).resolves.toMatchObject({ desktopUpdateChannel: 'rc', serverUpdateChannel: 'stable' });
102
104
  });
103
105
 
104
106
  it('rejects prototype-polluting keys', async () => {
@@ -25,7 +25,7 @@ HTTP remains the authenticated command plane for create, resize, appearance upda
25
25
  - Concurrent creates for one ID are single-flight only when working directory and shell preference match. Existing IDs cannot be reused for another working directory.
26
26
  - Dimensions are bounded to 1-1000 columns and 1-500 rows; input is capped at 64 KiB.
27
27
  - A client may create before its renderer has mounted. It derives an initial size from the container and font metrics (falling back to 80x24 when unavailable), then sends a resize once the renderer reports its final dimensions. This allows shell startup and renderer initialization to overlap.
28
- - PTY children explicitly clear `NODE_CHANNEL_FD`; daemon IPC descriptors are host-private and invalid after PTY descriptor cleanup.
28
+ - PTY children explicitly clear `NODE_CHANNEL_FD`; daemon IPC descriptors are host-private and invalid after PTY descriptor cleanup. They carry `PICHAMBER_SERVER_TERMINAL=1` so lifecycle commands can distinguish a browser terminal descended from the server from a normal SSH or local shell; startup environment snapshots never persist this marker.
29
29
  - PTY children also strip AppImage `ARGV0` (and other host-private shell vars such as `ELECTRON_RUN_AS_NODE`, `BASH_ENV`, `ENV`, `BASH_XTRACEFD`). An exported `ARGV0` makes zsh rewrite argv[0] for every external command, which breaks Python venv detection and other argv[0]/$0 consumers while leaving `/proc/self/exe` correct. On Linux, PTY spawn is wrapped with `env -u ARGV0` because `bun-pty` merges the native OS environ and would otherwise reintroduce `ARGV0` after a JS-only delete.
30
30
  - `GET /api/terminal/shells` reports shell IDs available on the active server using the same augmented PATH provided to spawned PTYs, plus whether each executable has a supported login-mode argument. `auto` preserves environment/platform fallback order; an explicit unavailable shell fails creation instead of silently running a different shell. Login mode is opt-in and uses only built-in arguments for known shells. Preference changes affect new sessions and explicit restarts, not running PTYs.
31
31
  - PTY data and exit callbacks enter one FIFO queue. Stale callbacks from replaced processes are ignored.
@@ -66,7 +66,7 @@ export function createTerminalRuntime({
66
66
  const args = loginShell ? getTerminalShellLoginArgs(executable) : [];
67
67
  if (!args) throw new Error(`Terminal shell "${resolvedShell.id}" does not support login mode`);
68
68
  try {
69
- const env = { ...process.env, PATH: buildAugmentedPath(), TERM: 'xterm-256color', COLORTERM: 'truecolor', COLORFGBG: themeMode === 'light' ? '0;15' : '15;0' };
69
+ const env = { ...process.env, PATH: buildAugmentedPath(), TERM: 'xterm-256color', COLORTERM: 'truecolor', COLORFGBG: themeMode === 'light' ? '0;15' : '15;0', PICHAMBER_SERVER_TERMINAL: '1' };
70
70
  // The daemon's IPC fd is closed inside the PTY. An explicit override is
71
71
  // required because bun-pty also inherits Bun's native process environment.
72
72
  env.NODE_CHANNEL_FD = '';
@@ -154,6 +154,7 @@ describe('terminal runtime', () => {
154
154
  expect(harness.processes[0].options.cwd).toBe('/repo');
155
155
  expect(harness.processes[0].options.env.COLORFGBG).toBe('0;15');
156
156
  expect(harness.processes[0].options.env.NODE_CHANNEL_FD).toBe('');
157
+ expect(harness.processes[0].options.env.PICHAMBER_SERVER_TERMINAL).toBe('1');
157
158
  expect(harness.processes[0].options.env).not.toHaveProperty('ARGV0');
158
159
  expect(harness.processes[0].options.env).not.toHaveProperty('ELECTRON_RUN_AS_NODE');
159
160
  if (process.platform === 'linux') {
@@ -0,0 +1,173 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
3
+ import { dirname, join } from 'node:path';
4
+
5
+ import { resolvePiChamberDataDir } from './pichamber-data-dir.js';
6
+ import { withCrossProcessLock } from './server/cross-process-lock.js';
7
+
8
+ const UPDATE_JOB_STATES = new Set(['queued', 'installing', 'verifying', 'restarting', 'complete', 'failed']);
9
+ const ACTIVE_UPDATE_STATES = new Set(['queued', 'installing', 'verifying', 'restarting']);
10
+ const UPDATE_JOB_MAX_AGE_MS = 30 * 60 * 1000;
11
+ const UPDATE_JOB_STARTUP_GRACE_MS = 30 * 1000;
12
+ const UPDATE_JOB_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
13
+ const UPDATE_CHANNELS = new Set(['stable', 'rc']);
14
+
15
+ const invalidJobError = () => {
16
+ const error = new Error('Update status is invalid.');
17
+ error.code = 'UPDATE_JOB_INVALID';
18
+ return error;
19
+ };
20
+
21
+ const normalizeError = (value) => {
22
+ if (typeof value !== 'string') return undefined;
23
+ const trimmed = value.trim();
24
+ return trimmed.length > 0 ? trimmed.slice(0, 2000) : undefined;
25
+ };
26
+
27
+ const isValidJob = (job) => (
28
+ job
29
+ && typeof job === 'object'
30
+ && !Array.isArray(job)
31
+ && UPDATE_JOB_ID_PATTERN.test(job.id)
32
+ && UPDATE_JOB_STATES.has(job.state)
33
+ && Number.isFinite(job.startedAt)
34
+ && Number.isFinite(job.updatedAt)
35
+ && (job.channel === undefined || UPDATE_CHANNELS.has(job.channel))
36
+ );
37
+
38
+ export const createUpdateJobStore = ({
39
+ file = join(resolvePiChamberDataDir(), 'run', 'update-job.json'),
40
+ now = () => Date.now(),
41
+ createId = randomUUID,
42
+ maxAgeMs = UPDATE_JOB_MAX_AGE_MS,
43
+ startupGraceMs = UPDATE_JOB_STARTUP_GRACE_MS,
44
+ processLike = process,
45
+ } = {}) => {
46
+ const lockFile = `${file}.lock`;
47
+
48
+ const readFileValue = async () => {
49
+ try {
50
+ const parsed = JSON.parse(await readFile(file, 'utf8'));
51
+ if (!isValidJob(parsed)) throw invalidJobError();
52
+ return parsed;
53
+ } catch (error) {
54
+ if (error?.code === 'ENOENT') return null;
55
+ if (error?.code === 'UPDATE_JOB_INVALID') throw error;
56
+ throw invalidJobError();
57
+ }
58
+ };
59
+
60
+ const writeFileValue = async (job) => {
61
+ await mkdir(dirname(file), { recursive: true, mode: 0o700 });
62
+ const temporary = `${file}.${process.pid}.tmp`;
63
+ await writeFile(temporary, JSON.stringify(job), { mode: 0o600 });
64
+ await rename(temporary, file);
65
+ return job;
66
+ };
67
+
68
+ const reconcileActiveJob = async (job, timestamp) => {
69
+ if (!job || !ACTIVE_UPDATE_STATES.has(job.state)) return job;
70
+
71
+ const age = timestamp - job.updatedAt;
72
+ if (!Number.isInteger(job.workerPid) || job.workerPid <= 0) {
73
+ const graceMs = job.state === 'queued' ? Math.min(startupGraceMs, maxAgeMs) : maxAgeMs;
74
+ if (age >= 0 && age <= graceMs) return job;
75
+ return writeFileValue({
76
+ ...job,
77
+ state: 'failed',
78
+ updatedAt: timestamp,
79
+ error: job.state === 'queued'
80
+ ? 'The update worker did not start within the allowed time. Run: pichamber update'
81
+ : 'The update worker stopped before recording its process ID. Run: pichamber update',
82
+ });
83
+ }
84
+
85
+ try {
86
+ processLike.kill(job.workerPid, 0);
87
+ return job;
88
+ } catch (error) {
89
+ if (error?.code === 'EPERM') return job;
90
+ return writeFileValue({
91
+ ...job,
92
+ state: 'failed',
93
+ updatedAt: timestamp,
94
+ error: 'The update worker exited before the update completed. Run: pichamber update',
95
+ });
96
+ }
97
+ };
98
+
99
+ const claim = async ({ previousVersion, targetVersion, packageManager, channel } = {}) => withCrossProcessLock(lockFile, async () => {
100
+ let current = null;
101
+ try {
102
+ current = await readFileValue();
103
+ } catch (error) {
104
+ if (error?.code !== 'UPDATE_JOB_INVALID') throw error;
105
+ }
106
+ const timestamp = now();
107
+ current = await reconcileActiveJob(current, timestamp);
108
+ if (current && ACTIVE_UPDATE_STATES.has(current.state)) {
109
+ return { job: current, created: false };
110
+ }
111
+
112
+ const job = {
113
+ id: createId(),
114
+ state: 'queued',
115
+ previousVersion: typeof previousVersion === 'string' ? previousVersion : undefined,
116
+ targetVersion: typeof targetVersion === 'string' ? targetVersion : undefined,
117
+ packageManager: typeof packageManager === 'string' ? packageManager : undefined,
118
+ channel: UPDATE_CHANNELS.has(channel) ? channel : 'stable',
119
+ startedAt: timestamp,
120
+ updatedAt: timestamp,
121
+ };
122
+ await writeFileValue(job);
123
+ return { job, created: true };
124
+ });
125
+
126
+ const update = async (id, changes = {}) => {
127
+ if (!UPDATE_JOB_ID_PATTERN.test(id)) throw invalidJobError();
128
+ return withCrossProcessLock(lockFile, async () => {
129
+ const current = await readFileValue();
130
+ if (!current || current.id !== id) {
131
+ const error = new Error('Update job was not found.');
132
+ error.code = 'UPDATE_JOB_NOT_FOUND';
133
+ throw error;
134
+ }
135
+ if (changes.state !== undefined && !UPDATE_JOB_STATES.has(changes.state)) throw invalidJobError();
136
+ if (!ACTIVE_UPDATE_STATES.has(current.state) && changes.state !== undefined && changes.state !== current.state) {
137
+ const error = new Error('Update job is already in a terminal state.');
138
+ error.code = 'UPDATE_JOB_NOT_ACTIVE';
139
+ throw error;
140
+ }
141
+ if (changes.channel !== undefined && !UPDATE_CHANNELS.has(changes.channel)) throw invalidJobError();
142
+ const next = { ...current, updatedAt: now() };
143
+ for (const key of ['state', 'previousVersion', 'targetVersion', 'currentVersion', 'packageManager', 'channel']) {
144
+ if (typeof changes[key] === 'string' && changes[key].length > 0) next[key] = changes[key];
145
+ }
146
+ if (Number.isInteger(changes.workerPid) && changes.workerPid > 0) next.workerPid = changes.workerPid;
147
+ if (Object.hasOwn(changes, 'error')) {
148
+ const error = normalizeError(changes.error);
149
+ if (error) next.error = error;
150
+ else delete next.error;
151
+ }
152
+ await writeFileValue(next);
153
+ return next;
154
+ });
155
+ };
156
+
157
+ const read = async (id) => {
158
+ if (id !== undefined && !UPDATE_JOB_ID_PATTERN.test(id)) return null;
159
+ return withCrossProcessLock(lockFile, async () => {
160
+ const job = await readFileValue();
161
+ if (!job || (id !== undefined && job.id !== id)) return null;
162
+ return reconcileActiveJob(job, now());
163
+ });
164
+ };
165
+
166
+ return { claim, read, update };
167
+ };
168
+
169
+ const defaultUpdateJobStore = createUpdateJobStore();
170
+
171
+ export const claimUpdateJob = (details) => defaultUpdateJobStore.claim(details);
172
+ export const readUpdateJob = (id) => defaultUpdateJobStore.read(id);
173
+ export const updateUpdateJob = (id, changes) => defaultUpdateJobStore.update(id, changes);
@@ -0,0 +1,179 @@
1
+ import { mkdtemp, readFile, rm } from 'node:fs/promises';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { afterEach, describe, expect, it } from 'vitest';
5
+
6
+ import { createUpdateJobStore } from './update-job-store.js';
7
+
8
+ const temporaryDirectories = [];
9
+
10
+ const createStore = async (options = {}) => {
11
+ const directory = await mkdtemp(path.join(os.tmpdir(), 'pichamber-update-job-'));
12
+ temporaryDirectories.push(directory);
13
+ return {
14
+ file: path.join(directory, 'run', 'update-job.json'),
15
+ store: createUpdateJobStore({ file: path.join(directory, 'run', 'update-job.json'), ...options }),
16
+ };
17
+ };
18
+
19
+ afterEach(async () => {
20
+ await Promise.all(temporaryDirectories.splice(0).map((directory) => rm(directory, { recursive: true, force: true })));
21
+ });
22
+
23
+ describe('update job store', () => {
24
+ it('persists update state without secrets and reads it after recreation', async () => {
25
+ const id = '10000000-0000-4000-8000-000000000001';
26
+ const { file, store } = await createStore({ createId: () => id, now: () => 100 });
27
+
28
+ await store.claim({ previousVersion: '1.0.0', targetVersion: '2.0.0-rc.2', packageManager: 'npm', channel: 'rc' });
29
+ await store.update(id, { state: 'installing' });
30
+
31
+ await expect(createUpdateJobStore({ file, now: () => 100 }).read(id)).resolves.toMatchObject({
32
+ id,
33
+ state: 'installing',
34
+ previousVersion: '1.0.0',
35
+ targetVersion: '2.0.0-rc.2',
36
+ packageManager: 'npm',
37
+ channel: 'rc',
38
+ });
39
+ expect(await readFile(file, 'utf8')).not.toContain('password');
40
+ });
41
+
42
+ it('returns an active job instead of starting a concurrent update', async () => {
43
+ const { store } = await createStore({
44
+ createId: () => '10000000-0000-4000-8000-000000000001',
45
+ now: () => 100,
46
+ });
47
+
48
+ const first = await store.claim();
49
+ const second = await store.claim();
50
+
51
+ expect(first.created).toBe(true);
52
+ expect(second).toEqual({ job: first.job, created: false });
53
+ });
54
+
55
+ it('replaces a stale active job', async () => {
56
+ let timestamp = 100;
57
+ let sequence = 0;
58
+ const ids = [
59
+ '10000000-0000-4000-8000-000000000001',
60
+ '10000000-0000-4000-8000-000000000002',
61
+ ];
62
+ const { store } = await createStore({
63
+ createId: () => ids[sequence++],
64
+ now: () => timestamp,
65
+ maxAgeMs: 50,
66
+ });
67
+
68
+ const first = await store.claim();
69
+ timestamp = 151;
70
+ const second = await store.claim();
71
+
72
+ expect(second.created).toBe(true);
73
+ expect(second.job.id).not.toBe(first.job.id);
74
+ });
75
+
76
+ it('marks an active job failed when its worker has exited', async () => {
77
+ const id = '10000000-0000-4000-8000-000000000001';
78
+ const { store } = await createStore({
79
+ createId: () => id,
80
+ now: () => 100,
81
+ processLike: { kill: () => { const error = new Error('missing'); error.code = 'ESRCH'; throw error; } },
82
+ });
83
+ const first = await store.claim();
84
+ await store.update(first.job.id, { state: 'installing', workerPid: 12345 });
85
+
86
+ await expect(store.read(id)).resolves.toMatchObject({
87
+ id,
88
+ state: 'failed',
89
+ error: expect.stringContaining('worker exited'),
90
+ });
91
+ });
92
+
93
+ it('fails a queued job when its worker does not start within the grace period', async () => {
94
+ let timestamp = 100;
95
+ const id = '10000000-0000-4000-8000-000000000001';
96
+ const { store } = await createStore({
97
+ createId: () => id,
98
+ now: () => timestamp,
99
+ startupGraceMs: 30_000,
100
+ });
101
+ await store.claim();
102
+ timestamp += 30_001;
103
+
104
+ await expect(store.read(id)).resolves.toMatchObject({
105
+ id,
106
+ state: 'failed',
107
+ error: expect.stringContaining('did not start'),
108
+ });
109
+ });
110
+
111
+ it('allows retry immediately when a claimed worker has exited', async () => {
112
+ let sequence = 0;
113
+ const ids = [
114
+ '10000000-0000-4000-8000-000000000001',
115
+ '10000000-0000-4000-8000-000000000002',
116
+ ];
117
+ const { store } = await createStore({
118
+ createId: () => ids[sequence++],
119
+ now: () => 100,
120
+ processLike: { kill: () => { const error = new Error('missing'); error.code = 'ESRCH'; throw error; } },
121
+ });
122
+ const first = await store.claim();
123
+ await store.update(first.job.id, { state: 'installing', workerPid: 12345 });
124
+
125
+ const retried = await store.claim();
126
+
127
+ expect(retried.created).toBe(true);
128
+ expect(retried.job.id).toBe(ids[1]);
129
+ });
130
+
131
+ it('does not let a delayed worker reactivate a failed job', async () => {
132
+ const id = '10000000-0000-4000-8000-000000000001';
133
+ const { store } = await createStore({ createId: () => id, now: () => 100 });
134
+ await store.claim();
135
+ await store.update(id, { state: 'failed', error: 'Worker startup timed out' });
136
+
137
+ await expect(store.update(id, { state: 'installing', workerPid: 12345 })).rejects.toMatchObject({
138
+ code: 'UPDATE_JOB_NOT_ACTIVE',
139
+ });
140
+ });
141
+
142
+ it('protects job identity and start time from status patches', async () => {
143
+ const id = '10000000-0000-4000-8000-000000000001';
144
+ const { store } = await createStore({ createId: () => id, now: () => 100 });
145
+ await store.claim();
146
+
147
+ const updated = await store.update(id, {
148
+ state: 'installing',
149
+ id: '10000000-0000-4000-8000-000000000002',
150
+ startedAt: 999,
151
+ unexpected: 'value',
152
+ });
153
+
154
+ expect(updated).toMatchObject({ id, startedAt: 100, state: 'installing' });
155
+ expect(updated).not.toHaveProperty('unexpected');
156
+ });
157
+
158
+ it('does not let an old worker overwrite a newer job', async () => {
159
+ let timestamp = 100;
160
+ let sequence = 0;
161
+ const ids = [
162
+ '10000000-0000-4000-8000-000000000001',
163
+ '10000000-0000-4000-8000-000000000002',
164
+ ];
165
+ const { store } = await createStore({
166
+ createId: () => ids[sequence++],
167
+ now: () => timestamp,
168
+ maxAgeMs: 50,
169
+ });
170
+
171
+ const first = await store.claim();
172
+ timestamp = 151;
173
+ await store.claim();
174
+
175
+ await expect(store.update(first.job.id, { state: 'complete' })).rejects.toMatchObject({
176
+ code: 'UPDATE_JOB_NOT_FOUND',
177
+ });
178
+ });
179
+ });