arco-workbench 0.2.0 → 0.2.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 (48) hide show
  1. package/CONTRIBUTING.md +26 -24
  2. package/client/dist/assets/{PhosphorBackdrop-9jNRO1ZM.js → PhosphorBackdrop-BbR3xmfD.js} +1 -1
  3. package/client/dist/assets/{ThemedBackgroundShaderImpl-tUi3k54Y.js → ThemedBackgroundShaderImpl-UMjbs9ZN.js} +1 -1
  4. package/client/dist/assets/{XtermView-B7BOSnVo.js → XtermView-n135qz-f.js} +1 -1
  5. package/client/dist/assets/{galleryEditor-Ohc2h9cD.js → galleryEditor-CFSke4by.js} +1 -1
  6. package/client/dist/assets/{index-ILGXWriO.js → index-DeoJbjI3.js} +235 -235
  7. package/client/dist/index.html +1 -1
  8. package/client/src/components/HeaderVersionBox.tsx +6 -8
  9. package/client/src/components/SettingsPanel.tsx +44 -6
  10. package/client/src/components/settings/AppVersionSection.tsx +4 -4
  11. package/client/src/help/content/header.tsx +3 -2
  12. package/client/src/help/content/settings.tsx +10 -5
  13. package/client/src/help/manualSections/configuration.tsx +2 -0
  14. package/client/src/help/manualSections/maintenance.tsx +11 -7
  15. package/client/src/stores/appUpdateStore.ts +7 -1
  16. package/docs/HTTP_API.md +2 -2
  17. package/docs/OPERATIONS.md +22 -14
  18. package/docs/PROTOCOL.md +2 -2
  19. package/docs/RESEARCH.md +1 -1
  20. package/docs/SETTINGS.md +11 -7
  21. package/node_modules/@arco/shared/dist/protocol/serverMessages.d.ts +2 -2
  22. package/node_modules/@arco/shared/package.json +1 -1
  23. package/package.json +2 -2
  24. package/scripts/packaging/update.mjs +92 -35
  25. package/server/dist/authLoginSession.js +9 -1
  26. package/server/dist/capabilities.d.ts +6 -0
  27. package/server/dist/capabilities.js +13 -4
  28. package/server/dist/http/diagnosticsRoutes.js +1 -1
  29. package/server/dist/providers/antigravity/index.js +2 -2
  30. package/server/dist/providers/antigravity/status.js +3 -2
  31. package/server/dist/providers/antigravity/usage.js +3 -2
  32. package/server/dist/updateCheck.js +53 -67
  33. package/server/dist/updateManager.d.ts +2 -4
  34. package/server/dist/updateManager.js +4 -1
  35. package/server/dist/windowsCommand.d.ts +15 -0
  36. package/server/dist/windowsCommand.js +85 -4
  37. package/server/package.json +1 -1
  38. package/server/src/authLoginSession.ts +9 -1
  39. package/server/src/capabilities.ts +14 -4
  40. package/server/src/http/diagnosticsRoutes.ts +1 -1
  41. package/server/src/providers/antigravity/index.ts +2 -2
  42. package/server/src/providers/antigravity/status.ts +3 -2
  43. package/server/src/providers/antigravity/usage.ts +3 -2
  44. package/server/src/updateCheck.ts +47 -54
  45. package/server/src/updateManager.ts +5 -2
  46. package/server/src/windowsCommand.ts +83 -4
  47. package/shared/dist/protocol/serverMessages.d.ts +2 -2
  48. package/shared/src/protocol/serverMessages.ts +2 -2
@@ -1,3 +1,4 @@
1
+ import { execFileSync } from 'node:child_process';
1
2
  import { existsSync, readFileSync, statSync } from 'node:fs';
2
3
  import { win32 } from 'node:path';
3
4
  const defaultIsFile = (p) => {
@@ -32,6 +33,84 @@ export function findWindowsCommand(command, env, isFile) {
32
33
  }
33
34
  return null;
34
35
  }
