cc-viewer 1.9.36 → 1.9.38

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 (102) hide show
  1. package/README.md +5 -1
  2. package/cli.js +4 -0
  3. package/dist/assets/App-CF8BZExv.js +2 -0
  4. package/dist/assets/App-DwLJPKiz.css +1 -0
  5. package/dist/assets/{ArchivePreview-ezRMkut5.js → ArchivePreview-BwkACTcN.js} +1 -1
  6. package/dist/assets/{AudioPreview-MxQVazDj.js → AudioPreview-Bzzv-8w2.js} +1 -1
  7. package/dist/assets/{MdxEditorPanel-CmG2jyvK.js → MdxEditorPanel-DgInZmjn.js} +1 -1
  8. package/dist/assets/{Mobile-B5V_-6Hc.css → Mobile-B_8Wt_hT.css} +1 -1
  9. package/dist/assets/Mobile-BwxpuUXE.js +1 -0
  10. package/dist/assets/ProxyStatsModal-C0EVF31b.js +1 -0
  11. package/dist/assets/{SubtitlePreview-CHRRgV95.js → SubtitlePreview-D3MhYKJS.js} +1 -1
  12. package/dist/assets/{_baseUniq-ClHxNSma.js → _baseUniq-uUw7d1E3.js} +1 -1
  13. package/dist/assets/{arc-ClGYU-1i.js → arc-BOWuMiV4.js} +1 -1
  14. package/dist/assets/{architectureDiagram-Q4EWVU46-El3lNwsp.js → architectureDiagram-Q4EWVU46-h5aWPWJ4.js} +1 -1
  15. package/dist/assets/{blockDiagram-DXYQGD6D-DH290jST.js → blockDiagram-DXYQGD6D-CudvZcvo.js} +1 -1
  16. package/dist/assets/{c4Diagram-AHTNJAMY-BQMsMwnY.js → c4Diagram-AHTNJAMY-DYlZi3dM.js} +1 -1
  17. package/dist/assets/{channel-C-OnmeWg.js → channel-XJqusGHw.js} +1 -1
  18. package/dist/assets/{chunk-4BX2VUAB-PRxJ3zS8.js → chunk-4BX2VUAB-CLpyEaWp.js} +1 -1
  19. package/dist/assets/{chunk-4TB4RGXK-C_TKsRMW.js → chunk-4TB4RGXK-BAuE3fNK.js} +1 -1
  20. package/dist/assets/{chunk-55IACEB6-nGpnU7E4.js → chunk-55IACEB6-B4tW65z_.js} +1 -1
  21. package/dist/assets/{chunk-EDXVE4YY-D0-9hlXC.js → chunk-EDXVE4YY-Bb7xoST0.js} +1 -1
  22. package/dist/assets/{chunk-FMBD7UC4-hKmwmsrB.js → chunk-FMBD7UC4-CTkqi9Np.js} +1 -1
  23. package/dist/assets/{chunk-OYMX7WX6-CZnR4qSn.js → chunk-OYMX7WX6-uQdTKgLj.js} +1 -1
  24. package/dist/assets/{chunk-QZHKN3VN-CGtdnavD.js → chunk-QZHKN3VN-C6ugcDBb.js} +1 -1
  25. package/dist/assets/{chunk-YZCP3GAM-GPB3qNXk.js → chunk-YZCP3GAM-Hp9H2dEu.js} +1 -1
  26. package/dist/assets/classDiagram-6PBFFD2Q-CqAo3MbD.js +1 -0
  27. package/dist/assets/classDiagram-v2-HSJHXN6E-CqAo3MbD.js +1 -0
  28. package/dist/assets/clone-BIwWiqgh.js +1 -0
  29. package/dist/assets/{cose-bilkent-S5V4N54A-9L57MjYD.js → cose-bilkent-S5V4N54A-BqngH0-b.js} +1 -1
  30. package/dist/assets/{dagre-KV5264BT-CNkz8gO7.js → dagre-KV5264BT-CB2GDseU.js} +1 -1
  31. package/dist/assets/{diagram-5BDNPKRD-DQBFzIFl.js → diagram-5BDNPKRD-DLymVFaP.js} +1 -1
  32. package/dist/assets/{diagram-G4DWMVQ6-CTwwGTIV.js → diagram-G4DWMVQ6-D90wHjyV.js} +1 -1
  33. package/dist/assets/{diagram-MMDJMWI5-BKEsMMNd.js → diagram-MMDJMWI5-BUN9g8qX.js} +1 -1
  34. package/dist/assets/{diagram-TYMM5635-BgAqGIDJ.js → diagram-TYMM5635-I51WOx9p.js} +1 -1
  35. package/dist/assets/{erDiagram-SMLLAGMA-BuR-DOkX.js → erDiagram-SMLLAGMA-CR1_hpJO.js} +1 -1
  36. package/dist/assets/{flowDiagram-DWJPFMVM-CtEs3omg.js → flowDiagram-DWJPFMVM-CiwoAZbF.js} +1 -1
  37. package/dist/assets/{ganttDiagram-T4ZO3ILL-aEyreBxU.js → ganttDiagram-T4ZO3ILL-CJXNdMQL.js} +1 -1
  38. package/dist/assets/{gitGraphDiagram-UUTBAWPF-B0jK9QeS.js → gitGraphDiagram-UUTBAWPF-BaZdjuy6.js} +1 -1
  39. package/dist/assets/{graph-ehKfRbVz.js → graph-CpnKw6r1.js} +1 -1
  40. package/dist/assets/index-B15ZeDb-.css +1 -0
  41. package/dist/assets/{index-B0uKNGh1.js → index-BrAqjeq3.js} +1 -1
  42. package/dist/assets/{index-CtricoKb.js → index-BzeiQo_V.js} +1 -1
  43. package/dist/assets/{index-Dns_OQOp.js → index-C1VAmODt.js} +1 -1
  44. package/dist/assets/{index-D5KJq71j.js → index-C5FKlPaZ.js} +1 -1
  45. package/dist/assets/index-D-DhPfzj.js +2 -0
  46. package/dist/assets/{index-Brys6nSs.js → index-D3x00_V6.js} +1 -1
  47. package/dist/assets/{index-CH6ZHNzo.js → index-DL6PUDDq.js} +1 -1
  48. package/dist/assets/{index-BDj-fJNP.js → index-VjrFIlap.js} +1 -1
  49. package/dist/assets/{infoDiagram-42DDH7IO-CUntIdK6.js → infoDiagram-42DDH7IO-BvyXlqWb.js} +1 -1
  50. package/dist/assets/{ishikawaDiagram-UXIWVN3A-CtCGMBTX.js → ishikawaDiagram-UXIWVN3A-CwbVWeK4.js} +1 -1
  51. package/dist/assets/{journeyDiagram-VCZTEJTY-DCRvOrOx.js → journeyDiagram-VCZTEJTY-DDVzhfoW.js} +1 -1
  52. package/dist/assets/{jszip.min-DZsXbJ4A.js → jszip.min-RVG0sxQ-.js} +1 -1
  53. package/dist/assets/{kanban-definition-6JOO6SKY-jEtOSXmn.js → kanban-definition-6JOO6SKY-CC9zdzb4.js} +1 -1
  54. package/dist/assets/{layout-C-6TbhHY.js → layout-BP8agUEZ.js} +1 -1
  55. package/dist/assets/{linear-DQg_Idt4.js → linear-D2xrTRbP.js} +1 -1
  56. package/dist/assets/{mermaid.core-C_rq53MX.js → mermaid.core-iygJ4rTs.js} +2 -2
  57. package/dist/assets/{min-BqPulfFi.js → min-DZABGYh9.js} +1 -1
  58. package/dist/assets/{mindmap-definition-QFDTVHPH-CNsFBo-7.js → mindmap-definition-QFDTVHPH-DonHZQOo.js} +1 -1
  59. package/dist/assets/{pieDiagram-DEJITSTG-BDn3Cz--.js → pieDiagram-DEJITSTG-CEn16Sb_.js} +1 -1
  60. package/dist/assets/{quadrantDiagram-34T5L4WZ-CsrLWd-H.js → quadrantDiagram-34T5L4WZ-385okL2K.js} +1 -1
  61. package/dist/assets/{requirementDiagram-MS252O5E-DPzJKSB5.js → requirementDiagram-MS252O5E-B7AA6wNS.js} +1 -1
  62. package/dist/assets/{sankeyDiagram-XADWPNL6-DYDGySQ1.js → sankeyDiagram-XADWPNL6-BE2hbI0P.js} +1 -1
  63. package/dist/assets/seqResourceLoaders-BdxjrasH.css +41 -0
  64. package/dist/assets/seqResourceLoaders-DPto114V.js +2 -0
  65. package/dist/assets/{sequenceDiagram-FGHM5R23-HVWMhF8a.js → sequenceDiagram-FGHM5R23-DUbU1ZOb.js} +1 -1
  66. package/dist/assets/{stateDiagram-FHFEXIEX-BtcEUJOY.js → stateDiagram-FHFEXIEX-BKKvwNQM.js} +1 -1
  67. package/dist/assets/{stateDiagram-v2-QKLJ7IA2-DWDh2D71.js → stateDiagram-v2-QKLJ7IA2-qXlEdp-K.js} +1 -1
  68. package/dist/assets/{timeline-definition-GMOUNBTQ-B81djDNu.js → timeline-definition-GMOUNBTQ-DQnlfuvY.js} +1 -1
  69. package/dist/assets/{vendor-antd-C5Wsfsxn.js → vendor-antd-DTdiXvO1.js} +1 -1
  70. package/dist/assets/{vendor-codemirror-DPXDhteu.js → vendor-codemirror-Dg_w9qS2.js} +1 -1
  71. package/dist/assets/{vendor-mdxeditor-DLPCj_fe.js → vendor-mdxeditor-DNrU6OL8.js} +2 -2
  72. package/dist/assets/{vendor-qrcode-BzB5n5mK.js → vendor-qrcode-BdV5qU8N.js} +1 -1
  73. package/dist/assets/{vendor-virtuoso-Beq6R5oo.js → vendor-virtuoso-BQELbHyq.js} +1 -1
  74. package/dist/assets/{vennDiagram-DHZGUBPP-BeitG2yA.js → vennDiagram-DHZGUBPP-B51WBYoK.js} +1 -1
  75. package/dist/assets/{wardley-RL74JXVD-BCzOL4u_.js → wardley-RL74JXVD-DQSgSi6f.js} +1 -1
  76. package/dist/assets/{wardleyDiagram-NUSXRM2D-20SEChwk.js → wardleyDiagram-NUSXRM2D-B5PCvQWU.js} +1 -1
  77. package/dist/assets/{xychartDiagram-5P7HB3ND-Behle0ry.js → xychartDiagram-5P7HB3ND-fY2LLKhL.js} +1 -1
  78. package/dist/index.html +5 -5
  79. package/node_modules/@ccv/core/src/sdk-task-label.js +70 -0
  80. package/package.json +1 -1
  81. package/server/interceptor.js +32 -3
  82. package/server/lib/builtin-model-prompts.js +16 -7
  83. package/server/lib/chat-queue.js +159 -31
  84. package/server/lib/compact-inject-guard.js +100 -0
  85. package/server/lib/model-system-prompts.js +207 -13
  86. package/server/lib/project-prefs.js +12 -5
  87. package/server/lib/proxy-session-registry.js +75 -12
  88. package/server/lib/sdk-manager.js +129 -7
  89. package/server/lib/task-state.js +11 -0
  90. package/server/routes/preferences.js +17 -2
  91. package/server/server.js +207 -0
  92. package/dist/assets/App-BJIeZQK0.css +0 -1
  93. package/dist/assets/App-C_S65Ygt.js +0 -2
  94. package/dist/assets/Mobile-BerOQqT4.js +0 -1
  95. package/dist/assets/ProxyStatsModal-dqlP2r2c.js +0 -1
  96. package/dist/assets/classDiagram-6PBFFD2Q-DigyQWGQ.js +0 -1
  97. package/dist/assets/classDiagram-v2-HSJHXN6E-DigyQWGQ.js +0 -1
  98. package/dist/assets/clone-DwpJyNdv.js +0 -1
  99. package/dist/assets/index-BLzca-ta.css +0 -1
  100. package/dist/assets/index-DBmXRTLE.js +0 -2
  101. package/dist/assets/seqResourceLoaders-BOVRL7Y-.js +0 -2
  102. package/dist/assets/seqResourceLoaders-b9deQDrA.css +0 -41
