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

linkedThread.ts

116 lines4.8 KB

1import { useAtomSet, useAtomValue } from "@effect/atom-react";
2import {
3 connectLinkedEnvironment,
4 type LinkedThreadTarget,
5} from "@t3tools/client-runtime/linked-thread";
6import type { EnvironmentId, OrchestrationV2Subagent } from "@t3tools/contracts";
7import { useState } from "react";
8​
9import { connectPairingUrl, reachesEnvironment } from "../connection/onboarding";
10import { linkedEnvironmentPrefillAtom } from "../features/connection/linkedEnvironmentPrefill";
11import { buildPairingUrl } from "../features/connection/pairing";
12import { useEnvironments } from "./environments";
13import { peerLinkEnvironment, useLinkedEnvironments } from "./peerLinks";
14import { useEnvironmentQuery } from "./query";
15import { useAtomCommand } from "./use-atom-command";
16​
17/**
18 * What places a delegated task's thread: this app's own connections, and the links `environmentId`
19 * holds. Links are listed only while a task runs somewhere this app is not connected to.
20 */
21export function useLinkedThreadReach(
22 environmentId: EnvironmentId,
23 subagents: ReadonlyArray<Pick<OrchestrationV2Subagent, "childThreadId" | "remoteChild">>,
24) {
25 const { presentationById } = useEnvironments();
26 const ownConnection = (id: EnvironmentId) => {
27 const own = presentationById.get(id);
28 return own && { connected: own.connection.phase === "connected" };
29 };
30 const remote = subagents.flatMap((subagent) =>
31 subagent.childThreadId === null &&
32 subagent.remoteChild !== undefined &&
33 ownConnection(subagent.remoteChild.environmentId)?.connected !== true
34 ? [subagent.remoteChild.environmentId]
35 : [],
36 );
37 const links = useLinkedEnvironments(remote.length > 0 ? environmentId : null, remote);
38 return { ownConnection, isLinked: (id: EnvironmentId) => links.has(id) };
40​
41export type LinkedEnvironmentConnectState =
42 | { readonly phase: "idle" | "connecting" }
43 | { readonly phase: "unreachable"; readonly label: string };
44​
45/**
46 * Connects this app to the environment `target` lives in. One step when the linking environment
47 * can get a pairing for this app; otherwise the caller opens the add-environment screen, which
48 * reads what was learned about the machine.
49 */
50export function useConnectLinkedEnvironment(target: LinkedThreadTarget) {
51 const setPrefill = useAtomSet(linkedEnvironmentPrefillAtom);
52 const mayPair = useAtomValue(
53 peerLinkEnvironment.pairClient.permissionAtom(target.viaEnvironmentId),
54 );
55 const quiet = { reportFailure: false, reportDefect: false } as const;
56 const requestPairing = useAtomCommand(peerLinkEnvironment.pairClient, quiet);
57 const reaches = useAtomCommand(reachesEnvironment, quiet);
58 const pair = useAtomCommand(connectPairingUrl, quiet);
59 const [state, setState] = useState<LinkedEnvironmentConnectState>({ phase: "idle" });
60 const connect = async () => {
61 setState({ phase: "connecting" });
62 const outcome = await connectLinkedEnvironment({
63 label: target.label,
64 requestPairing: async () => {
65 // Without it the linking environment refuses; the user can still pair by hand.
66 if (!mayPair) return null;
67 const result = await requestPairing({
68 environmentId: target.viaEnvironmentId,
69 input: { environmentId: target.environmentId },
70 });
71 return result._tag === "Success" ? result.value : null;
72 },
73 reaches: async (host) => {
74 const result = await reaches({ host, environmentId: target.environmentId });
75 return result._tag === "Success" && result.value;
76 },
77 pair: async ({ host, pairingCode }) => {
78 const result = await pair({
79 pairingUrl: buildPairingUrl(host, pairingCode),
80 expectedEnvironmentId: target.environmentId,
81 });
82 return result._tag === "Success";
83 },
84 });
85 setState(
86 outcome.type === "unreachable"
87 ? { phase: "unreachable", label: outcome.label }
88 : { phase: "idle" },
89 );
90 if (outcome.type === "manual") {
91 setPrefill({ environmentId: target.environmentId, label: outcome.label, host: outcome.host });
92 }
93 return outcome;
94 };
95 return { state, connect };
97​
98/**
99 * The thread of `target`, streamed through the environment that links to it. The stream runs only
100 * while `active`; what it last showed stays, so coming back to the screen shows it at once.
101 */
102export function useLinkedThreadView(target: LinkedThreadTarget, active: boolean) {
103 const viewTarget = {
104 environmentId: target.viaEnvironmentId,
105 input: { environmentId: target.environmentId, threadId: target.threadId },
106 };
107 const live = useEnvironmentQuery(active ? peerLinkEnvironment.threadView(viewTarget) : null);
108 const view = useAtomValue(peerLinkEnvironment.lastThreadView(viewTarget));
109 return {
110 view,
111 /** Why the stream is not running: it ended, or it waits to ask again. */
112 error: live.failure ?? view?.error ?? null,
113 /** Asks again now. */
114 retry: live.refresh,
115 };