ccdeck 3.81.0 → 3.81.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.
@@ -1 +1 @@
1
- import"./app-l0spNrc0.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const e of document.querySelectorAll('link[rel="modulepreload"]'))i(e);new MutationObserver(e=>{for(const r of e)if(r.type==="childList")for(const o of r.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function s(e){const r={};return e.integrity&&(r.integrity=e.integrity),e.referrerPolicy&&(r.referrerPolicy=e.referrerPolicy),e.crossOrigin==="use-credentials"?r.credentials="include":e.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(e){if(e.ep)return;e.ep=!0;const r=s(e);fetch(e.href,r)}})();
1
+ import"./app-uL65pD1B.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const e of document.querySelectorAll('link[rel="modulepreload"]'))i(e);new MutationObserver(e=>{for(const r of e)if(r.type==="childList")for(const o of r.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function s(e){const r={};return e.integrity&&(r.integrity=e.integrity),e.referrerPolicy&&(r.referrerPolicy=e.referrerPolicy),e.crossOrigin==="use-credentials"?r.credentials="include":e.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(e){if(e.ep)return;e.ep=!0;const r=s(e);fetch(e.href,r)}})();
@@ -77,8 +77,8 @@
77
77
  document.documentElement.setAttribute("data-density", density === "tightest" || density === "tighter" || density === "compact" || density === "comfortable" ? density : "default");
78
78
  })();
79
79
  </script>
80
- <script type="module" crossorigin src="/assets/index-inV7HzhI.js"></script>
81
- <link rel="modulepreload" crossorigin href="/assets/app-l0spNrc0.js">
80
+ <script type="module" crossorigin src="/assets/index-4-WbGg1k.js"></script>
81
+ <link rel="modulepreload" crossorigin href="/assets/app-uL65pD1B.js">
82
82
  <link rel="stylesheet" crossorigin href="/assets/app-BIrh5Q0W.css">
83
83
  </head>
84
84
  <body>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ccdeck",
3
- "version": "3.81.0",
3
+ "version": "3.81.2",
4
4
  "description": "Local dashboard for Claude Code and Codex CLI sessions: which Claude Code session needs input, every tool call and Claude Code subagent live, token cost and quota, several Claude accounts. Run npx ccdeck.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -84,6 +84,8 @@
84
84
  "without one."
85
85
  ],
86
86
  "//summaries": {
87
+ "3.81.2": "Codex account switches wait through activity changes",
88
+ "3.81.1": "Codex reconnection and Windows fixes",
87
89
  "3.81.0": "Codex accounts on a par with Claude's, Codex over Local network, and ccdeck tui for the whole deck",
88
90
  "3.80.0": "Codex account switching, continuation and sharing",
89
91
  "3.53.0": "Codex accounts, with sign-in, switching and Auto-switch",
@@ -136,6 +138,41 @@
136
138
  "3.53.1",
137
139
  "3.53.3"
138
140
  ],
