@xmoon76/dsh-pi-tui 0.5.2-rc.1 → 0.5.3

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.
@@ -1,4 +1,3 @@
1
- import { ut as stripTerminalSequences } from "./extensions-VuoIE_Jc.mjs";
2
1
  import { normalize } from "node:path";
3
2
  //#region src/domain/transcript/content-blocks.ts
4
3
  /** Match the Web JsonBlock serialized-payload bound. */
@@ -399,6 +398,311 @@ function formatBytes(bytes) {
399
398
  return `${(bytes / 1048576).toFixed(1)} MiB`;
400
399
  }
401
400
  //#endregion
401
+ //#region src/tui/presentation/terminal-text.ts
402
+ /**
403
+ * Untrusted-text projections for terminal-bound presentation.
404
+ *
405
+ * Source bytes, Session/Job facts and copy payloads stay authoritative and
406
+ * untouched; only the disposable display string is projected here. Two
407
+ * explicit policies exist:
408
+ *
409
+ * - {@link sanitizeDisplayText}: plain untrusted text (prose, labels,
410
+ * Markdown, command arguments). Every recognized ANSI/VT sequence and every
411
+ * unsafe C0/C1 character is removed. CRLF normalizes to LF, a lone CR to one
412
+ * ASCII space, TAB to three spaces. Nothing terminal-active survives.
413
+ * - {@link sanitizeDisplayLog}: untrusted log/terminal text. Same control
414
+ * removal, except strictly whitelisted complete CSI SGR (`ESC [ … m`) is
415
+ * retained and a lone CR becomes LF so progress frames read as log history
416
+ * instead of screen overwrite. The result ends in an app-owned `ESC[0m`
417
+ * whenever any SGR survives, so no source-controlled terminal state leaks
418
+ * past its display block.
419
+ *
420
+ * One linear-time scanner handles ESC/C1 introducers, whole CSI/OSC/DCS/SOS/
421
+ * PM/APC sequences (including unterminated tails) and the remaining control
422
+ * bytes. It is a pure `string -> string` projection: no cache, no process
423
+ * state, no side effects.
424
+ *
425
+ * @module @xmoon76/dsh-pi-tui/tui/presentation/terminal-text
426
+ */
427
+ const ESC = 27;
428
+ const BEL = 7;
429
+ const LF = 10;
430
+ const CR = 13;
431
+ const TAB = 9;
432
+ const DEL = 127;
433
+ const C1_CSI = 155;
434
+ const C1_ST = 156;
435
+ const C1_OSC = 157;
436
+ const C1_DCS = 144;
437
+ const C1_SOS = 152;
438
+ const C1_PM = 158;
439
+ const C1_APC = 159;
440
+ const BACKSLASH = 92;
441
+ /** The app-owned reset appended after a display block that kept any SGR. */
442
+ const SGR_RESET = "\x1B[0m";
443
+ /** SGR parameters permitted by the log whitelist (non-color attributes). */
444
+ const SGR_ATTRIBUTES = /* @__PURE__ */ new Set([
445
+ 0,
446
+ 1,
447
+ 2,
448
+ 3,
449
+ 4,
450
+ 7,
451
+ 9,
452
+ 22,
453
+ 23,
454
+ 24,
455
+ 27,
456
+ 29,
457
+ 39,
458
+ 49
459
+ ]);
460
+ /** True when any code unit needs the scanner (a C0 control, DEL or C1). */
461
+ function needsScan(source) {
462
+ for (let i = 0; i < source.length; i++) {
463
+ const code = source.charCodeAt(i);
464
+ if (code < 32 || code >= DEL && code <= 159) return true;
465
+ }
466
+ return false;
467
+ }
468
+ /** True for the standard 8/16-color foreground/background parameter set. */
469
+ function isStandardColor(value) {
470
+ return value >= 30 && value <= 37 || value >= 40 && value <= 47 || value >= 90 && value <= 97 || value >= 100 && value <= 107;
471
+ }
472
+ /**
473
+ * Validate one SGR parameter string (the bytes between `[` and `m`). Only
474
+ * decimal fields, the attribute set, standard colors and the `38/48;5;n` /
475
+ * `38/48;2;r;g;b` extended-color groups are accepted; every malformed,
476
+ * unknown, colon, empty or out-of-range parameter rejects the WHOLE sequence.
477
+ */
478
+ function isWhitelistedSgrParams(body) {
479
+ if (body === "") return true;
480
+ const parts = body.split(";");
481
+ for (const part of parts) {
482
+ if (part.length === 0 || part.length > 4) return false;
483
+ for (let k = 0; k < part.length; k++) {
484
+ const code = part.charCodeAt(k);
485
+ if (code < 48 || code > 57) return false;
486
+ }
487
+ }
488
+ let i = 0;
489
+ while (i < parts.length) {
490
+ const value = Number(parts[i]);
491
+ if (value === 38 || value === 48) {
492
+ const mode = parts[i + 1];
493
+ if (mode === "5") {
494
+ const n = parts[i + 2];
495
+ if (n === void 0 || Number(n) > 255) return false;
496
+ i += 3;
497
+ continue;
498
+ }
499
+ if (mode === "2") {
500
+ const r = parts[i + 2];
501
+ const g = parts[i + 3];
502
+ const b = parts[i + 4];
503
+ if (r === void 0 || g === void 0 || b === void 0) return false;
504
+ if (Number(r) > 255 || Number(g) > 255 || Number(b) > 255) return false;
505
+ i += 5;
506
+ continue;
507
+ }
508
+ return false;
509
+ }
510
+ if (!SGR_ATTRIBUTES.has(value) && !isStandardColor(value)) return false;
511
+ i++;
512
+ }
513
+ return true;
514
+ }
515
+ /**
516
+ * Consume one CSI sequence starting at its first parameter byte. Returns the
517
+ * index just past the sequence, plus the sequence itself when it is a complete
518
+ * `ESC [ … m` satisfying the log whitelist.
519
+ *
520
+ * A byte outside the parameter/intermediate/final classes ends the sequence
521
+ * early and resumes normal scanning at that byte; running off the end consumes
522
+ * the unterminated remainder.
523
+ */
524
+ function scanCsi(source, start, allowSgr) {
525
+ const len = source.length;
526
+ let j = start;
527
+ while (j < len) {
528
+ const code = source.charCodeAt(j);
529
+ if (code >= 32 && code <= 63) {
530
+ j++;
531
+ continue;
532
+ }
533
+ if (code >= 64 && code <= 126) {
534
+ if (allowSgr && code === 109) {
535
+ const body = source.slice(start, j);
536
+ if (isWhitelistedSgrParams(body)) return {
537
+ end: j + 1,
538
+ sgr: `\u001b[${body}m`
539
+ };
540
+ }
541
+ return { end: j + 1 };
542
+ }
543
+ break;
544
+ }
545
+ return { end: j };
546
+ }
547
+ /**
548
+ * Consume one string control (OSC/DCS/SOS/PM/APC) starting at its first
549
+ * payload byte. BEL terminates only OSC; `ESC \` and C1 ST terminate every
550
+ * string control. An unterminated string consumes to end of input.
551
+ */
552
+ function scanString(source, start, belTerminates) {
553
+ const len = source.length;
554
+ let j = start;
555
+ while (j < len) {
556
+ const code = source.charCodeAt(j);
557
+ if (belTerminates && code === BEL) return j + 1;
558
+ if (code === C1_ST) return j + 1;
559
+ if (code === ESC && j + 1 < len && source.charCodeAt(j + 1) === BACKSLASH) return j + 2;
560
+ j++;
561
+ }
562
+ return len;
563
+ }
564
+ /** Project one source string under either display policy. */
565
+ function project(source, keepSgr) {
566
+ if (!needsScan(source)) return source;
567
+ const len = source.length;
568
+ let out = "";
569
+ let keptSgr = false;
570
+ let i = 0;
571
+ while (i < len) {
572
+ const code = source.charCodeAt(i);
573
+ if (code === ESC) {
574
+ const next = i + 1 < len ? source.charCodeAt(i + 1) : -1;
575
+ if (next === 91) {
576
+ const csi = scanCsi(source, i + 2, keepSgr);
577
+ if (csi.sgr !== void 0) {
578
+ out += csi.sgr;
579
+ keptSgr = true;
580
+ }
581
+ i = csi.end;
582
+ continue;
583
+ }
584
+ if (next === 93) {
585
+ i = scanString(source, i + 2, true);
586
+ continue;
587
+ }
588
+ if (next === 80 || next === 88 || next === 94 || next === 95) {
589
+ i = scanString(source, i + 2, false);
590
+ continue;
591
+ }
592
+ if (next >= 32 && next <= 47) {
593
+ let j = i + 1;
594
+ while (j < len && source.charCodeAt(j) >= 32 && source.charCodeAt(j) <= 47) j++;
595
+ if (j < len && source.charCodeAt(j) >= 48 && source.charCodeAt(j) <= 126) j++;
596
+ i = j;
597
+ continue;
598
+ }
599
+ if (next >= 48 && next <= 126) {
600
+ i += 2;
601
+ continue;
602
+ }
603
+ i++;
604
+ continue;
605
+ }
606
+ if (code === C1_CSI) {
607
+ i = scanCsi(source, i + 1, false).end;
608
+ continue;
609
+ }
610
+ if (code === C1_OSC) {
611
+ i = scanString(source, i + 1, true);
612
+ continue;
613
+ }
614
+ if (code === C1_DCS || code === C1_SOS || code === C1_PM || code === C1_APC) {
615
+ i = scanString(source, i + 1, false);
616
+ continue;
617
+ }
618
+ if (code === LF) {
619
+ out += "\n";
620
+ i++;
621
+ continue;
622
+ }
623
+ if (code === CR) {
624
+ if (i + 1 < len && source.charCodeAt(i + 1) === LF) {
625
+ out += "\n";
626
+ i += 2;
627
+ continue;
628
+ }
629
+ out += keepSgr ? "\n" : " ";
630
+ i++;
631
+ continue;
632
+ }
633
+ if (code === TAB) {
634
+ out += " ";
635
+ i++;
636
+ continue;
637
+ }
638
+ if (code < 32 || code === DEL || code >= 128 && code <= 159) {
639
+ i++;
640
+ continue;
641
+ }
642
+ out += source[i];
643
+ i++;
644
+ }
645
+ if (keepSgr && keptSgr) out += SGR_RESET;
646
+ return out;
647
+ }
648
+ /**
649
+ * Project untrusted plain text onto terminal-safe display text: every escape
650
+ * sequence and unsafe control character is removed, CRLF becomes LF, a lone CR
651
+ * becomes one space and TAB becomes three spaces. Ordinary Unicode passes
652
+ * through verbatim and the exact input string is returned when no code unit
653
+ * needs projection.
654
+ */
655
+ function sanitizeDisplayText(source) {
656
+ return project(source, false);
657
+ }
658
+ /**
659
+ * Project untrusted log/terminal text onto terminal-safe display text:
660
+ * whitelisted complete SGR survives, a lone CR becomes LF so progress frames
661
+ * stay readable as history, and any retained SGR ends with an app-owned reset.
662
+ */
663
+ function sanitizeDisplayLog(source) {
664
+ return project(source, true);
665
+ }
666
+ //#endregion
667
+ //#region src/tui/presentation/lines.ts
668
+ /**
669
+ * Presentation-boundary projections shared by single-row renderers.
670
+ *
671
+ * @module @xmoon76/dsh-pi-tui/tui/presentation/lines
672
+ */
673
+ /**
674
+ * Project arbitrary presentation text onto exactly one physical terminal
675
+ * row.
676
+ *
677
+ * Raw/domain text must remain unchanged; call this only at a presentation
678
+ * boundary that semantically owns exactly one physical row (a renderer
679
+ * whose returned `string[]` element is budgeted as one terminal row).
680
+ * Width primitives (`visibleWidth`, `truncateToWidth`), marquee windowing,
681
+ * and hit-map construction are not newline sanitizers: an embedded CR/LF
682
+ * inside one array element escapes the row budget and the mouse hit map.
683
+ *
684
+ * Deliberately preserves ordinary/leading/trailing spaces (some
685
+ * presentation labels carry structural whitespace); it only collapses
686
+ * CR/LF row breaks into a single ordinary space, keeping the whole text
687
+ * visible instead of dropping every line after the first.
688
+ */
689
+ function singlePhysicalLine(text) {
690
+ return text.replace(/[\r\n]+/g, " ");
691
+ }
692
+ /**
693
+ * The stricter sibling of {@link singlePhysicalLine} for text that may also
694
+ * carry terminal escape sequences or other control characters (a Host
695
+ * session title/label): {@link sanitizeDisplayText} removes every recognized
696
+ * ANSI/VT sequence and unsafe control character (so a raw `\x1b[31m` can never
697
+ * leave visible `[31m` payload), then any remaining line break collapses to a
698
+ * space. TAB and CR are already normalized by the shared projection. The
699
+ * result is guaranteed to be a single physical row with no terminal-control
700
+ * content.
701
+ */
702
+ function sanitizedPhysicalLine(text) {
703
+ return sanitizeDisplayText(text).replace(/[\t\r\n]+/g, " ");
704
+ }
705
+ //#endregion
402
706
  //#region src/tui/pickers/model-directory.ts
