@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
@@ -1,3 +1,5 @@
1
+ import { validateFrameMetadata } from "./attach-frame-proof.mjs";
2
+
1
3
  /**
2
4
  * Decide whether the next attach repaint should force a full clear.
3
5
  *
@@ -83,6 +85,10 @@ export function createAttachOutputRenderScheduler(requestRender, delayMs = ATTAC
83
85
  }, delayMs);
84
86
  timer.unref?.();
85
87
  },
88
+ cancel() {
89
+ if (timer) clearTimeout(timer);
90
+ timer = null;
91
+ },
86
92
  dispose() {
87
93
  disposed = true;
88
94
  if (timer) clearTimeout(timer);
@@ -120,3 +126,236 @@ export function detectCursorDesync(buf, cursor) {
120
126
  if (!cell) return "misaligned";
121
127
  return cell.isInverse() ? "aligned" : "misaligned";
122
128
  }
129
+
130
+ /**
131
+ * Source-comparison gate for a committed view projection (spec §4.2/§4.3).
132
+ * A projection may be shown only while every identity axis still matches the
133
+ * current connection/baseline/parser/geometry target. Missing/unknown facts and
134
+ * a closed component always fail closed.
135
+ */
136
+ export function canPublishAttachView(viewIdentity, currentIdentity) {
137
+ if (viewIdentity === null || typeof viewIdentity !== "object" || Array.isArray(viewIdentity)) return false;
138
+ if (currentIdentity === null || typeof currentIdentity !== "object" || Array.isArray(currentIdentity)) return false;
139
+ if (viewIdentity.closed === true || currentIdentity.closed === true) return false;
140
+ const known = (value) => value !== null && value !== undefined && !(typeof value === "string" && value.length === 0) && !(typeof value === "number" && !Number.isFinite(value));
141
+ for (const key of ["connectionToken", "baselineToken", "generation", "parser", "geometryRevision", "targetCols", "targetRows"]) {
142
+ if (!known(viewIdentity[key]) || !known(currentIdentity[key])) return false;
143
+ if (viewIdentity[key] !== currentIdentity[key]) return false;
144
+ }
145
+ if (!Number.isInteger(viewIdentity.targetCols) || viewIdentity.targetCols < 1) return false;
146
+ if (!Number.isInteger(viewIdentity.targetRows) || viewIdentity.targetRows < 1) return false;
147
+ if (!Number.isInteger(viewIdentity.geometryRevision) || viewIdentity.geometryRevision < 0) return false;
148
+ return true;
149
+ }
150
+
151
+ /**
152
+ * Issue #294: derive the resize-intent evidence from view-proof records.
153
+ * One matcher for every evidence source — snapshotReady's records array and
154
+ * the live single-record path both call this; no revision/intent-only
155
+ * shortcut may exist anywhere. Fail-closed: anything short of a fully
156
+ * matching target F yields no evidence.
157
+ * @param {{ required: boolean, geometryRevision: number, intentId: number, cols: number, rows: number } | null} intent
158
+ * @param {unknown} records
159
+ * @returns {{ satisfied: boolean, proofSeq: number | null }}
160
+ */
161
+ export function resizeIntentEvidenceFromRecords(intent, records) {
162
+ if (intent === null || typeof intent !== "object") return { satisfied: false, proofSeq: null };
163
+ if (intent.required !== true) return { satisfied: true, proofSeq: null };
164
+ if (!Array.isArray(records)) return { satisfied: false, proofSeq: null };
165
+ let best = null;
166
+ for (const record of records) {
167
+ if (record === null || typeof record !== "object") continue;
168
+ if (record.marker !== "F") continue;
169
+ if (!Number.isInteger(record.seq) || record.seq < 1) continue;
170
+ const validation = validateFrameMetadata(record.metadata);
171
+ if (!validation.ok) continue;
172
+ const metadata = validation.value;
173
+ if (metadata.geometryRevision !== intent.geometryRevision) continue;
174
+ if (metadata.intentId !== intent.intentId) continue;
175
+ if (metadata.cols !== intent.cols || metadata.rows !== intent.rows) continue;
176
+ if (best === null || record.seq > best) best = record.seq;
177
+ }
178
+ return best === null ? { satisfied: false, proofSeq: null } : { satisfied: true, proofSeq: best };
179
+ }
180
+
181
+ /**
182
+ * Pure §4 presentation decision. It consumes only immutable facts — no clock,
183
+ * timer, terminal or I/O. `deadlineState:"expired"` can only change a WAIT
184
+ * reason; it can never upgrade an incomplete view to publish. Legacy decisions
185
+ * stay independent of proof facts.
186
+ *
187
+ * Issue #284 adds a second, lower-priority outcome: when the full-view (F) chain
188
+ * fails AND the caller supplies recovery facts (any of the `committed*` /
189
+ * `witnessLatched` / `proofStatus` / `budgetElapsed` / `capRecoverable` inputs
190
+ * below), a committed-degraded chain is evaluated instead — every predicate
191
+ * must pass to `publish-degraded`, otherwise the first failing predicate names
192
+ * the wait reason. Callers that do not supply recovery facts get the exact
193
+ * pre-#284 behavior. The F chain keeps absolute priority: a fully covered view
194
+ * always publishes `complete` without waiting for the budget.
195
+ *
196
+ * Issue #288 adds the cap floor to the degraded chain's proof predicate (5):
197
+ * once `deadlineState` is "expired", an invalid `proofStatus` may still pass
198
+ * when `capRecoverable` is exactly `true` (the caller derives it from the
199
+ * absence of a hard proof invalidation on the current baseline); any other
200
+ * value — including undefined — fails closed, and pending deadlines keep the
201
+ * exact #284 pass set.
202
+ *
203
+ * @param {{
204
+ * closed?: boolean,
205
+ * mode?: "undecided" | "protocol" | "legacy" | "raw" | string,
206
+ * baselineState?: "unverified" | "hydrating" | "valid-empty" | "valid-content" | "undecided" | string,
207
+ * localParseComplete?: boolean,
208
+ * frameState?: "unknown" | "open" | "complete" | string,
209
+ * openSyncBlock?: boolean,
210
+ * openCandidate?: boolean,
211
+ * contentAvailable?: boolean,
212
+ * contentKind?: "complete" | "boot" | "raw" | string,
213
+ * localSeq?: number,
214
+ * viewProof?: any,
215
+ * viewIdentity?: any,
216
+ * currentIdentity?: any,
217
+ * targetCols?: number,
218
+ * targetRows?: number,
219
+ * geometryRevision?: number,
220
+ * requiredGeometryRevision?: number,
221
+ * resizeIntentRequired?: boolean,
222
+ * resizeIntentSatisfied?: boolean,
223
+ * resizeIntentProofSeq?: number | null,
224
+ * intentId?: number,
225
+ * deadlineState?: "pending" | "expired",
226
+ * witnessLatched?: boolean,
227
+ * committedViewValid?: boolean,
228
+ * committedViewSource?: "snapshot" | "sync-close" | "none",
229
+ * committedViewCols?: number,
230
+ * committedViewRows?: number,
231
+ * committedContentKind?: "complete" | "boot" | "raw" | "partial" | "unknown",
232
+ * proofStatus?: "none" | "missing" | "invalid" | "covered",
233
+ * capRecoverable?: boolean,
234
+ * budgetElapsed?: boolean,
235
+ * }} state
236
+ * @returns {{ action: "closed" | "legacy" | "wait" | "publish" | "publish-degraded", reason: string }}
237
+ */
238
+ export function decideAttachPresentation(state) {
239
+ if (state === null || typeof state !== "object" || Array.isArray(state)) return { action: "wait", reason: "state-missing" };
240
+ if (state.closed === true) return { action: "closed", reason: "closed" };
241
+ if (state.mode === "closed") return { action: "closed", reason: "closed" };
242
+ if (state.mode === "legacy") return { action: "legacy", reason: "legacy-mode" };
243
+ const wait = (reason) => ({
244
+ action: "wait",
245
+ reason: state.deadlineState === "expired" ? `deadline-expired:${reason}` : reason,
246
+ });
247
+ if (state.mode !== "protocol") return wait(`mode-${state.mode ?? "unknown"}`);
248
+ const full = fullViewDecision(state, wait);
249
+ if (full.action === "publish") return full;
250
+ return degradedViewDecision(state, wait) ?? full;
251
+ }
252
+
253
+ /** The full-view (F) predicate chain. */
254
+ function fullViewDecision(state, wait) {
255
+ if (state.baselineState !== "valid-content" && state.baselineState !== "valid-empty") {
256
+ if (state.baselineState === "hydrating") return wait("baseline-hydrating");
257
+ if (state.baselineState === "unverified") return wait("baseline-unverified");
258
+ return wait("baseline-unknown");
259
+ }
260
+ if (state.localParseComplete !== true) return wait("local-parse-incomplete");
261
+ if (state.frameState === "open") return wait("sync-open");
262
+ if (state.frameState !== "complete") return wait("frame-incomplete");
263
+ if (state.openSyncBlock === true) return wait("sync-open");
264
+ if (state.openCandidate === true) return wait("candidate-open");
265
+ if (state.baselineState === "valid-empty") {
266
+ if (!Number.isInteger(state.localSeq) || state.localSeq < 1) return wait("empty-baseline-needs-live-complete");
267
+ }
268
+ if (state.contentKind === "boot") return wait("boot-content");
269
+ if (state.contentKind === "raw") return wait("raw-content");
270
+ if (state.contentKind !== "complete") return wait("content-kind-unknown");
271
+ if (state.contentAvailable !== true) return wait("content-missing");
272
+ if (!Number.isInteger(state.targetCols) || state.targetCols < 1) return wait("geometry-unknown");
273
+ if (!Number.isInteger(state.targetRows) || state.targetRows < 1) return wait("geometry-unknown");
274
+ const coverage = state.viewProof;
275
+ if (coverage === null || typeof coverage !== "object" || Array.isArray(coverage)) return wait("view-proof-missing");
276
+ if (coverage.status !== "covered") return wait(`view-proof-${coverage.status ?? "unknown"}`);
277
+ if (!Number.isInteger(coverage.throughSeq)) return wait("view-proof-invalid");
278
+ if (!Number.isInteger(state.localSeq) || coverage.throughSeq < state.localSeq) return wait("view-proof-behind");
279
+ if (coverage.throughSeq > state.localSeq) return wait("view-proof-future");
280
+ if (coverage.proof === null || typeof coverage.proof !== "object" || Array.isArray(coverage.proof)) return wait("view-proof-missing");
281
+ if (coverage.proof.marker !== "F" || !Number.isInteger(coverage.proof.seq) || coverage.proof.seq > coverage.throughSeq) return wait("view-proof-invalid");
282
+ const metadata = validateFrameMetadata(coverage.proof.metadata);
283
+ if (!metadata.ok) return wait("view-proof-invalid");
284
+ if (metadata.value.cols !== state.targetCols || metadata.value.rows !== state.targetRows) return wait("proof-geometry-mismatch");
285
+ // Issue #294: a validated intent proof (snapshot-carried or live) that is
286
+ // fresh against the covered window, plus an ordinary post-intent (0/0)
287
+ // coverage head at the target size, is an acceptable alternative to the
288
+ // head itself carrying the intent metadata. Everything else fails closed
289
+ // to the original waits.
290
+ const intentEvidenceHeadOk =
291
+ state.resizeIntentRequired === true &&
292
+ state.resizeIntentSatisfied === true &&
293
+ Number.isInteger(state.resizeIntentProofSeq) &&
294
+ state.resizeIntentProofSeq <= coverage.throughSeq &&
295
+ metadata.value.intentId === 0 &&
296
+ metadata.value.geometryRevision === 0 &&
297
+ metadata.value.cols === state.targetCols &&
298
+ metadata.value.rows === state.targetRows;
299
+ if (state.requiredGeometryRevision !== undefined && metadata.value.geometryRevision !== state.requiredGeometryRevision && !intentEvidenceHeadOk) return wait("geometry-revision");
300
+ if (state.resizeIntentRequired === true) {
301
+ if (state.resizeIntentSatisfied !== true) return wait("resize-intent");
302
+ const headCarriesIntent = metadata.value.intentId === state.intentId && metadata.value.intentId !== 0;
303
+ if (!headCarriesIntent && !intentEvidenceHeadOk) return wait("resize-intent");
304
+ }
305
+ if (!canPublishAttachView(state.viewIdentity, state.currentIdentity)) return wait("identity-mismatch");
306
+ return { action: "publish", reason: "complete" };
307
+ }
308
+
309
+ /** Recovery facts assembled by the caller; presence of any one opts into the degraded chain. */
310
+ const RECOVERY_FACT_KEYS = [
311
+ "witnessLatched",
312
+ "committedViewValid",
313
+ "committedViewSource",
314
+ "committedViewCols",
315
+ "committedViewRows",
316
+ "committedContentKind",
317
+ "proofStatus",
318
+ "capRecoverable",
319
+ "budgetElapsed",
320
+ ];
321
+
322
+ /**
323
+ * Issue #284 §3.1 committed-degraded chain, evaluated only after the F chain
324
+ * failed and only for callers that supply recovery facts. All seven predicates
325
+ * must pass to publish-degraded; the first failure names the wait reason
326
+ * (shared predicates reuse the F-chain reason strings). Every missing or
327
+ * unrecognized fact fails closed. Returns null when recovery facts are absent
328
+ * so the F-chain wait stands unchanged.
329
+ */
330
+ function degradedViewDecision(state, wait) {
331
+ if (!RECOVERY_FACT_KEYS.some((key) => state[key] !== undefined)) return null;
332
+ if (state.mode !== "protocol") return wait(`mode-${state.mode ?? "unknown"}`);
333
+ if (state.witnessLatched !== true) return wait("witness-not-latched");
334
+ if (state.baselineState !== "valid-content") {
335
+ if (state.baselineState === "hydrating") return wait("baseline-hydrating");
336
+ if (state.baselineState === "unverified") return wait("baseline-unverified");
337
+ if (state.baselineState === "valid-empty") return wait("baseline-empty");
338
+ return wait("baseline-unknown");
339
+ }
340
+ if (state.localParseComplete !== true) return wait("local-parse-incomplete");
341
+ if (state.frameState !== "complete") return wait(state.frameState === "open" ? "sync-open" : "frame-incomplete");
342
+ if (state.openSyncBlock === true) return wait("sync-open");
343
+ if (state.committedViewValid !== true) return wait(state.committedViewValid == null ? "committed-view-missing" : "committed-view-invalid");
344
+ if (state.committedViewCols !== state.targetCols || state.committedViewRows !== state.targetRows) return wait("committed-geometry-mismatch");
345
+ if (state.resizeIntentRequired === true) return wait("resize-intent");
346
+ if (state.proofStatus === "covered") return wait("proof-status-covered");
347
+ if (state.proofStatus !== "none" && state.proofStatus !== "missing") {
348
+ // Issue #288 cap floor: once the attach hard timeout has expired, an
349
+ // invalid classification may still pass — but only when the caller
350
+ // asserts capRecoverable === true (trailing-only invalidation; the
351
+ // component derives it from !proofHardInvalidatedThisBaseline). Any
352
+ // other value fails closed, and pending deadlines keep the #284 pass
353
+ // set exactly. The wait helper prefixes "deadline-expired:".
354
+ const capFloorAdmitted =
355
+ state.deadlineState === "expired" && state.proofStatus === "invalid" && state.capRecoverable === true;
356
+ if (!capFloorAdmitted) return wait("proof-status-invalid");
357
+ }
358
+ if (state.budgetElapsed !== true) return wait("recovery-budget-pending");
359
+ if (state.committedContentKind !== "complete") return wait(`content-kind-${state.committedContentKind ?? "unknown"}`);
360
+ return { action: "publish-degraded", reason: "committed-degraded" };
361
+ }
@@ -0,0 +1,237 @@
1
+ // Parse Kitty graphics commands in order with the PTY grid,
2
+ // then render uploads/placements as image lines, never at the host's parked cursor.
3
+ const PREFIX = "\x1b_G";
4
+ const ST = "\x1b\\";
5
+ const OSC = 99173;
6
+ const MAX_BYTES = 32 * 1024 * 1024;
7
+ const MAX_IMAGES = 32;
8
+ const command = (controls, payload = "") => `${PREFIX}${controls};${payload}${ST}`;
9
+ const controlsString = (controls) => Object.entries(controls).map(([k, v]) => `${k}=${v}`).join(",");
10
+
11
+ function sourceImageHeight(controls, data) {
12
+ if (controls.f === "100") {
13
+ // Only decode the PNG header, not the entire cached image on every frame.
14
+ const header = Buffer.from(data.slice(0, 44), "base64");
15
+ if (header.length >= 24 && header.subarray(0, 8).equals(Buffer.from("89504e470d0a1a0a", "hex")) && header.toString("ascii", 12, 16) === "IHDR") {
16
+ return header.readUInt32BE(20);
17
+ }
18
+ } else if (["24", "32"].includes(controls.f)) {
19
+ return Number(controls.v) || undefined;
20
+ }
21
+ return undefined;
22
+ }
23
+
24
+ /**
25
+ * Track Pi's direct Kitty uploads and placements alongside an xterm parser.
26
+ * No Kitty APCs means no graphical state or scroll-history side effects;
27
+ * non-Kitty terminal protocols are passed through to the parser unchanged.
28
+ */
29
+ export function createPtyKittyImages(term, onClearScrollback = () => {}) {
30
+ let carry = "";
31
+ let nextToken = 0;
32
+ let transmission = null;
33
+ let usedKittyImages = false;
34
+ const pending = new Map();
35
+ const images = new Map();
36
+ const placements = new Map();
37
+
38
+ function removePlacement(key) {
39
+ placements.get(key)?.marker?.dispose();
40
+ placements.delete(key);
41
+ }
42
+ function removeImage(id) {
43
+ images.delete(id);
44
+ for (const [key, p] of placements) if (p.id === id) removePlacement(key);
45
+ }
46
+ function clearPlacements() {
47
+ for (const key of placements.keys()) removePlacement(key);
48
+ }
49
+ function place(controls) {
50
+ const id = controls.i;
51
+ const image = images.get(id);
52
+ if (!image) return;
53
+ const c = { ...image.controls, ...controls, a: "p", C: "1", q: "2" };
54
+ // Pi emits explicit cell dimensions; reject unknown extents rather than
55
+ // risking an image over the attach header/footer. Only placement keys survive.
56
+ if (!(Number(c.r) > 0 && Number(c.c) > 0) || c.U === "1") return;
57
+ const allowed = new Set(["a", "i", "p", "x", "y", "w", "h", "X", "Y", "c", "r", "C", "q", "z"]);
58
+ for (const key of Object.keys(c)) if (!allowed.has(key)) delete c[key];
59
+ const key = `${id}:${c.p ?? 0}`;
60
+ removePlacement(key);
61
+ const buf = term.buffer.active;
62
+ placements.set(key, {
63
+ id, controls: c, buffer: buf.type,
64
+ row: buf.baseY + buf.cursorY, col: buf.cursorX,
65
+ marker: term.registerMarker?.(0),
66
+ });
67
+ }
68
+ function accept(sequence) {
69
+ const body = sequence.slice(PREFIX.length, -ST.length);
70
+ const semi = body.indexOf(";");
71
+ const header = semi < 0 ? body : body.slice(0, semi);
72
+ const payload = semi < 0 ? "" : body.slice(semi + 1);
73
+ const c = Object.fromEntries(header.split(",").filter(Boolean).map((part) => part.split("=")));
74
+ if (c.a === "d") {
75
+ const mode = c.d ?? "a";
76
+ if (mode.toLowerCase() === "a") {
77
+ clearPlacements();
78
+ if (mode === "A") images.clear();
79
+ } else if (mode.toLowerCase() === "i") {
80
+ for (const [key, p] of placements) if (p.id === c.i && (!c.p || p.controls.p === c.p)) removePlacement(key);
81
+ if (mode === "I") images.delete(c.i);
82
+ }
83
+ return;
84
+ }
85
+ if (c.a === "p") return place(c);
86
+ // Pi's direct transfers can span hundreds of APCs and arbitrary PTY reads.
87
+ if (!transmission) {
88
+ if (!["t", "T"].includes(c.a ?? "T") || (c.t && c.t !== "d") || !c.i) return;
89
+ transmission = { controls: c, chunks: [], bytes: 0 };
90
+ }
91
+ transmission.bytes += payload.length;
92
+ if (transmission.bytes <= MAX_BYTES) transmission.chunks.push(payload);
93
+ if (c.m === "1") return;
94
+ const complete = transmission;
95
+ transmission = null;
96
+ if (complete.bytes > MAX_BYTES) return;
97
+ usedKittyImages = true;
98
+ const original = complete.controls;
99
+ const upload = { ...original, a: "t", q: "2" };
100
+ delete upload.m;
101
+ // Re-chunk the cached upload so replay remains valid for Kitty's 4KiB limit.
102
+ const data = complete.chunks.join("");
103
+ const parts = [];
104
+ for (let i = 0; i < data.length || i === 0; i += 4096) {
105
+ const first = i === 0;
106
+ const more = i + 4096 < data.length;
107
+ parts.push(command(controlsString(first ? { ...upload, m: more ? "1" : "0" } : { m: more ? "1" : "0" }), data.slice(i, i + 4096)));
108
+ }
109
+ removeImage(original.i);
110
+ const joined = parts.join("");
111
+ images.set(original.i, {
112
+ controls: original, sequence: joined, bytes: data.length,
113
+ // Cached so project() re-concats only the small header per frame instead
114
+ // of re-slicing a potentially multi-MB payload string on every render.
115
+ payloadCommands: joined.slice(joined.indexOf(";")),
116
+ uploadControls: { ...upload, m: data.length > 4096 ? "1" : "0" },
117
+ heightPx: sourceImageHeight(original, data),
118
+ });
119
+ let total = [...images.values()].reduce((n, image) => n + image.bytes, 0);
120
+ while (images.size > MAX_IMAGES || total > MAX_BYTES) {
121
+ const id = images.keys().next().value;
122
+ total -= images.get(id).bytes;
123
+ removeImage(id);
124
+ }
125
+ if ((original.a ?? "T") === "T") place(original);
126
+ }
127
+
128
+ // A live child redraw can clear hydration overflow/history. Notify the UI
129
+ // at parser order so its old snapshot floor cannot disable real scrollback.
130
+ const clearHandler = term.parser.registerCsiHandler({ final: "J" }, (params) => {
131
+ if (params[0] === 3 && usedKittyImages) onClearScrollback();
132
+ return false;
133
+ });
134
+
135
+ // xterm does not expose APC handlers. Replace each complete APC with a tiny
136
+ // private OSC token. Its handler runs after ALL preceding cursor movements,
137
+ // including movements earlier in the same async xterm.write call.
138
+ const handler = term.parser.registerOscHandler(OSC, (token) => {
139
+ if (token === "reset") {
140
+ clearPlacements();
141
+ transmission = null;
142
+ return true;
143
+ }
144
+ const sequence = pending.get(token);
145
+ pending.delete(token);
146
+ if (sequence) accept(sequence);
147
+ return true;
148
+ });
149
+ return {
150
+ /** Cheap gate for hot paths: no placements means project() is a no-op. */
151
+ hasPlacements() { return placements.size > 0; },
152
+ transform(data, reset = false) {
153
+ if (reset) carry = "";
154
+ // Zero-copy fast path: return the ORIGINAL string identity when the chunk
155
+ // contains no Kitty APC and has no escape-prefix suffix a later chunk could
156
+ // complete into `\x1b_G`. Only `\x1b` / `\x1b_` tails can split that prefix
157
+ // (an ESC-[ tail cannot). A reset with live placements must keep the reset
158
+ // token so the parser-ordered handler clears them and any in-flight chunked
159
+ // upload (a reset with a pending transmission but no placement yet must not
160
+ // pass through either). Preserving identity also keeps the attach
161
+ // write-instrumentation `===` frame match working.
162
+ if (!carry && !data.includes(PREFIX) && !/\x1b_?$/.test(data) && !(reset && (placements.size > 0 || transmission))) return data;
163
+ const input = carry + data;
164
+ carry = "";
165
+ let out = reset ? `\x1b]${OSC};reset\x07` : "";
166
+ let from = 0;
167
+ while (from < input.length) {
168
+ const start = input.indexOf(PREFIX, from);
169
+ if (start < 0) {
170
+ const tail = input.slice(from);
171
+ const suffix = tail.endsWith("\x1b_") ? 2 : tail.endsWith("\x1b") ? 1 : 0;
172
+ carry = suffix ? tail.slice(-suffix) : "";
173
+ out += suffix ? tail.slice(0, -suffix) : tail;
174
+ break;
175
+ }
176
+ out += input.slice(from, start);
177
+ const end = input.indexOf(ST, start + PREFIX.length);
178
+ if (end < 0) {
179
+ carry = input.slice(start);
180
+ // Large unterminated APCs stay APCs in xterm, not visible payload text.
181
+ if (carry.length > MAX_BYTES) { out += carry; carry = ""; }
182
+ break;
183
+ }
184
+ const token = String(++nextToken);
185
+ pending.set(token, input.slice(start, end + ST.length));
186
+ out += `\x1b]${OSC};${token}\x07`;
187
+ from = end + ST.length;
188
+ }
189
+ return out;
190
+ },
191
+ project(lines, start, height) {
192
+ const out = [...lines];
193
+ for (const [key, p] of placements) {
194
+ if (p.marker?.isDisposed) { removePlacement(key); continue; }
195
+ const row = (p.marker?.line ?? p.row) - start;
196
+ const rows = Number(p.controls.r);
197
+ const limit = Math.min(height, out.length);
198
+ if (p.buffer !== term.buffer.active.type || row >= limit || row + rows <= 0) continue;
199
+ const image = images.get(p.id);
200
+ if (!image) continue;
201
+ const targetRow = Math.max(0, row);
202
+ const visibleRows = Math.min(row + rows, limit) - targetRow;
203
+ const controls = { ...p.controls };
204
+ if (visibleRows !== rows) {
205
+ const sourceY = Number(controls.y ?? 0);
206
+ const sourceHeight = Number(controls.h ?? (image.heightPx - sourceY));
207
+ if (!(sourceHeight > 0)) continue; // Unknown geometry: retain the safe fallback.
208
+ const hiddenRows = targetRow - row;
209
+ const cropTop = Math.floor(sourceHeight * hiddenRows / rows);
210
+ const cropEnd = Math.min(sourceHeight, Math.ceil(sourceHeight * (hiddenRows + visibleRows) / rows));
211
+ controls.y = String(sourceY + cropTop);
212
+ controls.h = String(cropEnd - cropTop);
213
+ controls.r = String(visibleRows);
214
+ }
215
+ // Keep the FIRST APC's row count consistent with the actual placement:
216
+ // Pi uses it to reserve/pre-clear rows before drawing a Kitty image.
217
+ const uploadHeader = { ...image.uploadControls, c: controls.c, r: controls.r };
218
+ // Re-uploading on each projected render is idempotent but can resend large
219
+ // payloads; upload-once/place-only would need host-terminal cache tracking.
220
+ const upload = `${PREFIX}${controlsString(uploadHeader)}${image.payloadCommands}`;
221
+ // The outer TUI supplies the screen row; only the column is adjusted.
222
+ out[targetRow] = `\x1b7\x1b[${p.col + 1}G${upload}${command(controlsString(controls))}\x1b8${out[targetRow]}`;
223
+ }
224
+ return out;
225
+ },
226
+ clearPlacements,
227
+ dispose() {
228
+ handler.dispose();
229
+ clearHandler.dispose();
230
+ clearPlacements();
231
+ images.clear();
232
+ pending.clear();
233
+ carry = "";
234
+ transmission = null;
235
+ },
236
+ };
237
+ }
@@ -269,15 +269,15 @@ export function resolvePasteSelectionSource(value) {
269
269
  }
