@zhuxixi/pi-agent-board 0.13.0 → 0.14.0

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 (91) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +37 -12
  3. package/docs/SECTION_FOLDING.md +53 -0
  4. package/docs/superpowers/plans/2026-10-23-issue-222-attach-ready.md +290 -0
  5. package/docs/superpowers/plans/2026-10-26-issue-245-key-hints-doc-sync.md +244 -0
  6. package/docs/superpowers/plans/2026-10-27-issue-172-fullscreen-selection-clear.md +344 -0
  7. package/docs/superpowers/plans/2026-10-27-issue-252-select-key-hints.md +209 -0
  8. package/docs/superpowers/plans/2026-10-28-issue-255-coordinator-endpoint-zombie.md +442 -0
  9. package/docs/superpowers/plans/2026-10-28-issue-257-legacy-pty-runner-endpoint-cleanup.md +256 -0
  10. package/docs/superpowers/plans/2026-11-03-cwd-favorites-full-pool.md +266 -0
  11. package/docs/superpowers/plans/2026-11-03-issue-266-alt-h-detach.md +467 -0
  12. package/docs/superpowers/plans/2026-11-04-issue-270-scenario-stdout-flush.md +584 -0
  13. package/docs/superpowers/plans/2026-11-05-issue-278-ctrl-g-external-editor.md +381 -0
  14. package/docs/superpowers/plans/2026-11-06-issue-280-frame-witness-delivery.md +430 -0
  15. package/docs/superpowers/plans/2026-11-07-issue-284-attach-recovery.md +115 -0
  16. package/docs/superpowers/plans/2026-11-07-issue-284-u1-u2-trial-guide.md +39 -0
  17. package/docs/superpowers/plans/2026-11-08-host-restart-model-override.md +894 -0
  18. package/docs/superpowers/plans/2026-11-08-issue-288-cap-floor.md +51 -0
  19. package/docs/superpowers/plans/2026-11-09-dashboard-fold-flake.md +166 -0
  20. package/docs/superpowers/plans/2026-11-09-issue-273-harness-console-log-exit.md +369 -0
  21. package/docs/superpowers/plans/2026-11-10-issue-258-board-selection-settle.md +760 -0
  22. package/docs/superpowers/plans/2026-11-13-issue-294-snapshot-resize-intent.md +590 -0
  23. package/docs/superpowers/plans/2026-11-16-greeting-title-poll.md +838 -0
  24. package/docs/superpowers/plans/2026-11-22-issue-297-compaction-mirror.md +797 -0
  25. package/docs/superpowers/plans/2026-11-23-issue-254-cursor-keep-position.md +663 -0
  26. package/docs/superpowers/plans/2026-11-23-issue-95-legacy-quarantine.md +320 -0
  27. package/docs/superpowers/specs/2026-10-23-issue-222-attach-ready-design.md +204 -0
  28. package/docs/superpowers/specs/2026-10-26-issue-245-key-hints-doc-sync-design.md +72 -0
  29. package/docs/superpowers/specs/2026-10-27-issue-172-fullscreen-selection-clear-design.md +248 -0
  30. package/docs/superpowers/specs/2026-10-27-issue-252-select-key-hints-design.md +95 -0
  31. package/docs/superpowers/specs/2026-10-28-issue-255-coordinator-endpoint-zombie-design.md +380 -0
  32. package/docs/superpowers/specs/2026-10-28-issue-257-legacy-pty-runner-endpoint-cleanup-design.md +197 -0
  33. package/docs/superpowers/specs/2026-11-03-cwd-favorites-full-pool-design.md +106 -0
  34. package/docs/superpowers/specs/2026-11-03-issue-266-alt-h-detach-design.md +185 -0
  35. package/docs/superpowers/specs/2026-11-04-issue-270-scenario-stdout-flush-design.md +176 -0
  36. package/docs/superpowers/specs/2026-11-05-issue-278-ctrl-g-external-editor-design.md +185 -0
  37. package/docs/superpowers/specs/2026-11-07-issue-284-attach-recovery-design.md +166 -0
  38. package/docs/superpowers/specs/2026-11-08-host-restart-model-override-design.md +115 -0
  39. package/docs/superpowers/specs/2026-11-08-issue-288-cap-floor-design.md +86 -0
  40. package/docs/superpowers/specs/2026-11-09-dashboard-fold-flake-design.md +109 -0
  41. package/docs/superpowers/specs/2026-11-09-issue-273-harness-console-log-exit-design.md +182 -0
  42. package/docs/superpowers/specs/2026-11-10-issue-258-board-selection-settle-design.md +109 -0
  43. package/docs/superpowers/specs/2026-11-13-issue-294-snapshot-resize-intent-design.md +141 -0
  44. package/docs/superpowers/specs/2026-11-16-greeting-title-poll-design.md +174 -0
  45. package/docs/superpowers/specs/2026-11-22-issue-297-compaction-mirror-design.md +158 -0
  46. package/docs/superpowers/specs/2026-11-22-issue-95-legacy-quarantine-design.md +209 -0
  47. package/docs/superpowers/specs/2026-11-23-issue-254-cursor-keep-position-design.md +201 -0
  48. package/package.json +1 -1
  49. package/runner/pty-runner.mjs +526 -63
  50. package/runner/state-coordinator.mjs +62 -5
  51. package/runner/title-runner.mjs +33 -24
  52. package/src/commands/agent-board.ts +5 -1
  53. package/src/core/attach-detach.mjs +27 -0
  54. package/src/core/attach-frame-proof.mjs +897 -0
  55. package/src/core/attach-frame-reporter.mjs +738 -0
  56. package/src/core/attach-frame-stream.mjs +266 -0
  57. package/src/core/attach-pr-label.mjs +12 -0
  58. package/src/core/attach-recovery.mjs +239 -0
  59. package/src/core/attach-screen-owner.mjs +55 -0
  60. package/src/core/attach-view-proof.mjs +709 -0
  61. package/src/core/auto-state.mjs +6 -1
  62. package/src/core/cwd-stats.mjs +3 -1
  63. package/src/core/dashboard-prefs.mjs +31 -0
  64. package/src/core/derive.mjs +8 -1
  65. package/src/core/events.mjs +127 -1
  66. package/src/core/foreground-projection-cache.mjs +1 -0
  67. package/src/core/frame-witness-update.mjs +35 -0
  68. package/src/core/fullscreen-selection.mjs +60 -0
  69. package/src/core/host-coordination.mjs +48 -0
  70. package/src/core/host-protocol.mjs +13 -2
  71. package/src/core/hosted-frame-witness.mjs +60 -0
  72. package/src/core/paths.mjs +10 -3
  73. package/src/core/pty-attach-render.mjs +239 -0
  74. package/src/core/pty-kitty-images.mjs +237 -0
  75. package/src/core/pty-scroll.mjs +8 -8
  76. package/src/core/rows.mjs +43 -7
  77. package/src/core/session-entries.mjs +82 -0
  78. package/src/core/session-launch-prefs.mjs +45 -0
  79. package/src/core/session-view.mjs +3 -63
  80. package/src/core/store.mjs +1 -0
  81. package/src/core/terminal-attach-client.mjs +199 -20
  82. package/src/core/terminal-attach-protocol.mjs +221 -7
  83. package/src/core/terminal-model.mjs +24 -3
  84. package/src/core/terminal-snapshot.mjs +10 -0
  85. package/src/core/title-flow.mjs +66 -0
  86. package/src/core/title.mjs +101 -0
  87. package/src/core/types.mjs +17 -0
  88. package/src/index.ts +85 -0
  89. package/src/runtime/service.mjs +87 -18
  90. package/src/ui/dashboard.ts +206 -49
  91. package/src/ui/pty-attach.ts +1472 -99
@@ -6,15 +6,22 @@ import { createConnection, type Socket } from "node:net";
6
6
  import type { Component, KeybindingsManager, RgbColor, TUI, TerminalColorScheme, TuiMouseEvent, TuiMouseEventResult } from "@earendil-works/pi-tui";
