cc-viewer 1.9.20 → 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.
Files changed (33) hide show
  1. package/README.md +1 -0
  2. package/cli.js +25 -13
  3. package/dist/assets/{App-Cf04lonP.js → App-BN3viVRq.js} +2 -2
  4. package/dist/assets/{MdxEditorPanel-DKU2r-KQ.js → MdxEditorPanel-CmHF9Mz1.js} +1 -1
  5. package/dist/assets/{Mobile-DK6O4hoa.js → Mobile-nbI6IeX_.js} +1 -1
  6. package/dist/assets/{ProxyStatsModal-B2njUNcC.js → ProxyStatsModal-Ogrx3mxS.js} +1 -1
  7. package/dist/assets/{index-C8223pn2.js → index-DoFyHmPM.js} +2 -2
  8. package/dist/assets/seqResourceLoaders-n9iXZRHx.js +2 -0
  9. package/dist/index.html +1 -1
  10. package/package.json +1 -1
  11. package/server/i18n.js +93 -14
  12. package/server/interceptor.js +6 -0
  13. package/server/lib/async-write-queue.js +18 -0
  14. package/server/lib/auth.js +11 -3
  15. package/server/lib/base-path.js +89 -18
  16. package/server/lib/base-url.js +209 -0
  17. package/server/lib/log-management.js +21 -1
  18. package/server/lib/plugin-runtime.js +24 -5
  19. package/server/lib/v2/adapter.js +147 -15
  20. package/server/lib/v2/conversation-store.js +9 -0
  21. package/server/lib/v2/journal.js +35 -0
  22. package/server/lib/v2/layout.js +67 -1
  23. package/server/lib/v2/live-feed.js +15 -0
  24. package/server/lib/v2/replay.js +11 -3
  25. package/server/lib/v2/session-select.js +34 -2
  26. package/server/lib/v2/shard-manager.js +249 -0
  27. package/server/lib/v2/v2-writer.js +252 -6
  28. package/server/proxy.js +25 -11
  29. package/server/routes/events.js +75 -4
  30. package/server/routes/logs.js +47 -16
  31. package/server/routes/misc.js +15 -5
  32. package/server/server.js +85 -27
  33. package/dist/assets/seqResourceLoaders-0JGRMKPS.js +0 -2
package/server/proxy.js CHANGED
@@ -378,12 +378,17 @@ async function handleLlmApiRequest(req, res, fullUrl, fetchOptions, body, proxyD
378
378
  clientAbort.signal.addEventListener('abort', clearSlowTimer, { once: true });
379
379
  // The timer measures time-to-HEADERS (fetch resolves at headers). Keep it armed
380
380
  // until the first BODY chunk so a headers-fast-then-stalled stream still counts
381
- // as slow (review P2-3); the finally below stays as the cleanup backstop.
381
+ // as slow (review P1-2). markFirstByte is the real settle point: it disarms the
382
+ // timer AND emits resolved; the finally below is only an error-path backstop
383
+ // (executeRequest resolves at headers, so clearing there would defeat this).
382
384
  let slowFirstByteSeen = false;
383
385
  const markFirstByte = () => {
384
386
  if (slowFirstByteSeen) return;
385
387
  slowFirstByteSeen = true;
386
388
  clearSlowTimer();
389
+ if (slowFired) {
390
+ __testing.emit({ type: 'resolved', requestId: slowReqId, cwd: slowCwd, instanceKey: slowInstance });
391
+ }
387
392
  };
388
393
 
389
394
  // 执行带重试的请求
@@ -404,11 +409,15 @@ async function handleLlmApiRequest(req, res, fullUrl, fetchOptions, body, proxyD
404
409
  },
405
410
  });
