cc-viewer 1.9.24 → 1.9.26

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 (109) hide show
  1. package/README.md +1 -1
  2. package/cli.js +14 -0
  3. package/dist/assets/App-CjP88gbM.css +1 -0
  4. package/dist/assets/App-CkbwkH74.js +2 -0
  5. package/dist/assets/ArchivePreview-1XAr8LvB.js +1 -0
  6. package/dist/assets/AudioPreview-7zCADwCz.css +1 -0
  7. package/dist/assets/AudioPreview-DGcbrJjl.js +1 -0
  8. package/dist/assets/{MdxEditorPanel-CT6w8hjl.js → MdxEditorPanel-DFGSL5OM.js} +1 -1
  9. package/dist/assets/Mobile-DFu8Kn5W.js +1 -0
  10. package/dist/assets/ProxyStatsModal-BU9liIIO.js +1 -0
  11. package/dist/assets/SubtitlePreview-BGW9y2LI.css +1 -0
  12. package/dist/assets/SubtitlePreview-Ca_dpMFL.js +1 -0
  13. package/dist/assets/{_baseUniq-BGBEhBne.js → _baseUniq-9PjtCZvX.js} +1 -1
  14. package/dist/assets/{arc-4pbWOEmh.js → arc-C7i0W-3s.js} +1 -1
  15. package/dist/assets/{architectureDiagram-Q4EWVU46-BHZPDnby.js → architectureDiagram-Q4EWVU46-B0-9CMiF.js} +1 -1
  16. package/dist/assets/{blockDiagram-DXYQGD6D-DszLU7Pg.js → blockDiagram-DXYQGD6D-v3Zg9ooQ.js} +1 -1
  17. package/dist/assets/{c4Diagram-AHTNJAMY-DbDJNYxl.js → c4Diagram-AHTNJAMY-BngN_7qF.js} +1 -1
  18. package/dist/assets/{channel-BpIsxDHj.js → channel-IbZhDvnM.js} +1 -1
  19. package/dist/assets/{chunk-4BX2VUAB-ChcBwBh2.js → chunk-4BX2VUAB-8cHviTVA.js} +1 -1
  20. package/dist/assets/{chunk-4TB4RGXK-DzBEAck_.js → chunk-4TB4RGXK-C3CP4doN.js} +1 -1
  21. package/dist/assets/{chunk-55IACEB6-9UDvmw07.js → chunk-55IACEB6-FUVA-xfN.js} +1 -1
  22. package/dist/assets/{chunk-EDXVE4YY-DHEU2DKg.js → chunk-EDXVE4YY-BL4ddY7-.js} +1 -1
  23. package/dist/assets/{chunk-FMBD7UC4-sysT0Sy2.js → chunk-FMBD7UC4-fgqPq6Tx.js} +1 -1
  24. package/dist/assets/{chunk-OYMX7WX6-DLXt2vYo.js → chunk-OYMX7WX6-BGnPcd9h.js} +1 -1
  25. package/dist/assets/{chunk-QZHKN3VN-CDIkC7QK.js → chunk-QZHKN3VN-Cs6WjmqO.js} +1 -1
  26. package/dist/assets/{chunk-YZCP3GAM-D9b_INz7.js → chunk-YZCP3GAM-qq4Q4j7H.js} +1 -1
  27. package/dist/assets/classDiagram-6PBFFD2Q-Bszndikj.js +1 -0
  28. package/dist/assets/classDiagram-v2-HSJHXN6E-Bszndikj.js +1 -0
  29. package/dist/assets/clone-MC_fW61A.js +1 -0
  30. package/dist/assets/{cose-bilkent-S5V4N54A-DJQwV_Dp.js → cose-bilkent-S5V4N54A-D-uK3RSk.js} +1 -1
  31. package/dist/assets/{dagre-KV5264BT-bl9Pq21t.js → dagre-KV5264BT-BulmeCnQ.js} +1 -1
  32. package/dist/assets/{diagram-5BDNPKRD-BA8CJxzI.js → diagram-5BDNPKRD-DI7Q04yx.js} +1 -1
  33. package/dist/assets/{diagram-G4DWMVQ6-DzSQULuz.js → diagram-G4DWMVQ6-B7zYIZac.js} +1 -1
  34. package/dist/assets/{diagram-MMDJMWI5-DhfHWnT4.js → diagram-MMDJMWI5-D_f5k-GJ.js} +1 -1
  35. package/dist/assets/{diagram-TYMM5635-BbAoFfGS.js → diagram-TYMM5635-DQ-vW7nJ.js} +1 -1
  36. package/dist/assets/{erDiagram-SMLLAGMA-CMjA2eBk.js → erDiagram-SMLLAGMA-BgubHrDi.js} +1 -1
  37. package/dist/assets/{flowDiagram-DWJPFMVM-bOubqgJ6.js → flowDiagram-DWJPFMVM-fPYA9wmX.js} +1 -1
  38. package/dist/assets/{ganttDiagram-T4ZO3ILL-BUIu7WwI.js → ganttDiagram-T4ZO3ILL-hNsatnIF.js} +1 -1
  39. package/dist/assets/{gitGraphDiagram-UUTBAWPF-B_vrztDU.js → gitGraphDiagram-UUTBAWPF-1GijxkLh.js} +1 -1
  40. package/dist/assets/{graph-BR3YGx52.js → graph-sNq_HPra.js} +1 -1
  41. package/dist/assets/{index-BMpUfdYI.js → index-BnWh6jkG.js} +1 -1
  42. package/dist/assets/{index-DtZAmvwJ.js → index-CmwhODrM.js} +1 -1
  43. package/dist/assets/{index-B88yR2TU.js → index-D6mBgqj7.js} +1 -1
  44. package/dist/assets/{index-mvm_Pxcf.js → index-DggrqRzx.js} +1 -1
  45. package/dist/assets/{index-BQx5MOpr.js → index-DiVw76Ih.js} +1 -1
  46. package/dist/assets/index-Dn7twftJ.js +2 -0
  47. package/dist/assets/{index-DwMyfQJq.js → index-ijWns1Ex.js} +1 -1
  48. package/dist/assets/{index-ClTuiPoz.js → index-ng96S3Hy.js} +1 -1
  49. package/dist/assets/{infoDiagram-42DDH7IO-Co9Db2ir.js → infoDiagram-42DDH7IO-C9HYi6HU.js} +1 -1
  50. package/dist/assets/{ishikawaDiagram-UXIWVN3A-4z7EydCd.js → ishikawaDiagram-UXIWVN3A-D3Ae6xRc.js} +1 -1
  51. package/dist/assets/{journeyDiagram-VCZTEJTY-CtLfbhYE.js → journeyDiagram-VCZTEJTY-BMPDBa6W.js} +1 -1
  52. package/dist/assets/{jszip.min-DtbrAiWv.js → jszip.min-D6JfNfcl.js} +1 -1
  53. package/dist/assets/{kanban-definition-6JOO6SKY-9ZrhOvdX.js → kanban-definition-6JOO6SKY-BXEtzhr-.js} +1 -1
  54. package/dist/assets/{layout-Ddo06NJO.js → layout-CbMMhBh2.js} +1 -1
  55. package/dist/assets/{linear-BZUsBSwS.js → linear-DivVFiS7.js} +1 -1
  56. package/dist/assets/{mermaid.core-O-x0KuTp.js → mermaid.core-Dq-d8oPN.js} +2 -2
  57. package/dist/assets/{min-PzJh19JL.js → min-CXI1r_lz.js} +1 -1
  58. package/dist/assets/{mindmap-definition-QFDTVHPH-C3MVo-7p.js → mindmap-definition-QFDTVHPH-CONBMUxc.js} +1 -1
  59. package/dist/assets/{pieDiagram-DEJITSTG-CMn9-kQc.js → pieDiagram-DEJITSTG-C0rsPXdi.js} +1 -1
  60. package/dist/assets/{quadrantDiagram-34T5L4WZ-9eyqTdkj.js → quadrantDiagram-34T5L4WZ-DA2PNu4u.js} +1 -1
  61. package/dist/assets/{requirementDiagram-MS252O5E-BJbuDOpR.js → requirementDiagram-MS252O5E-DjsBvm40.js} +1 -1
  62. package/dist/assets/{sankeyDiagram-XADWPNL6-CzQ1KxD3.js → sankeyDiagram-XADWPNL6-Drl_Kmzt.js} +1 -1
  63. package/dist/assets/{seqResourceLoaders-DH-Nl0yh.css → seqResourceLoaders-CjAnOisT.css} +1 -1
  64. package/dist/assets/seqResourceLoaders-L-Fzax-z.js +2 -0
  65. package/dist/assets/{sequenceDiagram-FGHM5R23-CfmSEAYp.js → sequenceDiagram-FGHM5R23-Dcz5NXKY.js} +1 -1
  66. package/dist/assets/{stateDiagram-FHFEXIEX-Brw2ZXQC.js → stateDiagram-FHFEXIEX-7P3czdgX.js} +1 -1
  67. package/dist/assets/{stateDiagram-v2-QKLJ7IA2-Dnyo23Rp.js → stateDiagram-v2-QKLJ7IA2-C3xgfAOE.js} +1 -1
  68. package/dist/assets/{timeline-definition-GMOUNBTQ-DNi7GnlG.js → timeline-definition-GMOUNBTQ-BVe-eF-9.js} +1 -1
  69. package/dist/assets/util-DUb-88OI.js +1 -0
  70. package/dist/assets/{vendor-antd-DWLgSkPo.js → vendor-antd-VJVAjRBJ.js} +1 -1
  71. package/dist/assets/{vendor-codemirror-CKsm_iG4.js → vendor-codemirror-D2yaEhu3.js} +1 -1
  72. package/dist/assets/{vendor-mdxeditor-Dah6NK0y.js → vendor-mdxeditor-DKI8QSRd.js} +2 -2
  73. package/dist/assets/{vendor-qrcode-CDcb8weP.js → vendor-qrcode-CDB9Y_Vp.js} +1 -1
  74. package/dist/assets/{vendor-virtuoso-DKUobZpA.js → vendor-virtuoso-DEFa9UCG.js} +1 -1
  75. package/dist/assets/{vennDiagram-DHZGUBPP-Cdkdx7gB.js → vennDiagram-DHZGUBPP-C8KL2OR8.js} +1 -1
  76. package/dist/assets/{wardley-RL74JXVD-YKzsVN4U.js → wardley-RL74JXVD-Dm4mxyoW.js} +1 -1
  77. package/dist/assets/{wardleyDiagram-NUSXRM2D-gBsb6aut.js → wardleyDiagram-NUSXRM2D-BoA34gDh.js} +1 -1
  78. package/dist/assets/{xychartDiagram-5P7HB3ND-Bh63NWof.js → xychartDiagram-5P7HB3ND-66ynIBzj.js} +1 -1
  79. package/dist/index.html +4 -4
  80. package/package.json +1 -1
  81. package/server/lib/approval-policy.js +5 -2
  82. package/server/lib/ask/perm-bridge.js +4 -0
  83. package/server/lib/ask/perm-request-bridge.js +1 -1
  84. package/server/lib/audio-stream.js +267 -0
  85. package/server/lib/auto-approve.js +26 -5
  86. package/server/lib/restart-helper.js +65 -0
  87. package/server/lib/restart.js +83 -0
  88. package/server/lib/sdk-manager.js +19 -10
  89. package/server/lib/terminal-ws-ping.js +42 -0
  90. package/server/lib/update-instances.js +42 -0
  91. package/server/lib/update-job.js +260 -0
  92. package/server/lib/updater.js +37 -220
  93. package/server/proxy.js +16 -9
  94. package/server/pty-manager.js +1 -0
  95. package/server/routes/ask-perm.js +17 -13
  96. package/server/routes/files-content.js +65 -0
  97. package/server/routes/project-meta.js +11 -7
  98. package/server/routes/update.js +58 -0
  99. package/server/server.js +67 -11
  100. package/dist/assets/App-BwRRqrP5.css +0 -1
  101. package/dist/assets/App-Cfmm41z0.js +0 -2
  102. package/dist/assets/ArchivePreview-dKWXN9Zp.js +0 -1
  103. package/dist/assets/Mobile-noWViQpL.js +0 -1
  104. package/dist/assets/ProxyStatsModal-BeCRPqaC.js +0 -1
  105. package/dist/assets/classDiagram-6PBFFD2Q-4Lh0SB4X.js +0 -1
  106. package/dist/assets/classDiagram-v2-HSJHXN6E-4Lh0SB4X.js +0 -1
  107. package/dist/assets/clone-cWiXtXrO.js +0 -1
  108. package/dist/assets/index-Ca3a2tOc.js +0 -2
  109. package/dist/assets/seqResourceLoaders-DeqzMajS.js +0 -2