403
707
  const IDENTITY_SEP = "\0";
404
708
  const PROVIDER_DEFAULT = `${IDENTITY_SEP}provider-default`;
@@ -740,16 +1044,16 @@ function formatSessionAge(createdAt, now = Date.now()) {
740
1044
  return `${Math.floor(months / 12)}y`;
741
1045
  }
742
1046
  /** Strip terminal control characters from untrusted text before it enters
743
- * the picker presentation. Complete ANSI/OSC/APC sequences are removed
744
- * first (the fork's parser), then every remaining C0 control (including a
745
- * lone ESC), DEL, and C1 control (U+0080–U+009F — CSI/OSC/APC in 8-bit
746
- * form) is dropped: the picker writes descriptions straight to the
747
- * terminal, and a terminal decoding UTF-8 interprets C1 code points as
748
- * control sequences, not text. Host snippets may carry persisted control
749
- * bytes (message/tool output) — a raw ESC/OSC would be interpreted, not
750
- * displayed. */
1047
+ * the picker presentation. The shared presentation projection removes every
1048
+ * complete ANSI/OSC/APC sequence (including C1 8-bit forms and unterminated
1049
+ * tails), then every remaining C0 control, DEL and C1 control, and folds the
1050
+ * result onto exactly one physical row: the picker writes descriptions
1051
+ * straight to the terminal, and a terminal decoding UTF-8 interprets C1 code
1052
+ * points as control sequences, not text. Host snippets may carry persisted
1053
+ * control bytes (message/tool output) — a raw ESC/OSC would be interpreted,
1054
+ * not displayed. */
751
1055
  function sanitizeTerminalText(value) {
752
- return stripTerminalSequences(value).replace(/[\u0000-\u001f\u007f-\u009f]/gu, "");
1056
+ return sanitizedPhysicalLine(value);
753
1057
  }
