cc-viewer 1.9.37 → 1.9.39

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 (29) hide show
  1. package/README.md +4 -0
  2. package/cli.js +4 -0
  3. package/dist/assets/App-CpjhCyrl.js +2 -0
  4. package/dist/assets/App-DwLJPKiz.css +1 -0
  5. package/dist/assets/{ArchivePreview-BBXuZnGC.js → ArchivePreview-BHhhDCbz.js} +1 -1
  6. package/dist/assets/{AudioPreview-BmqzQZGt.js → AudioPreview-B0A6FVQc.js} +1 -1
  7. package/dist/assets/{MdxEditorPanel-BLcS9OVC.js → MdxEditorPanel-CEZPc4wd.js} +1 -1
  8. package/dist/assets/{Mobile-4mZy680Y.js → Mobile-B6az-Lrt.js} +1 -1
  9. package/dist/assets/{ProxyStatsModal-BDLwkqxD.js → ProxyStatsModal-B2PEO1Bm.js} +1 -1
  10. package/dist/assets/{SubtitlePreview-ei5OtiKq.js → SubtitlePreview-Ca7FKVpv.js} +1 -1
  11. package/dist/assets/index-DMmTEKEL.js +2 -0
  12. package/dist/assets/seqResourceLoaders-BJEa97Uq.js +2 -0
  13. package/dist/assets/seqResourceLoaders-BdxjrasH.css +41 -0
  14. package/dist/index.html +1 -1
  15. package/node_modules/@ccv/core/src/sdk-task-label.js +70 -0
  16. package/package.json +1 -1
  17. package/server/lib/chat-queue.js +159 -31
  18. package/server/lib/compact-inject-guard.js +100 -0
  19. package/server/lib/project-prefs.js +3 -2
  20. package/server/lib/sdk-manager.js +113 -2
  21. package/server/lib/task-state.js +11 -0
  22. package/server/routes/preferences.js +9 -2
  23. package/server/routes/project-prefs.js +6 -0
  24. package/server/server.js +207 -0
  25. package/dist/assets/App-BJIeZQK0.css +0 -1
  26. package/dist/assets/App-C_AI6A4g.js +0 -2
  27. package/dist/assets/index-CVnJzK-y.js +0 -2
  28. package/dist/assets/seqResourceLoaders-BT5ki0J4.js +0 -2
  29. package/dist/assets/seqResourceLoaders-CXgVOdgW.css +0 -41
package/dist/index.html CHANGED
@@ -21,7 +21,7 @@
21
21
  // 整体显示大小已弃用 CSS zoom:Electron 改用 webFrame.setZoomFactor(首屏抢占见
22
22
  // electron/tab-content-preload.js),纯浏览器交由用户用浏览器自带快捷键缩放,故此处不再设 zoom。
23
23
  </script>
24
- <script type="module" crossorigin src="./assets/index-CVnJzK-y.js"></script>
24
+ <script type="module" crossorigin src="./assets/index-DMmTEKEL.js"></script>
25
25
  <link rel="modulepreload" crossorigin href="./assets/vendor-antd-BciJO790.js">
26
26
  <link rel="modulepreload" crossorigin href="./assets/vendor-codemirror-BVX6n7ix.js">
27
27
  <link rel="modulepreload" crossorigin href="./assets/vendor-mdxeditor-BlcXEhaG.js">