406
411
  } finally {
407
- clearSlowTimer();
408
- // If the advisory fired, tell the UI the wait is over so the persistent
409
- // toast is dismissed instead of lingering past completion.
410
- if (slowFired) {
411
- __testing.emit({ type: 'resolved', requestId: slowReqId, cwd: slowCwd, instanceKey: slowInstance });
412
+ // Error-path backstop ONLY: executeRequest resolved at headers, so a success
413
+ // path must NOT clear here — the timer stays armed until the first body chunk
414
+ // (markFirstByte). Clear+resolve only when no usable response came back
415
+ // (network error / aborted / no response object) so the advisory never leaks.
416
+ if (slowFirstByteSeen || !result || !result.response) {
417
+ clearSlowTimer();
418
+ if (slowFired) {
419
+ __testing.emit({ type: 'resolved', requestId: slowReqId, cwd: slowCwd, instanceKey: slowInstance });
420
+ }
412
421
  }
413
422
  }
414
423
 
@@ -463,6 +472,7 @@ async function handleLlmApiRequest(req, res, fullUrl, fetchOptions, body, proxyD
463
472
 
464
473
  // 网络异常(finalStatus=0)或竞速全失败:返回 502 + Proxy Error,与原 catch 分支一致
465
474
  if (finalStatus === 0) {
475
+ markFirstByte(); // settle the advisory on a hard network failure
466
476
  res.writeHead(502, { 'x-forward-attempts': String(attempts) });
467
477
  res.end('Proxy Error');
468
478
  return;
@@ -474,11 +484,12 @@ async function handleLlmApiRequest(req, res, fullUrl, fetchOptions, body, proxyD
474
484
  if (response.body) {
475
485
  // @ts-ignore
476
486
  const nodeStream = Readable.fromWeb(response.body);
477
- nodeStream.on('error', () => {});
478
- // First body byte arrived → the upstream is no longer "slow"; stop the
479
- // advisory timer. Headers alone don't count (a headers-fast-then-stalled
480
- // SSE stream is exactly the silent case we want to surface).
487
+ // First body chunk → the wait is over. Also settle if the body errors or
488
+ // closes before any byte (client abort / stalled-then-closed stream), so the
489
+ // advisory never leaks past a terminal stream state.
490
+ nodeStream.on('error', markFirstByte);
481
491
  nodeStream.once('data', markFirstByte);
492
+ nodeStream.once('close', markFirstByte);
482
493
  const streamIdleMs = retryConfig && retryConfig.mode === 'off'
483
494
  ? (retryConfig.streamIdleTimeoutMs ?? 0)
484
495
  : 0;
@@ -530,10 +541,13 @@ async function handleLlmApiRequest(req, res, fullUrl, fetchOptions, body, proxyD
530
541
  });
531
542
  }
532
543
  } else if (response.text) {
533
- // 竞速失败兜底 response:用 text() 取 body
544
+ // 竞速失败兜底 response:用 text() 取 body —— a fully-read non-stream body
545
+ // means the wait is over.
534
546
  const text = await response.text();
547
+ markFirstByte();
535
548
  res.end(text);
536
549
  } else {
550
+ markFirstByte(); // no body at all — settle the advisory
537
551
  res.end();
538
552
  }
539
553
  }
@@ -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';
@@ -524,15 +525,21 @@ setSlowUpstreamListener(({ type, requestId, cwd, instanceKey, waitingMs, model }
524
525
  const sess = instanceKey
525
526
  ? (sessions.find(s => s.instanceKey === instanceKey) || null)
526
527
  : (sessions.find(s => cwd && s.cwd === cwd) || null);
527
- if (!sess) return;
528
528
  if (type === 'resolved') {
529
- // The waited-on request settled — tell the UI to dismiss the toast.
529
+ // The waited-on request settled — tell the UI to dismiss the toast. A
530
+ // request can settle AFTER its session closed (review P2-2): the session
531
+ // lookup then misses and the dismiss would be silently dropped, leaving a
532
+ // stuck toast. Fall back to the request's own self-reported cwd/instanceKey
533
+ // so the dismiss always reaches the workspace that was told to wait.
534
+ const rcwd = sess ? sess.cwd : cwd;
535
+ const rinst = sess ? (sess.instanceKey || null) : (instanceKey || null);
530
536
  broadcastWsMessage({
531
- type: 'sdk-slow-upstream-resolved', cwd: sess.cwd, project: projectKeyForCwd(sess.cwd),
532
- instanceKey: sess.instanceKey || null, requestId: requestId || null, ts: Date.now(),
537
+ type: 'sdk-slow-upstream-resolved', cwd: rcwd, project: projectKeyForCwd(rcwd),
538
+ instanceKey: rinst, requestId: requestId || null, ts: Date.now(),
533
539
  });
534
540
  return;
535
541
  }
542
+ if (!sess) return;
536
543
  broadcastWsMessage({
537
544
  type: 'sdk-slow-upstream', cwd: sess.cwd, project: projectKeyForCwd(sess.cwd),
538
545
  instanceKey: sess.instanceKey || null, requestId: requestId || null, waitingMs, model: model || null, ts: Date.now(),
@@ -603,6 +610,17 @@ function startLogWatch() {
603
610
  const feed = _feedForSessionDir(dir);
604
611
  if (feed) feed.tick(dir);
605
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
+ });
606
624
  // Feed each resolved (sid, project) into the PTY sid index so chat sends can
607
625
  // be routed to the PTY owning that conversation (anchor routing, 2026-10-05).
608
626
  // Lazy import keeps pty-manager out of the early module graph (and off the
@@ -954,6 +972,13 @@ function checkHostAllowed(hostHeaderValue) {
954
972
  const allowedHosts = process.env.CCV_ALLOWED_HOSTS
955
973
  ? process.env.CCV_ALLOWED_HOSTS.split(',').map(s => s.trim()).filter(Boolean)
956
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);
957
982
  if (allowedHosts.includes('*')) return null;
958
983
  const hostHeader = (hostHeaderValue || '').toLowerCase();
959
984
  // Port stripping: RFC 3986 requires bracketed IPv6 `[::1]:port`; bare `::1` would lose its last `\d` to port stripping.
@@ -969,6 +994,18 @@ function checkHostAllowed(hostHeaderValue) {
969
994
  }
970
995
 
971
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;
972
1009
  const parsedUrl = safeParseRequestUrl(req);
973
1010
  if (!parsedUrl) {
974
1011
  res.writeHead(400, { 'Content-Type': 'application/json' });
@@ -976,13 +1013,6 @@ async function handleRequest(req, res) {
976
1013
  return;
977
1014
  }
978
1015
  let url = parsedUrl.pathname;
979
-
980
- // CCV_BASE_PATH reverse proxy: strip prefix at TOP so API/WS/static/SPA
981
- // all work with original unprefixed paths. 剥离后必须写回 parsedUrl.pathname ——
982
- // dispatch()(routes/_dispatch.js)与多个 handler(files-content/ask-perm/im)直读
983
- // parsedUrl.pathname 做路由匹配和偏移 slice,不写回则前缀下全部 /api/* 与 SSE /events
984
- // 命不中、落 SPA fallback(PR #108 遗留 P0)。searchParams 不受 pathname 赋值影响。
985
- const bp = normalizeBasePath(process.env.CCV_BASE_PATH);
986
1016
  url = stripBasePath(url, bp);
987
1017
  parsedUrl.pathname = url;
988
1018
  const method = req.method;
@@ -1041,7 +1071,7 @@ async function handleRequest(req, res) {
1041
1071
  if (authDecision.action === 'login-page') {
1042
1072
  const lang = localeFromAcceptLanguage(req.headers['accept-language']) || getLang();
1043
1073
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' });
1044
- res.end(renderLoginPage({ lang }));
1074
+ res.end(renderLoginPage({ lang, basePath: bp }));
1045
1075
  return;
1046
1076
  }
1047
1077
  if (authDecision.action === 'unauthorized') {
@@ -1139,7 +1169,7 @@ async function handleRequest(req, res) {
1139
1169
  // base=''(相对路径产物),让浏览器把所有相对 URL(含任意深度 SPA-fallback 文档里的
1140
1170
  // ./assets)解析到正确根/前缀下,避免深链直访(如 /a/b)时相对当前路径解析 → 白屏。
1141
1171
  // window.__CCV_BASE_PATH__ 仅子路径时注入:运行时 API/WS 的 base 语义保持"未设=无前缀"不变。
1142
- const injectBase = normalizeBasePath(process.env.CCV_BASE_PATH);
1172
+ const injectBase = bp;
1143
1173
  const baseHref = injectBase || '/';
1144
1174
  const escapedBase = baseHref.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
1145
1175
  let injectHtml = `<base href="${escapedBase}">`;
@@ -1494,26 +1524,40 @@ async function _doStart() {
1494
1524
  if (_prefs.lang) setLang(_prefs.lang);
1495
1525
  }
1496
1526
  } catch { /* 读 prefs 失败就保持默认语言 */ }
1497
- // CCV_BASE_PATH 配置校验:缺前导 '/' 时剥离静默失效(startsWith 永不命中),
1498
- // 启动期告警一次。放在 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();
1499
1533
  {
1500
- const _bpCheck = validateBasePath(process.env.CCV_BASE_PATH);
1501
- 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 }));
1502
1539
  }
1503
1540
  // interceptor.js runs in this same process (via proxy.js → setupInterceptor).
1504
1541
  // Inject live-port via module-level setter instead of process.env to avoid
1505
1542
  // polluting env of child_process.spawn descendants (Bash tools / MCP / Electron tabs).
1506
1543
  setLivePort(port, serverProtocol);
1507
1544
  // 自动打开/serverStarted hook 用的 URL 也要带反代前缀(与启动打印一致)
1508
- 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;
1509
1553
  if (!isCliMode) {
1510
1554
  console.error(t('server.started'));
1511
- const _bp = normalizeBasePath(process.env.CCV_BASE_PATH);
1512
- console.error(t('server.startedLocal', { protocol: serverProtocol, port, basePath: _bp }));
1555
+ console.error(t('server.startedLocal', { protocol: serverProtocol, port, basePath: _baseCfg.basePath }));
1513
1556
  const _ips = getAllLocalIps();
1514
1557
  for (const _ip of _ips) {
1515
- 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 }));
1516
1559
  }
1560
+ if (externalUrl) console.error(t('server.startedExternal', { url: externalUrl }));
1517
1561
  if (authConfig.enabled) {
1518
1562
  if (authConfig.password === '') console.error(t('server.passwordEmptyWarn'));
1519
1563
  else console.error(t('server.passwordActive', { password: authConfig.password }));
@@ -1526,8 +1570,19 @@ async function _doStart() {
1526
1570
  const ccVer = JSON.parse(readFileSync(ccPkgPath, 'utf-8')).version;
1527
1571
  const [maj, min, pat] = ccVer.split('.').map(Number);
1528
1572
  if ((maj < 2 || (maj === 2 && min === 0 && pat < 69)) && !isBrowserOpenSuppressed()) {
1529
- const cmd = platform() === 'darwin' ? 'open' : platform() === 'win32' ? 'start' : 'xdg-open';
1530
- 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();
1531
1586
  }
1532
1587
  } catch { }
1533
1588
  // 工作区模式下延迟到选择工作区后再启动监听
@@ -1557,7 +1612,7 @@ async function _doStart() {
1557
1612
  await pluginRuntime.onServerStarted({
1558
1613
  logDir: LOG_DIR,
1559
1614
  port, host: HOST,
1560
- basePath: normalizeBasePath(process.env.CCV_BASE_PATH),
1615
+ basePath: _baseCfg.basePath,
1561
1616
  protocol: serverProtocol,
1562
1617
  token: ACCESS_TOKEN,
1563
1618
  internalToken: INTERNAL_TOKEN,
@@ -1722,10 +1777,13 @@ function installUpgradeRouter(httpServer) {
1722
1777
  if (!httpServer._ccvUpgradeRoutes) httpServer._ccvUpgradeRoutes = [];
1723
1778
  httpServer.on('upgrade', (req, socket, head) => {
1724
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;
1725
1784
  const wsUrl = safeParseRequestUrl(req);
1726
1785
  if (!wsUrl) { socket.destroy(); return; }
1727
- // Upgrades bypass handleRequest, so basePath is stripped independently (same helper as HTTP)
1728
- const pathname = stripBasePath(wsUrl.pathname, normalizeBasePath(process.env.CCV_BASE_PATH));
1786
+ const pathname = stripBasePath(wsUrl.pathname, bp);
1729
1787
  // Same auth as HTTP (WS upgrades previously ignored tokens entirely - a remote-terminal hole).
1730
1788
  // Compute isLocal explicitly here (same three-way check as handleRequest); WS is never an HTML request.
1731
1789
  const wsRemoteIp = req.socket.remoteAddress;