cc-viewer 1.9.39 → 1.9.41

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 (78) hide show
  1. package/cli.js +21 -3
  2. package/dist/assets/AgentLoopModal-DAGLL1xj.css +1 -0
  3. package/dist/assets/AgentLoopModal-jmaSV1sC.js +1 -0
  4. package/dist/assets/App-BkyA7Kjt.js +2 -0
  5. package/dist/assets/{ArchivePreview-BHhhDCbz.js → ArchivePreview-xID8CpEa.js} +1 -1
  6. package/dist/assets/{AudioPreview-B0A6FVQc.js → AudioPreview-wKkv4Ff3.js} +1 -1
  7. package/dist/assets/{MdxEditorPanel-CEZPc4wd.js → MdxEditorPanel-COSqx6U3.js} +1 -1
  8. package/dist/assets/Mobile-CGYtYhak.js +1 -0
  9. package/dist/assets/{ProxyStatsModal-B2PEO1Bm.js → ProxyStatsModal-CkTorkzL.js} +1 -1
  10. package/dist/assets/{SubtitlePreview-Ca7FKVpv.js → SubtitlePreview-woHDzfI4.js} +1 -1
  11. package/dist/assets/{_baseUniq-xRiWMqOw.js → _baseUniq-FIciuICM.js} +1 -1
  12. package/dist/assets/{arc-edNwlWnI.js → arc-Cb7-d5Dh.js} +1 -1
  13. package/dist/assets/{architectureDiagram-Q4EWVU46-SMfdtr57.js → architectureDiagram-Q4EWVU46-D9keH5pH.js} +1 -1
  14. package/dist/assets/{blockDiagram-DXYQGD6D-BxAsQG58.js → blockDiagram-DXYQGD6D-BhvTUyc1.js} +1 -1
  15. package/dist/assets/{c4Diagram-AHTNJAMY-DvEHTYBD.js → c4Diagram-AHTNJAMY-D08NPlEN.js} +1 -1
  16. package/dist/assets/{channel-Ce5Cf3nY.js → channel-Dj8ENzwe.js} +1 -1
  17. package/dist/assets/{chunk-4BX2VUAB--OnGvs-9.js → chunk-4BX2VUAB-CWxl0ldd.js} +1 -1
  18. package/dist/assets/{chunk-4TB4RGXK-MSrYeKo5.js → chunk-4TB4RGXK-CDSOF4bX.js} +1 -1
  19. package/dist/assets/{chunk-55IACEB6-CD4rh-7b.js → chunk-55IACEB6-BnFbnzVr.js} +1 -1
  20. package/dist/assets/{chunk-EDXVE4YY-CrAxlPfF.js → chunk-EDXVE4YY-DRbZYEab.js} +1 -1
  21. package/dist/assets/{chunk-FMBD7UC4-CMb4qB5t.js → chunk-FMBD7UC4-DjZZbc1r.js} +1 -1
  22. package/dist/assets/{chunk-OYMX7WX6-CEP3GJND.js → chunk-OYMX7WX6-DcQ3sS0P.js} +1 -1
  23. package/dist/assets/{chunk-QZHKN3VN-Xko480I7.js → chunk-QZHKN3VN-Djz6f4jG.js} +1 -1
  24. package/dist/assets/{chunk-YZCP3GAM-xKPv2jAr.js → chunk-YZCP3GAM-DyJnuL9m.js} +1 -1
  25. package/dist/assets/{classDiagram-6PBFFD2Q-CAw9u3mr.js → classDiagram-6PBFFD2Q-DkwnbQIl.js} +1 -1
  26. package/dist/assets/{classDiagram-v2-HSJHXN6E-CAw9u3mr.js → classDiagram-v2-HSJHXN6E-DkwnbQIl.js} +1 -1
  27. package/dist/assets/clone-CdIGKMba.js +1 -0
  28. package/dist/assets/{cose-bilkent-S5V4N54A-Dd5Fpol9.js → cose-bilkent-S5V4N54A-DWeRG1gF.js} +1 -1
  29. package/dist/assets/{dagre-KV5264BT-BH00hKa4.js → dagre-KV5264BT-17yeVEWW.js} +1 -1
  30. package/dist/assets/{diagram-5BDNPKRD-BJZlGmRA.js → diagram-5BDNPKRD-CUB-PRyE.js} +1 -1
  31. package/dist/assets/{diagram-G4DWMVQ6-BTj-YG-C.js → diagram-G4DWMVQ6-B8Tqqick.js} +1 -1
  32. package/dist/assets/{diagram-MMDJMWI5-2ZD4VZMB.js → diagram-MMDJMWI5-DETfB0tT.js} +1 -1
  33. package/dist/assets/{diagram-TYMM5635-mTEHpW4W.js → diagram-TYMM5635-BQMrRqnL.js} +1 -1
  34. package/dist/assets/{erDiagram-SMLLAGMA-DTOSCCrk.js → erDiagram-SMLLAGMA-CP7zuxG_.js} +1 -1
  35. package/dist/assets/{flowDiagram-DWJPFMVM-C4ZAoiRL.js → flowDiagram-DWJPFMVM-DxzIXW26.js} +1 -1
  36. package/dist/assets/{ganttDiagram-T4ZO3ILL-C56IAugD.js → ganttDiagram-T4ZO3ILL-nsu-qxBO.js} +1 -1
  37. package/dist/assets/{gitGraphDiagram-UUTBAWPF-fvtnUb6S.js → gitGraphDiagram-UUTBAWPF-BlMdg6RO.js} +1 -1
  38. package/dist/assets/{graph-CnqqDZhs.js → graph-4W_s4IzB.js} +1 -1
  39. package/dist/assets/index-B-ODflMJ.js +2 -0
  40. package/dist/assets/{infoDiagram-42DDH7IO-B-b77lg9.js → infoDiagram-42DDH7IO-CqMDTGmP.js} +1 -1
  41. package/dist/assets/{ishikawaDiagram-UXIWVN3A-B1ituugL.js → ishikawaDiagram-UXIWVN3A-Dy1IGF_a.js} +1 -1
  42. package/dist/assets/{journeyDiagram-VCZTEJTY-DvFc_1_L.js → journeyDiagram-VCZTEJTY-BJ8PynK6.js} +1 -1
  43. package/dist/assets/{kanban-definition-6JOO6SKY-B-3zDwdJ.js → kanban-definition-6JOO6SKY-Ccbypvle.js} +1 -1
  44. package/dist/assets/{layout-B8tT3Nrd.js → layout-Bv-UoBwe.js} +1 -1
  45. package/dist/assets/{linear-BVxRmpuU.js → linear-D_8kfx63.js} +1 -1
  46. package/dist/assets/{mermaid.core-TpktUJt6.js → mermaid.core-D-K_u2mA.js} +3 -3
  47. package/dist/assets/{min-4AuCZ0ho.js → min-GpwgsFUK.js} +1 -1
  48. package/dist/assets/{mindmap-definition-QFDTVHPH-MQeup-Jb.js → mindmap-definition-QFDTVHPH-DIk351-n.js} +1 -1
  49. package/dist/assets/{pieDiagram-DEJITSTG-mSFlWRpV.js → pieDiagram-DEJITSTG-iZqhLfvH.js} +1 -1
  50. package/dist/assets/{quadrantDiagram-34T5L4WZ-BE2AHw1J.js → quadrantDiagram-34T5L4WZ-BRUNYhvW.js} +1 -1
  51. package/dist/assets/{requirementDiagram-MS252O5E-CSat0Shv.js → requirementDiagram-MS252O5E-BFZLZvbl.js} +1 -1
  52. package/dist/assets/{sankeyDiagram-XADWPNL6-jSfdI1J9.js → sankeyDiagram-XADWPNL6-kqYCYleU.js} +1 -1
  53. package/dist/assets/seqResourceLoaders-DobEEoQx.js +2 -0
  54. package/dist/assets/seqResourceLoaders-qHMtyjDg.css +41 -0
  55. package/dist/assets/{sequenceDiagram-FGHM5R23-n8z9Vixi.js → sequenceDiagram-FGHM5R23-DCLpZCg6.js} +1 -1
  56. package/dist/assets/{stateDiagram-FHFEXIEX-Dn_y_D8r.js → stateDiagram-FHFEXIEX-CZZ1TD_E.js} +1 -1
  57. package/dist/assets/{stateDiagram-v2-QKLJ7IA2-BB1b-66S.js → stateDiagram-v2-QKLJ7IA2-FzCg96zz.js} +1 -1
  58. package/dist/assets/{timeline-definition-GMOUNBTQ-Bvy0hn9D.js → timeline-definition-GMOUNBTQ-BqAwxYOG.js} +1 -1
  59. package/dist/assets/{vennDiagram-DHZGUBPP-BVqFkdla.js → vennDiagram-DHZGUBPP-BIL2Fh1B.js} +1 -1
  60. package/dist/assets/{wardley-RL74JXVD-BIAqGP0w.js → wardley-RL74JXVD-BNhgQs0l.js} +1 -1
  61. package/dist/assets/{wardleyDiagram-NUSXRM2D-DGUvrzIN.js → wardleyDiagram-NUSXRM2D-CJebAReJ.js} +1 -1
  62. package/dist/assets/{xychartDiagram-5P7HB3ND-BjEJgIoR.js → xychartDiagram-5P7HB3ND-O_QBYfmH.js} +1 -1
  63. package/dist/index.html +1 -1
  64. package/package.json +1 -1
  65. package/server/lib/im/im-config.js +16 -3
  66. package/server/lib/im/im-proxy-profile.js +99 -0
  67. package/server/lib/sdk-manager.js +2 -2
  68. package/server/lib/session-transcript-reader.js +127 -1
  69. package/server/routes/agent-loop-timings.js +47 -0
  70. package/server/routes/dingtalk.js +4 -0
  71. package/server/routes/im.js +4 -0
  72. package/server/server.js +7 -5
  73. package/dist/assets/App-CpjhCyrl.js +0 -2
  74. package/dist/assets/Mobile-B6az-Lrt.js +0 -1
  75. package/dist/assets/clone-CW1SPXDP.js +0 -1
  76. package/dist/assets/index-DMmTEKEL.js +0 -2
  77. package/dist/assets/seqResourceLoaders-BJEa97Uq.js +0 -2
  78. package/dist/assets/seqResourceLoaders-BdxjrasH.css +0 -41