@@ -0,0 +1,70 @@
1
+ /**
2
+ * sdk-task-label.js — shared predicate for "does this task entry carry a
3
+ * user-visible label?" Used by:
4
+ * - server `getSdkTaskSnapshot` (packages/app/server/lib/sdk-manager.js)
5
+ * - client `sdkTaskTracker.applySnapshot` (apps/web/src/utils/sdkTaskTracker.js)
6
+ * - client `sdkTaskTracker.restoreFromStorage` (apps/web/src/utils/sdkTaskTracker.js)
7
+ *
8
+ * Field-name mapping (two names for the same concept, one per shape):
9
+ * wire / server table : description = task title/text (started/progress frames)
10
+ * summary = terminal notification's result text
11
+ * client tracker : subject = task title/text (from wire description)
12
+ * description = terminal result text (from wire summary)
13
+ *
14
+ * "Label-less" = no displayable label on any field. A row is label-less iff
15
+ * NEITHER field has any displayable text (null/undefined/empty/whitespace-only).
16
+ * Truthiness-based after trim — a `description: ''` or `summary: ''` is as
17
+ * label-less as an absent field. NOTE: the HUD uses `||` for the label chain,
18
+ * so a whitespace-only label that passes this predicate (because the OTHER
19
+ * field has text) will render as blank — a known, deliberate asymmetry (the
20
+ * fallback to `#id` is a last resort; we prefer a blank-but-real row to a
21
+ * fabricated one).
22
+ *
23
+ * Realistic label-less origins (server side, post fold-bug fix):
24
+ * - a `task_updated` frame whose patch lacks `description` landing as the
25
+ * FIRST frame for its taskId (e.g. the server table was reset / evicted
26
+ * and a status-only update arrives for a still-running task);
27
+ * - a `task_notification` frame with NO summary and no description arriving
28
+ * without its task_started (a frame lost in a WS gap).
29
+ * A `task_notification`-only entry WITH `summary` is NOT label-less — it is
30
+ * exactly what the HUD fallback (`subject || description || #id`) relabels.
31
+ *
32
+ * Filter scope (post P2 decision): the label-less filter is applied to
33
+ * TERMINAL entries only (`status` in {completed, failed, stopped, killed} on
34
+ * the wire, `status` in {completed, failed} on the client). An in-flight
35
+ * task whose only frames are status-only task_updated patches is still a
36
+ * live task; filtering it would hide it from a reconnect replay with no way
37
+ * for later deltas to re-label it.
38
+ */
39
+
40
+ function _hasText(v) {
41
+ return typeof v === 'string' && v.trim().length > 0;
42
+ }
43
+
44
+ const _WIRE_TERMINAL = new Set(['completed', 'failed', 'stopped', 'killed']);
45
+ const _CLIENT_TERMINAL = new Set(['completed', 'failed']);
46
+
47
+ /**
48
+ * Wire-shape predicate (server table entries / sdk-task-snapshot payloads).
49
+ * @param {object} t - { description?, summary?, status?, terminal? }
50
+ * @returns {boolean} true iff the entry has at least one displayable label
51
+ * field OR is not terminal (in-flight entries stay visible regardless).
52
+ */
53
+ export function hasWireTaskLabel(t) {
54
+ if (!t || typeof t !== 'object') return false;
55
+ const terminal = t.terminal === true || _WIRE_TERMINAL.has(t.status);
56
+ if (!terminal) return true; // in-flight rows stay regardless of label
57
+ return _hasText(t.description) || _hasText(t.summary);
58
+ }
59
+
60
+ /**
61
+ * Client-shape predicate (taskStore / sdkTaskTracker rows).
62
+ * @param {object} t - { subject?, description?, status? }
63
+ * @returns {boolean} true iff the row has at least one displayable label
64
+ * field OR is not terminal.
65
+ */
66
+ export function hasTrackerTaskLabel(t) {
67
+ if (!t || typeof t !== 'object') return false;
68
+ if (!_CLIENT_TERMINAL.has(t.status)) return true; // in-flight rows stay
69
+ return _hasText(t.subject) || _hasText(t.description);
70
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cc-viewer",
3
- "version": "1.9.37",
3
+ "version": "1.9.39",
4
4
  "description": "Claude Code logging, visualization, and management toolkit — launch a web viewer alongside Claude Code with full request/response tracing, proxy, and mobile support",
5
5
  "license": "MIT",
6
6
  "main": "server.js",
@@ -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
+ }
@@ -14,8 +14,9 @@ import { listPlatforms } from './im/im-config.js';
14
14
  import { getProjectName } from './project-state.js';
15
15
 
16
16
  // SINGLE SOURCE of "what must never live inside a fork": secrets (auth password + IM creds),
17
- // machine-level paths (logDir/claudeConfigDir), and the internal forks map. snapshotForFork /
18
- // cleanPatch / the admin list read all funnel through stripSensitive so the rule can't drift.
17
+ // machine-level paths (logDir/claudeConfigDir), the internal forks map, and global-only features
18
+ // that must stay identical across every project (scheduledTasks). snapshotForFork / cleanPatch /
19
+ // the admin list read all funnel through stripSensitive so the rule can't drift.
19
20
  const STRIP_KEYS = ['auth', 'authByProject', 'prefsByProject', 'logDir', 'claudeConfigDir', 'scheduledTasks'];