754
1058
  /** Assemble one session row for the picker, marking the current session.
755
1059
  * @param indent - tree depth for the "All" category: rows hang under their
@@ -761,15 +1065,15 @@ function sanitizeTerminalText(value) {
761
1065
  function sessionPickerItem(row, currentId, indent = 0, contentHit) {
762
1066
  const marker = row.id === currentId ? "● " : "";
763
1067
  const treePrefix = indent <= 0 ? "" : `${" ".repeat(indent)}└─ `;
764
- const meta = [shortSessionId(row.id), formatSessionAge(row.createdAt ?? row.updatedAt)];
1068
+ const meta = [sanitizeTerminalText(shortSessionId(row.id)), formatSessionAge(row.createdAt ?? row.updatedAt)];
765
1069
  if (row.origin === "subagent") meta.push("sub");
766
1070
  if (row.parentSession !== void 0) meta.push("fork");
767
- if (row.preset !== void 0) meta.push(`preset:${row.preset}`);
1071
+ if (row.preset !== void 0) meta.push(`preset:${sanitizeTerminalText(row.preset)}`);
768
1072
  if (row.live) meta.push("live");
769
1073
  if (contentHit !== void 0) meta.push(`…${sanitizeTerminalText(contentHit.snippet)}…`);
770
1074
  return {
771
1075
  value: row.id,
772
- label: `${treePrefix}${marker}${row.title ?? shortSessionId(row.id)}`,
1076
+ label: `${treePrefix}${marker}${row.title === void 0 ? sanitizeTerminalText(shortSessionId(row.id)) : sanitizeTerminalText(row.title)}`,
773
1077
  description: meta.join(" · "),
774
1078
  group: workspaceKey(row.cwd)
775
1079
  };
@@ -2311,6 +2615,14 @@ function clusterAdjacentAmbientContext(messages) {
2311
2615
  * cluster presentation, and expanded Focus consumes it for its process tail.
2312
2616
  * The same boundary identity is therefore never re-derived per preset.
2313
2617
  *
2618
+ * A Work span may CARRY a foldable Context row as a structural part without
2619
+ * making it Process: the row keeps its Context semantics, its source bytes and
2620
+ * its own disclosure, but no longer splits one turn's Activity/Thought. Two
2621
+ * narrow forms qualify: a `form:'snapshot'` singleton / snapshot-only raw
2622
+ * cluster, and a `tool-jobs` Notice with durable same-turn `next-step`
2623
+ * delivery evidence. A mixed `instructions`/`catalog`/`snapshot` cluster and
2624
+ * every other Notice form stay independent Context boundaries.
2625
+ *
2314
2626
  * The projector is a single forward pass plus the linear ambient-clustering
2315
2627
  * pass (O(n)); wrappers are freshly allocated each call, but their
2316
2628
  * `owner`/`members` always reference the original `TranscriptMessage`
@@ -2328,49 +2640,189 @@ function clusterAdjacentAmbientContext(messages) {
2328
2640
  * renders standalone. Exported so the live Preparing ownership consumes the
2329
2641
  * SAME boundary authority as every projection: a settled interaction closes
2330
2642
  * the trailing run.
2643
+ *
2644
+ * This predicate deliberately does NOT admit Snapshot Context: it also answers
2645
+ * Process/live-Preparing eligibility. Work PRESENTATION carriage is decided by
2646
+ * {@link isFoldableSnapshotContext} inside {@link projectTranscriptStructure}.
2331
2647
  */
