cc-viewer 1.9.24 → 1.9.25

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 (86) hide show
  1. package/cli.js +14 -0
  2. package/dist/assets/App-BUIwNK3C.js +2 -0
  3. package/dist/assets/{App-BwRRqrP5.css → App-C5xq-7nS.css} +1 -1
  4. package/dist/assets/{ArchivePreview-dKWXN9Zp.js → ArchivePreview-BuFE-N7z.js} +1 -1
  5. package/dist/assets/{MdxEditorPanel-CT6w8hjl.js → MdxEditorPanel-BiKPuJGb.js} +1 -1
  6. package/dist/assets/{Mobile-noWViQpL.js → Mobile-D2UvqCIN.js} +1 -1
  7. package/dist/assets/{ProxyStatsModal-BeCRPqaC.js → ProxyStatsModal-CBdBgS9_.js} +1 -1
  8. package/dist/assets/{_baseUniq-BGBEhBne.js → _baseUniq-h4hafO2D.js} +1 -1
  9. package/dist/assets/{arc-4pbWOEmh.js → arc-CN5nAVn-.js} +1 -1
  10. package/dist/assets/{architectureDiagram-Q4EWVU46-BHZPDnby.js → architectureDiagram-Q4EWVU46-NTnIUsWP.js} +1 -1
  11. package/dist/assets/{blockDiagram-DXYQGD6D-DszLU7Pg.js → blockDiagram-DXYQGD6D-BPFMPOwn.js} +1 -1
  12. package/dist/assets/{c4Diagram-AHTNJAMY-DbDJNYxl.js → c4Diagram-AHTNJAMY-CAPyXRVj.js} +1 -1
  13. package/dist/assets/{channel-BpIsxDHj.js → channel-BULnUStk.js} +1 -1
  14. package/dist/assets/{chunk-4BX2VUAB-ChcBwBh2.js → chunk-4BX2VUAB-BeSOU8fB.js} +1 -1
  15. package/dist/assets/{chunk-4TB4RGXK-DzBEAck_.js → chunk-4TB4RGXK-BVCrVLA0.js} +1 -1
  16. package/dist/assets/{chunk-55IACEB6-9UDvmw07.js → chunk-55IACEB6-D0XHzdzo.js} +1 -1
  17. package/dist/assets/{chunk-EDXVE4YY-DHEU2DKg.js → chunk-EDXVE4YY-DizHN_m_.js} +1 -1
  18. package/dist/assets/{chunk-FMBD7UC4-sysT0Sy2.js → chunk-FMBD7UC4-3r0oXmep.js} +1 -1
  19. package/dist/assets/{chunk-OYMX7WX6-DLXt2vYo.js → chunk-OYMX7WX6-C701FNEA.js} +1 -1
  20. package/dist/assets/{chunk-QZHKN3VN-CDIkC7QK.js → chunk-QZHKN3VN-KAdMyJai.js} +1 -1
  21. package/dist/assets/{chunk-YZCP3GAM-D9b_INz7.js → chunk-YZCP3GAM-Cn2gaRZ3.js} +1 -1
  22. package/dist/assets/classDiagram-6PBFFD2Q-7MJg98xK.js +1 -0
  23. package/dist/assets/classDiagram-v2-HSJHXN6E-7MJg98xK.js +1 -0
  24. package/dist/assets/clone-Bddq99Xt.js +1 -0
  25. package/dist/assets/{cose-bilkent-S5V4N54A-DJQwV_Dp.js → cose-bilkent-S5V4N54A-URab8isi.js} +1 -1
  26. package/dist/assets/{dagre-KV5264BT-bl9Pq21t.js → dagre-KV5264BT-Cq24tJ6h.js} +1 -1
  27. package/dist/assets/{diagram-5BDNPKRD-BA8CJxzI.js → diagram-5BDNPKRD-D4KEpJ0T.js} +1 -1
  28. package/dist/assets/{diagram-G4DWMVQ6-DzSQULuz.js → diagram-G4DWMVQ6-DZLa6S7S.js} +1 -1
  29. package/dist/assets/{diagram-MMDJMWI5-DhfHWnT4.js → diagram-MMDJMWI5-BBhsOBKy.js} +1 -1
  30. package/dist/assets/{diagram-TYMM5635-BbAoFfGS.js → diagram-TYMM5635-ClWpYbD-.js} +1 -1
  31. package/dist/assets/{erDiagram-SMLLAGMA-CMjA2eBk.js → erDiagram-SMLLAGMA-5RXRgGvh.js} +1 -1
  32. package/dist/assets/{flowDiagram-DWJPFMVM-bOubqgJ6.js → flowDiagram-DWJPFMVM-DXiHDbOU.js} +1 -1
  33. package/dist/assets/{ganttDiagram-T4ZO3ILL-BUIu7WwI.js → ganttDiagram-T4ZO3ILL-Db5oVw9h.js} +1 -1
  34. package/dist/assets/{gitGraphDiagram-UUTBAWPF-B_vrztDU.js → gitGraphDiagram-UUTBAWPF-CCPK1X9H.js} +1 -1
  35. package/dist/assets/{graph-BR3YGx52.js → graph-DNxO4J9w.js} +1 -1
  36. package/dist/assets/{index-DtZAmvwJ.js → index-Bc_IaWe7.js} +1 -1
  37. package/dist/assets/{index-mvm_Pxcf.js → index-CXW8X8EW.js} +1 -1
  38. package/dist/assets/{index-DwMyfQJq.js → index-DDo6Z3Ov.js} +1 -1
  39. package/dist/assets/{index-ClTuiPoz.js → index-DR_FOzBM.js} +1 -1
  40. package/dist/assets/{index-BMpUfdYI.js → index-DaP3fzs1.js} +1 -1
  41. package/dist/assets/{index-B88yR2TU.js → index-Do02L044.js} +1 -1
  42. package/dist/assets/{index-BQx5MOpr.js → index-HLRCpKmY.js} +1 -1
  43. package/dist/assets/{index-Ca3a2tOc.js → index-ev1Hmm1O.js} +2 -2
  44. package/dist/assets/{infoDiagram-42DDH7IO-Co9Db2ir.js → infoDiagram-42DDH7IO-CzPZsFEc.js} +1 -1
  45. package/dist/assets/{ishikawaDiagram-UXIWVN3A-4z7EydCd.js → ishikawaDiagram-UXIWVN3A-eEVseuO_.js} +1 -1
  46. package/dist/assets/{journeyDiagram-VCZTEJTY-CtLfbhYE.js → journeyDiagram-VCZTEJTY-CmMKnKhj.js} +1 -1
  47. package/dist/assets/{jszip.min-DtbrAiWv.js → jszip.min-JnHXMwa-.js} +1 -1
  48. package/dist/assets/{kanban-definition-6JOO6SKY-9ZrhOvdX.js → kanban-definition-6JOO6SKY-CZMggR3M.js} +1 -1
  49. package/dist/assets/{layout-Ddo06NJO.js → layout-DVqRDfNO.js} +1 -1
  50. package/dist/assets/{linear-BZUsBSwS.js → linear-BHB3KNeC.js} +1 -1
  51. package/dist/assets/{mermaid.core-O-x0KuTp.js → mermaid.core-DOjmjAg3.js} +2 -2
  52. package/dist/assets/{min-PzJh19JL.js → min-DxJCEK6c.js} +1 -1
  53. package/dist/assets/{mindmap-definition-QFDTVHPH-C3MVo-7p.js → mindmap-definition-QFDTVHPH-B6W3RjCJ.js} +1 -1
  54. package/dist/assets/{pieDiagram-DEJITSTG-CMn9-kQc.js → pieDiagram-DEJITSTG-BRNQVuFX.js} +1 -1
  55. package/dist/assets/{quadrantDiagram-34T5L4WZ-9eyqTdkj.js → quadrantDiagram-34T5L4WZ-CUCnCkJJ.js} +1 -1
  56. package/dist/assets/{requirementDiagram-MS252O5E-BJbuDOpR.js → requirementDiagram-MS252O5E-Ds-5hLni.js} +1 -1
  57. package/dist/assets/{sankeyDiagram-XADWPNL6-CzQ1KxD3.js → sankeyDiagram-XADWPNL6-Cxi30RZc.js} +1 -1
  58. package/dist/assets/{seqResourceLoaders-DeqzMajS.js → seqResourceLoaders-B8ZIXCeg.js} +2 -2
  59. package/dist/assets/{sequenceDiagram-FGHM5R23-CfmSEAYp.js → sequenceDiagram-FGHM5R23-C6CukZv8.js} +1 -1
  60. package/dist/assets/{stateDiagram-FHFEXIEX-Brw2ZXQC.js → stateDiagram-FHFEXIEX-iPJCU2Ja.js} +1 -1
  61. package/dist/assets/{stateDiagram-v2-QKLJ7IA2-Dnyo23Rp.js → stateDiagram-v2-QKLJ7IA2-DMFhwtNH.js} +1 -1
  62. package/dist/assets/{timeline-definition-GMOUNBTQ-DNi7GnlG.js → timeline-definition-GMOUNBTQ-Dqd-tCUs.js} +1 -1
  63. package/dist/assets/{vendor-antd-DWLgSkPo.js → vendor-antd-D1L_UwKJ.js} +1 -1
  64. package/dist/assets/{vendor-codemirror-CKsm_iG4.js → vendor-codemirror-DOZOjrWx.js} +1 -1
  65. package/dist/assets/{vendor-mdxeditor-Dah6NK0y.js → vendor-mdxeditor-8ZUcYZ6G.js} +2 -2
  66. package/dist/assets/{vendor-qrcode-CDcb8weP.js → vendor-qrcode-Pw_LHfBZ.js} +1 -1
  67. package/dist/assets/{vendor-virtuoso-DKUobZpA.js → vendor-virtuoso-AhfR22q5.js} +1 -1
  68. package/dist/assets/{vennDiagram-DHZGUBPP-Cdkdx7gB.js → vennDiagram-DHZGUBPP-CrOJisSD.js} +1 -1
  69. package/dist/assets/{wardley-RL74JXVD-YKzsVN4U.js → wardley-RL74JXVD-By8Ltw9G.js} +1 -1
  70. package/dist/assets/{wardleyDiagram-NUSXRM2D-gBsb6aut.js → wardleyDiagram-NUSXRM2D-5SnzlvF9.js} +1 -1
  71. package/dist/assets/{xychartDiagram-5P7HB3ND-Bh63NWof.js → xychartDiagram-5P7HB3ND-CJ4uNjoK.js} +1 -1
  72. package/dist/index.html +4 -4
  73. package/package.json +1 -1
  74. package/server/lib/restart-helper.js +65 -0
  75. package/server/lib/restart.js +83 -0
  76. package/server/lib/update-instances.js +42 -0
  77. package/server/lib/update-job.js +260 -0
  78. package/server/lib/updater.js +37 -220
  79. package/server/pty-manager.js +1 -0
  80. package/server/routes/project-meta.js +11 -7
  81. package/server/routes/update.js +58 -0
  82. package/server/server.js +17 -5
  83. package/dist/assets/App-Cfmm41z0.js +0 -2
  84. package/dist/assets/classDiagram-6PBFFD2Q-4Lh0SB4X.js +0 -1
  85. package/dist/assets/classDiagram-v2-HSJHXN6E-4Lh0SB4X.js +0 -1
  86. package/dist/assets/clone-cWiXtXrO.js +0 -1