@@ -15,7 +15,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
15
15
  import { dirname, join, basename } from 'node:path';
16
16
  import { LOG_DIR } from '../findcc.js';
17
17
  import { assembleStreamMessage, createStreamAssembler, isAnthropicApiPath, isMainAgentRequest, replaceTopLevelModel, replaceTopLevelSystem, injectOutputConfigEffort, resolveProfileModel, extractAgentSpawnPairs, classifyProxyRole, resolveRoleProfile, resolveSessionMainProfile, resolveSessionRoleProfile, normalizeRoles, mergeActivePayload } from './lib/interceptor-core.js';
18
- import { registerGlobalDefaultProvider, registerSeedProvider, getSessionProxy } from './lib/proxy-session-registry.js';
18
+ import { registerGlobalDefaultProvider, registerSeedProvider, getSessionProxy, reseedSeedOriginBindings } from './lib/proxy-session-registry.js';
19
19
  import { V2Writer } from './lib/v2/v2-writer.js';
20
20
  import { reportSwallowed } from './lib/error-report.js';
21
21
  import { latestMainSessionDir, sessionHasMainTurn, sessionHasCompletedMainTurn } from './lib/v2/session-select.js';
@@ -289,7 +289,7 @@ function _getActiveProfileFilePath() {
289
289
 
290
290
  function _readWorkspaceActive() {
291
291
  const p = _getActiveProfileFilePath();
292
- const empty = { activeId: null, roles: normalizeRoles(undefined) };
292
+ const empty = { activeId: null, roles: normalizeRoles(undefined), unreadable: false };
293
293
  if (!p) return empty;
294
294
  try {
295
295
  if (existsSync(p)) {
@@ -297,11 +297,14 @@ function _readWorkspaceActive() {
297
297
  return {
298
298
  activeId: typeof data?.activeId === 'string' ? data.activeId : null,
299
299
  roles: normalizeRoles(data?.roles),
300
+ unreadable: false,
300
301
  };
301
302
  }
302
303
  } catch (err) {
303
- // 损坏的工作区文件会把 active/roles 静默回落默认 —— 属"丢数据"级,必须记账(有节流)
304
+ // 损坏的工作区文件会把 active/roles 静默回落默认 —— 属"丢数据"级,必须记账(有节流)。
305
+ // 标记 unreadable=true 让重算跳过(避免把 seed 绑定误降级为全局默认后又 flap 回来)。
304
306
  reportSwallowed('proxy-profile.workspace-read', err);
307
+ return { ...empty, unreadable: true };
305
308
  }
306
309
  return empty;
307
310
  }
@@ -409,6 +412,13 @@ function _loadProxyProfile() {
409
412
  const activeId = ws.activeId || data.active;
410
413
  const active = profiles.find(p => p.id === activeId);
411
414
  _activeProfile = (active && active.id !== 'max') ? active : null;
415
+ // Re-align seed-origin session bindings with the workspace's just-loaded active/roles.
416
+ // Runs on every successful load — setActiveProfileForWorkspace, both watchFile callbacks,
417
+ // and initForWorkspace/resetWorkspace re-arms all converge here, so no separate trigger is
418
+ // needed. Skip on the catch path (a corrupt profile.json is fail-closed) and when the
419
+ // workspace file itself is unreadable — re-seeding to the global default in either case
420
+ // would just downgrade the bindings and flap back once the file recovers.
421
+ if (!ws.unreadable) _reconcileSeedBindings(activeId);
412
422
  } catch (err) {
413
423
  _activeProfile = null;
414
424
  _globalDefaultId = 'max';
@@ -420,6 +430,25 @@ function _loadProxyProfile() {
420
430
  }
421
431
  }
422
432
 
433
+ // Re-align seed-origin session bindings with the current workspace's active/roles after a
434
+ // successful (re)load. Only bindings auto-seeded from THIS workspace are updated — explicit
435
+ // user choices (origin 'user') are never overwritten. Scoped by _projectName so a workspace
436
+ // switch never rewrites sessions that belong to a different workspace; skipped entirely when
437
+ // no workspace is bound (resetWorkspace / pre-selection). By design (reviewed), only the
438
+ // currently-bound workspace reconciles in real time — a seed binding for another live
439
+ // workspace converges when that workspace is next activated (initForWorkspace → this path).
440
+ function _reconcileSeedBindings(activeId) {
441
+ if (!_projectName) return;
442
+ try {
443
+ reseedSeedOriginBindings(
444
+ { main: (typeof activeId === 'string' && activeId) ? activeId : 'max', roles: _roleIds },
445
+ { workspace: _projectName },
446
+ );
447
+ } catch (err) {
448
+ reportSwallowed('proxy-profile.reseed-session-bindings', err);
449
+ }
450
+ }
451
+
423
452
  // 为 server.js::POST /api/proxy-profiles 使用,切换当前 workspace 的 active / roles。
424
453
  // 合并语义:activeId 或 roles 传 undefined = 保留文件现值(只改角色不动 main,反之亦然)。
425
454
  // activeId 有参时同时写两个位置,彼此互为兜底:
@@ -15,7 +15,7 @@ import { createHash } from 'node:crypto';
15
15
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
16
16
  import { tmpdir } from 'node:os';
17
17
  import { join } from 'node:path';
18
- import { expandModelIdVariants, normalizeModelName } from './model-system-prompts.js';
18
+ import { expandModelIdVariants, normalizeModelName, modelIdTokens, modelIdSegments, matchSegments, collectSegmentHits, segmentHitRank, substringHits } from './model-system-prompts.js';
19
19
  import { listSystemPromptPresets } from './system-prompt-presets.js';
20
20
  import { renameSyncWithRetry } from './file-api.js';
21
21
  import { reportSwallowed } from '../lib/error-report.js';
@@ -63,6 +63,9 @@ export function listBuiltinModelPrompts() {
63
63
  name,
64
64
  mode: p.defaultMode === 'override' ? 'override' : 'append',
65
65
  matchLower: p.match.toLowerCase(),
66
+ // 预计算段,供 matchBuiltinModelPrompt 复用(避免每次匹配重算)。
67
+ // Precomputed segments, reused by the matcher to avoid re-tokenizing per call.
68
+ segs: modelIdSegments(modelIdTokens(p.match.toLowerCase())),
66
69
  text: p.text,
67
70
  });
68
71
  }