@@ -0,0 +1,99 @@
1
+ // Per-platform proxy-profile pin for IM SDK workers.
2
+ //
3
+ // An IM worker binds its interceptor workspace from process.cwd() (= IM_<id>) the moment
4
+ // server/proxy.js → server/interceptor.js is imported, and reads <LOG_DIR>/IM_<id>/
5
+ // active-profile.json at module top. So the pin must be written BEFORE that import — cli.js
6
+ // calls applyImProxyProfile() just before importing proxy.js.
7
+ //
8
+ // Source of truth: the platform's config (`preferences.json.<platform>.proxyProfileId`). The
9
+ // workspace file is a projection of that config, re-asserted on every boot. We deliberately do
10
+ // NOT reuse interceptor's _writeWorkspaceActive (private, returns bool, swallows) or
11
+ // mergeActivePayload for the clear path: mergeActivePayload coerces a non-string activeId to
12
+ // 'max' (an explicit Default pin), which cannot express "clear the override and follow global".
13
+ // Omitting the activeId key restores the global fallback (see _readWorkspaceActive, which only
14
+ // honors a string activeId). Reads/writes go through the shared json-store kernel (atomic, 0600).
15
+ //
16
+ // "Unset" vs "explicitly cleared": an empty config pin is ambiguous — it is both the factory
17
+ // state and the value after a user clears the selector. A marker file (.proxy-pin-bootstrapped)
18
+ // records that first-boot adoption has already run: before the marker, an existing workspace pin
19
+ // (set via the worker's own proxy UI) is ADOPTED into the config rather than discarded; after the
20
+ // marker, an empty config authoritatively clears the override.
21
+ import { join } from 'node:path';
22
+ import { existsSync, writeFileSync } from 'node:fs';
23
+ import { reportSwallowed } from '../error-report.js';
24
+ import { readJsonStrict, writeJsonAtomic } from '../json-store.js';
25
+ import { normalizeRoles } from '../interceptor-core.js';
26
+ import { loadConfig, saveConfig } from './im-config.js';
27
+ import { imDir } from './im-lock.js';
28
+ import { LOG_DIR } from '../../../findcc.js';
29
+
30
+ const BOOTSTRAP_MARK = '.proxy-pin-bootstrapped';
31
+
32
+ function profileIdsOrNull() {
33
+ // null = profile.json absent/unreadable (unknown, not "empty").
34
+ const file = join(LOG_DIR, 'profile.json');
35
+ const r = readJsonStrict(file);
36
+ if (r.state === 'corrupt') {
37
+ reportSwallowed('im-proxy-profile.read-profile-json', new Error(`profile.json unreadable: ${file}`));
38
+ return null;
39
+ }
40
+ if (r.state !== 'ok') return null;
41
+ return new Set((r.data?.profiles || []).filter((p) => p && typeof p.id === 'string').map((p) => p.id));
42
+ }
43
+
44
+ function markBootstrapped(id) {
45
+ try { writeFileSync(join(imDir(id), BOOTSTRAP_MARK), '', { mode: 0o600 }); }
46
+ catch (err) { reportSwallowed('im-proxy-profile.bootstrap-mark', err); } // best-effort
47
+ }
48
+
49
+ // Persist the platform's pinned proxy profile into the worker's workspace active-profile.json.
50
+ // Returns { applied: 'noop'|'pinned'|'cleared'|'adopted', file }. Throws only when the atomic
51
+ // write fails; the caller (worker boot) treats that as non-fatal and falls back to the
52
+ // existing/global profile.
53
+ export function applyImProxyProfile(id, profileId) {
54
+ const file = join(imDir(id), 'active-profile.json');
55
+ const pin = typeof profileId === 'string' ? profileId.trim() : '';
56
+
57
+ // Structured read: missing / ok / corrupt. A corrupt file is repaired below with a clean
58
+ // payload — data-loss class, must be reported (throttled).
59
+ const r = readJsonStrict(file);
60
+ if (r.state === 'corrupt') {
61
+ reportSwallowed('im-proxy-profile.read-workspace-active', new Error(`active-profile.json unreadable: ${file}`));
62
+ }
63
+ const existing = r.state === 'ok' ? r.data : null;
64
+ // Merge-preserve roles: the worker's own Web UI may own subagent/teammate assignments.
65
+ const roles = normalizeRoles(existing?.roles);
66
+ const existingPin = (typeof existing?.activeId === 'string' && existing.activeId) ? existing.activeId : '';
67
+ const bootstrapped = existsSync(join(imDir(id), BOOTSTRAP_MARK));
68
+
69
+ if (!pin) {
70
+ if (existingPin && r.state === 'ok' && !bootstrapped) {
71
+ // First boot with an empty config but a runtime-set workspace pin: adopt it into the config
72
+ // (so the upgrade never silently discards the user's choice), then config is authoritative.
73
+ try { saveConfig(id, { ...loadConfig(id), proxyProfileId: existingPin }); }
74
+ catch (err) { reportSwallowed('im-proxy-profile.adopt-pin', err); } // non-fatal: keep the runtime pin this boot
75
+ markBootstrapped(id);
76
+ return { applied: 'adopted', file };
77
+ }
78
+ markBootstrapped(id);
79
+ if (!existingPin && r.state !== 'corrupt') return { applied: 'noop', file }; // follow global, nothing to clear
80
+ // Empty config AFTER bootstrap (or a corrupt file) ⇒ authoritatively clear: omit activeId.
81
+ writeJsonAtomic(file, { roles }, { mode: 0o600 });
82
+ return { applied: 'cleared', file };
83
+ }
84
+
85
+ // A non-empty config pin is authoritative; it also settles the bootstrap state.
86
+ markBootstrapped(id);
87
+ if (pin !== 'max') {
88
+ const ids = profileIdsOrNull();
89
+ // Unknown id: the interceptor resolves a dangling workspace activeId to Default and the
90
+ // session seed degrades to legacy main (also Default). Keep the pin so it auto-resumes if
91
+ // the profile is re-created; record it for diagnosis. profile.json unreadable → skip.
92
+ if (ids && !ids.has(pin)) {
93
+ reportSwallowed('im-proxy-profile.unknown-profile',
94
+ new Error(`IM ${id} pinned proxy profile "${pin}" not in profile.json — worker will fall back to Default`));
95
+ }
96
+ }
97
+ writeJsonAtomic(file, { activeId: pin, roles }, { mode: 0o600 });
98
+ return { applied: 'pinned', file };
99
+ }
@@ -2858,7 +2858,7 @@ function _createSession(cwd, { freshKey = false } = {}) {
2858
2858
  }
