Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

linkedThread.ts

444 lines17.3 KB

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