@@ -70,10 +73,11 @@ export function listBuiltinModelPrompts() {
70
73
  }
71
74
 
72
75
  /**
73
- * 按 modelId 匹配内置条目:别名展开(expandModelIdVariants,先 lowercase)后任一变体
74
- * 包含 preset 的 match 即命中;多命中取 match 最长者、等长字典序(对齐 matchModelPrompt
75
- * 的消歧规则)。
76
- * Match a model id against built-in entries (alias-expanded substring, longest wins).
76
+ * 按 modelId 匹配内置条目:别名展开(expandModelIdVariants,先 lowercase)后切段,
77
+ * 与用户层同一套段匹配(ident 锁家族、版本排序消歧不否决);段匹配全 miss 时与用户层
78
+ * 同样回退旧子串(vendor 前缀可能与家族同名、锚错起点时子串仍能救回,两层保持同语义)。
79
+ * 多命中按「版本贴近度 > 段数多 > 名字长 > 精确 > 字典序」消歧(复用 segmentHitRank)。
80
+ * Match a model id against built-in entries (segment match + shared substring fallback).
77
81
  *
78
82
  * @param {string|null} modelId
79
83
  * @returns {{ id: string, name: string, mode: 'override'|'append', text: string } | null}
@@ -81,9 +85,14 @@ export function listBuiltinModelPrompts() {
81
85
  export function matchBuiltinModelPrompt(modelId) {
82
86
  const variants = expandModelIdVariants(modelId);
83
87
  if (!variants.length) return null;
84
- const hits = listBuiltinModelPrompts().filter((e) => variants.some((v) => v.includes(e.matchLower)));
88
+ const idSegsList = variants.map((v) => modelIdSegments(modelIdTokens(v)));
89
+ const entries = listBuiltinModelPrompts();
90
+ // 主路径:段匹配(与用户层同一套 collectSegmentHits + segmentHitRank)。
91
+ let hits = collectSegmentHits(entries, idSegsList, (e) => e.segs);
92
+ // 兜底:段匹配全 miss 时回退旧子串(与用户层同语义)。
93
+ if (!hits.length) hits = substringHits(variants, entries);
85
94
  if (!hits.length) return null;
86
- hits.sort((a, b) => b.matchLower.length - a.matchLower.length || a.name.localeCompare(b.name));
95
+ hits.sort(segmentHitRank);
87
96
  const e = hits[0];
88
97
  return { id: e.id, name: e.name, mode: e.mode, text: e.text };
89
98
  }
@@ -317,12 +317,16 @@ function _injectHead() {
317
317
  }
318
318
 
319
319
  /**
320
- * Poll (≤ INJECT_POLL_MAX_MS) until _safeToInject(), then run fn. On timeout: do NOT inject —
320
+ * Poll (≤ INJECT_POLL_MAX_MS) until the idle probe passes, then run fn. On timeout: do NOT inject —
321
321
  * invoke onTimeout instead (caller decides: keep queued / restore item). A timed-out blind
322
322
  * write could land in a TUI-native question prompt and be submitted as its answer.
323
323
  * Tick-counted (not Date-based) so mock.timers without Date mocking can drive it in tests.
324
+ *
325
+ * `probe` defaults to the global `_safeToInject`; anchor-targeted injects (injectCommand) pass
326
+ * their target-scoped probe so the poll watches the SAME workspace the initial check gated on.
324
327
  */