270
270
 
271
271
  /**
272
- * Issue #174 (B2): whether a normalized mouse event ends a selection gesture
273
- * we should mirror into the X11 PRIMARY selection. Only release/click of the
274
- * left button with native paste enabled (pi's fullscreen selection owns the
275
- * gesture; we observe without consuming). Pure by contract.
272
+ * Issue #174 (B2) / #172: whether a normalized mouse event ends a fullscreen text
273
+ * selection gesture the attach overlay must settle — mirror the selection into X11
274
+ * PRIMARY (#174) and drop pi's highlight once copy-on-select has run (#172). Only
275
+ * release/click of the left button ends a selection in TuiAltScreen; pi owns the
276
+ * gesture, so the overlay observes without consuming. Pure: the native-paste kill
277
+ * switch is applied by writePrimarySelection, not here.
276
278
  */
277
- export function shouldMirrorSelectionToPrimary(event, { nativePasteEnabled }) {
278
- if (!nativePasteEnabled) return null;
279
- if ((event.type === "release" || event.type === "click") && event.button === "left") return "mirror-primary";
280
- return null;
279
+ export function isFullscreenSelectionEnd(event) {
280
+ return (event.type === "release" || event.type === "click") && event.button === "left";
281
281
  }
282
282
 
283
283
  /**
package/src/core/rows.mjs CHANGED
@@ -276,6 +276,29 @@ export function nextVisibleIdAfterRemoval(rows, id, now) {
276
276
  return null;
277
277
  }
278
278
 
279
+ /**
280
+ * Issue #254: the row the board should select after `removedIds` leave their
281
+ * current positions. Mirrors the issue #147 delete semantics — the next visible
282
+ * row after the anchor's slot, else the previous one, else null — but works on
283
+ * the dashboard's already-filtered, already-folded order.
284
+ * @param {readonly string[]} orderedIds visible row ids in board order
285
+ * @param {Iterable<string>} removedIds ids that will leave their positions
286
+ * @param {string} anchorId the id whose slot must be kept
287
+ * @returns {{ neighborId: string | null, anchorIndex: number } | null} null when anchorId is not visible
288
+ */
289
+ export function neighborAfterRemoval(orderedIds, removedIds, anchorId) {
290
+ const anchorIndex = orderedIds.indexOf(anchorId);
291
+ if (anchorIndex === -1) return null;
292
+ const removed = removedIds instanceof Set ? removedIds : new Set(removedIds);
293
+ for (let i = anchorIndex + 1; i < orderedIds.length; i += 1) {
294
+ if (!removed.has(orderedIds[i])) return { neighborId: orderedIds[i], anchorIndex };
295
+ }
296
+ for (let i = anchorIndex - 1; i >= 0; i -= 1) {
297
+ if (!removed.has(orderedIds[i])) return { neighborId: orderedIds[i], anchorIndex };
298
+ }
299
+ return { neighborId: null, anchorIndex };
300
+ }
301
+
279
302
  /**
280
303
  * Stable row order: pinned first, then creation order (oldest first), then id.
281
304
  * Activity time deliberately does not participate, so rows never reshuffle while
@@ -298,9 +321,10 @@ function normalizeFolderKey(path) {
298
321
 
299
322
  /**
300
323
  * Parse a filter query into a state filter + free-text terms.
301
- * Supports `s:<state>` (state prefix) and bare words (AND substring match).
324
+ * Supports `s:<state>` (state prefix), `pr:<number>` (exact PR reference),
325
+ * and bare words (AND substring match).
302
326
  * @param {string} query
303
- * @returns {{ states: SemanticState[], terms: string[], reviewReady: boolean, diagStalled: boolean, evidenceError: boolean, queued: boolean, steering: string|null }}
327
+ * @returns {{ states: SemanticState[], terms: string[], prNumber: number|null, reviewReady: boolean, diagStalled: boolean, evidenceError: boolean, queued: boolean, steering: string|null }}
304
328
  */
305
329
  export function parseFilter(query) {
306
330
  /** @type {Set<SemanticState>} */
@@ -308,6 +332,7 @@ export function parseFilter(query) {
308
332
  /** @type {string[]} */
309
333
  const terms = [];
310
334
  let reviewReady = false;
335
+ let prNumber = null;
311
336
  let diagStalled = false;
312
337
  let evidenceError = false;
313
338
  let queued = false;
@@ -320,6 +345,8 @@ export function parseFilter(query) {
320
345
  const aliases = [s, GROUP_LABELS[s]];
321
346
  if (aliases.some((alias) => matchesStateToken(alias, want))) states.add(s);
322
347
  }
348
+ } else if (/^pr:(?:#|!)?[1-9]\d*$/i.test(tok) && Number.isSafeInteger(Number(tok.replace(/^pr:(?:#|!)?/i, "")))) {
349
+ prNumber = Number(tok.replace(/^pr:(?:#|!)?/i, ""));
323
350
  } else if (/^review:ready$/i.test(tok)) {
324
351
  reviewReady = true;
325
352
  } else if (/^diag:stalled$/i.test(tok)) {
@@ -334,7 +361,7 @@ export function parseFilter(query) {
334
361
  terms.push(tok.toLowerCase());
335
362
  }
336
363
  }
337
- return { states: [...states], terms, reviewReady, diagStalled, evidenceError, queued, steering };
364
+ return { states: [...states], terms, prNumber, reviewReady, diagStalled, evidenceError, queued, steering };
338
365
  }
339
366
 
340
367
  /** @param {string} value */
@@ -350,7 +377,7 @@ function matchesStateToken(alias, want) {
350
377
 
351
378
  /** @param {string} query @returns {boolean} whether the text is a filter expression. */
352
379
  export function isFilterQuery(query) {
353
- return /(^|\s)(s:|review:|diag:|evidence:|queued:|steer:)/i.test(query || "");
380
+ return /(^|\s)(s:|pr:|review:|diag:|evidence:|queued:|steer:)/i.test(query || "");
354
381
  }
355
382
 
356
383
  /**
@@ -360,17 +387,26 @@ export function isFilterQuery(query) {
360
387
  * @returns {Row[]}
361
388
  */
362
389
  export function filterRows(rows, query) {
363
- const { states, terms, reviewReady, diagStalled, evidenceError, queued, steering } = parseFilter(query);
364
- if (states.length === 0 && terms.length === 0 && !reviewReady && !diagStalled && !evidenceError && !queued && !steering) return rows;
390
+ const { states, terms, prNumber, reviewReady, diagStalled, evidenceError, queued, steering } = parseFilter(query);
391
+ if (states.length === 0 && terms.length === 0 && prNumber === null && !reviewReady && !diagStalled && !evidenceError && !queued && !steering) return rows;
365
392
  return rows.filter((row) => {
366
393
  if (states.length > 0 && !states.includes(rowState(row))) return false;
394
+ const prRefs = [row.codeRefs?.pr, ...(row.codeRefs?.allRefs ?? [])];
395
+ if (prNumber !== null && !prRefs.some((ref) => ref?.kind === "pr" && ref.number === prNumber)) return false;
367
396
  if (reviewReady && !row.state?.review?.ready) return false;
368
397
  if (diagStalled && !row.state?.diagnostics?.stalled) return false;
369
398
  if (evidenceError && (row.state?.review?.errorCount ?? 0) <= 0) return false;
370
399
  if (queued && (row.state?.followUps?.queuedCount ?? 0) <= 0) return false;
371
400
  if (steering && normalizeStateToken(row.state?.steering?.status ?? "none") !== steering) return false;
372
401
  if (terms.length === 0) return true;
373
- const hay = [row.meta.name, row.state?.summary ?? "", row.meta.repoCwd, row.meta.cwd]
402
+ // Search the bounded, persisted PR refs already displayed by the board.
403
+ // A partial number ("2", "22", "227") narrows results as it is typed;
404
+ // issue refs stay distinct and the session transcript is not scanned.
405
+ const prText = prRefs
406
+ .filter((ref) => ref?.kind === "pr" && Number.isSafeInteger(ref.number))
407
+ .map((ref) => `PR #${ref.number} !${ref.number}`)
408
+ .join(" ");
409
+ const hay = [row.meta.name, row.state?.summary ?? "", row.meta.repoCwd, row.meta.cwd, prText]
374
410
  .join(" ")
375
411
  .toLowerCase();
376
412
  return terms.every((t) => hay.includes(t));