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

linkedThread.ts

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