@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
@@ -8,10 +8,12 @@
8
8
  */
9
9
  import { readFileSync } from "node:fs";
10
10
  import { CustomEditor } from "@earendil-works/pi-coding-agent";
11
- import type { Component, EditorTheme, KeybindingsManager, TUI } from "@earendil-works/pi-tui";
12
- import { Key, matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
11
+ import type { Component, EditorTheme, KeybindingsManager, TUI, TuiMouseEvent, TuiMouseEventResult } from "@earendil-works/pi-tui";
12
+ import { Key, matchesKey, parseKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
13
13
  import { requestDashboardRender } from "../core/dashboard-render.mjs";
14
+ import { readFoldedSections, saveFoldedSections } from "../core/dashboard-prefs.mjs";
14
15
  import { normalizeGenericStatusText } from "../core/derive.mjs";
16
+ import { createFullscreenSelectionSettler } from "../core/fullscreen-selection.mjs";
15
17
  import { firstSentence, truncate } from "../core/heuristics.mjs";
16
18
  import {
17
19
  browseTabCompletion,
@@ -28,14 +30,18 @@ import {
28
30
  import { createPrewarmScheduler } from "../core/prewarm-schedule.mjs";
29
31
  import { planDashboardAttach, planPrewarm, replyNotice } from "./dashboard-decisions.mjs";
30
32
  import { ensureCwdStatsSeeded, rankedCwdCandidates, recordCwdLaunch } from "../core/cwd-stats.mjs";
31
- import { filterRows, groupRowsByFolder, rowState, stateGlyph } from "../core/rows.mjs";
33
+ import { filterRows, groupRowsByFolder, neighborAfterRemoval, rowState, stateGlyph } from "../core/rows.mjs";
32
34
  import { loadSessionView } from "../core/session-view.mjs";
33
35
  import { GROUP_LABELS } from "../core/types.mjs";
34
36
  import { buildEvidencePanel } from "./dashboard-evidence.mjs";
37
+ import type { FullscreenSelectionHost } from "./pty-attach.ts";
35
38
  import { type Row } from "../core/store.mjs";
36
39
  import type { createService } from "../runtime/service.mjs";
37
40
 
38
41
  type Service = ReturnType<typeof createService>;
42
+ type SectionState = keyof typeof GROUP_LABELS;
43
+ type ListTarget = { kind: "section"; state: SectionState } | { kind: "row"; state: SectionState; id: string };
44
+ type PositionAnchor = { neighborId: string | null; anchorIndex: number };
39
45
  type PtyIssue = {
40
46
  id: string;
41
47
  title: string;
@@ -129,6 +135,10 @@ export class DashboardComponent implements Component {
129
135
  private rows: Row[] = [];
130
136
  private orderedIds: string[] = [];
131
137
  private selectedId: string | null = null;
138
+ private selectedSection: SectionState | null = null;
139
+ private foldedSections = new Set<SectionState>();
140
+ private listTargets: ListTarget[] = [];
141
+ private selectedBodyLine = 0;
132
142
  private selectedIds = new Set<string>();
133
143
  private input = "";
134
144
  private filterQuery = "";
@@ -150,6 +160,11 @@ export class DashboardComponent implements Component {
150
160
  * "assumes clean screen" (fullRender(false)) and overlays never get
151
161
  * clearOnShrink — crash output / dirty bottoms would persist (issue #88). */
152
162
  private needsFullClear = true;
163
+ /** Issue #258: set at dispose() so a settle queued before unmount cannot
164
+ * touch pi-level selection state afterwards (the gesture serial only grows
165
+ * on presses this component still observes). */
166
+ private disposed = false;
167
+ private readonly selectionSettler: ReturnType<typeof createFullscreenSelectionSettler>;
153
168
  /** Content line count of the previous frame BEFORE spacer/padding fill
154
169
  * (padding always fills the terminal height, so padded counts never
155
170
  * shrink — shrink detection must run on pre-fill counts). */
@@ -174,9 +189,15 @@ export class DashboardComponent implements Component {
174
189
  };
175
190
  this.editor.onSubmit = (text) => this.submitEditor(text);
176
191
  this.selectedId = deps.initialSelectedId ?? null;
192
+ this.selectionSettler = createFullscreenSelectionSettler({
193
+ host: tui as unknown as FullscreenSelectionHost,
194
+ repaint: () => this.tui.requestRender(),
195
+ shouldSettle: () => !this.disposed,
196
+ });
177
197
  // Issue #147: the post-delete reopen carries the Deleted notice here —
178
198
  // the component is new each open, so an inline notice cannot travel.
179
199
  if (deps.initialNotice) this.notice(deps.initialNotice, "info");
200
+ this.foldedSections = new Set(readFoldedSections(deps.root));
180
201
  try {
181
202
  this.lastLaunchPrefs = this.deps.service.getLaunchPrefs?.() ?? null;
182
203
  } catch {
@@ -193,16 +214,62 @@ export class DashboardComponent implements Component {
193
214
  const all = this.deps.service.rows();
194
215
  this.rows = this.filterQuery ? filterRows(all, this.filterQuery) : all;
195
216
  const groups = groupRowsByFolder(this.rows, Date.now());
196
- this.orderedIds = groups.flatMap((g) => g.folders.flatMap((f) => f.rows.map((r) => r.id)));
217
+ this.listTargets = groups.flatMap((group): ListTarget[] => [
218
+ { kind: "section", state: group.state },
219
+ ...(this.isSectionFolded(group.state) ? [] : group.folders.flatMap((folder) =>
220
+ folder.rows.map((row): ListTarget => ({ kind: "row", state: group.state, id: row.id })))),
221
+ ]);
222
+ this.orderedIds = this.listTargets.flatMap((target) => target.kind === "row" ? [target.id] : []);
197
223
  const visibleIds = new Set(this.orderedIds);
198
224
  this.selectedIds = new Set([...this.selectedIds].filter((id) => visibleIds.has(id)));
199
- if (this.orderedIds.length === 0) {
225
+ if (this.selectedId && visibleIds.has(this.selectedId)) {
226
+ this.selectedSection = null;
227
+ } else if (this.selectedId) {
228
+ // A row can move into a folded section while the board is polling.
229
+ const row = this.rows.find((row) => row.meta.id === this.selectedId);
230
+ this.selectedSection = row ? rowState(row) : null;
200
231
  this.selectedId = null;
201
- if (this.mode === "select") this.mode = "list";
202
- } else if (!this.selectedId || !this.orderedIds.includes(this.selectedId)) {
203
- this.selectedId = this.orderedIds[0];
204
232
  }
205
- if (this.selectedId && this.selectedId !== previousSelected) this.prewarmScheduler.schedule();
233
+ if (this.selectedSection && !groups.some((group) => group.state === this.selectedSection)) this.selectedSection = null;
234
+ if (!this.selectedId && !this.selectedSection) {
235
+ // Preserve the existing initial focus on a session when one is visible.
236
+ this.selectedId = this.orderedIds[0] ?? null;
237
+ if (!this.selectedId) this.selectedSection = this.listTargets[0]?.state ?? null;
238
+ }
239
+ if (this.orderedIds.length === 0 && this.mode === "select") this.mode = "list";
240
+ if (!this.selectedId) this.prewarmScheduler.cancel();
241
+ else if (this.selectedId !== previousSelected) this.prewarmScheduler.schedule();
242
+ }
243
+
244
+ /**
245
+ * Issue #254: the slot a demote command is about to vacate. Capture it BEFORE
246
+ * the state command runs — afterwards the row has already moved and the old
247
+ * position is only recoverable from the pre-mutation order.
248
+ */
249
+ private capturePositionAnchor(id: string, removedIds: string[] = [id]): PositionAnchor | null {
250
+ return neighborAfterRemoval(this.orderedIds, removedIds, id);
251
+ }
252
+
253
+ /**
254
+ * Issue #254: apply a captured anchor after refresh(). Prefer the row that
255
+ * filled the slot, else clamp to the old index. Never assign an id that is no
256
+ * longer visible — refresh() would read it as "selected row vanished" and jump
257
+ * to the top of the list.
258
+ */
259
+ private applyPositionAnchor(anchor: PositionAnchor | null): void {
260
+ if (!anchor) return;
261
+ const last = this.orderedIds.length - 1;
262
+ if (last < 0) return;
263
+ const neighbor = anchor.neighborId;
264
+ const target = neighbor && this.orderedIds.includes(neighbor)
265
+ ? neighbor
266
+ : this.orderedIds[Math.min(anchor.anchorIndex, last)];
267
+ if (!target) return;
268
+ this.selectedId = target;
269
+ this.selectedSection = null;
270
+ // Defer like every other prewarm entry point: a burst of `h` presses must
271
+ // spawn at most one host, for the resting selection (prewarm-schedule.mjs).
272
+ this.prewarmScheduler.schedule();
206
273
  }
207
274
 
208
275
  private selectedRow(): Row | null {
@@ -264,15 +331,47 @@ export class DashboardComponent implements Component {
264
331
  }
265
332
 
266
333
  private moveSelection(delta: number): void {
267
- if (this.orderedIds.length === 0) return;
268
- const cur = this.selectedId ? this.orderedIds.indexOf(this.selectedId) : 0;
269
- const len = this.orderedIds.length;
270
- // Wrap around both ends: down past last -> first, up past first -> last.
271
- const next = (((cur < 0 ? 0 : cur) + delta) % len + len) % len;
272
- const nextId = this.orderedIds[next];
273
- if (nextId === this.selectedId) return;
274
- this.selectedId = nextId;
275
- this.prewarmScheduler.schedule();
334
+ // Batch selection still navigates sessions only, never section headings.
335
+ const targets: ListTarget[] = this.mode === "select"
336
+ ? this.listTargets.filter((target) => target.kind === "row")
337
+ : this.listTargets;
338
+ if (targets.length === 0) return;
339
+ const cur = targets.findIndex((target) => target.kind === "section"
340
+ ? target.state === this.selectedSection
341
+ : target.id === this.selectedId);
342
+ const next = (((cur < 0 ? 0 : cur) + delta) % targets.length + targets.length) % targets.length;
343
+ const target = targets[next];
344
+ this.selectedId = target.kind === "row" ? target.id : null;
345
+ this.selectedSection = target.kind === "section" ? target.state : null;
346
+ if (this.selectedId) this.prewarmScheduler.schedule();
347
+ else this.prewarmScheduler.cancel();
348
+ }
349
+
350
+ private isSectionFolded(state: SectionState): boolean {
351
+ // Search results remain discoverable without discarding saved folds.
352
+ return !this.filterQuery.trim() && this.foldedSections.has(state);
353
+ }
354
+
355
+ private toggleSectionFold(folded?: boolean): void {
356
+ const row = this.selectedRow();
357
+ const state = this.selectedSection ?? (row ? rowState(row) : null);
358
+ if (!state) return;
359
+ if (this.filterQuery.trim()) {
360
+ this.notifyInputState("Clear the filter to fold sections", "muted");
361
+ return;
362
+ }
363
+ if (folded ?? !this.foldedSections.has(state)) this.foldedSections.add(state);
364
+ else this.foldedSections.delete(state);
365
+ // Header focus keeps a collapsed section reachable and never leaves a
366
+ // hidden session as the target of attach/delete/hold actions.
367
+ this.selectedId = null;
368
+ this.selectedSection = state;
369
+ this.refresh();
370
+ try {
371
+ saveFoldedSections(this.deps.root, this.foldedSections);
372
+ } catch {
373
+ this.notifyInputState("Fold changed for now; could not save preference", "warning");
374
+ }
276
375
  }
277
376
 
278
377
  private prewarmSelected(): void {
@@ -356,18 +455,32 @@ export class DashboardComponent implements Component {
356
455
  requestDashboardRender(this.tui);
357
456
  }
358
457
 
458
+ /** Issue #258: observe-only mouse hook. pi keeps every gesture (selection,
459
+ * copy, links); the settler only drops the stale highlight after
460
+ * copy-on-select. Always returns undefined — never consumes. */
461
+ handleMouse(_event: TuiMouseEvent): TuiMouseEventResult | undefined {
462
+ this.selectionSettler.observeMouse(_event);
463
+ return undefined;
464
+ }
465
+
359
466
  private handleListKey(data: string): void {
360
467
  if (!matchesKey(data, Key.ctrl("x"))) this.deleteArm = null;
361
468
  if (matchesKey(data, Key.up) || data === "k") return void this.moveSelection(-1);
362
469
  if (matchesKey(data, Key.down) || data === "j") return void this.moveSelection(1);
470
+ // Older pi-tui matchesKey misses unmodified modifyOtherKeys Tab, even
471
+ // though parseKey decodes it correctly (some terminal/tmux paths use it).
472
+ if (matchesKey(data, Key.tab) || parseKey(data) === Key.tab) return this.toggleSectionFold();
473
+ if (this.selectedSection && matchesKey(data, Key.left)) return this.toggleSectionFold(true);
474
+ if (this.selectedSection && (matchesKey(data, Key.right) || data === "l")) return this.toggleSectionFold(false);
363
475
  if (matchesKey(data, Key.right) || data === ">" || data === "l") return this.attachSelected();
364
476
  if (data === "v") return this.openSessionView();
365
477
  if (data === "e") return this.openEvidenceView();
366
478
  if (matchesKey(data, Key.enter)) {
367
479
  if (this.input.trim()) return this.openLaunchDialog();
480
+ if (this.selectedSection) return this.toggleSectionFold();
368
481
  return this.attachSelected();
369
482
  }
370
- if (matchesKey(data, Key.space)) return this.openPeek();
483
+ if (matchesKey(data, Key.space)) return this.selectedSection ? this.toggleSectionFold() : this.openPeek();
371
484
  if (data === "m") return this.startSelectionMode();
372
485
  if (data === "/") return this.startFilter();
373
486
  if (data === "?") return this.openHelp("list");
@@ -752,7 +865,7 @@ export class DashboardComponent implements Component {
752
865
  if (picker === "cwd") {
753
866
  try {
754
867
  ensureCwdStatsSeeded(this.deps.root);
755
- launch.cwdRanked = existingCwdCandidates(rankedCwdCandidates(this.deps.root, 8));
868
+ launch.cwdRanked = existingCwdCandidates(rankedCwdCandidates(this.deps.root));
756
869
  } catch {
757
870
  launch.cwdRanked = [];
758
871
  }
@@ -980,10 +1093,19 @@ export class DashboardComponent implements Component {
980
1093
  this.pending = {
981
1094
  prompt: `Mark "${row.meta.name}" as done? (y/N)`,
982
1095
  onYes: () => {
1096
+ // Issue #254: capture before the state command; apply only on success.
1097
+ const anchor = this.capturePositionAnchor(row.meta.id);
983
1098
  void this.markCompleted(row).then((res) => {
1099
+ // Read the cursor BEFORE refresh(): a j/k during the round-trip moved it
1100
+ // already, and refresh() re-anchors selectedId off the demoted row in the
1101
+ // active-filter case — so the comparison must see the pre-refresh value.
1102
+ // Peek mode acts on peekId, so a peek repeat is "moved" and skips the
1103
+ // anchor but must still refresh.
1104
+ const moved = this.selectedId !== row.meta.id;
984
1105
  if (!res.ok) this.notice(res.error ?? "Mark done failed", "error");
985
1106
  else this.notice("Marked done", "info");
986
1107
  this.refresh();
1108
+ if (res.ok && !moved) this.applyPositionAnchor(anchor);
987
1109
  });
988
1110
  },
989
1111
  };
@@ -997,11 +1119,24 @@ export class DashboardComponent implements Component {
997
1119
  if (!row) return;
998
1120
  const holding = row.state?.semanticState === "holding";
999
1121
  if (!holding && isAgentBusy(row)) return this.notice("Wait for the active run to finish before placing on hold", "warn");
1122
+ // Issue #254: remember the slot before the state command moves the row.
1123
+ const anchor = this.capturePositionAnchor(row.meta.id);
1000
1124
  const run = holding ? this.deps.service.clearHoldView(row.meta.id) : this.deps.service.holdView(row.meta.id);
1001
1125
  void Promise.resolve(run).then((res) => {
1002
- if (!res.ok) this.notice(res.error ?? (holding ? "Resume failed" : "Hold failed"), "error");
1003
- else this.notice(holding ? "Resumed — needs instructions" : "On hold", "info");
1126
+ if (!res.ok) {
1127
+ this.notice(res.error ?? (holding ? "Resume failed" : "Hold failed"), "error");
1128
+ this.refresh();
1129
+ return;
1130
+ }
1131
+ this.notice(holding ? "Resumed — needs instructions" : "On hold", "info");
1132
+ // The command is async IPC; a j/k (or a new peek target) during the
1133
+ // round-trip moved the cursor already — never override that newer choice.
1134
+ // Read it BEFORE refresh(): refresh() re-anchors selectedId off the demoted
1135
+ // row in the active-filter case. Peek mode acts on peekId, so a peek repeat
1136
+ // is "moved" and skips the anchor but must still refresh.
1137
+ const moved = this.selectedId !== row.meta.id;
1004
1138
  this.refresh();
1139
+ if (!moved) this.applyPositionAnchor(anchor);
1005
1140
  });
1006
1141
  }
1007
1142
 
@@ -1015,13 +1150,27 @@ export class DashboardComponent implements Component {
1015
1150
  prompt: `Mark ${doneIds.length} selected session${doneIds.length === 1 ? "" : "s"} as done?${skipped ? ` ${skipped} will be skipped.` : ""} (y/N)`,
1016
1151
  returnMode: "select",
1017
1152
  onYes: () => {
1153
+ // Issue #254: anchor on the topmost selected row in board order —
1154
+ // selectedIds is a Set in insertion order, so doneIds[0] is arbitrary.
1155
+ const topmost = doneIds
1156
+ .map((id) => this.orderedIds.indexOf(id))
1157
+ .filter((index) => index >= 0)
1158
+ .reduce((min, index) => (index < min ? index : min), Number.POSITIVE_INFINITY);
1159
+ const anchor = Number.isFinite(topmost)
1160
+ ? this.capturePositionAnchor(this.orderedIds[topmost], doneIds)
1161
+ : null;
1162
+ // The cursor the batch was confirmed from; a j/k during the round-trip
1163
+ // moves it, and the anchor must not override that newer choice.
1164
+ const cursorBefore = this.selectedId;
1018
1165
  void Promise.resolve(this.deps.service.markCompletedMany?.(doneIds) ?? { ok: true, completed: 0, skipped: doneIds.length, completedIds: [] }).then((res) => {
1166
+ // Read the cursor BEFORE refresh(): refresh() re-anchors selectedId off
1167
+ // a demoted row in the active-filter case.
1168
+ const moved = this.selectedId !== cursorBefore;
1019
1169
  if (!res.ok) this.notice("Mark done failed", "error");
1020
- else {
1021
- if (res.completedIds?.length) this.selectedId = res.completedIds[0];
1022
- this.notice(`Moved ${res.completed} to Done${res.skipped ? ` · skipped ${res.skipped}` : ""}`, "info");
1023
- }
1170
+ else this.notice(`Moved ${res.completed} to Done${res.skipped ? ` · skipped ${res.skipped}` : ""}`, "info");
1024
1171
  this.refresh();
1172
+ // A batch that completed nothing moved nothing — keep the cursor.
1173
+ if (res.ok && res.completed > 0 && !moved) this.applyPositionAnchor(anchor);
1025
1174
  });
1026
1175
  },
1027
1176
  };
@@ -1204,6 +1353,7 @@ export class DashboardComponent implements Component {
1204
1353
 
1205
1354
  dispose(): void {
1206
1355
  /* poll interval is owned by the factory */
1356
+ this.disposed = true;
1207
1357
  this.prewarmScheduler.cancel();
1208
1358
  }
1209
1359
 
@@ -1352,13 +1502,18 @@ export class DashboardComponent implements Component {
1352
1502
  "space toggle",
1353
1503
  "a all visible",
1354
1504
  "u clear",
1355
- "d move done",
1356
- "ctrl+x delete done",
1357
- "esc cancel",
1505
+ "d done",
1506
+ "ctrl+x delete",
1507
+ "m/esc cancel",
1508
+ "? help",
1509
+ "! pty",
1358
1510
  ]);
1359
1511
  }
1512
+ if (this.selectedSection && !this.input.trim()) {
1513
+ return this.hintLine("SECTION", "accent", ["tab/enter fold", "← collapse", "→ expand", "↑↓ navigate", "i insert", "/ filter", "? help", "esc exit"]);
1514
+ }
1360
1515
  const primary = this.input.trim() ? "enter launch" : live ? "enter attach live" : "enter resume";
1361
- const hints = ["i insert", primary, "→/l attach", "m multi-select", ...(unread > 0 ? [`•${unread} unread`] : []), "d done", "h hold", "space peek", "v transcript", "e evidence", "ctrl+n new session", "ctrl+r rename", "x delete (y/N)", "ctrl+x x2 quick", "X delete state", "/ filter", "! pty", "? help"];
1516
+ const hints = ["i insert", primary, "tab fold", "→/l attach", "m multi-select", ...(unread > 0 ? [`•${unread} unread`] : []), "d done", "h hold", "space peek", "v transcript", "e evidence", "ctrl+n new session", "ctrl+r rename", "x delete (y/N)", "ctrl+x x2 quick", "X delete state", "/ filter", "! pty", "? help"];
1362
1517
  if (this.input.trim()) hints.splice(1, 0, "esc clear");
1363
1518
  return this.hintLine("NORMAL", "muted", hints);
1364
1519
  }
@@ -1420,13 +1575,17 @@ export class DashboardComponent implements Component {
1420
1575
  const now = Date.now();
1421
1576
  const groups = groupRowsByFolder(this.rows, now);
1422
1577
  const out: string[] = [];
1578
+ this.selectedBodyLine = 0;
1423
1579
  for (const g of groups) {
1424
1580
  if (out.length > 0) out.push("");
1581
+ if (this.selectedSection === g.state) this.selectedBodyLine = out.length;
1425
1582
  out.push(this.renderStageHeader(g.state, g.label, g.rowCount, width));
1583
+ if (this.isSectionFolded(g.state)) continue;
1426
1584
  const showFolderHeaders = g.showFolders;
1427
1585
  for (const folder of g.folders) {
1428
1586
  if (showFolderHeaders) out.push(this.renderFolderHeader(g.state, folder, width));
1429
1587
  for (const rv of folder.rows) {
1588
+ if (rv.id === this.selectedId) this.selectedBodyLine = out.length;
1430
1589
  out.push(this.renderRow(rv, width, { showFolder: !showFolderHeaders, indent: showFolderHeaders ? 4 : 2 }));
1431
1590
  }
1432
1591
  }
@@ -1436,10 +1595,12 @@ export class DashboardComponent implements Component {
1436
1595
 
1437
1596
  private renderStageHeader(state: keyof typeof GROUP_LABELS, label: string, count: number, width: number): string {
1438
1597
  const t = this.theme;
1439
- const glyph = stateGlyph(state, state === "working");
1440
- const title = stageFg(state, t.bold(`${glyph} ${label.toUpperCase()}`));
1441
- const countText = t.fg("dim", ` ${count}`);
1442
- const ruleWidth = Math.max(0, width - visibleWidth(`${glyph} ${label.toUpperCase()} ${count}`) - 2);
1598
+ const disclosure = this.isSectionFolded(state) ? "▸" : "▾";
1599
+ const marker = this.selectedSection === state ? "›" : " ";
1600
+ const text = `${marker}${disclosure} ${label.toUpperCase()}`;
1601
+ const title = stageFg(state, t.bold(text));
1602
+ const countText = t.fg("dim", ` (${count})`);
1603
+ const ruleWidth = Math.max(0, width - visibleWidth(`${text} (${count})`) - 1);
1443
1604
  return clip(`${title}${countText} ${t.fg("borderMuted", "─".repeat(ruleWidth))}`, width);
1444
1605
  }
1445
1606
 
@@ -1540,7 +1701,7 @@ export class DashboardComponent implements Component {
1540
1701
  const notice = this.currentInputNotice();
1541
1702
  if (notice) out.push(clip(t.fg(notice.color, `ⓘ ${notice.text}`), width));
1542
1703
  } else {
1543
- out.push(clip(t.fg("dim", "↑↓ prev/next · →/> attach · d done · v transcript · e evidence · r reply · esc back"), width));
1704
+ out.push(clip(t.fg("dim", "↑↓/j/k prev/next · →/l attach · d done · v transcript · e evidence · r reply · esc back"), width));
1544
1705
  }
1545
1706
  return out;
1546
1707
  }
@@ -1698,21 +1859,22 @@ export class DashboardComponent implements Component {
1698
1859
  private renderHelp(width: number): string[] {
1699
1860
  const t = this.theme;
1700
1861
  const rows: Array<[string, string]> = [
1701
- ["normal", "Dashboard owns keys; i enters insert mode"],
1702
- ["insert", "Editor owns text keys; / is literal, arrows move cursor"],
1862
+ ["normal/insert", "Normal: board keys; i enters insert; Esc returns to normal"],
1703
1863
  ["i", "Enter insert/compose mode; then / is literal for slash commands"],
1704
1864
  ["m", "Enter multi-select mode from the board list"],
1705
1865
  ["enter", "Normal/insert with draft: open start-session dialog; empty: attach/resume"],
1706
1866
  ["shift+enter", "Insert a newline while in insert/reply"],
1707
1867
  ["esc", "Insert → normal; Normal with draft clears; empty quits standalone dashboard"],
1708
- ["↑/↓ or j/k", "Normal: move selection; Insert: move cursor"],
1868
+ ["↑/↓ or j/k", "Normal: navigate sessions and section headings; Insert: move cursor"],
1869
+ ["tab", "Fold/unfold the selected section (or session's section); remembered on reopen"],
1709
1870
  ["ctrl/alt+←/→", "Jump by word in insert mode"],
1710
- ["→ / > / l", "Attach to the selected real Pi session"],
1871
+ ["→ / > / l", "Session: attach; section heading: →/l expand / ← collapse"],
1711
1872
  ["d", "Confirm and mark selected inactive session done"],
1712
1873
  ["h", "Hold / unhold the selected inactive session (on-hold state)"],
1713
- ["space", "Peek when input is empty; in multi-select: toggle current row"],
1874
+ ["space", "Session: peek; section: fold/unfold; multi-select: toggle row"],
1714
1875
  ["e", "Open evidence / diagnostics panel for selected session"],
1715
1876
  ["/", "Filter in normal mode; use i then / for slash commands"],
1877
+ ["?", "Open the key help overlay (list and multi-select)"],
1716
1878
  ["!", "Open node-pty diagnostics and fix steps"],
1717
1879
  ["ctrl+n", "Open the new-session launch dialog (prompt pre-filled)"],
1718
1880
  ["ctrl+r/t/s", "Rename · pin · stop selected"],
@@ -1720,7 +1882,7 @@ export class DashboardComponent implements Component {
1720
1882
  ["ctrl+x x2", "Delete selected session (quick double-press, no confirm)"],
1721
1883
  ["X", "Delete all inactive sessions in selected state"],
1722
1884
  ["v", "Open read-only transcript view"],
1723
- ["In select", "j/k move · a select all · u clear · d move done · ctrl+x delete · esc cancel"],
1885
+ ["In select", "↑↓/j/k move · space toggle · a all · u clear · d done · ctrl+x delete · m/esc cancel"],
1724
1886
  ["In peek", "→/l attach · v transcript · e evidence · r reply · ↑↓/j/k adjacent"],
1725
1887
  ["In session", "← back · ↑↓/j/k scroll · e evidence · enter attach · r reply"],
1726
1888
  ["In evidence", "← back · ↑↓/j/k scroll · →/l attach · r reply · v transcript · x clear diag"],
@@ -1770,17 +1932,11 @@ export class DashboardComponent implements Component {
1770
1932
  }
1771
1933
 
1772
1934
  /** Keep the selected row visible within `capacity` lines, with scroll markers. */
1773
- private windowBody(body: string[], capacity: number): { lines: string[] } {
1935
+ private windowBody(body: string[], capacity: number, selLine = this.selectedBodyLine): { lines: string[] } {
1774
1936
  if (body.length <= capacity) {
1775
1937
  this.scrollTop = 0;
1776
1938
  return { lines: body };
1777
1939
  }
1778
- // Find the line index of the selected row (best effort: match its rendered prefix).
1779
- let selLine = 0;
1780
- if (this.selectedId) {
1781
- const idx = body.findIndex((l) => l.includes("›"));
1782
- selLine = idx >= 0 ? idx : 0;
1783
- }
1784
1940
  // The boundary lines can become scroll markers, so keep selection inside
1785
1941
  // them. On tiny viewports, prioritize the selected row over markers.
1786
1942
  const margin = capacity >= 3 ? 1 : 0;
@@ -1789,7 +1945,8 @@ export class DashboardComponent implements Component {
1789
1945
  this.scrollTop = Math.max(0, Math.min(this.scrollTop, body.length - capacity));
1790
1946
  // The first session can follow both a stage and a folder header. Those
1791
1947
  // lines aren't selectable, so reveal them when the first session fits.
1792
- if (this.selectedId === this.orderedIds[0] && selLine < capacity) this.scrollTop = 0;
1948
+ const atStart = this.selectedSection === this.listTargets[0]?.state || this.selectedId === this.orderedIds[0];
1949
+ if (atStart && selLine < capacity) this.scrollTop = 0;
1793
1950
  const slice = body.slice(this.scrollTop, this.scrollTop + capacity);
1794
1951
  const more = body.length - this.scrollTop - capacity;
1795
1952
  if (this.scrollTop > 0 && selLine !== this.scrollTop) slice[0] = this.theme.fg("dim", ` ↑ ${this.scrollTop + 1} more`);