7
7
  import { CURSOR_MARKER, Key, matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
8
8
  import { resolveAttachDeleteKey } from "../core/attach-delete.mjs";
9
+ import { classifyProofInvalidFamily, classifyProofStatus, sanitizeViewProofEnumPair } from "../core/attach-recovery.mjs";
10
+ import { resolveAttachDetachChord } from "../core/attach-detach.mjs";
11
+ import { createAttachScreenOwnerState, installAttachScreenOwnerObservers } from "../core/attach-screen-owner.mjs";
12
+ import { createPtyKittyImages } from "../core/pty-kitty-images.mjs";
9
13
  import { findHttpUrlAtCells, findWordRangeAtCells } from "../core/pty-links.mjs";
10
- import { createAttachOutputRenderScheduler, detectCursorDesync, isPtyCursorHidden, nextAttachRender, projectPtyCursor, shouldScheduleAttachRenderForMessage } from "../core/pty-attach-render.mjs";
14
+ import { canPublishAttachView, createAttachOutputRenderScheduler, decideAttachPresentation, detectCursorDesync, isPtyCursorHidden, nextAttachRender, projectPtyCursor, resizeIntentEvidenceFromRecords, shouldScheduleAttachRenderForMessage } from "../core/pty-attach-render.mjs";
11
15
  import { evaluateAttachReconnect, shouldEscapeAttach } from "../core/pty-attach-reconnect.mjs";
12
16
  import { installImeCursorCoalesce } from "../core/ime-cursor-coalesce.mjs";
13
17
  import { createJiggleRetryController } from "../core/pty-attach-jiggle-controller.mjs";
14
18
  import { createTerminalAttachClient } from "../core/terminal-attach-client.mjs";
19
+ import { MAX_VIEW_PROOF_RECORDS } from "../core/terminal-attach-protocol.mjs";
20
+ import { createSafeTrailingClassifier } from "../core/attach-view-proof.mjs";
15
21
  import { backgroundRgbFromTerminalColors, buildSettleSchemePatch, colorSchemeForBackgroundRgb, extractOscQuerySequences, resolveProbeApi, toColorSchemeReport } from "../core/terminal-query-sequences.mjs";
16
22
  import { REPLY_GUARD_WINDOW_MS, createReplyGuard, isReplyGuardEnabled } from "../core/terminal-reply-guard.mjs";
17
- import { clampInt, encodeWheelReport, fullscreenMouseEnableSequence, historyFloorAfterHydrate, resolveAttachMouseAction, resolveAttachWheelRoute, resolvePasteSelectionSource, resolveWheelLines, sameMousePoint, scrollableHistoryLines, scrollViewportTop, selectionDragScrollLines, selectionReleaseIsDrag, shouldMirrorSelectionToPrimary, shouldOwnOuterMouseMode, splitAttachInput, wheelScrollLinesUp } from "../core/pty-scroll.mjs";
23
+ import { createFullscreenSelectionSettler } from "../core/fullscreen-selection.mjs";
24
+ import { clampInt, encodeWheelReport, fullscreenMouseEnableSequence, historyFloorAfterHydrate, isFullscreenSelectionEnd, resolveAttachMouseAction, resolveAttachWheelRoute, resolvePasteSelectionSource, resolveWheelLines, sameMousePoint, scrollableHistoryLines, scrollViewportTop, selectionDragScrollLines, selectionReleaseIsDrag, shouldOwnOuterMouseMode, splitAttachInput, wheelScrollLinesUp } from "../core/pty-scroll.mjs";
18
25
 
19
26
  export type PtyAttachResult = { action: "detached" } | { action: "closed"; exitCode?: number | null } | { action: "delete" };
20
27
 
@@ -23,6 +30,16 @@ type ThemeLike = {
23
30
  bold(text: string): string;
24
31
  };
25
32
 
33
+ /** The pi-tui members the attach view reads without a public typing contract:
34
+ * getActiveSelectionText / clearTextSelection are private in TuiAltScreen's d.ts
35
+ * (runtime-reachable plain methods), getCopyOnSelect is public. Every access is
36
+ * feature-detected so an older or newer pi-tui degrades instead of throwing. */
37
+ export interface FullscreenSelectionHost {
38
+ getActiveSelectionText?: () => string | undefined;
39
+ getCopyOnSelect?: () => boolean;
40
+ clearTextSelection?: () => void;
41
+ }
42
+
26
43
  /** Diagnostic patch emitted at attach settle (DiagnosticEvent-compatible; built by buildSettleSchemePatch). */
27
44
  export interface AttachSettleDiagnosticPatch {
28
45
  source: string;
@@ -32,14 +49,96 @@ export interface AttachSettleDiagnosticPatch {
32
49
  details: { probeApi?: string; outcome: string; report?: string; late?: boolean };
33
50
  }
34
51
 
52
+ /** Issue #284 §3.4: which path settled this attach (recorded as readyReason). */
53
+ export type AttachReadyReason = "complete" | "committed-degraded" | "legacy-settle" | "legacy-cap";
54
+
55
+ /** Issue #284 §3.4/D5: recovery facts recorded at attach settle (and, from
56
+ * issue #288 D2, at each attach WAIT phase expiry). Numbers and finite
57
+ * enums only — never tokens, screen text, keys, or raw terminal data.
58
+ * The committedView identity records only numeric facts: the local parser
59
+ * generation (epoch) and the geometry revision; the connection/baseline
60
+ * tokens stay out of the diagnostic payload, and the wire generation id and
61
+ * the parser object remain excluded as non-numeric identity axes.
62
+ * latestViewProof carries the whitelisted (status, reason) pair — unrecognized
63
+ * wire strings map to "unrecognized" (sanitizeViewProofEnumPair). */
64
+ export interface AttachRecoveryFacts {
65
+ notReadyReason: string | null;
66
+ publishabilityState: string;
67
+ deadlineState: string;
68
+ witnessLatched: boolean;
69
+ budgetDeadline: number;
70
+ budgetElapsed: boolean;
71
+ proofStatus: string | null;
72
+ proofStickyInvalid: boolean;
73
+ committedView: {
74
+ generation: number;
75
+ geometryRevision: number;
76
+ source: string;
77
+ sourceCols: number;
78
+ sourceRows: number;
79
+ contentKind: string;
80
+ } | null;
81
+ latestViewProof: { status: string; reason: string } | null;
82
+ }
83
+
84
+ /** Diagnostic patch emitted at attach settle with the #284 recovery facts. */
85
+ export interface AttachRecoveryDiagnosticPatch {
86
+ source: string;
87
+ level: "info";
88
+ code: "attach_settle_ready";
89
+ message: string;
90
+ details: AttachRecoveryFacts & { readyReason: AttachReadyReason };
91
+ }
92
+
93
+ /** Issue #288 D2: which attach deadline expired while the attach was still
94
+ * waiting — the 250ms recovery budget or the 2500ms hard cap. */
95
+ export type AttachWaitExpiredPhase = "budget" | "cap";
96
+
97
+ /** Diagnostic patch emitted when an attach wait phase expires and the attach
98
+ * keeps waiting (issue #288 D2). Same recovery facts as the settle record;
99
+ * no readyReason — a waiting attach has none. */
100
+ export interface AttachWaitExpiredDiagnosticPatch {
101
+ source: string;
102
+ level: "info";
103
+ code: "attach_wait_expired";
104
+ message: string;
105
+ details: AttachRecoveryFacts & { phase: AttachWaitExpiredPhase };
106
+ }
107
+
35
108
  export interface PtyAttachOptions {
36
109
  socketPath: string;
37
110
  screenLogPath?: string;
38
111
  title: string;
112
+ /** Persisted winning PR/MR reference shown beside the session name. */
113
+ prLabel?: string;
39
114
  /** Issue #161: receives settle-scheme diagnostic patches. Default: no-op. */
40
- onDiagnostic?: (event: AttachSettleDiagnosticPatch) => void;
115
+ onDiagnostic?: (event: AttachSettleDiagnosticPatch | AttachRecoveryDiagnosticPatch | AttachWaitExpiredDiagnosticPatch) => void;
116
+ /** Issue #284: injectable clock for attach-lifecycle deadlines. The default
117
+ * (host clock + global timers) keeps the existing behavior untouched; the
118
+ * component harness injects a virtual time source and timer queue so the
119
+ * 250ms settle / 2500ms cap / 250ms recovery budget boundaries are asserted
120
+ * deterministically instead of on wall clock. */
121
+ clock?: AttachClock;
41
122
  }
42
123
 
124
+ /** Issue #284 attach-lifecycle clock seam: `now` plus a scheduler pair. The
125
+ * scheduled handle is opaque (the injected scheduler may return any id). */
126
+ export interface AttachClock {
127
+ now(): number;
128
+ schedule(fn: () => void, ms: number): unknown;
129
+ clear(handle: unknown): void;
130
+ }
131
+
132
+ const hostAttachClock: AttachClock = {
133
+ now: () => Date.now(),
134
+ schedule: (fn, ms) => {
135
+ const timer = setTimeout(fn, ms);
136
+ timer.unref?.();
137
+ return timer;
138
+ },
139
+ clear: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
140
+ };
141
+
43
142
  const require = createRequire(import.meta.url);
44
143
  const { Terminal } = require("@xterm/headless") as { Terminal: new (opts: Record<string, unknown>) => XtermLike };
45
144
 
@@ -52,8 +151,17 @@ const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇",
52
151
  const LOADING_TICK_MS = 120;
53
152
  /** How long to keep the loading banner after the last resize-jiggle during attach. */
54
153
  const ATTACH_SETTLE_MS = 250;
55
- /** Hard cap on the attach transition so a silent session can't stall the banner. */
56
- const ATTACH_HARD_TIMEOUT_MS = 2500;
154
+ /** Hard cap on the attach transition so a silent session can't stall the banner.
155
+ * Issue #288: the cap doubles as the trailing-only downgrade floor (spec §2
156
+ * D1); exported for the integration driver's wall-clock readouts. */
157
+ export const ATTACH_HARD_TIMEOUT_MS = 2500;
158
+ /** Issue #284 recovery budget: one 250ms window per attach lifetime. Once it
159
+ * elapses, a protocol attach with a safely committed view but no covering F
160
+ * proof may publish degraded (spec §3.2; the policy wiring lands with T6 —
161
+ * this constant only owns the timer fact). Ordinary output and reconnect
162
+ * re-entry never reset or extend it (invariant I5). Exported for the
163
+ * component harness's diagnostic readouts. */
164
+ export const ATTACH_RECOVERY_BUDGET_MS = 250;
57
165
  /** Protocol-race guard for legacy jiggle arming (issue #91 phase 4): the
58
166
  * undecided window must not pulse the child before the snapshot probe
59
167
  * resolves — a resize-free attach is the protocol-mode contract. Invisible
@@ -92,9 +200,15 @@ const TERMINAL_PASSTHROUGH_CARRY_MAX_BYTES = TERMINAL_PASSTHROUGH_MAX_BYTES + 40
92
200
  const KITTY_IMAGE_PREFIX = "\x1b_G";
93
201
  const ITERM2_FILE_PREFIX = "\x1b]1337;File=";
94
202
 
203
+ interface XtermParserLike {
204
+ registerCsiHandler(opts: { prefix: string; final: string }, cb: (params: (number | number[])[]) => boolean): { dispose(): void };
205
+ }
206
+
95
207
  interface XtermLike {
96
208
  write(data: string, cb?: () => void): void;
97
209
  resize(cols: number, rows: number): void;
210
+ parser?: XtermParserLike;
211
+ dispose?(): void;
98
212
  // Full buffer wipe (@xterm/headless Terminal.reset): the attach client's
99
213
  // "empty/resnapshot → UI resets its buffer" contract (phase 4, F3).
100
214
  reset(): void;
@@ -151,8 +265,110 @@ interface BufferCellLike {
151
265
  isOverline(): number;
152
266
  }
153
267
 
268
+ interface CommittedRow { cells: SnapshotLine; kittyPrefix: string; }
269
+
270
+ interface CommittedView {
271
+ identity: {
272
+ connectionToken: number;
273
+ baselineToken: number;
274
+ generation: string;
275
+ parser: XtermLike;
276
+ geometryRevision: number;
277
+ targetCols: number;
278
+ targetRows: number;
279
+ closed: boolean;
280
+ };
281
+ start: number;
282
+ end: number;
283
+ rows: CommittedRow[];
284
+ cursor: { row: number; col: number } | null;
285
+ cursorHidden: boolean;
286
+ viewportTop: number | null;
287
+ proofSeq: number | null;
288
+ /** Issue #284 §3.1 predicate 7 facts, recorded at commit: which path
289
+ * captured the grid, the grid's ACTUAL dimensions (the parser size at
290
+ * commit — the readiness assembly must never re-read the current target
291
+ * here), and the locally closed completeness classification. */
292
+ source: "snapshot" | "sync-close";
293
+ sourceCols: number;
294
+ sourceRows: number;
295
+ contentKind: "complete" | "unknown";
296
+ }
297
+
298
+ /** Primitive cell snapshot used by committed rendering and interactions. */
299
+ class SnapshotCell implements BufferCellLike {
300
+ private constructor(
301
+ private readonly charsValue: string,
302
+ private readonly widthValue: number,
303
+ private readonly attrs: {
304
+ bold: number; dim: number; italic: number; underline: number; blink: number; inverse: number;
305
+ invisible: number; strikethrough: number; overline: number;
306
+ fgRGB: boolean; fgPalette: boolean; fg: number;
307
+ bgRGB: boolean; bgPalette: boolean; bg: number;
308
+ },
309
+ private readonly uriValue: string,
310
+ ) {
311
+ this.extended = this.uriValue ? { urlId: 1, _urlId: 1 } : undefined;
312
+ }
313
+ static empty(): SnapshotCell {
314
+ return new SnapshotCell("", 0, {
315
+ bold: 0, dim: 0, italic: 0, underline: 0, blink: 0, inverse: 0,
316
+ invisible: 0, strikethrough: 0, overline: 0,
317
+ fgRGB: false, fgPalette: false, fg: -1, bgRGB: false, bgPalette: false, bg: -1,
318
+ }, "");
319
+ }
320
+ static fromBufferCell(cell: BufferCellLike, uri: string): SnapshotCell {
321
+ return new SnapshotCell(cell.getChars(), cell.getWidth(), {
322
+ bold: cell.isBold(), dim: cell.isDim(), italic: cell.isItalic(), underline: cell.isUnderline(),
323
+ blink: cell.isBlink(), inverse: cell.isInverse(), invisible: cell.isInvisible(),
324
+ strikethrough: cell.isStrikethrough(), overline: cell.isOverline(),
325
+ fgRGB: cell.isFgRGB(), fgPalette: cell.isFgPalette(), fg: cell.getFgColor(),
326
+ bgRGB: cell.isBgRGB(), bgPalette: cell.isBgPalette(), bg: cell.getBgColor(),
327
+ }, uri);
328
+ }
329
+ getWidth(): number { return this.widthValue; }
330
+ getChars(): string { return this.charsValue; }
331
+ hasExtendedAttrs(): number { return this.uriValue ? 1 : 0; }
332
+ extended?: { urlId?: number; _urlId?: number };
333
+ getFgColor(): number { return this.attrs.fg; }
334
+ getBgColor(): number { return this.attrs.bg; }
335
+ isFgRGB(): boolean { return this.attrs.fgRGB; }
336
+ isBgRGB(): boolean { return this.attrs.bgRGB; }
337
+ isFgPalette(): boolean { return this.attrs.fgPalette; }
338
+ isBgPalette(): boolean { return this.attrs.bgPalette; }
339
+ isFgDefault(): boolean { return !this.attrs.fgRGB && !this.attrs.fgPalette; }
340
+ isBgDefault(): boolean { return !this.attrs.bgRGB && !this.attrs.bgPalette; }
341
+ isBold(): number { return this.attrs.bold; }
342
+ isItalic(): number { return this.attrs.italic; }
343
+ isDim(): number { return this.attrs.dim; }
344
+ isUnderline(): number { return this.attrs.underline; }
345
+ isBlink(): number { return this.attrs.blink; }
346
+ isInverse(): number { return this.attrs.inverse; }
347
+ isInvisible(): number { return this.attrs.invisible; }
348
+ isStrikethrough(): number { return this.attrs.strikethrough; }
349
+ isOverline(): number { return this.attrs.overline; }
350
+ osc8Uri(): string { return this.uriValue; }
351
+ }
352
+
353
+ class SnapshotLine implements BufferLineLike {
354
+ constructor(readonly cells: SnapshotCell[]) {}
355
+ get length(): number { return this.cells.length; }
356
+ getCell(x: number): BufferCellLike | undefined { return this.cells[x]; }
357
+ translateToString(trimRight = false): string {
358
+ const text = this.cells.map((cell) => cell.getChars() || " ").join("");
359
+ return trimRight ? text.replace(/\s+$/u, "") : text;
360
+ }
361
+ }
362
+
154
363
  type MousePoint = { line: number; col: number };
155
364
  type ScreenCell = { row: number; col: number };
365
+ /** Issue #278: one ownership-adapter transition (attach-screen-owner.mjs). */
366
+ type AttachScreenOwnerTransition = {
367
+ previous: { syncOpen: boolean; externalOutputActive: boolean };
368
+ current: { syncOpen: boolean; externalOutputActive: boolean };
369
+ syncOpenMarker: boolean;
370
+ syncCloseMarker: boolean;
371
+ };
156
372
  /** Issue #187: `screenAnchor` is the RAW reported cell of the press; the drag/click
157
373
  * decision compares it against the release cell, because buffer coordinates drift
158
374
  * while the session streams. Absent on word selections (they are created on release). */
@@ -222,7 +438,106 @@ export class PtyAttachComponent implements Component {
222
438
  // configurable via $AGENT_BOARD_WHEEL_LINES. The fullscreen handleMouse path uses
223
439
  // the TUI's wheelDelta instead, which is already accelerated and line-quantified.
224
440
  private readonly mouseWheelLines = resolveWheelLines();
225
- private readonly term: XtermLike;
441
+ /** Current local parser. Replaced atomically at an accepted snapshotReady. */
442
+ private term: XtermLike;
443
+ private kittyImages: ReturnType<typeof createPtyKittyImages> | null;
444
+ /** Monotonic identity axes: one per accepted socket / authoritative baseline / parser. */
445
+ private connectionToken = 0;
446
+ private baselineToken = 0;
447
+ private parserEpoch = 1;
448
+ private parserObservers: Array<{ dispose(): void }> = [];
449
+ private parserObservationSupported = true;
450
+ private replacementFailureCount = 0;
451
+ private parserSyncOpen = false;
452
+ private parserObserverEvents = 0;
453
+ /** Issue #278: true while an external editor (Ctrl+G Nvim) owns the child screen. */
454
+ private externalOutputActive = false;
455
+ /** Set when an ownership transition arrived while an authoritative frame was
456
+ * hydrating: the frame's own wrapper sync window must not clear external
457
+ * ownership, so the adapter is re-synced from component state once the
458
+ * hydration write completes (design D7: suspend, then preserve). */
459
+ private screenOwnerResyncPending = false;
460
+ private collectingConnectionToken = 0;
461
+ private collectingBaselineToken = 0;
462
+ private collectingParserEpoch = 0;
463
+ /** Distinct facts; none of these is presentation truth in this stage. */
464
+ private protocolBaselineState: "unverified" | "valid-empty" | "valid-content" = "unverified";
465
+ private localHydrationState: "idle" | "hydrating" | "complete" | "failed" = "idle";
466
+ private publishabilityState: "wait" | "unknown" | "ready" = "wait";
467
+ private firstAttachSideEffectsApplied = false;
468
+ private latestViewProof: unknown = null;
469
+ private viewProofRecords: unknown[] = [];
470
+ private viewProofRecordCount = 0;
471
+ /** Identity captured when the current proof/coverage was received. */
472
+ private viewProofIdentity: ReturnType<PtyAttachComponent["currentViewIdentity"]> | null = null;
473
+ /** Local geometry revision: incremented once per real differing-size transition. */
474
+ private geometryRevision = 0;
475
+ private resizeIntentRequired = false;
476
+ private resizeIntentSatisfied = false;
477
+ /** Issue #294: seq of the F record that proved the current intent (gate
478
+ * freshness fact: the evidence must not postdate the covered window). */
479
+ private resizeIntentProofSeq: number | null = null;
480
+ private resizeIntentId = 0;
481
+ private pendingEarlySyncTarget: string | null = null;
482
+ /** Protocol transition facts; timers may mark expiry but never publish. */
483
+ private deadlineState: "pending" | "expired" = "pending";
484
+ private notReadyReason: string | null = null;
485
+ private parserWritesInFlight = 0;
486
+ private readonly attachStartedAt: number;
487
+ private readonly viewProofTrailing = createSafeTrailingClassifier();
488
+ private recentProtocolOutput: Array<{ seq: number; data: string }> = [];
489
+ private proofResyncRequested = false;
490
+ /** Runner-reported reporter capability. Without it the attach keeps the
491
+ * accepted legacy deadline path (old/no-reporter hosts are not stranded). */
492
+ private frameWitnessAvailable = false;
493
+ /** Issue #284 latch layer (spec §3.3/I6): set once when frameWitnessAvailable
494
+ * first becomes true during THIS attach. Capability loss never clears it —
495
+ * the attach stays on the committed presentation path (no legacy deadline
496
+ * restore) until detach/dispose; same-component reconnects and view-layer
497
+ * invalidations (resnapshot/reset/baseline change) leave it alone. */
498
+ private witnessLatched = false;
499
+ /** Issue #284 failure-fact layer (spec §3.1.1/I6): the baseline token an
500
+ * unrecovered invalid proof classification was recorded on. The effective
501
+ * sticky state is (token === baselineToken). Recovery is PUBLISH-ONLY: a
502
+ * covered classification alone never clears it, because coverage is
503
+ * established before the full-view policy validates
504
+ * sequence/metadata/geometry/intent/identity — a wrong-geometry F would
505
+ * otherwise wash the sticky fact and re-open the degraded path. Only
506
+ * evaluateAttachReady's policy "publish" on the current baseline/identity
507
+ * (or a new baseline identity via replaceParser at an accepted
508
+ * snapshotReady, which rebinds it) clears/rebinds it. Capability loss —
509
+ * which nulls latestViewProof — deliberately keeps it. */
510
+ private proofInvalidatedBaselineToken: number | null = null;
511
+ /** Issue #288 D1/I8 hard-dominance latch: the baseline token a HARD invalid
512
+ * family classification (classifyProofInvalidFamily === "hard") latched
513
+ * on; the effective state is (token === baselineToken), exactly like the
514
+ * sticky failure fact. Hard dominance: once latched, later trailing
515
+ * shapes, other non-covered shapes, capability loss, S records, and
516
+ * missing proofs NEVER clear it — the cap floor stays closed for this
517
+ * baseline. Cleared only where the sticky fact clears: the policy PUBLISH
518
+ * branch (a fully valid F) or a baseline identity change (replaceParser
519
+ * increments baselineToken, so the stale binding goes inactive). The
520
+ * cap-floor publish-degraded deliberately does NOT clear it (I7). */
521
+ private proofHardInvalidatedThisBaseline: number | null = null;
522
+ /** Last §3.1.1 classification assembled for the policy (diagnostics/readout). */
523
+ private lastProofStatus: "none" | "missing" | "invalid" | "covered" | null = null;
524
+ /** Sticky-state twin of the classification (diagnostics/readout): mirrors
525
+ * the POST-update sticky state — (proofInvalidatedBaselineToken ===
526
+ * baselineToken) AFTER the classification applied its binding change, so
527
+ * the invalidation (false→true) and publish recovery (true→false)
528
+ * transitions are both visible to settle readouts. */
529
+ private lastProofStickyInvalid = false;
530
+ /** Issue #284 §3.4: which path settled this attach; null while still
531
+ * waiting (the wait reason stays in notReadyReason, semantics unchanged). */
532
+ private readyReason: AttachReadyReason | null = null;
533
+ /** Last complete modern projection installed at a real ?2026l boundary. */
534
+ private committedView: CommittedView | null = null;
535
+ /** Display-only same-generation/geometry recovery view; never readiness. */
536
+ private recoveryView: CommittedView | null = null;
537
+ private recoveryGeneration: string | null = null;
538
+ private currentWireGeneration: string | null = null;
539
+ private emptyResetPending = false;
540
+ private attachWaitToken = 0;
226
541
  private cols = 120;
227
542
  private rows = 24;
228
543
  // Absolute buffer line shown at the top of the viewport. null means follow bottom.
@@ -238,7 +553,12 @@ export class PtyAttachComponent implements Component {
238
553
  private desyncProbeTimer: ReturnType<typeof setInterval> | null = null;
239
554
  /** Injectable clock for desync gating (tests override this). */
240
555
  private nowFn: () => number = () => Date.now();
556
+ /** Issue #284: attach-lifecycle clock (deadlines + attach timers). */
557
+ private readonly clock: AttachClock;
241
558
  private selection: MouseSelection | null = null;
559
+ /** Issue #172/#174/#258: the shared settle core owns the gesture serial, the
560
+ * deferral and the closed gate; attach supplies only the X11 PRIMARY mirror. */
561
+ private readonly selectionSettler: ReturnType<typeof createFullscreenSelectionSettler>;
242
562
  private selectionDragging = false;
243
563
  private selectionAutoScrollTimer: ReturnType<typeof setInterval> | null = null;
244
564
  private selectionAutoScrollLines = 0;
@@ -258,8 +578,25 @@ export class PtyAttachComponent implements Component {
258
578
  // initial resize-jiggle redraws settle, so attach never visibly scrolls/flashes the
259
579
  // buffer. `receivedOutput` tracks buffer content; `attaching` gates whether we paint it.
260
580
  private attaching = true;
261
- private attachSettleTimer: ReturnType<typeof setTimeout> | null = null;
262
- private attachHardTimeout: ReturnType<typeof setTimeout> | null = null;
581
+ private attachSettleTimer: unknown = null;
582
+ private attachHardTimeout: unknown = null;
583
+ // Issue #284 recovery budget: armed ONCE per attach lifetime at the first
584
+ // startAttachSettle entry (deadline = attachStartedAt + 250ms). Reconnect
585
+ // re-entry must never re-arm or extend it (I5). The callback is fenced by
586
+ // the attach lifetime itself — attaching && !closed && budgetArmed — NOT by
587
+ // attachWaitToken: that token increments on every startAttachSettle re-entry
588
+ // and would permanently invalidate the armed callback after a reconnect
589
+ // (spec §3.2 fence lifecycle). Stale-connection views stay blocked by the
590
+ // identity fence (I3) instead.
591
+ private attachRecoveryBudgetTimer: unknown = null;
592
+ private budgetArmed = false;
593
+ /** Issue #288 D2: which wait phases already recorded their wait diagnostic
594
+ * — single-shot per phase per attach (the budgetArmed fence pattern). */
595
+ private attachWaitDiagnosticEmitted: { budget: boolean; cap: boolean } = { budget: false, cap: false };
596
+ /** Timer fact only: the budget deadline passed while this attach was still
597
+ * waiting. Publishing on it is the policy's decision (T6 wiring), never the
598
+ * timer's. */
599
+ private budgetElapsed = false;
263
600
  // Last scheme delivered to the child at settle (issue #161). Starts null:
264
601
  // null never matches the duplicate check, so a timeout-then-late sequence
265
602
  // still delivers. Single-shot per attach — settle runs at most once.
@@ -295,6 +632,20 @@ export class PtyAttachComponent implements Component {
295
632
  private readonly done: (result: PtyAttachResult) => void,
296
633
  private readonly opts: PtyAttachOptions,
297
634
  ) {
635
+ // Issue #284 clock seam: assigned from the constructor parameter (not a
636
+ // field initializer) so it is set regardless of the loader's field-init
637
+ // semantics, before any attach-lifecycle deadline is computed. Output
638
+ // timestamps (nowFn) follow the injected clock too, so legacy deadline
639
+ // math never mixes virtual and wall time.
640
+ this.clock = opts.clock ?? hostAttachClock;
641
+ this.attachStartedAt = this.clock.now();
642
+ if (opts.clock) this.nowFn = opts.clock.now;
643
+ this.selectionSettler = createFullscreenSelectionSettler({
644
+ host: this.tui as FullscreenSelectionHost,
645
+ mirror: (text) => this.writePrimarySelection(text),
646
+ repaint: () => this.scheduleRender(),
647
+ shouldSettle: () => !this.closed,
648
+ });
298
649
  const size = this.currentSize();
299
650
  this.cols = size.cols;
300
651
  this.rows = size.rows;
@@ -302,6 +653,12 @@ export class PtyAttachComponent implements Component {
302
653
  // parameter property is set regardless of the TS loader's field-init semantics.
303
654
  this.imeCoalesceUninstall = installImeCursorCoalesce(this.tui);
304
655
  this.term = new Terminal({ cols: this.cols, rows: this.rows, scrollback: 2000, allowProposedApi: true });
656
+ this.kittyImages = process.env.AGENT_BOARD_FORWARD_IMAGES !== "0"
657
+ ? createPtyKittyImages(this.term, () => { this.historyFloor = 0; })
658
+ : null;
659
+ this.parserObservers = this.installParserObservers(this.term, this.parserEpoch);
660
+ this.parserObservationSupported = this.parserObservers.length > 0;
661
+ if (!this.parserObservationSupported) this.attachClient.forceLegacy("parser_observation_unavailable");
305
662
  // Keep mouse reporting enabled by default so wheel scrolling and local drag-to-copy
306
663
  // selection can coexist inside the attach surface. Set AGENT_BOARD_ATTACH_MOUSE=0
307
664
  // to fall back to terminal-native selection only.
@@ -418,25 +775,11 @@ export class PtyAttachComponent implements Component {
418
775
  this.send({ type: "input", data });
419
776
  return;
420
777
  }
421
- if (matchesKey(data, "ctrl+\\")) {
422
- // Unconditional, terminal-independent escape (issue #126): 0x1c is a
423
- // single raw ASCII byte every terminal forwards unchanged in raw
424
- // mode — no modifier-encoding dependency like Ctrl+Left (macOS
425
- // Terminal.app never emits it, WezTerm consumes it for tab
426
- // switching). Only caveat (documented in README): layouts where
427
- // `\` sits on AltGr may never produce this byte; the escape ladder
428
- // still covers those. matchesKey also covers the kitty CSI-u and
429
- // modifyOtherKeys encodings of the same chord.
430
- this.detach();
431
- return;
432
- }
433
- if (matchesKey(data, Key.ctrl("left"))) {
434
- // Explicit detach chord (issue #89): single ← is gated on editor state
435
- // (it doubles as cursor-left inside a non-empty draft), so a user with
436
- // a draft had no way out short of Ctrl+C/D, which kills the child Pi.
437
- // Ctrl+← is unambiguous intent — detach unconditionally, regardless of
438
- // editor state or socket liveness (same always-exitable guarantee as
439
- // the disconnected-← escape, issue #48).
778
+ if (resolveAttachDetachChord(data)) {
779
+ // Issue #266: unconditional detach chords — Ctrl+\ (raw 0x1c, #126),
780
+ // Ctrl+← (#89) and Alt+H (vim h = left). Bare ← stays gated on the
781
+ // pushed editor_state; a chord needs no gate. Rationale and the
782
+ // encoding matrix live in src/core/attach-detach.mjs.
440
783
  this.detach();
441
784
  return;
442
785
  }
@@ -520,13 +863,10 @@ export class PtyAttachComponent implements Component {
520
863
  return { handled: true, render: false };
521
864
  }
522
865
  const nativePasteEnabled = process.env.AGENT_BOARD_ATTACH_NATIVE_PASTE !== "0";
523
- if (shouldMirrorSelectionToPrimary(event, { nativePasteEnabled })) {
524
- // Observe only — pi's fullscreen selection keeps the event. Mirroring must
525
- // run after TuiAltScreen finalizes the selection for this event (overlays
526
- // are dispatched before the selection logic), hence the deferred tick.
527
- process.nextTick(() => this.mirrorFullscreenSelectionToPrimary());
528
- return undefined;
529
- }
866
+ // Issue #172 + #258: observe the gesture; the shared settler owns the
867
+ // serial guard, the deferral and the lifecycle gate.
868
+ this.selectionSettler.observeMouse(event);
869
+ if (isFullscreenSelectionEnd(event)) return undefined;
530
870
  const action = resolveAttachMouseAction(event, { nativePasteEnabled });
531
871
  if (action !== "paste-primary") return undefined;
532
872
  this.clearPendingClick();
@@ -536,22 +876,26 @@ export class PtyAttachComponent implements Component {
536
876
  }
537
877
 
538
878
  render(width: number): string[] {
879
+ if (this.closed) return [];
539
880
  this.resizeIfNeeded(width);
540
881
  const height = this.tui.terminal?.rows ?? 24;
541
882
  const bodyHeight = Math.max(1, height - 2);
542
883
  let body: string[];
543
- if (!this.attaching && this.receivedOutput) {
884
+ if (this.modernCommittedMode() && this.emptyResetPending) {
885
+ body = Array.from({ length: bodyHeight }, () => "");
886
+ } else if (!this.attaching && this.receivedOutput) {
544
887
  const projected = this.project(bodyHeight);
545
888
  body = projected.lines;
546
889
  while (body.length < bodyHeight) body.unshift("");
547
890
  } else {
548
891
  body = this.renderLoading(bodyHeight, width);
549
892
  }
893
+ const headerTitle = this.opts.prLabel ? `${this.opts.title} · ${this.opts.prLabel}` : this.opts.title;
550
894
  const header = this.confirmArmed
551
895
  ? this.theme.fg("accent", this.theme.bold(` Delete "${truncateToWidth(this.opts.title, 24, "")}"? `)) +
552
896
  this.theme.fg("muted", "y confirms · any other key cancels")
553
- : this.theme.fg("accent", this.theme.bold(` ${this.opts.title} `)) +
554
- this.theme.fg("muted", `${this.status} · opens links · drag selects+copies · Ctrl+←/Ctrl+\\ detach`);
897
+ : this.theme.fg("accent", this.theme.bold(` ${headerTitle} `)) +
898
+ this.theme.fg("muted", `${this.status} · links · select+copy · Ctrl+←/Ctrl+\\/Alt+H detach`);
555
899
  return [clip(header, width), ...body.map((l) => clipTerminalLine(l, width)), this.theme.fg("dim", "─".repeat(width))];
556
900
  }
557
901
 
@@ -567,7 +911,7 @@ export class PtyAttachComponent implements Component {
567
911
  out.push(center(this.theme.fg("accent", this.theme.bold(title)), width));
568
912
  out.push(center(this.theme.fg("muted", detail), width));
569
913
  out.push("");
570
- out.push(center(this.theme.fg("dim", "Ctrl+←/Ctrl+\\ to detach"), width));
914
+ out.push(center(this.theme.fg("dim", "Ctrl+←/Ctrl+\\/Alt+H to detach"), width));
571
915
  while (out.length < height) out.push("");
572
916
  return out.slice(0, height);
573
917
  }
@@ -605,6 +949,154 @@ export class PtyAttachComponent implements Component {
605
949
  this.done({ action: "detached" });
606
950
  }
607
951
 
952
+ /** Install the component's public ?2026 observers; false return keeps xterm defaults.
953
+ * Issue #278: the ownership adapter tracks ?2026 sync windows around ?1049
954
+ * alt-screen exits so external editor output can be projected live. */
955
+ private installParserObservers(term: XtermLike, epoch: number): Array<{ dispose(): void }> {
956
+ try {
957
+ return installAttachScreenOwnerObservers(term, {
958
+ initialState: createAttachScreenOwnerState(this.externalOutputActive),
959
+ // The .mjs adapter infers an untyped default callback; the transition
960
+ // handler below carries the exact shape (cast at this assignment only).
961
+ onTransition: ((info: AttachScreenOwnerTransition) => {
962
+ this.handleScreenOwnerTransition(term, epoch, info);
963
+ }) as () => void,
964
+ });
965
+ } catch {
966
+ return [];
967
+ }
968
+ }
969
+
970
+ /** Apply one ownership-adapter transition to the component: sync-window
971
+ * bookkeeping, interaction cleanup on an external-flag change, and the
972
+ * committed-view commit at a real sync close. */
973
+ private handleScreenOwnerTransition(term: XtermLike, epoch: number, { previous, current, syncOpenMarker, syncCloseMarker }: AttachScreenOwnerTransition): void {
974
+ if (this.closed || this.term !== term || this.parserEpoch !== epoch) return;
975
+ this.parserSyncOpen = current.syncOpen;
976
+ if (syncOpenMarker || syncCloseMarker) this.parserObserverEvents += 1;
977
+ if (current.externalOutputActive !== previous.externalOutputActive) {
978
+ if (this.localHydrationState === "hydrating") {
979
+ // Runner-synthesized hydration frames wrap their content in their own
980
+ // ?2026 window; that wrapper clear is not a real ownership return.
981
+ this.screenOwnerResyncPending = true;
982
+ } else if (this.attachMode !== "legacy") {
983
+ this.externalOutputActive = current.externalOutputActive;
984
+ this.resetExternalProjectionInteraction();
985
+ }
986
+ // Legacy mode: no adoption and no interaction cleanup — a Ctrl+G handoff
987
+ // must not destroy selection/scroll state on the raw-buffer surface.
988
+ }
989
+ if (syncCloseMarker) this.commitCommittedView(term, epoch, "sync-close");
990
+ }
991
+
992
+ /** Reinstall the ownership observers on the current parser after a hydration
993
+ * window that suppressed frame-wrapper ownership transitions: the adapter
994
+ * re-initializes from the component's preserved external ownership. The
995
+ * observed sync-window position is kept; failure keeps the old observers. */
996
+ private resyncScreenOwnerAdapter(term: XtermLike, epoch: number): void {
997
+ const syncOpen = this.parserSyncOpen;
998
+ const observers = this.installParserObservers(term, epoch);
999
+ if (observers.length === 0) return;
1000
+ for (const observer of this.parserObservers) {
1001
+ try { observer.dispose(); } catch { /* best effort */ }
1002
+ }
1003
+ this.parserObservers = observers;
1004
+ this.parserSyncOpen = syncOpen;
1005
+ }
1006
+
1007
+ /** Side-effect boundary for an external-ownership change: stale Pi interaction
1008
+ * geometry (viewport/selection/clicks) must not leak onto the external or
1009
+ * restored surface. Never sends input and never forces a parser read. */
1010
+ private resetExternalProjectionInteraction(): void {
1011
+ this.clearSelectionAutoScroll();
1012
+ this.clearPendingClick();
1013
+ this.selection = null;
1014
+ this.selectionDragging = false;
1015
+ this.lastClickPoint = null;
1016
+ this.lastClickAt = 0;
1017
+ this.viewportTop = null;
1018
+ }
1019
+
1020
+ /**
1021
+ * Replace the local parser exactly at an accepted authoritative snapshotReady:
1022
+ * same constructor options, observers installed before the first frame write.
1023
+ * Creation/observer failure is fail-closed (old parser retained, no write).
1024
+ */
1025
+ private replaceParser(): boolean {
1026
+ // Preserve the last complete same-generation view before a nonempty
1027
+ // resnapshot replaces the parser. An empty baseline clears it later in
1028
+ // the same snapshotReady event.
1029
+ this.captureRecoveryView();
1030
+ let next: XtermLike;
1031
+ try {
1032
+ next = new Terminal({ cols: this.cols, rows: this.rows, scrollback: 2000, allowProposedApi: true });
1033
+ } catch {
1034
+ return false;
1035
+ }
1036
+ const nextEpoch = this.parserEpoch + 1;
1037
+ const observers = this.installParserObservers(next, nextEpoch);
1038
+ let nextImages: ReturnType<typeof createPtyKittyImages> | null = null;
1039
+ try {
1040
+ if (this.kittyImages) nextImages = createPtyKittyImages(next, () => { this.historyFloor = 0; });
1041
+ } catch {
1042
+ for (const observer of observers) observer.dispose();
1043
+ try { next.dispose?.(); } catch { /* best effort */ }
1044
+ return false;
1045
+ }
1046
+ if (observers.length === 0) {
1047
+ nextImages?.dispose();
1048
+ try { next.dispose?.(); } catch { /* best effort */ }
1049
+ return false;
1050
+ }
1051
+ const previous = this.term;
1052
+ const previousObservers = this.parserObservers;
1053
+ const previousImages = this.kittyImages;
1054
+ this.term = next;
1055
+ this.kittyImages = nextImages;
1056
+ this.parserObservers = observers;
1057
+ this.parserEpoch = nextEpoch;
1058
+ this.baselineToken += 1;
1059
+ this.replacementFailureCount = 0;
1060
+ this.parserObservationSupported = true;
1061
+ this.parserSyncOpen = false;
1062
+ this.parserWritesInFlight = 0;
1063
+ this.committedView = null;
1064
+ this.historyFloor = 0;
1065
+ this.viewportTop = null;
1066
+ this.selection = null;
1067
+ this.selectionDragging = false;
1068
+ this.localHydrationState = "idle";
1069
+ for (const observer of previousObservers) {
1070
+ try { observer.dispose(); } catch { /* best effort */ }
1071
+ }
1072
+ previousImages?.dispose();
1073
+ try { previous.dispose?.(); } catch { /* best effort */ }
1074
+ return true;
1075
+ }
1076
+
1077
+ private disposeCurrentParser(): void {
1078
+ for (const observer of this.parserObservers) {
1079
+ try { observer.dispose(); } catch { /* best effort */ }
1080
+ }
1081
+ this.parserObservers = [];
1082
+ this.kittyImages?.dispose();
1083
+ this.kittyImages = null;
1084
+ try { this.term.dispose?.(); } catch { /* best effort */ }
1085
+ }
1086
+
1087
+ /** Bounded fail-closed policy for a failed authoritative parser replacement. */
1088
+ private handleParserReplacementFailure(): void {
1089
+ this.protocolBaselineState = "unverified";
1090
+ this.localHydrationState = "failed";
1091
+ this.publishabilityState = "wait";
1092
+ this.latestViewProof = null;
1093
+ this.viewProofRecords = [];
1094
+ this.viewProofRecordCount = 0;
1095
+ this.replacementFailureCount += 1;
1096
+ if (this.replacementFailureCount <= 3) this.attachClient.requestResync("parser_replacement_failed");
1097
+ else this.attachClient.forceLegacy("parser_replacement_failed");
1098
+ }
1099
+
608
1100
  private connect(): void {
609
1101
  if (this.closed || this.connected || this.socket) return;
610
1102
  // On Windows the control socket is a named pipe — it never exists as a
@@ -626,10 +1118,25 @@ export class PtyAttachComponent implements Component {
626
1118
  return;
627
1119
  }
628
1120
  this.clearRetry();
1121
+ this.outputRenderScheduler.cancel();
1122
+ this.captureRecoveryView();
629
1123
  this.connected = true;
630
1124
  this.everConnected = true;
1125
+ this.connectionToken += 1;
1126
+ this.committedView = null;
1127
+ // Issue #284 view layer (I6): a connection-generation change also
1128
+ // invalidates the old proof facts — only the new connection's
1129
+ // snapshot/records may re-establish them. The latch survives: it is
1130
+ // attach-scoped, not connection-scoped.
1131
+ this.latestViewProof = null;
1132
+ this.viewProofIdentity = null;
1133
+ this.viewProofTrailing.reset();
1134
+ this.currentWireGeneration = null;
1135
+ // Do not paint the previous generation between reconnect and its
1136
+ // confirming hello/status; same-generation status clears this gate.
1137
+ this.emptyResetPending = true;
631
1138
  this.disconnectedAt = null;
632
- this.status = "attached";
1139
+ this.status = this.recoveryView !== null ? "reconnecting…" : "attached";
633
1140
  this.send({ type: "hello", clientId: `ui-${Date.now()}`, wantOutput: true });
634
1141
  // Snapshot+subscribe attach (issue #91 phase 4): the first connect
635
1142
  // probes with subscribe_terminal (old runners stay silent → probe
@@ -644,7 +1151,7 @@ export class PtyAttachComponent implements Component {
644
1151
  // so the jiggle never runs there (armLegacyJiggle guards the race).
645
1152
  this.armLegacyJiggle();
646
1153
  this.enableMouseScroll();
647
- this.scheduleRender();
1154
+ if (!this.emptyResetPending) this.scheduleRender();
648
1155
  this.startAttachSettle();
649
1156
  });
650
1157
  socket.on("data", (chunk) => {
@@ -655,6 +1162,7 @@ export class PtyAttachComponent implements Component {
655
1162
  // A failed socket can close after a replacement connection has already
656
1163
  // succeeded. Never let that stale event clear the replacement state.
657
1164
  if (this.socket !== socket) return;
1165
+ this.captureRecoveryView();
658
1166
  this.socket = null;
659
1167
  this.connected = false;
660
1168
  this.disconnectedAt ??= Date.now();
@@ -676,6 +1184,7 @@ export class PtyAttachComponent implements Component {
676
1184
  try { socket.destroy(); } catch { /* best-effort stale-socket cleanup */ }
677
1185
  return;
678
1186
  }
1187
+ this.captureRecoveryView();
679
1188
  this.socket = null;
680
1189
  this.connected = false;
681
1190
  // Notify before nulling: the close event that follows will hit the
@@ -746,22 +1255,547 @@ export class PtyAttachComponent implements Component {
746
1255
  */
747
1256
  private startAttachSettle(): void {
748
1257
  if (!this.attaching) return;
1258
+ this.armAttachRecoveryBudget();
1259
+ this.attachWaitToken += 1;
1260
+ const waitToken = this.attachWaitToken;
749
1261
  this.deferAttachSettle();
750
- if (!this.attachHardTimeout) {
751
- this.attachHardTimeout = setTimeout(() => this.finishAttachTransition(), ATTACH_HARD_TIMEOUT_MS);
752
- this.attachHardTimeout.unref?.();
1262
+ if (this.attachHardTimeout !== null) this.clock.clear(this.attachHardTimeout);
1263
+ const remainingHard = Math.max(0, ATTACH_HARD_TIMEOUT_MS - (this.clock.now() - this.attachStartedAt));
1264
+ this.attachHardTimeout = this.clock.schedule(() => this.handleAttachHardTimeout(waitToken), remainingHard);
1265
+ }
1266
+
1267
+ /** Arm the recovery budget once per attach lifetime; every later
1268
+ * startAttachSettle re-entry (reconnect) is a no-op so the deadline never
1269
+ * moves (I5). */
1270
+ private armAttachRecoveryBudget(): void {
1271
+ if (this.budgetArmed || this.closed || !this.attaching) return;
1272
+ this.budgetArmed = true;
1273
+ const remaining = Math.max(0, ATTACH_RECOVERY_BUDGET_MS - (this.clock.now() - this.attachStartedAt));
1274
+ this.attachRecoveryBudgetTimer = this.clock.schedule(() => this.handleAttachRecoveryBudgetTimeout(), remaining);
1275
+ }
1276
+
1277
+ /** Budget expiry records the timer fact and re-evaluates readiness at the
1278
+ * shared convergence point. The fence is the attach lifetime only (spec
1279
+ * §3.2): a settled or closed component records nothing. */
1280
+ private handleAttachRecoveryBudgetTimeout(): void {
1281
+ this.attachRecoveryBudgetTimer = null;
1282
+ if (!this.budgetArmed || !this.attaching || this.closed) return;
1283
+ this.budgetElapsed = true;
1284
+ // Issue #288 D2: the budget expiry leaves on-disk wait evidence — emitted
1285
+ // BEFORE the policy re-evaluation so a settle it triggers always follows
1286
+ // the budget record (A4 ordering).
1287
+ this.emitAttachWaitExpiredDiagnostic("budget");
1288
+ this.evaluateAttachReady();
1289
+ }
1290
+
1291
+ private clearAttachRecoveryBudget(): void {
1292
+ if (this.attachRecoveryBudgetTimer !== null) {
1293
+ this.clock.clear(this.attachRecoveryBudgetTimer);
1294
+ this.attachRecoveryBudgetTimer = null;
753
1295
  }
754
1296
  }
755
1297
 
756
1298
  private deferAttachSettle(): void {
757
- if (!this.attaching) return;
758
- if (this.attachSettleTimer) clearTimeout(this.attachSettleTimer);
759
- this.attachSettleTimer = setTimeout(() => this.finishAttachTransition(), ATTACH_SETTLE_MS);
760
- this.attachSettleTimer.unref?.();
1299
+ // Protocol sessions never defer the legacy settle; a LATCHED session
1300
+ // stays on that path even after capability loss (issue #284 I6) — a
1301
+ // post-loss reconnect/output must not resurrect the legacy settle.
1302
+ if (!this.attaching || this.modernCommittedMode()) return;
1303
+ if (this.attachSettleTimer !== null) this.clock.clear(this.attachSettleTimer);
1304
+ const waitToken = this.attachWaitToken;
1305
+ this.attachSettleTimer = this.clock.schedule(() => this.handleAttachSettleTimeout(waitToken), ATTACH_SETTLE_MS);
1306
+ }
1307
+
1308
+ /** Legacy settle callback. In protocol mode the timer is cancelled; an
1309
+ * undecided timer may not consume the first transition either. */
1310
+ private handleAttachSettleTimeout(waitToken = this.attachWaitToken): void {
1311
+ if (waitToken !== this.attachWaitToken) return;
1312
+ this.attachSettleTimer = null;
1313
+ if (!this.attaching || this.closed) return;
1314
+ // A latched protocol attach is never legacy-compatible: capability loss
1315
+ // keeps the committed path (issue #284 I6), so this timer may not consume
1316
+ // the transition for it.
1317
+ const legacyCompatible = this.attachMode === "legacy" || (this.attachMode === "protocol" && !this.modernCommittedMode());
1318
+ if (legacyCompatible) this.finishAttachTransition("legacy-settle");
1319
+ }
1320
+
1321
+ /** The 2500 ms cap never forces a modern publish of an UNFINISHED frame. It
1322
+ * records an explicit expired wait and hands the decision to the readiness
1323
+ * policy: the 250 ms recovery budget (armed once at attach start) has long
1324
+ * elapsed by then, so the degraded chain alone decides whether a safely
1325
+ * committed view may be revealed — the #265 idle-downgrade special case is
1326
+ * deleted (issue #284 §3.2); the policy owns every reveal. Legacy keeps its
1327
+ * old reveal. */
1328
+ private handleAttachHardTimeout(waitToken = this.attachWaitToken): void {
1329
+ if (waitToken !== this.attachWaitToken) return;
1330
+ this.attachHardTimeout = null;
1331
+ if (!this.attaching || this.closed) return;
1332
+ // Same latch rule as the settle timeout: a latched attach never falls
1333
+ // back to the legacy reveal branch (issue #284 I6).
1334
+ const legacyCompatible = this.attachMode === "legacy" || (this.attachMode === "protocol" && !this.modernCommittedMode());
1335
+ if (legacyCompatible) {
1336
+ this.finishAttachTransition("legacy-cap");
1337
+ return;
1338
+ }
1339
+ this.deadlineState = "expired";
1340
+ this.notReadyReason = this.attachMode === "protocol" ? "deadline-expired:waiting-for-complete-frame" : "deadline-expired:mode-undecided";
1341
+ this.publishabilityState = "unknown";
1342
+ // Issue #288 D2: the cap expiry is the second wait phase — recorded after
1343
+ // the deadline state flip (and after the budget record, which fired at
1344
+ // 250ms) and before the policy re-evaluation, so a cap-floor settle it
1345
+ // triggers still lands after both wait records (A4 ordering).
1346
+ this.emitAttachWaitExpiredDiagnostic("cap");
1347
+ this.evaluateAttachReady();
1348
+ this.scheduleRender();
761
1349
  }
762
1350
 
763
- private finishAttachTransition(): void {
764
- if (!this.attaching) return;
1351
+ /** A late legacy decision restores the ORIGINAL deadlines (remaining time),
1352
+ * not a fresh extended window. */
1353
+ private restoreLegacyDeadlines(): void {
1354
+ if (!this.attaching || this.closed) return;
1355
+ const now = this.clock.now();
1356
+ if (now - this.attachStartedAt >= ATTACH_HARD_TIMEOUT_MS) {
1357
+ this.finishAttachTransition("legacy-cap");
1358
+ return;
1359
+ }
1360
+ const settleBase = this.lastOutputAt > 0 ? this.lastOutputAt : this.attachStartedAt;
1361
+ const remaining = Math.max(0, ATTACH_SETTLE_MS - (now - settleBase));
1362
+ if (this.attachSettleTimer !== null) this.clock.clear(this.attachSettleTimer);
1363
+ const waitToken = this.attachWaitToken;
1364
+ this.attachSettleTimer = this.clock.schedule(() => this.handleAttachSettleTimeout(waitToken), remaining);
1365
+ if (this.attachHardTimeout === null) {
1366
+ this.attachHardTimeout = this.clock.schedule(() => this.handleAttachHardTimeout(waitToken), Math.max(0, ATTACH_HARD_TIMEOUT_MS - (now - this.attachStartedAt)));
1367
+ }
1368
+ }
1369
+
1370
+ private currentViewIdentity() {
1371
+ return {
1372
+ connectionToken: this.connectionToken,
1373
+ baselineToken: this.baselineToken,
1374
+ generation: this.attachClient.getIdentity().generation ?? "local",
1375
+ parser: this.term,
1376
+ geometryRevision: this.geometryRevision,
1377
+ targetCols: this.cols,
1378
+ targetRows: this.rows,
1379
+ closed: this.closed,
1380
+ };
1381
+ }
1382
+
1383
+ /** Snapshot the visible complete grid at a real close boundary. Only
1384
+ * primitives are copied; no xterm BufferLine/Cell survives this call.
1385
+ * `source` records which path captured the grid (spec §3.1 predicate 7):
1386
+ * "snapshot" — the authoritative hydration write of a validated non-empty
1387
+ * snapshot frame; "sync-close" — a locally parsed closed ?2026 sync frame. */
1388
+ private commitCommittedView(term: XtermLike, epoch: number, source: "snapshot" | "sync-close"): void {
1389
+ if (this.closed || this.term !== term || this.parserEpoch !== epoch) return;
1390
+ if (!this.modernCommittedMode() || this.localHydrationState === "hydrating") return;
1391
+ const height = this.bodyHeight();
1392
+ const buf = term.buffer.active;
1393
+ const start = Math.max(0, Math.min(this.viewportTop ?? this.liveBottomViewportTop(height), Math.max(0, buf.length - height)));
1394
+ const end = Math.min(buf.length, start + height);
1395
+ const rows: CommittedRow[] = [];
1396
+ // Capture image APCs with the committed grid so recovery can outlive
1397
+ // the parser and its Kitty markers during an authoritative resnapshot.
1398
+ const kittyLines = this.kittyImages?.hasPlacements() ? this.kittyImages.project(Array(end - start).fill(""), start, end - start) : undefined;
1399
+ for (let lineIndex = start; lineIndex < end; lineIndex += 1) {
1400
+ const line = buf.getLine(lineIndex);
1401
+ const cells: SnapshotCell[] = [];
1402
+ if (line) {
1403
+ for (let x = 0; x < line.length; x += 1) {
1404
+ const cell = line.getCell(x);
1405
+ if (!cell || cell.getWidth() === 0) {
1406
+ cells.push(SnapshotCell.empty());
1407
+ continue;
1408
+ }
1409
+ cells.push(SnapshotCell.fromBufferCell(cell, osc8UriForCell(term, cell)));
1410
+ }
1411
+ }
1412
+ rows.push({ cells: new SnapshotLine(cells), kittyPrefix: kittyLines?.[lineIndex - start] ?? "" });
1413
+ }
1414
+ const cursor = projectPtyCursor(buf, start, height);
1415
+ // The grid's actual dimensions at commit (duck-typed xterm read; the
1416
+ // parser is kept at this.cols/this.rows, but the fact must come from the
1417
+ // captured grid itself, never be re-derived from the current target at
1418
+ // assembly time — spec §3.1 predicate 4).
1419
+ const dims = term as { cols?: unknown; rows?: unknown };
1420
+ const sourceCols = typeof dims.cols === "number" && dims.cols > 0 ? dims.cols : this.cols;
1421
+ const sourceRows = typeof dims.rows === "number" && dims.rows > 0 ? dims.rows : this.rows;
1422
+ // §3.1 predicate 7 (locally closed completeness only — no semantic
1423
+ // boot/raw claim without an F): a snapshot commit is complete when the
1424
+ // validated non-empty frame finished hydrating (this method early-returns
1425
+ // while hydrating, and empty baselines never write a frame); a sync-close
1426
+ // commit is closed by definition. Anything else fails closed to "unknown".
1427
+ const contentKind: "complete" | "unknown" =
1428
+ source === "snapshot"
1429
+ ? this.protocolBaselineState === "valid-content" && this.localHydrationState === "complete" ? "complete" : "unknown"
1430
+ : source === "sync-close"
1431
+ ? "complete"
1432
+ : "unknown";
1433
+ this.committedView = {
1434
+ identity: this.currentViewIdentity(),
1435
+ start,
1436
+ end,
1437
+ rows,
1438
+ cursor,
1439
+ cursorHidden: isPtyCursorHidden(term),
1440
+ viewportTop: this.viewportTop,
1441
+ proofSeq: null,
1442
+ source,
1443
+ sourceCols,
1444
+ sourceRows,
1445
+ contentKind,
1446
+ };
1447
+ this.recoveryView = null;
1448
+ this.recoveryGeneration = null;
1449
+ this.emptyResetPending = false;
1450
+ if (this.connected) this.status = "attached";
1451
+ // Issue #284 D4 rendezvous: a successful commit is a convergence point.
1452
+ // A late snapshot arriving after the budget expired re-evaluates
1453
+ // immediately instead of waiting for the next cap (spec D4).
1454
+ this.evaluateAttachReady();
1455
+ }
1456
+
1457
+ private captureRecoveryView(): void {
1458
+ if (!this.modernCommittedMode() || this.committedView === null || this.closed) return;
1459
+ if (!canPublishAttachView(this.committedView.identity, this.currentViewIdentity())) return;
1460
+ this.recoveryView = this.committedView;
1461
+ this.recoveryGeneration = this.committedView.identity.generation;
1462
+ }
1463
+
1464
+ private invalidateRecoveryView(): void {
1465
+ this.recoveryView = null;
1466
+ this.recoveryGeneration = null;
1467
+ }
1468
+
1469
+ private recoveryViewValid(): boolean {
1470
+ if (!this.modernCommittedMode() || this.recoveryView === null || this.closed) return false;
1471
+ if (this.recoveryView.identity.closed === true) return false;
1472
+ if (this.recoveryView.identity.targetCols !== this.cols || this.recoveryView.identity.targetRows !== this.rows) return false;
1473
+ if (this.recoveryView.identity.geometryRevision !== this.geometryRevision) return false;
1474
+ if (typeof this.currentWireGeneration !== "string" || this.currentWireGeneration.length === 0) return false;
1475
+ if (this.currentWireGeneration !== this.recoveryGeneration) return false;
1476
+ return true;
1477
+ }
1478
+
1479
+ private activeCommittedView(): CommittedView | null {
1480
+ if (this.committedViewValid()) return this.committedView;
1481
+ if (this.recoveryViewValid()) return this.recoveryView;
1482
+ return null;
1483
+ }
1484
+
1485
+ /** Committed-path membership (projection, commits, recovery, selection
1486
+ * source): protocol mode with the reporter capability OR the #284 latch —
1487
+ * capability loss after a latched attach keeps this path alive (spec §3.3). */
1488
+ private modernCommittedMode(): boolean {
1489
+ return this.attachMode === "protocol" && (this.frameWitnessAvailable || this.witnessLatched);
1490
+ }
1491
+
1492
+ /** Visible/interaction fork (issue #278): the committed projection is used in
1493
+ * modern mode except while an external editor owns the screen — then the live
1494
+ * buffer is projected/addressed. Hydration keeps committed blank protection
1495
+ * even under external ownership, so an open frame never leaks partial rows. */
1496
+ private usesCommittedProjection(): boolean {
1497
+ return this.modernCommittedMode() &&
1498
+ (!this.externalOutputActive || this.localHydrationState === "hydrating");
1499
+ }
1500
+
1501
+ private committedViewValid(): boolean {
1502
+ if (this.committedView === null) return false;
1503
+ return canPublishAttachView(this.committedView.identity, this.currentViewIdentity());
1504
+ }
1505
+
1506
+ private liveBottomViewportTop(height: number): number {
1507
+ const buf = this.term.buffer.active;
1508
+ const bottom = Math.min(buf.length, buf.baseY + this.rows);
1509
+ return Math.max(0, bottom - height);
1510
+ }
1511
+
1512
+ private committedLineAt(lineIndex: number): BufferLineLike | null {
1513
+ if (!this.modernCommittedMode()) return null;
1514
+ const view = this.activeCommittedView();
1515
+ if (view === null || lineIndex < view.start || lineIndex >= view.end) return null;
1516
+ return view.rows[lineIndex - view.start]?.cells ?? null;
1517
+ }
1518
+
1519
+ private captureViewProofIdentity(): void {
1520
+ this.viewProofIdentity = this.currentViewIdentity();
1521
+ }
1522
+
1523
+ private invalidateViewProof(reason: string): void {
1524
+ this.latestViewProof = { status: "unknown", reason, proof: null, throughSeq: null, cursorVisible: null };
1525
+ this.viewProofIdentity = null;
1526
+ this.viewProofTrailing.reset();
1527
+ // Issue #294: intent evidence is sticky — see noteGeometryIntent/snapshotReady/viewProofRecord.
1528
+ }
1529
+
1530
+ /** Feed ordinary output after the last F proof through the safe-trailing
1531
+ * classifier. Only a completely safe window may extend coverage. */
1532
+ private noteViewProofOutput(data: string): void {
1533
+ const coverage = this.latestViewProof as { status?: string; proof?: unknown } | null;
1534
+ if (this.attachMode !== "protocol" || coverage === null || coverage.status !== "covered" || coverage.proof === null) return;
1535
+ const localSeq = this.attachClient.getLastSeq();
1536
+ const state = this.viewProofTrailing.push(data);
1537
+ if (state.status === "safe") {
1538
+ this.latestViewProof = {
1539
+ status: "covered",
1540
+ reason: "safe-trailing",
1541
+ proof: (coverage as { proof: unknown }).proof,
1542
+ throughSeq: localSeq,
1543
+ cursorVisible: state.cursorVisible,
1544
+ };
1545
+ this.captureViewProofIdentity();
1546
+ } else {
1547
+ this.invalidateViewProof(state.status === "pending" ? "view-proof-trailing-pending" : `view-proof-trailing-${state.reason ?? "unsafe"}`);
1548
+ }
1549
+ }
1550
+
1551
+ private noteViewProofRecord(record: Record<string, unknown>): void {
1552
+ if (record.marker === "S") {
1553
+ this.viewProofRecords.push(record);
1554
+ if (this.viewProofRecords.length > MAX_VIEW_PROOF_RECORDS) this.viewProofRecords.shift();
1555
+ this.viewProofRecordCount += 1;
1556
+ this.invalidateViewProof("candidate-open");
1557
+ return;
1558
+ }
1559
+ if (record.marker === "A") {
1560
+ this.viewProofRecords.push(record);
1561
+ if (this.viewProofRecords.length > MAX_VIEW_PROOF_RECORDS) this.viewProofRecords.shift();
1562
+ this.viewProofRecordCount += 1;
1563
+ this.invalidateViewProof("candidate-aborted");
1564
+ return;
1565
+ }
1566
+ if (record.marker !== "F") return;
1567
+ this.viewProofRecords.push(record);
1568
+ if (this.viewProofRecords.length > MAX_VIEW_PROOF_RECORDS) this.viewProofRecords.shift();
1569
+ this.viewProofRecordCount += 1;
1570
+ this.latestViewProof = {
1571
+ status: "covered",
1572
+ reason: "safe-trailing",
1573
+ proof: record,
1574
+ throughSeq: record.seq,
1575
+ cursorVisible: typeof record.cursorVisible === "boolean" ? record.cursorVisible : null,
1576
+ };
1577
+ this.captureViewProofIdentity();
1578
+ this.viewProofTrailing.reset(typeof record.cursorVisible === "boolean" ? { cursorVisible: record.cursorVisible } : {});
1579
+ const proofSeq = Number(record.seq);
1580
+ const following = this.recentProtocolOutput.filter((chunk) => chunk.seq > proofSeq).sort((a, b) => a.seq - b.seq);
1581
+ let expectedSeq = proofSeq + 1;
1582
+ for (const chunk of following) {
1583
+ if (chunk.seq !== expectedSeq) {
1584
+ this.invalidateViewProof("view-proof-replay-gap");
1585
+ return;
1586
+ }
1587
+ expectedSeq = chunk.seq + 1;
1588
+ const state = this.viewProofTrailing.push(chunk.data);
1589
+ if (state.status !== "safe") {
1590
+ this.invalidateViewProof(state.status === "pending" ? "view-proof-trailing-pending" : `view-proof-trailing-${state.reason ?? "unsafe"}`);
1591
+ return;
1592
+ }
1593
+ this.latestViewProof = {
1594
+ status: "covered",
1595
+ reason: "safe-trailing",
1596
+ proof: record,
1597
+ throughSeq: chunk.seq,
1598
+ cursorVisible: state.cursorVisible,
1599
+ };
1600
+ this.captureViewProofIdentity();
1601
+ }
1602
+ if (this.attachClient.getLastSeq() >= expectedSeq) {
1603
+ this.invalidateViewProof("view-proof-replay-gap");
1604
+ }
1605
+ }
1606
+
1607
+ /** Derive proofStatus through the §3.1.1 pure classifier and manage the
1608
+ * sticky failure fact (the component-side duty of spec §3.1.1): any
1609
+ * invalid classification binds to the CURRENT baseline. The classifier
1610
+ * NEVER clears the binding here — recovery is publish-only (see
1611
+ * evaluateAttachReady's publish branch): noteViewProofRecord(F) builds
1612
+ * covered/safe-trailing coverage BEFORE the full-view policy validates
1613
+ * sequence/metadata/geometry/intent/identity, so a covered classification
1614
+ * on a non-publishable F must keep the degraded path blocked. A new
1615
+ * baseline identity (replaceParser at an accepted snapshotReady) rebinds
1616
+ * it. Capability loss (latestViewProof = null) keeps the recorded fact. */
1617
+ private classifyLatestProof(): "none" | "missing" | "invalid" | "covered" {
1618
+ const stickyInvalid = this.proofInvalidatedBaselineToken === this.baselineToken;
1619
+ const proofStatus = classifyProofStatus(this.latestViewProof as Record<string, unknown> | null, stickyInvalid);
1620
+ this.lastProofStatus = proofStatus;
1621
+ if (proofStatus === "invalid") this.proofInvalidatedBaselineToken = this.baselineToken;
1622
+ // Issue #288 D1: latch the HARD invalid family on the current baseline.
1623
+ // The family is a property of the ARRIVAL shape (never of the sticky
1624
+ // fact), so a trailing arrival under an existing sticky binding latches
1625
+ // nothing, while a hard arrival latches even when the sticky fact was
1626
+ // first set by a trailing shape — hard dominates (I8). Never cleared
1627
+ // here: same publish-only/baseline-rebind lifecycle as the sticky fact.
1628
+ if (proofStatus === "invalid" && classifyProofInvalidFamily(this.latestViewProof as Record<string, unknown> | null) === "hard") {
1629
+ this.proofHardInvalidatedThisBaseline = this.baselineToken;
1630
+ }
1631
+ // The diagnostic field mirrors the POST-update sticky state (review fix):
1632
+ // recording the pre-update value hid the invalidation transition
1633
+ // (false→true) from every settle readout built from it.
1634
+ this.lastProofStickyInvalid = this.proofInvalidatedBaselineToken === this.baselineToken;
1635
+ return proofStatus;
1636
+ }
1637
+
1638
+ /** Fact assembly for the accepted decideAttachPresentation gate. Issue #284
1639
+ * extends the assembly with the recovery facts (spec §3.1): the policy —
1640
+ * and only the policy — decides the committed-degraded publish; a timer
1641
+ * fact alone never publishes. */
1642
+ private evaluateAttachReady(): void {
1643
+ if (!this.attaching || this.closed || this.attachMode !== "protocol") return;
1644
+ // A latched attach keeps evaluating after capability loss (I6): the
1645
+ // committed presentation path — and with it the recovery facts — stays
1646
+ // alive until detach/dispose. Never-latched/legacy sessions keep the
1647
+ // legacy deadline path untouched.
1648
+ if (!this.modernCommittedMode()) return;
1649
+ const proofStatus = this.classifyLatestProof();
1650
+ if (this.parserWritesInFlight > 0) return;
1651
+ if (this.committedView === null) {
1652
+ this.notReadyReason = "committed-view-missing";
1653
+ return;
1654
+ }
1655
+ const coverage = this.latestViewProof as { status?: string; proof?: { metadata?: unknown } | null } | null;
1656
+ const proof = coverage?.status === "covered" && coverage.proof !== null ? coverage.proof : null;
1657
+ const localSeq = this.attachClient.getLastSeq();
1658
+ const baselineState =
1659
+ this.protocolBaselineState === "valid-empty" || this.protocolBaselineState === "valid-content"
1660
+ ? this.protocolBaselineState
1661
+ : this.localHydrationState === "hydrating"
1662
+ ? "hydrating"
1663
+ : this.protocolBaselineState;
1664
+ const committedView = this.committedView;
1665
+ const decision = decideAttachPresentation({
1666
+ closed: this.closed,
1667
+ mode: this.attachMode,
1668
+ baselineState,
1669
+ localParseComplete: this.parserWritesInFlight === 0 && this.localHydrationState !== "hydrating",
1670
+ frameState: this.parserSyncOpen ? "open" : this.parserWritesInFlight > 0 ? "unknown" : "complete",
1671
+ contentAvailable: this.receivedOutput === true && proof !== null,
1672
+ contentKind: proof === null ? "unknown" : "complete",
1673
+ localSeq,
1674
+ viewProof: coverage,
1675
+ viewIdentity: this.viewProofIdentity,
1676
+ currentIdentity: this.currentViewIdentity(),
1677
+ targetCols: this.cols,
1678
+ targetRows: this.rows,
1679
+ geometryRevision: this.geometryRevision,
1680
+ requiredGeometryRevision: this.resizeIntentRequired ? this.geometryRevision : undefined,
1681
+ resizeIntentRequired: this.resizeIntentRequired,
1682
+ resizeIntentSatisfied: this.resizeIntentSatisfied,
1683
+ resizeIntentProofSeq: this.resizeIntentProofSeq,
1684
+ intentId: this.resizeIntentId,
1685
+ deadlineState: this.deadlineState,
1686
+ // Issue #284 recovery facts (spec §3.1): plain facts recorded on the
1687
+ // committed view and by the §3.1.1 classifier. Supplying them opts the
1688
+ // protocol call into the degraded chain inside the policy.
1689
+ witnessLatched: this.witnessLatched,
1690
+ committedViewValid: this.committedViewValid(),
1691
+ committedViewSource: committedView.source,
1692
+ committedViewCols: committedView.sourceCols,
1693
+ committedViewRows: committedView.sourceRows,
1694
+ committedContentKind: committedView.contentKind,
1695
+ proofStatus,
1696
+ // Issue #288 D1 cap floor: the hard-latch absence is the policy's
1697
+ // recoverability fact — a trailing-only invalidation may pass
1698
+ // predicate 5 once the cap expires; a hard one never may.
1699
+ capRecoverable: this.proofHardInvalidatedThisBaseline !== this.baselineToken,
1700
+ budgetElapsed: this.budgetElapsed,
1701
+ });
1702
+ this.notReadyReason = decision.action === "wait" ? decision.reason : null;
1703
+ if (decision.action === "publish") {
1704
+ // Issue #284 §3.1.1 recovery is publish-only: the covered
1705
+ // classification precedes the full-view gates, so ONLY a policy
1706
+ // "publish" — a fully valid F for the current baseline/identity —
1707
+ // may clear the sticky failure fact. A wrong-geometry/intent F that
1708
+ // merely covers the proof channel must keep the degraded path
1709
+ // blocked (a covered-but-unpublishable F is exactly the shape the
1710
+ // degraded chain refuses via proof-status-covered).
1711
+ this.proofInvalidatedBaselineToken = null;
1712
+ this.proofHardInvalidatedThisBaseline = null;
1713
+ this.lastProofStickyInvalid = false;
1714
+ this.publishabilityState = "ready";
1715
+ this.finishAttachTransition("complete");
1716
+ } else if (decision.action === "publish-degraded") {
1717
+ this.publishabilityState = "ready";
1718
+ this.finishAttachTransition("committed-degraded");
1719
+ } else if (decision.action === "wait") {
1720
+ this.publishabilityState = this.deadlineState === "expired" ? "unknown" : "wait";
1721
+ }
1722
+ }
1723
+
1724
+ /** Issue #288 D2: the SHARED recovery-facts snapshot behind the settle and
1725
+ * wait diagnostic records — the #284 settle-diagnostic assembly (enum
1726
+ * whitelisting via sanitizeViewProofEnumPair, numeric-only committedView
1727
+ * identity, token exclusion) moved here verbatim; the two event wrappers
1728
+ * below add only their outcome field, so the whitelist logic is never
1729
+ * duplicated. Numbers and finite enums only — never tokens, screen text,
1730
+ * keys, or raw terminal data. */
1731
+ private buildAttachRecoveryFacts(): AttachRecoveryFacts {
1732
+ const committedView = this.committedView;
1733
+ const proof = sanitizeViewProofEnumPair(this.latestViewProof as Record<string, unknown> | null);
1734
+ return {
1735
+ notReadyReason: this.notReadyReason,
1736
+ publishabilityState: this.publishabilityState,
1737
+ deadlineState: this.deadlineState,
1738
+ witnessLatched: this.witnessLatched,
1739
+ budgetDeadline: this.attachStartedAt + ATTACH_RECOVERY_BUDGET_MS,
1740
+ budgetElapsed: this.budgetElapsed,
1741
+ proofStatus: this.lastProofStatus,
1742
+ proofStickyInvalid: this.lastProofStickyInvalid,
1743
+ committedView: committedView === null ? null : {
1744
+ // Numeric identity facts only: the local parser generation
1745
+ // (the committed view's epoch — identity.parser is the current
1746
+ // parser at every publish settle) and the geometry revision.
1747
+ // The connection/baseline tokens are deliberately omitted.
1748
+ generation: this.parserEpoch,
1749
+ geometryRevision: committedView.identity.geometryRevision,
1750
+ source: committedView.source,
1751
+ sourceCols: committedView.sourceCols,
1752
+ sourceRows: committedView.sourceRows,
1753
+ contentKind: committedView.contentKind,
1754
+ },
1755
+ latestViewProof: proof,
1756
+ };
1757
+ }
1758
+
1759
+ /** Issue #284 §3.4/D5: the settle record. Captured inside
1760
+ * finishAttachTransition before the wait state resets, so it keeps the
1761
+ * LAST wait reason. Byte-identical to the pre-#288 settle payload (the
1762
+ * readyReason field still leads the details object). */
1763
+ private buildSettleDiagnostic(source: AttachReadyReason): AttachRecoveryDiagnosticPatch {
1764
+ return {
1765
+ source: "attach",
1766
+ level: "info",
1767
+ code: "attach_settle_ready",
1768
+ message: `attach settle ready via ${source}`,
1769
+ details: { readyReason: source, ...this.buildAttachRecoveryFacts() },
1770
+ };
1771
+ }
1772
+
1773
+ /** Issue #288 D2: the wait record — the same recovery facts plus the
1774
+ * expired phase, and NO readyReason (a waiting attach has none). */
1775
+ private buildWaitExpiredDiagnostic(phase: AttachWaitExpiredPhase): AttachWaitExpiredDiagnosticPatch {
1776
+ return {
1777
+ source: "attach",
1778
+ level: "info",
1779
+ code: "attach_wait_expired",
1780
+ message: `attach wait expired at ${phase} deadline`,
1781
+ details: { phase, ...this.buildAttachRecoveryFacts() },
1782
+ };
1783
+ }
1784
+
1785
+ /** Issue #288 D2: record a wait-phase expiry on the onDiagnostic channel.
1786
+ * Emitted only while the attach is still waiting and at most once per
1787
+ * phase per attach — a settled or closed component records nothing, and a
1788
+ * re-scheduled deadline (reconnect re-entry of startAttachSettle) cannot
1789
+ * duplicate the event. */
1790
+ private emitAttachWaitExpiredDiagnostic(phase: AttachWaitExpiredPhase): void {
1791
+ if (this.closed || !this.attaching) return;
1792
+ if (this.attachWaitDiagnosticEmitted[phase]) return;
1793
+ this.attachWaitDiagnosticEmitted[phase] = true;
1794
+ this.opts.onDiagnostic?.(this.buildWaitExpiredDiagnostic(phase));
1795
+ }
1796
+
1797
+ private finishAttachTransition(source: AttachReadyReason): void {
1798
+ if (!this.attaching || this.closed) return;
765
1799
  // Note: jiggle retry chain is NOT cancelled here — it survives the settle
766
1800
  // transition because any successful jiggle triggers a fullRender which emits
767
1801
  // \x1b[2J, self-cancelling the chain. Post-settle jiggles only occur when the
@@ -771,15 +1805,25 @@ export class PtyAttachComponent implements Component {
771
1805
  // selection) is acceptable in exchange for self-healing. When the child is
772
1806
  // healthy, the very first jiggle's fullRender is detected and the chain
773
1807
  // stops before settle ends, so no post-settle jiggle fires at all.
1808
+ // Issue #284 §3.4: record which path settled BEFORE the wait state resets
1809
+ // (the diagnostic keeps the last wait reason; notReadyReason semantics are
1810
+ // unchanged — null once settled).
1811
+ const settleDiagnostic = this.buildSettleDiagnostic(source);
774
1812
  this.attaching = false;
775
- if (this.attachSettleTimer) {
776
- clearTimeout(this.attachSettleTimer);
1813
+ this.publishabilityState = "ready";
1814
+ this.readyReason = source;
1815
+ this.notReadyReason = null;
1816
+ this.opts.onDiagnostic?.(settleDiagnostic);
1817
+ this.firstAttachSideEffectsApplied = true;
1818
+ if (this.attachSettleTimer !== null) {
1819
+ this.clock.clear(this.attachSettleTimer);
777
1820
  this.attachSettleTimer = null;
778
1821
  }
779
- if (this.attachHardTimeout) {
780
- clearTimeout(this.attachHardTimeout);
1822
+ if (this.attachHardTimeout !== null) {
1823
+ this.clock.clear(this.attachHardTimeout);
781
1824
  this.attachHardTimeout = null;
782
1825
  }
1826
+ this.clearAttachRecoveryBudget();
783
1827
  this.stopLoadingTicker();
784
1828
  // Force a full clear so the loading banner is replaced atomically by the settled
785
1829
  // buffer, instead of diffing banner lines into buffer lines.
@@ -1242,11 +2286,26 @@ export class PtyAttachComponent implements Component {
1242
2286
  }
1243
2287
  }
1244
2288
 
2289
+ private interactionLine(lineIndex: number): BufferLineLike | null {
2290
+ if (this.usesCommittedProjection()) return this.committedLineAt(lineIndex);
2291
+ return this.term.buffer.active.getLine(lineIndex) ?? null;
2292
+ }
2293
+
2294
+ private interactionNullCell(): BufferCellLike {
2295
+ return this.usesCommittedProjection() ? SnapshotCell.empty() : this.term.buffer.active.getNullCell();
2296
+ }
2297
+
1245
2298
  private mousePointForEvent(row: number, col: number, clampToBody: boolean): MousePoint | null {
1246
2299
  const height = this.bodyHeight();
1247
2300
  const bodyRow = row - 2;
1248
2301
  if (!clampToBody && (bodyRow < 0 || bodyRow >= height)) return null;
1249
2302
  const clampedRow = clampInt(bodyRow, 0, Math.max(0, height - 1));
2303
+ if (this.usesCommittedProjection()) {
2304
+ const view = this.activeCommittedView();
2305
+ if (view === null) return null;
2306
+ const line = clampInt(view.start + clampedRow, view.start, Math.max(view.start, view.end - 1));
2307
+ return { line, col: clampInt(col - 1, 0, Math.max(0, this.cols - 1)) };
2308
+ }
1250
2309
  this.clampViewportTop(height);
1251
2310
  const start = this.viewportTop ?? this.bottomViewportTop(height);
1252
2311
  const line = clampInt(start + clampedRow, 0, Math.max(0, this.term.buffer.active.length - 1));
@@ -1280,10 +2339,9 @@ export class PtyAttachComponent implements Component {
1280
2339
  }
1281
2340
 
1282
2341
  private selectWordAtPoint(point: MousePoint): boolean {
1283
- const buf = this.term.buffer.active;
1284
- const line = buf.getLine(point.line);
2342
+ const line = this.interactionLine(point.line);
1285
2343
  if (!line) return false;
1286
- const reusable = buf.getNullCell();
2344
+ const reusable = this.interactionNullCell();
1287
2345
  const range = findWordRangeAtCells(asciiCellsForBufferLine(line, reusable), point.col);
1288
2346
  if (!range) return false;
1289
2347
  this.selection = {
@@ -1301,10 +2359,9 @@ export class PtyAttachComponent implements Component {
1301
2359
  }
1302
2360
 
1303
2361
  private linkAtPoint(point: MousePoint): string | null {
1304
- const buf = this.term.buffer.active;
1305
- const line = buf.getLine(point.line);
2362
+ const line = this.interactionLine(point.line);
1306
2363
  if (!line) return null;
1307
- const reusable = buf.getNullCell();
2364
+ const reusable = this.interactionNullCell();
1308
2365
  const cell = line.getCell(point.col, reusable);
1309
2366
  const osc8 = cell ? osc8UriForCell(this.term, cell) : "";
1310
2367
  if (osc8) return osc8;
@@ -1367,19 +2424,6 @@ export class PtyAttachComponent implements Component {
1367
2424
  }
1368
2425
  }
1369
2426
 
1370
- /** Issue #174 (B2): after a selection gesture ends inside this overlay, copy
1371
- * pi's final selection text into the X11 PRIMARY selection so the classic
1372
- * select-then-middle-click-paste loop works in fullscreen. Runs on nextTick
1373
- * because overlays are dispatched before TuiAltScreen finalizes the
1374
- * selection for the same event. No-op in regular mode (no
1375
- * getActiveSelectionText) and under the native-paste kill switch. */
1376
- private mirrorFullscreenSelectionToPrimary(): void {
1377
- if (this.closed) return;
1378
- const alt = this.tui as { getActiveSelectionText?: () => string | undefined };
1379
- const text = alt.getActiveSelectionText?.();
1380
- if (typeof text === "string" && text.length > 0) this.writePrimarySelection(text);
1381
- }
1382
-
1383
2427
  /** Write `text` to the X11 PRIMARY selection so other apps can middle-click-paste it. */
1384
2428
  private writePrimarySelection(text: string): void {
1385
2429
  if (process.env.AGENT_BOARD_ATTACH_NATIVE_PASTE === "0") return;
@@ -1396,11 +2440,10 @@ export class PtyAttachComponent implements Component {
1396
2440
  private selectionText(): string {
1397
2441
  const range = normalizeSelection(this.selection);
1398
2442
  if (!range) return "";
1399
- const buf = this.term.buffer.active;
1400
- const reusable = buf.getNullCell();
2443
+ const reusable = this.interactionNullCell();
1401
2444
  const parts: string[] = [];
1402
2445
  for (let lineIndex = range.start.line; lineIndex <= range.end.line; lineIndex++) {
1403
- const line = buf.getLine(lineIndex);
2446
+ const line = this.interactionLine(lineIndex);
1404
2447
  if (!line) {
1405
2448
  parts.push("");
1406
2449
  continue;
@@ -1434,9 +2477,15 @@ export class PtyAttachComponent implements Component {
1434
2477
  // Render width is authoritative inside ctx.ui.custom; terminal.cols is not
1435
2478
  // consistently exposed by all Pi TUI versions.
1436
2479
  size.cols = Math.max(20, width);
1437
- if (size.cols === this.cols && size.rows === this.rows) return;
2480
+ if (size.cols === this.cols && size.rows === this.rows) {
2481
+ // A same-size render after the early protocol size-sync consumes that
2482
+ // one-shot pair; it must not mint another intent.
2483
+ if (this.pendingEarlySyncTarget === `${size.cols}x${size.rows}`) this.pendingEarlySyncTarget = null;
2484
+ return;
2485
+ }
1438
2486
  this.cols = size.cols;
1439
2487
  this.rows = size.rows;
2488
+ this.noteGeometryIntent(size.cols, size.rows);
1440
2489
  // A real terminal resize supersedes the hold protocol: cancel any armed
1441
2490
  // hold and adopt the new size as the baseline (guard G4, issue #25).
1442
2491
  this.jiggleRetry.notifyExternalResize(size.cols, size.rows);
@@ -1451,6 +2500,33 @@ export class PtyAttachComponent implements Component {
1451
2500
  this.enableMouseScroll();
1452
2501
  }
1453
2502
 
2503
+ /** A differing resize is exactly one local geometry revision/intent; an
2504
+ * applied ack is not completion, only a matching proof is. */
2505
+ private noteGeometryIntent(cols = this.cols, rows = this.rows, options: { early?: boolean } = {}): void {
2506
+ const target = `${cols}x${rows}`;
2507
+ if (options.early === true) {
2508
+ // Every actual early size-sync/mismatch advances once. De-dup is
2509
+ // ONLY early→next render; early→early is never collapsed. The latest
2510
+ // pending target is consumed by the next render of that target.
2511
+ this.pendingEarlySyncTarget = target;
2512
+ } else if (this.pendingEarlySyncTarget === target) {
2513
+ // The next render of the same target consumes the early pair.
2514
+ this.pendingEarlySyncTarget = null;
2515
+ return;
2516
+ } else {
2517
+ this.pendingEarlySyncTarget = null;
2518
+ }
2519
+ this.geometryRevision += 1;
2520
+ this.resizeIntentId = this.geometryRevision;
2521
+ this.resizeIntentRequired = true;
2522
+ this.resizeIntentSatisfied = false;
2523
+ this.resizeIntentProofSeq = null;
2524
+ this.committedView = null;
2525
+ this.recoveryView = null;
2526
+ this.recoveryGeneration = null;
2527
+ this.invalidateViewProof("geometry-resize");
2528
+ }
2529
+
1454
2530
  private sendResize(cols = this.cols, rows = this.rows): void {
1455
2531
  // Phase 5 (D4): enveloped resize when the host has an instance fence
1456
2532
  // (correlated applied/superseded acks; starting-window host_starting is
@@ -1489,6 +2565,14 @@ export class PtyAttachComponent implements Component {
1489
2565
 
1490
2566
  private tryScrollBy(linesUp: number): boolean {
1491
2567
  const height = this.bodyHeight();
2568
+ if (this.usesCommittedProjection()) {
2569
+ // The committed view is the only visible cache. Record the requested
2570
+ // viewport intent but let the child own history: the display stays on
2571
+ // the current complete range until a later verified boundary.
2572
+ const intent = scrollViewportTop(this.viewportTop, this.bottomViewportTop(height), linesUp, this.scrollFloorStart(height));
2573
+ this.viewportTop = intent.viewportTop;
2574
+ return false;
2575
+ }
1492
2576
  const result = scrollViewportTop(this.viewportTop, this.bottomViewportTop(height), linesUp, this.scrollFloorStart(height));
1493
2577
  this.viewportTop = result.viewportTop;
1494
2578
  if (result.changed) this.requestScrollRender();
@@ -1582,6 +2666,7 @@ export class PtyAttachComponent implements Component {
1582
2666
  const lines = this.parserBuffer.split("\n");
1583
2667
  this.parserBuffer = lines.pop() ?? "";
1584
2668
  let needsRender = false;
2669
+ let suppressGenerationRender = false;
1585
2670
  for (const line of lines) {
1586
2671
  if (!line.trim()) continue;
1587
2672
  try {
@@ -1598,7 +2683,58 @@ export class PtyAttachComponent implements Component {
1598
2683
  continue;
1599
2684
  }
1600
2685
  if (msg.type === "hello" || msg.type === "status") {
2686
+ const wireGeneration = typeof msg.generation === "string" ? msg.generation : typeof msg.status?.generation === "string" ? msg.status.generation : null;
2687
+ if (wireGeneration !== null) {
2688
+ this.currentWireGeneration = wireGeneration;
2689
+ this.emptyResetPending = this.recoveryGeneration !== null && wireGeneration !== this.recoveryGeneration;
2690
+ if (
2691
+ (this.committedView !== null && wireGeneration !== this.committedView.identity.generation) ||
2692
+ (this.recoveryGeneration !== null && wireGeneration !== this.recoveryGeneration)
2693
+ ) {
2694
+ this.outputRenderScheduler.cancel();
2695
+ this.committedView = null;
2696
+ this.invalidateRecoveryView();
2697
+ this.invalidateViewProof("generation-change");
2698
+ // Do not paint the previous generation from a status render
2699
+ // before the new empty/snapshot arrives.
2700
+ suppressGenerationRender = true;
2701
+ }
2702
+ }
1601
2703
  this.status = "attached";
2704
+ const status = (msg.status ?? msg) as { frameWitness?: { enabled?: unknown } };
2705
+ if (status.frameWitness?.enabled === true) {
2706
+ const wasAvailable = this.frameWitnessAvailable;
2707
+ this.frameWitnessAvailable = true;
2708
+ // Latch on the first observation of this attach (idempotent):
2709
+ // later losses may not strand the attach on the legacy path.
2710
+ this.witnessLatched = true;
2711
+ if (!wasAvailable && this.attaching && this.attachMode === "protocol") {
2712
+ if (this.attachSettleTimer !== null) {
2713
+ this.clock.clear(this.attachSettleTimer);
2714
+ this.attachSettleTimer = null;
2715
+ }
2716
+ this.deadlineState = "pending";
2717
+ this.evaluateAttachReady();
2718
+ }
2719
+ } else if (status.frameWitness?.enabled === false && this.frameWitnessAvailable) {
2720
+ this.frameWitnessAvailable = false;
2721
+ this.latestViewProof = null;
2722
+ this.viewProofIdentity = null;
2723
+ if (this.attaching && this.attachMode === "protocol") {
2724
+ if (this.witnessLatched) {
2725
+ // Issue #284 latch layer (I6/§3.3): a latched attach keeps the
2726
+ // committed presentation path — no restoreLegacyDeadlines, no
2727
+ // latch clear. Record the loss and keep waiting for safe facts;
2728
+ // the view layer rebuilds on the next new-identity snapshot or
2729
+ // closed frame.
2730
+ this.notReadyReason = "witness-capability-lost";
2731
+ } else {
2732
+ this.deadlineState = "pending";
2733
+ this.notReadyReason = "legacy-deadlines-without-reporter";
2734
+ this.restoreLegacyDeadlines();
2735
+ }
2736
+ }
2737
+ }
1602
2738
  if (msg.type === "hello") this.editorEmpty = typeof msg.editorEmpty === "boolean" ? msg.editorEmpty : null;
1603
2739
  } else if (msg.type === "editor_state") {
1604
2740
  this.editorEmpty = typeof msg.empty === "boolean" ? msg.empty : null;
@@ -1617,7 +2753,7 @@ export class PtyAttachComponent implements Component {
1617
2753
  // Ignore malformed protocol lines; raw PTY data is only legal inside output.data.
1618
2754
  }
1619
2755
  }
1620
- if (needsRender) this.scheduleRender();
2756
+ if (needsRender && !suppressGenerationRender) this.scheduleRender();
1621
2757
  }
1622
2758
 
1623
2759
  /**
@@ -1626,7 +2762,7 @@ export class PtyAttachComponent implements Component {
1626
2762
  * hydrates frames.
1627
2763
  */
1628
2764
  private handleAttachEvent(
1629
- event: "mode" | "snapshotBegin" | "snapshotReady" | "output" | "resubscribing" | "protocolError" | "cmdAck" | "reconciled" | "epochReset",
2765
+ event: "mode" | "snapshotBegin" | "snapshotReady" | "output" | "viewProof" | "viewProofRecord" | "resubscribing" | "protocolError" | "cmdAck" | "reconciled" | "epochReset",
1630
2766
  payload: any,
1631
2767
  ): void {
1632
2768
  if (event === "mode") {
@@ -1635,9 +2771,22 @@ export class PtyAttachComponent implements Component {
1635
2771
  if (this.attachMode === "protocol") {
1636
2772
  // Snapshot mode owns screen correctness: cancel any pending legacy
1637
2773
  // jiggle arming and unwind anything already armed (restores a held
1638
- // resize; no-ops otherwise).
2774
+ // resize; no-ops otherwise). The legacy 250 ms settle is cancelled
2775
+ // permanently for this attach; the hard deadline only marks an
2776
+ // explicit expired wait, never a forced publish.
1639
2777
  this.clearJiggleStartTimer();
1640
2778
  this.jiggleRetry.restoreAndStop();
2779
+ if (this.modernCommittedMode() && this.attachSettleTimer !== null) {
2780
+ this.clock.clear(this.attachSettleTimer);
2781
+ this.attachSettleTimer = null;
2782
+ }
2783
+ this.deadlineState = "pending";
2784
+ this.notReadyReason = this.frameWitnessAvailable
2785
+ ? "awaiting-complete-frame"
2786
+ : this.witnessLatched
2787
+ ? "witness-capability-lost"
2788
+ : "legacy-deadlines-without-reporter";
2789
+ this.evaluateAttachReady();
1641
2790
  } else if (prev === "protocol") {
1642
2791
  // Downgrade after a protocol session (recovery budget exhausted):
1643
2792
  // re-arm the legacy screen-healing machinery. This must run whenever
@@ -1648,11 +2797,50 @@ export class PtyAttachComponent implements Component {
1648
2797
  this.clearJiggleStartTimer();
1649
2798
  if (this.connected) this.jiggleRetry.start(this.cols, this.rows);
1650
2799
  }
2800
+ if (this.attachMode === "legacy") {
2801
+ this.externalOutputActive = false;
2802
+ this.restoreLegacyDeadlines();
2803
+ }
1651
2804
  // Legacy decided during the undecided window: the race-guard timer
1652
2805
  // already fired at 100ms (≪ the 1500ms probe timeout) — nothing to do.
1653
2806
  return;
1654
2807
  }
1655
2808
  if (event === "snapshotBegin") {
2809
+ // Collecting identity only: replacement happens at snapshotReady.
2810
+ const beginGeneration = (payload ?? {}) as { generation?: unknown; empty?: unknown; externalOutputActive?: unknown };
2811
+ if (beginGeneration.empty === true) {
2812
+ // Empty baseline invalidates old views/proof AT THE BEGIN, before
2813
+ // any status/hello render can present the dead generation again.
2814
+ this.outputRenderScheduler.cancel();
2815
+ this.committedView = null;
2816
+ this.invalidateRecoveryView();
2817
+ this.invalidateViewProof("new-empty-baseline");
2818
+ this.emptyResetPending = true;
2819
+ this.scheduleRender();
2820
+ }
2821
+ if (typeof beginGeneration.generation === "string") {
2822
+ const generationChanged =
2823
+ (this.committedView !== null && beginGeneration.generation !== this.committedView.identity.generation) ||
2824
+ (this.recoveryGeneration !== null && beginGeneration.generation !== this.recoveryGeneration);
2825
+ if (generationChanged) {
2826
+ this.committedView = null;
2827
+ this.invalidateRecoveryView();
2828
+ this.invalidateViewProof("generation-change");
2829
+ // New-generation state starts unowned; only a validated snapshot
2830
+ // boolean below may adopt external ownership for this generation.
2831
+ this.externalOutputActive = false;
2832
+ }
2833
+ }
2834
+ // Issue #278: the runner samples external ownership at capture end into
2835
+ // snapshot_begin. A validated boolean adopts it (running the interaction
2836
+ // cleanup on change); an absent field preserves same-generation local state.
2837
+ if (typeof beginGeneration.externalOutputActive === "boolean" && beginGeneration.externalOutputActive !== this.externalOutputActive) {
2838
+ this.externalOutputActive = beginGeneration.externalOutputActive;
2839
+ this.resetExternalProjectionInteraction();
2840
+ }
2841
+ this.collectingConnectionToken = this.connectionToken;
2842
+ this.collectingBaselineToken = this.baselineToken;
2843
+ this.collectingParserEpoch = this.parserEpoch;
1656
2844
  // Protocol attach size-sync (CR R1 blocking): the legacy attach resized
1657
2845
  // the child at every connect (jiggle start); subscribe_terminal carries
1658
2846
  // no size, so without this the child keeps its host-creation geometry
@@ -1667,12 +2855,16 @@ export class PtyAttachComponent implements Component {
1667
2855
  typeof beginSize.rows === "number" &&
1668
2856
  (beginSize.cols !== this.cols || beginSize.rows !== this.rows)
1669
2857
  ) {
2858
+ // One early size-sync pairs with the next render of the same target.
2859
+ // Later independent size-syncs to an already-seen target still advance.
2860
+ this.noteGeometryIntent(this.cols, this.rows, { early: true });
1670
2861
  this.sendResize();
1671
2862
  }
1672
2863
  return;
1673
2864
  }
1674
2865
  if (event === "snapshotReady") {
1675
- const snap = (payload ?? {}) as { frame?: string; empty?: boolean; resnapshot?: boolean; scrollbackLines?: number };
2866
+ const snap = (payload ?? {}) as { frame?: string; empty?: boolean; resnapshot?: boolean; scrollbackLines?: number; viewProof?: unknown; viewProofRecords?: unknown[] };
2867
+ if (this.collectingConnectionToken !== this.connectionToken) return;
1676
2868
  // The synthesized frame is self-contained on dirty terminals (phase 3
1677
2869
  // torture-proven: DECSTR + clear preamble wipes the constructor
1678
2870
  // screen.log replay and any pre-probe broadcast bytes), so hydrating is
@@ -1687,29 +2879,124 @@ export class PtyAttachComponent implements Component {
1687
2879
  // constructor's screen.log warm-start must not outlive the protocol
1688
2880
  // answer — a gated reset let the dead session's tail render as a
1689
2881
  // cold-start ghost once the banner lifted (final-review F1).
2882
+ if (!this.replaceParser()) {
2883
+ this.handleParserReplacementFailure();
2884
+ return; // fail-closed: no write to the old parser
2885
+ }
2886
+ const records = Array.isArray(snap.viewProofRecords) ? snap.viewProofRecords.slice(0, MAX_VIEW_PROOF_RECORDS) : [];
2887
+ this.viewProofRecords = records;
2888
+ this.viewProofRecordCount = records.length;
2889
+ if (
2890
+ !this.proofResyncRequested &&
2891
+ records.some((record) => (record as { marker?: unknown } | null)?.marker === "F") &&
2892
+ (snap.viewProof as { status?: string } | null | undefined)?.status !== "covered"
2893
+ ) {
2894
+ this.proofResyncRequested = true;
2895
+ this.attachClient.requestResync("view-proof-records-without-coverage");
2896
+ }
2897
+ this.viewProofTrailing.reset();
2898
+ this.recentProtocolOutput = [];
2899
+ const evidence = resizeIntentEvidenceFromRecords(
2900
+ { required: this.resizeIntentRequired, geometryRevision: this.geometryRevision, intentId: this.resizeIntentId, cols: this.cols, rows: this.rows },
2901
+ records,
2902
+ );
2903
+ this.resizeIntentSatisfied = evidence.satisfied;
2904
+ this.resizeIntentProofSeq = evidence.proofSeq;
2905
+ if (snap.viewProof !== undefined) {
2906
+ this.latestViewProof = snap.viewProof;
2907
+ this.viewProofIdentity = (snap.viewProof as { status?: string } | null)?.status === "covered" ? this.currentViewIdentity() : null;
2908
+ if ((snap.viewProof as { status?: string } | null)?.status === "covered") this.proofResyncRequested = false;
2909
+ } else if (snap.empty === true) {
2910
+ this.latestViewProof = { status: "unknown", reason: "empty-baseline", proof: null, throughSeq: null, cursorVisible: null };
2911
+ this.viewProofIdentity = null;
2912
+ } else {
2913
+ this.latestViewProof = null;
2914
+ this.viewProofIdentity = null;
2915
+ }
1690
2916
  if (typeof snap.frame === "string") {
2917
+ this.protocolBaselineState = "valid-content";
2918
+ this.localHydrationState = "hydrating";
1691
2919
  this.pushOutput(snap.frame, { authoritative: true, scrollbackLines: snap.scrollbackLines });
1692
2920
  } else if (snap.empty || snap.resnapshot) {
2921
+ if (snap.empty === true) {
2922
+ this.committedView = null;
2923
+ this.invalidateRecoveryView();
2924
+ this.invalidateViewProof("new-empty-baseline");
2925
+ this.emptyResetPending = true;
2926
+ }
2927
+ this.protocolBaselineState = "valid-empty";
1693
2928
  this.childInputReady = false;
1694
2929
  this.childInputModeCarry = "";
1695
- this.term.reset();
1696
- // Issue #205: the buffer is empty again, so a stale floor would make the
1697
- // first `floor` lines of the restarted host unscrollable.
2930
+ // Issue #205: the replacement parser is empty, so no stale floor/poison
2931
+ // survives. Empty/resnapshot never triggers the first-attach hooks.
1698
2932
  this.historyFloor = 0;
2933
+ this.scheduleRender();
2934
+ this.evaluateAttachReady();
1699
2935
  }
1700
2936
  return;
1701
2937
  }
1702
2938
  if (event === "output") {
2939
+ // Replacement failure is a hard fence: protocol bytes cannot be mixed into
2940
+ // the old parser while waiting for a bounded fresh resync/legacy decision.
2941
+ if (this.localHydrationState === "failed") return;
1703
2942
  // Live/replay protocol output: no jiggle clear-detection — that feed
1704
2943
  // exists to cancel the shrink-and-hold chain, which never runs in
1705
2944
  // protocol mode.
1706
- if (typeof payload === "string") this.pushOutput(payload, { forwardProtocols: true });
2945
+ if (typeof payload === "string") {
2946
+ this.recentProtocolOutput.push({ seq: this.attachClient.getLastSeq(), data: payload });
2947
+ if (this.recentProtocolOutput.length > 16) this.recentProtocolOutput.shift();
2948
+ this.noteViewProofOutput(payload);
2949
+ this.pushOutput(payload, { forwardProtocols: true });
2950
+ }
2951
+ return;
2952
+ }
2953
+ if (event === "viewProof") {
2954
+ this.latestViewProof = payload ?? null;
2955
+ if ((payload as { status?: string } | null)?.status === "covered") {
2956
+ this.viewProofIdentity = this.currentViewIdentity();
2957
+ this.viewProofTrailing.reset({ cursorVisible: typeof (payload as { cursorVisible?: unknown }).cursorVisible === "boolean" ? (payload as { cursorVisible: boolean }).cursorVisible : undefined });
2958
+ } else {
2959
+ this.viewProofIdentity = null;
2960
+ this.viewProofTrailing.reset();
2961
+ if (String((payload as { reason?: string } | null)?.reason ?? "").includes("reporter-replaced")) {
2962
+ this.viewProofRecords = [];
2963
+ this.viewProofRecordCount = 0;
2964
+ }
2965
+ }
2966
+ this.evaluateAttachReady();
2967
+ return;
2968
+ }
2969
+ if (event === "viewProofRecord") {
2970
+ if (payload !== null && typeof payload === "object") {
2971
+ const record = payload as Record<string, unknown>;
2972
+ this.noteViewProofRecord(record);
2973
+ if (record.marker === "F") {
2974
+ // Issue #294: one matcher for every evidence source — a live F
2975
+ // re-evaluates through the same pure predicate (full validation
2976
+ // incl. target dims); a non-match leaves the evidence untouched.
2977
+ const evidence = resizeIntentEvidenceFromRecords(
2978
+ { required: this.resizeIntentRequired, geometryRevision: this.geometryRevision, intentId: this.resizeIntentId, cols: this.cols, rows: this.rows },
2979
+ [record],
2980
+ );
2981
+ if (evidence.satisfied) {
2982
+ this.resizeIntentSatisfied = true;
2983
+ this.resizeIntentProofSeq = evidence.proofSeq;
2984
+ }
2985
+ }
2986
+ this.evaluateAttachReady();
2987
+ }
1707
2988
  return;
1708
2989
  }
1709
2990
  if (event === "epochReset") {
1710
2991
  this.childInputReady = false;
1711
2992
  this.childInputModeCarry = "";
2993
+ this.committedView = null;
2994
+ this.invalidateRecoveryView();
2995
+ this.invalidateViewProof("epoch-reset");
2996
+ this.externalOutputActive = false;
1712
2997
  }
2998
+ // "viewProof"/"viewProofRecord": independent protocol facts in this stage;
2999
+ // the component has no readiness/publish hook for them yet.
1713
3000
  // "resubscribing": recovery is client-internal (informational only).
1714
3001
  // "protocolError": observability only — recovery is automatic until the
1715
3002
  // legacy fallback, whose mode event the UI acts on above.
@@ -1731,7 +3018,8 @@ export class PtyAttachComponent implements Component {
1731
3018
  if (process.env.AGENT_BOARD_FORWARD_IMAGES !== "0") {
1732
3019
  const { sequences, carry } = extractTerminalPassthroughSequences(this.passthroughCarry + data);
1733
3020
  this.passthroughCarry = carry;
1734
- toWrite.push(...sequences);
3021
+ // Kitty placements belong to projected grid rows, not the host's parked cursor.
3022
+ toWrite.push(...sequences.filter((seq) => !seq.startsWith(KITTY_IMAGE_PREFIX)));
1735
3023
  }
1736
3024
  if (process.env.AGENT_BOARD_FORWARD_TERMINAL_QUERIES !== "0") {
1737
3025
  // Issue #128 D1: forward the child's terminal capability queries
@@ -1802,25 +3090,79 @@ export class PtyAttachComponent implements Component {
1802
3090
  }
1803
3091
  if (opts.forwardProtocols || opts.authoritative) this.updateChildInputReadiness(data);
1804
3092
  if (opts.forwardProtocols) this.forwardTerminalProtocols(data);
3093
+ const term = this.term;
3094
+ const connectionToken = this.connectionToken;
3095
+ const baselineToken = this.baselineToken;
3096
+ const parserEpoch = this.parserEpoch;
3097
+ const generation = this.attachClient.getIdentity().generation ?? "local";
3098
+ const capturedIdentity = { connectionToken, baselineToken, generation, parser: term, geometryRevision: this.geometryRevision, targetCols: this.cols, targetRows: this.rows, closed: false };
1805
3099
  // @xterm/headless parses asynchronously; the buffer is only populated once this
1806
3100
  // callback fires. Mark the buffer as ready (so the project path can paint it), but
1807
3101
  // stay on the loading banner while `attaching` — otherwise the screen-log replay and
1808
3102
  // the initial resize-jiggle redraws would flash through the viewport. Each parsed
1809
- // chunk also defers the settle window, so the banner holds until output actually
3103
+ // chunk defers the settle window, so the banner holds until output actually
1810
3104
  // stops arriving (i.e. the redraw finished), not just until the resize jiggle ends.
1811
- this.term.write(data, () => {
3105
+ // Current-epoch invariant: replaceParser() resets this counter to 0 when it
3106
+ // advances parserEpoch. A stale callback returns below WITHOUT decrementing;
3107
+ // decrementing it would cancel a new-epoch write and allow premature publish.
3108
+ this.parserWritesInFlight += 1;
3109
+ try {
3110
+ // snapshotReady already replaced the parser and Kitty bridge; injecting an
3111
+ // extra reset OSC into its frame would disturb complete-frame observation.
3112
+ term.write(this.kittyImages?.transform(data) ?? data, () => {
3113
+ if (this.parserEpoch !== parserEpoch) return;
3114
+ if (this.parserWritesInFlight > 0) this.parserWritesInFlight -= 1;
3115
+ const currentIdentity = {
3116
+ connectionToken: this.connectionToken,
3117
+ baselineToken: this.baselineToken,
3118
+ generation: this.attachClient.getIdentity().generation ?? "local",
3119
+ parser: this.term,
3120
+ geometryRevision: this.geometryRevision,
3121
+ targetCols: this.cols,
3122
+ targetRows: this.rows,
3123
+ closed: this.closed,
3124
+ };
3125
+ if (!canPublishAttachView(capturedIdentity, currentIdentity)) return;
1812
3126
  if (opts.forwardProtocols || opts.authoritative) this.flushPendingSchemeReport();
1813
3127
  // Issue #205: baseY is only final once this chunk parsed, and the callback
1814
3128
  // has no buffer binding — re-read it. Rows past the runner-vouched
1815
3129
  // scrollback are overflow the hydration itself scrolled out.
1816
- if (opts.authoritative) this.historyFloor = historyFloorAfterHydrate(this.term.buffer.active.baseY, opts.scrollbackLines);
3130
+ if (opts.authoritative) {
3131
+ this.historyFloor = historyFloorAfterHydrate(term.buffer.active.baseY, opts.scrollbackLines);
3132
+ this.localHydrationState = "complete";
3133
+ if (this.screenOwnerResyncPending) {
3134
+ // The hydrating frame's wrapper sync window is fully parsed now;
3135
+ // restore adapter/component ownership agreement before committing.
3136
+ this.screenOwnerResyncPending = false;
3137
+ this.resyncScreenOwnerAdapter(term, parserEpoch);
3138
+ }
3139
+ if (!this.parserSyncOpen) this.commitCommittedView(term, parserEpoch, "snapshot");
3140
+ }
1817
3141
  this.receivedOutput = true;
1818
- this.deferAttachSettle();
1819
- this.outputRenderScheduler.request();
1820
- });
3142
+ this.deferAttachSettle();
3143
+ this.outputRenderScheduler.request();
3144
+ this.evaluateAttachReady();
3145
+ });
3146
+ } catch {
3147
+ if (this.parserEpoch === parserEpoch && this.parserWritesInFlight > 0) this.parserWritesInFlight -= 1;
3148
+ }
3149
+ }
3150
+
3151
+ private projectCommitted(height: number): { lines: string[]; cursor: { row: number; col: number } | null } {
3152
+ const view = this.activeCommittedView();
3153
+ if (view === null) return { lines: [], cursor: null };
3154
+ const selection = normalizeSelection(this.selection);
3155
+ const out: string[] = [];
3156
+ for (let index = 0; index < view.rows.length && out.length < height; index += 1) {
3157
+ const lineIndex = view.start + index;
3158
+ out.push(view.rows[index].kittyPrefix + lineToAnsi(view.rows[index].cells, SnapshotCell.empty(), this.term, lineIndex, selection, view.cursor, view.cursorHidden));
3159
+ }
3160
+ return { lines: out, cursor: view.cursor };
1821
3161
  }
1822
3162
 
1823
3163
  private project(height: number): { lines: string[]; cursor: { row: number; col: number } | null } {
3164
+ if (this.closed) return { lines: [], cursor: null };
3165
+ if (this.usesCommittedProjection()) return this.projectCommitted(height);
1824
3166
  const out: string[] = [];
1825
3167
  const buf = this.term.buffer.active;
1826
3168
  const selection = normalizeSelection(this.selection);
@@ -1837,7 +3179,7 @@ export class PtyAttachComponent implements Component {
1837
3179
  out.push(lineToAnsi(buf.getLine(i), reusable, this.term, i, selection, cursor, cursorHidden));
1838
3180
  }
1839
3181
  if (out.length === 0) out.push("Waiting for PTY output…");
1840
- return { lines: out.slice(-height), cursor };
3182
+ return { lines: this.kittyImages?.project(out.slice(-height), start, height) ?? out.slice(-height), cursor };
1841
3183
  }
1842
3184
 
1843
3185
  private close(gracefulSocket = false): void {
@@ -1848,6 +3190,12 @@ export class PtyAttachComponent implements Component {
1848
3190
  return;
1849
3191
  }
1850
3192
  this.closed = true;
3193
+ this.attachWaitToken += 1;
3194
+ this.committedView = null;
3195
+ this.externalOutputActive = false;
3196
+ this.recoveryView = null;
3197
+ this.recoveryGeneration = null;
3198
+ this.disposeCurrentParser();
1851
3199
  this.imeCoalesceUninstall?.();
1852
3200
  this.detachColorSchemeBridge();
1853
3201
  this.clearReplyGuardTimer();
@@ -1861,15 +3209,38 @@ export class PtyAttachComponent implements Component {
1861
3209
  this.clearRetry();
1862
3210
  this.stopLoadingTicker();
1863
3211
  this.outputRenderScheduler.dispose();
3212
+ // Narrow feature-detected host seam (repo pi-tui 1.1.0, host pi 1.4.0):
3213
+ // cancel the already-queued TUI frame without stopping the TUI. A closed
3214
+ // flag inside render cannot cancel a render queued before dispose.
3215
+ const renderSeam = this.tui as unknown as {
3216
+ cancelRenderTimer?: () => void;
3217
+ renderRequested?: boolean;
3218
+ };
3219
+ if (typeof renderSeam.cancelRenderTimer === "function") {
3220
+ try { renderSeam.cancelRenderTimer(); } catch { /* host seam is best-effort */ }
3221
+ }
3222
+ // TuiBase.requestImmediateRender() queues a process.nextTick that checks
3223
+ // renderRequested; clearing it cancels an already queued immediate paint
3224
+ // without stopping the TUI. Verified host pi 1.4.0 shape.
3225
+ if (typeof renderSeam.renderRequested === "boolean") renderSeam.renderRequested = false;
1864
3226
  this.stopDesyncProbe();
1865
- if (this.attachSettleTimer) {
1866
- clearTimeout(this.attachSettleTimer);
3227
+ if (this.attachSettleTimer !== null) {
3228
+ this.clock.clear(this.attachSettleTimer);
1867
3229
  this.attachSettleTimer = null;
1868
3230
  }
1869
- if (this.attachHardTimeout) {
1870
- clearTimeout(this.attachHardTimeout);
3231
+ if (this.attachHardTimeout !== null) {
3232
+ this.clock.clear(this.attachHardTimeout);
1871
3233
  this.attachHardTimeout = null;
1872
3234
  }
3235
+ this.clearAttachRecoveryBudget();
3236
+ this.budgetArmed = false;
3237
+ // Issue #284 latch layer: the latch is attach-scoped — detach/dispose
3238
+ // ends this attach; a new component re-observes the capability fresh.
3239
+ this.witnessLatched = false;
3240
+ // Same attach scope for the sticky failure fact (spec §3.1.1/I6) and the
3241
+ // #288 hard-dominance latch (spec §3 I8).
3242
+ this.proofInvalidatedBaselineToken = null;
3243
+ this.proofHardInvalidatedThisBaseline = null;
1873
3244
  this.clearGracefulSocketCloseTimer();
1874
3245
  const socket = this.socket;
1875
3246
  this.socket = null;
@@ -2091,12 +3462,14 @@ function clip(line: string, width: number): string {
2091
3462
 
2092
3463
  function clipTerminalLine(line: string, width: number): string {
2093
3464
  // pi-tui's width helpers are ANSI-aware, but OSC sequences are terminal
2094
- // protocols rather than SGR styling. Avoid truncating inside OSC 8 hyperlinks;
2095
- // these lines are already projected from an xterm buffer sized to the viewport.
2096
- return line.includes("\x1b]") ? line : clip(line, width);
3465
+ // protocols rather than SGR styling. Preserve complete OSC 8 links and Kitty
3466
+ // APCs; these lines are projected from a buffer already sized to the viewport.
3467
+ return line.includes("\x1b]") || line.includes(KITTY_IMAGE_PREFIX) ? line : clip(line, width);
2097
3468
  }
2098
3469
 
2099
3470
  function osc8UriForCell(term: XtermLike, cell: BufferCellLike): string {
3471
+ const committed = (cell as { osc8Uri?: () => string }).osc8Uri?.();
3472
+ if (typeof committed === "string" && committed.length > 0) return committed;
2100
3473
  // xterm leaves cached extended data on reused cells when this flag is unset.
2101
3474
  if (!cell.hasExtendedAttrs()) return "";
2102
3475
  const id = cell.extended?.urlId ?? cell.extended?._urlId ?? 0;