cc-viewer 1.9.21 → 1.9.22

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.
@@ -9,7 +9,8 @@ import { reportSwallowed } from '../lib/error-report.js';
9
9
  import { sseHead, sseWrite, needsDrain, wireEnd, awaitWireDrain, isWireV3Enabled } from '../lib/wire-compress.js';
10
10
  import { scopeKeyForProducer } from '../lib/scope-router.js';
11
11
  import { readV2ColdBundle } from '../lib/v2/meta-rows.js';
12
- import { readV2SingleEntry } from '../lib/v2/adapter.js';
12
+ import { readV2SingleEntry, readV2ShardEntries, isV2SessionDir } from '../lib/v2/adapter.js';
13
+ import { initialShardCursor } from '../lib/v2/shard-manager.js';
13
14
  import { createAttachBufferClient, flushAttachBuffer } from '../lib/attach-buffer.js';
14
15
  import { resolveSessionDirName, latestMainSessionDir } from '../lib/v2/session-select.js';
15
16
  import { sanitizePathComponent, normalizeSessionCwd } from '../lib/v2/layout.js';
@@ -171,6 +172,7 @@ export function paramsFromParsedUrl(parsedUrl) {
171
172
  const sidRaw = g('sid');
172
173
  const instanceRaw = g('instance');
173
174
  const limitRaw = g('limit');
175
+ const shardBeforeRaw = g('shardBefore');
174
176
  return {
175
177
  sid: (typeof sidRaw === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(sidRaw)) ? sidRaw : null,
176
178
  project: g('project'),
@@ -179,6 +181,10 @@ export function paramsFromParsedUrl(parsedUrl) {
179
181
  cc: parseInt(g('cc'), 10) || 0,
180
182
  limitRaw, // keep the raw string so "absent" (null) ≠ "explicit 0"
181
183
  limitGiven: limitRaw !== null,
184
+ // Sharding (2026-11): when present with ?sid, the cold load reads the
185
+ // frozen `.part<N>` shard older than this journal seq instead of the
186
+ // active session dir.
187
+ shardBefore: (typeof shardBeforeRaw === 'string' && /^\d+$/.test(shardBeforeRaw)) ? parseInt(shardBeforeRaw, 10) : 0,
182
188
  };
183
189
  }
184
190
 
@@ -203,6 +209,18 @@ export function sseUpdateBadgeFrame(pending) {
203
209
  * sink.registrable the object pushed into deps.clients (gets _ccvView* stamps)
204
210
  */
205
211
 
212
+ /**
213
+ * Initial shard cursor for a cold-load source: when the session has frozen
214
+ * shards, the "load earlier history" button needs the entry point — the seq
215
+ * just past the newest frozen shard's cut (i.e. the first seq the ACTIVE dir
216
+ * owns). Returns null when there are no shards. Delegates to shard-manager's
217
+ * shared implementation (cut.json-aware).
218
+ */
219
+ function _initialShardCursor(sourceDir) {
220
+ if (!sourceDir || !isV2SessionDir(sourceDir)) return null;
221
+ return initialShardCursor(sourceDir);
222
+ }
223
+
206
224
  /**
207
225
  * serveEventStream — THE single implementation of one /events stream, behind both the SSE
208
226
  * route and the WS-mux stream. Resolves after history + kv/context + the broadcast-list
@@ -243,7 +261,7 @@ export async function serveEventStream(sink, params, deps) {
243
261
  // previous tail-registration leaked the timer and pushed a dead res in that window.
244
262
  sink.onClose?.(dispose);
245
263
 
246
- const { sidParam, projectParam, instanceParam, sinceParam, ccParam, limitRaw, limitGiven } = {
264
+ const { sidParam, projectParam, instanceParam, sinceParam, ccParam, limitRaw, limitGiven, shardBeforeParam } = {
247
265
  sidParam: params.sid,
248
266
  projectParam: params.project,
249
267
  instanceParam: params.instance,
@@ -251,6 +269,7 @@ export async function serveEventStream(sink, params, deps) {
251
269
  ccParam: params.cc,
252
270
  limitRaw: params.limitRaw,
253
271
  limitGiven: params.limitGiven,
272
+ shardBeforeParam: params.shardBefore,
254
273
  };
255
274
 
256
275
  // 注意:不要在此处 clients.push(res)!
@@ -488,15 +507,58 @@ export async function serveEventStream(sink, params, deps) {
488
507
  // Wire v3 (V3.S5): flagged + v2 source ⇒ the legacy full-entry cold stream
489
508
  // is REPLACED by rows + native lines (the byte win); the client assembler
490
509
  // rebuilds entries locally. v1 legacy files keep the entry pipeline.
491
- const _v3Src = (deps.wireV3 && !emptyLiveView) ? (coldSource || getLiveLogSource()) : null;
510
+ // A shardBefore cold read is a legacy-shape stream over ONE frozen shard —
511
+ // never the v3 native bundle (the client renders it as a "load earlier"
512
+ // prepend, not a fresh baseline).
513
+ const _v3Src = (deps.wireV3 && !emptyLiveView && !shardBeforeParam) ? (coldSource || getLiveLogSource()) : null;
492
514
  const v3Cold = !!(_v3Src && existsSync(join(_v3Src, 'journal.jsonl')));
493
515
 
516
+ // Sharding (2026-11): ?sid=<uuid>&shardBefore=<seq> serves the frozen
517
+ // `.part<N>` shard immediately older than that seq, as a self-contained
518
+ // window with its own baseline (the shard's incremental snapshot replays to
519
+ // the cut state). Live append is untouched — the live feed only ever reads
520
+ // the active dir.
521
+ if (shardBeforeParam > 0 && viewColdDir && isV2SessionDir(viewColdDir)) {
522
+ try {
523
+ const shardRes = await readV2ShardEntries(viewColdDir, { beforeSeq: shardBeforeParam, limit: useLimit ? effectiveLimit : 0, cached: false });
524
+ sink.write(`event: load_start\ndata: ${JSON.stringify({
525
+ total: shardRes.totalCount,
526
+ incremental: false,
527
+ hasMore: shardRes.hasMore,
528
+ oldestTs: shardRes.oldestTimestamp || '',
529
+ // prepend:true tells the client this is a "load earlier" load — buffer
530
+ // chunks separately and PREPEND at load_end, never reset the baseline.
531
+ shard: { partIndex: shardRes.partIndex, oldestSeq: shardRes.oldestSeq, hasMore: shardRes.hasMore, prepend: true },
532
+ })}\n\n`);
533
+ for (const raw of shardRes.entries) {
534
+ if (!sink.alive()) break;
535
+ const out = enrichRawIfNeeded(raw);
536
+ try {
537
+ sink.write('event: load_chunk\ndata: [');
538
+ sink.write(out.includes('\n') ? out.replace(/\n/g, '') : out);
539
+ sink.write(']\n\n');
540
+ } catch { break; }
541
+ }
542
+ } catch (err) {
543
+ reportSwallowed('events.shard-load', err, { sid: sidParam, shardBefore: shardBeforeParam });
544
+ try { sink.write(`event: load_start\ndata: ${JSON.stringify({ total: 0, incremental: false, shard: { partIndex: 0, oldestSeq: null, hasMore: false, prepend: true } })}\n\n`); } catch {}
545
+ }
546
+ sink.write(`event: load_end\ndata: {}\n\n`);
547
+ return;
548
+ }
549
+
494
550
  // S6b: the cold-load source is the current v2 session dir when the v2
495
551
  // writer is active (adapter stream), else the v1 file.
496
552
  // serveInFlight follows the wire: the legacy entry stream ships the
497
553
  // in-flight placeholder, which the client batch gate still blocks — the
498
554
  // previous conversation is the better cold load there (interceptor.js
499
555
  // getLiveLogSource header comment).
556
+ // Initial shard cursor for the "load earlier history" button: computed once
557
+ // from the cold source. oldestSeq is REFINED in onReady to the delivered
558
+ // window's oldest seq (a limit-truncated cold window must not skip the active
559
+ // shard's own pre-window prefix by jumping straight to the frozen cut).
560
+ const _coldShardCursor = shardBeforeParam ? null : _initialShardCursor(emptyLiveView ? null : (coldSource || getLiveLogSource()));
561
+
500
562
  const coldLoadResult = v3Cold ? null : await streamRawEntriesAsync(emptyLiveView ? '' : (coldSource || getLiveLogSource({ serveInFlight: !!deps.wireV3 })), async (raw) => {
501
563
  // 直接发送原始 JSON 字符串,不做 parse/reconstruct/stringify
502
564
  // ExitPlanMode V2 空 input 的条目按需补全 plan / planFilePath,其它原样透传
@@ -536,7 +598,7 @@ export async function serveEventStream(sink, params, deps) {
536
598
  if (mainAgentRawRing.length > MAINAGENT_SCAN_RING) mainAgentRawRing.shift();
537
599
  }
538
600
  },
539
- onReady: ({ totalCount, hasMore, oldestTs }) => {
601
+ onReady: ({ totalCount, hasMore, oldestTs, oldestSeq }) => {
540
602
  // Pass 1 完成、Pass 2 开始前:发送 load_start
541
603
  // 增量模式下不显示 loading 遮罩,非增量模式显示进度
542
604
  const loadStartData = { total: totalCount, incremental: !!useIncremental };
@@ -551,6 +613,14 @@ export async function serveEventStream(sink, params, deps) {
551
613
  loadStartData.hasMore = !!hasMore;
552
614
  loadStartData.oldestTs = oldestTs || '';
553
615
  }
616
+ // Initial shard cursor — refined to the DELIVERED window's oldest seq so
617
+ // the first "load earlier" read covers the active shard's own pre-window
618
+ // prefix before jumping to the frozen shards (no middle gap).
619
+ if (_coldShardCursor) {
620
+ const refined = { ..._coldShardCursor };
621
+ if (typeof oldestSeq === 'number' && oldestSeq > 0) refined.oldestSeq = oldestSeq;
622
+ loadStartData.shard = refined;
623
+ }
554
624
  sink.write(`event: load_start\ndata: ${JSON.stringify(loadStartData)}\n\n`);
555
625
  },
556
626
  });
@@ -589,6 +659,7 @@ export async function serveEventStream(sink, params, deps) {
589
659
  loadStartData.hasMore = !!meta.hasMore;
590
660
  loadStartData.oldestTs = meta.oldestTimestamp || '';
591
661
  }
662
+ if (_coldShardCursor) loadStartData.shard = _coldShardCursor;
592
663
  sink.write(`event: load_start\ndata: ${JSON.stringify(loadStartData)}\n\n`);
593
664
  sink.write(`event: v2_requests\ndata: ${rowsPayload}\n\n`);
594
665
  for (const payload of native.convPayloads) sink.write(`event: v3_conv\ndata: ${payload}\n\n`);
@@ -1,5 +1,5 @@
1
1
  // Local log management routes (moved verbatim from server.js handleRequest).
2
- import { existsSync, realpathSync, statSync, createReadStream, mkdtempSync, rmSync, readdirSync } from 'node:fs';
2
+ import { existsSync, realpathSync, statSync, createReadStream, mkdtempSync, rmSync, readdirSync, readFileSync } from 'node:fs';
3
3
  import { join, basename } from 'node:path';
4
4
  import { tmpdir } from 'node:os';
5
5
  import AdmZip from 'adm-zip';
@@ -12,6 +12,29 @@ import { dirSizeSync, sanitizePathComponent } from '../lib/v2/layout.js';
12
12
  import { extractV2Zip } from '../lib/log-zip.js';
13
13
  import { startConvert, stopConvert, convertStatus } from '../lib/v2/convert-manager.js';
14
14
  import { migrationStatus } from '../lib/v2/migrate-prompt.js';
15
+ import { readV2ShardEntries, isV2SessionDir } from '../lib/v2/adapter.js';
16
+ import { initialShardCursor } from '../lib/v2/shard-manager.js';
17
+ import { reportSwallowed } from '../lib/error-report.js';
18
+
19
+ /** Initial shard cursor for a v2 local-log source: lets the read-only view's
20
+ * "load earlier history" button appear on the first (non-shard) load of a
21
+ * sharded session. Same contract as the /events cold-load cursor — delegates
22
+ * to shard-manager's shared implementation (cut.json-aware). */
23
+ function _initialShardCursor(filePath) {
24
+ if (!isV2SessionDir(filePath)) return null;
25
+ return initialShardCursor(filePath);
26
+ }
27
+
28
+ /** Write one entry per load_chunk frame (SSE data fields may not contain raw
29
+ * newlines — the strip keeps pretty-printed JSON on one line). Shared by the
30
+ * shard/tail/full branches so the framing lives in exactly one place. */
31
+ function _writeEntryFrames(res, entries) {
32
+ for (const raw of entries) {
33
+ sseWrite(res, 'event: load_chunk\ndata: [');
34
+ sseWrite(res, raw.includes('\n') ? raw.replace(/\n/g, '') : raw);
35
+ sseWrite(res, ']\n\n');
36
+ }
37
+ }
15
38
 
16
39
  // Cap for the in-memory zip build (adm-zip toBuffer holds the whole archive in
17
40
  // heap) and the upload accumulation — the repo has an OOM history, so both the
@@ -211,8 +234,7 @@ async function downloadLog(req, res, parsedUrl) {
211
234
  }
212
235
  }
213
236
 
214
- async function localLog(req, res, parsedUrl) {
215
- const file = parsedUrl.searchParams.get('file');
237
+ async function localLog(req, res, parsedUrl) { const file = parsedUrl.searchParams.get('file');
216
238
  if (!file || file.includes('..')) {
217
239
  res.writeHead(400, { 'Content-Type': 'application/json' });
218
240
  res.end(JSON.stringify({ error: 'Invalid file name' }));
@@ -233,6 +255,7 @@ async function localLog(req, res, parsedUrl) {
233
255
  // v2 寻址时 validateLogPath 返回 session 目录绝对路径,log-stream 据此分派适配器
234
256
  const filePath = validateLogPath(LOG_DIR, file);
235
257
  const limitVal = Math.min(parseInt(parsedUrl.searchParams.get('limit'), 10) || 0, 500);
258
+ const shardBefore = parseInt(parsedUrl.searchParams.get('shardBefore'), 10) || 0;
236
259
 
237
260
  // Negotiated Content-Encoding (br|identity) — every subsequent byte MUST
238
261
  // go through sseWrite/wireEnd (see server/lib/wire-compress.js).
@@ -242,24 +265,32 @@ async function localLog(req, res, parsedUrl) {
242
265
  'Connection': 'keep-alive',
243
266
  });
244
267
 
245
- if (limitVal > 0) {
268
+ if (isV2Ref && shardBefore > 0) {
269
+ // Sharding (2026-11): serve the frozen `.part<N>` shard older than this
270
+ // seq — same load_start/load_chunk/load_end frame shape as the full
271
+ // branch, plus a `shard` block the client uses for its "load earlier"
272
+ // cursor.
273
+ const shardRes = await readV2ShardEntries(filePath, { beforeSeq: shardBefore, limit: limitVal || 0, cached: true });
274
+ sseWrite(res, `event: load_start\ndata: ${JSON.stringify({
275
+ total: shardRes.totalCount,
276
+ incremental: false,
277
+ hasMore: shardRes.hasMore,
278
+ oldestTs: shardRes.oldestTimestamp || '',
279
+ shard: { partIndex: shardRes.partIndex, oldestSeq: shardRes.oldestSeq, hasMore: shardRes.hasMore, prepend: true },
280
+ })}\n\n`);
281
+ _writeEntryFrames(res, shardRes.entries);
282
+ } else if (limitVal > 0) {
246
283
  // 尾部加载模式:跳过 countLogEntries,只读文件末尾
247
284
  const { entries, hasMore, oldestTimestamp, estimatedTotal } = await readTailEntries(filePath, { limit: limitVal });
248
- sseWrite(res, `event: load_start\ndata: ${JSON.stringify({ total: estimatedTotal, incremental: false, hasMore, oldestTs: oldestTimestamp })}\n\n`);
249
- for (const raw of entries) {
250
- sseWrite(res, 'event: load_chunk\ndata: [');
251
- sseWrite(res, raw.includes('\n') ? raw.replace(/\n/g, '') : raw);
252
- sseWrite(res, ']\n\n');
253
- }
285
+ const shard = _initialShardCursor(filePath);
286
+ sseWrite(res, `event: load_start\ndata: ${JSON.stringify({ total: estimatedTotal, incremental: false, hasMore, oldestTs: oldestTimestamp, ...(shard && { shard }) })}\n\n`);
287
+ _writeEntryFrames(res, entries);
254
288
  } else {
255
289
  // 全量加载模式(向后兼容)
256
290
  const total = await countLogEntries(filePath);
257
- sseWrite(res, `event: load_start\ndata: ${JSON.stringify({ total, incremental: false })}\n\n`);
258
- await streamRawEntriesAsync(filePath, (raw) => {
259
- sseWrite(res, 'event: load_chunk\ndata: [');
260
- sseWrite(res, raw.includes('\n') ? raw.replace(/\n/g, '') : raw);
261
- sseWrite(res, ']\n\n');
262
- });
291
+ const shard = _initialShardCursor(filePath);
292
+ sseWrite(res, `event: load_start\ndata: ${JSON.stringify({ total, incremental: false, ...(shard && { shard }) })}\n\n`);
293
+ await streamRawEntriesAsync(filePath, (raw) => { _writeEntryFrames(res, [raw]); });
263
294
  }
264
295
  sseWrite(res, `event: load_end\ndata: {}\n\n`);
265
296
  wireEnd(res);
@@ -1,7 +1,7 @@
1
1
  // Miscellaneous small routes (moved verbatim from server.js handleRequest).
2
2
  import { getUserProfile } from '../lib/user-profile.js';
3
3
  import { runWaterfallHook } from '../lib/plugin-loader.js';
4
- import { normalizeBasePath } from '../lib/base-path.js';
4
+ import { resolveBaseConfig, externalUrlFromConfig } from '../lib/base-url.js';
5
5
  import { isAdminReq } from '../lib/is-admin.js';
6
6
  import { isSameOriginBrowserRequest } from '../lib/same-origin.js';
7
7
 
@@ -22,10 +22,20 @@ async function localUrl(req, res, parsedUrl, isLocal, deps) {
22
22
  return;
23
23
  }
24
24
  const localIp = deps.getLocalIp();
25
- // 反代子路径部署时分享/二维码 URL 也要带前缀,否则扫码绕过代理直连源站端口(与
26
- // server.startedNetwork 启动打印保持一致)。未设 CCV_BASE_PATH 时为空串,行为不变。
27
- const basePath = normalizeBasePath(process.env.CCV_BASE_PATH);
28
- const defaultUrl = `${deps.protocol}://${localIp}:${deps.actualPort}${basePath}?token=${deps.ACCESS_TOKEN}`;
25
+ const cfg = resolveBaseConfig();
26
+ let defaultUrl;
27
+ const externalUrl = externalUrlFromConfig(cfg, { token: deps.ACCESS_TOKEN, req });
28
+ if (externalUrl) {
29
+ // CCV_BASE_URL with a host: the QR/share link MUST be the public URL — otherwise the
30
+ // scan bypasses the proxy and hits the container's internal IP (a phone can never
31
+ // reach it). Scheme: explicit > this request's X-Forwarded-Proto > https.
32
+ defaultUrl = externalUrl;
33
+ } else {
34
+ // Behind a reverse-proxy sub-path the share/QR URL must carry the prefix too —
35
+ // otherwise the scan bypasses the proxy and hits the origin port (consistent with
36
+ // the server.startedNetwork startup print). Empty prefix → empty string, unchanged.
37
+ defaultUrl = `${deps.protocol}://${localIp}:${deps.actualPort}${cfg.basePath}?token=${deps.ACCESS_TOKEN}`;
38
+ }
29
39
  const hookResult = await runWaterfallHook('localUrl', { url: defaultUrl, ip: localIp, port: deps.actualPort, token: deps.ACCESS_TOKEN });
30
40
  res.writeHead(200, { 'Content-Type': 'application/json' });
31
41
  res.end(JSON.stringify({ url: hookResult.url }));
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,
@@ -1728,10 +1777,13 @@ function installUpgradeRouter(httpServer) {
1728
1777
  if (!httpServer._ccvUpgradeRoutes) httpServer._ccvUpgradeRoutes = [];
1729
1778
  httpServer.on('upgrade', (req, socket, head) => {
1730
1779
  try {
1780
+ // Upgrades bypass handleRequest, so basePath is stripped independently (same helper as
1781
+ // HTTP). Literal braces need no pre-handling: new URL already encodes them in the
1782
+ // pathname, and stripBasePath matches the wire form.
1783
+ const bp = resolveBaseConfig().basePath;
1731
1784
  const wsUrl = safeParseRequestUrl(req);
1732
1785
  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));
1786
+ const pathname = stripBasePath(wsUrl.pathname, bp);
1735
1787
  // Same auth as HTTP (WS upgrades previously ignored tokens entirely - a remote-terminal hole).
1736
1788
  // Compute isLocal explicitly here (same three-way check as handleRequest); WS is never an HTML request.
1737
1789
  const wsRemoteIp = req.socket.remoteAddress;