325
- function _pollUntilSafe(fn, onTimeout) {
328
+ function _pollUntilSafe(fn, onTimeout, probe) {
329
+ const isIdle = typeof probe === 'function' ? probe : _safeToInject;
326
330
  _clearPollTimer();
327
331
  const maxTicks = Math.ceil(INJECT_POLL_MAX_MS / INJECT_POLL_MS);
328
332
  let ticks = 0;
@@ -333,7 +337,7 @@ function _pollUntilSafe(fn, onTimeout) {
333
337
  if (onTimeout) onTimeout();
334
338
  return;
335
339
  }
336
- if (!_safeToInject()) return;
340
+ if (!isIdle()) return;
337
341
  _clearPollTimer();
338
342
  fn();
339
343
  }, INJECT_POLL_MS);
@@ -514,8 +518,48 @@ export function sendNow(id, anchor) {
514
518
  _restoreDispatch();
515
519
  };
516
520
 
521
+ // Busy check for the ITEM's own scope (anchor-scoped when available), not whichever PTY is
522
+ // globally active: a background workspace's streaming must not decide whether THIS target gets
523
+ // interrupted, and this target's streaming must not be masked by an idle global bucket (review:
524
+ // force compaction would otherwise paste /compact into a busy target without interrupting it).
525
+ const itemAnchor = item.anchor || null;
526
+ const _scopedProbes = itemAnchor && typeof _deps.isTurnActiveFor === 'function' && typeof _deps.isStreamingFor === 'function';
527
+ // Target-scoped idle probe for the poll/inject path: prefers the anchor-aware probes, plus the
528
+ // claude-TUI kind + approval/external-injection guards; falls back to the global _safeToInject
529
+ // when no scoped probe is wired. Mirrors _injectTextWhenIdle's targetIdle (review P1-1).
530
+ const idleProbe = _scopedProbes
531
+ ? (() => {
532
+ if (!_deps) return false;
533
+ if (_injecting) return false;
534
+ try {
535
+ if (_deps.isTurnActiveFor(itemAnchor)) return false;
536
+ if (_deps.isStreamingFor(itemAnchor)) return false;
537
+ if (typeof _deps.getPtyKindFor === 'function' && _deps.getPtyKindFor(itemAnchor) !== 'claude') return false;
538
+ if (_deps.hasPendingApproval && _deps.hasPendingApproval()) return false;
539
+ if (_deps.hasExternalInjection && _deps.hasExternalInjection()) return false;
540
+ } catch (err) { reportSwallowed('chat-queue.probe', err); return false; }
541
+ return true;
542
+ })
543
+ : _safeToInject;
517
544
  let streaming = false;
