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

HandoffRequestCard.tsx

308 lines11.7 KB

1import { useAtomValue } from "@effect/atom-react";
2import {
3 HANDOFF_LINK_DEFAULT_ACCESS,
4 handoffLinkCandidates,
5 handoffRequestDisplay,
6 type HandoffRequestItem,
7 handoffRequestTarget,
8} from "@t3tools/client-runtime/handoff-request";
9import { linkRequestFailureMessage } from "@t3tools/client-runtime/link-request";
10import {
11 isAtomCommandInterrupted,
12 squashAtomCommandFailure,
13} from "@t3tools/client-runtime/state/runtime";
14import {
15 AuthAccessWriteScope,
16 type AuthMcpClientAccess,
17 type EnvironmentId,
18 type OrchestrationV2ProjectedTurnItem,
19 type ProjectId,
20} from "@t3tools/contracts";
21import * as Result from "effect/Result";
22import { T, msg, useGT, useMessages } from "gt-react";
23import { CheckIcon, LockIcon, MinusIcon, MonitorUpIcon } from "lucide-react";
24import { useRef, useState } from "react";
25​
26import { mintPairingCodeOn } from "~/state/peerPairingCode";
27import { peerLinkEnvironment, useLinkableMachines } from "~/state/peerLinks";
28import { useEnvironmentQuery } from "~/state/query";
29import { useEnvironmentsWithScope } from "~/state/session";
30import { canMoveThreadsAtom, threadHandoffEnvironment } from "~/state/threadHandoff";
31import { useAtomCommand } from "~/state/use-atom-command";
32import { Button } from "../ui/button";
33import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
34import { LinkAccessPicker } from "../settings/LinkAccessPicker";
35import { useHandoffProject } from "./useHandoffProject";
36import { WorkLogRow } from "./WorkLog";
37​
38const TITLE = msg("Move this thread");
39​
40/** An agent's ask to move its thread: the user picks the machine and moves it, or declines. */
41export function HandoffRequestCard(props: {
42 readonly environmentId: EnvironmentId;
43 readonly item: HandoffRequestItem;
44 readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"];
45}) {
46 const m = useMessages();
47 const display = handoffRequestDisplay(props.item, props.visibility, m);
48 if (display.kind === "pending") {
49 return <PendingHandoffRequest environmentId={props.environmentId} item={props.item} />;
50 }
51 const Icon =
52 display.kind === "pending-elsewhere" ? LockIcon : display.accepted ? CheckIcon : MinusIcon;
53 return (
54 <WorkLogRow
55 data-v2-item-type={props.item.type}
56 icon={<Icon className="size-3.5 text-icon-muted" aria-hidden />}
57 label={
58 <>
59 {m(TITLE)} · {display.label}
60 </>
61 }
62 />
63 );
65​
66function PendingHandoffRequest(props: {
67 readonly environmentId: EnvironmentId;
68 readonly item: HandoffRequestItem;
69}) {
70 const gt = useGT();
71 const m = useMessages();
72 const { item } = props;
73 const canMove = useAtomValue(canMoveThreadsAtom(props.environmentId));
74 const targets = useEnvironmentQuery(
75 threadHandoffEnvironment.options({
76 environmentId: props.environmentId,
77 input: { threadId: item.threadId },
78 }),
79 );
80 const start = useAtomCommand(threadHandoffEnvironment.start, { reportFailure: false });
81 const cancel = useAtomCommand(threadHandoffEnvironment.cancel, { reportFailure: false });
82 const link = useAtomCommand(peerLinkEnvironment.link, {
83 // The failure cause holds the request, and with it the code; keep it out of the console.
84 reportFailure: false,
85 reportDefect: false,
86 });
87 const [picked, setPicked] = useState<EnvironmentId | null>(null);
88 const [access, setAccess] = useState<AuthMcpClientAccess>(HANDOFF_LINK_DEFAULT_ACCESS);
89 const [submitting, setSubmitting] = useState(false);
90 const [error, setError] = useState<string | null>(null);
91 // Two clicks can land before a render.
92 const inFlight = useRef(false);
93 const options = targets.data?.options ?? [];
94 // Machines this client is connected to and may link the thread's environment to itself.
95 const candidates = handoffLinkCandidates(useLinkableMachines(props.environmentId, true));
96 const mayLink = useEnvironmentsWithScope(candidates, AuthAccessWriteScope);
97 // Linking is changed on this thread's machine too, which this session may not be allowed to.
98 const mayLinkHere = useAtomValue(peerLinkEnvironment.link.permissionAtom(props.environmentId));
99 const linkable = candidates.filter(
100 (machine) =>
101 targets.data !== null &&
102 mayLinkHere &&
103 mayLink.has(machine.environmentId) &&
104 !options.some((option) => option.environmentId === machine.environmentId),
105 );
106 const wanted = picked ?? item.environmentId;
107 const toLink = linkable.find((machine) => machine.environmentId === wanted);
108 const chosen = toLink === undefined ? handoffRequestTarget(options, wanted) : undefined;
109 const target = toLink ?? chosen;
110 const suggestedProject =
111 target?.environmentId === item.environmentId ? item.projectId : undefined;
112 const needsProject =
113 suggestedProject === undefined &&
114 (toLink !== undefined || chosen?.projectSelectionRequired === true);
115 const project = useHandoffProject(
116 { environmentId: props.environmentId, threadId: item.threadId },
117 target?.environmentId,
118 needsProject,
119 submitting || !canMove,
120 chosen?.projectChoices,
121 );
122​
123 const answer = async (send: () => ReturnType<typeof start> | ReturnType<typeof cancel>) => {
124 if (inFlight.current) return;
125 inFlight.current = true;
126 setSubmitting(true);
127 setError(null);
128 const result = await send().finally(() => {
129 inFlight.current = false;
130 setSubmitting(false);
131 });
132 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
133 const failure = squashAtomCommandFailure(result);
134 setError(failure instanceof Error ? failure.message : gt`The thread could not be moved.`);
135 };
136 const disabled = submitting || !canMove;
137​
138 const move = (environmentId: EnvironmentId, projectId?: ProjectId) =>
139 start({
140 environmentId: props.environmentId,
141 input: {
142 threadId: item.threadId,
143 environmentId,
144 turnItemId: item.id,
145 ...(projectId === undefined ? {} : { projectId }),
146 },
147 });
148​
149 /** Links the thread's environment to `machine`; resolves to what went wrong, or null. */
150 const linkTo = async (machine: (typeof linkable)[number]): Promise<unknown> => {
151 const [url, ...alternateUrls] = machine.urls;
152 if (url === undefined) return "interrupted";
153 const code = await mintPairingCodeOn(machine.environmentId, access);
154 if (Result.isFailure(code)) return code.failure;
155 const linked = await link({
156 environmentId: props.environmentId,
157 input: {
158 url,
159 ...(alternateUrls.length === 0 ? {} : { alternateUrls }),
160 pairingCode: code.success,
161 access,
162 expectedEnvironmentId: machine.environmentId,
163 expectedLabel: machine.label,
164 },
165 });
166 if (linked._tag !== "Failure") return null;
167 return isAtomCommandInterrupted(linked) ? "interrupted" : squashAtomCommandFailure(linked);
168 };
169​
170 /** Links to a machine this client is connected to, then moves the thread there. */
171 const linkAndMove = async (machine: (typeof linkable)[number], projectId?: ProjectId) => {
172 if (inFlight.current) return;
173 inFlight.current = true;
174 setSubmitting(true);
175 setError(null);
176 const failure = await linkTo(machine);
177 inFlight.current = false;
178 setSubmitting(false);
179 if (failure !== null) {
180 if (failure !== "interrupted") setError(linkRequestFailureMessage(failure, m));
181 return;
182 }
183 targets.refresh();
184 await answer(() => move(machine.environmentId, projectId));
185 };
186​
187 const moveToTarget = (projectId?: ProjectId) => {
188 if (toLink !== undefined) void linkAndMove(toLink, projectId);
189 else if (chosen !== undefined) void answer(() => move(chosen.environmentId, projectId));
190 };
191​
192 return (
193 <section
194 data-v2-item-type={item.type}
195 aria-label={m(TITLE)}
196 className="flex min-w-0 flex-col gap-3 rounded-xl border border-border/60 bg-card p-4"
197 >
198 <div className="flex min-w-0 flex-col gap-1">
199 <h3 className="flex items-center gap-1.5 text-sm font-medium text-foreground">
200 <MonitorUpIcon className="size-3.5 shrink-0 text-icon-muted" aria-hidden />
201 <T>Move this thread to another machine?</T>
202 </h3>
203 <p className="text-xs text-muted-foreground">
204 <T>
205 It moves with its conversation and its code, uncommitted changes included. This copy
206 becomes read-only.
207 </T>
208 </p>
209 </div>
210 <Select
211 value={target?.environmentId ?? null}
212 disabled={disabled || (options.length === 0 && linkable.length === 0)}
213 onValueChange={(value) => {
214 if (value) setPicked(value);
215 }}
216 >
217 <SelectTrigger size="sm" aria-label={gt`Machine to continue on`}>
218 <SelectValue>
219 {target?.label ??
220 (targets.data === null && targets.error === null
221 ? gt`Asking linked machines…`
222 : gt`Choose a machine`)}
223 </SelectValue>
224 </SelectTrigger>
225 <SelectPopup alignItemWithTrigger={false}>
226 {options.map((option) => (
227 <SelectItem
228 key={option.environmentId}
229 value={option.environmentId}
230 disabled={option.reason !== null && !option.projectSelectionRequired}
231 >
232 {option.reason === null || option.projectSelectionRequired
233 ? option.label
234 : `${option.label}: ${option.reason}`}
235 </SelectItem>
236 ))}
237 {linkable.map((machine) => (
238 <SelectItem key={machine.environmentId} value={machine.environmentId}>
239 {gt`${{ machine: machine.label }} (not linked yet)`}
240 </SelectItem>
241 ))}
242 </SelectPopup>
243 </Select>
244 {toLink !== undefined ? (
245 <div className="flex min-w-0 flex-col gap-2">
246 <p className="text-xs text-muted-foreground">
247 {gt`This machine is not linked to ${{ machine: toLink.label }} yet. Moving the thread links them first, with a code this device creates there. Choose what agents here may do there.`}
248 </p>
249 <LinkAccessPicker value={access} onChange={setAccess} disabled={disabled} forWriting />
250 </div>
251 ) : null}
252 {project.picker}
253 {needsProject && project.picker === null && project.clone === undefined ? (
254 <p className="text-xs text-muted-foreground">
255 {chosen?.reason ?? gt`No project is available on this machine.`}
256 </p>
257 ) : null}
258 {(error ?? targets.error) !== null ? (
259 <p role="alert" className="text-xs text-destructive">
260 {error ?? targets.error}
261 </p>
262 ) : !canMove ? (
263 <p className="text-xs text-muted-foreground">
264 <T>Only someone who can run agents on this machine can move it or decline.</T>
265 </p>
266 ) : null}
267 <div className="flex items-center justify-end gap-2">
268 <Button
269 type="button"
270 size="sm"
271 variant="ghost-muted"
272 disabled={disabled}
273 onClick={() =>
274 void answer(() =>
275 cancel({
276 environmentId: props.environmentId,
277 input: { threadId: item.threadId, turnItemId: item.id },
278 }),
279 )
280 }
281 >
282 <T>Not now</T>
283 </Button>
284 <Button
285 type="button"
286 size="sm"
287 disabled={
288 disabled ||
289 target === undefined ||
290 (needsProject && !project.projectId && !project.clone)
291 }
292 onClick={() => {
293 if (project.clone) project.clone(moveToTarget);
294 else moveToTarget(project.projectId ?? suggestedProject);
295 }}
296 >
297 {project.clone ? (
298 gt`Add project and move`
299 ) : toLink === undefined ? (
300 <T>Move</T>
301 ) : (
302 <T>Link and move</T>
303 )}
304 </Button>
305 </div>
306 </section>
307 );