2859
2859
 
2860
2860
  /**
2861
- * 960K forced compaction only: skips the idle gate and directly "enqueues one + send-now immediately",
2861
+ * 900K forced compaction only: skips the idle gate and directly "enqueues one + send-now immediately",
2862
2862
  * equivalent to the user manually sending now — after interrupting the current turn (q.interrupt), drain pushes this item out as the next turn.
2863
2863
  * Reuses _sendQueuedNow's full lifecycle (occupies the dispatch slot / _interruptTurn / _suppressDrain reset),
2864
2864
  * avoiding the naive "interrupt + sendUserMessage" combination getting the message stuck in the queue (_interruptTurn sets
@@ -3505,7 +3505,7 @@ export function sendQueuedNow(id, anchor) {
3505
3505
  return sess ? sess.sendQueuedNow(id) : [];
3506
3506
  }
3507
3507
 
3508
- /** 960K forced compaction: interrupt the current turn and inject one message immediately (routed to the anchor's session). */
3508
+ /** 900K forced compaction: interrupt the current turn and inject one message immediately (routed to the anchor's session). */
3509
3509
  export function forceSendUserMessage(text, anchor) {
3510
3510
  if (!_query) throw new Error('Agent SDK not available');
3511
3511
  const sess = anchor ? _sessionForAnchor(anchor, { allowPrimaryFallback: true }) : _active();
@@ -19,8 +19,9 @@
19
19
  */
20
20
 
21
21
  import { existsSync, statSync, openSync, readSync, closeSync, readdirSync } from 'node:fs';
22
- import { join } from 'node:path';
22
+ import { join, dirname } from 'node:path';
23
23
  import { getClaudeConfigDir } from '../../findcc.js';
24
+ import { reportSwallowed } from './error-report.js';
24
25
 
25
26
  function projectsDir() {
26
27
  return process.env.CCV_PROJECTS_DIR || join(getClaudeConfigDir(), 'projects');
@@ -293,6 +294,131 @@ export function lookupToolUseResult(sessionId, toolUseId, projectHint) {
293
294
  return result;
294
295
  }
295
296
 
297
+ // ── Whole-session tool timing scan (Agent-Loop timeline precise timing) ──────
298
+
299
+ const SUBAGENT_SCAN_MAX_FILES = 64;
300
+
301
+ /**
302
+ * Scan a whole transcript file (no early break) and collect every tool_use /
303
+ * tool_result line timestamp, paired by tool_use.id.
304
+ *
305
+ * The per-line `timestamp` on a tool_result (user) line is the tool's true end;
306
+ * the `timestamp` on the assistant line carrying the tool_use block is its true
307
+ * start. First-seen wins for each id (later duplicates are replays).
308
+ *
309
+ * @param {string} filePath
310
+ * @param {Map<string, {startMs:number|null,endMs:number|null}>} into - merged in place
311
+ * @returns {{truncated:boolean}} truncated=true when the file was skipped (size cap).
312
+ */
313
+ function collectTimingsFromFile(filePath, into) {
314
+ try {
315
+ const fileSize = statSync(filePath).size;
316
+ if (fileSize === 0) return { truncated: false };
317
+ if (fileSize > MAX_TRANSCRIPT_BYTES) return { truncated: true };
318
+ const fd = openSync(filePath, 'r');
319
+ const buf = Buffer.alloc(Math.min(READ_CHUNK_SIZE, fileSize));
320
+ let offset = 0;
321
+ let pending = '';
322
+ const handleLine = (line) => {
323
+ if (!line) return;
324
+ // Cheap prefilter to avoid parsing every line.
325
+ const hasUse = line.indexOf('"tool_use"') !== -1;
326
+ const hasResult = line.indexOf('"tool_result"') !== -1;
327
+ if (!hasUse && !hasResult) return;
328
+ let entry;
329
+ try { entry = JSON.parse(line); } catch { return; }
330
+ const tsMs = entry && entry.timestamp ? Date.parse(entry.timestamp) : NaN;
331
+ if (!Number.isFinite(tsMs)) return;
332
+ const content = entry && entry.message && Array.isArray(entry.message.content)
333
+ ? entry.message.content
334
+ : [];
335
+ for (const blk of content) {
336
+ if (!blk || typeof blk !== 'object') continue;
337
+ if (hasUse && blk.type === 'tool_use' && blk.id != null) {
338
+ const id = String(blk.id);
339
+ const cur = into.get(id);
340
+ if (!cur) into.set(id, { startMs: tsMs, endMs: null });
341
+ else if (cur.startMs == null) cur.startMs = tsMs;
342
+ } else if (hasResult && blk.type === 'tool_result' && blk.tool_use_id != null) {
343
+ const id = String(blk.tool_use_id);
344
+ const cur = into.get(id);
345
+ if (!cur) into.set(id, { startMs: null, endMs: tsMs });
346
+ else if (cur.endMs == null) cur.endMs = tsMs;
347
+ }
348
+ }
349
+ };
350
+ try {
351
+ while (offset < fileSize) {
352
+ const toRead = Math.min(buf.length, fileSize - offset);
353
+ const bytesRead = readSync(fd, buf, 0, toRead, offset);
354
+ if (bytesRead === 0) break;
355
+ offset += bytesRead;
356
+ const text = pending + buf.toString('utf-8', 0, bytesRead);
357
+ const lines = text.split('\n');
358
+ pending = lines.pop() ?? '';
359
+ for (const line of lines) handleLine(line);
360
+ }
361
+ if (pending) handleLine(pending);
362
+ } finally {
363
+ closeSync(fd);
364
+ }
365
+ return { truncated: false };
366
+ } catch (err) {
367
+ // A broken/unreadable transcript silently yields zero timings, indistinguishable
368
+ // from "not found" — report it (entry ingest class), then degrade to estimated.
369
+ reportSwallowed('agentLoop.timings.scan', err);
370
+ return { truncated: false };
371
+ }
372
+ }
373
+
374
+ /**
375
+ * Collect precise tool start/end times for a session from its Claude Code
376
+ * transcript (main + subagents/agent-*.jsonl). Main transcript is authoritative;
377
+ * subagent files only fill ids/fields the main file didn't provide.
378
+ *
379
+ * @param {string} sessionId - Claude session UUID.
380
+ * @param {string} [projectHint] - interceptor's sanitized cwd basename.
381
+ * @param {object} [opts]
382
+ * @param {string} [opts.sessionDir] - pre-resolved transcript FILE path (skips lookup).
383
+ * Despite the name this is the full .jsonl file path, not a directory.
384
+ * @returns {{available:boolean, timings:Object, truncated:boolean}}
385
+ */
386
+ export function lookupSessionToolTimings(sessionId, projectHint, opts = {}) {
387
+ const empty = { available: false, timings: {}, truncated: false };
388
+ if (!sessionId) return empty;
389
+ const mainPath = opts.sessionDir || findTranscriptPath(sessionId, projectHint);
390
+ if (!mainPath || !existsSync(mainPath)) return empty;
391
+
392
+ const into = new Map();
393
+ let truncated = false;
394
+ const mainRes = collectTimingsFromFile(mainPath, into);
395
+ truncated = truncated || mainRes.truncated;
396
+
397
+ // Subagent transcripts: <sessionDir>/subagents/agent-*.jsonl (fill missing only).
398
+ try {
399
+ const sessionDir = join(dirname(mainPath), sessionId);
400
+ const subDir = join(sessionDir, 'subagents');
401
+ if (existsSync(subDir)) {
402
+ const files = readdirSync(subDir)
403
+ .filter(f => /^agent-.+\.jsonl$/.test(f))
404
+ .slice(0, SUBAGENT_SCAN_MAX_FILES);
405
+ for (const f of files) {
406
+ const res = collectTimingsFromFile(join(subDir, f), into);
407
+ truncated = truncated || res.truncated;
408
+ }
409
+ }
410
+ } catch (err) { /* subagent discovery is best-effort; main timings already collected */
411
+ reportSwallowed('agentLoop.timings.subagents', err);
412
+ }
413
+
414
+ // Use a null-prototype object so tool ids like "__proto__"/"constructor" are
415
+ // stored as own properties (a plain {} would silently drop them or read an
416
+ // inherited value on the client).
417
+ const timings = Object.create(null);
418
+ for (const [id, v] of into) timings[id] = v;
419
+ return { available: true, timings, truncated };
420
+ }
421
+
296
422
  /** 测试用:清掉三个 LRU。 */
297
423
  export function clearCache() {
298
424
  transcriptPathCache.clear();
@@ -0,0 +1,47 @@
1
+ // Agent-Loop timeline precise timing: serve per-tool start/end timestamps read
2
+ // from the Claude Code transcript (main + subagents/agent-*.jsonl). Read-only;
3
+ // returns 200 + available:false when the transcript isn't found so the client
4
+ // silently falls back to estimated timing (imported/foreign histories).
5
+ import { lookupSessionToolTimings } from '../lib/session-transcript-reader.js';
6
+
7
+ // sessionId is interpolated into a transcript path — validate as UUID to block
8
+ // traversal (same convention as workflow-journal.js SESSION_RE).
9
+ const SESSION_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
10
+
11
+ /**
12
+ * GET /api/agent-loop-timings?session=<uuid>[&project=<name>]
13
+ * Response: { ok:true, available:true, timings:{id:{startMs,endMs}}, truncated }
14
+ * { ok:true, available:false, timings:{} } (transcript not found)
15
+ * 400 { ok:false, error } (bad/missing session)
16
+ */
17
+ function agentLoopTimings(req, res, parsedUrl) {
18
+ const session = parsedUrl.searchParams.get('session') || '';
19
+ const project = parsedUrl.searchParams.get('project') || undefined;
20
+ if (!SESSION_RE.test(session)) {
21
+ res.writeHead(400, { 'Content-Type': 'application/json' });
22
+ res.end(JSON.stringify({ ok: false, error: 'expected session=<uuid>' }));
23
+ return;
24
+ }
25
+ try {
26
+ const result = lookupSessionToolTimings(session, project);
27
+ // Serialize BEFORE writeHead: a payload approaching the string-length ceiling
28
+ // throws RangeError here, and writeHead(500) below must not run after a 200
29
+ // head was already sent (that double-head throw escapes the dispatcher and
30
+ // kills the process — see server.js handleRequest note).
31
+ const body = JSON.stringify({ ok: true, ...result });
32
+ res.writeHead(200, { 'Content-Type': 'application/json' });
33
+ res.end(body);
34
+ } catch (err) {
35
+ // Never echo the raw message — it can carry ~/.claude/projects/... paths.
36
+ if (!res.headersSent) {
37
+ res.writeHead(500, { 'Content-Type': 'application/json' });
38
+ res.end(JSON.stringify({ ok: false, error: 'Internal error' }));
39
+ } else {
40
+ res.end();
41
+ }
42
+ }
43
+ }
44
+
45
+ export const agentLoopTimingsRoutes = [
46
+ { method: 'GET', match: 'exact', path: '/api/agent-loop-timings', handler: agentLoopTimings },
47
+ ];
@@ -105,6 +105,10 @@ function dingtalkConfigPost(req, res, parsedUrl, isLocal, deps) {
105
105
  cardTemplateId: incoming.cardTemplateId,
106
106
  aiCardTemplateId: incoming.aiCardTemplateId,
107
107
  aiCardStreamKey: incoming.aiCardStreamKey,
108
+ // Pass through the proxy-profile pin; a client that predates the field omits it, which would
109
+ // let normalize() reset it to ''. Preserve the stored value in that case (mirrors the
110
+ // secret-field "empty = keep" convention) so a legacy full save cannot silently clear the pin.
111
+ proxyProfileId: 'proxyProfileId' in incoming ? incoming.proxyProfileId : loadDingTalkConfig().proxyProfileId,
108
112
  });
109
113
  // 驱动进程管理器(替代旧的在进程 reloadBridge):启用→重启 worker,停用→停 worker。
110
114
  try {
@@ -186,6 +186,10 @@ function imConfigPost(req, res, parsedUrl, isLocal, deps) {
186
186
  const incomingObj = (incoming && typeof incoming === 'object' && !Array.isArray(incoming)) ? incoming : {};
187
187
  const touchesOthers = desc.fields.some((f) => f.key !== 'enabled' && f.key in incomingObj);
188
188
  const effective = touchesOthers ? incomingObj : { ...loadConfig(id), enabled: !!incomingObj.enabled };
189
+ // Preserve the proxy-profile pin across full saves from a client that predates the field (a
190
+ // stale browser bundle / older API caller): absent from the body must not reset it to ''.
191
+ // Mirrors the secret-field "empty = keep" convention so the pin survives version skew.
192
+ if (!('proxyProfileId' in effective)) effective.proxyProfileId = loadConfig(id).proxyProfileId;
189
193
  if (effective.enabled) warnIfEmptyAllowlist(id, effective);
190
194
  const saved = saveConfig(id, effective);
191
195
  // applyProcess(默认 true,保持旧调用方语义):前端 onBlur 自动保存传 false → 仅存盘、不驱动进程,
package/server/server.js CHANGED
@@ -48,6 +48,7 @@ import { resumeRoutes } from './routes/resume.js';
48
48
  import { sdkContextRoutes } from './routes/sdk-context.js';
49
49
  import { sdkMcpStatusRoutes } from './routes/sdk-mcp-status.js';
50
50
  import { proxyStatsRoutes } from './routes/proxy-stats.js';
51
+ import { agentLoopTimingsRoutes } from './routes/agent-loop-timings.js';
51
52
  import { updateRoutes } from './routes/update.js';
52
53
  import { UpdateJob } from './lib/update-job.js';
53
54
  import { setProxyStatsListener, setSlowUpstreamListener } from './lib/proxy/proxy-stats.js';
@@ -996,6 +997,7 @@ const _routes = [
996
997
  ...dingtalkRoutes,
997
998
  ...imRoutes,
998
999
  ...proxyStatsRoutes,
1000
+ ...agentLoopTimingsRoutes,
999
1001
  ...updateRoutes,
1000
1002
  ...resumeRoutes,
1001
1003
  ...sdkContextRoutes,
@@ -3218,7 +3220,7 @@ async function setupTerminalWebSocket(httpServer) {
3218
3220
  const project = (typeof msg.project === 'string' && msg.project) ? msg.project : null;
3219
3221
  const instanceKey = (typeof msg.instanceKey === 'string' && msg.instanceKey) ? msg.instanceKey : null;
3220
3222
  const anchor = (project || instanceKey) ? { project: project || undefined, instanceKey: instanceKey || undefined } : null;
3221
- // 960K forced compaction: the only path allowed to inject mid-stream (interrupts the current session). Other sources never inject mid-stream.
3223
+ // 900K forced compaction: the only path allowed to inject mid-stream (interrupts the current session). Other sources never inject mid-stream.
3222
3224
  const isForce = msg.force === true;
3223
3225
  if (!reqId || !/^\/compact(\s|$)/.test(text) || text.length > 20000) { reply({ reqId, ok: false, reason: 'bad-text' }); return; }
3224
3226
  if (!anchor) { reply({ reqId, ok: false, reason: 'no-anchor' }); return; }
@@ -3233,7 +3235,7 @@ async function setupTerminalWebSocket(httpServer) {
3233
3235
  if (!gate) { reply({ reqId, ok: false, reason: 'session-inactive' }); return; }
3234
3236
  resolvedInstance = gate.instanceKey || instanceKey;
3235
3237
  // Atomic gate: idle + no turn in flight + no pending approval + empty queue; otherwise reply busy so the frontend retries next turn.
3236
- // 960K forced compaction skips the idle gate (it exists precisely to interrupt a busy current turn).
3238
+ // 900K forced compaction skips the idle gate (it exists precisely to interrupt a busy current turn).
3237
3239
  if (!isForce && !gate.idle) { reply({ reqId, ok: false, reason: 'busy' }); return; }
3238
3240
  } else {
3239
3241
  // PTY mode: target liveness precheck (a dead target is rejected immediately, no polling). Use the module-level
@@ -3278,7 +3280,7 @@ async function setupTerminalWebSocket(httpServer) {
3278
3280
  };
3279
3281
 
3280
3282
  if (isSdkMode) {
3281
- // 960K forced compaction: enqueue + immediate send-now (once the current turn is interrupted, drain pushes out /compact).
3283
+ // 900K forced compaction: enqueue + immediate send-now (once the current turn is interrupted, drain pushes out /compact).
3282
3284
  if (isForce) {
3283
3285
  if (!_sdkForceSendUserMessage) { finishFail('no-deps'); return; }
3284
3286
  try {
@@ -3324,7 +3326,7 @@ async function setupTerminalWebSocket(httpServer) {
3324
3326
  }
3325
3327
  finishOk();
3326
3328
  } else {
3327
- // 960K forced compaction (PTY): enqueue + sendNow — write focus-in+ESC to interrupt the current generation,
3329
+ // 900K forced compaction (PTY): enqueue + sendNow — write focus-in+ESC to interrupt the current generation,
3328
3330
  // poll for idle, then bracketed-paste /compact. Never a blind write (on failure requeue; frontend ack failure is retryable).
3329
3331
  if (isForce) {
3330
3332
  try {
@@ -4414,7 +4416,7 @@ export function setSdkCancelApproval(fn) { _sdkCancelApproval = fn; }
4414
4416
  let _sdkSendUserMessage = null;
4415
4417
  export function setSdkSendUserMessage(fn) { _sdkSendUserMessage = fn; }
4416
4418
 
4417
- /** Reference to sdk-manager's forceSendUserMessage (set by cli.js after import) — 960K forced compaction. */
4419
+ /** Reference to sdk-manager's forceSendUserMessage (set by cli.js after import) — 900K forced compaction. */
4418
4420
  let _sdkForceSendUserMessage = null;
4419
4421
  export function setSdkForceSendUserMessage(fn) { _sdkForceSendUserMessage = fn; }
4420
4422