@cueloop/client 0.1.0-alpha.6 → 0.1.0-alpha.61

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 (161) hide show
  1. package/native/build-pty.sh +51 -0
  2. package/native/build.sh +82 -0
  3. package/native/darwin-arm64/libcuelooppty.dylib +0 -0
  4. package/native/darwin-arm64/libcueloopvt.dylib +0 -0
  5. package/native/src/pty.zig +193 -0
  6. package/native/src/shim.zig +114 -0
  7. package/package.json +37 -33
  8. package/src/App.appearance.test.tsx +51 -0
  9. package/src/App.autoclose.test.tsx +73 -47
  10. package/src/App.diff.test.tsx +169 -22
  11. package/src/App.export.test.tsx +49 -37
  12. package/src/App.plan-review.test.tsx +714 -0
  13. package/src/App.prototype.test.tsx +194 -0
  14. package/src/App.readonly.test.tsx +69 -35
  15. package/src/App.rendering.test.tsx +59 -31
  16. package/src/App.review-panel.test.tsx +143 -0
  17. package/src/App.submit-confirm.test.tsx +229 -0
  18. package/src/App.test.tsx +139 -68
  19. package/src/App.toast.test.tsx +77 -0
  20. package/src/App.tsx +0 -0
  21. package/src/App.walk.test.tsx +299 -0
  22. package/src/__snapshots__/view-plan.regression.test.ts.snap +100 -0
  23. package/src/app-key-state.ts +61 -0
  24. package/src/app-screens.tsx +270 -0
  25. package/src/app-view-model.ts +307 -0
  26. package/src/attribution.test.ts +31 -0
  27. package/src/attribution.ts +42 -0
  28. package/src/clipboard.test.ts +23 -0
  29. package/src/clipboard.ts +33 -0
  30. package/src/components/AnnotationCard.compose-rows.test.ts +49 -0
  31. package/src/components/AnnotationCard.stories.tsx +94 -0
  32. package/src/components/AnnotationCard.tsx +250 -0
  33. package/src/components/Breadcrumb.stories.tsx +19 -0
  34. package/src/components/Breadcrumb.tsx +45 -0
  35. package/src/components/CodeBlock.stories.tsx +42 -0
  36. package/src/components/CodeBlock.tsx +84 -0
  37. package/src/components/CompletionOverlay.stories.tsx +23 -0
  38. package/src/components/CompletionOverlay.tsx +60 -0
  39. package/src/components/ConfirmCard.stories.tsx +35 -0
  40. package/src/components/ConfirmCard.tsx +129 -0
  41. package/src/components/ConfirmDialog.stories.tsx +21 -0
  42. package/src/components/ConfirmDialog.tsx +66 -0
  43. package/src/components/DiffSheet.scroll.test.tsx +135 -0
  44. package/src/components/DiffSheet.stories.tsx +78 -0
  45. package/src/components/DiffSheet.syntax.test.tsx +65 -0
  46. package/src/components/DiffSheet.tsx +374 -0
  47. package/src/components/InboxList.stories.tsx +31 -0
  48. package/src/components/InboxList.tsx +64 -0
  49. package/src/components/KeybindsDialog.stories.tsx +31 -0
  50. package/src/components/KeybindsDialog.tsx +59 -0
  51. package/src/components/MarkerPopover.stories.tsx +58 -0
  52. package/src/components/MarkerPopover.tsx +109 -0
  53. package/src/components/MenuBar.stories.tsx +37 -0
  54. package/src/components/MenuBar.tsx +75 -0
  55. package/src/components/PlanSheet.stories.tsx +113 -0
  56. package/src/components/PlanSheet.tsx +422 -0
  57. package/src/components/PromptDialog.stories.tsx +36 -0
  58. package/src/components/PromptDialog.tsx +80 -0
  59. package/src/components/PrototypeSheet.stories.tsx +20 -0
  60. package/src/components/PrototypeSheet.tsx +450 -0
  61. package/src/components/ReviewPanel.stories.tsx +86 -0
  62. package/src/components/ReviewPanel.tsx +103 -0
  63. package/src/components/ReviewRail.stories.tsx +218 -0
  64. package/src/components/ReviewRail.tsx +318 -0
  65. package/src/components/SettingsDialog.stories.tsx +111 -0
  66. package/src/components/SettingsDialog.tsx +147 -0
  67. package/src/components/SettingsRows.stories.tsx +18 -0
  68. package/src/components/SettingsRows.tsx +112 -0
  69. package/src/components/Toast.stories.tsx +12 -0
  70. package/src/components/Toast.tsx +45 -0
  71. package/src/components/WalkWizard.stories.tsx +100 -0
  72. package/src/components/WalkWizard.tsx +152 -0
  73. package/src/components/__snapshots__/stories.test.tsx.snap +1857 -0
  74. package/src/components/agent-launcher.stories.tsx +26 -0
  75. package/src/components/agent-launcher.test.tsx +50 -0
  76. package/src/components/agent-launcher.tsx +149 -0
  77. package/src/components/diff-sheet-layout.test.ts +128 -0
  78. package/src/components/diff-sheet-layout.ts +184 -0
  79. package/src/components/plan-sheet-run-style.ts +90 -0
  80. package/src/components/primitives/Button.stories.tsx +32 -0
  81. package/src/components/primitives/Button.tsx +52 -0
  82. package/src/components/primitives/Card.stories.tsx +25 -0
  83. package/src/components/primitives/Card.tsx +60 -0
  84. package/src/components/primitives/Dialog.stories.tsx +24 -0
  85. package/src/components/primitives/Dialog.tsx +66 -0
  86. package/src/components/primitives/StatusBar.stories.tsx +11 -0
  87. package/src/components/primitives/StatusBar.tsx +23 -0
  88. package/src/components/primitives/Tabs.stories.tsx +29 -0
  89. package/src/components/primitives/Tabs.tsx +102 -0
  90. package/src/components/primitives/Toolbar.stories.tsx +17 -0
  91. package/src/components/primitives/Toolbar.tsx +14 -0
  92. package/src/components/primitives/frame.test.ts +12 -0
  93. package/src/components/primitives/frame.ts +14 -0
  94. package/src/components/quick-actions-editor.stories.tsx +54 -0
  95. package/src/components/quick-actions-editor.tsx +138 -0
  96. package/src/components/stories-app.tsx +124 -0
  97. package/src/components/stories.test.tsx +66 -0
  98. package/src/components/story-fixtures.ts +98 -0
  99. package/src/components/story.ts +75 -0
  100. package/src/components/syntax-highlight.ts +102 -0
  101. package/src/components/terminal-pane.test.tsx +40 -0
  102. package/src/components/terminal-pane.ts +193 -0
  103. package/src/components/theme-context.stories.tsx +46 -0
  104. package/src/components/theme-context.tsx +37 -0
  105. package/src/components/truncate-text.ts +7 -0
  106. package/src/config.test.ts +448 -31
  107. package/src/config.ts +339 -57
  108. package/src/diff-hunk-curate.test.ts +315 -0
  109. package/src/diff-hunk-curate.ts +253 -0
  110. package/src/diff-intraline.test.ts +165 -0
  111. package/src/diff-intraline.ts +146 -0
  112. package/src/diff-syntax.test.ts +96 -0
  113. package/src/diff-syntax.ts +176 -0
  114. package/src/editor.test.ts +149 -0
  115. package/src/editor.ts +135 -9
  116. package/src/ghostty-terminal.test.ts +84 -0
  117. package/src/ghostty-terminal.ts +176 -0
  118. package/src/herdr.test.ts +9 -34
  119. package/src/herdr.ts +17 -21
  120. package/src/index.ts +10 -0
  121. package/src/integrations.test.ts +41 -0
  122. package/src/integrations.ts +32 -0
  123. package/src/intent-dispatch.test.ts +499 -0
  124. package/src/intent-dispatch.ts +585 -0
  125. package/src/key-bindings.test.ts +156 -0
  126. package/src/key-bindings.ts +452 -0
  127. package/src/keymap.test.ts +635 -0
  128. package/src/keymap.ts +404 -0
  129. package/src/kitty-image.test.ts +66 -0
  130. package/src/kitty-image.ts +138 -0
  131. package/src/prototype-browser.test.ts +56 -0
  132. package/src/prototype-browser.ts +289 -0
  133. package/src/pty.test.ts +81 -0
  134. package/src/pty.ts +237 -0
  135. package/src/review-panel.test.ts +113 -0
  136. package/src/review-panel.ts +83 -0
  137. package/src/run.ts +16 -5
  138. package/src/serve.test.ts +25 -9
  139. package/src/serve.ts +19 -8
  140. package/src/session-controller.curate.test.ts +260 -0
  141. package/src/session-controller.share.test.ts +320 -0
  142. package/src/session-controller.ts +993 -0
  143. package/src/share.ts +120 -0
  144. package/src/test-support.test.ts +60 -0
  145. package/src/test-support.ts +197 -0
  146. package/src/theme-presets.test.ts +51 -0
  147. package/src/theme-presets.ts +187 -0
  148. package/src/theme.ts +64 -17
  149. package/src/use-settings-dialog.tsx +275 -0
  150. package/src/version.ts +5 -0
  151. package/src/view-diff.test.ts +22 -8
  152. package/src/view-diff.ts +39 -23
  153. package/src/view-plan.regression.test.ts +60 -0
  154. package/src/view-plan.test.ts +406 -0
  155. package/src/view-plan.ts +554 -0
  156. package/src/walk.test.ts +121 -0
  157. package/src/walk.ts +74 -0
  158. package/src/syntax.test.ts +0 -41
  159. package/src/syntax.ts +0 -88
  160. package/src/view.test.ts +0 -157
  161. package/src/view.ts +0 -0