2332
2648
  function isTranscriptWorkMember(message) {
2333
2649
  return "turn" in message && classifyTranscriptMessage(message).class === "process" && !isSurfacedInteractionTool(message) && !isPostTurnReplayEvidence(message);
2334
2650
  }
2651
+ /** Whether one row is a producer-declared Snapshot Context row (the ONE
2652
+ * ambient form whose disclosure follows the surrounding Work/Thought). */
2653
+ function isSnapshotContext(message) {
2654
+ return isSurfacedContext(message) && contextFormOf(message) === "snapshot";
2655
+ }
2656
+ /** Per-cluster memo of {@link isSnapshotOnlyCluster}: cluster wrappers are
2657
+ * freshly allocated per projection pass but may be queried once per member by
2658
+ * the structure scan and the Focus disposition. The WeakMap keeps every scan
2659
+ * linear for one large snapshot run (no per-member `every()` rescan). */
2660
+ const snapshotOnlyClusterMemo = /* @__PURE__ */ new WeakMap();
2661
+ /** Whether one raw-adjacent ambient cluster consists ONLY of Snapshot rows, so
2662
+ * the whole cluster may be carried inside a Work span without tearing a mixed
2663
+ * foundation cluster apart. Memoized per cluster object; a cluster wrapper is
2664
+ * never reused across projection passes. */
2665
+ function isSnapshotOnlyCluster(cluster) {
2666
+ const memoized = snapshotOnlyClusterMemo.get(cluster);
2667
+ if (memoized !== void 0) return memoized;
2668
+ const result = cluster.members.every(isSnapshotContext);
2669
+ snapshotOnlyClusterMemo.set(cluster, result);
2670
+ return result;
2671
+ }
2672
+ /**
2673
+ * The narrow display-layer predicate: may this Snapshot row's presentation be
2674
+ * carried by the same-turn Work/Thought instead of ending it?
2675
+ *
2676
+ * The answer is source-derived (`form:'snapshot'`) and depends on the raw
2677
+ * adjacency result: a Snapshot that shares its raw-adjacent ambient cluster
2678
+ * with `instructions`/`catalog` is part of one indivisible mixed Context
2679
+ * cluster and stays a Work boundary. A singleton Snapshot or a snapshot-only
2680
+ * cluster is foldable.
2681
+ * @param message - one raw transcript row.
2682
+ * @param clusterByMember - raw-adjacency membership for the SAME window.
2683
+ */
2684
+ function isFoldableSnapshotContext(message, clusterByMember) {
2685
+ if (!isSnapshotContext(message)) return false;
2686
+ const cluster = clusterByMember.get(message);
2687
+ return cluster === void 0 || isSnapshotOnlyCluster(cluster);
2688
+ }
2689
+ /**
2690
+ * Whether one row is a Working `tool-jobs` completion Notice with durable
2691
+ * same-turn `next-step` delivery evidence.
2692
+ *
2693
+ * This is a NARROW exception, never a generic notice rule: the producer-declared
2694
+ * `sourceKind === 'tool-jobs'` AND `form === 'notice'` are both required, plus
2695
+ * the fold's presentation-only `sameTurnNextStep` flag derived from the durable
2696
+ * `agent/inbox/spliced` insert/claim identity chain. A `next-turn` wakeup, a
2697
+ * foreign/legacy log, a different producer (including `subagent-settled`) or a
2698
+ * missing claim carries no flag and therefore stays an independent Context
2699
+ * boundary.
2700
+ */
2701
+ function isWorkingToolJobsNotice(message) {
2702
+ if (!isSurfacedContext(message)) return false;
2703
+ const presentation = message.contextPresentation;
2704
+ return presentation !== void 0 && presentation.sameTurnNextStep === true && presentation.form === "notice" && presentation.sourceKind === "tool-jobs";
2705
+ }
2706
+ /**
2707
+ * The complete narrow display-layer eligibility: may this Context row be
2708
+ * carried by the same-turn Work/Thought instead of ending it? Only a foldable
2709
+ * Snapshot or a proven Working `tool-jobs` Notice qualifies; every other
2710
+ * surfaced Context remains a boundary.
2711
+ */
2712
+ function isFoldableWorkContext(message, clusterByMember) {
2713
+ return isFoldableSnapshotContext(message, clusterByMember) || isWorkingToolJobsNotice(message);
2714
+ }
2335
2715
  /**
2336
2716
  * Segment one raw transcript window into canonical structural blocks.
2337
2717
  *
2338
2718
  * Ambient Context clusters are computed FIRST from raw adjacency, so a hidden
2339
2719
  * Process row can never merge two Context rows that were not adjacent, and a
2340
- * cluster is a Work boundary exactly like a standalone Context row. A settled
2341
- * surfaced-interaction card is its own boundary and belongs to neither the
2342
- * preceding nor the following span. The result partitions `messages` exactly:
2343
- * every input row appears once, in raw order, either as a `message` block, a
2344
- * Work member, or a cluster member.
2720
+ * cluster is a Work boundary exactly like a standalone Context row — except a
2721
+ * snapshot-only cluster, which is carried as a nested part of the surrounding
2722
+ * same-turn Work.
2723
+ *
2724
+ * Snapshot Context rows seen before the first Process of a same-turn run are
2725
+ * held in a CALL-LOCAL pending buffer: they join the run once a real Process
2726
+ * arrives, or materialize as their original Context block(s) when a hard
2727
+ * boundary or the window end arrives first. The buffer never persists across
2728
+ * calls and never invents a Process-free Work span.
2729
+ *
2730
+ * A settled surfaced-interaction card is its own boundary and belongs to
2731
+ * neither the preceding nor the following span. The result partitions
2732
+ * `messages` exactly: every input row appears once, in raw order, either as a
2733
+ * `message` block, a Work member, or a cluster member.
2345
2734
  * @param messages - the transcript window in raw chronology.
2346
2735
  */
