The best way to control Claude Code, Codex and more from any computer or phone

main
ts 162 lines 6.49 KB
Raw
1 import { useAtomValue } from "@effect/atom-react";
2 import {
3 linkableMachines,
4 linkedEnvironmentNames,
5 offersLinkedEnvironments,
6 } from "@t3tools/client-runtime/link-request";
7 import { linkBackOffer, type LinkBackOffer } from "@t3tools/client-runtime/link-batch";
8 import { createPeerLinkEnvironmentAtoms } from "@t3tools/client-runtime/state/peerLinks";
9 import { AuthAccessReadScope, AuthAccessWriteScope, type EnvironmentId } from "@t3tools/contracts";
10 import { Atom } from "effect/reactivity";
11 import { useEffect, useEffectEvent } from "react";
12
13 import { connectionAtomRuntime } from "../connection/runtime";
14 import { environmentAtomList, environmentIdsKey } from "./environmentAtomList";
15 import { useEnvironmentIdentities, useEnvironments } from "./environments";
16 import { environmentPresentations } from "./presentation";
17 import { relayEnvironmentDiscovery } from "./relay";
18 import { useEnvironmentQuery } from "./query";
19 import { useEnvironmentsWithScope } from "./session";
20 import { useAtomCommand } from "./use-atom-command";
21
22 export const peerLinkEnvironment = createPeerLinkEnvironmentAtoms(connectionAtomRuntime);
23
24 /** Each environment's link list as the settings list loads it, in the order of the ids. */
25 export const peerLinkListsAtom = environmentAtomList("peer-links:lists", (environmentId) =>
26 peerLinkEnvironment.list({ environmentId, input: {} }),
27 );
28
29 /** Whether `environmentId` offers links, so its threads may name another machine. */
30 export const offersLinkedEnvironmentsAtom = Atom.family((environmentId: EnvironmentId) =>
31 Atom.make((get) =>
32 offersLinkedEnvironments(get(environmentPresentations.serverConfigsAtom).get(environmentId)),
33 ).pipe(Atom.withLabel(`peer-links:offered:${environmentId}`)),
34 );
35
36 const offersNoLinksAtom = Atom.make(false).pipe(Atom.withLabel("peer-links:offered:none"));
37
38 /**
39 * The machines `environmentId` links to, by name, while it offers links, and none otherwise.
40 * Its agents can read threads there, and so can a client allowed to read threads on it.
41 */
42 export function useLinkedEnvironments(
43 environmentId: EnvironmentId | null,
44 ): ReadonlyMap<EnvironmentId, string> {
45 const offered = useAtomValue(
46 environmentId === null ? offersNoLinksAtom : offersLinkedEnvironmentsAtom(environmentId),
47 );
48 const identities = useEnvironmentIdentities();
49 const links = useEnvironmentQuery(
50 offered && environmentId !== null
51 ? peerLinkEnvironment.names({ environmentId, input: {} })
52 : null,
53 );
54 return linkedEnvironmentNames({
55 links: offered ? (links.data?.links ?? []) : [],
56 environments: identities,
57 });
58 }
59
60 export function usePeerLinkHosts() {
61 const { environments } = useEnvironments();
62 const supported = environments.filter(
63 (environment) =>
64 environment.connection.phase === "connected" &&
65 offersLinkedEnvironments(environment.serverConfig),
66 );
67 const readable = useEnvironmentsWithScope(supported, AuthAccessReadScope);
68 return supported.filter((environment) => readable.has(environment.environmentId));
69 }
70
71 /**
72 * The user's other machines, for picking one to link `environmentId` to,
73 * including those only on their T3 Connect account. Reads that environment's
74 * links only while `enabled`, since listing them asks every linked machine
75 * whether it answers.
76 */
77 export function useLinkableMachines(environmentId: EnvironmentId, enabled: boolean) {
78 const { environments } = useEnvironments();
79 const discovery = useAtomValue(relayEnvironmentDiscovery.stateValueAtom);
80 const refreshDiscovery = useAtomCommand(relayEnvironmentDiscovery.refresh, {
81 reportFailure: false,
82 });
83 // Connect hosts are listed only once something asked for them, so ask on open.
84 const discoverIfUnasked = useEffectEvent(() => {
85 if (discovery.environments.size === 0 && !discovery.refreshing) void refreshDiscovery();
86 });
87 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- discovery follows the picker's visibility, which a card's mount or a dialog's open sets
88 useEffect(() => {
89 if (enabled) discoverIfUnasked();
90 }, [enabled]);
91 const links = useEnvironmentQuery(
92 enabled ? peerLinkEnvironment.list({ environmentId, input: {} }) : null,
93 );
94 return linkableMachines({
95 environments,
96 threadEnvironmentId: environmentId,
97 links: links.data?.links ?? [],
98 connect: discovery.environments,
99 });
100 }
101
102 const NOT_OFFERED: LinkBackOffer = { kind: "hidden" };
103
104 /**
105 * Whether linking `sourceId` to each of `targetIds` can also link that machine back, and the
106 * source as the reverse link names it. Only machines that could link back are asked for their
107 * links, and only while `enabled`: listing asks every machine they link to whether it answers.
108 */
109 export function useLinkBackOffers(
110 sourceId: EnvironmentId,
111 targetIds: ReadonlyArray<EnvironmentId>,
112 enabled: boolean,
113 ) {
114 const { environments } = useEnvironments();
115 const discovery = useAtomValue(relayEnvironmentDiscovery.stateValueAtom);
116 const writable = useEnvironmentsWithScope(environments, AuthAccessWriteScope);
117 const source = linkableMachines({
118 environments,
119 threadEnvironmentId: null,
120 links: [],
121 connect: discovery.environments,
122 }).find((machine) => machine.environmentId === sourceId);
123 const wanted = new Set(targetIds);
124 const targets = environments.filter((environment) => wanted.has(environment.environmentId));
125 const listed = targets
126 .filter(
127 (target) =>
128 enabled &&
129 target.connection.phase === "connected" &&
130 offersLinkedEnvironments(target.serverConfig) &&
131 writable.has(target.environmentId),
132 )
133 .map((target) => target.environmentId);
134 const lists = useAtomValue(peerLinkListsAtom(environmentIdsKey(listed)));
135 const offers = new Map<EnvironmentId, LinkBackOffer>();
136 for (const target of targets) {
137 if (source === undefined) break;
138 const list = lists[listed.indexOf(target.environmentId)];
139 offers.set(
140 target.environmentId,
141 linkBackOffer({
142 source: {
143 environmentId: sourceId,
144 connected: source.connected,
145 writable: writable.has(sourceId),
146 urls: source.urls,
147 },
148 target: {
149 connected: target.connection.phase === "connected",
150 offersLinks: offersLinkedEnvironments(target.serverConfig),
151 writable: writable.has(target.environmentId),
152 links: list?._tag === "Success" ? list.value.links : null,
153 },
154 }),
155 );
156 }
157 return {
158 source: source ?? null,
159 offerFor: (targetId: EnvironmentId | null): LinkBackOffer =>
160 (targetId === null ? undefined : offers.get(targetId)) ?? NOT_OFFERED,
161 };
162 }