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.
- package/README.md +2 -1
- package/cli.js +50 -14
- package/dist/assets/{App-C4f2Dpy9.js → App-DEA3HoZr.js} +2 -2
- package/dist/assets/{MdxEditorPanel-D7aQDQJp.js → MdxEditorPanel-CTAS2DJv.js} +1 -1
- package/dist/assets/{Mobile-D9ekLQFS.js → Mobile-CgVpXvs2.js} +1 -1
- package/dist/assets/{ProxyStatsModal-CWpgyVKI.js → ProxyStatsModal-C4sl-cuB.js} +1 -1
- package/dist/assets/index-CS47d9oh.js +2 -0
- package/dist/assets/seqResourceLoaders-CORH46PN.js +2 -0
- package/dist/assets/seqResourceLoaders-v4YzKhTS.css +41 -0
- package/dist/index.html +1 -1
- package/findcc.js +4 -4
- package/node_modules/@ccv/core/src/contentFilter.js +4 -1
- package/node_modules/@ccv/core/src/ultraplanTemplates.js +199 -0
- package/package.json +1 -1
- package/server/i18n.js +97 -14
- package/server/interceptor.js +6 -0
- package/server/lib/async-write-queue.js +18 -0
- package/server/lib/auth.js +11 -3
- package/server/lib/base-path.js +89 -18
- package/server/lib/base-url.js +209 -0
- package/server/lib/ensure-hooks.js +134 -2
- package/server/lib/im/im-bridge-core.js +16 -0
- package/server/lib/log-management.js +21 -1
- package/server/lib/plugin-runtime.js +24 -5
- package/server/lib/scheduled-task-executor.js +14 -2
- package/server/lib/scheduled-task-store.js +129 -18
- package/server/lib/sdk-manager.js +113 -11
- package/server/lib/v2/adapter.js +147 -15
- package/server/lib/v2/conversation-store.js +9 -0
- package/server/lib/v2/journal.js +35 -0
- package/server/lib/v2/layout.js +67 -1
- package/server/lib/v2/live-feed.js +15 -0
- package/server/lib/v2/replay.js +11 -3
- package/server/lib/v2/session-select.js +34 -2
- package/server/lib/v2/shard-manager.js +249 -0
- package/server/lib/v2/v2-writer.js +252 -6
- package/server/pty-manager.js +103 -4
- package/server/routes/events.js +75 -4
- package/server/routes/logs.js +47 -16
- package/server/routes/misc.js +15 -5
- package/server/routes/scheduled-tasks.js +13 -0
- package/server/server.js +123 -23
- package/dist/assets/index-CocpEURl.js +0 -2
- package/dist/assets/seqResourceLoaders-BhiCEaUt.js +0 -2
- package/dist/assets/seqResourceLoaders-DbccWwKz.css +0 -41
package/server/pty-manager.js
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
import { resolveNativePath, LOG_DIR } from '../findcc.js';
|
|
2
2
|
import { normalizeSessionCwd } from './lib/v2/layout.js';
|
|
3
3
|
import { fileURLToPath } from 'node:url';
|
|
4
|
-
import { join, dirname, sep } from 'node:path';
|
|
5
|
-
import { chmodSync, statSync } from 'node:fs';
|
|
4
|
+
import { join, dirname, sep, resolve } from 'node:path';
|
|
5
|
+
import { chmodSync, statSync, existsSync } from 'node:fs';
|
|
6
6
|
import { platform, arch, homedir } from 'node:os';
|
|
7
7
|
import { createRequire } from 'node:module';
|
|
8
8
|
import { prepareEmbeddedShellSpawn, stripClaudeNoFlickerUnlessOptedIn, applyClaudeAltScreenPref } from './lib/terminal-env.js';
|
|
9
9
|
import { killPtyTree } from './lib/term-signals.js';
|
|
10
10
|
import { findSafeSliceStart, splitTrailingIncomplete } from './lib/ansi-safe-slice.js';
|
|
11
|
+
import { imDir } from './lib/im/im-lock.js';
|
|
11
12
|
import { resolveSpawnModel } from './lib/spawn-model-resolver.js';
|
|
12
13
|
import { mergeSettingsIntoArgs } from './lib/settings-merge.js';
|
|
13
14
|
import { projectKeyForCwd } from './lib/system-prompt-snapshots.js';
|
|
@@ -18,6 +19,7 @@ import { randomBytes } from 'node:crypto';
|
|
|
18
19
|
import { withDefaultThinkingDisplay, resolveLaunchSystemPrompt, insertBeforeDashDash } from './lib/launch-config.js';
|
|
19
20
|
export { withDefaultThinkingDisplay } from './lib/launch-config.js';
|
|
20
21
|
import { reportSwallowed } from './lib/error-report.js';
|
|
22
|
+
import { ensureOnboardingAndTrust } from './lib/ensure-hooks.js';
|
|
21
23
|
import { t, tFor } from './i18n.js';
|
|
22
24
|
|
|
23
25
|
const __filename = fileURLToPath(import.meta.url);
|
|
@@ -389,6 +391,21 @@ async function _spawnClaudeImpl(key, proxyPort, cwd, extraArgs = [], claudePath
|
|
|
389
391
|
env.CCV_PROXY_MODE = '1'; // tell interceptor.js not to start a server again
|
|
390
392
|
env.CCV_LOG_DIR = LOG_DIR; // let the forked Claude Code process find the same
|
|
391
393
|
// profile.json etc. resources
|
|
394
|
+
// IM worker CodeFuse config-dir fallback is handled in cli.js runImMode
|
|
395
|
+
// (before runCliMode), so that ensureHooks() writes to the same directory
|
|
396
|
+
// the child will read. Here we only need to inherit the already-resolved
|
|
397
|
+
// CLAUDE_CONFIG_DIR from process.env (which the env copy above already does).
|
|
398
|
+
// Pre-seed onboarding + trust state so Claude never blocks on interactive
|
|
399
|
+
// confirmation dialogs ("Yes, I accept" / "Yes, I trust this folder") in
|
|
400
|
+
// headless environments. Only applies to the IM worker's OWN working directory
|
|
401
|
+
// (imDir) — a user-launched workspace inside an IM worker must NOT silently
|
|
402
|
+
// accept trust on behalf of the user (security boundary).
|
|
403
|
+
if (process.env.CCV_IM_PLATFORM && cwd) {
|
|
404
|
+
const imWorkspace = imDir(process.env.CCV_IM_PLATFORM);
|
|
405
|
+
if (resolve(cwd) === resolve(imWorkspace)) {
|
|
406
|
+
ensureOnboardingAndTrust({ configDir: env.CLAUDE_CONFIG_DIR, workspacePath: cwd });
|
|
407
|
+
}
|
|
408
|
+
}
|
|
392
409
|
// Self-report project (2026-10, multi-PTY): every main-PTY claude ALSO tags its
|
|
393
410
|
// requests with `x-ccv-project-dir` = its own cwd, so the writer routes its
|
|
394
411
|
// writes to ITS project — not the (possibly re-bound) server project. This is
|
|
@@ -599,8 +616,8 @@ async function _spawnClaudeImpl(key, proxyPort, cwd, extraArgs = [], claudePath
|
|
|
599
616
|
let command = claudePath;
|
|
600
617
|
let args = ['--settings', settingsJson, ...launchArgs];
|
|
601
618
|
|
|
602
|
-
// If it is the npm version (cli.js), it must run under node
|
|
603
|
-
if (isNpmVersion && claudePath.endsWith('.js')) {
|
|
619
|
+
// If it is the npm version (cli.js / cli.cjs), it must run under node
|
|
620
|
+
if (isNpmVersion && (claudePath.endsWith('.js') || claudePath.endsWith('.cjs'))) {
|
|
604
621
|
command = nodePath;
|
|
605
622
|
args = [claudePath, '--settings', settingsJson, ...launchArgs];
|
|
606
623
|
}
|
|
@@ -616,9 +633,13 @@ async function _spawnClaudeImpl(key, proxyPort, cwd, extraArgs = [], claudePath
|
|
|
616
633
|
// A (re)spawn starts a fresh conversation — drop any sessionId a prior life
|
|
617
634
|
// on this record resolved to, so a stale sid never misroutes a send.
|
|
618
635
|
if (s.sessionId) { sidToKey.delete(s.sessionId); s.sessionId = null; }
|
|
636
|
+
// Clear any latched boot-blocked state from a previous life on this record —
|
|
637
|
+
// the respawn may succeed where the prior attempt was blocked.
|
|
638
|
+
s._bootBlockedState = null;
|
|
619
639
|
// Boot-window anchor for the injection fallback tiers below (same clock as the
|
|
620
640
|
// comparison — _now(), never Date.now(), so tests can steer both ends together).
|
|
621
641
|
const spawnedAt = _now();
|
|
642
|
+
s._spawnedAt = spawnedAt; // also stored on the record for getPtyBootState()
|
|
622
643
|
|
|
623
644
|
s.ptyProcess = pty.spawn(command, args, {
|
|
624
645
|
name: 'xterm-256color',
|
|
@@ -1531,6 +1552,84 @@ export function getOutputBuffer() {
|
|
|
1531
1552
|
return s ? s.outputBuffer : '';
|
|
1532
1553
|
}
|
|
1533
1554
|
|
|
1555
|
+
// ─── PTY boot-state detection ───
|
|
1556
|
+
// Patterns that indicate the Claude PTY is blocked on an interactive dialog
|
|
1557
|
+
// instead of being ready to accept prompts. Used by the IM bridge to fail fast
|
|
1558
|
+
// with a clear error instead of letting the message sit until the 120s timeout.
|
|
1559
|
+
//
|
|
1560
|
+
// IMPORTANT: Ink renders dialog options as separately positioned words using
|
|
1561
|
+
// cursor-forward ANSI sequences (ESC[<n>G) instead of literal spaces. The raw
|
|
1562
|
+
// output looks like: "Yes,\x1b[12GI\x1b[14Gtrust\x1b[20Gthis\x1b[25Gfolder".
|
|
1563
|
+
// We normalize the buffer by stripping ANSI sequences before matching.
|
|
1564
|
+
//
|
|
1565
|
+
// To avoid false positives from normal conversation (e.g. a user asking about
|
|
1566
|
+
// "trust" or "onboarding"), detection is only active during a boot window
|
|
1567
|
+
// (first N ms after spawn) and only scans the last portion of the buffer.
|
|
1568
|
+
// Once a dialog is detected during the window, the state is LATCHED — it
|
|
1569
|
+
// persists until the PTY exits, so a user messaging minutes after boot still
|
|
1570
|
+
// gets the fail-fast error instead of the 120s timeout.
|
|
1571
|
+
const _BOOT_WINDOW_MS = 30_000; // 30s after spawn — enough for slow container starts
|
|
1572
|
+
const _BOOT_SCAN_TAIL = 4096; // only scan the last 4KB (current screenful)
|
|
1573
|
+
|
|
1574
|
+
// Strip ANSI escape sequences (cursor movement, colors, etc.) so that Ink's
|
|
1575
|
+
// positioned rendering ("Yes,\x1b[12GI\x1b[14Gtrust...") becomes plain text
|
|
1576
|
+
// ("Yes, I trust this folder").
|
|
1577
|
+
function _stripAnsi(str) {
|
|
1578
|
+
// eslint-disable-next-line no-control-regex
|
|
1579
|
+
return str.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, ' ');
|
|
1580
|
+
}
|
|
1581
|
+
|
|
1582
|
+
const _BOOT_PATTERNS = {
|
|
1583
|
+
'blocked-on-trust': [
|
|
1584
|
+
/yes,?\s+i\s+trust\s+this\s+folder/i,
|
|
1585
|
+
/do\s+you\s+trust\s+this\s+folder/i,
|
|
1586
|
+
],
|
|
1587
|
+
'blocked-on-onboarding': [
|
|
1588
|
+
/yes,?\s+i\s+accept/i,
|
|
1589
|
+
],
|
|
1590
|
+
};
|
|
1591
|
+
|
|
1592
|
+
/**
|
|
1593
|
+
* Detect whether the active PTY is ready, still booting, blocked on an
|
|
1594
|
+
* interactive dialog, or has exited. Returns one of:
|
|
1595
|
+
* 'ready' — PTY is running and no blocking dialog detected
|
|
1596
|
+
* 'booting' — PTY is running but within the boot window
|
|
1597
|
+
* 'blocked-on-trust' — "Yes, I trust this folder" dialog detected (latched)
|
|
1598
|
+
* 'blocked-on-onboarding' — onboarding/first-run dialog detected (latched)
|
|
1599
|
+
* 'exited' — PTY process has exited
|
|
1600
|
+
* 'no-pty' — no PTY record exists
|
|
1601
|
+
*
|
|
1602
|
+
* Latching: once a dialog is detected during the boot window, the state is
|
|
1603
|
+
* stored on the record and returned for the PTY's lifetime. This prevents
|
|
1604
|
+
* the 30s window from expiring while the dialog is still on screen.
|
|
1605
|
+
*/
|
|
1606
|
+
export function getPtyBootState() {
|
|
1607
|
+
const s = _active();
|
|
1608
|
+
if (!s) return 'no-pty';
|
|
1609
|
+
if (!s.ptyProcess) return 'exited';
|
|
1610
|
+
// Return latched state if a dialog was previously detected.
|
|
1611
|
+
if (s._bootBlockedState) return s._bootBlockedState;
|
|
1612
|
+
// Only detect blocking dialogs during the boot window. After that, any
|
|
1613
|
+
// match would be a false positive from normal conversation content.
|
|
1614
|
+
const elapsed = _now() - (s._spawnedAt || 0);
|
|
1615
|
+
if (elapsed > _BOOT_WINDOW_MS) return 'ready';
|
|
1616
|
+
const buf = s.outputBuffer || '';
|
|
1617
|
+
if (buf.length < 50) return 'booting';
|
|
1618
|
+
// Only scan the tail of the buffer — the current screen content. Older
|
|
1619
|
+
// output may contain legitimate uses of trigger words from conversation.
|
|
1620
|
+
const tail = _stripAnsi(buf.slice(-_BOOT_SCAN_TAIL));
|
|
1621
|
+
for (const [state, patterns] of Object.entries(_BOOT_PATTERNS)) {
|
|
1622
|
+
for (const re of patterns) {
|
|
1623
|
+
if (re.test(tail)) {
|
|
1624
|
+
// Latch the state so it persists beyond the boot window.
|
|
1625
|
+
s._bootBlockedState = state;
|
|
1626
|
+
return state;
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
}
|
|
1630
|
+
return 'ready';
|
|
1631
|
+
}
|
|
1632
|
+
|
|
1534
1633
|
/**
|
|
1535
1634
|
* Launch-or-reattach for a workspace cwd (2026-10-06, multi-instance). Now that spawnClaude
|
|
1536
1635
|
* mints a fresh instanceKey per call and no longer kills an existing same-cwd record, an
|
package/server/routes/events.js
CHANGED
|
@@ -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
|
-
|
|
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`);
|
package/server/routes/logs.js
CHANGED
|
@@ -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 (
|
|
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
|
-
|
|
249
|
-
|
|
250
|
-
|
|
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
|
-
|
|
258
|
-
|
|
259
|
-
|
|
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);
|
package/server/routes/misc.js
CHANGED
|
@@ -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 {
|
|
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
|
-
|
|
26
|
-
|
|
27
|
-
const
|
|
28
|
-
|
|
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 }));
|
|
@@ -165,10 +165,19 @@ function _publicTask(t) {
|
|
|
165
165
|
// List payload keeps the full prompt OUT (it may carry secrets and every logged-in
|
|
166
166
|
// viewer can read the list — security P2-3). Full prompts only ship when the project
|
|
167
167
|
// resolves (bound / registry / live instance — see listHandler's fullPrompt gate).
|
|
168
|
+
// Attachments (absolute paths, usernames) and template snapshots get the same treatment.
|
|
168
169
|
function _listTask(t) {
|
|
169
170
|
const p = _publicTask(t);
|
|
170
171
|
p.promptSummary = String(t.prompt || '').replace(/\s+/g, ' ').trim().slice(0, 200);
|
|
172
|
+
// Attachments-only tasks have no prompt text — fall back to file names so the list
|
|
173
|
+
// row and toasts never render blank.
|
|
174
|
+
if (!p.promptSummary && Array.isArray(t.attachments) && t.attachments.length) {
|
|
175
|
+
p.promptSummary = `[${t.attachments.map(a => a.name).filter(Boolean).join(', ')}]`.slice(0, 200);
|
|
176
|
+
}
|
|
171
177
|
delete p.prompt;
|
|
178
|
+
delete p.attachments;
|
|
179
|
+
delete p.template;
|
|
180
|
+
delete p.templateContent;
|
|
172
181
|
return p;
|
|
173
182
|
}
|
|
174
183
|
|
|
@@ -190,6 +199,8 @@ function createHandler(req, res, parsedUrl, isLocal, deps) {
|
|
|
190
199
|
out = await createTask(LOG_DIR, {
|
|
191
200
|
project, cwd: resolved.cwd, prompt: body.prompt, mode: body.mode,
|
|
192
201
|
schedule: body.schedule, enabled: body.enabled,
|
|
202
|
+
template: body.template, templateContent: body.templateContent,
|
|
203
|
+
attachments: body.attachments,
|
|
193
204
|
}, Date.now());
|
|
194
205
|
} catch (err) {
|
|
195
206
|
reportSwallowed('scheduled-tasks.create', err);
|
|
@@ -210,6 +221,8 @@ function updateHandler(req, res, parsedUrl, isLocal, deps) {
|
|
|
210
221
|
try {
|
|
211
222
|
out = await updateTask(LOG_DIR, id, {
|
|
212
223
|
prompt: body.prompt, mode: body.mode, schedule: body.schedule, enabled: body.enabled,
|
|
224
|
+
template: body.template, templateContent: body.templateContent,
|
|
225
|
+
attachments: body.attachments,
|
|
213
226
|
}, Date.now());
|
|
214
227
|
} catch (err) {
|
|
215
228
|
reportSwallowed('scheduled-tasks.update', err);
|