36
+ // A service or launcher started before an install keeps the PATH it began
37
+ // with, while a new terminal reads the current one from the registry. This
38
+ // reads that current value (machine then user, as Windows joins them) and
39
+ // expands %NAME% references. Empty when it cannot be read.
40
+ // The system utility by absolute path, never found through PATH or the folder.
41
+ function regExe() {
42
+ const root = process.env.SystemRoot ?? process.env.windir ?? 'C:\\Windows';
43
+ return win32.join(root, 'System32', 'reg.exe');
44
+ }
45
+ let registryCache = null;
46
+ export function readRegistryPath() {
47
+ const env = process.env;
48
+ if (process.platform !== 'win32')
49
+ return '';
50
+ if (registryCache && Date.now() - registryCache.at < 30_000)
51
+ return registryCache.value;
52
+ const read = (key) => {
53
+ try {
54
+ const out = execFileSync(regExe(), ['query', key, '/v', 'Path'], { encoding: 'utf8', timeout: 3000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] });
55
+ return /^\s*Path\s+REG_(?:EXPAND_)?SZ\s+(.*)$/im.exec(out)?.[1]?.trim() ?? '';
56
+ }
57
+ catch {
58
+ return '';
59
+ }
60
+ };
61
+ const joined = [read('HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment'), read('HKCU\\Environment')].filter(Boolean).join(';');
62
+ const value = joined.replace(/%([^%]+)%/g, (whole, name) => envValue(env, name.toUpperCase()) ?? whole);
63
+ registryCache = { at: Date.now(), value };
64
+ return value;
65
+ }
66
+ // findWindowsCommand on the running PATH first, then on the PATH a new
67
+ // terminal would have. Returns the file and the PATH that located it, so a
68
+ // child process can be given the same PATH.
69
+ export function locateWindowsCommand(command, env, isFile, registryPath) {
70
+ const direct = findWindowsCommand(command, env, isFile);
71
+ if (direct)
72
+ return { file: direct };
73
+ if (/[\\/]/.test(command) || win32.isAbsolute(command))
74
+ return null;
75
+ const fresh = registryPath?.();
76
+ if (!fresh)
77
+ return null;
78
+ const current = envValue(env, 'PATH') ?? '';
79
+ const merged = [...new Set([...fresh.split(';'), ...current.split(';')].map((d) => d.trim()).filter(Boolean))].join(';');
80
+ const file = findWindowsCommand(command, { ...env, PATH: merged, Path: merged }, isFile);
81
+ return file ? { file, path: merged } : null;
82
+ }
83
+ function freshSource(opts) {
84
+ if (!opts.fresh)
85
+ return undefined;
86
+ if (opts.registryPath)
87
+ return opts.registryPath;
88
+ return opts.env ? undefined : readRegistryPath;
89
+ }
90
+ // The environment with exactly one PATH variable, whatever its spelling.
91
+ export function withSinglePath(env, path) {
92
+ const key = Object.keys(env).find((k) => k.toUpperCase() === 'PATH') ?? 'PATH';
93
+ const out = {};
94
+ for (const [k, v] of Object.entries(env))
95
+ if (k.toUpperCase() !== 'PATH')
96
+ out[k] = v;
97
+ out[key] = path;
98
+ return out;
99
+ }
100
+ // The first word of a sign-in command line, found like a provider program is;
101
+ // the rest is kept. `missing` names the program when it cannot be located.
102
+ export function resolveLoginCommand(line, opts = {}) {
103
+ if ((opts.platform ?? process.platform) !== 'win32')
104
+ return { line };
105
+ const match = /^([A-Za-z0-9._-]+)(\s.*)?$/.exec(line.trim());
106
+ if (!match)
107
+ return { line };
108
+ const env = opts.env ?? process.env;
109
+ const hit = locateWindowsCommand(match[1], env, opts.isFile ?? defaultIsFile, freshSource(opts));
110
+ if (!hit)
111
+ return { missing: match[1] };
112
+ return { line: `"${hit.file}"${match[2] ?? ''}`, ...(hit.path ? { path: hit.path } : {}) };
113
+ }
35
114
  // npm's cmd-shim writes `"%dp0%\node_modules\<pkg>\<bin>.js" %*` (older
36
115
  // versions `"%~dp0\..."`). Returns the absolute JavaScript entry, or null when
37
116
  // the shim does not wrap a script (for example a shim for a native binary).
@@ -50,9 +129,11 @@ export function resolveCommand(command, args = [], opts = {}) {
50
129
  return { command, args: [...args] };
51
130
  const env = opts.env ?? process.env;
52
131
  const isFile = opts.isFile ?? defaultIsFile;
53
- const found = findWindowsCommand(command, env, isFile);
54
- if (!found)
132
+ const located = locateWindowsCommand(command, env, isFile, freshSource(opts));
133
+ if (!located)
55
134
  return { command, args: [...args] };
135
+ const found = located.file;
136
+ const freshEnv = located.path ? { env: withSinglePath(env, located.path) } : {};
56
137
  const ext = win32.extname(found).toLowerCase();
57
138
  if (ext === '.cmd' || ext === '.bat') {
58
139
  let text = '';
@@ -62,10 +143,10 @@ export function resolveCommand(command, args = [], opts = {}) {
62
143
  catch { /* unreadable shim */ }
63
144
  const script = npmShimTarget(found, text);
64
145
  if (script && isFile(script))
65
- return { command: opts.nodePath ?? process.execPath, args: [script, ...args] };
146
+ return { command: opts.nodePath ?? process.execPath, args: [script, ...args], ...freshEnv };
66
147
  return { command, args: [...args] };
67
148
  }
68
- return { command: found, args: [...args] };
149
+ return { command: found, args: [...args], ...freshEnv };
69
150
  }
70
151
  // `spawn(...commandArgs('codex', args), options)`: the resolved command and
71
152
  // arguments as a tuple for the spawn/execFile call sites.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arco/server",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "private": true,
5
5
  "type": "module"
6
6
  }
@@ -7,6 +7,7 @@
7
7
  import { noteAntigravityLoginCompleted } from './providers/antigravity/status.js';
8
8
  import { noteGeminiResearchSignInExpired } from './providers/antigravity/researchSignIn.js';
9
9
  import { spawn, type ChildProcess } from 'child_process';
10
+ import { resolveLoginCommand, withSinglePath } from './windowsCommand.js';
10
11
  import type { AuthLoginSession, LoginSessionTarget as AuthLoginTarget } from '@arco/shared';
11
12
  import { killProcessTree } from './workers/processKill.js';
12
13
 
@@ -83,11 +84,18 @@ export function startLoginSession(provider: AuthLoginTarget, command: string): A
83
84
  };