@@ -0,0 +1,260 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { readFileSync, writeFileSync } from 'node:fs';import { mkdir, open, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { spawn, execFile, spawnSync } from 'node:child_process';
6
+ import { once } from 'node:events';
7
+ import { finished } from 'node:stream/promises';
8
+ import { PACKAGE_ROOT } from '../_paths.js';
9
+ import { getClaudeConfigDir, buildNpmRootCommand, parseNpmRootOutput } from '../../findcc.js';
10
+ import { checkAndUpdate, detectHomebrewInstall, detectPnpmGlobalInstall, STABLE_VERSION_RE, isNewer, getCurrentVersion } from './updater.js';
11
+ import { hasOtherNormalInstance } from './update-instances.js';
12
+ import { reportSwallowed } from './error-report.js';
13
+ import { withFileLockAsync } from './async-file-lock.js';
14
+ import { isPidAlive } from './pid-alive.js';
15
+
16
+ const DOWNLOAD_TIMEOUT_MS = 10 * 60 * 1000;
17
+ const INSTALL_TIMEOUT_MS = 15 * 60 * 1000;
18
+ export const UPDATE_STATE_FILE = join(getClaudeConfigDir(), 'cc-viewer', 'update-state.json');
19
+ export const RESTART_CONFIG_FILE = join(getClaudeConfigDir(), 'cc-viewer', 'restart-config.json');
20
+ export const RESTART_READY_FILE = join(getClaudeConfigDir(), 'cc-viewer', 'restart-ready.json');
21
+ const CURRENT_CLI_PATH = fileURLToPath(new URL('../../cli.js', import.meta.url));
22
+ function updateError(message, code) { return Object.assign(new Error(message), { code }); }
23
+ export function readRestartConfig(file = RESTART_CONFIG_FILE) { return JSON.parse(readFileSync(file, 'utf8')); }
24
+ const npmRoot = () => new Promise((resolveRoot, reject) => {
25
+ const { cmd, args, windowsVerbatimArguments } = buildNpmRootCommand();
26
+ execFile(cmd, args, { encoding: 'utf8', timeout: 10000, windowsHide: true, windowsVerbatimArguments }, (err, stdout) => {
27
+ if (err) { reject(Object.assign(new Error('Unable to resolve the npm global directory'), { code: 'npm_unavailable' })); return; }
28
+ const root = parseNpmRootOutput(stdout);
29
+ if (!root) reject(Object.assign(new Error('Unable to resolve the npm global directory'), { code: 'npm_unavailable' }));
30
+ else resolveRoot(root);
31
+ });
32
+ });
33
+
34
+ function isStableRelease(release, version) {
35
+ try {
36
+ const url = typeof release?.dist?.tarball === 'string' ? new URL(release.dist.tarball) : null;
37
+ return release?.version === version && STABLE_VERSION_RE.test(version)
38
+ && url?.protocol === 'https:' && url.hostname === 'registry.npmjs.org'
39
+ && Boolean(release.dist.integrity || release.dist.shasum);
40
+ } catch { return false; }
41
+ }
42
+
43
+ export async function resolveNpmInstallRoot({ rootImpl = npmRoot, packageRoot = PACKAGE_ROOT, detectImpl = () => detectHomebrewInstall() || detectPnpmGlobalInstall() } = {}) {
44
+ if (process.versions.electron) throw Object.assign(new Error('Electron uses its installer'), { code: 'unsupported_channel' });
45
+ if (detectImpl()) throw Object.assign(new Error('Use the package manager that installed cc-viewer'), { code: 'unsupported_channel' });
46
+ const [actualRoot, actualPackage] = await Promise.all([Promise.resolve(rootImpl()).then(root => realpath(root)), realpath(packageRoot)]);
47
+ if (actualPackage !== resolve(actualRoot, 'cc-viewer')) {
48
+ throw Object.assign(new Error('This is not a direct npm global installation'), { code: 'unsupported_layout' });
49
+ }
50
+ return actualRoot;
51
+ }
52
+
53
+ export function buildNpmInstallCommand(tarballPath, { platform = process.platform, env = process.env, root } = {}) {
54
+ const quote = (s) => `"${String(s).replaceAll('"', '""')}"`;
55
+ const args = ['install', '-g', tarballPath, '--no-audit', '--no-fund', '--registry=https://registry.npmjs.org'];
56
+ if (root) args.push(`--prefix=${platform === 'win32' ? resolve(root, '..') : resolve(root, '..', '..')}`);
57
+ if (platform === 'win32') {
58
+ return { cmd: env.COMSPEC || 'cmd.exe', args: ['/d', '/s', '/c', `"${['npm', ...args].map(quote).join(' ')}"`], options: { windowsHide: true, windowsVerbatimArguments: true } };
59
+ }
60
+ return { cmd: 'npm', args, options: { windowsHide: true } };
61
+ }
62
+
63
+ export function verifyDigest(buffer, dist) {
64
+ if (dist?.integrity) {
65
+ const [algorithm, expected] = dist.integrity.split('-');
66
+ if (['sha256', 'sha384', 'sha512'].includes(algorithm) && /^[A-Za-z0-9+/]+={0,2}$/.test(expected || '')) {
67
+ if (createHash(algorithm).update(buffer).digest('base64') === expected) return true;
68
+ }
69
+ return false;
70
+ }
71
+ if (/^[a-f0-9]{40}$/i.test(dist?.shasum || '')) return createHash('sha1').update(buffer).digest('hex') === dist.shasum.toLowerCase();
72
+ return false;
73
+ }
74
+
75
+ export async function downloadRelease({ release, directory, fetchImpl = fetch, onProgress = () => {}, timeoutMs = DOWNLOAD_TIMEOUT_MS, uuid = randomUUID, openImpl = open, finishedImpl = finished }) {
76
+ if (!isStableRelease(release, release?.version)) throw Object.assign(new Error('Invalid package download metadata'), { code: 'invalid_release' });
77
+ const url = release.dist.tarball;
78
+ await mkdir(directory, { recursive: true, mode: 0o700 });
79
+ const file = join(directory, `cc-viewer-${uuid()}.tgz`);
80
+ const controller = new AbortController();
81
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
82
+ let handle;
83
+ let output;
84
+ let outputError;
85
+ try {
86
+ handle = await openImpl(file, 'wx', 0o600);
87
+ output = handle.createWriteStream();
88
+ output.on('error', (err) => { outputError = err; });
89
+ const streamDone = finishedImpl(output).catch((err) => { outputError ??= err; });
90
+ const response = await fetchImpl(url, { signal: controller.signal, redirect: 'error' });
91
+ if (!response.ok || !response.body) throw new Error(`Download failed: HTTP ${response.status}`);
92
+ const total = Number(response.headers.get('content-length')) || null;
93
+ let downloaded = 0;
94
+ try {
95
+ for await (const chunk of response.body) {
96
+ if (outputError) throw outputError;
97
+ downloaded += chunk.length;
98
+ if (!output.write(chunk)) await Promise.race([once(output, 'drain'), once(output, 'close').then(() => { throw outputError || new Error('Package output closed'); })]);
99
+ onProgress({ downloaded, total });
100
+ }
101
+ output.end();
102
+ await streamDone;
103
+ } catch (err) {
104
+ output.destroy();
105
+ throw err;
106
+ }
107
+ if (!verifyDigest(await readFile(file), release.dist)) throw Object.assign(new Error('Package integrity check failed'), { code: 'integrity_mismatch' });
108
+ return file;
109
+ } catch (err) {
110
+ if (output) {
111
+ output.destroy();
112
+ await finishedImpl(output).catch(() => {});
113
+ } else await handle?.close().catch(() => {});
114
+ await rm(file, { force: true }).catch((rmErr) => reportSwallowed('update-job.download-cleanup', rmErr));
115
+ throw err;
116
+ } finally { clearTimeout(timeout); }
117
+ }
118
+
119
+ export function runInstallProcess(command, { spawnImpl = spawn, timeoutMs = INSTALL_TIMEOUT_MS, onLog = () => {}, killTreeImpl } = {}) {
120
+ return new Promise((resolvePromise, reject) => {
121
+ let child;
122
+ try { child = spawnImpl(command.cmd, command.args, { ...command.options, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe'] }); }
123
+ catch (err) { reject(err); return; }
124
+ let settled = false;
125
+ const finish = (fn, value) => { if (settled) return; settled = true; clearTimeout(timer); fn(value); };
126
+ let timedOut = false;
127
+ const timer = setTimeout(() => {
128
+ timedOut = true;
129
+ try {
130
+ if (killTreeImpl) killTreeImpl(child);
131
+ else if (process.platform === 'win32') spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { timeout: 2000, windowsHide: true });
132
+ else process.kill(-child.pid, 'SIGKILL');
133
+ } catch (err) { reportSwallowed('update-job.kill', err); try { child.kill('SIGKILL'); } catch { } }
134
+ }, timeoutMs);
135
+ timer.unref?.();
136
+ child.on('error', (err) => finish(reject, err));
137
+ child.stdout?.on('data', (buf) => onLog(String(buf).slice(-4000)));
138
+ child.stderr?.on('data', (buf) => onLog(String(buf).slice(-4000)));
139
+ child.on('close', (code, signal) => {
140
+ if (timedOut) { finish(reject, Object.assign(new Error('Installation timed out'), { code: 'install_timeout' })); return; }
141
+ if (code === 0) finish(resolvePromise);
142
+ else finish(reject, Object.assign(new Error(`npm install failed (${code ?? signal})`), { code: 'install_failed' }));
143
+ });
144
+ });
145
+ }
146
+
147
+ export async function installStagedUpdate(config, { installImpl = runInstallProcess, log = console.error, stateFile = UPDATE_STATE_FILE, ownerPid, resolveRootImpl = resolveNpmInstallRoot, cliPath = CURRENT_CLI_PATH, packageRoot = PACKAGE_ROOT } = {}) {
148
+ const file = config?.tarballPath;
149
+ if (!file || typeof config.root !== 'string' || !STABLE_VERSION_RE.test(config.version || '')) throw new Error('Invalid staged update');
150
+ const root = await realpath(config.root);
151
+ const filePath = await realpath(file);
152
+ if (dirname(filePath) !== await realpath(dirname(stateFile))) throw new Error('Staged package is outside the update directory');
153
+ if (ownerPid !== undefined && config.pid !== ownerPid && isPidAlive(config.pid)) throw updateError('Staged update belongs to a different live process', 'another_instance');
154
+ if (!isNewer(config.version, getCurrentVersion())) throw updateError('Staged update is not newer than the installed version', 'not_newer');
155
+ const command = buildNpmInstallCommand(filePath, { root });
156
+ let logTail = '';
157
+ await withFileLockAsync(join(dirname(stateFile), 'update-install.lock'), async () => {
158
+ try {
159
+ const activeRoot = await resolveRootImpl({ packageRoot });
160
+ if (activeRoot !== root) throw updateError('The active npm global directory has changed; stage the update again', 'unsupported_layout');
161
+ if (dirname(await realpath(cliPath)) !== resolve(root, 'cc-viewer')) throw updateError('The running CLI does not belong to the staged npm global directory', 'unsupported_layout');
162
+ if (ownerPid !== undefined && config.pid !== ownerPid && isPidAlive(config.pid)) throw updateError('Staged update belongs to a different live process', 'another_instance');
163
+ if (!isNewer(config.version, getCurrentVersion())) throw updateError('Staged update is not newer than the installed version', 'not_newer');
164
+ if (!verifyDigest(await readFile(filePath), config.dist)) throw new Error('Staged package integrity check failed');
165
+ await installImpl(command, { onLog: (text) => { logTail = (logTail + text).slice(-12000); } });
166
+ const installed = JSON.parse(await readFile(join(root, 'cc-viewer', 'package.json'), 'utf8'));
167
+ if (installed.version !== config.version || !(await stat(join(root, 'cc-viewer', 'cli.js'))).isFile()) throw new Error('Installed version could not be verified');
168
+ } catch (err) {
169
+ err.message = `${err.message}${logTail ? `\n${logTail}` : ''}`;
170
+ throw err;
171
+ }
172
+ }, { ensureDir: dirname(stateFile), deadline: INSTALL_TIMEOUT_MS + 30000 });
173
+ log(`[CC Viewer] Installed v${config.version}`);
174
+ }
175
+
176
+ export class UpdateJob {
177
+ constructor(options = {}) {
178
+ this.options = options;
179
+ this.listeners = new Set();
180
+ this.lastBroadcastAt = 0;
181
+ this.state = { status: 'idle', currentVersion: null, version: null, downloaded: 0, total: null, error: null, updatedAt: Date.now() };
182
+ if (!options.disableRestore) {
183
+ try {
184
+ const pending = JSON.parse(readFileSync(UPDATE_STATE_FILE, 'utf8'));
185
+ if (pending.status === 'failed' && pending.error) this.state = { ...this.state, status: 'error', error: pending.error, version: pending.version || null };
186
+ else if (!pending.status && STABLE_VERSION_RE.test(pending.version || '') && pending.tarballPath && pending.root && isNewer(pending.version, getCurrentVersion())) {
187
+ this.state = { ...this.state, status: 'restart_required', version: pending.version };
188
+ if (pending.pid !== process.pid) {
189
+ try { writeFileSync(UPDATE_STATE_FILE, JSON.stringify({ ...pending, pid: process.pid }), { mode: 0o600 }); }
190
+ catch (err) { reportSwallowed('update-job.restore', err); }
191
+ }
192
+ }
193
+ } catch (err) {
194
+ if (err?.code !== 'ENOENT') reportSwallowed('update-job.restore', err);
195
+ }
196
+ }
197
+ }
198
+ getState() { const { release, log, ...state } = this.state; return state; }
199
+ subscribe(listener) { this.listeners.add(listener); listener(this.getState()); return () => this.listeners.delete(listener); }
200
+ setState(patch) { this.state = { ...this.state, ...patch, updatedAt: Date.now() }; for (const listener of this.listeners) { try { listener(this.getState()); } catch (err) { reportSwallowed('update-job.listener', err); } } }
201
+ async check() {
202
+ if (['checking', 'downloading', 'installing', 'restarting', 'restart_required'].includes(this.state.status)) return this.getState();
203
+ this.setState({ status: 'checking', error: null, version: null, release: null });
204
+ try {
205
+ const result = await (this.options.checkImpl || checkAndUpdate)({ force: true, interactive: true, allowDisabled: true });
206
+ const release = result.release || null;
207
+ if (result.status === 'error') throw new Error(result.error);
208
+ if (result.status === 'disabled') throw Object.assign(new Error('Update checks are disabled by Claude settings'), { code: 'disabled' });
209
+ this.setState({ status: result.status, currentVersion: result.currentVersion, version: result.status === 'latest' ? null : result.remoteVersion, release, error: null, errorCode: null, checkedAt: Date.now() });
210
+ } catch (err) { this.setState({ status: 'error', error: err.message, errorCode: err.code || 'check_failed', version: null, release: null }); }
211
+ return this.getState();
212
+ }
213
+ async restart(handler) {
214
+ if (this.state.status === 'restarting') return this.getState();
215
+ if (this.state.status !== 'restart_required') throw new Error('No verified update is ready');
216
+ this.setState({ status: 'restarting' });
217
+ try { await handler(this.state.version); }
218
+ catch (err) { this.setState({ status: 'restart_required', error: err.message }); throw err; }
219
+ }
220
+ async start() {
221
+ if (['checking', 'downloading', 'installing', 'restarting', 'restart_required'].includes(this.state.status)) return this.getState();
222
+ if (!this.state.version || !this.state.release) {
223
+ const state = await this.check();
224
+ if (state.status !== 'available') return state;
225
+ }
226
+ let { version, release } = this.state;
227
+ if (!isStableRelease(release, version)) {
228
+ const state = await this.check();
229
+ if (state.status !== 'available') return state;
230
+ ({ version, release } = this.state);
231
+ if (!isStableRelease(release, version)) {
232
+ this.setState({ status: 'error', error: 'Invalid package download metadata', errorCode: 'invalid_release' });
233
+ return this.getState();
234
+ }
235
+ }
236
+ this.setState({ status: 'downloading', error: null, downloaded: 0, total: null });
237
+ const directory = dirname(UPDATE_STATE_FILE);
238
+ let file;
239
+ try {
240
+ if (await (this.options.hasOtherInstanceImpl || hasOtherNormalInstance)({ currentPort: this.options.currentPort })) throw updateError('Exit other cc-viewer instances before updating', 'another_instance');
241
+ const root = await (this.options.resolveRootImpl || resolveNpmInstallRoot)();
242
+ const actualRoot = await realpath(root);
243
+ await withFileLockAsync(join(dirname(UPDATE_STATE_FILE), 'update-install.lock'), async () => {
244
+ file = await (this.options.downloadImpl || downloadRelease)({ release, directory, fetchImpl: this.options.fetchImpl, onProgress: (p) => {
245
+ const now = Date.now();
246
+ if (p.downloaded === p.total || now - this.lastBroadcastAt >= 100) {
247
+ this.lastBroadcastAt = now;
248
+ this.setState({ status: 'downloading', ...p });
249
+ }
250
+ } });
251
+ await writeFile(UPDATE_STATE_FILE, JSON.stringify({ version, tarballPath: file, root: actualRoot, pid: process.pid, dist: release.dist }), { mode: 0o600 });
252
+ this.setState({ status: 'restart_required', error: null, errorCode: null });
253
+ }, { ensureDir: directory, deadline: DOWNLOAD_TIMEOUT_MS + 30000 });
254
+ } catch (err) {
255
+ await rm(file, { force: true }).catch((rmErr) => reportSwallowed('update-job.cleanup', rmErr));
256
+ this.setState({ status: 'error', error: err.message, errorCode: err.code || 'update_failed' });
257
+ }
258
+ return this.getState();
259
+ }
260
+ }
@@ -1,100 +1,48 @@
1
1
  import { readFileSync, writeFileSync, mkdirSync, existsSync, realpathSync } from 'node:fs';
2
- import { execSync, spawn as realSpawn } from 'node:child_process';
2
+ import { execSync } from 'node:child_process';
3
3
  import { join } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { dirname } from 'node:path';
6
- import { t } from '../i18n.js';
7
- import { getClaudeConfigDir } from '../../findcc.js';
8
6
  import { PACKAGE_JSON } from '../_paths.js';
7
+ import { getClaudeConfigDir } from '../../findcc.js';
9
8
 
10
- const __filename = fileURLToPath(import.meta.url);
11
- const __dirname = dirname(__filename);
9
+ const __dirname = dirname(fileURLToPath(import.meta.url));
12
10
 
13
- // 探测当前 cc-viewer 是否通过 Homebrew 安装。
14
- // brew 的标准布局:<prefix>/Cellar/cc-viewer/<version>/lib/node_modules/cc-viewer/
15
- // - Apple Silicon 默认 prefix: /opt/homebrew
16
- // - Intel mac 默认 prefix: /usr/local
17
- // - linuxbrew / 自定义 prefix: 任意路径,但 Cellar/cc-viewer 段不变
18
- // 走 realpath 解析符号链接(npm-style bin shim 可能链到 Cellar 里)。
19
- // dirOverride 用于单测注入;realpathImpl 同理。
20
- // 失败安全:realpath 抛出 / 路径不匹配 → 返回 null(让上层走默认 npm 路径,不会误升级)。
21
11
  export function detectHomebrewInstall(dirOverride, realpathImpl = realpathSync) {
22
12
  const dir = dirOverride || __dirname;
23
13
  let real;
24
- try {
25
- real = realpathImpl(dir);
26
- } catch {
27
- real = dir;
28
- }
29
- // 用正斜杠规范化 Windows 反斜杠(brew 不在 Windows,但 indexOf 跨平台稳一点)
14
+ try { real = realpathImpl(dir); } catch { real = dir; }
30
15
  const normalized = real.replace(/\\/g, '/');
31
16
  const idx = normalized.indexOf('/Cellar/cc-viewer/');
32
17
  if (idx === -1) return null;
33
- // 校验 Cellar 后必须紧跟"版本号样式"目录段:必须以数字开头,仅含数字/字母/. _ - +
34
- // 防御 dev clone 场景:用户在 /Users/x/projects/Cellar/cc-viewer/lib/... 工作时
35
- // 不应误判为 brew 安装;同样防御 Time Machine backups 等含此 segment 的非真实安装。
36
- // 注意:cc-viewer formula 当前没有 `head do` block,所以 brew HEAD install
37
- // (Cellar/cc-viewer/HEAD-<sha>/) 不会被这里命中。如果未来 formula 加了 head do,
38
- // 需要把正则放宽为 /^(?:\d[\w.\-+]*|HEAD-[\w.\-+]+)\//,否则 HEAD 用户会被静默
39
- // 路由到 npm install -g 分支,触发双渠道污染。
40
18
  const afterCellar = normalized.slice(idx + '/Cellar/cc-viewer/'.length);
41
19
  if (!/^\d[\w.\-+]*\//.test(afterCellar)) return null;
42
- return normalized.slice(0, idx); // 返回 brew prefix
20
+ return normalized.slice(0, idx);
43
21
  }
44
22
 
45
- // Detect whether cc-viewer was installed via a pnpm global install (`pnpm add -g`).
46
- // pnpm's global layout: <root>/global/<id>/node_modules/.pnpm/cc-viewer@<version>/node_modules/cc-viewer/
47
- // - macOS default root: ~/Library/pnpm (PNPM_HOME)
48
- // - Linux default root: ~/.local/share/pnpm
49
- // - Windows default root: %LOCALAPPDATA%\pnpm
50
- // - custom PNPM_HOME / global-dir: any path, but the `.pnpm` virtual-store segment stays fixed.
51
- // Detection key: the `/.pnpm/cc-viewer@` virtual-store segment. npm never creates a `.pnpm`
52
- // directory and the `pkg@<version>`-style segment only occurs inside pnpm-managed trees, so this
53
- // is reliable regardless of where PNPM_HOME lives — a plain `/pnpm/` segment check would misfire
54
- // on `npm i -g --prefix ~/Library/pnpm` installs. The marker covers `pnpm add -g` installs,
55
- // `pnpm dlx` caches, and pnpm projects running cc-viewer from their own node_modules — all of
56
- // them must NOT be upgraded via `npm install -g` (dual-channel pollution). The module's own
57
- // realpath always flows through the virtual store (bin-shim symlinks resolve there too), so no
58
- // PNPM_HOME env read is needed.
59
- // dirOverride is for unit-test injection; realpathImpl likewise.
60
- // Fail-safe: realpath throwing / path mismatch -> null (upstream falls back to the default npm
61
- // path, never an unintended upgrade).
62
23
  export function detectPnpmGlobalInstall(dirOverride, realpathImpl = realpathSync) {
63
24
  const dir = dirOverride || __dirname;
64
25
  let real;
65
- try {
66
- real = realpathImpl(dir);
67
- } catch {
68
- real = dir;
69
- }
70
- // Normalize Windows backslashes (forward slashes keep indexOf portable)
26
+ try { real = realpathImpl(dir); } catch { real = dir; }
71
27
  const normalized = real.replace(/\\/g, '/');
72
28
  const marker = '/.pnpm/cc-viewer@';
73
29
  const idx = normalized.indexOf(marker);
74
30
  if (idx === -1) return null;
75
- // The segment after `cc-viewer@` must be version-shaped (same regex as the brew detector):
76
- // rejects dev-clone / backup paths that merely contain the literal marker text, and tag-style
77
- // segments like `cc-viewer@nightly` (pnpm tag installs — same caveat as the brew HEAD comment).
78
- const after = normalized.slice(idx + marker.length);
79
- if (!/^\d[\w.\-+]*\//.test(after)) return null;
80
- // Return the pnpm root (PNPM_HOME / custom global-dir): the path up to the first `/global/`
81
- // segment; without one (e.g. a dlx cache) strip the trailing `/node_modules` and return that.
31
+ if (!/^\d[\w.\-+]*\//.test(normalized.slice(idx + marker.length))) return null;
82
32
  const globalIdx = normalized.indexOf('/global/');
83
33
  if (globalIdx !== -1) return normalized.slice(0, globalIdx);
84
34
  const preMarker = normalized.slice(0, idx);
85
- return preMarker.endsWith('/node_modules')
86
- ? preMarker.slice(0, -'/node_modules'.length)
87
- : preMarker;
35
+ return preMarker.endsWith('/node_modules') ? preMarker.slice(0, -'/node_modules'.length) : preMarker;
88
36
  }
89
37
 
90
- const CHECK_INTERVAL = 4 * 60 * 60 * 1000; // 4 hours
38
+ const CHECK_INTERVAL = 4 * 60 * 60 * 1000;
91
39
  const CACHE_DIR = join(getClaudeConfigDir(), 'cc-viewer');
92
40
  const CACHE_FILE = join(CACHE_DIR, 'update-check.json');
93
41
  const CC_SETTINGS_FILE = join(getClaudeConfigDir(), 'settings.json');
42
+ export const STABLE_VERSION_RE = /^\d+\.\d+\.\d+$/;
94
43
 
95
- function getCurrentVersion() {
96
- const pkg = JSON.parse(readFileSync(PACKAGE_JSON, 'utf-8'));
97
- return pkg.version;
44
+ export function getCurrentVersion() {
45
+ return JSON.parse(readFileSync(PACKAGE_JSON, 'utf-8')).version;
98
46
  }
99
47
 
100
48
  function parseVersion(ver) {
@@ -102,7 +50,8 @@ function parseVersion(ver) {
102
50
  return { major, minor, patch };
103
51
  }
104
52
 
105
- function isNewer(remote, current) {
53
+ export function isNewer(remote, current) {
54
+ if (!STABLE_VERSION_RE.test(remote) || !STABLE_VERSION_RE.test(current)) return false;
106
55
  const r = parseVersion(remote);
107
56
  const c = parseVersion(current);
108
57
  if (r.major !== c.major) return r.major > c.major;
@@ -110,29 +59,20 @@ function isNewer(remote, current) {
110
59
  return r.patch > c.patch;
111
60
  }
112
61
 
113
- // 读取 Claude Code 全局配置,判断是否允许自更新
114
62
  function isAutoUpdateEnabled() {
115
- // 环境变量禁用
116
63
  if (process.env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC) return false;
117
-
118
64
  try {
119
- if (!existsSync(CC_SETTINGS_FILE)) return true; // 默认启用
120
- const settings = JSON.parse(readFileSync(CC_SETTINGS_FILE, 'utf-8'));
121
- // Claude Code 用 autoUpdates: false 显式禁用
122
- if (settings.autoUpdates === false) return false;
65
+ if (!existsSync(CC_SETTINGS_FILE)) return true;
66
+ if (JSON.parse(readFileSync(CC_SETTINGS_FILE, 'utf-8')).autoUpdates === false) return false;
123
67
  } catch { }
124
-
125
- return true; // 默认启用
68
+ return true;
126
69
  }
127
70
 
128
71
  function shouldCheck() {
129
72
  try {
130
73
  if (!existsSync(CACHE_FILE)) return true;
131
- const data = JSON.parse(readFileSync(CACHE_FILE, 'utf-8'));
132
- return Date.now() - data.lastCheck > CHECK_INTERVAL;
133
- } catch {
134
- return true;
135
- }
74
+ return Date.now() - JSON.parse(readFileSync(CACHE_FILE, 'utf-8')).lastCheck > CHECK_INTERVAL;
75
+ } catch { return true; }
136
76
  }
137
77
 
138
78
  function saveCheckTime() {
@@ -142,168 +82,45 @@ function saveCheckTime() {
142
82
  } catch { }
143
83
  }
144
84
 
145
- // 判断本机是否有任何 CCV 实例在使用:
146
- // 1. 调用方(当前 server)通过 `busy` 明确告知自己有 SSE client / PTY / SDK session 在跑
147
- // 2. 扫 CCV 端口范围,看是否有**除自己外**的其它 CCV server 实例正在 LISTEN
148
- // 参数 `lsofImpl` 用于单测注入假的 lsof 输出;默认走真 execSync。
149
- // 非 POSIX / 没装 lsof / 超时 → fallback 只看 busy,不强行判忙(避免 Windows 永远升不了级)。
150
85
  export function isAnyCcvBusy({ currentPid, busy, portRange, lsofImpl } = {}) {
151
86
  if (busy) return true;
152
-
153
87
  const [start, end] = Array.isArray(portRange) && portRange.length === 2 ? portRange : [7008, 7099];
154
88
  const pid = typeof currentPid === 'number' ? currentPid : process.pid;
155
89
  const runLsof = lsofImpl || ((cmd) => execSync(cmd, { timeout: 2000, encoding: 'utf-8', windowsHide: true }));
156
-
157
90
  try {
158
91
  const out = String(runLsof(`lsof -iTCP:${start}-${end} -sTCP:LISTEN -P -n -Fp`));
159
- // -Fp 输出每行是 field:p<pid> 是进程标识,f<fd>/cwd/txt 等是其它字段,不能误纳。
160
- // 防御:(a) 预先剥 CRLF(Windows / 某些管道会带 \r),(b) 用严格正则 ^p\d+$,只认"p + 纯数字",
161
- // 拒 `p` 空行 / `p-1` 负值 / `p0` / `p\r` 等畸形;(c) 只保留正整数。
162
- const lines = out.replace(/\r/g, '').split('\n');
163
- const pids = lines
164
- .filter(l => /^p\d+$/.test(l))
165
- .map(l => Number(l.slice(1)))
166
- .filter(n => Number.isFinite(n) && n > 0);
167
- const others = pids.filter(p => p !== pid);
168
- if (others.length > 0) return true;
169
- } catch {
170
- // lsof 不在 / 非 POSIX / 超时 → 放过
171
- }
172
- return false;
92
+ return out.replace(/\r/g, '').split('\n').filter(l => /^p\d+$/.test(l))
93
+ .map(l => Number(l.slice(1))).filter(n => n > 0 && n !== pid).length > 0;
94
+ } catch { return false; }
173
95
  }
174
96
 
175
- // options:
176
- // fetchImpl -- 注入 fetch(默认全局 fetch)
177
- // spawnImpl -- 注入 spawn(默认 node:child_process 的 spawn)
178
- // lsofImpl -- 注入 lsof exec(默认 execSync);传给 isAnyCcvBusy
179
- // dryRun -- 不真执行 install(spawn 路径直接跳过)
180
- // busy -- 本进程是否忙(SSE/PTY/SDK 活跃),由 server.js 调用点组装
181
- // portRange -- [start, end],传给 lsof 扫端口;server.js 里 START_PORT/MAX_PORT
182
- // brewPrefix -- 测试注入。语义:任何非 undefined 值(包含 null/string/'')= 显式覆盖,
183
- // undefined 或不传 = 走真探测。改用 !== undefined 比 hasOwnProperty 更稳,
184
- // 避免 caller 用 `{ ...opts, brewPrefix: maybe }` 时 maybe 为 undefined
185
- // 却被当显式传值,从而绕过自动检测,让 brew 用户被错误地走 npm 路径升级。
186
- // pnpmRoot -- 测试注入。语义与 brewPrefix 完全相同:非 undefined = 显式覆盖(含 null/''),
187
- // undefined = 走真探测 detectPnpmGlobalInstall()。
188
- //
189
- // 返回 status:
190
- // disabled | skipped | skipped_test_context | latest | major_available | deferred_busy
191
- // | brew_managed | pnpm_managed | upgrading_in_background | error
97
+ // A check never installs. Only an explicit, user-confirmed update job may do so.
192
98
  export async function checkAndUpdate(options = {}) {
193
99
  const fetchImpl = options.fetchImpl || fetch;
194
- const spawnImpl = options.spawnImpl || realSpawn;
195
- const lsofImpl = options.lsofImpl; // undefined → isAnyCcvBusy 走默认
196
- const dryRun = options.dryRun === true;
197
- const busy = options.busy === true;
198
- const portRange = options.portRange;
199
- // brew 安装 → 跳过 npm install -g(会跟 brew 的 Cellar 打架),改建议 brew upgrade
200
- const brewPrefix = options.brewPrefix !== undefined
201
- ? options.brewPrefix
202
- : detectHomebrewInstall();
203
- // pnpm 全局安装(pnpm add -g)→ 同样不能 npm install -g:会在 npm 全局前缀残留第二份
204
- // cc-viewer(双渠道污染),改建议 pnpm add -g cc-viewer@<version>
205
- const pnpmRoot = options.pnpmRoot !== undefined
206
- ? options.pnpmRoot
207
- : detectPnpmGlobalInstall();
208
100
  const currentVersion = getCurrentVersion();
209
-
210
- // 跟随 Claude Code 全局配置
211
- if (!isAutoUpdateEnabled()) {
212
- return { status: 'disabled', currentVersion, remoteVersion: null };
213
- }
214
-
215
- if (!shouldCheck()) {
216
- return { status: 'skipped', currentVersion, remoteVersion: null };
217
- }
218
-
219
- // ████████ 测试隔离铁闸 L5 —— 绝对不可移除(2026-06-06 数据事故防再犯)████████
220
- // 单元测试【绝不允许】发送真实网络请求:起真实 server 的测试,启动链的 30s 定时器
221
- // (server.js startViewer)会走到这里,真打 registry.npmjs.org,同大版本空闲时甚至
222
- // 触发 detached `npm install` 真实自更新——测试能改写用户的 cc-viewer 安装。
223
- // 条件说明:
224
- // - NODE_TEST_CONTEXT:node:test runner 自动注入,覆盖测试进程及 spread env 子进程;
225
- // - NODE_ENV==='test' 兜底:覆盖测试用 spawnSync 起的孙进程(NODE_TEST_CONTEXT 跨代
226
- // 传递不保证,如 branch-server.test.js 的 runScenario);
227
- // - 注入 fetchImpl 的 updater 单测(假网络)不受影响,走正常逻辑;
228
- // - 闸位必须在 disabled/skipped 早退【之后】、真实 fetch【之前】:放函数入口会劫持
229
- // 存量无-fetchImpl 用例对 disabled/skipped 的断言。
230
- // 守卫单测:test/updater-test-guard.test.js。
101
+ if (!isAutoUpdateEnabled() && !options.allowDisabled) return { status: 'disabled', currentVersion, remoteVersion: null };
102
+ if (!options.force && !shouldCheck()) return { status: 'skipped', currentVersion, remoteVersion: null };
231
103
  if ((process.env.NODE_TEST_CONTEXT || process.env.NODE_ENV === 'test') && !options.fetchImpl) {
232
104
  return { status: 'skipped_test_context', currentVersion, remoteVersion: null };
233
105
  }
234
- // ████████████████████████████████████████████████████████████████████████████
235
-
236
106
  try {
237
- const res = await fetchImpl('https://registry.npmjs.org/cc-viewer');
107
+ const res = await fetchImpl('https://registry.npmjs.org/cc-viewer/latest', { signal: AbortSignal.timeout(15000) });
238
108
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
239
109
  const data = await res.json();
240
- const remoteVersion = data['dist-tags']?.latest;
241
-
242
- // saveCheckTime 在所有分支前统一记录:4h 节流既避免 npm fetch 频繁,
243
- // 也覆盖 brew_managed / pnpm_managed banner 的提示频率(stderr 一行 + SSE 一次足够,4h 后再提)。
244
- // 故意不为 brew_managed / pnpm_managed 单独提速:banner 刷屏比慢提示更扰人,stderr 仍是侧通道。
110
+ const remoteVersion = data.version || data['dist-tags']?.latest;
111
+ if (!STABLE_VERSION_RE.test(remoteVersion || '')) return { status: 'error', currentVersion, remoteVersion: null, error: 'No version found' };
245
112
  saveCheckTime();
246
-
247
- if (!remoteVersion) {
248
- return { status: 'error', currentVersion, remoteVersion: null, error: 'No version found' };
249
- }
250
-
251
- if (!isNewer(remoteVersion, currentVersion)) {
252
- return { status: 'latest', currentVersion, remoteVersion };
253
- }
254
-
255
- const remote = parseVersion(remoteVersion);
256
- const current = parseVersion(currentVersion);
257
-
258
- // brew 安装:不能 npm install -g(会跟 Cellar 打架,残留双安装)→ 提示 brew upgrade。
259
- // 必须放在 major_available 之前——否则 brew 用户跨大版本时会被引导跑 npm i -g,
260
- // 触发我们正想杜绝的"双渠道污染"。`brew upgrade cc-viewer` 跨大版本同样能用,
261
- // brew_managed 文案适用所有版本差。
262
- if (brewPrefix) {
263
- console.error(`[CC Viewer] ${t('update.brewManaged', { version: remoteVersion })}`);
264
- return { status: 'brew_managed', currentVersion, remoteVersion, brewPrefix };
265
- }
266
-
267
- // pnpm 全局安装:不能 npm install -g(会在 npm 全局前缀造出第二份,双渠道污染)
268
- // → 提示 pnpm add -g cc-viewer@<version>。同样必须放在 major_available 之前,
269
- // 否则 pnpm 用户跨大版本时会被引导跑 npm i -g,触发我们正想杜绝的双渠道污染。
270
- if (pnpmRoot) {
271
- console.error(`[CC Viewer] ${t('update.pnpmManaged', { version: remoteVersion })}`);
272
- return { status: 'pnpm_managed', currentVersion, remoteVersion, pnpmRoot };
273
- }
274
-
275
- // 跨大版本:仅提示
276
- if (remote.major !== current.major) {
277
- console.error(`[CC Viewer] ${t('update.majorAvailable', { version: remoteVersion })}`);
278
- return { status: 'major_available', currentVersion, remoteVersion };
279
- }
280
-
281
- // 同大版本:查忙
282
- if (isAnyCcvBusy({ currentPid: process.pid, busy, portRange, lsofImpl })) {
283
- // 有人在用 → 不升,避免卡顿;下次启动再重试。Banner 仍会广播(见 server.js 调用点)。
113
+ if (!isNewer(remoteVersion, currentVersion)) return { status: 'latest', currentVersion, remoteVersion };
114
+ const brewPrefix = options.brewPrefix !== undefined ? options.brewPrefix : detectHomebrewInstall();
115
+ const pnpmRoot = options.pnpmRoot !== undefined ? options.pnpmRoot : detectPnpmGlobalInstall();
116
+ if (process.versions.electron) return { status: 'electron_managed', currentVersion, remoteVersion };
117
+ if (brewPrefix) return { status: 'brew_managed', currentVersion, remoteVersion, brewPrefix };
118
+ if (pnpmRoot) return { status: 'pnpm_managed', currentVersion, remoteVersion, pnpmRoot };
119
+ if (!options.interactive && parseVersion(remoteVersion).major !== parseVersion(currentVersion).major) return { status: 'major_available', currentVersion, remoteVersion };
120
+ if (!options.interactive && (options.busy === true || isAnyCcvBusy({ currentPid: process.pid, busy: false, portRange: options.portRange, lsofImpl: options.lsofImpl }))) {
284
121
  return { status: 'deferred_busy', currentVersion, remoteVersion };
285
122
  }
286
-
287
- // 空闲 → detached spawn 后台跑 npm install;立即返回,不阻塞事件循环。
288
- // Windows 下 `npm` 实际是 `npm.cmd`,Node spawn **不带 shell** 不会自动解析 .cmd 扩展名,会 ENOENT。
289
- // 用 `shell: process.platform === 'win32'` 条件启用 shell 模式跨平台兜底。
290
- console.error(`[CC Viewer] ${t('update.updating', { version: remoteVersion })} (background)`);
291
- if (!dryRun) {
292
- try {
293
- const child = spawnImpl(
294
- 'npm',
295
- ['install', '-g', `cc-viewer@${remoteVersion}`, '--no-audit', '--no-fund'],
296
- // windowsHide:Windows 下 shell 模式经 cmd.exe 跑 npm.cmd(console-subsystem),
297
- // 不隐藏会在后台更新期间常驻一个可见控制台窗口;POSIX 上为 no-op。
298
- { detached: true, stdio: 'ignore', shell: process.platform === 'win32', windowsHide: true }
299
- );
300
- if (child && typeof child.unref === 'function') child.unref();
301
- } catch (err) {
302
- console.error(`[CC Viewer] ${t('update.failed', { error: err.message })}`);
303
- return { status: 'error', currentVersion, remoteVersion, error: err.message };
304
- }
305
- }
306
- return { status: 'upgrading_in_background', currentVersion, remoteVersion };
123
+ return { status: 'available', currentVersion, remoteVersion, release: data };
307
124
  } catch (err) {
308
125
  saveCheckTime();
309
126
  return { status: 'error', currentVersion, remoteVersion: null, error: err.message };