20
21
 
21
22
  /** Strip secrets + IM credentials + machine-level keys from a prefs-shaped object in place. */
@@ -39,6 +39,7 @@ import { seedSessionProxyProfile, clearSessionProxyProfile, clearSessionProxyPro
39
39
  import { readPrefsRaw } from './prefs-store.js';
40
40
  import { projectKeyForCwd } from './system-prompt-snapshots.js';
41
41
  import { AGENT_PROMPT_SNIPPET_LEN } from '@ccv/core/contentFilter';
42
+ import { hasWireTaskLabel } from '@ccv/core/sdk-task-label';
42
43
  import {
43
44
  computeAutoApprove,
44
45
  createAutoApproveState,
@@ -473,6 +474,21 @@ function _normalizeSdkTask(msg) {
473
474
  const _SDK_TASK_TERMINAL = new Set(['completed', 'failed', 'stopped', 'killed']);
474
475
  function _foldSdkTask(prev, frame) {
475
476
  const next = { ...(prev || {}), taskId: frame.taskId };
477
+ // A task_started re-fire opens a NEW run for this taskId (the client tracker
478
+ // does the same — sdkTaskTracker.js resets status to in_progress on re-fire,
479
+ // "a task id may be reused after session reset or completion"). Reset the
480
+ // run-scoped fields so a previous incarnation's terminal state does not leak
481
+ // into the new run: a status-only task_notification/summary/usage/endTime
482
+ // from the old run must not survive, and the new run starts in 'running'.
483
+ // Without this, merge semantics (post fold-bug fix) would let `completed`
484
+ // stick across the re-fire, and the next reconnect replay would clobber the
485
+ // client's correct in_progress row back to the stale terminal one.
486
+ if (frame.subtype === 'task_started') {
487
+ delete next.status;
488
+ delete next.summary;
489
+ delete next.usage;
490
+ delete next.endTime;
491
+ }
476
492
  if (frame.sessionId != null) next.sessionId = frame.sessionId;
477
493
  if (frame.toolUseId != null) next.toolUseId = frame.toolUseId;
478
494
  if (frame.taskType != null) next.taskType = frame.taskType;
@@ -1820,8 +1836,13 @@ function _createSession(cwd, { freshKey = false } = {}) {
1820
1836
  _sdkTaskTable = new Map();
1821
1837
  _sdkTaskTableSessionId = sdkTaskFrame.sessionId;
1822
1838
  }
1839
+ // Read prev BEFORE the LRU delete — otherwise _foldSdkTask always
1840
+ // sees undefined and "merge" silently becomes "replace", wiping the
1841
+ // started frame's description/toolUseId/promptSnippet on any
1842
+ // status-only task_updated / task_notification.
1843
+ const prev = _sdkTaskTable.get(sdkTaskFrame.taskId);
1823
1844
  _sdkTaskTable.delete(sdkTaskFrame.taskId); // re-insert for LRU order
1824
- _sdkTaskTable.set(sdkTaskFrame.taskId, _foldSdkTask(_sdkTaskTable.get(sdkTaskFrame.taskId), sdkTaskFrame));
1845
+ _sdkTaskTable.set(sdkTaskFrame.taskId, _foldSdkTask(prev, sdkTaskFrame));
1825
1846
  while (_sdkTaskTable.size > _SDK_TASK_TABLE_CAP) {
1826
1847
  const oldest = _sdkTaskTable.keys().next().value;
1827
1848
  _sdkTaskTable.delete(oldest);
@@ -2836,6 +2857,39 @@ function _createSession(cwd, { freshKey = false } = {}) {
2836
2857
  return [];
2837
2858
  }
2838
2859
 
2860
+ /**
2861
+ * 960K forced compaction only: skips the idle gate and directly "enqueues one + send-now immediately",
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
+ * Reuses _sendQueuedNow's full lifecycle (occupies the dispatch slot / _interruptTurn / _suppressDrain reset),
2864
+ * avoiding the naive "interrupt + sendUserMessage" combination getting the message stuck in the queue (_interruptTurn sets
2865
+ * _suppressDrain=true, and busy enqueue does not reset it). Returns _sendQueuedNow's result (the cancelled list).
2866
+ */
2867
+ function _forceSendUserMessage(text) {
2868
+ if (!_query) throw new Error('Agent SDK not available');
2869
+ // The dispatch slot is owned by another in-flight send-now/drain: forcing now would have to
2870
+ // preempt THAT, which the queue model forbids. Enqueue-then-send-now would silently park the
2871
+ // /compact at the FIFO tail and still look like a success upstream (the "fake success" the
2872
+ // rollback path exists to prevent). Fail fast so the caller reports a real, retryable failure.
2873
+ if (_dispatching) {
2874
+ const err = new Error('force-send while another message is dispatching');
2875
+ err.code = 'busy';
2876
+ throw err;
2877
+ }
2878
+ const item = _makeQueueItem(text);
2879
+ _messageQueue.push(item);
2880
+ const cancelled = _sendQueuedNow(item.id);
2881
+ // _sendQueuedNow succeeded only if it actually took the dispatch slot (item no longer queued).
2882
+ const stillQueued = _messageQueue.some((it) => it.id === item.id);
2883
+ if (stillQueued) {
2884
+ // Defensive: slot was free a moment ago but the item wasn't dispatched — don't leave a ghost.
2885
+ _messageQueue = _messageQueue.filter((it) => it.id !== item.id);
2886
+ const err = new Error('force-send did not take the dispatch slot');
2887
+ err.code = 'busy';
2888
+ throw err;
2889
+ }
2890
+ return { ok: true, cancelled: Array.isArray(cancelled) ? cancelled : [] };
2891
+ }
2892
+
2839
2893
  /** Remove one queued message (bubble ×). Returns true when found. The dispatching
2840
2894
  * item is locked until _startTurn accepts it: reject and re-broadcast so a stale
2841
2895
  * enabled bubble converges instead of silently dropping a message mid-commit. */
@@ -3016,6 +3070,7 @@ function _createSession(cwd, { freshKey = false } = {}) {
3016
3070
  sendUserMessage: _sendUserMessage,
3017
3071
  interruptTurn: _interruptTurn,
3018
3072
  sendQueuedNow: _sendQueuedNow,
3073
+ forceSendUserMessage: _forceSendUserMessage,
3019
3074
  removeQueued: _removeQueued,
3020
3075
  clearQueued: _clearQueued,
3021
3076
  getQueueSnapshot: _getQueueSnapshot,
@@ -3029,6 +3084,26 @@ function _createSession(cwd, { freshKey = false } = {}) {
3029
3084
  const head = _pendingTurns[0] || null;
3030
3085
  return { type: 'sdk-session-state', state: _lastSessionState, sessionId: _sessionId || null, cwd: _cwd, instanceKey, turnId: _currentTurnId(), turnStartedAt: head ? head.startedAt : _lastTurnStartedAt, pendingApprovals: _pendingApprovals.size };
3031
3086
  },
3087
+ // Atomic "can a turn start immediately" gate snapshot (used by compact injection etc.): returns all fields needed for live busy/idle in one call.
3088
+ // Difference from getSessionStateSnapshot: state is derived from the live `_queryBusy`/`_pendingTurns`,
3089
+ // not `_lastSessionState` (the latter still lingers at 'idle' during _startTurn's ensure window, causing misjudgment).
3090
+ // When a fresh/resume session has not announced yet, _lastSessionState is null → state is derived as 'idle'
3091
+ // (in that case _queryBusy/_pendingTurns are the truth for busy/idle).
3092
+ getTurnGate: () => {
3093
+ const queueLen = _getQueueSnapshot().length;
3094
+ const busy = _queryBusy || _pendingTurns.length > 0;
3095
+ const pendingApprovals = _pendingApprovals.size;
3096
+ return {
3097
+ exists: true,
3098
+ state: busy ? 'running' : (_lastSessionState || 'idle'),
3099
+ turnId: _currentTurnId(),
3100
+ pendingApprovals,
3101
+ queueLen,
3102
+ instanceKey,
3103
+ // Judgment for injecting a turn immediately: idle + no turn in flight + no pending approval + empty queue.
3104
+ idle: !busy && pendingApprovals === 0 && queueLen === 0,
3105
+ };
3106
+ },
3032
3107
  getContextUsageSnapshot: () => _lastContextUsage,
3033
3108
  getMcpStatusSnapshot: () => _lastMcpStatus,
3034
3109
  getSkillsSnapshot: () => _lastSkillsSnapshot,
@@ -3038,12 +3113,21 @@ function _createSession(cwd, { freshKey = false } = {}) {
3038
3113
  // otherwise a client that missed the session boundary keeps its stale agents.
3039
3114
  // skipTranscript entries are tracked (they carry the session boundary) but hidden
3040
3115
  // from the replay, matching the live path that never shows ambient tasks.
3116
+ // Label-less TERMINAL entries are also hidden: the predicate (hasWireTaskLabel)
3117
+ // is shared with the client tracker and treats null/empty/whitespace-only
3118
+ // description+summary as "no label" — a terminal ghost would render as a bare
3119
+ // `#id` on the HUD with no live update to relabel it. In-flight entries stay
3120
+ // visible regardless of label so a later task_progress(description) frame
3121
+ // can still enrich them. Label-less entries still live in the table for
3122
+ // session-boundary detection and LRU bookkeeping; the filter only spares
3123
+ // the replay payload.
3041
3124
  getSdkTaskSnapshot: () => ({
3042
3125
  type: 'sdk-task-snapshot',
3043
3126
  cwd: _cwd,
3044
3127
  instanceKey,
3045
3128
  sessionId: _sdkTaskTableSessionId,
3046
- tasks: [..._sdkTaskTable.values()].filter((t) => t.skipTranscript !== true),
3129
+ tasks: [..._sdkTaskTable.values()].filter((t) =>
3130
+ t.skipTranscript !== true && hasWireTaskLabel(t)),
3047
3131
  }),
3048
3132
  fetchContextUsage: async () => {
3049
3133
  // On-demand fetch for the HTTP route: refresh the snapshot, broadcast to all clients,
@@ -3421,6 +3505,21 @@ export function sendQueuedNow(id, anchor) {
3421
3505
  return sess ? sess.sendQueuedNow(id) : [];
3422
3506
  }
3423
3507
 
3508
+ /** 960K forced compaction: interrupt the current turn and inject one message immediately (routed to the anchor's session). */
3509
+ export function forceSendUserMessage(text, anchor) {
3510
+ if (!_query) throw new Error('Agent SDK not available');
3511
+ const sess = anchor ? _sessionForAnchor(anchor, { allowPrimaryFallback: true }) : _active();
3512
+ if (!sess) {
3513
+ const targetName = (anchor && (anchor.cwd || anchor.project || anchor.instanceKey)) || 'active';
3514
+ console.warn(`[sdk-manager] no SDK session for force-send to "${targetName}"`);
3515
+ const err = new Error('no SDK session for force send');
3516
+ err.code = 'not-delivered';
3517
+ throw err;
3518
+ }
3519
+ if (anchor && sess.instanceKey !== _activeKey) _activeKey = sess.instanceKey;
3520
+ return sess.forceSendUserMessage(text);
3521
+ }
3522
+
3424
3523
  /** Remove one queued message of the ACTIVE session (or an anchor's session —
3425
3524
  * a targeted action; does not switch active). */
3426
3525
  export function removeQueued(id, anchor) {
@@ -3663,6 +3762,18 @@ export function getSessionStateSnapshot(anchor) {
3663
3762
  return sess ? sess.getSessionStateSnapshot() : null;
3664
3763
  }
3665
3764
 
3765
+ /**
3766
+ * Atomic "can a turn start right now" gate for the anchored session (compaction inject).
3767
+ * Resolved with allowPrimaryFallback:true — the SAME resolver sendUserMessage uses — so the
3768
+ * gate's target is the session a send would actually land on (a same-cwd ambiguous project
3769
+ * anchor resolves to the primary rather than reporting "no session"). Returns null when the
3770
+ * anchor resolves to no registered session (callers treat that as not-idle / target-gone).
3771
+ */
3772
+ export function getTurnGate(anchor) {
3773
+ const sess = anchor ? _sessionForAnchor(anchor, { allowPrimaryFallback: true }) : _active();
3774
+ return sess ? sess.getTurnGate() : null;
3775
+ }
3776
+
3666
3777
  /** WS reconnect replay getter for the context-usage frame. No anchor → active session. */
3667
3778
  export function getContextUsageSnapshot(anchor) {
3668
3779
  const sess = anchor ? _sessionForAnchor(anchor) : _active();