84
85
  live.set(provider, entry);
85
86
  let child: ChildProcess;
87
+ // Windows: find the program the way provider turns do (running PATH, then the
88
+ // PATH a new terminal reads), so sign-in does not depend on cmd.exe alone.
89
+ const resolved = resolveLoginCommand(spec.command ?? command, { fresh: provider === 'antigravity-cli' });
90
+ if ('missing' in resolved) {
91
+ finish(entry, 'failed', `${resolved.missing} was not found on the PATH Arco is running with. Restart Arco from a new terminal after installing it, or run the sign-in command in your terminal.`);
92
+ return snapshot(entry);
93
+ }
86
94
  try {
87
95
  // No browser exists where the server runs; the CLIs print the link anyway.
88
96
  // detached on POSIX makes the shell a process-group leader, so a cancel or
89
97
  // timeout reaches the provider CLI it started, not only the shell.
90
- child = spawn(spec.command ?? command, { shell: true, detached: process.platform !== 'win32', windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'], env: Object.fromEntries(Object.entries({ ...process.env, BROWSER: 'true', NO_BROWSER: 'true', ...(spec.env ?? {}) }).filter(([name]) => !spec.unsetEnv?.includes(name))) });
98
+ child = spawn(resolved.line, { shell: true, detached: process.platform !== 'win32', windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'], env: Object.fromEntries(Object.entries({ ...(resolved.path ? withSinglePath(process.env, resolved.path) : process.env), BROWSER: 'true', NO_BROWSER: 'true', ...(spec.env ?? {}) }).filter(([name]) => !spec.unsetEnv?.includes(name))) });
91
99
  } catch (err) {
92
100
  finish(entry, 'failed', err instanceof Error ? err.message : String(err));
93
101
  return snapshot(entry);
@@ -13,7 +13,7 @@ import { atomicWriteFile } from './atomicFile.js';
13
13
  import { probeCodexUpdate, describeCliUpdate, type CliUpdateDecision, type UpdateCommandResult } from './cliUpdateDecision.js';
14
14
  import { compareVersions } from './updateCheck.js';
15
15
  import { arcoHome } from './arcoHome.js';
16
- import { commandArgs } from './windowsCommand.js';
16
+ import { commandArgs, resolveCommand, type ResolveOptions } from './windowsCommand.js';
17
17
 
18
18
  const execFileAsync = promisify(execFile);
19
19
  const CLI_PROBE_OPTIONS = {
@@ -38,9 +38,17 @@ const cliBinary = (provider: CliProvider): string => provider === 'cursor' ? 'cu
38
38
  // optional dep, so npm exited 0 — and every `codex --version` threw. Collapsing
39
39
  // that into 'unknown' made the whole CODEX row disappear from the popover, which
40
40
  // reads as "not installed" and gives the operator nothing to click or diagnose.
41
+ // Antigravity is found the way its status, usage, sign-in and turns find it: a
42
+ // program installed after Arco started, or on the new-terminal PATH only, still
43
+ // counts. Every other program keeps the plain lookup.
44
+ export function probeCommandFor(bin: string, args: string[], opts: ResolveOptions = {}): { command: string; args: string[]; env?: NodeJS.ProcessEnv } {
45
+ return resolveCommand(bin, args, bin === 'agy' ? { fresh: true, ...opts } : opts);
46
+ }
47
+
41
48
  export async function probeVersion(bin: string, flags: string[] = ['--version'], timeoutMs = 5_000): Promise<string> {
42
49
  try {
43
- const { stdout } = await execFileAsync(...commandArgs(bin, flags), { ...CLI_PROBE_OPTIONS, timeout: timeoutMs });
50
+ const cmd = probeCommandFor(bin, flags);
51
+ const { stdout } = await execFileAsync(cmd.command, cmd.args, { ...CLI_PROBE_OPTIONS, timeout: timeoutMs, ...(cmd.env ? { env: cmd.env } : {}) });
44
52
  const match = stdout.match(/(\d+\.\d+\.\d+(?:[-.][A-Za-z0-9.-]+)?)/);
45
53
  return match ? match[1] : 'unknown';
46
54
  } catch (err) {
@@ -53,7 +61,8 @@ export async function probeVersion(bin: string, flags: string[] = ['--version'],
53
61
  // fits the popover's one-line result slot.
54
62
  async function probeFailureReason(bin: string): Promise<string | null> {
55
63
  try {
56
- await execFileAsync(...commandArgs(bin, ['--version']), CLI_PROBE_OPTIONS);
64
+ const cmd = probeCommandFor(bin, ['--version']);
65
+ await execFileAsync(cmd.command, cmd.args, { ...CLI_PROBE_OPTIONS, ...(cmd.env ? { env: cmd.env } : {}) });
57
66
  return null;
58
67
  } catch (err) {
59
68
  const e = err as NodeJS.ErrnoException & { stderr?: string; stdout?: string };
@@ -303,7 +312,8 @@ async function runUpdateCommand(cmd: string, args: string[], provider: CliProvid
303
312
  for (const name of ['CODEX_MANAGED_BY_NPM', 'CODEX_MANAGED_BY_BUN', 'CODEX_MANAGED_BY_PNPM', 'CODEX_MANAGED_BY_VITE_PLUS', 'CODEX_MANAGED_PACKAGE_ROOT', 'npm_config_user_agent', 'npm_execpath']) delete env[name];
304
313
  }
305
314
  try {
306
- const { stdout, stderr } = await execFileAsync(...commandArgs(cmd, args), { env, maxBuffer: 4 * 1024 * 1024, timeout: 180_000 });
315
+ const run = probeCommandFor(cmd, args);
316
+ const { stdout, stderr } = await execFileAsync(run.command, run.args, { env: run.env ? { ...env, ...run.env } : env, maxBuffer: 4 * 1024 * 1024, timeout: 180_000 });
307
317
  return { output: (stdout + stderr).trim(), exitCode: 0 };
308
318
  } catch (err) {
309
319
  const error = err as { code?: number | string; stdout?: string; stderr?: string; message?: string };
@@ -46,7 +46,7 @@ export async function tryHandleDiagnosticsRoutes(
46
46
 
47
47
  if (path === '/api/diagnostics/research-sandbox') {
48
48
  const [claudeCli, codex, cursor, gemini, geminiSignIn] = await Promise.all([researchSandboxAvailable('claude'), researchSandboxAvailable('codex'), researchSandboxAvailable('cursor'), researchSandboxAvailable('antigravity'), geminiResearchSignInState()]);
49
- return send(200, { claudeCli, codex, cursor, gemini, geminiSignIn, codexVersionReason: codexResearchVersionReason(installedCodexVersion()), cursorVersionReason: cursorIsolationReason() });
49
+ return send(200, { claudeCli, codex, cursor, gemini, geminiSignIn, platform: process.platform, codexVersionReason: codexResearchVersionReason(installedCodexVersion()), cursorVersionReason: cursorIsolationReason() });
50
50
  }
51
51
 
52
52
  if (path === '/api/diagnostics/support-bundle') {
@@ -20,7 +20,7 @@ import type { WorkerConfig, WorkerStatus } from '@arco/shared';
20
20
  import type { Provider, ProviderProcess } from '../types.js';
21
21
  import { AcpJsonRpcClient, AcpReplyError, type IncomingRequest, type JsonRpcNotification } from '../acp/acpJsonRpc.js';
22
22
  import { cancelAcpPermissions, requestAcpPermission } from '../acp/permissionGate.js';
23
- import { commandArgs } from '../../windowsCommand.js';
23
+ import { resolveCommand } from '../../windowsCommand.js';
24
24
  import { killProcessTree } from '../../workers/processKill.js';
25
25
  import { probeVersion } from '../../capabilities.js';
26
26
  import { compareVersions } from '../../updateCheck.js';
@@ -118,7 +118,7 @@ class AntigravityTurn extends EventEmitter implements ProviderProcess {
118
118
  }
119
119
  const proc = fenced
120
120
  ? spawn(fenced.command.file, fenced.command.args, { cwd: '/', env: { PATH: '/usr/bin:/bin' }, stdio: ['pipe', 'pipe', 'pipe'], detached: true })
121
- : spawn(...commandArgs('agy', ['acp']), { cwd, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, detached: process.platform !== 'win32' });
121
+ : (() => { const agy = resolveCommand('agy', ['acp'], { fresh: true }); return spawn(agy.command, agy.args, { cwd, ...(agy.env ? { env: agy.env } : {}), stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, detached: process.platform !== 'win32' }); })();
122
122
  if (fenced) { const launch = fenced; proc.once('close', () => { void launch.close().catch(() => this.emit('system_notice', 'Worker isolation cleanup failed.')); }); }
123
123
  this.proc = proc;
124
124
  proc.once('error', error => this.fail(error));
@@ -1,6 +1,6 @@
1
1
  import { execFile } from 'node:child_process';
2
2
  import { promisify } from 'node:util';
3
- import { commandArgs } from '../../windowsCommand.js';
3
+ import { resolveCommand } from '../../windowsCommand.js';
4
4
 
5
5
  let authState: 'unknown' | 'ready' | 'rejected' = 'unknown';
6
6
  let models: string[] = [];
@@ -14,7 +14,8 @@ export async function antigravityStatus(): Promise<{ loggedIn: boolean; probeFai
14
14
  if (Date.now() - lastProbe > 60_000) {
15
15
  lastProbe = Date.now();
16
16
  try {
17
- const { stdout } = await exec(...commandArgs('agy', ['models']), { timeout: 10_000, maxBuffer: 256 * 1024 });
17
+ const agy = resolveCommand('agy', ['models'], { fresh: true });
18
+ const { stdout } = await exec(agy.command, agy.args, { timeout: 10_000, maxBuffer: 256 * 1024, ...(agy.env ? { env: agy.env } : {}) });
18
19
  const ids = stdout.split(/\r?\n/).map(line => line.split(/\s+/)[0]).filter(id => /^gemini-[a-z0-9.-]+$/.test(id));
19
20
  models = [...new Set(ids.map(id => id.replace(/-(low|medium|high|xhigh)$/, '')))];
20
21
  capabilities = Object.fromEntries(models.map(model => { const levels = ['low', 'medium', 'high', 'xhigh'].filter(level => ids.includes(`${model}-${level}`)); return [model, { tools: true, vision: true, thinking: levels.length > 0, thinkingLevels: levels }]; }));
@@ -1,6 +1,6 @@
1
1
  import { execFile } from 'node:child_process';
2
2
  import { promisify } from 'node:util';
3
- import { commandArgs } from '../../windowsCommand.js';
3
+ import { resolveCommand } from '../../windowsCommand.js';
4
4
 
5
5
  const exec = promisify(execFile);
6
6
  export interface AntigravityUsagePool { name: string; percentLeft: number; reset: string }
@@ -23,7 +23,8 @@ export function parseAntigravityUsage(text: string): AntigravityUsagePool[] | nu
23
23
 
24
24
  export async function getAntigravityUsage(): Promise<AntigravityUsagePool[] | null> {
25
25
  try {
26
- const { stdout } = await exec(...commandArgs('agy', ['-p', '/usage', '--output-format', 'json']), { timeout: 5000, killSignal: 'SIGKILL', maxBuffer: 256 * 1024, windowsHide: true });
26
+ const agy = resolveCommand('agy', ['-p', '/usage', '--output-format', 'json'], { fresh: true });
27
+ const { stdout } = await exec(agy.command, agy.args, { timeout: 5000, killSignal: 'SIGKILL', maxBuffer: 256 * 1024, windowsHide: true, ...(agy.env ? { env: agy.env } : {}) });
27
28
  return parseAntigravityUsage(stdout);
28
29
  } catch { return null; }
29
30
  }
@@ -1,6 +1,8 @@
1
1
  import type { AppUpdateAvailableMessage, AppUpdateStatusChangedMessage, UpdateCheckStatus } from '@arco/shared';
2
2
 
3
- const ENDPOINT = 'https://api.github.com/repos/ghreprimand/arco/releases/latest';
3
+ const GITHUB_LATEST = 'https://api.github.com/repos/ghreprimand/arco/releases/latest';
4
+ const NPM_LATEST = 'https://registry.npmjs.org/arco-workbench/latest';
5
+ const STABLE_VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
4
6
  const RELEASE_PREFIX = 'https://github.com/ghreprimand/arco/releases/tag/';
5
7
  const SEMVER = /^(?:v)?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][\da-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][\da-zA-Z-]*))*))?(?:\+[\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*)?$/;
6
8
 
@@ -51,62 +53,53 @@ export function createUpdateChecker(deps: Dependencies) {
51
53
  async function status(): Promise<UpdateCheckStatus> {
52
54
  return { ...cache, enabled: enabled(await deps.settings()) };
53
55
  }
56
+ async function lookup(): Promise<{ latest: string; url: string; publishedAt: string | null }> {
57
+ const response = await request(deps.packaged ? NPM_LATEST : GITHUB_LATEST, {
58
+ headers: { Accept: deps.packaged ? 'application/json' : 'application/vnd.github+json', 'User-Agent': `arco/${deps.current}` },
59
+ signal: AbortSignal.timeout(5000), redirect: 'error',
60
+ });
61
+ if (!response.ok) throw new Error('Release check unavailable');
62
+ if (deps.packaged) {
63
+ const pkg = await response.json() as { name?: string; version?: string; dist?: { tarball?: string } };
64
+ const version = pkg?.version;
65
+ if (pkg?.name !== 'arco-workbench' || typeof version !== 'string' || !STABLE_VERSION.test(version) ||
66
+ pkg.dist?.tarball !== `https://registry.npmjs.org/arco-workbench/-/arco-workbench-${version}.tgz`) throw new Error('Invalid npm release');
67
+ const latest = `v${version}`;
68
+ return { latest, url: RELEASE_PREFIX + latest, publishedAt: null };
69
+ }
70
+ const release = await response.json() as Record<string, unknown>;
71
+ const tag = release?.tag_name;
72
+ if (typeof tag !== 'string' || !STABLE_VERSION.test(tag.replace(/^v/, '')) ||
73
+ typeof release.html_url !== 'string' || !release.html_url.startsWith(RELEASE_PREFIX) ||
74
+ typeof release.published_at !== 'string' || !Number.isFinite(Date.parse(release.published_at))) throw new Error('Invalid GitHub release');
75
+ return { latest: `v${tag.replace(/^v/, '')}`, url: release.html_url, publishedAt: release.published_at };
76
+ }
54
77
  async function perform(): Promise<UpdateCheckStatus> {
55
78
  if (!enabled(await deps.settings())) return status();
56
- cache.checkedAt = now().toISOString();
57
- try {
58
- const response = await request(ENDPOINT, {
59
- headers: { Accept: 'application/vnd.github+json', 'User-Agent': `arco/${deps.current}` },
60
- signal: AbortSignal.timeout(5000), redirect: 'error',
61
- });
62
- if (!response.ok) throw new Error('release check unavailable');
63
- const release = await response.json() as Record<string, unknown>;
64
- const tag = release.tag_name;
65
- if (typeof tag !== 'string' || compareVersions(tag, deps.current) === null ||
66
- typeof release.html_url !== 'string' || !release.html_url.startsWith(RELEASE_PREFIX) ||
67
- typeof release.published_at !== 'string' || !Number.isFinite(Date.parse(release.published_at))) throw new Error('invalid release');
68
- const latest = `v${tag.replace(/^v/, '')}`;
69
- let packageStatus: UpdateCheckStatus['packageStatus'];
70
- if (deps.packaged && compareVersions(tag, deps.current)! > 0) {
71
- try {
72
- const version = tag.replace(/^v/, '');
73
- if (!/^\d+\.\d+\.\d+$/.test(version)) throw new Error('not a stable version');
74
- const npm = await request(`https://registry.npmjs.org/arco-workbench/${version}`, {
75
- headers: { Accept: 'application/json' }, signal: AbortSignal.timeout(5000), redirect: 'error',
76
- });
77
- if (npm.status === 404) packageStatus = 'unpublished';
78
- else if (!npm.ok) packageStatus = 'unknown';
79
- else {
80
- const metadata = await npm.json() as Record<string, unknown>;
81
- packageStatus = metadata.name === 'arco-workbench' && metadata.version === version && !!(metadata.dist && typeof metadata.dist === 'object' && typeof (metadata.dist as Record<string, unknown>).tarball === 'string') ? 'available' : 'unknown';
82
- }
83
- } catch { packageStatus = 'unknown'; }
84
- }
85
- // Re-read preferences: an opt-out or dismissal can arrive during the request.
86
- const settings = await deps.settings();
87
- if (!enabled(settings)) return status();
88
- const wasAvailable = cache.updateAvailable;
89
- const previousLatest = cache.latest;
90
- cache = { ...cache, latest, url: release.html_url, publishedAt: release.published_at, updateAvailable: compareVersions(tag, deps.current)! > 0 && (!deps.packaged || packageStatus === 'available'), ...(deps.packaged ? { packageStatus } : {}) };
91
- if (deps.packaged && wasAvailable && !cache.updateAvailable) {
92
- if (previousLatest) announced.delete(previousLatest);
93
- deps.broadcast({ type: 'app_update_status_changed' });
94
- }
95
- if (cache.updateAvailable && settings.updateCheckDismissed !== latest && !announced.has(latest)) {
96
- announced.add(latest);
97
- const message: AppUpdateAvailableMessage = { type: 'app_update_available', current: deps.current, latest, url: release.html_url, publishedAt: release.published_at };
98
- deps.broadcast(message);
99
- deps.log?.(`app_update_available ${latest}`);
100
- }
101
- } catch {
102
- if (deps.packaged) {
103
- const wasAvailable = cache.updateAvailable;
104
- cache = { ...cache, updateAvailable: false, packageStatus: 'unknown' };
105
- if (wasAvailable) { if (cache.latest) announced.delete(cache.latest); deps.broadcast({ type: 'app_update_status_changed' }); }
106
- }
107
- if (!loggedFailure) { loggedFailure = true; deps.debug?.('Release check unavailable; retrying on the next scheduled check.'); }
79
+ const checkedAt = now().toISOString();
80
+ let release;
81
+ try { release = await lookup(); } catch { /* Record the source of the failed check without exposing upstream detail. */ }
82
+ const settings = await deps.settings();
83
+ if (!enabled(settings)) return status();
84
+ const previous = cache;
85
+ if (release) {
86
+ const order = compareVersions(release.latest, deps.current);
87
+ cache = { ...release, current: deps.current, enabled: true, checkedAt, updateAvailable: order === 1 };
88
+ } else {
89
+ const checkFailure = deps.packaged ? 'npm' : 'github';
90
+ cache = { ...cache, checkedAt, updateAvailable: false, checkFailure };
91
+ if (!loggedFailure) { loggedFailure = true; deps.debug?.(`Release check unavailable (${checkFailure}); retrying on the next scheduled check.`); }
92
+ }
93
+ if (previous.latest !== cache.latest || previous.checkFailure !== cache.checkFailure || previous.updateAvailable !== cache.updateAvailable) {
94
+ deps.broadcast({ type: 'app_update_status_changed' });
95
+ }
96
+ const { latest, url, publishedAt } = cache;
97
+ if (cache.updateAvailable && latest && url && settings.updateCheckDismissed !== latest && !announced.has(latest)) {
98
+ announced.add(latest);
99
+ deps.broadcast({ type: 'app_update_available', current: deps.current, latest, url, publishedAt });
100
+ deps.log?.(`app_update_available ${latest}`);
108
101
  }
109
- return status();
102
+ return { ...cache, enabled: true };
110
103
  }
111
104
  function check(): Promise<UpdateCheckStatus> {
112
105
  if (!pending) pending = perform().finally(() => { pending = undefined; });
@@ -6,6 +6,7 @@ import { randomUUID } from 'node:crypto';
6
6
  import { arcoHome } from './arcoHome.js';
7
7
  import { updateChecker } from './server/updateCheck.js';
8
8
  import { APP_VERSION } from './appVersion.js';
9
+ import type { UpdateCheckStatus } from '@arco/shared';
9
10
 
10
11
  export type UpdateMode = 'service' | 'foreground' | 'docker';
11
12
  export function updateMode(platform = process.platform, env: NodeJS.ProcessEnv = process.env): UpdateMode {
@@ -17,7 +18,7 @@ const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
17
18
  type Status = { outcome: string; message?: string; startedAt?: number; finishedAt?: number; attemptId?: string; fromVersion?: string; target?: string; reportedAt?: number };
18
19
  export function createUpdateManager(deps: {
19
20
  mode?: () => UpdateMode; home?: () => string; root?: string; env?: NodeJS.ProcessEnv; platform?: NodeJS.Platform;
20
- check?: () => Promise<{ latest: string | null; updateAvailable: boolean }>;
21
+ check?: () => Promise<Pick<UpdateCheckStatus, 'latest' | 'updateAvailable' | 'checkFailure'>>;
21
22
  launch?: (command: string, args: string[]) => { status: number | null; error?: Error; stderr?: string | null };
22
23
  now?: () => number; version?: string;
23
24
  } = {}) {
@@ -59,7 +60,9 @@ export function createUpdateManager(deps: {
59
60
  const previous = read();
60
61
  if (previous?.outcome === 'running' && now() - (previous.startedAt ?? 0) < 30 * 60_000) return { ok: false, status: 409, error: 'An update is already running.' };
61
62
  let latest;
62
- try { latest = await check(); } catch { return { ok: false, status: 503, error: 'Release check unavailable. Try again or use npm run arco:update.' }; }
63
+ const lookupError = packaged ? 'Could not check npm for updates.' : 'Could not check GitHub for releases.';
64
+ try { latest = await check(); } catch { return { ok: false, status: 503, error: lookupError }; }
65
+ if (latest.checkFailure) return { ok: false, status: 503, error: lookupError };
63
66
  if (!latest.updateAvailable || !latest.latest || !/^v\d+\.\d+\.\d+$/.test(latest.latest)) return { ok: false, status: 409, error: 'No newer stable release is available.' };
64
67
  if ((body as { expectedLatest: string }).expectedLatest !== latest.latest) return { ok: false, status: 409, error: 'The latest release changed. Review the new release before updating.' };
65
68
  const attempt = { attemptId: randomUUID(), startedAt: now(), fromVersion: version, target: latest.latest };
@@ -1,9 +1,13 @@
1
+ import { execFileSync } from 'node:child_process';
1
2
  import { existsSync, readFileSync, statSync } from 'node:fs';
2
3
  import { win32 } from 'node:path';
3
4
 
4
5
  export interface ResolvedCommand {
5
6
  command: string;
6
7
  args: string[];
8
+ // Present when the program was found on the new-terminal PATH: the process
9
+ // environment with that PATH under one key, for the child to run with.
10
+ env?: NodeJS.ProcessEnv;
7
11
  }
8
12
 
9
13
  export interface ResolveOptions {
@@ -12,6 +16,11 @@ export interface ResolveOptions {
12
16
  nodePath?: string;
13
17
  isFile?: (path: string) => boolean;
14
18
  readText?: (path: string) => string;
19
+ // Opt in to searching the machine and user PATH a new terminal reads, after
20
+ // the running PATH. Only for the process's own environment: a caller that
21
+ // passes `env` never gains the host PATH implicitly.
22
+ fresh?: boolean;
23
+ registryPath?: () => string;
15
24
  }
16
25
 
17
26
  const defaultIsFile = (p: string): boolean => {
@@ -43,6 +52,74 @@ export function findWindowsCommand(command: string, env: NodeJS.ProcessEnv, isFi
43
52
  return null;
44
53
  }
45
54
 
55
+ // A service or launcher started before an install keeps the PATH it began
56
+ // with, while a new terminal reads the current one from the registry. This
57
+ // reads that current value (machine then user, as Windows joins them) and
58
+ // expands %NAME% references. Empty when it cannot be read.
59
+ // The system utility by absolute path, never found through PATH or the folder.
60
+ function regExe(): string {
61
+ const root = process.env.SystemRoot ?? process.env.windir ?? 'C:\\Windows';
62
+ return win32.join(root, 'System32', 'reg.exe');
63
+ }
64
+ let registryCache: { at: number; value: string } | null = null;
65
+ export function readRegistryPath(): string {
66
+ const env = process.env;
67
+ if (process.platform !== 'win32') return '';
68
+ if (registryCache && Date.now() - registryCache.at < 30_000) return registryCache.value;
69
+ const read = (key: string): string => {
70
+ try {
71
+ const out = execFileSync(regExe(), ['query', key, '/v', 'Path'], { encoding: 'utf8', timeout: 3000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] });
72
+ return /^\s*Path\s+REG_(?:EXPAND_)?SZ\s+(.*)$/im.exec(out)?.[1]?.trim() ?? '';
73
+ } catch { return ''; }
74
+ };
75
+ const joined = [read('HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment'), read('HKCU\\Environment')].filter(Boolean).join(';');
76
+ const value = joined.replace(/%([^%]+)%/g, (whole, name: string) => envValue(env, name.toUpperCase()) ?? whole);
77
+ registryCache = { at: Date.now(), value };
78
+ return value;
79
+ }
80
+
81
+ // findWindowsCommand on the running PATH first, then on the PATH a new
82
+ // terminal would have. Returns the file and the PATH that located it, so a
83
+ // child process can be given the same PATH.
84
+ export function locateWindowsCommand(command: string, env: NodeJS.ProcessEnv, isFile: (p: string) => boolean, registryPath?: () => string): { file: string; path?: string } | null {
85
+ const direct = findWindowsCommand(command, env, isFile);
86
+ if (direct) return { file: direct };
87
+ if (/[\\/]/.test(command) || win32.isAbsolute(command)) return null;
88
+ const fresh = registryPath?.();
89
+ if (!fresh) return null;
90
+ const current = envValue(env, 'PATH') ?? '';
91
+ const merged = [...new Set([...fresh.split(';'), ...current.split(';')].map((d) => d.trim()).filter(Boolean))].join(';');
92
+ const file = findWindowsCommand(command, { ...env, PATH: merged, Path: merged }, isFile);
93
+ return file ? { file, path: merged } : null;
94
+ }
95
+
96
+ function freshSource(opts: ResolveOptions): (() => string) | undefined {
97
+ if (!opts.fresh) return undefined;
98
+ if (opts.registryPath) return opts.registryPath;
99
+ return opts.env ? undefined : readRegistryPath;
100
+ }
101
+
102
+ // The environment with exactly one PATH variable, whatever its spelling.
103
+ export function withSinglePath(env: NodeJS.ProcessEnv, path: string): NodeJS.ProcessEnv {
104
+ const key = Object.keys(env).find((k) => k.toUpperCase() === 'PATH') ?? 'PATH';
105
+ const out: NodeJS.ProcessEnv = {};
106
+ for (const [k, v] of Object.entries(env)) if (k.toUpperCase() !== 'PATH') out[k] = v;
107
+ out[key] = path;
108
+ return out;
109
+ }
110
+
111
+ // The first word of a sign-in command line, found like a provider program is;
112
+ // the rest is kept. `missing` names the program when it cannot be located.
113
+ export function resolveLoginCommand(line: string, opts: ResolveOptions = {}): { line: string; path?: string } | { missing: string } {
114
+ if ((opts.platform ?? process.platform) !== 'win32') return { line };
115
+ const match = /^([A-Za-z0-9._-]+)(\s.*)?$/.exec(line.trim());
116
+ if (!match) return { line };
117
+ const env = opts.env ?? process.env;
118
+ const hit = locateWindowsCommand(match[1], env, opts.isFile ?? defaultIsFile, freshSource(opts));
119
+ if (!hit) return { missing: match[1] };
120
+ return { line: `"${hit.file}"${match[2] ?? ''}`, ...(hit.path ? { path: hit.path } : {}) };
121
+ }
122
+
46
123
  // npm's cmd-shim writes `"%dp0%\node_modules\<pkg>\<bin>.js" %*` (older
47
124
  // versions `"%~dp0\..."`). Returns the absolute JavaScript entry, or null when
48
125
  // the shim does not wrap a script (for example a shim for a native binary).
@@ -60,17 +137,19 @@ export function resolveCommand(command: string, args: readonly string[] = [], op
60
137
  if (platform !== 'win32') return { command, args: [...args] };
61
138
  const env = opts.env ?? process.env;
62
139
  const isFile = opts.isFile ?? defaultIsFile;
63
- const found = findWindowsCommand(command, env, isFile);
64
- if (!found) return { command, args: [...args] };
140
+ const located = locateWindowsCommand(command, env, isFile, freshSource(opts));
141
+ if (!located) return { command, args: [...args] };
142
+ const found = located.file;
143
+ const freshEnv = located.path ? { env: withSinglePath(env, located.path) } : {};
65
144
  const ext = win32.extname(found).toLowerCase();
66
145
  if (ext === '.cmd' || ext === '.bat') {
67
146
  let text = '';
68
147
  try { text = (opts.readText ?? defaultReadText)(found); } catch { /* unreadable shim */ }
69
148
  const script = npmShimTarget(found, text);
70
- if (script && isFile(script)) return { command: opts.nodePath ?? process.execPath, args: [script, ...args] };
149
+ if (script && isFile(script)) return { command: opts.nodePath ?? process.execPath, args: [script, ...args], ...freshEnv };
71
150
  return { command, args: [...args] };
72
151
  }
73
- return { command: found, args: [...args] };
152
+ return { command: found, args: [...args], ...freshEnv };
74
153
  }
75
154
 
76
155
  // `spawn(...commandArgs('codex', args), options)`: the resolved command and
@@ -843,14 +843,14 @@ export interface UpdateCheckStatus {
843
843
  checkedAt: string | null;
844
844
  updateAvailable: boolean;
845
845
  enabled: boolean;
846
- packageStatus?: 'available' | 'unpublished' | 'unknown';
846
+ checkFailure?: 'npm' | 'github';
847
847
  }
848
848
  export interface AppUpdateAvailableMessage {
849
849
  type: 'app_update_available';
850
850
  current: string;
851
851
  latest: string;
852
852
  url: string;
853
- publishedAt: string;
853
+ publishedAt: string | null;
854
854
  }
855
855
  export interface AppUpdateStatusChangedMessage {
856
856
  type: 'app_update_status_changed';
@@ -1507,7 +1507,7 @@ export interface UpdateCheckStatus {
1507
1507
  checkedAt: string | null;
1508
1508
  updateAvailable: boolean;
1509
1509
  enabled: boolean;
1510
- packageStatus?: 'available' | 'unpublished' | 'unknown';
1510
+ checkFailure?: 'npm' | 'github';
1511
1511
  }
1512
1512
 
1513
1513
  export interface AppUpdateAvailableMessage {
@@ -1515,7 +1515,7 @@ export interface AppUpdateAvailableMessage {
1515
1515
  current: string;
1516
1516
  latest: string;
1517
1517
  url: string;
1518
- publishedAt: string;
1518
+ publishedAt: string | null;
1519
1519
  }
1520
1520
 
1521
1521
  export interface AppUpdateStatusChangedMessage {