cc-viewer 1.9.37 → 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.
- package/README.md +4 -0
- package/cli.js +4 -0
- package/dist/assets/App-CF8BZExv.js +2 -0
- package/dist/assets/App-DwLJPKiz.css +1 -0
- package/dist/assets/{ArchivePreview-BBXuZnGC.js → ArchivePreview-BwkACTcN.js} +1 -1
- package/dist/assets/{AudioPreview-BmqzQZGt.js → AudioPreview-Bzzv-8w2.js} +1 -1
- package/dist/assets/{MdxEditorPanel-BLcS9OVC.js → MdxEditorPanel-DgInZmjn.js} +1 -1
- package/dist/assets/Mobile-BwxpuUXE.js +1 -0
- package/dist/assets/{ProxyStatsModal-BDLwkqxD.js → ProxyStatsModal-C0EVF31b.js} +1 -1
- package/dist/assets/{SubtitlePreview-ei5OtiKq.js → SubtitlePreview-D3MhYKJS.js} +1 -1
- package/dist/assets/{_baseUniq-xRiWMqOw.js → _baseUniq-uUw7d1E3.js} +1 -1
- package/dist/assets/{arc-edNwlWnI.js → arc-BOWuMiV4.js} +1 -1
- package/dist/assets/{architectureDiagram-Q4EWVU46-SMfdtr57.js → architectureDiagram-Q4EWVU46-h5aWPWJ4.js} +1 -1
- package/dist/assets/{blockDiagram-DXYQGD6D-BxAsQG58.js → blockDiagram-DXYQGD6D-CudvZcvo.js} +1 -1
- package/dist/assets/{c4Diagram-AHTNJAMY-DvEHTYBD.js → c4Diagram-AHTNJAMY-DYlZi3dM.js} +1 -1
- package/dist/assets/{channel-Ce5Cf3nY.js → channel-XJqusGHw.js} +1 -1
- package/dist/assets/{chunk-4BX2VUAB--OnGvs-9.js → chunk-4BX2VUAB-CLpyEaWp.js} +1 -1
- package/dist/assets/{chunk-4TB4RGXK-MSrYeKo5.js → chunk-4TB4RGXK-BAuE3fNK.js} +1 -1
- package/dist/assets/{chunk-55IACEB6-CD4rh-7b.js → chunk-55IACEB6-B4tW65z_.js} +1 -1
- package/dist/assets/{chunk-EDXVE4YY-CrAxlPfF.js → chunk-EDXVE4YY-Bb7xoST0.js} +1 -1
- package/dist/assets/{chunk-FMBD7UC4-CMb4qB5t.js → chunk-FMBD7UC4-CTkqi9Np.js} +1 -1
- package/dist/assets/{chunk-OYMX7WX6-CEP3GJND.js → chunk-OYMX7WX6-uQdTKgLj.js} +1 -1
- package/dist/assets/{chunk-QZHKN3VN-Xko480I7.js → chunk-QZHKN3VN-C6ugcDBb.js} +1 -1
- package/dist/assets/{chunk-YZCP3GAM-xKPv2jAr.js → chunk-YZCP3GAM-Hp9H2dEu.js} +1 -1
- package/dist/assets/classDiagram-6PBFFD2Q-CqAo3MbD.js +1 -0
- package/dist/assets/classDiagram-v2-HSJHXN6E-CqAo3MbD.js +1 -0
- package/dist/assets/clone-BIwWiqgh.js +1 -0
- package/dist/assets/{cose-bilkent-S5V4N54A-Dd5Fpol9.js → cose-bilkent-S5V4N54A-BqngH0-b.js} +1 -1
- package/dist/assets/{dagre-KV5264BT-BH00hKa4.js → dagre-KV5264BT-CB2GDseU.js} +1 -1
- package/dist/assets/{diagram-5BDNPKRD-BJZlGmRA.js → diagram-5BDNPKRD-DLymVFaP.js} +1 -1
- package/dist/assets/{diagram-G4DWMVQ6-BTj-YG-C.js → diagram-G4DWMVQ6-D90wHjyV.js} +1 -1
- package/dist/assets/{diagram-MMDJMWI5-2ZD4VZMB.js → diagram-MMDJMWI5-BUN9g8qX.js} +1 -1
- package/dist/assets/{diagram-TYMM5635-mTEHpW4W.js → diagram-TYMM5635-I51WOx9p.js} +1 -1
- package/dist/assets/{erDiagram-SMLLAGMA-DTOSCCrk.js → erDiagram-SMLLAGMA-CR1_hpJO.js} +1 -1
- package/dist/assets/{flowDiagram-DWJPFMVM-C4ZAoiRL.js → flowDiagram-DWJPFMVM-CiwoAZbF.js} +1 -1
- package/dist/assets/{ganttDiagram-T4ZO3ILL-C56IAugD.js → ganttDiagram-T4ZO3ILL-CJXNdMQL.js} +1 -1
- package/dist/assets/{gitGraphDiagram-UUTBAWPF-fvtnUb6S.js → gitGraphDiagram-UUTBAWPF-BaZdjuy6.js} +1 -1
- package/dist/assets/{graph-CnqqDZhs.js → graph-CpnKw6r1.js} +1 -1
- package/dist/assets/{index-CcAn_gE2.js → index-BrAqjeq3.js} +1 -1
- package/dist/assets/{index-CEinmFtX.js → index-BzeiQo_V.js} +1 -1
- package/dist/assets/{index-CdN-CkKM.js → index-C1VAmODt.js} +1 -1
- package/dist/assets/{index-DjoCHMpJ.js → index-C5FKlPaZ.js} +1 -1
- package/dist/assets/index-D-DhPfzj.js +2 -0
- package/dist/assets/{index-BUkls72j.js → index-D3x00_V6.js} +1 -1
- package/dist/assets/{index-Dq3ex7Ip.js → index-DL6PUDDq.js} +1 -1
- package/dist/assets/{index-F9AcG6Ef.js → index-VjrFIlap.js} +1 -1
- package/dist/assets/{infoDiagram-42DDH7IO-B-b77lg9.js → infoDiagram-42DDH7IO-BvyXlqWb.js} +1 -1
- package/dist/assets/{ishikawaDiagram-UXIWVN3A-B1ituugL.js → ishikawaDiagram-UXIWVN3A-CwbVWeK4.js} +1 -1
- package/dist/assets/{journeyDiagram-VCZTEJTY-DvFc_1_L.js → journeyDiagram-VCZTEJTY-DDVzhfoW.js} +1 -1
- package/dist/assets/{jszip.min-Br1yL7Q3.js → jszip.min-RVG0sxQ-.js} +1 -1
- package/dist/assets/{kanban-definition-6JOO6SKY-B-3zDwdJ.js → kanban-definition-6JOO6SKY-CC9zdzb4.js} +1 -1
- package/dist/assets/{layout-B8tT3Nrd.js → layout-BP8agUEZ.js} +1 -1
- package/dist/assets/{linear-BVxRmpuU.js → linear-D2xrTRbP.js} +1 -1
- package/dist/assets/{mermaid.core-TpktUJt6.js → mermaid.core-iygJ4rTs.js} +2 -2
- package/dist/assets/{min-4AuCZ0ho.js → min-DZABGYh9.js} +1 -1
- package/dist/assets/{mindmap-definition-QFDTVHPH-MQeup-Jb.js → mindmap-definition-QFDTVHPH-DonHZQOo.js} +1 -1
- package/dist/assets/{pieDiagram-DEJITSTG-mSFlWRpV.js → pieDiagram-DEJITSTG-CEn16Sb_.js} +1 -1
- package/dist/assets/{quadrantDiagram-34T5L4WZ-BE2AHw1J.js → quadrantDiagram-34T5L4WZ-385okL2K.js} +1 -1
- package/dist/assets/{requirementDiagram-MS252O5E-CSat0Shv.js → requirementDiagram-MS252O5E-B7AA6wNS.js} +1 -1
- package/dist/assets/{sankeyDiagram-XADWPNL6-jSfdI1J9.js → sankeyDiagram-XADWPNL6-BE2hbI0P.js} +1 -1
- package/dist/assets/seqResourceLoaders-BdxjrasH.css +41 -0
- package/dist/assets/seqResourceLoaders-DPto114V.js +2 -0
- package/dist/assets/{sequenceDiagram-FGHM5R23-n8z9Vixi.js → sequenceDiagram-FGHM5R23-DUbU1ZOb.js} +1 -1
- package/dist/assets/{stateDiagram-FHFEXIEX-Dn_y_D8r.js → stateDiagram-FHFEXIEX-BKKvwNQM.js} +1 -1
- package/dist/assets/{stateDiagram-v2-QKLJ7IA2-BB1b-66S.js → stateDiagram-v2-QKLJ7IA2-qXlEdp-K.js} +1 -1
- package/dist/assets/{timeline-definition-GMOUNBTQ-Bvy0hn9D.js → timeline-definition-GMOUNBTQ-DQnlfuvY.js} +1 -1
- package/dist/assets/{vendor-antd-BciJO790.js → vendor-antd-DTdiXvO1.js} +1 -1
- package/dist/assets/{vendor-codemirror-BVX6n7ix.js → vendor-codemirror-Dg_w9qS2.js} +1 -1
- package/dist/assets/{vendor-mdxeditor-BlcXEhaG.js → vendor-mdxeditor-DNrU6OL8.js} +2 -2
- package/dist/assets/{vendor-qrcode-DVibqC0x.js → vendor-qrcode-BdV5qU8N.js} +1 -1
- package/dist/assets/{vendor-virtuoso-CsBSMJ5R.js → vendor-virtuoso-BQELbHyq.js} +1 -1
- package/dist/assets/{vennDiagram-DHZGUBPP-BVqFkdla.js → vennDiagram-DHZGUBPP-B51WBYoK.js} +1 -1
- package/dist/assets/{wardley-RL74JXVD-BIAqGP0w.js → wardley-RL74JXVD-DQSgSi6f.js} +1 -1
- package/dist/assets/{wardleyDiagram-NUSXRM2D-DGUvrzIN.js → wardleyDiagram-NUSXRM2D-B5PCvQWU.js} +1 -1
- package/dist/assets/{xychartDiagram-5P7HB3ND-BjEJgIoR.js → xychartDiagram-5P7HB3ND-fY2LLKhL.js} +1 -1
- package/dist/index.html +4 -4
- package/node_modules/@ccv/core/src/sdk-task-label.js +70 -0
- package/package.json +1 -1
- package/server/lib/chat-queue.js +159 -31
- package/server/lib/compact-inject-guard.js +100 -0
- package/server/lib/project-prefs.js +12 -5
- package/server/lib/sdk-manager.js +113 -2
- package/server/lib/task-state.js +11 -0
- package/server/routes/preferences.js +17 -2
- package/server/server.js +207 -0
- package/dist/assets/App-BJIeZQK0.css +0 -1
- package/dist/assets/App-C_AI6A4g.js +0 -2
- package/dist/assets/Mobile-4mZy680Y.js +0 -1
- package/dist/assets/classDiagram-6PBFFD2Q-CAw9u3mr.js +0 -1
- package/dist/assets/classDiagram-v2-HSJHXN6E-CAw9u3mr.js +0 -1
- package/dist/assets/clone-CW1SPXDP.js +0 -1
- package/dist/assets/index-CVnJzK-y.js +0 -2
- package/dist/assets/seqResourceLoaders-BT5ki0J4.js +0 -2
- package/dist/assets/seqResourceLoaders-CXgVOdgW.css +0 -41
package/server/lib/chat-queue.js
CHANGED
|
@@ -317,12 +317,16 @@ function _injectHead() {
|
|
|
317
317
|
}
|
|
318
318
|
|
|
319
319
|
/**
|
|
320
|
-
* Poll (≤ INJECT_POLL_MAX_MS) until
|
|
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 (!
|
|
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 {
|
|
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 (
|
|
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
|
-
*
|
|
598
|
-
*
|
|
599
|
-
*
|
|
600
|
-
*
|
|
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
|
-
*
|
|
603
|
-
*
|
|
604
|
-
*
|
|
605
|
-
*
|
|
606
|
-
*
|
|
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
|
-
*
|
|
611
|
-
*
|
|
612
|
-
*
|
|
613
|
-
*
|
|
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
|
-
|
|
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(
|
|
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.
|
|
699
|
+
reportSwallowed('chat-queue.inject', err);
|
|
636
700
|
done({ ok: false, reason: 'write-failed' });
|
|
637
701
|
}
|
|
638
702
|
};
|
|
639
|
-
if (
|
|
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,9 +14,11 @@ 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),
|
|
18
|
-
//
|
|
19
|
-
|
|
17
|
+
// machine-level paths (logDir/claudeConfigDir), the internal forks map, and global-only features
|
|
18
|
+
// that must stay identical across every project (scheduledTasks; contextCompaction — the
|
|
19
|
+
// compaction rules are a machine-global list, never per-project). snapshotForFork / cleanPatch /
|
|
20
|
+
// the admin list read all funnel through stripSensitive so the rule can't drift.
|
|
21
|
+
const STRIP_KEYS = ['auth', 'authByProject', 'prefsByProject', 'logDir', 'claudeConfigDir', 'scheduledTasks', 'contextCompaction'];
|
|
20
22
|
|
|
21
23
|
/** Strip secrets + IM credentials + machine-level keys from a prefs-shaped object in place. */
|
|
22
24
|
export function stripSensitive(obj) {
|
|
@@ -80,12 +82,17 @@ export function snapshotForFork(prefsRaw) {
|
|
|
80
82
|
* stamps them after this runs.
|
|
81
83
|
*/
|
|
82
84
|
export function resolveScoped(globalPrefs, fork) {
|
|
83
|
-
const { approvalModal: gAM, ...gRest } = globalPrefs || {};
|
|
84
|
-
|
|
85
|
+
const { approvalModal: gAM, contextCompaction: gCC, ...gRest } = globalPrefs || {};
|
|
86
|
+
// Strip the fork's own contextCompaction copy up front so a hand-edited/legacy dirty fork
|
|
87
|
+
// can never shadow the global machine-wide list. The GLOBAL value is re-applied below.
|
|
88
|
+
const { approvalModal: fAM, contextCompaction: _fCC, ...fRest } = fork || {};
|
|
85
89
|
const merged = { ...gRest, ...fRest };
|
|
86
90
|
// 定时任务是全局状态(claim CAS 只在全局 prefs 上进行)——fork 永远不得携带/遮蔽它,
|
|
87
91
|
// 否则脏 fork 会把任务定义/claim 透给 scoped 客户端读侧。
|
|
88
92
|
delete merged.scheduledTasks;
|
|
93
|
+
// Compaction rules are machine-global (STRIP_KEYS already blocks fork writes): after stripping the fork's dirty copy, restore the global value —
|
|
94
|
+
// what was removed is the fork's shadowing, not the global value itself (otherwise scoped clients lose the rules and their save would overwrite the global).
|
|
95
|
+
if (gCC !== undefined) merged.contextCompaction = gCC;
|
|
89
96
|
if (gAM || fAM) {
|
|
90
97
|
// 防引用别名:fork 无 approvalModal 时也返回浅拷贝,避免调用方(preferencesGet 的
|
|
91
98
|
// voicePack reconcile)回写到解析出的全局对象(当前每请求新解析虽无害,仍保持"绝不外泄内部引用")。
|
|
@@ -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(
|
|
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) =>
|
|
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();
|
package/server/lib/task-state.js
CHANGED
|
@@ -14,6 +14,17 @@
|
|
|
14
14
|
* the single-workspace behavior is byte-identical.
|
|
15
15
|
*
|
|
16
16
|
* L1-lib: pure module, Node builtins only, no imports.
|
|
17
|
+
*
|
|
18
|
+
* PTY-vs-SDK label policy: this module deliberately does NOT filter stub
|
|
19
|
+
* entries whose subject/description are both null. A PTY stub is the intended
|
|
20
|
+
* placeholder for a task whose TaskCreated hook was lost (or fired before
|
|
21
|
+
* cc-viewer started watching) — the HUD shows `#id` for a beat until the next
|
|
22
|
+
* TaskUpdate(subject) / TaskCompleted(subject) lands. That is a live,
|
|
23
|
+
* in-flight row, NOT an SDK-mode "label-less ghost" (a terminal residue with
|
|
24
|
+
* neither description nor summary on the wire). The SDK-side label-less filter
|
|
25
|
+
* is scoped to TERMINAL entries only and lives in sdk-manager.js /
|
|
26
|
+
* sdkTaskTracker.js / @ccv/core/sdk-task-label; PTY snapshot semantics stay
|
|
27
|
+
* byte-identical here.
|
|
17
28
|
*/
|
|
18
29
|
|
|
19
30
|
/** @type {Map<string, {sessionId: string|null, tasks: Map<string, object>, lastUsedAt: number}>} */
|
|
@@ -150,9 +150,24 @@ function preferencesPost(req, res, parsedUrl, isLocal, deps) {
|
|
|
150
150
|
// prefsByProject(项目独立配置 fork)只能经 admin-only 的 /api/project-prefs/* 修改;元字段
|
|
151
151
|
// (_isLocal/_projectScoped/…)仅 GET 回包,绝不让它们经 /api/preferences 落盘污染。
|
|
152
152
|
delete incoming.prefsByProject;
|
|
153
|
-
//
|
|
154
|
-
//
|
|
153
|
+
// Scheduled tasks are writable only via /api/scheduled-tasks (admin+same-origin) — no client
|
|
154
|
+
// (admin included) may inject/clear/overwrite tasks through a prefs POST (claim CAS and schedule
|
|
155
|
+
// state validation live only in the store layer).
|
|
155
156
|
delete incoming.scheduledTasks;
|
|
157
|
+
// Compaction rules are machine-global, and executionTiming:'auto' is auto-injected by the frontend
|
|
158
|
+
// without confirmation — the danger class is identical to scheduledTasks. Non-admin clients (an
|
|
159
|
+
// open no-password LAN session, or a cross-site form) must not plant a "low threshold + auto +
|
|
160
|
+
// arbitrary script" rule into every session of the host operator. Admin-only; stripped otherwise.
|
|
161
|
+
if (!isAdminReq(req, isLocal)) {
|
|
162
|
+
delete incoming.contextCompaction;
|
|
163
|
+
} else if (Object.prototype.hasOwnProperty.call(incoming, 'contextCompaction')) {
|
|
164
|
+
// Admin writes still require same-origin (blocks cross-site form POSTs; same gate as CLAUDE_EXECUTABLE).
|
|
165
|
+
if (!isSameOriginBrowserRequest(req, parsedUrl)) {
|
|
166
|
+
res.writeHead(403, { 'Content-Type': 'application/json' });
|
|
167
|
+
res.end(JSON.stringify({ error: 'Same-origin request required' }));
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
156
171
|
for (const k of Object.keys(incoming)) if (k[0] === '_') delete incoming[k];
|
|
157
172
|
// IM bridge configs 同理:只能经 admin-only 的 /api/dingtalk/config、/api/im/* 修改,禁止借
|
|
158
173
|
// /api/preferences 植入凭据。
|