141
+ "3.81.2": [
142
+ {
143
+ "title": "Codex account switches wait through activity changes",
144
+ "body": "If new work starts while a switch is being prepared, ccdeck now waits and retries safely instead of leaving the switch failed.",
145
+ "priority": "highlight",
146
+ "icon": "accounts"
147
+ }
148
+ ],
149
+ "3.81.1": [
150
+ {
151
+ "title": "Fix Codex sharing on Windows",
152
+ "body": "Codex logins blocked by Windows folder permissions can now be prepared for sharing from the Share dialog.",
153
+ "priority": "highlight",
154
+ "icon": "accounts",
155
+ "noticeLabel": "Folder permissions",
156
+ "notice": "Secure permissions and share is optional and restricts the selected Codex folders and auth.json to your Windows user, including changes to inherited access for their contents. Your login, settings and active account stay in place. Automatic network sync never changes folder permissions."
157
+ },
158
+ {
159
+ "title": "Windows updates reach the copy you use",
160
+ "body": "Global npm updates now target the active installation and confirm that newer files arrived before showing installed.",
161
+ "priority": "highlight",
162
+ "noticeLabel": "Already stuck?",
163
+ "notice": "An older Windows installation already stuck at installed may need one manual update to receive this fix. For the desktop app, run the latest Windows installer. For npm, follow the Windows recovery steps in README, then restart ccdeck. Accounts and settings are kept."
164
+ },
165
+ {
166
+ "title": "Reconnect Codex without a false login-change warning",
167
+ "body": "Connecting to an unchanged Codex account no longer pauses control because of its initial account update.",
168
+ "priority": "highlight",
169
+ "icon": "accounts"
170
+ },
171
+ {
172
+ "title": "See why a shared login did not arrive",
173
+ "body": "The network map now shows a failed transfer instead of promising that the login will arrive next round."
174
+ }
175
+ ],
139
176
  "3.81.0": [
140
177
  {
141
178
  "title": "👥 Codex accounts work the way Claude's do",
@@ -56,14 +56,14 @@ export async function handleCodexAccountShare(req, res, action) {
56
56
  const raw = await readBody(req, res, CODEX_SHARE_MAX_LENGTH + 4096).catch(() => null);
57
57
  let body;
58
58
  try { body = JSON.parse(raw ?? ''); } catch { return send(res, 400, { ok: false, reason: 'bad_request' }); }
59
- const allowed = action === 'export' ? ['ids'] : ['blob', 'expectedRevision'];
59
+ const allowed = action === 'export' ? ['ids', 'preparePermissions'] : ['blob', 'expectedRevision'];
60
60
  if (!body || typeof body !== 'object' || Array.isArray(body) || Object.keys(body).some(key => !allowed.includes(key))) {
61
61
  return send(res, 400, { ok: false, reason: 'bad_request' });
62
62
  }
63
63
  const result = await (action === 'export' ? createCodexShare(body) : importCodexShare(body));
64
64
  send(res, 200, result);
65
65
  } catch (error) {
66
- const safe = new Set(['invalid_profiles', 'unknown_profile', 'file_auth_required', 'unsupported_auth', 'share_too_large', 'invalid_share', 'invalid_revision', 'selection_conflict', 'selection_busy', 'registry_corrupt', 'registry_write_failed', 'profile_unavailable', 'import_write_failed', 'windows_permissions_failed']);
66
+ const safe = new Set(['invalid_profiles', 'unknown_profile', 'file_auth_required', 'unsupported_auth', 'share_too_large', 'invalid_share', 'invalid_revision', 'selection_conflict', 'selection_busy', 'registry_corrupt', 'registry_write_failed', 'profile_unavailable', 'import_write_failed', 'windows_permissions_failed', 'windows_permissions_required', 'windows_share_protection_failed']);
67
67
  const reason = safe.has(error?.code) ? error.code : 'share_failed';
68
68
  send(res, ['selection_conflict', 'selection_busy'].includes(reason) ? 409 : reason === 'unknown_profile' ? 404 : 400, { ok: false, reason });
69
69
  }
@@ -111,7 +111,7 @@ export function createCodexLiveAccountController(input = {}) {
111
111
  }
112
112
  if (message.method === 'account/login/completed') {
113
113
  if (login && !login.completed && message.params?.loginId === null && message.params?.success === true) login.completed = true;
114
- else if (login) invalidateOwnership();
114
+ else invalidateOwnership();
115
115
  } else if (message.method === 'account/updated') {
116
116
  // Native external-token login sends its RPC result, then login/completed,
117
117
  // then updated (account_processor.rs, rust-v0.166.0). Consume only that
@@ -170,9 +170,18 @@ export function createCodexLiveAccountController(input = {}) {
170
170
  if (!await lease.valid()) throw liveError('native_control_lost');
171
171
  endpoint = next;
172
172
  const serial = ++connectionSerial;
173
+ let readingInitialAccount = true;
174
+ let initialUpdate = false, resolveInitialUpdate;
175
+ const initialAccountReady = new Promise(resolve => { resolveInitialUpdate = resolve; });
173
176
  rpc = await connect(next, {
174
177
  onRequest: m => serial === connectionSerial ? serverRequest(m) : undefined,
175
178
  onNotification: m => {
179
+ // New connections receive an account/updated routing snapshot even
180
+ // when no login changed. Establish the account baseline first; restore
181
+ // and reconnect still attest its native IDs before reclaiming control.
182
+ if (!closed && serial === connectionSerial && readingInitialAccount && !initialUpdate && m.method === 'account/updated') {
183
+ initialUpdate = true; resolveInitialUpdate(); return;
184
+ }
176
185
  const observe = () => { if (!closed && serial === connectionSerial) accountNotification(m); };
177
186
  // A WebSocket read can contain the result and both notifications. Let
178
187
  // its already-resolved RPC continuation mark the acknowledgement first,
@@ -185,7 +194,24 @@ export function createCodexLiveAccountController(input = {}) {
185
194
  rpc = null; if (!closed && owned) update({ state: 'disconnected', reason: 'native_disconnected' });
186
195
  },
187
196
  });
188
- const account = await rpc.request('account/read', { refreshToken: false });
197
+ let account;
198
+ try {
199
+ account = await rpc.request('account/read', { refreshToken: false });
200
+ // Routing discovery notifies each initialized connection asynchronously,
201
+ // including after account/read has answered. Do not mistake that delayed
202
+ // snapshot for an outside login, or claim ownership before it arrives.
203
+ if (account.workspaceRouting && !initialUpdate) {
204
+ let timeout;
205
+ try {
206
+ await Promise.race([initialAccountReady, new Promise((_, reject) => {
207
+ timeout = setTimeout(() => reject(liveError('native_initial_account_unconfirmed')),
208
+ options.initialAccountTimeoutMs ?? 30_000);
209
+ })]);
210
+ } finally { clearTimeout(timeout); }
211
+ account = await rpc.request('account/read', { refreshToken: false });
212
+ }
213
+ }
214
+ finally { readingInitialAccount = false; }
189
215
  if (account.account && account.account.type !== 'chatgpt') { rpc.close(); rpc = null; owned = false; throw liveError('unsupported_auth_mode'); }
190
216
  }
191
217
  async function loginCredential(id, refresh = false) {
@@ -320,6 +346,17 @@ export function createCodexLiveAccountController(input = {}) {
320
346
  }
321
347
  } catch (error) {
322
348
  handoff ??= error.handoff;
349
+ // Activity may start between the handoff snapshot and the final quiet
350
+ // check. If nothing was sent, retain the current selection and observe
351
+ // again instead of turning a harmless race into a permanent failure.
352
+ // Any durable interrupt/checkpoint or possible login stays on the
353
+ // existing recovery path: uncertain work must never be replayed.
354
+ if (error.code === 'native_activity_changed' && !maybeApplied && !checkpoint
355
+ && !journal.entries.length && !handoff?.paused?.length && owner() && await lease?.valid()) {
356
+ defer(intent, refresh, automatic);
357
+ update({ state: 'waiting', requestedProfileId: intent.id, reason: 'native_tools_active', continuation: 'waiting' });
358
+ return status();
359
+ }
323
360
  const lostControl = ['native_control_lost', 'account_changed_outside_deck', 'native_disconnected'].includes(error.code);
324
361
  if (!maybeApplied && !lostControl && handoff?.paused?.length && rpc && !closed) {
325
362
  try { await resume(); } catch { update({ continuation: 'manual_required' }); }
@@ -7,7 +7,7 @@ import { chmod, lstat, mkdir, open, readFile, unlink } from 'node:fs/promises';
7
7
  import { join } from 'node:path';
8
8
  import { createTemp, renameWithRetry } from './atomic-write.mjs';
9
9
  import { readCodexSelection, importCodexProfiles, withCodexProfileLocked } from './codex-selection.mjs';
10
- import { ensureWindowsPrivateDirectory, holdWindowsPrivatePath } from './codex-windows-private.mjs';
10
+ import { ensureWindowsPrivateDirectory, holdWindowsPrivatePath, protectWindowsCodexLogin } from './codex-windows-private.mjs';
11
11
 
12
12
  export const CODEX_SHARE_PREFIX = 'ccdeck-codex-v1.';
13
13
  export const CODEX_SHARE_MAX_LENGTH = 512_000;
@@ -80,23 +80,30 @@ function requireFileStore(config) {
80
80
  }
81
81
  }
82
82
 
83
+ async function requireFileStoreAt(home) {
84
+ let config = '';
85
+ try {
86
+ const file = join(home, 'config.toml');
87
+ if ((await lstat(file)).size > 128_000) fail('unsupported_auth');
88
+ config = await readFile(file, 'utf8');
89
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
90
+ requireFileStore(config);
91
+ }
92
+
83
93
  async function readFileAuth(home, options) {
84
94
  const platform = options.platform ?? process.platform;
85
95
  let handle, guard;
86
96
  try {
87
97
  // A non-file store can leave a stale auth.json behind. Never export that
88
98
  // stale copy as if it were the actual native login. Unknown TOML is refused.
89
- let config = '';
90
- try {
91
- const file = join(home, 'config.toml');
92
- if ((await lstat(file)).size > 128_000) fail('unsupported_auth');
93
- config = await readFile(file, 'utf8');
94
- } catch (error) { if (error.code !== 'ENOENT') throw error; }
95
- requireFileStore(config);
99
+ await requireFileStoreAt(home);
96
100
  const file = join(home, 'auth.json');
97
- if (platform === 'win32') guard = await holdWindowsPrivatePath(file, { ...options, kind: 'file' });
98
101
  const before = await lstat(file);
99
102
  privateAuthFile(before, platform);
103
+ if (platform === 'win32') {
104
+ try { guard = await holdWindowsPrivatePath(file, { ...options, kind: 'file' }); }
105
+ catch { fail('windows_permissions_required'); }
106
+ }
100
107
  handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
101
108
  const opened = await handle.stat();
102
109
  privateAuthFile(opened, platform);
@@ -110,18 +117,28 @@ async function readFileAuth(home, options) {
110
117
  if (guard && !guard.valid()) fail('file_auth_required');
111
118
  return chatgptAuth(JSON.parse(bytes.subarray(0, bytesRead).toString('utf8')));
112
119
  } catch (error) {
113
- if (['file_auth_required', 'unsupported_auth'].includes(error.code)) throw error;
120
+ if (['file_auth_required', 'unsupported_auth', 'windows_permissions_required'].includes(error.code)) throw error;
114
121
  fail('file_auth_required');
115
122
  } finally { try { await handle?.close(); } finally { await guard?.release(); } }
116
123
  }
117
124
 
118
125
  /** Called only by explicit POST export, against opaque registered profile IDs. */
119
- export async function createCodexShare({ ids } = {}, options = {}) {
126
+ export async function createCodexShare({ ids, preparePermissions = false } = {}, options = {}) {
120
127
  if (!Array.isArray(ids) || ids.length < 1 || ids.length > CODEX_SHARE_MAX_ACCOUNTS
121
128
  || new Set(ids).size !== ids.length || ids.some(id => typeof id !== 'string' || !/^[a-f0-9]{20}$/.test(id))) fail('invalid_profiles');
129
+ if (typeof preparePermissions !== 'boolean' || (preparePermissions && (options.platform ?? process.platform) !== 'win32')) fail('invalid_profiles');
122
130
  const selection = await readCodexSelection(options);
123
131
  const profiles = ids.map(id => selection.profiles.find(profile => profile.id === id));
124
132
  if (profiles.some(profile => !profile)) fail('unknown_profile');
133
+ if (preparePermissions) {
134
+ // The export and LAN paths never repair permissions implicitly. Check the
135
+ // credential store for the entire selection before this explicit action.
136
+ for (const profile of profiles) await requireFileStoreAt(profile.home);
137
+ for (const profile of profiles) {
138
+ try { await protectWindowsCodexLogin(profile.home, options); }
139
+ catch { fail('windows_share_protection_failed'); }
140
+ }
141
+ }
125
142
  const accounts = [];
126
143
  for (const profile of profiles) {
127
144
  const label = selection.profileLabels.find(entry => entry.id === profile.id)?.label ?? null;
@@ -42,6 +42,8 @@ async function check(path, operation, options) {
42
42
  * execFile is an async (file, args, options) => { stdout } test seam.
43
43
  */
44
44
  export const ensureWindowsPrivateDirectory = async (path, options = {}) => (await check(path, 'ensure', { ...options, kind: 'directory' })).path;
45
+ // Only the explicit Share repair may tighten an existing profile.
46
+ export const protectWindowsCodexLogin = async (path, options = {}) => (await check(path, 'protect-login', { ...options, kind: 'directory' })).path;
45
47
  export const assertWindowsPrivatePath = async (path, options = {}) => (await check(path, 'check', options)).path;
46
48
  export async function inspectWindowsPrivateSocket(path, options = {}) {
47
49
  const value = await check(path, 'check', { ...options, kind: 'socket' });
@@ -1,5 +1,5 @@
1
1
  param(
2
- [ValidateSet('ensure','check','hold')][string]$Operation,
2
+ [ValidateSet('ensure','check','hold','protect-login')][string]$Operation,
3
3
  [Parameter(Mandatory=$true)][string]$TargetPath,
4
4
  [ValidateSet('directory','file','socket')][string]$Kind = 'directory'
5
5
  )
@@ -83,6 +83,49 @@ public static class CodexPrivatePath {
83
83
  Require(userAccess);
84
84
  } finally { if (descriptor != IntPtr.Zero) LocalFree(descriptor); }
85
85
  }
86
+ // Explicit preparation only. Open both objects without following final
87
+ // reparse points or sharing deletion; modify security through those handles,
88
+ // never by looking up an unchecked path a second time. No credential bytes
89
+ // are read, copied or replaced here.
90
+ [DllImport("advapi32.dll", SetLastError=true)]
91
+ static extern uint SetSecurityInfo(SafeFileHandle h, uint type, uint what, IntPtr owner, IntPtr group, IntPtr dacl, IntPtr sacl);
92
+ static SafeFileHandle OpenForProtection(string path, bool directory) {
93
+ var h = CreateFileW(path, 0xe0081u, directory ? 3u : 1u,
94
+ IntPtr.Zero, 3, 0x02000000u | 0x00200000u, IntPtr.Zero);
95
+ if (h.IsInvalid) { h.Dispose(); throw new IOException("unsafe"); }
96
+ try {
97
+ FileInfo info; Require(GetFileInformationByHandle(h, out info));
98
+ Require((info.Attributes & 0x400u) == 0 && ((info.Attributes & 0x10u) != 0) == directory);
99
+ if (!directory) Require(info.Links == 1);
100
+ return h;
101
+ } catch { h.Dispose(); throw; }
102
+ }
103
+ static void Protect(SafeFileHandle h, bool directory) {
104
+ var user = WindowsIdentity.GetCurrent().User;
105
+ var sid = new byte[user.BinaryLength]; user.GetBinaryForm(sid, 0);
106
+ var acl = new RawAcl(2, 1);
107
+ acl.InsertAce(0, new CommonAce(directory ? AceFlags.ContainerInherit | AceFlags.ObjectInherit : AceFlags.None,
108
+ AceQualifier.AccessAllowed, 0x1f01ff, user, false, null));
109
+ var bytes = new byte[acl.BinaryLength]; acl.GetBinaryForm(bytes, 0);
110
+ var owner = GCHandle.Alloc(sid, GCHandleType.Pinned);
111
+ var dacl = GCHandle.Alloc(bytes, GCHandleType.Pinned);
112
+ try {
113
+ Require(SetSecurityInfo(h, 1, 0x80000005u, owner.AddrOfPinnedObject(), IntPtr.Zero, dacl.AddrOfPinnedObject(), IntPtr.Zero) == 0);
114
+ ValidateAcl(h, directory);
115
+ } finally { dacl.Free(); owner.Free(); }
116
+ }
117
+ public static string ProtectLogin(string path) {
118
+ Require(!String.Equals(Path.GetPathRoot(path).TrimEnd('\\'), path.TrimEnd('\\'), StringComparison.OrdinalIgnoreCase));
119
+ using (var directory = OpenForProtection(path, true)) {
120
+ string canonical = Canonical(directory);
121
+ using (var file = OpenForProtection(Path.Combine(canonical, "auth.json"), false)) {
122
+ Protect(file, false);
123
+ Protect(directory, true);
124
+ ValidateAcl(file, false);
125
+ }
126
+ return canonical;
127
+ }
128
+ }
86
129
  public static string SocketGeneration(string path) {
87
130
  // Node/libuv lstat returns EACCES on Windows AF_UNIX entries. Open only
88
131
  // reparse metadata, never follow a symlink/junction or read socket bytes.
@@ -111,6 +154,10 @@ public static class CodexPrivatePath {
111
154
  $guards = [System.Collections.Generic.List[System.IDisposable]]::new()
112
155
  try {
113
156
  $path = [IO.Path]::GetFullPath($TargetPath)
157
+ if ($Operation -eq 'protect-login') {
158
+ if ($Kind -ne 'directory') { throw 'unsafe' }
159
+ $null = [CodexPrivatePath]::ProtectLogin($path)
160
+ }
114
161
  if ($Operation -eq 'ensure') {
115
162
  if ($Kind -ne 'directory') { throw 'unsafe' }
116
163
  [CodexPrivatePath]::Ensure($path)
@@ -117,7 +117,10 @@ export function createCodexLan(options = {}) {
117
117
  const out = await (options.share ?? createCodexShare)({ ids: [id] }, options);
118
118
  const entries = readCodexShare(out?.blob);
119
119
  return entries.length === 1 && codexLoginOf(entries[0].auth)?.key === expectedKey ? out.blob : null;
120
- } catch { return null; }
120
+ } catch (err) {
121
+ if (err?.code === 'windows_permissions_required') throw Object.assign(new Error('windows_permissions_required'), { code: 'windows_permissions_required' });
122
+ return null;
123
+ }
121
124
  },
122
125
 
123
126
  /**
@@ -277,7 +277,7 @@ export const SENDER_UNREADABLE = "keychain_unavailable";
277
277
  * "refused". "in use" is the sending deck being on that login itself (#2192);
278
278
  * a deck older than that records it as "refused", which is all it proves. */
279
279
  export const IN_USE = "in use";
280
- const WIRE_REFUSALS = new Set(["proof", "not shared", "not mine to give", "export failed", SENDER_UNREADABLE, IN_USE, "error"]);
280
+ const WIRE_REFUSALS = new Set(["proof", "not shared", "not mine to give", "export failed", "windows_permissions_required", SENDER_UNREADABLE, IN_USE, "error"]);
281
281
 
282
282
  /**
283
283
  * A peer's refusal, as this deck records it. The panel prints these, so a peer
@@ -120,7 +120,12 @@ export function createServe({
120
120
  return ctx.send({ t: "no", why: "export failed" });
121
121
  }
122
122
  if (!maySend()) return ctx.send({ t: "no", why: "not shared" });
123
- const blob = codexWant ? await exportCodex(mine.num, msg.key) : await exportAccount(mine.num, msg.key);
123
+ let blob;
124
+ try { blob = codexWant ? await exportCodex(mine.num, msg.key) : await exportAccount(mine.num, msg.key); }
125
+ catch (err) {
126
+ if (codexWant && err?.code === 'windows_permissions_required') return ctx.send({ t: 'no', why: 'windows_permissions_required' });
127
+ throw err;
128
+ }
124
129
  if (!maySend()) return ctx.send({ t: "no", why: "not shared" });
125
130
  // A Mac's failed export refreshes the verdict behind `readable` in the
126
131
  // background, so when the Keychain was why, the next ask is answered by
@@ -166,7 +166,7 @@ async function handleUpgrade(_req, res) {
166
166
  // has finished booting this settled long ago; it only waits for a press that
167
167
  // lands in the first moments of a boot, or on a server nothing marked ready.
168
168
  await pinRunningBuild();
169
- const out = startUpgrade({ pkgRoot: PKG_ROOT });
169
+ const out = startUpgrade({ pkgRoot: PKG_ROOT, running: RUNNING_VERSION });
170
170
  if (out.ok) selfUpdateStarted();
171
171
  send(res, out.ok ? 200 : 409, out);
172
172
  }
@@ -414,7 +414,7 @@ async function awayUpdateTick() {
414
414
  // Pinned before npm is spawned, never after it — see pinned-build.mjs. On a
415
415
  // deck bin/deck.js has marked ready this is a promise that settled long ago.
416
416
  await pinRunningBuild();
417
- const started = su.startUpgrade({ pkgRoot: PKG_ROOT });
417
+ const started = su.startUpgrade({ pkgRoot: PKG_ROOT, running: RUNNING_VERSION });
418
418
  if (started?.ok) selfUpdateStarted();
419
419
  return step.act;
420
420
  }
@@ -9,14 +9,16 @@
9
9
  // upgrade is refused and how the last one went for the version report, and
10
10
  // re-exports every name, so index.mjs still reaches startUpgrade there. The
11
11
  // code is unchanged.
12
+ import { npmPrefix } from "./terminal-cli.mjs";
13
+ import { isOlder } from "./version-order.mjs";
12
14
  import { inApp } from "./app-host.mjs";
13
15
  import { accessSync, constants as FS, unlinkSync, writeFileSync } from "node:fs";
14
16
  import { spawn } from "node:child_process";
15
17
  import { join, resolve } from "node:path";
16
- import { killTree, shimPath, spawnSpec } from "./exec.mjs";
18
+ import { killTree, shimPath, spawnSpec, shellQuoteArg } from "./exec.mjs";
17
19
  import { npmCliLaunch } from "./npx.mjs";
18
20
  import {
19
- frozenNameInstall, hostPackage, installedName, isGitCheckout, isNpxInstall, isOneOffRun,
21
+ frozenNameInstall, hostPackage, installedName, installedVersion, isGitCheckout, isNpxInstall, isOneOffRun,
20
22
  PUBLISHED_NAME, successorRoot, upgradeCommand, upgradeName,
21
23
  } from "./install-layout.mjs";
22
24
 
@@ -235,7 +237,7 @@ export function upgradeStatus() {
235
237
  * assembled from request input: the only thing that varies is which alias, and
236
238
  * that is read off the install on disk and confined to ALIAS_PACKAGES.
237
239
  */
238
- export function startUpgrade({ pkgRoot, name = PUBLISHED_NAME }) {
240
+ export function startUpgrade({ pkgRoot, name = PUBLISHED_NAME, running = installedVersion(pkgRoot) }) {
239
241
  if (_upgrade.state === "running") return { ok: true, already: true, command: _upgrade.command };
240
242
  const blocked = upgradeBlock(pkgRoot);
241
243
  if (blocked) return { ok: false, reason: blocked, command: upgradeCommand(pkgRoot, name) };
@@ -245,18 +247,27 @@ export function startUpgrade({ pkgRoot, name = PUBLISHED_NAME }) {
245
247
  // there wrote a tree this process never reads, so the version on disk never
246
248
  // moved and the same update was offered forever.
247
249
  const target = upgradeName(pkgRoot, name);
248
- const spec = upgradeSpec(target);
250
+ const installRoot = hostPackage(pkgRoot, installedName(pkgRoot))?.root ?? successorRoot(pkgRoot) ?? pkgRoot;
251
+ const prefix = npmPrefix(installRoot, undefined, process.platform);
252
+ const spec = upgradeSpec(target, process.platform, undefined, prefix);
249
253
  // The LOGICAL vector, not the cmd.exe line: this string is shown to the user
250
254
  // and is the one they can paste. `cmd /d /s /c "…"` is an implementation
251
255
  // detail of how this platform reaches npm, and pasting it would be advice
252
256
  // about the deck rather than about their install.
253
- const command = `npm ${spec.plain.join(" ")}`;
257
+ const command = `npm ${spec.plain.map(arg => arg === prefix ? shellQuoteArg(arg) : arg).join(" ")}`;
254
258
  setUpgrade("running", command);
255
259
  // Deliberately does not restart anything once it is done. The new files on
256
260
  // disk make installedVersion() disagree with the running one, and the
257
261
  // ordinary drift path takes it from there — including its wait for an idle
258
262
  // moment.
259
- if (!runInstall(spec, (state, error) => setUpgrade(state, command, error))) {
263
+ if (!runInstall(spec, (state, error) => {
264
+ // A zero exit can mean npm wrote into another Node manager's prefix, or
265
+ // installed the same version again. Only the active copy's fresh manifest
266
+ // can establish that there are newer files for this process to restart.
267
+ if (state === "done" && !isOlder(running, installedVersion(pkgRoot))) {
268
+ setUpgrade("failed", command, "The install finished, but this running copy was not updated. Retry the update or reinstall this copy in its existing location.");
269
+ } else setUpgrade(state, command, error);
270
+ })) {
260
271
  return { ok: false, reason: "spawn_failed", command };
261
272
  }
262
273
  return { ok: true, command };
@@ -60,79 +60,9 @@ export {
60
60
  upgradeStatus,
61
61
  } from "./npm-upgrade.mjs";
62
62
 
63
- // ── version comparison ───────────────────────────────────────────────────────
63
+ import { isOlder } from "./version-order.mjs";
64
+ export { isOlder } from "./version-order.mjs";
64
65
 
65
- /** Numeric-segment compare of one version's parts: -1, 0 or 1. Non-numeric
66
- * segments count as 0 and missing segments pad with 0, so "1.30" sorts before
67
- * "1.30.1" and "1.9.0" before "1.10.0". */
68
- function cmpParts(x, y) {
69
- for (let i = 0; i < Math.max(x.length, y.length); i++) {
70
- const d = (x[i] ?? 0) - (y[i] ?? 0);
71
- if (d !== 0) return d < 0 ? -1 : 1;
72
- }
73
- return 0;
74
- }
75
-
76
- /** A version split at the FIRST `-`: the release on one side, the prerelease
77
- * identifiers on the other, or null when there is no prerelease at all.
78
- *
79
- * `+` stays inside the release half rather than starting a third part, which
80
- * keeps build metadata reading exactly as it read before — `1.0.0+build.7`
81
- * segments to [1,0,0,0,7] and therefore sorts above `1.0.0`. That is inherited
82
- * behaviour rather than a design, this repo has never published one, and a
83
- * change to it belongs in its own issue. */
84
- function versionParts(v) {
85
- const nums = (s) => s.split(/[.+]/).map(n => parseInt(n, 10)).map(n => Number.isNaN(n) ? 0 : n);
86
- const dash = v.indexOf("-");
87
- if (dash === -1) return { release: nums(v), pre: null };
88
- return { release: nums(v.slice(0, dash)), pre: nums(v.slice(dash + 1)) };
89
- }
90
-
91
- /** True when `a` sorts before `b`.
92
- *
93
- * A PRERELEASE SORTS BELOW THE RELEASE IT PRECEDES (#976), which is semver's
94
- * rule and was not this function's. Splitting on `[.\-+]` and mapping
95
- * non-numeric segments to 0 made `3.23.0-rc.1` segment to [3,23,0,0,1] — five
96
- * numbers against the release's three, so it compared ABOVE `3.23.0` and the
97
- * release compared below the candidate it was meant to supersede:
98
- *
99
- * isOlder("3.23.0-rc.1", "3.23.0") = false ← the release never looked newer
100
- * isOlder("3.23.0", "3.23.0-rc.1") = true ← and the deck would go backwards
101
- *
102
- * What that costs is not a cosmetic ordering. `autoUpdate` defaults on, so a
103
- * deck that has ended up on a prerelease — installed by hand by a tester, or
104
- * by the dist-tag accident publish.yml now prevents — produces no upgrade
105
- * notice when the real release ships, shows nothing in the banner, and has no
106
- * way to come back off it from inside the product. A bad release can be
107
- * followed by a good one; a fleet that cannot SEE the good one cannot be
108
- * rescued by publishing it, which is why this half matters even with the
109
- * dist-tag half in place.
110
- *
111
- * Ordinary numeric ordering is untouched — the release halves are compared
112
- * exactly as before — and so is build metadata; see versionParts.
113
- *
114
- * cswap-install.mjs had this written out a second time, without the type guard
115
- * below, and imports it from here now (#374). The two bodies were identical:
116
- * swept over 271,441 version-string pairs they disagreed on none, and the
117
- * guard was the whole difference — `isOlder(null, "1.0.0")` answers false here
118
- * and threw a TypeError there. Nothing could reach that call with a non-string
119
- * (both arguments are behind `typeof v === "string"` checks at the one call
120
- * site), so this is the copy with a test behind it absorbing the one without,
121
- * not a bug fix. That sweep is now one-sided on prerelease pairs and
122
- * duplicated-helpers.test.ts says which, rather than asserting an equality
123
- * that has deliberately stopped holding. */
124
- export function isOlder(a, b) {
125
- if (typeof a !== "string" || typeof b !== "string") return false;
126
- const x = versionParts(a), y = versionParts(b);
127
- const release = cmpParts(x.release, y.release);
128
- if (release !== 0) return release < 0;
129
- // Same release. A version carrying a prerelease is below the plain one, and
130
- // never the other way round; two prereleases of one release compare on their
131
- // own identifiers, so rc.2 is above rc.1.
132
- if (x.pre && !y.pre) return true;
133
- if (!x.pre || !y.pre) return false;
134
- return cmpParts(x.pre, y.pre) < 0;
135
- }
136
66
 
137
67
  // ── the notice ───────────────────────────────────────────────────────────────
138
68
 
@@ -75,8 +75,14 @@ function unixCli({ env, exists, read, realpath }) {
75
75
  * — or null for any other layout: pnpm, yarn and bun keep their globals
76
76
  * elsewhere, and a project's own node_modules has a package around it, as a
77
77
  * global prefix's `lib` never does (install-layout.mjs, frozenNameInstall). */
78
- function npmPrefix(root, read) {
79
- const modules = posix.dirname(root);
78
+ export function npmPrefix(root, read = readFileSync, platform = "linux") {
79
+ const path = platform === "win32" ? win32 : posix;
80
+ const modules = path.dirname(root);
81
+ if (platform === "win32") {
82
+ const prefix = path.dirname(modules);
83
+ return path.basename(modules).toLowerCase() === "node_modules"
84
+ && manifest(path.join(prefix, "package.json"), read) === undefined ? prefix : null;
85
+ }
80
86
  const lib = posix.dirname(modules);
81
87
  if (posix.basename(modules) !== "node_modules" || posix.basename(lib) !== "lib") return null;
82
88
  if (manifest(posix.join(lib, "package.json"), read) !== undefined) return null;
@@ -0,0 +1,74 @@
1
+ // Shared by version reporting and post-install verification. No I/O.
2
+ // ── version comparison ───────────────────────────────────────────────────────
3
+
4
+ /** Numeric-segment compare of one version's parts: -1, 0 or 1. Non-numeric
5
+ * segments count as 0 and missing segments pad with 0, so "1.30" sorts before
6
+ * "1.30.1" and "1.9.0" before "1.10.0". */
7
+ function cmpParts(x, y) {
8
+ for (let i = 0; i < Math.max(x.length, y.length); i++) {
9
+ const d = (x[i] ?? 0) - (y[i] ?? 0);
10
+ if (d !== 0) return d < 0 ? -1 : 1;
11
+ }
12
+ return 0;
13
+ }
14
+
15
+ /** A version split at the FIRST `-`: the release on one side, the prerelease
16
+ * identifiers on the other, or null when there is no prerelease at all.
17
+ *
18
+ * `+` stays inside the release half rather than starting a third part, which
19
+ * keeps build metadata reading exactly as it read before — `1.0.0+build.7`
20
+ * segments to [1,0,0,0,7] and therefore sorts above `1.0.0`. That is inherited
21
+ * behaviour rather than a design, this repo has never published one, and a
22
+ * change to it belongs in its own issue. */
23
+ function versionParts(v) {
24
+ const nums = (s) => s.split(/[.+]/).map(n => parseInt(n, 10)).map(n => Number.isNaN(n) ? 0 : n);
25
+ const dash = v.indexOf("-");
26
+ if (dash === -1) return { release: nums(v), pre: null };
27
+ return { release: nums(v.slice(0, dash)), pre: nums(v.slice(dash + 1)) };
28
+ }
29
+
30
+ /** True when `a` sorts before `b`.
31
+ *
32
+ * A PRERELEASE SORTS BELOW THE RELEASE IT PRECEDES (#976), which is semver's
33
+ * rule and was not this function's. Splitting on `[.\-+]` and mapping
34
+ * non-numeric segments to 0 made `3.23.0-rc.1` segment to [3,23,0,0,1] — five
35
+ * numbers against the release's three, so it compared ABOVE `3.23.0` and the
36
+ * release compared below the candidate it was meant to supersede:
37
+ *
38
+ * isOlder("3.23.0-rc.1", "3.23.0") = false ← the release never looked newer
39
+ * isOlder("3.23.0", "3.23.0-rc.1") = true ← and the deck would go backwards
40
+ *
41
+ * What that costs is not a cosmetic ordering. `autoUpdate` defaults on, so a
42
+ * deck that has ended up on a prerelease — installed by hand by a tester, or
43
+ * by the dist-tag accident publish.yml now prevents — produces no upgrade
44
+ * notice when the real release ships, shows nothing in the banner, and has no
45
+ * way to come back off it from inside the product. A bad release can be
46
+ * followed by a good one; a fleet that cannot SEE the good one cannot be
47
+ * rescued by publishing it, which is why this half matters even with the
48
+ * dist-tag half in place.
49
+ *
50
+ * Ordinary numeric ordering is untouched — the release halves are compared
51
+ * exactly as before — and so is build metadata; see versionParts.
52
+ *
53
+ * cswap-install.mjs had this written out a second time, without the type guard
54
+ * below, and imports it from here now (#374). The two bodies were identical:
55
+ * swept over 271,441 version-string pairs they disagreed on none, and the
56
+ * guard was the whole difference — `isOlder(null, "1.0.0")` answers false here
57
+ * and threw a TypeError there. Nothing could reach that call with a non-string
58
+ * (both arguments are behind `typeof v === "string"` checks at the one call
59
+ * site), so this is the copy with a test behind it absorbing the one without,
60
+ * not a bug fix. That sweep is now one-sided on prerelease pairs and
61
+ * duplicated-helpers.test.ts says which, rather than asserting an equality
62
+ * that has deliberately stopped holding. */
63
+ export function isOlder(a, b) {
64
+ if (typeof a !== "string" || typeof b !== "string") return false;
65
+ const x = versionParts(a), y = versionParts(b);
66
+ const release = cmpParts(x.release, y.release);
67
+ if (release !== 0) return release < 0;
68
+ // Same release. A version carrying a prerelease is below the plain one, and
69
+ // never the other way round; two prereleases of one release compare on their
70
+ // own identifiers, so rc.2 is above rc.1.
71
+ if (x.pre && !y.pre) return true;
72
+ if (!x.pre || !y.pre) return false;
73
+ return cmpParts(x.pre, y.pre) < 0;
74
+ }