@@ -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 };
@@ -445,6 +445,7 @@ async function _spawnClaudeImpl(key, proxyPort, cwd, extraArgs = [], claudePath
445
445
  // process (im-process-manager already strips the same for IM workers).
446
446
  delete env.CCV_WORKSPACE_MODE;
447
447
  delete env.CCV_ELECTRON_MULTITAB;
448
+ delete env.CCV_ELECTRON_TAB;
448
449
  // Claude Code's NO_FLICKER makes the embedded xterm use the alt screen and lose
449
450
  // scrollback. cc-viewer strips the inherited value by default; set
450
451
  // CCV_KEEP_CLAUDE_CODE_NO_FLICKER=1 explicitly when it is actually needed.
@@ -8,7 +8,7 @@ import { sanitizePathComponent } from '../lib/v2/layout.js';
8
8
  import { resolveViewRoot } from '../lib/view-root.js';
9
9
  import { loadWorkspaces } from '../workspace-registry.js';
10
10
  import { listLivePtys } from '../pty-manager.js';
11
- import { detectHomebrewInstall } from '../lib/updater.js';
11
+ import { detectHomebrewInstall, detectPnpmGlobalInstall } from '../lib/updater.js';
12
12
 
13
13
  // Multi-project (2026-10, review P2-6): stats reads for a VIEWED project must
14
14
  // not become a presence oracle over LOG_DIR — `?project=` is accepted ONLY
@@ -43,12 +43,13 @@ function _resolveStatsName(projectParam, instanceParam, res) {
43
43
  // deps 仅供单测注入;失败安全:detect 抛异常时回落到 npm(不会误导 brew 用户走 npm)。
44
44
  export function getInstallMethod({
45
45
  electron = process.versions && process.versions.electron,
46
+ electronTab = process.env.CCV_ELECTRON_TAB === '1',
46
47
  detect = detectHomebrewInstall,
48
+ detectPnpm = detectPnpmGlobalInstall,
47
49
  } = {}) {
48
- if (electron) return 'electron';
49
- try {
50
- if (detect()) return 'brew';
51
- } catch { /* 探测失败 → 回落 npm */ }
50
+ if (electron || electronTab) return 'electron';
51
+ try { if (detect()) return 'brew'; } catch { }
52
+ try { if (detectPnpm()) return 'pnpm'; } catch { }
52
53
  return 'npm';
53
54
  }
54
55
 
@@ -63,11 +64,14 @@ function projectDir(req, res) {
63
64
  res.end(JSON.stringify({ dir }));
64
65
  }
65
66
 
66
- function versionInfo(req, res) {
67
+ const PROCESS_STARTED_AT = Date.now();
68
+ const PROCESS_ID = `${process.pid}-${PROCESS_STARTED_AT}`;
69
+
70
+ function versionInfo(req, res, parsedUrl, isLocal, deps) {
67
71
  try {
68
72
  const pkg = JSON.parse(readFileSync(PACKAGE_JSON, 'utf-8'));
69
73
  res.writeHead(200, { 'Content-Type': 'application/json' });
70
- res.end(JSON.stringify({ version: pkg.version, installMethod: getInstallMethod() }));
74
+ res.end(JSON.stringify({ version: pkg.version, installMethod: getInstallMethod(), processId: PROCESS_ID, canRestart: deps?.canRestartProcess === true, instanceKind: process.env.CCV_IM_PLATFORM ? 'im' : (process.env.CCV_WORKSPACE_MODE ? 'workspace' : 'normal'), instancePort: deps?.actualPort || null }));
71
75
  } catch {
72
76
  res.writeHead(500, { 'Content-Type': 'application/json' });
73
77
  res.end(JSON.stringify({ error: 'Failed to read version' }));
@@ -0,0 +1,58 @@
1
+ import { isAdminReq } from '../lib/is-admin.js';
2
+ import { isSameOriginBrowserRequest } from '../lib/same-origin.js';
3
+ import { reportSwallowed } from '../lib/error-report.js';
4
+
5
+ function json(res, status, value) {
6
+ res.writeHead(status, { 'Content-Type': 'application/json' });
7
+ res.end(JSON.stringify(value));
8
+ }
9
+
10
+ function allowed(req, res, parsedUrl, isLocal) {
11
+ if (isAdminReq(req, isLocal) && isSameOriginBrowserRequest(req, parsedUrl)) return true;
12
+ json(res, 403, { error: 'Forbidden: admin and same-origin required' });
13
+ return false;
14
+ }
15
+
16
+ async function status(req, res, parsedUrl, isLocal, deps) {
17
+ if (!allowed(req, res, parsedUrl, isLocal)) return;
18
+ json(res, 200, deps.updateJob.getState());
19
+ }
20
+
21
+ async function check(req, res, parsedUrl, isLocal, deps) {
22
+ if (!allowed(req, res, parsedUrl, isLocal)) return;
23
+ const state = await deps.updateJob.check();
24
+ json(res, state.status === 'error' ? 502 : 200, state);
25
+ }
26
+
27
+ async function start(req, res, parsedUrl, isLocal, deps) {
28
+ if (!allowed(req, res, parsedUrl, isLocal)) return;
29
+ if (deps.isRuntimeStopping) { json(res, 409, { error: 'Server is stopping' }); return; }
30
+ if (!deps.canRestartProcess && deps.updateJob.getState().status !== 'restart_required') {
31
+ json(res, 409, { error: 'Restart is unavailable for this launch mode' });
32
+ return;
33
+ }
34
+ if (['checking', 'downloading', 'installing', 'restarting', 'restart_required'].includes(deps.updateJob.getState().status)) {
35
+ json(res, 200, deps.updateJob.getState());
36
+ return;
37
+ }
38
+ deps.updateJob.start().catch((err) => reportSwallowed('update.start', err));
39
+ json(res, 202, deps.updateJob.getState());
40
+ }
41
+
42
+ async function restart(req, res, parsedUrl, isLocal, deps) {
43
+ if (!allowed(req, res, parsedUrl, isLocal)) return;
44
+ if (deps.isRuntimeStopping) { json(res, 409, { error: 'Server is stopping', code: 'stopping' }); return; }
45
+ if (!['restart_required', 'restarting'].includes(deps.updateJob.getState().status)) { json(res, 409, { error: 'No verified update is ready', code: 'not_ready' }); return; }
46
+ if (!deps.canRestartProcess) { json(res, 409, { error: 'Restart is unavailable for this launch mode' }); return; }
47
+ try {
48
+ await deps.updateJob.restart(deps.restartProcess);
49
+ if (!res.writableEnded) json(res, 200, { ok: true, status: 'restarting' });
50
+ } catch (err) { reportSwallowed('update.restart', err); if (!res.writableEnded) json(res, 500, { error: err.message }); }
51
+ }
52
+
53
+ export const updateRoutes = [
54
+ { method: 'GET', match: 'exact', path: '/api/update/status', handler: status },
55
+ { method: 'POST', match: 'exact', path: '/api/update/check', handler: check },
56
+ { method: 'POST', match: 'exact', path: '/api/update/start', handler: start },
57
+ { method: 'POST', match: 'exact', path: '/api/update/restart', handler: restart },
58
+ ];
package/server/server.js CHANGED
@@ -47,6 +47,8 @@ import { resumeRoutes } from './routes/resume.js';
47
47
  import { sdkContextRoutes } from './routes/sdk-context.js';
48
48
  import { sdkMcpStatusRoutes } from './routes/sdk-mcp-status.js';
49
49
  import { proxyStatsRoutes } from './routes/proxy-stats.js';
50
+ import { updateRoutes } from './routes/update.js';
51
+ import { UpdateJob } from './lib/update-job.js';
50
52
  import { setProxyStatsListener, setSlowUpstreamListener } from './lib/proxy/proxy-stats.js';
51
53
  import * as imCore from './lib/im/im-bridge-core.js';
52
54
  import * as imProcMgr from './lib/im/im-process-manager.js';
@@ -353,6 +355,8 @@ export function setWorkspaceClaudePath(path, isNpm) {
353
355
  }
354
356
  let _launchCallback = null;
355
357
  export function setLaunchCallback(fn) { _launchCallback = fn; }
358
+ let _restartHandler = null;
359
+ export function setRestartHandler(fn) { _restartHandler = fn; }
356
360
  export function setWorkspaceLaunched(v) { _workspaceLaunched = v; }
357
361
  export function initPostLaunch() {
358
362
  startLogWatch();
@@ -732,6 +736,11 @@ function _ensureImWatch(id) {
732
736
  catch (e) { console.warn(`[im-log-watcher] ensure(${id}) failed:`, e?.message || e); }
733
737
  }
734
738
 
739
+ const updateJob = new UpdateJob({ get currentPort() { return actualPort; } });
740
+ updateJob.subscribe((state) => {
741
+ sendEventToClients(clients, 'update_progress', state);
742
+ });
743
+
735
744
  const deps = {
736
745
  // Reassignable runtime state — must stay getters.
737
746
  get protocol() { return serverProtocol; },
@@ -747,6 +756,10 @@ const deps = {
747
756
  // the live value at request time (e.g. resume.js scope-key resolution).
748
757
  get projectName() { return _projectName || ''; },
749
758
  get launchCallback() { return _launchCallback; },
759
+ updateJob,
760
+ restartProcess: (version) => _restartHandler(version),
761
+ get canRestartProcess() { return typeof _restartHandler === 'function'; },
762
+ get isRuntimeStopping() { return _isStopping; },
750
763
  get workspaceClaudeArgs() { return _workspaceClaudeArgs; },
751
764
  get workspaceClaudePath() { return _workspaceClaudePath; },
752
765
  get workspaceIsNpmVersion() { return _workspaceIsNpmVersion; },
@@ -939,6 +952,7 @@ const _routes = [
939
952
  ...dingtalkRoutes,
940
953
  ...imRoutes,
941
954
  ...proxyStatsRoutes,
955
+ ...updateRoutes,
942
956
  ...resumeRoutes,
943
957
  ...sdkContextRoutes,
944
958
  ...sdkMcpStatusRoutes,
@@ -4169,7 +4183,7 @@ if (!isWorkspaceMode) {
4169
4183
  // 延迟 30 秒异步检查更新。
4170
4184
  // 为什么是 30s 而非 3s:空闲/忙判断的核心是 `clients.length`(SSE 已连) + PTY + SDK。
4171
4185
  // 3s 时大多数 client 还没连上 → busy 恒 false → 升级照打断用户。30s 给"活跃会话"留出进入窗口。
4172
- // 同大版本直接后台 detached npm install(不阻塞事件循环);跨大版本 / 忙时 → 仅广播 banner,用户下次启动再升。
4186
+ // Check only; an install is always initiated and confirmed by the user.
4173
4187
  // 句柄必须保存:_doStop 要 clearTimeout(stop/start 循环防泄漏);.unref() 防 keep-alive。
4174
4188
  // 测试侧三重防护:此处 unref + updater.js 的 L5 铁闸 + npm test 脚本 DISABLE_NONESSENTIAL_TRAFFIC。
4175
4189
  _updateCheckTimer = setTimeout(async () => {
@@ -4185,17 +4199,15 @@ if (!isWorkspaceMode) {
4185
4199
  // 共用 update_major_available 事件渲染 banner(前端不区分子类,命令在 i18n 文案里给)。
4186
4200
  // brew_managed / pnpm_managed 走这里至关重要:否则 Electron / GUI 用户看不到升级提示,
4187
4201
  // 仅 stderr 一行 console.error 在桌面模式下不可见。
4188
- if (result.status === 'major_available' || result.status === 'deferred_busy' || result.status === 'brew_managed' || result.status === 'pnpm_managed') {
4202
+ if (result.remoteVersion && result.status !== 'latest' && result.status !== 'disabled' && result.status !== 'error') {
4189
4203
  // 先缓存:之后新连接的 SSE 客户端会在 events 路由里补推此事件
4190
4204
  pendingMajorUpdate = { version: result.remoteVersion, source: result.status };
4191
4205
  const payload = JSON.stringify(pendingMajorUpdate);
4192
4206
  clients.forEach(client => {
4193
4207
  try { sseWrite(client, `event: update_major_available\ndata: ${payload}\n\n`); } catch { }
4194
4208
  });
4195
- } else if (result.status === 'upgrading_in_background') {
4196
- console.error(`[CC Viewer] background upgrade to ${result.remoteVersion} started (active after next launch)`);
4197
4209
  }
4198
- } catch { /* update check 失败静默 */ }
4210
+ } catch (err) { reportSwallowed('server.update-check', err); }
4199
4211
  }, 30_000);
4200
4212
  _updateCheckTimer.unref();
4201
4213
  }).catch(err => {