@cueloop/client 0.1.0-alpha.7 → 0.1.0-alpha.8

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.
@@ -0,0 +1,345 @@
1
+ /**
2
+ * The review-session controller (#70): 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 { DaemonClient } from "@cueloop/daemon/client";
11
+ import {
12
+ cutBlock,
13
+ makeAnchor,
14
+ newAnnotationId,
15
+ restoreBlock,
16
+ restoreLine,
17
+ type ReviewSession,
18
+ type VerdictKind,
19
+ } from "@cueloop/schema";
20
+ import { Registry, type Exporter } from "@cueloop/extension-api";
21
+ import { createObsidianExtension, shouldExport, type ObsidianConfig } from "@cueloop/integration-obsidian";
22
+ import { buildDisplay, nextWorkBlock, type DisplayBlock } from "./view";
23
+ import { diffRowAnchor, diffRows, type DiffRow } from "./view-diff";
24
+ import { editInEditor } from "./editor";
25
+ import { focusHerdrPane, returnPaneFor } from "./herdr";
26
+ import { persistAutoClose, type AutoClose, type CueloopConfig } from "./config";
27
+
28
+ /**
29
+ * Post-submit lifecycle (a review pane should hand you back to the agent,
30
+ * not linger): idle → prompt (auto-close off: offer the choice) or
31
+ * counting (configured delay) → exit. esc dismisses to the resolved view.
32
+ */
33
+ export type Completion =
34
+ | { phase: "idle" }
35
+ | { phase: "prompt" }
36
+ | { phase: "counting"; remaining: number }
37
+ | { phase: "dismissed" };
38
+
39
+ export interface ControllerSnapshot {
40
+ session: ReviewSession | null;
41
+ inbox: ReviewSession[] | null;
42
+ status: string;
43
+ error: string | null;
44
+ completion: Completion;
45
+ }
46
+
47
+ export interface ReviewControllerOptions {
48
+ home?: string;
49
+ sessionId?: string;
50
+ /** Observer mode: stored for the key reducer's read-only gate. */
51
+ readOnly?: boolean;
52
+ onExit?: (code: number) => void;
53
+ }
54
+
55
+ export interface ReviewController {
56
+ readonly readOnly: boolean;
57
+ /** Snapshot listeners (stable identity - safe for useSyncExternalStore). */
58
+ subscribe(listener: () => void): () => void;
59
+ getSnapshot(): ControllerSnapshot;
60
+ /** Dial the daemon (autostart), subscribe to events, fetch session or inbox. */
61
+ connect(): void;
62
+ close(): void;
63
+ /** Loaded config parts the controller acts on: auto-close and exporters. */
64
+ applyConfig(cfg: CueloopConfig): void;
65
+ setStatus(msg: string): void;
66
+ /** Derived projections, cached per session identity. */
67
+ display(): DisplayBlock[];
68
+ rows(): DiffRow[];
69
+ working(): string;
70
+ /** Open a session from the inbox. */
71
+ open(id: string): void;
72
+ /** Cut the block under the cursor, or restore a cut one. */
73
+ cut(dispIdx: number): void;
74
+ /** The $EDITOR hand-off on the working copy. */
75
+ edit(): void;
76
+ /** Anchor and store an annotation; both plan and diff anchor constructions. */
77
+ annotate(kind: "comment" | "suggestion", dispIdx: number, start: number, end: number, body: string): void;
78
+ removeAnnotation(id: string): void;
79
+ setWorkingCopy(content: string | undefined): void;
80
+ /** Resolve the review, run the export, start the completion hand-back. */
81
+ submit(verdict: VerdictKind, summary: string): void;
82
+ /** Close the review and, inside herdr, bounce focus back to the agent. */
83
+ finishReview(): void;
84
+ dismissCompletion(): void;
85
+ /** From the completion prompt: persist auto-close and start the countdown. */
86
+ optInAutoClose(): void;
87
+ }
88
+
89
+ export function createReviewController(opts: ReviewControllerOptions): ReviewController {
90
+ return new Controller(opts);
91
+ }
92
+
93
+ class Controller implements ReviewController {
94
+ readonly readOnly: boolean;
95
+ private client: DaemonClient | null = null;
96
+ private closed = false;
97
+ private snap: ControllerSnapshot = {
98
+ session: null,
99
+ inbox: null,
100
+ status: "",
101
+ error: null,
102
+ completion: { phase: "idle" },
103
+ };
104
+ private listeners = new Set<() => void>();
105
+ private autoClose: AutoClose = "off";
106
+ private obsidian: ObsidianConfig | null = null;
107
+ private exporters = new Map<string, Exporter>();
108
+ private countdown: ReturnType<typeof setTimeout> | undefined;
109
+ /** Projections keyed by session identity so renders reuse one computation. */
110
+ private derivedFor: ReviewSession | null = null;
111
+ private derived: { display: DisplayBlock[]; rows: DiffRow[] } = { display: [], rows: [] };
112
+
113
+ constructor(private readonly opts: ReviewControllerOptions) {
114
+ this.readOnly = opts.readOnly ?? false;
115
+ }
116
+
117
+ subscribe = (listener: () => void): (() => void) => {
118
+ this.listeners.add(listener);
119
+ return () => this.listeners.delete(listener);
120
+ };
121
+
122
+ getSnapshot = (): ControllerSnapshot => this.snap;
123
+
124
+ private update(patch: Partial<ControllerSnapshot>): void {
125
+ this.snap = { ...this.snap, ...patch };
126
+ for (const l of this.listeners) l();
127
+ }
128
+
129
+ connect(): void {
130
+ void (async () => {
131
+ try {
132
+ const client = await DaemonClient.connect({ home: this.opts.home, autostart: true });
133
+ if (this.closed) return void client.close();
134
+ this.client = client;
135
+ client.onEvent((e) => {
136
+ // another controller/observer changed state: re-fetch
137
+ const s = this.snap.session;
138
+ if (s && e.sessionId === s.id) void this.refreshSession(s.id);
139
+ if (!this.opts.sessionId) void this.refreshInbox();
140
+ });
141
+ await client.subscribe();
142
+ if (this.opts.sessionId) {
143
+ this.update({ session: await client.sessionGet(this.opts.sessionId) });
144
+ } else {
145
+ this.update({ inbox: await client.sessionList({ status: "pending" }) });
146
+ }
147
+ } catch (err) {
148
+ this.update({ error: err instanceof Error ? err.message : String(err) });
149
+ }
150
+ })();
151
+ }
152
+
153
+ close(): void {
154
+ this.closed = true;
155
+ clearTimeout(this.countdown);
156
+ this.client?.close();
157
+ }
158
+
159
+ applyConfig(cfg: CueloopConfig): void {
160
+ this.autoClose = cfg.ui.autoClose;
161
+ this.obsidian = cfg.integrations.obsidian;
162
+ // bundled integrations register through the public extension API
163
+ const registry = new Registry();
164
+ void registry.load("obsidian", createObsidianExtension(cfg.integrations.obsidian)).then((rec) => {
165
+ this.exporters = rec.exporters;
166
+ });
167
+ }
168
+
169
+ setStatus(msg: string): void {
170
+ this.update({ status: msg });
171
+ }
172
+
173
+ // ── derived projections ─────────────────────
174
+ private ensureDerived(): void {
175
+ const s = this.snap.session;
176
+ if (this.derivedFor === s) return;
177
+ this.derivedFor = s;
178
+ this.derived = {
179
+ display: s ? buildDisplay(s.artifact.content, s.workingCopy) : [],
180
+ rows: s && s.artifact.type === "diff" ? diffRows(s.artifact.content) : [],
181
+ };
182
+ }
183
+
184
+ display(): DisplayBlock[] {
185
+ this.ensureDerived();
186
+ return this.derived.display;
187
+ }
188
+
189
+ rows(): DiffRow[] {
190
+ this.ensureDerived();
191
+ return this.derived.rows;
192
+ }
193
+
194
+ working(): string {
195
+ const s = this.snap.session;
196
+ return s ? (s.workingCopy ?? s.artifact.content) : "";
197
+ }
198
+
199
+ private async refreshSession(id: string): Promise<void> {
200
+ if (this.client) this.update({ session: await this.client.sessionGet(id) });
201
+ }
202
+
203
+ private async refreshInbox(): Promise<void> {
204
+ if (this.client) this.update({ inbox: await this.client.sessionList({ status: "pending" }) });
205
+ }
206
+
207
+ /** Optimistic apply: the daemon response is the next session snapshot. */
208
+ private apply(p: Promise<ReviewSession>): void {
209
+ p.then((session) => this.update({ session })).catch((e: unknown) =>
210
+ this.setStatus(String(e instanceof Error ? e.message : e)),
211
+ );
212
+ }
213
+
214
+ // ── verbs ───────────────────────────────────
215
+ open(id: string): void {
216
+ const cached = this.snap.inbox?.find((s) => s.id === id);
217
+ if (cached) this.update({ session: cached });
218
+ else void this.refreshSession(id);
219
+ }
220
+
221
+ cut(dispIdx: number): void {
222
+ const session = this.snap.session;
223
+ if (!session || session.status === "resolved") return;
224
+ const d = this.display()[dispIdx];
225
+ if (!d) return;
226
+ const working = this.working();
227
+ if (d.type === "del") {
228
+ const line = restoreLine(nextWorkBlock(this.display(), dispIdx), working.split("\n").length);
229
+ // restoreBlock returns undefined when the block structure round-trips
230
+ // to the submitted revision - the working copy is gone
231
+ const restored = restoreBlock(session.artifact.content, working, d.base!, line);
232
+ this.setWorkingCopy(restored);
233
+ this.setStatus("cut restored");
234
+ } else if (d.work) {
235
+ this.setWorkingCopy(cutBlock(working, d.work));
236
+ this.setStatus("block cut - it serializes into the diff");
237
+ }
238
+ }
239
+
240
+ edit(): void {
241
+ const session = this.snap.session;
242
+ if (!session || session.status === "resolved") return;
243
+ try {
244
+ const result = editInEditor(this.working(), "plan.md");
245
+ if (result.changed) {
246
+ this.setWorkingCopy(result.content);
247
+ this.setStatus("edits tracked - one diff");
248
+ } else this.setStatus("no changes");
249
+ } catch (err) {
250
+ this.setStatus(err instanceof Error ? err.message : String(err));
251
+ }
252
+ }
253
+
254
+ annotate(kind: "comment" | "suggestion", dispIdx: number, start: number, end: number, body: string): void {
255
+ const session = this.snap.session;
256
+ if (!session) return;
257
+ let anchor;
258
+ if (session.artifact.type === "diff") {
259
+ anchor = { ...diffRowAnchor(this.rows(), dispIdx), blockIndex: dispIdx };
260
+ } else {
261
+ const display = this.display();
262
+ const workBlocks = display.filter((d) => d.work).map((d) => d.work!);
263
+ const workIdx = display.slice(0, dispIdx + 1).filter((d) => d.work).length - 1;
264
+ anchor = makeAnchor(workBlocks, workIdx, start, end);
265
+ }
266
+ this.apply(
267
+ this.client!.sessionAnnotate(session.id, {
268
+ id: newAnnotationId(),
269
+ kind,
270
+ anchor,
271
+ body,
272
+ }),
273
+ );
274
+ this.setStatus(kind === "suggestion" ? "suggestion added - the agent applies it" : "comment added");
275
+ }
276
+
277
+ removeAnnotation(id: string): void {
278
+ const session = this.snap.session;
279
+ if (!session) return;
280
+ this.apply(this.client!.sessionRemoveAnnotation(session.id, id));
281
+ this.setStatus("annotation deleted");
282
+ }
283
+
284
+ setWorkingCopy(content: string | undefined): void {
285
+ const session = this.snap.session;
286
+ if (!session) return;
287
+ this.apply(this.client!.sessionSetWorkingCopy(session.id, content));
288
+ }
289
+
290
+ submit(verdict: VerdictKind, summary: string): void {
291
+ const session = this.snap.session;
292
+ if (!session) return;
293
+ this.client!.sessionResolve(session.id, verdict, summary)
294
+ .then((resolved) => {
295
+ this.update({ session: resolved, status: `review submitted - ${verdict.replace("_", " ")}` });
296
+ // notes-vault export: guarded by config, default is manual (no-op)
297
+ const obsidian = this.obsidian;
298
+ const exporter = this.exporters.get("obsidian");
299
+ if (obsidian && exporter && shouldExport(obsidian.exportOn, verdict)) {
300
+ void exporter(resolved).then((r) => {
301
+ this.setStatus(r.success && r.path ? `exported to ${r.path}` : `export failed: ${r.error ?? "unknown"}`);
302
+ });
303
+ }
304
+ // hand the reviewer back to the agent: prompt or count down per config;
305
+ // inside herdr with a known return pane, closing is the default
306
+ const delay = this.autoClose;
307
+ const returns = returnPaneFor(resolved.artifact.meta.herdrPane) !== undefined;
308
+ if (delay === 0) this.finishReview();
309
+ else if (typeof delay === "number") this.startCounting(delay);
310
+ else if (returns) this.startCounting(3);
311
+ else this.update({ completion: { phase: "prompt" } });
312
+ })
313
+ .catch((e: unknown) => this.setStatus(String(e instanceof Error ? e.message : e)));
314
+ }
315
+
316
+ // ── completion hand-back ────────────────────
317
+ private startCounting(remaining: number): void {
318
+ if (remaining <= 0) return this.finishReview();
319
+ this.update({ completion: { phase: "counting", remaining } });
320
+ this.countdown = setTimeout(() => this.startCounting(remaining - 1), 1000);
321
+ }
322
+
323
+ finishReview(): void {
324
+ clearTimeout(this.countdown);
325
+ const pane = returnPaneFor(this.snap.session?.artifact.meta.herdrPane);
326
+ if (pane) focusHerdrPane(pane);
327
+ this.opts.onExit?.(0);
328
+ }
329
+
330
+ dismissCompletion(): void {
331
+ clearTimeout(this.countdown);
332
+ this.update({ completion: { phase: "dismissed" } });
333
+ }
334
+
335
+ optInAutoClose(): void {
336
+ // opt in: close in 3s from now on, persisted to the user config
337
+ try {
338
+ persistAutoClose(3);
339
+ } catch {
340
+ // a read-only config dir must not block closing the review
341
+ }
342
+ this.autoClose = 3;
343
+ this.startCounting(3);
344
+ }
345
+ }