518
- try { streaming = !!(_deps.isStreaming && _deps.isStreaming()); } catch { streaming = false; }
545
+ try {
546
+ if (_scopedProbes) {
547
+ streaming = !!(_deps.isTurnActiveFor(itemAnchor) || _deps.isStreamingFor(itemAnchor));
548
+ } else {
549
+ streaming = !!(_deps.isStreaming && _deps.isStreaming());
550
+ }
551
+ } catch { streaming = false; }
552
+ // Pending-approval guard (regression): the anchor-scoped busy check treats "turn active while a
553
+ // tool approval is waiting" as streaming, but writing ESC here would cancel the user's pending
554
+ // approval prompt — the OLD global-isStreaming path never did that (API-call-level idle during an
555
+ // approval wait fell through to the idle poll). Don't touch the PTY while an approval is open;
556
+ // just poll until it's answered, then inject.
557
+ let pendingApproval = false;
558
+ try { pendingApproval = !!(_deps.hasPendingApproval && _deps.hasPendingApproval()); } catch { pendingApproval = false; }
559
+ if (streaming && pendingApproval) {
560
+ _pollUntilSafe(inject, restore, idleProbe);
561
+ return true;
562
+ }
519
563
  if (streaming) {
520
564
  // Interrupt the item's own session, not whichever PTY is globally active.
521
565
  const writeFocus = (data, tag) => {
@@ -540,14 +584,14 @@ export function sendNow(id, anchor) {
540
584
  _escTimer = null;
541
585
  if (gen !== _gen || !_dispatch || _dispatch.item.id !== item.id) return;
542
586
  if (writeFocus('\x1b', 'chat-queue.send-now.esc') === false) return;
543
- _pollUntilSafe(inject, restore);
587
+ _pollUntilSafe(inject, restore, idleProbe);
544
588
  }, STOP_ESC_DELAY_MS);
545
589
  if (typeof _escTimer.unref === 'function') _escTimer.unref();
546
- } else if (_safeToInject()) {
590
+ } else if (idleProbe()) {
547
591
  // Idle / parked queue (e.g. after Stop): no interrupt needed — inject right away.
548
592
  inject();
549
593
  } else {
550
- _pollUntilSafe(inject, restore);
594
+ _pollUntilSafe(inject, restore, idleProbe);
551
595
  }
552
596
  return true;
553
597
  }
