cc-viewer 1.9.21 → 1.9.23

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 (45) hide show
  1. package/README.md +2 -1
  2. package/cli.js +50 -14
  3. package/dist/assets/{App-C4f2Dpy9.js → App-DEA3HoZr.js} +2 -2
  4. package/dist/assets/{MdxEditorPanel-D7aQDQJp.js → MdxEditorPanel-CTAS2DJv.js} +1 -1
  5. package/dist/assets/{Mobile-D9ekLQFS.js → Mobile-CgVpXvs2.js} +1 -1
  6. package/dist/assets/{ProxyStatsModal-CWpgyVKI.js → ProxyStatsModal-C4sl-cuB.js} +1 -1
  7. package/dist/assets/index-CS47d9oh.js +2 -0
  8. package/dist/assets/seqResourceLoaders-CORH46PN.js +2 -0
  9. package/dist/assets/seqResourceLoaders-v4YzKhTS.css +41 -0
  10. package/dist/index.html +1 -1
  11. package/findcc.js +4 -4
  12. package/node_modules/@ccv/core/src/contentFilter.js +4 -1
  13. package/node_modules/@ccv/core/src/ultraplanTemplates.js +199 -0
  14. package/package.json +1 -1
  15. package/server/i18n.js +97 -14
  16. package/server/interceptor.js +6 -0
  17. package/server/lib/async-write-queue.js +18 -0
  18. package/server/lib/auth.js +11 -3
  19. package/server/lib/base-path.js +89 -18
  20. package/server/lib/base-url.js +209 -0
  21. package/server/lib/ensure-hooks.js +134 -2
  22. package/server/lib/im/im-bridge-core.js +16 -0
  23. package/server/lib/log-management.js +21 -1
  24. package/server/lib/plugin-runtime.js +24 -5
  25. package/server/lib/scheduled-task-executor.js +14 -2
  26. package/server/lib/scheduled-task-store.js +129 -18
  27. package/server/lib/sdk-manager.js +113 -11
  28. package/server/lib/v2/adapter.js +147 -15
  29. package/server/lib/v2/conversation-store.js +9 -0
  30. package/server/lib/v2/journal.js +35 -0
  31. package/server/lib/v2/layout.js +67 -1
  32. package/server/lib/v2/live-feed.js +15 -0
  33. package/server/lib/v2/replay.js +11 -3
  34. package/server/lib/v2/session-select.js +34 -2
  35. package/server/lib/v2/shard-manager.js +249 -0
  36. package/server/lib/v2/v2-writer.js +252 -6
  37. package/server/pty-manager.js +103 -4
  38. package/server/routes/events.js +75 -4
  39. package/server/routes/logs.js +47 -16
  40. package/server/routes/misc.js +15 -5
  41. package/server/routes/scheduled-tasks.js +13 -0
  42. package/server/server.js +123 -23
  43. package/dist/assets/index-CocpEURl.js +0 -2
  44. package/dist/assets/seqResourceLoaders-BhiCEaUt.js +0 -2
  45. package/dist/assets/seqResourceLoaders-DbccWwKz.css +0 -41
package/server/server.js CHANGED
@@ -133,7 +133,8 @@ import { createImLogWatcher } from './lib/im/im-log-watcher.js';
133
133
  import { unwatchAllWorkflows } from './lib/workflow-watcher.js';
134
134
  import { backupConfigs } from './lib/config-backup.js';
135
135
  import { migrateCredentialsToVault } from './lib/credential-migrate.js';
136
- import { normalizeBasePath, validateBasePath, stripBasePath } from './lib/base-path.js';
136
+ import { validateBasePath, stripBasePath } from './lib/base-path.js';
137
+ import { resolveBaseConfig, externalUrlFromConfig, baseUrlAllowedHost } from './lib/base-url.js';
137
138
  import { createHardenedCleanup } from './lib/term-signals.js';
138
139
  import { createBackpressureGate } from './lib/ws-backpressure.js';
