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 { M } from "gt-i18n";
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: M = 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 }}`),
146 detail:
147 serverMessage ||
148 resolve(msg`${{ via }} may need an update before it can read linked threads.`),
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 }}`),
159 detail: resolve(
160 msg`Turn it on in ${{ via }}'s Settings → Labs to read threads on the machines it links to.`,
161 ),
162 retryable,
163 };
164 case "unknown_link":
165 return {
166 title: resolve(msg`${{ via }} is no longer linked to ${{ label }}`),
167 detail: resolve(
168 msg`Link it again in ${{ via }}'s Settings → Connections to read its threads from here.`,
169 ),
170 retryable,
171 };
172 case "expired":
173 return {
174 title: resolve(msg`The link from ${{ via }} to ${{ label }} expired`),
175 detail: resolve(
176 msg`Link it again in ${{ via }}'s Settings → Connections with a new pairing code.`,
177 ),
178 retryable,
179 };
180 case "rejected":
181 return {
182 title: resolve(msg`${{ label }} refused the read`),
183 detail: serverMessage,
184 retryable,
185 };
186 case "thread_not_found":
187 return {
188 title: resolve(msg`This thread is no longer on ${{ label }}`),
189 detail: resolve(msg("It may have been deleted there.")),
190 retryable,
191 };
192 case "incompatible":
193 return {
194 title: resolve(msg`${{ label }} needs an update`),
195 detail: serverMessage,
196 retryable,
197 };
198 default:
199 return {
200 title: resolve(msg`${{ label }} is not answering ${{ via }}`),
201 detail: serverMessage,
202 retryable,
203 };
204 }
205}
206
207const WORKING_STATUSES = new Set(["preparing", "queued", "starting", "running", "waiting"]);
208
209/** Whether the thread has work under way, for the note that stands where its composer would. */
210export function isLinkedThreadWorking(projection: OrchestrationV2ThreadProjection): boolean {
211 return (
212 WORKING_STATUSES.has(deriveThreadStructureRuntime(projection)?.status ?? "") ||
213 deriveRunlessWorkStartedAt(projection) !== null
214 );
215}
216
217/** How long a view waits before asking again for a thread whose environment did not answer. */
218export const LINKED_THREAD_RETRY_MS = 15_000;
219
220type HistoryAnchor = Pick<OrchestrationV2ProjectedTurnItem, "sourceThreadId" | "sourceItemId">;
221
222interface LinkedHistoryWindow {
223 readonly sequence: number;
224 readonly cursor: string;
225}
226
227interface LinkedHistoryRequest {
228 readonly window: LinkedHistoryWindow;
229 readonly cursor: string;
230}
231
232function includesHistoryAnchor(rows: ReadonlyArray<HistoryAnchor>, anchor: HistoryAnchor): boolean {
233 return rows.some(
234 (row) =>
235 row.sourceThreadId === anchor.sourceThreadId && row.sourceItemId === anchor.sourceItemId,
236 );
237}
238
239/** A linked thread as its view holds it: the thread's own stream, reduced as any thread's is. */
240export interface LinkedThreadView {
241 readonly thread: ThreadStreamState;
242 /** Why the stream stopped, while the view waits to ask again; the next item clears it. */
243 readonly error: unknown;
244 readonly history: { readonly loading: boolean; readonly failed: boolean };
245 /** Pagination progress survives the temporary view that hides the cursor during reconnect. */
246 readonly loadedHistory: {
247 readonly window: LinkedHistoryWindow;
248 readonly nextCursor: string | null;
249 /** The oldest row still to recover, even if a read fails or the view closes during backfill. */
250 readonly restoreThrough: HistoryAnchor | null;
251 } | null;
252 /** Loads the turns before the ones shown. Does nothing while a page loads or none is left. */
253 readonly loadEarlier: () => void;
254}
255
256/**
257 * What a view keeps once its stream shows `next`. A stream that was opened again has read nothing
258 * until its snapshot arrives, so the thread read before stays, with the new stream's state beside
259 * it. Its earlier turns load again only once that stream has a thread of its own to add them to.
260 */
261export const keepLinkedThreadView = (
262 kept: LinkedThreadView | null,
263 next: LinkedThreadView,
264): LinkedThreadView =>
265 next.thread.projection !== null || kept === null || kept.thread.projection === null
266 ? next
267 : {
268 ...next,
269 thread: { ...kept.thread, historyCursor: null },
270 loadedHistory: kept.loadedHistory,
271 };
272
273/**
274 * Follows a linked environment's thread for as long as something consumes the result. The thread
275 * is built from the same stream items and with the same reducer as a guest page's, and older
276 * turns load through the same cursor. A linked environment that stops answering is asked again
277 * after a wait, with what was read kept; any other failure ends the stream.
278 */
279export const followLinkedThread = <E, R, E2, R2>(source: {
280 readonly items: Stream.Stream<OrchestrationV2ThreadStreamItem, E, R>;
281 readonly historyPage: (cursor: string) => Effect.Effect<OrchestrationV2ThreadHistoryPage, E2, R2>;
282 readonly previous?: LinkedThreadView | null;
283}): Stream.Stream<LinkedThreadView, E, R | R2> =>
284 Stream.unwrap(
285 Effect.gen(function* () {
286 const requests = yield* Queue.unbounded<LinkedHistoryRequest | null>();
287 let requested = false;
288 let previous = source.previous ?? null;
289 let snapshotWindow: LinkedHistoryWindow | null = null;
290 const requestPage = (window: LinkedHistoryWindow, cursor: string) => {
291 requested = true;
292 Queue.offerUnsafe(requests, { window, cursor });
293 };
294 let view: LinkedThreadView = {
295 thread: initialThreadStreamState,
296 error: null,
297 history: { loading: false, failed: false },
298 loadedHistory: null,
299 loadEarlier: () => {
300 const cursor = view.thread.historyCursor;
301 if (requested || snapshotWindow === null || cursor === null) return;
302 requestPage(snapshotWindow, cursor);
303 },
304 };
305 const show = (patch: Partial<LinkedThreadView>) => {
306 view = { ...view, ...patch };
307 return view;
308 };
309
310 const onItem = (item: OrchestrationV2ThreadStreamItem) => {
311 let thread = applyThreadStreamItem(view.thread, item);
312 if (item.kind !== "snapshot") return show({ thread, error: null });
313
314 const kept = view.thread.projection === null ? previous : view;
315 previous = null;
316 const loaded = kept?.loadedHistory;
317 const window =
318 thread.historyCursor === null
319 ? null
320 : { sequence: thread.sequence, cursor: thread.historyCursor };
321 let loadedHistory: LinkedThreadView["loadedHistory"] = null;
322 if (window && kept?.thread.projection && loaded) {
323 // A live update can advance the revision and move the window without invalidating held rows.
324 if (
325 kept.thread.sequence === window.sequence &&
326 (window.sequence > loaded.window.sequence || window.cursor === loaded.window.cursor)
327 ) {
328 thread = prependThreadHistory(
329 thread,
330 {
331 items: kept.thread.projection.visibleTurnItems,
332 subagents: kept.thread.projection.subagents,
333 },
334 loaded.nextCursor,
335 );
336 loadedHistory = { ...loaded, window };
337 } else if (window.sequence > kept.thread.sequence) {
338 const oldest = loaded.restoreThrough ?? kept.thread.projection.visibleTurnItems[0];
339 if (oldest && !includesHistoryAnchor(item.projection.visibleTurnItems, oldest)) {
340 const { sourceThreadId, sourceItemId } = oldest;
341 loadedHistory = {
342 window,
343 nextCursor: window.cursor,
344 restoreThrough: { sourceThreadId, sourceItemId },
345 };
346 }
347 }
348 }
349
350 snapshotWindow = window;
351 requested = false;
352 if (window && thread.historyCursor !== null && loadedHistory?.restoreThrough) {
353 requestPage(window, thread.historyCursor);
354 } else {
355 Queue.offerUnsafe(requests, null);
356 }
357 return show({
358 thread,
359 loadedHistory,
360 history: { loading: requested, failed: false },
361 error: null,
362 });
363 };
364
365 const attempt = (): Stream.Stream<
366 | { readonly kind: "item"; readonly item: OrchestrationV2ThreadStreamItem }
367 | { readonly kind: "unreachable"; readonly error: E },
368 E,
369 R
370 > =>
371 source.items.pipe(
372 Stream.map((item) => ({ kind: "item" as const, item })),
373 Stream.catch((error) =>
374 isLinkedThreadUnreachable(error)
375 ? Stream.make({ kind: "unreachable" as const, error }).pipe(
376 Stream.concat(
377 Stream.unwrap(Effect.sleep(LINKED_THREAD_RETRY_MS).pipe(Effect.map(attempt))),
378 ),
379 )
380 : Stream.fail(error),
381 ),
382 );
383
384 const earlier = Stream.fromQueue(requests).pipe(
385 Stream.switchMap((request) =>
386 request === null
387 ? Stream.empty
388 : Stream.make({ kind: "loading" as const, request }).pipe(
389 Stream.concat(
390 Stream.fromEffect(
391 source.historyPage(request.cursor).pipe(
392 Effect.result,
393 Effect.map((page) => ({ kind: "page" as const, request, page })),
394 ),
395 ),
396 ),
397 ),
398 ),
399 );
400
401 // Reduce snapshots, live items and history results in publication order.
402 return Stream.merge(attempt(), earlier, { haltStrategy: "left" }).pipe(
403 Stream.filterMap((update) => {
404 if (update.kind === "item") return Result.succeed(onItem(update.item));
405 if (update.kind === "unreachable") return Result.succeed(show({ error: update.error }));
406 const { window, cursor } = update.request;
407 if (snapshotWindow !== window || view.thread.historyCursor !== cursor) {
408 return Result.failVoid;
409 }
410 if (update.kind === "loading") {
411 return view.history.loading
412 ? Result.failVoid
413 : Result.succeed(show({ history: { loading: true, failed: false } }));
414 }
415 requested = false;
416 const page = update.page;
417 if (
418 Result.isFailure(page) ||
419 page.success.snapshotSequence < window.sequence ||
420 (page.success.hasMoreHistory && page.success.nextCursor === cursor)
421 ) {
422 return Result.succeed(show({ history: { loading: false, failed: true } }));
423 }
424
425 const thread = applyThreadHistoryPage(view.thread, cursor, page.success);
426 let restoreThrough = view.loadedHistory?.restoreThrough ?? null;
427 const nextCursor = thread.historyCursor;
428 if (
429 restoreThrough !== null &&
430 (nextCursor === null ||
431 includesHistoryAnchor(thread.projection?.visibleTurnItems ?? [], restoreThrough))
432 ) {
433 restoreThrough = null;
434 }
435 if (restoreThrough !== null && nextCursor !== null) requestPage(window, nextCursor);
436 return Result.succeed(
437 show({
438 thread,
439 loadedHistory: { window, nextCursor, restoreThrough },
440 history: { loading: requested, failed: false },
441 }),
442 );
443 }),
444 );
445 }),
446 );