@@ -594,50 +638,134 @@ export function stop() {
594
638
  const RESUME_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
595
639
 
596
640
  /**
597
- * True /resume (2026-10-06): inject `/resume <uuid>` into a target project's running claude
598
- * PTY so the process switches INTO that session in place (Claude Code's native SessionStart
599
- * hook then re-binds the v2 writer via beginResumeSwitch). This is the in-process switch —
600
- * NOT a respawn — and must only happen when the TUI is observably idle.
641
+ * Shared "inject a slash-command paste only when observably idle" core (2026-11).
642
+ * Owns the single `_dispatch`/`_injecting`/`_pollTimer` slot discipline: refuses up-front when
643
+ * any is owned (mirrors sendNow's guard) instead of clobbering a pending dispatch / drain poll
644
+ * and stranding a queued message.
601
645
  *
602
- * Promise-returning so the route can map the outcome to HTTP. Resolves:
603
- * { ok:true } — the paste was written
604
- * { ok:false, reason:'busy' } — TUI streaming / approval open / another inject, poll, or
605
- * dispatch in flight / timed out waiting for idle (never blind-injects)
606
- * { ok:false, reason:'bad-uuid' } — sessionUuid is not a UUID shape
607
- * { ok:false, reason:'no-deps' } — initChatQueue never ran (SDK mode / not wired)
608
- * { ok:false, reason:'write-failed' } — the PTY write failed or threw
646
+ * Anchor-targeted busy probe: when the caller passes an anchor AND deps expose the target-scoped
647
+ * probes (`isStreamingFor` / `getPtyKindFor`), the idle check is scoped to the TARGET workspace,
648
+ * not the globally-bound one (the generic `_safeToInject` reads the bound project's streaming
649
+ * state — a known multi-project limitation that would inject into a busy target or refuse an
650
+ * idle one). Falls back to the global probes when target-scoped ones are not wired.
609
651
  *
610
- * Shares the single `_injecting`/`_pollTimer`/`_dispatch` slots with the drain/sendNow paths,
611
- * so it refuses up-front when any is owned (mirrors sendNow's guard) instead of clobbering a
612
- * pending dispatch and stranding a queued message. The completion handler resets `_injecting`
613
- * unconditionally (both callback and catch) so a mid-inject clear()/stop() generation bump can
614
- * never wedge the queue.
652
+ * @param {string} text — already-validated command text (caller sanitizes/validates shape)
653
+ * @param {object|null} anchor — { project?, instanceKey? } routing target
654
+ * @param {object} [opts] — { strict:boolean } forwarded to writeToPtySequentialFor
655
+ * @returns Promise<{ok:true}|{ok:false,reason:'busy'|'no-deps'|'no-anchor'|'write-failed'}>
615
656
  */
616
- export function injectResumeCommand(sessionUuid, anchor) {
657
+ function _injectTextWhenIdle(text, anchor, { strict = false } = {}) {
617
658
  return new Promise((resolve) => {
618
659
  if (!_deps) { resolve({ ok: false, reason: 'no-deps' }); return; }
619
- const uuid = sanitizeInbound(String(sessionUuid == null ? '' : sessionUuid)).trim();
620
- if (!RESUME_UUID_RE.test(uuid)) { resolve({ ok: false, reason: 'bad-uuid' }); return; }
621
660
  // Refuse BEFORE touching _pollUntilSafe: a dispatch (even in its ESC-delay window) or a
622
661
  // drain's poll owns the single timer slots — barging in would strand a queued message.
623
662
  if (_dispatch || _injecting || _pollTimer) { resolve({ ok: false, reason: 'busy' }); return; }
663
+
664
+ // Target-scoped idle check. Uses the anchor-aware probes when available; falls back to the
665
+ // global _safeToInject otherwise. Never falls through to an inject on a throwing probe.
666
+ // - isStreamingFor(anchor) → target scope streaming (server wires streamingStateFor(scopeKeyOf(...)))
667
+ // - isTurnActiveFor(anchor) → target scope turn-level busy (turnStateFor); a turn-level truth
668
+ // covers the per-API-call flicker gap the streaming probe has.
669
+ // - getPtyKindFor(anchor) → target is a claude TUI
670
+ const targetIdle = () => {
671
+ if (!_deps) return false;
672
+ if (_injecting) return false;
673
+ try {
674
+ if (typeof _deps.isTurnActiveFor === 'function' && _deps.isTurnActiveFor(anchor)) return false;
675
+ if (typeof _deps.isStreamingFor === 'function' && _deps.isStreamingFor(anchor)) return false;
676
+ if (typeof _deps.getPtyKindFor === 'function' && _deps.getPtyKindFor(anchor) !== 'claude') return false;
677
+ // Fall back to the global probes only when no scoped probe is wired at all.
678
+ if (typeof _deps.isStreamingFor !== 'function' && typeof _deps.isTurnActiveFor !== 'function') {
679
+ if (_deps.getPtyKind && _deps.getPtyKind() !== 'claude') return false;
680
+ if (_deps.isStreaming && _deps.isStreaming()) return false;
681
+ }
682
+ if (_deps.hasPendingApproval && _deps.hasPendingApproval()) return false;
683
+ if (_deps.hasExternalInjection && _deps.hasExternalInjection()) return false;
684
+ } catch (err) { reportSwallowed('chat-queue.probe', err); return false; }
685
+ return true;
686
+ };
687
+
624
688
  let settled = false;
625
689
  const done = (r) => { if (!settled) { settled = true; resolve(r); } };
626
690
  const inject = () => {
627
691
  _injecting = true;
628
692
  try {
629
- _deps.writeToPtySequentialFor(bracketPasteSubmit(`/resume ${uuid}`), (ok) => {
693
+ _deps.writeToPtySequentialFor(bracketPasteSubmit(text), (ok) => {
630
694
  _injecting = false;
631
695
  done(ok ? { ok: true } : { ok: false, reason: 'write-failed' });
632
- }, { settleMs: 250 }, anchor || {});
696
+ }, { settleMs: 250, strict }, anchor || {});
633
697
  } catch (err) {
634
698
  _injecting = false;
635
- reportSwallowed('chat-queue.resume.inject', err);
699
+ reportSwallowed('chat-queue.inject', err);
636
700
  done({ ok: false, reason: 'write-failed' });
637
701
  }
638
702
  };
639
- if (_safeToInject()) { inject(); return; }
640
- _pollUntilSafe(inject, () => done({ ok: false, reason: 'busy' }));
703
+ if (targetIdle()) { inject(); return; }
704
+ _pollUntilSafe(inject, () => done({ ok: false, reason: 'busy' }), targetIdle);
705
+ });
706
+ }
707
+
708
+ /**
709
+ * True /resume (2026-10-06): inject `/resume <uuid>` into a target project's running claude
710
+ * PTY so the process switches INTO that session in place (Claude Code's native SessionStart
711
+ * hook then re-binds the v2 writer via beginResumeSwitch). This is the in-process switch —
712
+ * NOT a respawn — and must only happen when the TUI is observably idle.
713
+ *
714
+ * Promise-returning so the route can map the outcome to HTTP. Resolves:
715
+ * { ok:true } — the paste was written
716
+ * { ok:false, reason:'busy' } — TUI streaming / approval open / another inject, poll, or
717
+ * dispatch in flight / timed out waiting for idle (never blind-injects)
718
+ * { ok:false, reason:'bad-uuid' } — sessionUuid is not a UUID shape
719
+ * { ok:false, reason:'no-deps' } — initChatQueue never ran (SDK mode / not wired)
720
+ * { ok:false, reason:'write-failed' } — the PTY write failed or threw
721
+ */
722
+ export function injectResumeCommand(sessionUuid, anchor) {
723
+ if (!_deps) return Promise.resolve({ ok: false, reason: 'no-deps' });
724
+ const uuid = sanitizeInbound(String(sessionUuid == null ? '' : sessionUuid)).trim();
725
+ if (!RESUME_UUID_RE.test(uuid)) return Promise.resolve({ ok: false, reason: 'bad-uuid' });
726
+ return _injectTextWhenIdle(`/resume ${uuid}`, anchor);
727
+ }
728
+
729
+ const COMPACT_CMD_RE = /^\/compact(\s|$)/;
730
+ const INJECT_CMD_MAX_LEN = 20000;
731
+
732
+ /**
733
+ * Inject a `/compact <script>` (context compaction) command into the anchored claude PTY.
734
+ * Stricter than injectResumeCommand on routing: strict:true is ALWAYS passed so an unresolved /
735
+ * dead anchor fails (`target-gone`/`write-failed`) instead of falling back to the active PTY and
736
+ * compacting the WRONG conversation (review P0). The target is also liveness-probed up front, and
737
+ * a non-empty FIFO for the same scope returns `busy` (compaction must not jump ahead of queued
738
+ * user messages).
739
+ *
740
+ * Resolves:
741
+ * { ok:true } — the paste was written to the anchored PTY
742
+ * { ok:false, reason:'busy' } — target busy / slot owned / poll timeout (retryable)
743
+ * { ok:false, reason:'target-gone' } — anchor resolves to no live claude PTY
744
+ * { ok:false, reason:'bad-text' } — not a `/compact` command / empty / over-length
745
+ * { ok:false, reason:'no-anchor' } — no project/instance routing key supplied
746
+ * { ok:false, reason:'no-deps' } — initChatQueue never ran (SDK mode / not wired)
747
+ * { ok:false, reason:'write-failed'} — the PTY write failed or threw
748
+ */
749
+ export function injectCommand(text, anchor) {
750
+ return new Promise((resolve) => {
751
+ if (!_deps) { resolve({ ok: false, reason: 'no-deps' }); return; }
752
+ const clean = sanitizeInbound(String(text == null ? '' : text)).trim();
753
+ if (!clean || clean.length > INJECT_CMD_MAX_LEN || !COMPACT_CMD_RE.test(clean)) { resolve({ ok: false, reason: 'bad-text' }); return; }
754
+ const a = anchor && typeof anchor === 'object' ? anchor : null;
755
+ if (!a || !(a.project || a.instanceKey)) { resolve({ ok: false, reason: 'no-anchor' }); return; }
756
+ // Liveness pre-flight: a dead/mis-resolved target never enters the poll loop.
757
+ if (typeof _deps.hasLivePtyFor === 'function') {
758
+ let live;
759
+ try { live = _deps.hasLivePtyFor(a); } catch (err) { reportSwallowed('chat-queue.liveness-probe', err); live = undefined; }
760
+ if (live === false) { resolve({ ok: false, reason: 'target-gone' }); return; }
761
+ }
762
+ // Fairness: refuse to jump ahead of queued user messages for the same scope.
763
+ if (typeof _deps.getQueueSnapshot === 'function') {
764
+ let qlen = 0;
765
+ try { const snap = _deps.getQueueSnapshot(a); qlen = Array.isArray(snap) ? snap.length : 0; } catch (err) { reportSwallowed('chat-queue.queue-probe', err); qlen = 0; }
766
+ if (qlen > 0) { resolve({ ok: false, reason: 'busy' }); return; }
767
+ }
768
+ resolve(_injectTextWhenIdle(clean, a, { strict: true }));
641
769
  });
642
770
  }
643
771
 
@@ -0,0 +1,100 @@
1
+ /**
2
+ * compact-inject-guard.js — per-scope dedup gate for "context compaction injection".
3
+ *
4
+ * When multiple tabs/devices watch the same session, the confirm bar may be clicked on
5
+ * both ends at once. This module dedups server-side by "resolved target identity" so a
6
+ * single confirmation injects only once:
7
+ * - inFlight: holds the scope from injection start until ack; concurrent requests
8
+ * inside the window are judged duplicate (not sent again)
9
+ * - lastSuccessAt: keeps a time window after a successful injection, blocking late
10
+ * duplicate confirmations from the other end while compaction runs
11
+ * (compaction itself is a tens-of-seconds LLM call)
12
+ *
13
+ * busy/failure releases immediately (does not hold the window), so genuine retries pass right away.
14
+ * In-memory only, single process (module-level singleton in server.js); each Electron tab is
15
+ * an independent server subprocess, so no cross-process handling needed.
16
+ */
17
+
18
+ export function createCompactInjectGuard({ successWindowMs = 60000 } = {}) {
19
+ /** scopeKey -> { inFlight:boolean, lastSuccessAt:number } */
20
+ const scopes = new Map();
21
+
22
+ function _entry(scopeKey) {
23
+ let e = scopes.get(scopeKey);
24
+ if (!e) { e = { inFlight: false, lastSuccessAt: 0 }; scopes.set(scopeKey, e); }
25
+ return e;
26
+ }
27
+
28
+ /**
29
+ * Try to acquire the injection right for a scope. Returns:
30
+ * { allowed:true } — this call acquired the right (must commit or release afterwards)
31
+ * { allowed:false, inFlight:true } — an injection is already in flight (retryable; frontend should reply busy, not fake success)
32
+ * { allowed:false, duplicate:true } — still inside the window since the last success (already injected; frontend treats as success)
33
+ */
34
+ function tryBegin(scopeKey, now = Date.now()) {
35
+ if (!scopeKey) return { allowed: false, duplicate: false, badScope: true };
36
+ const e = _entry(scopeKey);
37
+ // In-flight ≠ succeeded: the PTY lock holder may still be polling for idle; if it ends up
38
+ // busy/failed, treating it as duplicate would fake success on the other end (nothing was
39
+ // actually injected). Distinguish the two: in-flight returns inFlight (retryable).
40
+ if (e.inFlight) return { allowed: false, inFlight: true };
41
+ if (e.lastSuccessAt && now - e.lastSuccessAt < successWindowMs) return { allowed: false, duplicate: true };
42
+ e.inFlight = true;
43
+ return { allowed: true };
44
+ }
45
+
46
+ /** Injection failed / busy: release the in-flight slot without recording a success time, allowing immediate retry. */
47
+ function release(scopeKey) {
48
+ const e = scopes.get(scopeKey);
49
+ if (e) e.inFlight = false;
50
+ }
51
+
52
+ /** Injection succeeded: release the in-flight slot and record the success time (enters the successWindowMs dedup window). */
53
+ function commit(scopeKey, now = Date.now()) {
54
+ const e = _entry(scopeKey);
55
+ e.inFlight = false;
56
+ e.lastSuccessAt = now;
57
+ }
58
+
59
+ /** Revoke an "optimistic success" (early not-delivered rollback after SDK ack-on-acceptance):
60
+ * clears both the in-flight slot and the success window so genuine retries are not judged duplicate. */
61
+ function rollback(scopeKey) {
62
+ const e = scopes.get(scopeKey);
63
+ if (e) { e.inFlight = false; e.lastSuccessAt = 0; }
64
+ }
65
+
66
+ /** Called after observing a compaction event / the next turn end: clears the success window,
67
+ * allowing the next decision. minAgeMs: windows younger than this are kept — prevents the
68
+ * interrupted round's result from prematurely clearing the success window just established by
69
+ * a forced compaction, which would let multiple tabs slip through and chain forced compactions (review P1-3). */
70
+ function clearSuccess(scopeKey, { minAgeMs = 0, now = Date.now() } = {}) {
71
+ const e = scopes.get(scopeKey);
72
+ if (!e) return;
73
+ if (minAgeMs > 0 && e.lastSuccessAt && now - e.lastSuccessAt < minAgeMs) return;
74
+ e.lastSuccessAt = 0;
75
+ }
76
+
77
+ /** Clear success windows by project: clears the project-level key and all `${project}\0<instance>` instance keys.
78
+ * On the PTY turn-end production side the scope is already normalized (instances folded away), while the
79
+ * injecting guard's key carries the instance stamp; the mismatch would leave the 60s window unreleased by
80
+ * turn end (review P2-2). turn-end calls this function instead.
81
+ * Also prunes fully idle entries (inFlight=false and lastSuccessAt=0) to keep the Map bounded (P3).
82
+ * minAgeMs: same as clearSuccess; protects a freshly established success window from early release. */
83
+ function clearProject(project, { minAgeMs = 0, now = Date.now() } = {}) {
84
+ if (!project) return;
85
+ for (const [key, e] of scopes) {
86
+ // Matches the project-level key (project itself) or instance keys (`${project}\0<instance>`); the \0 boundary prevents false matches on projects sharing a name prefix.
87
+ if (key === project || key.startsWith(`${project}\0`)) {
88
+ // Windows younger than minAgeMs are kept (compaction still running), not cleared.
89
+ const tooFresh = minAgeMs > 0 && e && e.lastSuccessAt && now - e.lastSuccessAt < minAgeMs;
90
+ if (e && !tooFresh) e.lastSuccessAt = 0;
91
+ // Reclaim fully idle entries (not in flight, no success window) to avoid one resident entry per instance.
92
+ if (e && !e.inFlight && !e.lastSuccessAt) scopes.delete(key);
93
+ }
94
+ }
95
+ }
96
+
97
+ function reset() { scopes.clear(); }
98
+
99
+ return { tryBegin, release, commit, rollback, clearSuccess, clearProject, reset };
100
+ }