139
140
  import { createFloodCoalescer, envIntAllowZero } from './lib/pty-flood-coalescer.js';
@@ -609,6 +610,17 @@ function startLogWatch() {
609
610
  const feed = _feedForSessionDir(dir);
610
611
  if (feed) feed.tick(dir);
611
612
  });
613
+ // Shard rotation (2026-11): after a rotation the dir's journal was rebuilt
614
+ // small at the SAME path — the feed's shrink→rebuild heuristic would re-attach
615
+ // with suppressExisting:true and swallow the fresh shard's first post-cut
616
+ // entries. Re-attach it explicitly WITHOUT suppression (the fresh shard is new
617
+ // content, not cold-load history).
618
+ _v2Writer.setOnShardRotated((dir) => {
619
+ try {
620
+ const feed = _feedForSessionDir(dir);
621
+ if (feed && typeof feed.reattachAfterShardRotation === 'function') feed.reattachAfterShardRotation(dir);
622
+ } catch { /* nudge only — never disturb the write */ }
623
+ });
612
624
  // Feed each resolved (sid, project) into the PTY sid index so chat sends can
613
625
  // be routed to the PTY owning that conversation (anchor routing, 2026-10-05).
614
626
  // Lazy import keeps pty-manager out of the early module graph (and off the
@@ -960,6 +972,13 @@ function checkHostAllowed(hostHeaderValue) {
960
972
  const allowedHosts = process.env.CCV_ALLOWED_HOSTS
961
973
  ? process.env.CCV_ALLOWED_HOSTS.split(',').map(s => s.trim()).filter(Boolean)
962
974
  : ['localhost', '127.0.0.1', '::1', '[::1]', ...getAllLocalIps()];
975
+ // A CCV_BASE_URL with a host is an explicit trust declaration: always merge it into the
976
+ // allowlist (additive semantics — an explicit CCV_ALLOWED_HOSTS list is kept, the base URL
977
+ // host appended), otherwise every request under the cloud-proxy domain (including the WS
978
+ // upgrade) is 403 host-not-allowed. Hostname only (port stripped), matching the hostNoPort
979
+ // comparison below. Merge semantics confirmed with the user (docs/base-url.md §Host allowlist).
980
+ const baseUrlHost = baseUrlAllowedHost();
981
+ if (baseUrlHost && !allowedHosts.includes(baseUrlHost)) allowedHosts.push(baseUrlHost);
963
982
  if (allowedHosts.includes('*')) return null;
964
983
  const hostHeader = (hostHeaderValue || '').toLowerCase();
965
984
  // Port stripping: RFC 3986 requires bracketed IPv6 `[::1]:port`; bare `::1` would lose its last `\d` to port stripping.
@@ -975,6 +994,18 @@ function checkHostAllowed(hostHeaderValue) {
975
994
  }
976
995
 
977
996
  async function handleRequest(req, res) {
997
+ // CCV_BASE_URL / CCV_BASE_PATH reverse proxy: strip prefix at TOP so API/WS/static/SPA
998
+ // all work with original unprefixed paths. The stripped path MUST be written back to
999
+ // parsedUrl.pathname — dispatch() (routes/_dispatch.js) and several handlers
1000
+ // (files-content/ask-perm/im) read parsedUrl.pathname directly for routing and offset
1001
+ // slicing; without the write-back every prefixed /api/* and SSE /events misses and falls
1002
+ // to the SPA fallback (PR #108 leftover P0). searchParams are unaffected by the pathname
1003
+ // assignment. Effective prefix: CCV_BASE_URL's path first, CCV_BASE_PATH as fallback;
1004
+ // re-read per request (tests flip env). Literal '{'/'}' need no preprocessing: new URL
1005
+ // percent-encodes them in special-scheme pathnames ('/a{token}/b' → '/a%7Btoken%7D/b'),
1006
+ // so stripBasePath matching on the encoded wire form naturally covers both client shapes
1007
+ // (literal via curl -g / proxy pass-through, encoded via browser/fetch).
1008
+ const bp = resolveBaseConfig().basePath;
978
1009
  const parsedUrl = safeParseRequestUrl(req);
979
1010
  if (!parsedUrl) {
980
1011
  res.writeHead(400, { 'Content-Type': 'application/json' });
@@ -982,13 +1013,6 @@ async function handleRequest(req, res) {
982
1013
  return;
983
1014
  }
984
1015
  let url = parsedUrl.pathname;
985
-
986
- // CCV_BASE_PATH reverse proxy: strip prefix at TOP so API/WS/static/SPA
987
- // all work with original unprefixed paths. 剥离后必须写回 parsedUrl.pathname ——
988
- // dispatch()(routes/_dispatch.js)与多个 handler(files-content/ask-perm/im)直读
989
- // parsedUrl.pathname 做路由匹配和偏移 slice,不写回则前缀下全部 /api/* 与 SSE /events
990
- // 命不中、落 SPA fallback(PR #108 遗留 P0)。searchParams 不受 pathname 赋值影响。
991
- const bp = normalizeBasePath(process.env.CCV_BASE_PATH);
992
1016
  url = stripBasePath(url, bp);
993
1017
  parsedUrl.pathname = url;
994
1018
  const method = req.method;
@@ -1047,7 +1071,7 @@ async function handleRequest(req, res) {
1047
1071
  if (authDecision.action === 'login-page') {
1048
1072
  const lang = localeFromAcceptLanguage(req.headers['accept-language']) || getLang();
1049
1073
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' });
1050
- res.end(renderLoginPage({ lang }));
1074
+ res.end(renderLoginPage({ lang, basePath: bp }));
1051
1075
  return;
1052
1076
  }
1053
1077
  if (authDecision.action === 'unauthorized') {
@@ -1145,7 +1169,7 @@ async function handleRequest(req, res) {
1145
1169
  // base=''(相对路径产物),让浏览器把所有相对 URL(含任意深度 SPA-fallback 文档里的
1146
1170
  // ./assets)解析到正确根/前缀下,避免深链直访(如 /a/b)时相对当前路径解析 → 白屏。
1147
1171
  // window.__CCV_BASE_PATH__ 仅子路径时注入:运行时 API/WS 的 base 语义保持"未设=无前缀"不变。
1148
- const injectBase = normalizeBasePath(process.env.CCV_BASE_PATH);
1172
+ const injectBase = bp;
1149
1173
  const baseHref = injectBase || '/';
1150
1174
  const escapedBase = baseHref.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
1151
1175
  let injectHtml = `<base href="${escapedBase}">`;
@@ -1500,26 +1524,40 @@ async function _doStart() {
1500
1524
  if (_prefs.lang) setLang(_prefs.lang);
1501
1525
  }
1502
1526
  } catch { /* 读 prefs 失败就保持默认语言 */ }
1503
- // CCV_BASE_PATH 配置校验:缺前导 '/' 时剥离静默失效(startsWith 永不命中),
1504
- // 启动期告警一次。放在 setLang 之后,告警语言才跟随用户配置。
1527
+ // CCV_BASE_URL / CCV_BASE_PATH config validation: an invalid CCV_BASE_URL falls
1528
+ // back to the legacy var with a warning; when both are set CCV_BASE_URL wins with
1529
+ // a notice; the legacy CCV_BASE_PATH missing-leading-'/' warning is kept (only when
1530
+ // not overridden by CCV_BASE_URL). Placed AFTER setLang so the warning language
1531
+ // follows the user's configured locale.
1532
+ const _baseCfg = resolveBaseConfig();
1505
1533
  {
1506
- const _bpCheck = validateBasePath(process.env.CCV_BASE_PATH);
1507
- if (_bpCheck.warning) console.warn(t(_bpCheck.warning, { value: process.env.CCV_BASE_PATH }));
1534
+ if (_baseCfg.source !== 'baseUrl') {
1535
+ const _bpCheck = validateBasePath(process.env.CCV_BASE_PATH);
1536
+ if (_bpCheck.warning) console.warn(t(_bpCheck.warning, { value: process.env.CCV_BASE_PATH }));
1537
+ }
1538
+ if (_baseCfg.warning) console.warn(t(_baseCfg.warning, { value: _baseCfg.warningValue }));
1508
1539
  }
1509
1540
  // interceptor.js runs in this same process (via proxy.js → setupInterceptor).
1510
1541
  // Inject live-port via module-level setter instead of process.env to avoid
1511
1542
  // polluting env of child_process.spawn descendants (Bash tools / MCP / Electron tabs).
1512
1543
  setLivePort(port, serverProtocol);
1513
1544
  // 自动打开/serverStarted hook 用的 URL 也要带反代前缀(与启动打印一致)
1514
- const url = `${serverProtocol}://127.0.0.1:${port}${normalizeBasePath(process.env.CCV_BASE_PATH)}`;
1545
+ const url = `${serverProtocol}://127.0.0.1:${port}${_baseCfg.basePath}`;
1546
+ // CCV_BASE_URL with a host: the public URL shown to the outside (QR/share/External
1547
+ // line). At startup there is no request context, so the scheme is the explicit
1548
+ // value or https by default (X-Forwarded-Proto is only available per request, in
1549
+ // /api/local-url). Must carry ?token= — under the default token auth a remote link
1550
+ // without it is a 403 dead link.
1551
+ const externalUrl = externalUrlFromConfig(_baseCfg, { token: ACCESS_TOKEN });
1552
+ const openUrl = externalUrl || url;
1515
1553
  if (!isCliMode) {
1516
1554
  console.error(t('server.started'));
1517
- const _bp = normalizeBasePath(process.env.CCV_BASE_PATH);
1518
- console.error(t('server.startedLocal', { protocol: serverProtocol, port, basePath: _bp }));
1555
+ console.error(t('server.startedLocal', { protocol: serverProtocol, port, basePath: _baseCfg.basePath }));
1519
1556
  const _ips = getAllLocalIps();
1520
1557
  for (const _ip of _ips) {
1521
- console.error(t('server.startedNetwork', { protocol: serverProtocol, ip: _ip, port, basePath: _bp, token: ACCESS_TOKEN }));
1558
+ console.error(t('server.startedNetwork', { protocol: serverProtocol, ip: _ip, port, basePath: _baseCfg.basePath, token: ACCESS_TOKEN }));
1522
1559
  }
1560
+ if (externalUrl) console.error(t('server.startedExternal', { url: externalUrl }));
1523
1561
  if (authConfig.enabled) {
1524
1562
  if (authConfig.password === '') console.error(t('server.passwordEmptyWarn'));
1525
1563
  else console.error(t('server.passwordActive', { password: authConfig.password }));
@@ -1532,8 +1570,19 @@ async function _doStart() {
1532
1570
  const ccVer = JSON.parse(readFileSync(ccPkgPath, 'utf-8')).version;
1533
1571
  const [maj, min, pat] = ccVer.split('.').map(Number);
1534
1572
  if ((maj < 2 || (maj === 2 && min === 0 && pat < 69)) && !isBrowserOpenSuppressed()) {
1535
- const cmd = platform() === 'darwin' ? 'open' : platform() === 'win32' ? 'start' : 'xdg-open';
1536
- execAsync(`${cmd} ${url}`, { timeout: 5000 }).catch(() => {});
1573
+ // spawn with an argv array bypasses the shell: the '?token='/'{token}' in the
1574
+ // URL is never shell-expanded or word-split; on Windows `start` is a cmd.exe
1575
+ // builtin whose second arg '""' is the title placeholder (otherwise the URL is
1576
+ // treated as the title).
1577
+ let child;
1578
+ if (platform() === 'win32') {
1579
+ child = spawn('cmd.exe', ['/c', 'start', '""', openUrl], { stdio: 'ignore', detached: true, windowsHide: true });
1580
+ } else {
1581
+ child = spawn(platform() === 'darwin' ? 'open' : 'xdg-open', [openUrl], { stdio: 'ignore', detached: true, windowsHide: true });
1582
+ }
1583
+ // headless/容器环境可能无 xdg-open/open/start → spawn 异步 error 事件需兜底
1584
+ child.on('error', () => {});
1585
+ child.unref();
1537
1586
  }
1538
1587
  } catch { }
1539
1588
  // 工作区模式下延迟到选择工作区后再启动监听
@@ -1563,7 +1612,7 @@ async function _doStart() {
1563
1612
  await pluginRuntime.onServerStarted({
1564
1613
  logDir: LOG_DIR,
1565
1614
  port, host: HOST,
1566
- basePath: normalizeBasePath(process.env.CCV_BASE_PATH),
1615
+ basePath: _baseCfg.basePath,
1567
1616
  protocol: serverProtocol,
1568
1617
  token: ACCESS_TOKEN,
1569
1618
  internalToken: INTERNAL_TOKEN,
@@ -1611,6 +1660,7 @@ async function _doStart() {
1611
1660
  getPtyState: pmb.getPtyState,
1612
1661
  getPtyKind: pmb.getPtyKind,
1613
1662
  getPtySkipPermissions: pmb.getPtySkipPermissions,
1663
+ getPtyBootState: pmb.getPtyBootState,
1614
1664
  isStreaming: () => streamingState.active,
1615
1665
  getConfig: () => loadConfig(id),
1616
1666
  // 钉钉 AI 卡片逐字流式的文本源(仅 worker 注入):对话过程中读主 agent 累计文本,
@@ -1728,10 +1778,13 @@ function installUpgradeRouter(httpServer) {
1728
1778
  if (!httpServer._ccvUpgradeRoutes) httpServer._ccvUpgradeRoutes = [];
1729
1779
  httpServer.on('upgrade', (req, socket, head) => {
1730
1780
  try {
1781
+ // Upgrades bypass handleRequest, so basePath is stripped independently (same helper as
1782
+ // HTTP). Literal braces need no pre-handling: new URL already encodes them in the
1783
+ // pathname, and stripBasePath matches the wire form.
1784
+ const bp = resolveBaseConfig().basePath;
1731
1785
  const wsUrl = safeParseRequestUrl(req);
1732
1786
  if (!wsUrl) { socket.destroy(); return; }
1733
- // Upgrades bypass handleRequest, so basePath is stripped independently (same helper as HTTP)
1734
- const pathname = stripBasePath(wsUrl.pathname, normalizeBasePath(process.env.CCV_BASE_PATH));
1787
+ const pathname = stripBasePath(wsUrl.pathname, bp);
1735
1788
  // Same auth as HTTP (WS upgrades previously ignored tokens entirely - a remote-terminal hole).
1736
1789
  // Compute isLocal explicitly here (same three-way check as handleRequest); WS is never an HTML request.
1737
1790
  const wsRemoteIp = req.socket.remoteAddress;
@@ -2344,6 +2397,31 @@ async function setupTerminalWebSocket(httpServer) {
2344
2397
  }
2345
2398
  }
2346
2399
 
2400
+ // Replay the authoritative sdk-task table so a refreshed/reconnected client can
2401
+ // reconcile its delta-only tracker (the active-agents strip) — a task frame lost in
2402
+ // a WS gap is no longer unrecoverable, and a session switch drops the table so the
2403
+ // prior session's agents never linger. Unlike the snapshots above, an EMPTY
2404
+ // `tasks: []` is authoritative (reconciles the client to "no tasks") and must be
2405
+ // sent. Anchor by view instance (exact) else view project — sdk-skills parity. When
2406
+ // the anchor resolves to no session at all, synthesize that empty frame for a bound
2407
+ // view so the reconcile is not silently lost; an unbound view sends nothing.
2408
+ if (isSdkMode && _sdkGetSdkTaskSnapshot) {
2409
+ const anchor = ws._ccvViewInstance
2410
+ ? { instanceKey: ws._ccvViewInstance }
2411
+ : (_viewProj ? { project: _viewProj } : null);
2412
+ const taskSnap = anchor ? _sdkGetSdkTaskSnapshot(anchor) : _sdkGetSdkTaskSnapshot();
2413
+ const taskFrame = taskSnap || ((ws._ccvViewInstance || ws._ccvViewProject) ? {
2414
+ type: 'sdk-task-snapshot',
2415
+ ...(ws._ccvViewProject ? { project: ws._ccvViewProject } : {}),
2416
+ ...(ws._ccvViewInstance ? { instanceKey: ws._ccvViewInstance } : {}),
2417
+ sessionId: null,
2418
+ tasks: [],
2419
+ } : null);
2420
+ if (taskFrame && _sdkFrameForView(taskFrame)) {
2421
+ try { ws.send(JSON.stringify(taskFrame)); } catch {}
2422
+ }
2423
+ }
2424
+
2347
2425
  // Replay the chat-composer busy queue so a refreshed/reconnected page restores the
2348
2426
  // floating queued-message bubbles (server is the source of truth in both modes).
2349
2427
  replayQueueSnapshot();
@@ -2521,6 +2599,24 @@ async function setupTerminalWebSocket(httpServer) {
2521
2599
  try { ws.send(JSON.stringify(stateSnap)); } catch (err) { reportSwallowed('sdk.session-state-replay', err); }
2522
2600
  }
2523
2601
  }
2602
+ // Replay the authoritative sdk-task table for the JUST-viewed workspace
2603
+ // (skills parity) so switching back to a workspace whose agent is mid-run
2604
+ // restores the active-agents strip immediately, and an empty table clears
2605
+ // a previously viewed workspace's agents. Anchor AND filter against the
2606
+ // freshly-stamped view — _sdkFrameForView closes over the connection-time
2607
+ // _viewProj, which is the departing view on a cross-workspace attach.
2608
+ if (_sdkGetSdkTaskSnapshot) {
2609
+ const taskAnchor = ws._ccvViewInstance
2610
+ ? { instanceKey: ws._ccvViewInstance }
2611
+ : (ws._ccvViewProject ? { project: ws._ccvViewProject } : null);
2612
+ const taskSnap = taskAnchor ? _sdkGetSdkTaskSnapshot(taskAnchor) : _sdkGetSdkTaskSnapshot();
2613
+ if (taskSnap) {
2614
+ const fp = (typeof taskSnap.cwd === 'string' && taskSnap.cwd) ? (projectKeyForCwd(taskSnap.cwd) || null) : null;
2615
+ if (!fp || !ws._ccvViewProject || fp === ws._ccvViewProject) {
2616
+ try { ws.send(JSON.stringify(taskSnap)); } catch { }
2617
+ }
2618
+ }
2619
+ }
2524
2620
  replayQueueSnapshot();
2525
2621
  return;
2526
2622
  }
@@ -3992,6 +4088,10 @@ export function setSdkGetMcpStatusSnapshot(fn) { _sdkGetMcpStatusSnapshot = fn;
3992
4088
  let _sdkGetSessionStateSnapshot = null;
3993
4089
  export function setSdkGetSessionStateSnapshot(fn) { _sdkGetSessionStateSnapshot = fn; }
3994
4090
 
4091
+ /** Reference to sdk-manager's getSdkTaskSnapshot (set by cli.js after import). */
4092
+ let _sdkGetSdkTaskSnapshot = null;
4093
+ export function setSdkGetSdkTaskSnapshot(fn) { _sdkGetSdkTaskSnapshot = fn; }
4094
+
3995
4095
  /** Reference to sdk-manager's sendQueuedNow (set by cli.js after import). */
3996
4096
  let _sdkSendQueuedNow = null;
3997
4097
  export function setSdkSendQueuedNow(fn) { _sdkSendQueuedNow = fn; }