@@ -0,0 +1,993 @@
1
+ /**
2
+ * The review-session controller: every daemon round-trip and mutation
3
+ * verb behind one React-free object. It owns connect/autostart/subscribe,
4
+ * the session/inbox/status/error snapshot, optimistic apply, the mutation
5
+ * verbs (cut/edit/annotate/submit/...), and the post-submit completion
6
+ * lifecycle including the notes-vault export and the herdr return-focus.
7
+ * App subscribes to snapshots and keeps only view state.
8
+ */
9
+
10
+ import { SystemClock, type Clock, type TimerHandle } from "@opentui/core";
11
+ import { DaemonClient, type SessionClient } from "@cueloop/daemon/client";
12
+ import {
13
+ cutBlock,
14
+ detectHerdr,
15
+ makeAnchor,
16
+ newAnnotationId,
17
+ parseBlocks,
18
+ resolveAnchor,
19
+ restoreBlock,
20
+ restoreLine,
21
+ returnPaneFor,
22
+ type Annotation,
23
+ type ReviewSession,
24
+ type VerdictKind,
25
+ } from "@cueloop/schema";
26
+ import { loadBundledExporters, type BundledExporter } from "./integrations";
27
+ import {
28
+ collaboratorAnnotations,
29
+ publishShare,
30
+ pullShare,
31
+ pushShare,
32
+ shareIdFromLine,
33
+ } from "./share";
34
+ import { buildDisplay, nextWorkBlock, type DisplayBlock } from "./view-plan";
35
+ import { diffRowAnchor, diffRows, type DiffRow } from "./view-diff";
36
+ import {
37
+ changeRejectionForRow,
38
+ curateDiff,
39
+ hunkRejectionForRow,
40
+ isRowRejected,
41
+ parseFileDiff,
42
+ rejectsWholeHunk,
43
+ sameRejection,
44
+ type HunkRejection,
45
+ } from "./diff-hunk-curate";
46
+ import type { FileDiffMetadata } from "@pierre/diffs";
47
+ import { firstUnviewedIndex, walkFiles, type WalkFile } from "./walk";
48
+ import { editInEditor } from "./editor";
49
+ import { focusHerdrPane } from "./herdr";
50
+ import {
51
+ persistAutoClose,
52
+ persistReviewState,
53
+ persistReviewWidth,
54
+ type AutoClose,
55
+ type CueloopConfig,
56
+ } from "./config";
57
+ import type { ReviewPanelMode } from "./review-panel";
58
+
59
+ /**
60
+ * Post-submit lifecycle (a review pane should hand you back to the agent,
61
+ * not linger): idle → counting (a visible countdown, the default) → exit.
62
+ * esc dismisses to the resolved view; a remembers the countdown as default.
63
+ */
64
+ export type Completion =
65
+ | { phase: "idle" }
66
+ | { phase: "prompt" }
67
+ | { phase: "counting"; remaining: number }
68
+ | { phase: "dismissed" };
69
+
70
+ /** Seconds the completion overlay counts down before it hands back. */
71
+ export const DEFAULT_AUTO_CLOSE = 5;
72
+
73
+ /** How often an open shared plan re-pulls collaborator notes (ADR 0005 stage 2). */
74
+ export const SHARE_POLL_MS = 4000;
75
+
76
+ /** Shared empty set so "nothing rejected" is a stable identity for renders. */
77
+ const EMPTY_REJECTED_ROWS: Set<number> = new Set();
78
+
79
+ /** Shared empty list so "nothing curated out" is a stable identity for renders. */
80
+ const EMPTY_CURATION_ITEMS: CurationItem[] = [];
81
+
82
+ /** Status shown when a curated-out removal (diff rejection or plan cut) is restored. */
83
+ const REMOVAL_RESTORED_STATUS = "removal restored";
84
+
85
+ export interface ToastState {
86
+ title?: string;
87
+ body: string;
88
+ }
89
+
90
+ /**
91
+ * One removed piece projected for the review rail, unified across both review
92
+ * kinds: a diff hunk/change the owner curated out, or a plan block they cut.
93
+ * `source` tells restore and reveal which path to take; `preview` is the removed
94
+ * content (a few lines) the card renders struck through; `revealIndex` is the
95
+ * diff row (diff) or display block (plan) to scroll to and restore against.
96
+ */
97
+ export interface CurationItem {
98
+ id: string;
99
+ source: "diff" | "plan";
100
+ preview: string[];
101
+ revealIndex: number;
102
+ }
103
+
104
+ /** Stable id for a rejection's rail item: diff:path#hunk#change (or #hunk for a whole hunk). */
105
+ export function curationItemId(rejection: HunkRejection): string {
106
+ return `diff:${rejection.path}#${rejection.hunkIndex}#${rejection.changeIndex ?? "hunk"}`;
107
+ }
108
+
109
+ /** Stable id for a plan cut's rail item, keyed on its fixed base-content line range. */
110
+ function planCutId(base: { lineStart: number; lineEnd: number }): string {
111
+ return `plan:${base.lineStart}-${base.lineEnd}`;
112
+ }
113
+
114
+ export interface ControllerSnapshot {
115
+ session: ReviewSession | null;
116
+ inbox: ReviewSession[] | null;
117
+ status: string;
118
+ toast: ToastState | null;
119
+ error: string | null;
120
+ completion: Completion;
121
+ /**
122
+ * Annotations whose anchor stopped resolving after the last editor
123
+ * hand-off - the reconciliation banner count. 0 = no banner.
124
+ */
125
+ editOrphanCount: number;
126
+ /**
127
+ * The guided walk's cursor (diff sessions): which wizard step is on
128
+ * screen. index === file count is the end card. null = not walking; the
129
+ * viewed set itself rides the session record, so leaving loses nothing.
130
+ */
131
+ walk: { index: number } | null;
132
+ }
133
+
134
+ export interface ReviewControllerOptions {
135
+ home?: string;
136
+ sessionId?: string;
137
+ /** Observer mode: stored for the key reducer's read-only gate. */
138
+ readOnly?: boolean;
139
+ onExit?: (code: number) => void;
140
+ /** Timer source for the auto-close countdown; tests inject a ManualClock. */
141
+ clock?: Clock;
142
+ /**
143
+ * How the controller gets its session client. Defaults to dialing the local
144
+ * daemon; the sharing gateway injects a blob-backed client so the same <App>
145
+ * renders a decrypted share instead.
146
+ */
147
+ openClient?: () => Promise<SessionClient>;
148
+ }
149
+
150
+ export interface ReviewController {
151
+ readonly readOnly: boolean;
152
+ /** Snapshot listeners (stable identity - safe for useSyncExternalStore). */
153
+ subscribe(listener: () => void): () => void;
154
+ getSnapshot(): ControllerSnapshot;
155
+ /** Dial the daemon (autostart), subscribe to events, fetch session or inbox. */
156
+ connect(): void;
157
+ close(): void;
158
+ /** Loaded config parts the controller acts on: auto-close and exporters. */
159
+ applyConfig(config: CueloopConfig): void;
160
+ setStatus(message: string): void;
161
+ showToast(body: string, title?: string): void;
162
+ dismissToast(): void;
163
+ /** Derived projections, cached per session identity. */
164
+ display(): DisplayBlock[];
165
+ rows(): DiffRow[];
166
+ /** The walk's step list, derived from the diff rows. */
167
+ files(): WalkFile[];
168
+ working(): string;
169
+ /** Open a session from the inbox. */
170
+ open(id: string): void;
171
+ /** Delete a session for good (inbox delete); the inbox refreshes on the event. */
172
+ deleteSession(id: string): void;
173
+ /** Record the viewer's own name into the share's participant registry (collaborator self-naming). */
174
+ setSelfName(name: string): void;
175
+ /** Cut the block under the cursor, or restore a cut one. */
176
+ cut(displayIndex: number): void;
177
+ /** Toggle rejection of the whole hunk under the diff cursor (owner curation). */
178
+ toggleRejectHunk(rowIndex: number): void;
179
+ /** Toggle rejection of the single change under the diff cursor (owner curation). */
180
+ toggleRejectChange(rowIndex: number): void;
181
+ /** Rendered row indices dropped by the current reject decisions (for dimming). */
182
+ rejectedRows(): Set<number>;
183
+ /** The curated-out rejections as rail items, in the order they were rejected. */
184
+ curationItems(): CurationItem[];
185
+ /** Undo one curation item by id: drop the rejection and recompute the working copy. */
186
+ restoreCuration(id: string): void;
187
+ /** The $EDITOR hand-off on the working copy. */
188
+ edit(): void;
189
+ /**
190
+ * Anchor and store an annotation; both plan and diff anchor constructions.
191
+ * Returns the minted annotation id so the view can select the new card.
192
+ */
193
+ annotate(
194
+ kind: "comment",
195
+ displayIndex: number,
196
+ start: number,
197
+ end: number,
198
+ body: string,
199
+ ): string | undefined;
200
+ /** Anchor a prototype comment to a DOM element by its selector. */
201
+ annotatePrototype(selector: string, quote: string, body: string): string | undefined;
202
+ /** Rewrite a stored annotation's body in place (the rail-card edit). */
203
+ updateAnnotation(id: string, body: string): void;
204
+ removeAnnotation(id: string): void;
205
+ setWorkingCopy(content: string | undefined): void;
206
+ /** Enter the guided walk at the first unviewed file (diff sessions). */
207
+ walkStart(): void;
208
+ /** Mark the current file viewed (persists with the session) and advance. */
209
+ walkForward(): void;
210
+ walkBack(): void;
211
+ /** Leave the walk; the viewed set stays on the session record. */
212
+ walkLeave(): void;
213
+ /** Resolve the review, run the export, start the completion hand-back. */
214
+ submit(verdict: VerdictKind, summary: string): void;
215
+ /** Publish the current session as a share; the ssh line lands on the clipboard. */
216
+ share(): void;
217
+ /** Pull a shared plan's collaborator notes back and union them in (planner only). */
218
+ pullShared(): Promise<void>;
219
+ /** Poll the share for collaborator notes while it is open; returns a stop handle. */
220
+ startSharePoll(): () => void;
221
+ /** Close the review and, inside herdr, bounce focus back to the agent. */
222
+ finishReview(): void;
223
+ dismissCompletion(): void;
224
+ /** From the completion prompt: persist auto-close and start the countdown. */
225
+ optInAutoClose(): void;
226
+ /**
227
+ * Persist the review-panel layout (client view state) to the user config so
228
+ * the collapse mode and rail width survive a restart. A read-only config dir
229
+ * never blocks the review.
230
+ */
231
+ saveReviewPanel(layout: { mode?: ReviewPanelMode; width?: number }): void;
232
+ }
233
+
234
+ export function createReviewController(options: ReviewControllerOptions): ReviewController {
235
+ return new Controller(options);
236
+ }
237
+
238
+ class Controller implements ReviewController {
239
+ readonly readOnly: boolean;
240
+ private client: SessionClient | null = null;
241
+ private closed = false;
242
+ private snapshot: ControllerSnapshot = {
243
+ session: null,
244
+ inbox: null,
245
+ status: "",
246
+ toast: null,
247
+ error: null,
248
+ completion: { phase: "idle" },
249
+ editOrphanCount: 0,
250
+ walk: null,
251
+ };
252
+ private listeners = new Set<() => void>();
253
+ private autoClose: AutoClose = "off";
254
+ private editor: string | undefined;
255
+ private exporters: BundledExporter[] = [];
256
+ private readonly clock: Clock;
257
+ private countdown: TimerHandle | undefined;
258
+ private sharePoll: TimerHandle | undefined;
259
+ private shareRun: object | null = null;
260
+ /** Projections keyed by session identity so renders reuse one computation. */
261
+ private derivedFor: ReviewSession | null = null;
262
+ private derived: {
263
+ display: DisplayBlock[];
264
+ rows: DiffRow[];
265
+ files: WalkFile[];
266
+ /** Per-path parsed diff models, for hunk curation; empty when files absent. */
267
+ models: Map<string, FileDiffMetadata>;
268
+ } = {
269
+ display: [],
270
+ rows: [],
271
+ files: [],
272
+ models: new Map(),
273
+ };
274
+ /** The owner's per-hunk/change reject decisions for the open diff session. */
275
+ private rejections: HunkRejection[] = [];
276
+
277
+ constructor(private readonly options: ReviewControllerOptions) {
278
+ this.readOnly = options.readOnly ?? false;
279
+ this.clock = options.clock ?? new SystemClock();
280
+ }
281
+
282
+ subscribe = (listener: () => void): (() => void) => {
283
+ this.listeners.add(listener);
284
+
285
+ return () => this.listeners.delete(listener);
286
+ };
287
+
288
+ getSnapshot = (): ControllerSnapshot => this.snapshot;
289
+
290
+ private update(patch: Partial<ControllerSnapshot>): void {
291
+ this.snapshot = { ...this.snapshot, ...patch };
292
+ for (const listener of this.listeners) listener();
293
+ }
294
+
295
+ connect(): void {
296
+ void (async () => {
297
+ try {
298
+ const openClient =
299
+ this.options.openClient ??
300
+ (() => DaemonClient.connect({ home: this.options.home, autostart: true }));
301
+ const client = await openClient();
302
+
303
+ if (this.closed) return void client.close();
304
+ this.client = client;
305
+ client.onEvent((event) => {
306
+ // another controller/observer changed state: re-fetch
307
+ const session = this.snapshot.session;
308
+
309
+ if (session && event.sessionId === session.id) void this.refreshSession(session.id);
310
+ if (!this.options.sessionId) void this.refreshInbox();
311
+ });
312
+ await client.subscribe();
313
+ if (this.options.sessionId) {
314
+ this.update({ session: await client.sessionGet(this.options.sessionId) });
315
+ } else {
316
+ this.update({ inbox: await client.sessionList({ status: "pending" }) });
317
+ }
318
+ } catch (err) {
319
+ this.update({ error: err instanceof Error ? err.message : String(err) });
320
+ }
321
+ })();
322
+ }
323
+
324
+ close(): void {
325
+ this.closed = true;
326
+ this.clearCountdown();
327
+ this.stopSharePoll();
328
+ this.client?.close();
329
+ }
330
+
331
+ private clearCountdown(): void {
332
+ if (this.countdown !== undefined) this.clock.clearTimeout(this.countdown);
333
+ this.countdown = undefined;
334
+ }
335
+
336
+ applyConfig(config: CueloopConfig): void {
337
+ this.autoClose = config.ui.autoClose;
338
+ this.editor = config.ui.editor;
339
+ void loadBundledExporters(config.integrations).then((exporters) => {
340
+ this.exporters = exporters;
341
+ });
342
+ }
343
+
344
+ setStatus(message: string): void {
345
+ this.update({ status: message });
346
+ }
347
+
348
+ showToast(body: string, title?: string): void {
349
+ this.update({ toast: { body, title } });
350
+ }
351
+
352
+ dismissToast(): void {
353
+ if (this.snapshot.toast) this.update({ toast: null });
354
+ }
355
+
356
+ // ── derived projections ─────────────────────
357
+ private ensureDerived(): void {
358
+ const session = this.snapshot.session;
359
+
360
+ if (this.derivedFor === session) return;
361
+ this.derivedFor = session;
362
+ const rows =
363
+ session && session.artifact.type === "diff" ? diffRows(session.artifact.content) : [];
364
+ const models = new Map<string, FileDiffMetadata>();
365
+
366
+ for (const file of session?.artifact.files ?? []) models.set(file.path, parseFileDiff(file));
367
+ this.derived = {
368
+ display: session ? buildDisplay(session.artifact.content, session.workingCopy) : [],
369
+ rows,
370
+ files: walkFiles(rows),
371
+ models,
372
+ };
373
+ }
374
+
375
+ display(): DisplayBlock[] {
376
+ this.ensureDerived();
377
+
378
+ return this.derived.display;
379
+ }
380
+
381
+ rows(): DiffRow[] {
382
+ this.ensureDerived();
383
+
384
+ return this.derived.rows;
385
+ }
386
+
387
+ files(): WalkFile[] {
388
+ this.ensureDerived();
389
+
390
+ return this.derived.files;
391
+ }
392
+
393
+ working(): string {
394
+ const session = this.snapshot.session;
395
+
396
+ return session ? (session.workingCopy ?? session.artifact.content) : "";
397
+ }
398
+
399
+ // Refreshes race the connection teardown: an event can arrive while close()
400
+ // is rejecting in-flight requests, and a fire-and-forget refresh must never
401
+ // surface that as an unhandled rejection.
402
+ private async refreshSession(id: string): Promise<void> {
403
+ try {
404
+ if (this.client) this.update({ session: await this.client.sessionGet(id) });
405
+ } catch (error) {
406
+ if (!this.closed) this.setStatus(error instanceof Error ? error.message : String(error));
407
+ }
408
+ }
409
+
410
+ private async refreshInbox(): Promise<void> {
411
+ try {
412
+ if (this.client) this.update({ inbox: await this.client.sessionList({ status: "pending" }) });
413
+ } catch (error) {
414
+ if (!this.closed) this.setStatus(error instanceof Error ? error.message : String(error));
415
+ }
416
+ }
417
+
418
+ /** Optimistic apply: the daemon response is the next session snapshot. */
419
+ private apply(mutation: Promise<ReviewSession>): void {
420
+ mutation
421
+ .then((session) => this.update({ session }))
422
+ .catch((error: unknown) =>
423
+ this.setStatus(String(error instanceof Error ? error.message : error)),
424
+ );
425
+ }
426
+
427
+ // ── verbs ───────────────────────────────────
428
+ open(id: string): void {
429
+ this.locallyViewed.clear();
430
+ this.rejections = [];
431
+ const cached = this.snapshot.inbox?.find((candidate) => candidate.id === id);
432
+
433
+ if (cached) this.update({ session: cached });
434
+ else void this.refreshSession(id);
435
+ }
436
+
437
+ deleteSession(id: string): void {
438
+ this.client
439
+ ?.sessionDelete(id)
440
+ .then(() => this.setStatus("plan deleted"))
441
+ .catch((error: unknown) =>
442
+ this.setStatus(`delete failed: ${error instanceof Error ? error.message : String(error)}`),
443
+ );
444
+ }
445
+
446
+ setSelfName(name: string): void {
447
+ const session = this.snapshot.session;
448
+
449
+ if (!session) return;
450
+ this.apply(this.client!.sessionSetSelfName(session.id, name));
451
+ }
452
+
453
+ cut(displayIndex: number): void {
454
+ const session = this.snapshot.session;
455
+
456
+ if (!session || session.status === "resolved") return;
457
+ const block = this.display()[displayIndex];
458
+
459
+ if (!block) return;
460
+ const working = this.working();
461
+
462
+ if (block.type === "del") {
463
+ this.restoreDelBlock(block, displayIndex);
464
+ } else if (block.work) {
465
+ this.setWorkingCopy(cutBlock(working, block.work));
466
+ this.setStatus("block cut - it serializes into the diff");
467
+ }
468
+ }
469
+
470
+ /** Re-insert a cut plan block at the next surviving block's line (Cut toggle + rail undo). */
471
+ private restoreDelBlock(block: DisplayBlock, displayIndex: number): void {
472
+ const session = this.snapshot.session;
473
+
474
+ if (!session || !block.base) return;
475
+ const working = this.working();
476
+ const line = restoreLine(
477
+ nextWorkBlock(this.display(), displayIndex),
478
+ working.split("\n").length,
479
+ );
480
+ // restoreBlock returns undefined when the block structure round-trips to the
481
+ // submitted revision - the working copy is back to pristine and is dropped
482
+ const restored = restoreBlock(session.artifact.content, working, block.base, line);
483
+
484
+ this.setWorkingCopy(restored);
485
+ this.setStatus(REMOVAL_RESTORED_STATUS);
486
+ }
487
+
488
+ // ── diff hunk curation ──────────────────────
489
+ /** The parsed model and row for a curation action, or null with a status set. */
490
+ private curationRow(rowIndex: number): { row: DiffRow; model: FileDiffMetadata } | null {
491
+ const session = this.snapshot.session;
492
+
493
+ if (!session || session.status === "resolved") return null;
494
+ if (!session.artifact.files) {
495
+ this.setStatus("hunk curation needs full file contents (PR diffs cannot be curated)");
496
+
497
+ return null;
498
+ }
499
+ const row = this.rows()[rowIndex];
500
+
501
+ if (!row || row.kind === "file" || row.kind === "hunk") {
502
+ this.setStatus("move to a code line to curate");
503
+
504
+ return null;
505
+ }
506
+ const model = this.derived.models.get(row.file);
507
+
508
+ if (!model) return null;
509
+
510
+ return { row, model };
511
+ }
512
+
513
+ toggleRejectHunk(rowIndex: number): void {
514
+ const located = this.curationRow(rowIndex);
515
+
516
+ if (!located) return;
517
+ const target = hunkRejectionForRow(located.row.file, located.model, located.row);
518
+
519
+ if (!target) return this.setStatus("no hunk under the cursor");
520
+ const wholeHunk = (rejection: HunkRejection): boolean => rejectsWholeHunk(rejection, target);
521
+
522
+ if (this.rejections.some(wholeHunk)) {
523
+ this.rejections = this.rejections.filter((rejection) => !wholeHunk(rejection));
524
+ this.setStatus("hunk restored");
525
+ } else {
526
+ // a whole-hunk reject supersedes any change-level rejects inside it
527
+ this.rejections = this.rejections.filter(
528
+ (rejection) =>
529
+ !(rejection.path === target.path && rejection.hunkIndex === target.hunkIndex),
530
+ );
531
+ this.rejections.push(target);
532
+ this.setStatus("hunk rejected - dropped from the working copy");
533
+ }
534
+ this.recomputeCuration();
535
+ }
536
+
537
+ toggleRejectChange(rowIndex: number): void {
538
+ const located = this.curationRow(rowIndex);
539
+
540
+ if (!located) return;
541
+ if (located.row.kind !== "add" && located.row.kind !== "del")
542
+ return this.setStatus("move to a changed line to reject a change");
543
+ const target = changeRejectionForRow(located.row.file, located.model, located.row);
544
+
545
+ if (!target) return this.setStatus("no change under the cursor");
546
+ const wholeCovers = this.rejections.some((rejection) => rejectsWholeHunk(rejection, target));
547
+
548
+ if (wholeCovers) return this.setStatus("the whole hunk is rejected - restore it first");
549
+ if (this.rejections.some((rejection) => sameRejection(rejection, target))) {
550
+ this.rejections = this.rejections.filter((rejection) => !sameRejection(rejection, target));
551
+ this.setStatus("change restored");
552
+ } else {
553
+ this.rejections.push(target);
554
+ this.setStatus("change rejected - dropped from the working copy");
555
+ }
556
+ this.recomputeCuration();
557
+ }
558
+
559
+ /** Recompute the curated patch and push it as the working copy (or clear it). */
560
+ private recomputeCuration(): void {
561
+ const files = this.snapshot.session?.artifact.files;
562
+
563
+ if (!files) return;
564
+ // no decisions left = the working copy reverts to the full submitted diff
565
+ this.setWorkingCopy(this.rejections.length ? curateDiff(files, this.rejections) : undefined);
566
+ // dimming reads `rejections` directly; a bare update forces the re-read
567
+ this.update({});
568
+ }
569
+
570
+ rejectedRows(): Set<number> {
571
+ this.ensureDerived();
572
+ if (!this.rejections.length) return EMPTY_REJECTED_ROWS;
573
+ const rejected = new Set<number>();
574
+
575
+ this.derived.rows.forEach((row, index) => {
576
+ const model = this.derived.models.get(row.file);
577
+
578
+ if (model && isRowRejected(row.file, model, row, this.rejections)) rejected.add(index);
579
+ });
580
+
581
+ return rejected;
582
+ }
583
+
584
+ curationItems(): CurationItem[] {
585
+ this.ensureDerived();
586
+ const session = this.snapshot.session;
587
+
588
+ if (!session) return EMPTY_CURATION_ITEMS;
589
+
590
+ return session.artifact.type === "diff" ? this.diffCurationItems() : this.planCurationItems();
591
+ }
592
+
593
+ restoreCuration(id: string): void {
594
+ // diff rejections drop from the reject list; a plan cut re-inserts its block
595
+ if (id.startsWith("diff:")) {
596
+ const kept = this.rejections.filter((rejection) => curationItemId(rejection) !== id);
597
+
598
+ if (kept.length === this.rejections.length) return;
599
+ this.rejections = kept;
600
+ this.setStatus(REMOVAL_RESTORED_STATUS);
601
+ this.recomputeCuration();
602
+
603
+ return;
604
+ }
605
+ const display = this.display();
606
+ const displayIndex = display.findIndex(
607
+ (block) => block.type === "del" && block.base && planCutId(block.base) === id,
608
+ );
609
+
610
+ if (displayIndex !== -1) this.restoreDelBlock(display[displayIndex]!, displayIndex);
611
+ }
612
+
613
+ /** The curated-out diff rejections as removal cards (newest decisions last). */
614
+ private diffCurationItems(): CurationItem[] {
615
+ if (!this.rejections.length) return EMPTY_CURATION_ITEMS;
616
+ const items: CurationItem[] = [];
617
+
618
+ for (const rejection of this.rejections) {
619
+ const rows = this.rowsForRejection(rejection);
620
+ const firstRow = rows[0];
621
+
622
+ items.push({
623
+ id: curationItemId(rejection),
624
+ source: "diff",
625
+ preview: rows.map(
626
+ (row) => `${row.kind === "add" ? "+" : "-"} ${row.text.replace(/\n$/, "")}`,
627
+ ),
628
+ revealIndex: firstRow ? this.derived.rows.indexOf(firstRow) : 0,
629
+ });
630
+ }
631
+
632
+ return items;
633
+ }
634
+
635
+ /** The cut plan blocks as removal cards, in document order. */
636
+ private planCurationItems(): CurationItem[] {
637
+ const items: CurationItem[] = [];
638
+
639
+ this.derived.display.forEach((block, displayIndex) => {
640
+ if (block.type !== "del" || !block.base) return;
641
+ items.push({
642
+ id: planCutId(block.base),
643
+ source: "plan",
644
+ preview: block.base.text.split("\n"),
645
+ revealIndex: displayIndex,
646
+ });
647
+ });
648
+
649
+ return items.length ? items : EMPTY_CURATION_ITEMS;
650
+ }
651
+
652
+ /** The change/deletion rows a rejection covers, for its preview and reveal row. */
653
+ private rowsForRejection(rejection: HunkRejection): DiffRow[] {
654
+ const model = this.derived.models.get(rejection.path);
655
+
656
+ if (!model) return [];
657
+ const rows: DiffRow[] = [];
658
+
659
+ for (const row of this.derived.rows) {
660
+ if (row.file !== rejection.path || (row.kind !== "add" && row.kind !== "del")) continue;
661
+ if (rejection.changeIndex === undefined) {
662
+ const target = hunkRejectionForRow(rejection.path, model, row);
663
+
664
+ if (target && target.hunkIndex === rejection.hunkIndex) rows.push(row);
665
+ } else {
666
+ const target = changeRejectionForRow(rejection.path, model, row);
667
+
668
+ if (target && sameRejection(target, rejection)) rows.push(row);
669
+ }
670
+ }
671
+
672
+ return rows;
673
+ }
674
+
675
+ edit(): void {
676
+ const session = this.snapshot.session;
677
+
678
+ if (!session || session.status === "resolved") return;
679
+ try {
680
+ const result = editInEditor(this.working(), "plan.md", { editor: this.editor });
681
+
682
+ if (result.changed) {
683
+ this.setWorkingCopy(result.content);
684
+ this.reconcileAnnotations(session, result.content);
685
+ this.setStatus("edits tracked - one diff");
686
+ } else this.setStatus("no changes");
687
+ } catch (err) {
688
+ this.setStatus(err instanceof Error ? err.message : String(err));
689
+ }
690
+ }
691
+
692
+ /**
693
+ * Edit-exit reconciliation: re-resolve every annotation against the edited
694
+ * working copy with the quote-primary cascade. Annotations that stop
695
+ * resolving stay stored (the feedback serializer flags orphaned anchors);
696
+ * the count feeds the one-line banner above the sheet.
697
+ */
698
+ private reconcileAnnotations(session: ReviewSession, editedContent: string): void {
699
+ const editedBlocks = parseBlocks(editedContent);
700
+ const orphanCount = session.annotations.filter(
701
+ (annotation) => resolveAnchor(annotation.anchor, editedBlocks) === null,
702
+ ).length;
703
+
704
+ this.update({ editOrphanCount: orphanCount });
705
+ }
706
+
707
+ annotate(
708
+ kind: "comment",
709
+ displayIndex: number,
710
+ start: number,
711
+ end: number,
712
+ body: string,
713
+ ): string | undefined {
714
+ const session = this.snapshot.session;
715
+
716
+ if (!session) return undefined;
717
+ let anchor;
718
+
719
+ if (session.artifact.type === "diff") {
720
+ anchor = { ...diffRowAnchor(this.rows(), displayIndex), blockIndex: displayIndex };
721
+ } else {
722
+ const display = this.display();
723
+ const workBlocks = display.filter((entry) => entry.work).map((entry) => entry.work!);
724
+ const workBlockIndex =
725
+ display.slice(0, displayIndex + 1).filter((entry) => entry.work).length - 1;
726
+
727
+ anchor = makeAnchor(workBlocks, workBlockIndex, start, end);
728
+ }
729
+ const wire = { id: newAnnotationId(), kind, anchor, body };
730
+ const persisted = this.client!.sessionAnnotate(session.id, wire);
731
+
732
+ this.apply(persisted);
733
+ this.mirrorAnnotation(persisted, wire);
734
+ this.setStatus("comment added");
735
+
736
+ return wire.id;
737
+ }
738
+
739
+ annotatePrototype(selector: string, quote: string, body: string): string | undefined {
740
+ const session = this.snapshot.session;
741
+
742
+ if (!session) return undefined;
743
+ const anchor = { quote, prefix: "", suffix: "", selector };
744
+ const wire = { id: newAnnotationId(), kind: "comment", anchor, body };
745
+ const persisted = this.client!.sessionAnnotate(session.id, wire);
746
+
747
+ this.apply(persisted);
748
+ this.mirrorAnnotation(persisted, wire);
749
+ this.setStatus("comment added");
750
+
751
+ return wire.id;
752
+ }
753
+
754
+ updateAnnotation(id: string, body: string): void {
755
+ const session = this.snapshot.session;
756
+
757
+ if (!session) return;
758
+ const existing = session.annotations.find((annotation) => annotation.id === id);
759
+
760
+ if (!existing) return;
761
+ // the daemon's annotate verb upserts by id: same id + anchor, new body
762
+ const wire = { id: existing.id, kind: existing.kind, anchor: existing.anchor, body };
763
+ const persisted = this.client!.sessionAnnotate(session.id, wire);
764
+
765
+ this.apply(persisted);
766
+ this.mirrorAnnotation(persisted, wire);
767
+ this.setStatus("annotation updated");
768
+ }
769
+
770
+ // push only after the local write lands, so a rejected write never leaks to the share
771
+ private mirrorAnnotation(
772
+ persisted: Promise<ReviewSession>,
773
+ annotation: Omit<Annotation, "createdAt">,
774
+ ): void {
775
+ const shareId = this.snapshot.session?.shareId;
776
+
777
+ if (!shareId) return;
778
+ void persisted.then(() => pushShare(shareId, [annotation])).catch(() => {});
779
+ }
780
+
781
+ removeAnnotation(id: string): void {
782
+ const session = this.snapshot.session;
783
+
784
+ if (!session) return;
785
+ this.apply(this.client!.sessionRemoveAnnotation(session.id, id));
786
+ this.setStatus("annotation deleted");
787
+ }
788
+
789
+ setWorkingCopy(content: string | undefined): void {
790
+ const session = this.snapshot.session;
791
+
792
+ if (!session) return;
793
+ this.apply(this.client!.sessionSetWorkingCopy(session.id, content));
794
+ }
795
+
796
+ // ── the guided walk ─────────────────────────
797
+ // Marks sent but possibly not yet reflected in the session snapshot; the
798
+ // union keeps the walk title truthful and rapid advances from losing marks.
799
+ private locallyViewed = new Set<string>();
800
+
801
+ private viewedSet(): Set<string> {
802
+ return new Set([...(this.snapshot.session?.viewedPaths ?? []), ...this.locallyViewed]);
803
+ }
804
+
805
+ walkStart(): void {
806
+ const session = this.snapshot.session;
807
+
808
+ if (!session || session.artifact.type !== "diff") return;
809
+ const files = this.files();
810
+
811
+ if (files.length === 0) return this.setStatus("nothing to walk - the diff is empty");
812
+ // resume at the first unviewed file; a finished walk reopens on the end card
813
+ this.update({ walk: { index: firstUnviewedIndex(files, this.viewedSet()) } });
814
+ }
815
+
816
+ walkForward(): void {
817
+ const walk = this.snapshot.walk;
818
+ const session = this.snapshot.session;
819
+
820
+ if (!walk || !session) return;
821
+ const files = this.files();
822
+ const current = files[walk.index];
823
+
824
+ if (!current) return; // already on the end card
825
+ // advancing IS the viewed mark: the step is complete once you move past
826
+ // it; the daemon verb merges, so only the new path travels
827
+ if (!this.viewedSet().has(current.path)) {
828
+ this.locallyViewed.add(current.path);
829
+ this.apply(this.client!.sessionSetViewed(session.id, [current.path]));
830
+ }
831
+ this.update({ walk: { index: walk.index + 1 } });
832
+ }
833
+
834
+ walkBack(): void {
835
+ const walk = this.snapshot.walk;
836
+
837
+ if (!walk) return;
838
+ this.update({ walk: { index: Math.max(0, walk.index - 1) } });
839
+ }
840
+
841
+ walkLeave(): void {
842
+ if (this.snapshot.walk) this.update({ walk: null });
843
+ }
844
+
845
+ submit(verdict: VerdictKind, summary: string): void {
846
+ const session = this.snapshot.session;
847
+
848
+ if (!session) return;
849
+ this.walkLeave();
850
+ this.client!.sessionResolve(session.id, verdict, summary)
851
+ .then((resolved) => {
852
+ // The completion overlay heading already states the verdict, so the
853
+ // status line stays empty here - only export/error messages fill it.
854
+ this.update({ session: resolved, status: "" });
855
+ // notes-vault export: guarded by each exporter's policy (default manual = no-op)
856
+ for (const exporter of this.exporters) {
857
+ if (!exporter.runsOn(verdict)) continue;
858
+ void exporter.run(resolved).then((exportResult) => {
859
+ this.setStatus(
860
+ exportResult.success && exportResult.path
861
+ ? `exported to ${exportResult.path}`
862
+ : `export failed: ${exportResult.error ?? "unknown"}`,
863
+ );
864
+ });
865
+ }
866
+ // Hand the reviewer back to the agent. The default is a visible
867
+ // countdown from DEFAULT_AUTO_CLOSE that closes on its own; esc stays,
868
+ // a remembers the choice. A configured delay overrides; 0 closes now.
869
+ const delay = this.autoClose;
870
+
871
+ if (delay === 0) this.finishReview();
872
+ else if (typeof delay === "number") this.startCounting(delay);
873
+ else this.startCounting(DEFAULT_AUTO_CLOSE);
874
+ })
875
+ .catch((error: unknown) =>
876
+ this.setStatus(String(error instanceof Error ? error.message : error)),
877
+ );
878
+ }
879
+
880
+ share(): void {
881
+ const session = this.snapshot.session;
882
+
883
+ if (!session) return;
884
+ this.setStatus("sharing…");
885
+ publishShare(session)
886
+ .then(async ({ line, copied }) => {
887
+ // Stamp the id back so a later pull knows which share to collect from.
888
+ const shareId = shareIdFromLine(line);
889
+
890
+ if (shareId && this.client) await this.client.sessionSetShareId(session.id, shareId);
891
+ this.setStatus("");
892
+ this.showToast(line, copied ? "share link copied" : "share link");
893
+ })
894
+ .catch((error: unknown) =>
895
+ this.setStatus(`share failed: ${error instanceof Error ? error.message : String(error)}`),
896
+ );
897
+ }
898
+
899
+ /**
900
+ * Pull collaborator notes for a shared plan and union them in, awaiting the
901
+ * merge so a poll never overlaps rounds. The daemon's merge emits
902
+ * session.updated, so the re-render happens through the normal event path.
903
+ * Best-effort: a failed refresh is silent and the next tick retries.
904
+ */
905
+ pullShared(): Promise<void> {
906
+ const session = this.snapshot.session;
907
+
908
+ if (!session?.shareId || !this.client) return Promise.resolve();
909
+ const client = this.client;
910
+
911
+ return pullShare(session.shareId)
912
+ .then((remote) =>
913
+ client.sessionMergeShared(session.id, {
914
+ annotations: collaboratorAnnotations(remote),
915
+ participants: remote.participants,
916
+ }),
917
+ )
918
+ .then(() => {})
919
+ .catch(() => {});
920
+ }
921
+
922
+ /**
923
+ * Poll the share for collaborator notes while it is open: pull now, then again
924
+ * every few seconds, each round waiting for the last so slow pulls never stack.
925
+ * Returns a stop handle the caller runs on leave.
926
+ */
927
+ startSharePoll(): () => void {
928
+ this.stopSharePoll();
929
+ // per-run token so a stale run's in-flight pull never re-arms the poll
930
+ const run = {};
931
+
932
+ this.shareRun = run;
933
+ const tick = (): void => {
934
+ void this.pullShared().finally(() => {
935
+ if (this.shareRun === run && !this.closed)
936
+ this.sharePoll = this.clock.setTimeout(tick, SHARE_POLL_MS);
937
+ });
938
+ };
939
+
940
+ tick();
941
+
942
+ return () => {
943
+ if (this.shareRun === run) this.stopSharePoll();
944
+ };
945
+ }
946
+
947
+ private stopSharePoll(): void {
948
+ this.shareRun = null;
949
+ if (this.sharePoll !== undefined) this.clock.clearTimeout(this.sharePoll);
950
+ this.sharePoll = undefined;
951
+ }
952
+
953
+ // ── completion hand-back ────────────────────
954
+ private startCounting(remaining: number): void {
955
+ if (remaining <= 0) return this.finishReview();
956
+ this.update({ completion: { phase: "counting", remaining } });
957
+ this.countdown = this.clock.setTimeout(() => this.startCounting(remaining - 1), 1000);
958
+ }
959
+
960
+ finishReview(): void {
961
+ this.clearCountdown();
962
+ const herdr = detectHerdr();
963
+ const pane = returnPaneFor(this.snapshot.session?.artifact.meta.herdrPane);
964
+
965
+ if (herdr && pane) focusHerdrPane(herdr.binPath, pane);
966
+ this.options.onExit?.(0);
967
+ }
968
+
969
+ dismissCompletion(): void {
970
+ this.clearCountdown();
971
+ this.update({ completion: { phase: "dismissed" } });
972
+ }
973
+
974
+ optInAutoClose(): void {
975
+ // Remember the default countdown for future submits, persisted to the user
976
+ // config. The countdown is already running; this only makes it the default.
977
+ try {
978
+ persistAutoClose(DEFAULT_AUTO_CLOSE);
979
+ } catch {
980
+ // a read-only config dir must not block closing the review
981
+ }
982
+ this.autoClose = DEFAULT_AUTO_CLOSE;
983
+ }
984
+
985
+ saveReviewPanel(layout: { mode?: ReviewPanelMode; width?: number }): void {
986
+ try {
987
+ if (layout.mode !== undefined) persistReviewState(layout.mode);
988
+ if (layout.width !== undefined) persistReviewWidth(layout.width);
989
+ } catch {
990
+ // a read-only config dir must never block collapsing or resizing the rail
991
+ }
992
+ }
993
+ }