2347
2736
  function projectTranscriptStructure(messages) {
2348
2737
  const clustering = clusterAdjacentAmbientContext(messages);
2349
2738
  const out = [];
2350
- let run = [];
2739
+ let runParts = [];
2740
+ let runMembers = [];
2351
2741
  let runTurn;
2742
+ let pendingParts = [];
2743
+ let pendingMembers = [];
2744
+ let pendingTurn;
2745
+ const materializePending = () => {
2746
+ for (const part of pendingParts) if (part.kind === "message") out.push({
2747
+ kind: "message",
2748
+ message: part.message
2749
+ });
2750
+ else out.push({
2751
+ kind: "context-cluster",
2752
+ cluster: part.cluster
2753
+ });
2754
+ pendingParts = [];
2755
+ pendingMembers = [];
2756
+ pendingTurn = void 0;
2757
+ };
2758
+ const pushPending = (parts, members, turn) => {
2759
+ if (pendingMembers.length > 0 && pendingTurn !== turn) materializePending();
2760
+ pendingParts.push(...parts);
2761
+ pendingMembers.push(...members);
2762
+ pendingTurn = turn;
2763
+ };
2352
2764
  const flush = () => {
2353
- const owner = run[0];
2765
+ materializePending();
2766
+ const owner = runMembers[0];
2354
2767
  if (owner !== void 0 && runTurn !== void 0) out.push({
2355
2768
  kind: "work",
2356
2769
  span: {
2357
2770
  kind: "work",
2358
2771
  turn: runTurn,
2359
- members: run,
2360
- owner
2772
+ members: runMembers,
2773
+ owner,
2774
+ parts: runParts
2361
2775
  }
2362
2776
  });
2363
- run = [];
2777
+ runParts = [];
2778
+ runMembers = [];
2364
2779
  runTurn = void 0;
2365
2780
  };
2366
2781
  for (const message of messages) {
2367
2782
  const cluster = clustering.byMember.get(message);
2368
2783
  if (cluster !== void 0) {
2369
- flush();
2370
- if (message === cluster.owner) out.push({
2784
+ if (message !== cluster.owner) continue;
2785
+ if (!isSnapshotOnlyCluster(cluster)) {
2786
+ flush();
2787
+ out.push({
2788
+ kind: "context-cluster",
2789
+ cluster
2790
+ });
2791
+ continue;
2792
+ }
2793
+ if (runMembers.length > 0) {
2794
+ if (runTurn === cluster.turn) {
2795
+ runParts.push({
2796
+ kind: "context-cluster",
2797
+ cluster
2798
+ });
2799
+ runMembers.push(...cluster.members);
2800
+ continue;
2801
+ }
2802
+ flush();
2803
+ }
2804
+ pushPending([{
2371
2805
  kind: "context-cluster",
2372
2806
  cluster
2373
- });
2807
+ }], cluster.members, cluster.turn);
2808
+ continue;
2809
+ }
2810
+ if (isFoldableWorkContext(message, clustering.byMember)) {
2811
+ if (runMembers.length > 0) {
2812
+ if (runTurn === message.turn) {
2813
+ runParts.push({
2814
+ kind: "message",
2815
+ message
2816
+ });
2817
+ runMembers.push(message);
2818
+ continue;
2819
+ }
2820
+ flush();
2821
+ }
2822
+ pushPending([{
2823
+ kind: "message",
2824
+ message
2825
+ }], [message], message.turn);
2374
2826
  continue;
2375
2827
  }
2376
2828
  if (isSurfacedInteractionTool(message)) {
@@ -2382,8 +2834,20 @@ function projectTranscriptStructure(messages) {
2382
2834
  continue;
2383
2835
  }
2384
2836
  if (isTranscriptWorkMember(message)) {
2385
- if (run.length > 0 && runTurn !== message.turn) flush();
2386
- run.push(message);
2837
+ if (runMembers.length > 0 && runTurn !== message.turn) flush();
2838
+ if (runMembers.length === 0) {
2839
+ if (pendingMembers.length > 0 && pendingTurn !== message.turn) materializePending();
2840
+ runParts = pendingParts;
2841
+ runMembers = pendingMembers;
2842
+ pendingParts = [];
2843
+ pendingMembers = [];
2844
+ pendingTurn = void 0;
2845
+ }
2846
+ runParts.push({
2847
+ kind: "message",
2848
+ message
2849
+ });
2850
+ runMembers.push(message);
2387
2851
  runTurn = message.turn;
2388
2852
  continue;
2389
2853
  }
@@ -2415,14 +2879,23 @@ function workByMemberOf(structure) {
2415
2879
  * Map every Context-cluster member to its canonical cluster. Presentation
2416
2880
  * layers that reorder or hoist rows (collapsed/expanded Focus) consume THIS
2417
2881
  * identity instead of re-clustering the reordered sequence, so canonical
2418
- * membership stays the only cluster authority.
2882
+ * membership stays the only cluster authority. Snapshot-only clusters nested
2883
+ * inside a Work span are included: their members must resolve to BOTH their
2884
+ * Work and cluster ancestors for disclosure/search.
2419
2885
  * @param structure - the canonical structural blocks for one window.
2420
2886
  */
2421
2887
  function clusterByMemberOf(structure) {
2422
2888
  const byMember = /* @__PURE__ */ new Map();
2889
+ const add = (cluster) => {
2890
+ for (const member of cluster.members) byMember.set(member, cluster);
2891
+ };
2423
2892
  for (const block of structure) {
2424
- if (block.kind !== "context-cluster") continue;
2425
- for (const member of block.cluster.members) byMember.set(member, block.cluster);
2893
+ if (block.kind === "context-cluster") {
2894
+ add(block.cluster);
2895
+ continue;
2896
+ }
2897
+ if (block.kind !== "work") continue;
2898
+ for (const part of block.span.parts) if (part.kind === "context-cluster") add(part.cluster);
2426
2899
  }
2427
2900
  return byMember;
2428
2901
  }
@@ -2475,4 +2948,4 @@ function contextClusterSummaryParts(cluster) {
2475
2948
  return parts;
2476
2949
  }
2477
2950
  //#endregion
2478
- export { sessionRowMatchesQuery as $, resultTextLines as A, writeFoldedPreview as B, parseCallPreview as C, isSurfacedInteractionTool as Ct, parseWriteEnvelope as D, openOpaqueBlockFallbackText as Dt, parseSkillEnvelope as E, finalizedBlockFallbackText as Et, toolIconSemantic as F, sessionLabelParts as G, findSessionMatch as H, toolPresenterFrom as I, shortSessionId as J, sessionPickerItem as K, toolSummaryKeys as L, subagentModelDisplay as M, systemContextBody as N, readFoldedPreview as O, textWithAttachmentMarkers as Ot, toolCardHeader as P, sanitizeSessionSearchInput as Q, toolTitle as R, isCompactActionTool as S, isSurfacedContext as St, parseReadEnvelopes as T, markPostTurnReplayEvidence as Tt, formatSessionAge as U, fileAttachmentSummary as V, sanitizeTerminalText as W, buildSessionTree as X, workspaceKey as Y, sameWorkspace as Z, foldedResultSummaryFor as _, contextIconSemantic as _t, workByMemberOf as a, formatLeaderSequence as at, goalResultSummary as b, contextSummary as bt, FOLDED_JSON_RESULT_TOOLS as c, PROVIDER_DEFAULT as ct, askAnswersSummary as d, modelIdentity as dt, HISTORY_CHORDS as et, compactToolExpandedLines as f, projectModelDirectory as ft, foldedCallPreview as g, contextFormOf as gt, focusToolDisplay as h, runSyncDisposalStepsWithPrimary as ht, projectTranscriptStructure as i, formatKeyId as it, skillFoldedPreview as j, relativizeToCwd as k, userBlocksVisibleNow as kt, GOAL_TOOL_NAMES as l, effortChoicesOf as lt, firstLine as m, runSyncDisposalSteps as mt, clusterByMemberOf as n, TSP_CONTINUED_INSPECTION_LABEL as nt, contextPresentationKind as o, isBuiltInPresetRow as ot, compactToolPresentation as p, formatBytes as pt, sessionSearchItem as q, isTranscriptWorkMember as r, formatHintKeys as rt, isNoticeContext as s, presetDisplayText as st, contextClusterSummaryParts as t, JOB_LOCAL_KEYS as tt, askAnswersLines as u, initialEffortOf as ut, genericRawInputLines as v, contextPresentation as vt, parseImageEnvelope as w, isSurfacedInteractionToolName as wt, imageFoldedPreview as x, isPostTurnReplayEvidence as xt, goalResultLines as y, contextProvenance as yt, webCardLines as z };
2951
+ export { sameWorkspace as $, readFoldedPreview as A, isSurfacedInteractionToolName as At, toolTitle as B, imageFoldedPreview as C, contextIconSemantic as Ct, parseReadEnvelopes as D, isPostTurnReplayEvidence as Dt, parseImageEnvelope as E, contextSummary as Et, systemContextBody as F, userBlocksVisibleNow as Ft, formatSessionAge as G, writeFoldedPreview as H, toolCardHeader as I, sessionPickerItem as J, sanitizeTerminalText as K, toolIconSemantic as L, resultTextLines as M, finalizedBlockFallbackText as Mt, skillFoldedPreview as N, openOpaqueBlockFallbackText as Nt, parseSkillEnvelope as O, isSurfacedContext as Ot, subagentModelDisplay as P, textWithAttachmentMarkers as Pt, buildSessionTree as Q, toolPresenterFrom as R, goalResultSummary as S, contextFormOf as St, parseCallPreview as T, contextProvenance as Tt, fileAttachmentSummary as U, webCardLines as V, findSessionMatch as W, shortSessionId as X, sessionSearchItem as Y, workspaceKey as Z, focusToolDisplay as _, sanitizeDisplayLog as _t, projectTranscriptStructure as a, formatHintKeys as at, genericRawInputLines as b, runSyncDisposalSteps as bt, contextPresentationKind as c, isBuiltInPresetRow as ct, GOAL_TOOL_NAMES as d, effortChoicesOf as dt, sanitizeSessionSearchInput as et, askAnswersLines as f, initialEffortOf as ft, firstLine as g, singlePhysicalLine as gt, compactToolPresentation as h, sanitizedPhysicalLine as ht, isTranscriptWorkMember as i, TSP_CONTINUED_INSPECTION_LABEL as it, relativizeToCwd as j, markPostTurnReplayEvidence as jt, parseWriteEnvelope as k, isSurfacedInteractionTool as kt, isNoticeContext as l, presetDisplayText as lt, compactToolExpandedLines as m, projectModelDirectory as mt, clusterByMemberOf as n, HISTORY_CHORDS as nt, workByMemberOf as o, formatKeyId as ot, askAnswersSummary as p, modelIdentity as pt, sessionLabelParts as q, isFoldableWorkContext as r, JOB_LOCAL_KEYS as rt, clusterAdjacentAmbientContext as s, formatLeaderSequence as st, contextClusterSummaryParts as t, sessionRowMatchesQuery as tt, FOLDED_JSON_RESULT_TOOLS as u, PROVIDER_DEFAULT as ut, foldedCallPreview as v, sanitizeDisplayText as vt, isCompactActionTool as w, contextPresentation as wt, goalResultLines as x, runSyncDisposalStepsWithPrimary as xt, foldedResultSummaryFor as y, formatBytes as yt, toolSummaryKeys as z };
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
2
- import { n as TUI_STARTUP_SERVICE } from "./startup-CWQl0-0n.mjs";
2
+ import { n as TUI_STARTUP_SERVICE } from "./startup-D5Xu8diR.mjs";
3
3
  import { createRequire } from "node:module";
4
4
  import * as fs from "node:fs";
5
5
  import { readFileSync } from "node:fs";
@@ -1,2 +1,2 @@
1
- import { a as PI_TUI_EXTENSIONS_SERVICE, i as name, o as API_VERSION, r as inject, s as describeKey, t as apply } from "./extensions-VuoIE_Jc.mjs";
1
+ import { a as PI_TUI_EXTENSIONS_SERVICE, i as name, o as API_VERSION, r as inject, s as describeKey, t as apply } from "./extensions-a-rxanjw.mjs";
2
2
  export { API_VERSION, PI_TUI_EXTENSIONS_SERVICE, apply, describeKey, inject, name };