Open History to see the last commit
1import type {
2 EnvironmentId,
3 OrchestrationV2ProjectedTurnItem,
4 OrchestrationV2ThreadHistoryPage,
5 OrchestrationV2ThreadProjection,
6 OrchestrationV2ThreadStreamItem,
7 PeerLinkClientPairingResult,
8 ThreadId,
9} from "@t3tools/contracts";
10import * as Effect from "effect/Effect";
11import * as Queue from "effect/Queue";
12import * as Result from "effect/Result";
13import * as Stream from "effect/Stream";
14import { mFallback, msg } from "gt-i18n";
15import type { MFunctionType } from "gt-i18n/types";
16
17import {
18 deriveRunlessWorkStartedAt,
19 deriveThreadStructureRuntime,
20} from "./state/threadExecution.ts";
21import {
22 applyThreadHistoryPage,
23 applyThreadStreamItem,
24 initialThreadStreamState,
25 prependThreadHistory,
26 type ThreadStreamState,
27} from "./state/threadStream.ts";
28
29/** A thread on a linked environment, read through the environment that holds the link. */
30export interface LinkedThreadTarget {
31 /** The environment this client is connected to, which reads the thread over its link. */
32 readonly viaEnvironmentId: EnvironmentId;
33 /** The linked environment the thread lives in. */
34 readonly environmentId: EnvironmentId;
35 readonly threadId: ThreadId;
36 /** What to call the linked environment and the thread until the first page names them. */
37 readonly label: string;
38 readonly title: string | null;
39}
40
41export type LinkedThreadOpen = "direct" | "linked" | "unavailable";
42
43/**
44 * How a client opens a thread on `environmentId` that a thread or link in `viaEnvironmentId`
45 * points at. A connection of the client's own always wins, since it can do more than read. Without
46 * one, the environment holding the link reads it. A saved environment that neither answers nor is
47 * linked still opens directly, where the client says it is offline.
48 */
49export function resolveLinkedThreadOpen(input: {
50 readonly environmentId: EnvironmentId;
51 readonly viaEnvironmentId: EnvironmentId;
52 /** The client's own saved connection to `environmentId`, when it has one. */
53 readonly own: { readonly connected: boolean } | undefined;
54 /** Whether `viaEnvironmentId` holds a link to `environmentId`. */
55 readonly linked: boolean;
56}): LinkedThreadOpen {
57 if (input.environmentId === input.viaEnvironmentId) return "direct";
58 if (input.own?.connected === true) return "direct";
59 if (input.linked) return "linked";
60 return input.own === undefined ? "unavailable" : "direct";
61}
62
63export type LinkedEnvironmentConnection =
64 /** This client paired with the linked environment and saved it. */
65 | { readonly type: "connected" }
66 /** No address the linking environment knows answers from this device. */
67 | { readonly type: "unreachable"; readonly label: string }
68 /** The user pairs with a code of their own, in the add-environment flow, with this filled in. */
69 | { readonly type: "manual"; readonly label: string; readonly host: string | null };
70
71/**
72 * Connects this client to a linked environment. The linking environment asks it for a one-time
73 * pairing over a full-access link, and the client redeems that at an address it can reach itself.
74 * Anything short of that leaves the user to pair by hand.
75 */
76export async function connectLinkedEnvironment(options: {
77 readonly label: string;
78 /** Asks the linking environment for a pairing; null when it could not answer. */
79 readonly requestPairing: () => Promise<PeerLinkClientPairingResult | null>;
80 /** Whether an address answers this device as the linked environment. */
81 readonly reaches: (host: string) => Promise<boolean>;
82 /** Pairs at `host` with the one-time credential and saves the environment. */
83 readonly pair: (input: {
84 readonly host: string;
85 readonly pairingCode: string;
86 }) => Promise<boolean>;
87}): Promise<LinkedEnvironmentConnection> {
88 const pairing = await options.requestPairing();
89 if (pairing === null) return { type: "manual", label: options.label, host: null };
90 const { label, urls } = pairing;
91 // Asked together, taken in the linking environment's order of preference.
92 const probes = urls.map((url) =>
93 options.reaches(url).then(
94 (reached) => (reached ? url : null),
95 () => null,
96 ),
97 );
98 let host: string | null = null;
99 for (const probe of probes) {
100 host = await probe;
101 if (host !== null) break;
102 }
103 if (pairing.type === "unsupported") {
104 return { type: "manual", label, host: host ?? urls[0] ?? null };
105 }
106 if (host === null) return { type: "unreachable", label };
107 return (await options.pair({ host, pairingCode: pairing.credential }))
108 ? { type: "connected" }
109 : { type: "manual", label, host };
110}
111
112const hasStringField = <K extends string>(value: unknown, key: K): value is Record<K, string> =>
113 typeof value === "object" &&
114 value !== null &&
115 typeof (value as Record<string, unknown>)[key] === "string";
116
117/** Whether a failed read can succeed later with nothing changed: the linked environment was only out of reach. */
118const isLinkedThreadUnreachable = (error: unknown): boolean =>
119 hasStringField(error, "_tag") &&
120 error._tag === "PeerLinkThreadReadError" &&
121 hasStringField(error, "reason") &&
122 error.reason === "unreachable";
123
124export interface LinkedThreadFailure {
125 readonly title: string;
126 readonly detail: string;
127 /** Whether reading again can succeed without the user changing something first. */
128 readonly retryable: boolean;
129}
130
131/**
132 * A failed read in the user's words. `via` and `label` name the two environments as the client
133 * knows them; the server's own label wins once it has answered with one.
134 */
135export function linkedThreadFailure(
136 error: unknown,
137 names: { readonly via: string; readonly label: string },
138 resolve: MFunctionType = mFallback,
139): LinkedThreadFailure {
140 const via = names.via;
141 const serverMessage = hasStringField(error, "message") ? error.message : "";
142 if (!hasStringField(error, "_tag") || error._tag !== "PeerLinkThreadReadError") {
143 // An environment from before this read answers with an unknown method.
144 return {
145 title: resolve(msg("Could not read this thread through {via}", { via })),
146 detail:
147 serverMessage ||
148 resolve(msg("{via} may need an update before it can read linked threads.", { via })),
149 retryable: true,
150 };
151 }
152 const retryable = isLinkedThreadUnreachable(error);
153 const label = hasStringField(error, "label") ? error.label : names.label;
154 const reason = hasStringField(error, "reason") ? error.reason : "";
155 switch (reason) {
156 case "disabled":
157 return {
158 title: resolve(msg("Linked environments is off on {via}", { via })),
159 detail: resolve(
160 msg(
161 "Turn it on in {via}'s Settings → Labs to read threads on the machines it links to.",
162 {
163 via,
164 },
165 ),
166 ),
167 retryable,
168 };
169 case "unknown_link":
170 return {
171 title: resolve(msg("{via} is no longer linked to {label}", { via, label })),
172 detail: resolve(
173 msg("Link it again in {via}'s Settings → Connections to read its threads from here.", {
174 via,
175 }),
176 ),
177 retryable,
178 };
179 case "expired":
180 return {
181 title: resolve(msg("The link from {via} to {label} expired", { via, label })),
182 detail: resolve(
183 msg("Link it again in {via}'s Settings → Connections with a new pairing code.", { via }),
184 ),
185 retryable,
186 };
187 case "rejected":
188 return {
189 title: resolve(msg("{label} refused the read", { label })),
190 detail: serverMessage,
191 retryable,
192 };
193 case "thread_not_found":
194 return {
195 title: resolve(msg("This thread is no longer on {label}", { label })),
196 detail: resolve(msg("It may have been deleted there.")),
197 retryable,
198 };
199 case "incompatible":
200 return {
201 title: resolve(msg("{label} needs an update", { label })),
202 detail: serverMessage,
203 retryable,
204 };
205 default:
206 return {
207 title: resolve(msg("{label} is not answering {via}", { label, via })),
208 detail: serverMessage,
209 retryable,
210 };
211 }
212}
213
214const WORKING_STATUSES = new Set(["preparing", "queued", "starting", "running", "waiting"]);
215
216/** Whether the thread has work under way, for the note that stands where its composer would. */
217export function isLinkedThreadWorking(projection: OrchestrationV2ThreadProjection): boolean {
218 return (
219 WORKING_STATUSES.has(deriveThreadStructureRuntime(projection)?.status ?? "") ||
220 deriveRunlessWorkStartedAt(projection) !== null
221 );
222}
223
224/** How long a view waits before asking again for a thread whose environment did not answer. */
225export const LINKED_THREAD_RETRY_MS = 15_000;
226
227type HistoryAnchor = Pick<OrchestrationV2ProjectedTurnItem, "sourceThreadId" | "sourceItemId">;
228
229interface LinkedHistoryWindow {
230 readonly sequence: number;
231 readonly cursor: string;
232}
233
234interface LinkedHistoryRequest {
235 readonly window: LinkedHistoryWindow;
236 readonly cursor: string;
237}
238
239function includesHistoryAnchor(rows: ReadonlyArray<HistoryAnchor>, anchor: HistoryAnchor): boolean {
240 return rows.some(
241 (row) =>
242 row.sourceThreadId === anchor.sourceThreadId && row.sourceItemId === anchor.sourceItemId,
243 );
244}
245
246/** A linked thread as its view holds it: the thread's own stream, reduced as any thread's is. */
247export interface LinkedThreadView {
248 readonly thread: ThreadStreamState;
249 /** Why the stream stopped, while the view waits to ask again; the next item clears it. */
250 readonly error: unknown;
251 readonly history: { readonly loading: boolean; readonly failed: boolean };
252 /** Pagination progress survives the temporary view that hides the cursor during reconnect. */
253 readonly loadedHistory: {
254 readonly window: LinkedHistoryWindow;
255 readonly nextCursor: string | null;
256 /** The oldest row still to recover, even if a read fails or the view closes during backfill. */
257 readonly restoreThrough: HistoryAnchor | null;
258 } | null;
259 /** Loads the turns before the ones shown. Does nothing while a page loads or none is left. */
260 readonly loadEarlier: () => void;
261}
262
263/**
264 * What a view keeps once its stream shows `next`. A stream that was opened again has read nothing
265 * until its snapshot arrives, so the thread read before stays, with the new stream's state beside
266 * it. Its earlier turns load again only once that stream has a thread of its own to add them to.
267 */
268export const keepLinkedThreadView = (
269 kept: LinkedThreadView | null,
270 next: LinkedThreadView,
271): LinkedThreadView =>
272 next.thread.projection !== null || kept === null || kept.thread.projection === null
273 ? next
274 : {
275 ...next,
276 thread: { ...kept.thread, historyCursor: null },
277 loadedHistory: kept.loadedHistory,
278 };
279
280/**
281 * Follows a linked environment's thread for as long as something consumes the result. The thread
282 * is built from the same stream items and with the same reducer as a guest page's, and older
283 * turns load through the same cursor. A linked environment that stops answering is asked again
284 * after a wait, with what was read kept; any other failure ends the stream.
285 */
286export const followLinkedThread = <E, R, E2, R2>(source: {
287 readonly items: Stream.Stream<OrchestrationV2ThreadStreamItem, E, R>;
288 readonly historyPage: (cursor: string) => Effect.Effect<OrchestrationV2ThreadHistoryPage, E2, R2>;
289 readonly previous?: LinkedThreadView | null;
290}): Stream.Stream<LinkedThreadView, E, R | R2> =>
291 Stream.unwrap(
292 Effect.gen(function* () {
293 const requests = yield* Queue.unbounded<LinkedHistoryRequest | null>();
294 let requested = false;
295 let previous = source.previous ?? null;
296 let snapshotWindow: LinkedHistoryWindow | null = null;
297 const requestPage = (window: LinkedHistoryWindow, cursor: string) => {
298 requested = true;
299 Queue.offerUnsafe(requests, { window, cursor });
300 };
301 let view: LinkedThreadView = {
302 thread: initialThreadStreamState,
303 error: null,
304 history: { loading: false, failed: false },
305 loadedHistory: null,
306 loadEarlier: () => {
307 const cursor = view.thread.historyCursor;
308 if (requested || snapshotWindow === null || cursor === null) return;
309 requestPage(snapshotWindow, cursor);
310 },
311 };
312 const show = (patch: Partial<LinkedThreadView>) => {
313 view = { ...view, ...patch };
314 return view;
315 };
316
317 const onItem = (item: OrchestrationV2ThreadStreamItem) => {
318 let thread = applyThreadStreamItem(view.thread, item);
319 if (item.kind !== "snapshot") return show({ thread, error: null });
320
321 const kept = view.thread.projection === null ? previous : view;
322 previous = null;
323 const loaded = kept?.loadedHistory;
324 const window =
325 thread.historyCursor === null
326 ? null
327 : { sequence: thread.sequence, cursor: thread.historyCursor };
328 let loadedHistory: LinkedThreadView["loadedHistory"] = null;
329 if (window && kept?.thread.projection && loaded) {
330 // A live update can advance the revision and move the window without invalidating held rows.
331 if (
332 kept.thread.sequence === window.sequence &&
333 (window.sequence > loaded.window.sequence || window.cursor === loaded.window.cursor)
334 ) {
335 thread = prependThreadHistory(
336 thread,
337 {
338 items: kept.thread.projection.visibleTurnItems,
339 subagents: kept.thread.projection.subagents,
340 },
341 loaded.nextCursor,
342 );
343 loadedHistory = { ...loaded, window };
344 } else if (window.sequence > kept.thread.sequence) {
345 const oldest = loaded.restoreThrough ?? kept.thread.projection.visibleTurnItems[0];
346 if (oldest && !includesHistoryAnchor(item.projection.visibleTurnItems, oldest)) {
347 const { sourceThreadId, sourceItemId } = oldest;
348 loadedHistory = {
349 window,
350 nextCursor: window.cursor,
351 restoreThrough: { sourceThreadId, sourceItemId },
352 };
353 }
354 }
355 }
356
357 snapshotWindow = window;
358 requested = false;
359 if (window && thread.historyCursor !== null && loadedHistory?.restoreThrough) {
360 requestPage(window, thread.historyCursor);
361 } else {
362 Queue.offerUnsafe(requests, null);
363 }
364 return show({
365 thread,
366 loadedHistory,
367 history: { loading: requested, failed: false },
368 error: null,
369 });
370 };
371
372 const attempt = (): Stream.Stream<
373 | { readonly kind: "item"; readonly item: OrchestrationV2ThreadStreamItem }
374 | { readonly kind: "unreachable"; readonly error: E },
375 E,
376 R
377 > =>
378 source.items.pipe(
379 Stream.map((item) => ({ kind: "item" as const, item })),
380 Stream.catch((error) =>
381 isLinkedThreadUnreachable(error)
382 ? Stream.make({ kind: "unreachable" as const, error }).pipe(
383 Stream.concat(
384 Stream.unwrap(Effect.sleep(LINKED_THREAD_RETRY_MS).pipe(Effect.map(attempt))),
385 ),
386 )
387 : Stream.fail(error),
388 ),
389 );
390
391 const earlier = Stream.fromQueue(requests).pipe(
392 Stream.switchMap((request) =>
393 request === null
394 ? Stream.empty
395 : Stream.make({ kind: "loading" as const, request }).pipe(
396 Stream.concat(
397 Stream.fromEffect(
398 source.historyPage(request.cursor).pipe(
399 Effect.result,
400 Effect.map((page) => ({ kind: "page" as const, request, page })),
401 ),
402 ),
403 ),
404 ),
405 ),
406 );
407
408 // Reduce snapshots, live items and history results in publication order.
409 return Stream.merge(attempt(), earlier, { haltStrategy: "left" }).pipe(
410 Stream.filterMap((update) => {
411 if (update.kind === "item") return Result.succeed(onItem(update.item));
412 if (update.kind === "unreachable") return Result.succeed(show({ error: update.error }));
413 const { window, cursor } = update.request;
414 if (snapshotWindow !== window || view.thread.historyCursor !== cursor) {
415 return Result.failVoid;
416 }
417 if (update.kind === "loading") {
418 return view.history.loading
419 ? Result.failVoid
420 : Result.succeed(show({ history: { loading: true, failed: false } }));
421 }
422 requested = false;
423 const page = update.page;
424 if (
425 Result.isFailure(page) ||
426 page.success.snapshotSequence < window.sequence ||
427 (page.success.hasMoreHistory && page.success.nextCursor === cursor)
428 ) {
429 return Result.succeed(show({ history: { loading: false, failed: true } }));
430 }
431
432 const thread = applyThreadHistoryPage(view.thread, cursor, page.success);
433 let restoreThrough = view.loadedHistory?.restoreThrough ?? null;
434 const nextCursor = thread.historyCursor;
435 if (
436 restoreThrough !== null &&
437 (nextCursor === null ||
438 includesHistoryAnchor(thread.projection?.visibleTurnItems ?? [], restoreThrough))
439 ) {
440 restoreThrough = null;
441 }
442 if (restoreThrough !== null && nextCursor !== null) requestPage(window, nextCursor);
443 return Result.succeed(
444 show({
445 thread,
446 loadedHistory: { window, nextCursor, restoreThrough },
447 history: { loading: requested, failed: false },
448 }),
449 );
450 }),
451 );
452 }),
453 );