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

ThreadHandoffBanner.tsx

246 lines9.1 KB

1import { useAtomValue } from "@effect/atom-react";
2import { scopeThreadRef } from "@t3tools/client-runtime/environment";
3import {
4 threadAwaitsAdoption,
5 threadHandoffClosesComposer,
6} from "@t3tools/client-runtime/state/peerLinks";
7import {
8 isAtomCommandInterrupted,
9 squashAtomCommandFailure,
10} from "@t3tools/client-runtime/state/runtime";
11import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
12import { Navigate, useNavigate } from "@tanstack/react-router";
13import { msg, useGT } from "gt-react";
14import { ArrowUpRightIcon, MonitorUpIcon, TriangleAlertIcon } from "lucide-react";
15import { useState } from "react";
16​
17import { m, type MessageResolver } from "~/i18n/messages";
18import { appAtomRegistry } from "~/rpc/atomRegistry";
19import { useConnectedEnvironmentIds } from "~/state/environments";
20import {
21 canMoveThreadsAtom,
22 dismissedThreadHandoffsAtom,
23 openThreadHandoffDialog,
24 threadHandoffEnvironment,
25} from "~/state/threadHandoff";
26import { useAtomCommand } from "~/state/use-atom-command";
27import { linkedThreadRouteParams } from "../../linkedThreadSurface";
28import { buildThreadRouteParams } from "../../threadRoutes";
29import { Button } from "../ui/button";
30import { stackedThreadToast, toastManager } from "../ui/toast";
31import type { ComposerBannerStackItem } from "./ComposerBannerStack";
32​
33type HandoffShell = Pick<EnvironmentThreadShell, "environmentId" | "id" | "handoff"> & {
34 readonly linkOrigin?: EnvironmentThreadShell["linkOrigin"];
35};
36​
37/** Why the composer is closed while a thread moves away, or null when it is open. */
38export function threadHandoffSendBlockReason(
39 shell: Pick<EnvironmentThreadShell, "handoff"> | null | undefined,
40 resolve: MessageResolver = m,
41): string | null {
42 const handoff = shell?.handoff;
43 if (!threadHandoffClosesComposer(handoff)) return null;
44 return handoff.state === "departing"
45 ? resolve(msg`Moving to ${{ machine: handoff.label }}`)
46 : resolve(msg`Continues on ${{ machine: handoff.label }}`);
48​
49/**
50 * Takes the client to where a moved thread continues, so the conversation reads as one thread:
51 * its own connection to that machine when it has one, else a view over the link that pairs
52 * with the machine by itself.
53 */
54export function ThreadHandoffFollower({
55 shell,
56}: {
57 readonly shell: HandoffShell | null | undefined;
58}) {
59 const connected = useConnectedEnvironmentIds();
60 const handoff = shell?.handoff;
61 if (shell == null || handoff?.state !== "departed") return null;
62 const there = scopeThreadRef(handoff.environmentId, handoff.threadId);
63 return connected.includes(handoff.environmentId) ? (
64 <Navigate to="/$environmentId/$threadId" params={buildThreadRouteParams(there)} replace />
65 ) : (
66 <Navigate
67 to="/linked/$viaEnvironmentId/$linkedEnvironmentId/$linkedThreadId"
68 params={linkedThreadRouteParams({ viaEnvironmentId: shell.environmentId, ...there })}
69 search={{ connect: true }}
70 replace
71 />
72 );
74​
75/**
76 * The notice for a thread's move to a linked machine: waiting (with a way to keep it here),
77 * under way, moved (with a way to open it there), or failed (with a way to try again).
78 */
79export function useThreadHandoffBannerItem(
80 shell: HandoffShell | null | undefined,
81): ComposerBannerStackItem | null {
82 const gt = useGT();
83 const navigate = useNavigate();
84 const cancel = useAtomCommand(threadHandoffEnvironment.cancel, { reportFailure: false });
85 const adopt = useAtomCommand(threadHandoffEnvironment.adopt, { reportFailure: false });
86 const [adopting, setAdopting] = useState(false);
87 const [cancelling, setCancelling] = useState(false);
88 const connected = useConnectedEnvironmentIds();
89 const dismissed = useAtomValue(dismissedThreadHandoffsAtom);
90 const canMove = useAtomValue(
91 canMoveThreadsAtom(shell?.environmentId ?? ("" as HandoffShell["environmentId"])),
92 );
93 // Adopting is local to this machine, so it does not need linked environments switched on.
94 const canAdopt = useAtomValue(
95 threadHandoffEnvironment.adopt.permissionAtom(shell?.environmentId ?? null),
96 );
97 const handoff = shell?.handoff ?? null;
98 if (shell != null && handoff === null && threadAwaitsAdoption(shell)) {
99 const origin = shell.linkOrigin?.label ?? "";
100 return {
101 id: `thread-handoff:${shell.id}:adopt`,
102 variant: "info",
103 icon: <MonitorUpIcon />,
104 title: gt`This thread was moved here over a limited link`,
105 description: gt`Its agent can change only what ${{ origin }} started here and cannot use this machine's links, until you make it a normal thread.`,
106 ...(canAdopt
107 ? {
108 actions: (
109 <Button
110 size="xs"
111 variant="ghost"
112 disabled={adopting}
113 onClick={() => {
114 setAdopting(true);
115 void adopt({
116 environmentId: shell.environmentId,
117 input: { threadId: shell.id },
118 }).then((result) => {
119 setAdopting(false);
120 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
121 const error = squashAtomCommandFailure(result);
122 toastManager.add(
123 stackedThreadToast({
124 type: "error",
125 title: gt`Could not make it a normal thread`,
126 ...(error instanceof Error ? { description: error.message } : {}),
127 }),
128 );
129 });
130 }}
131 >
132 {gt`Make it a normal thread`}
133 </Button>
134 ),
135 }
136 : {}),
137 };
138 }
139 if (shell == null || handoff === null) return null;
140 const id = `thread-handoff:${shell.id}:${handoff.handoffId}:${handoff.state}`;
141 const icon = <MonitorUpIcon />;
142 const machine = handoff.label;
143 switch (handoff.state) {
144 case "pending":
145 return {
146 id,
147 variant: "info",
148 icon,
149 title: gt`Moving to ${{ machine }} when this turn ends`,
150 description: gt`Sending a message keeps it here instead.`,
151 actions: (
152 <Button
153 size="xs"
154 variant="ghost"
155 disabled={cancelling || !canMove}
156 onClick={() => {
157 setCancelling(true);
158 void cancel({
159 environmentId: shell.environmentId,
160 input: { threadId: shell.id },
161 }).then((result) => {
162 setCancelling(false);
163 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
164 const error = squashAtomCommandFailure(result);
165 toastManager.add(
166 stackedThreadToast({
167 type: "error",
168 title: gt`Could not cancel the move`,
169 ...(error instanceof Error ? { description: error.message } : {}),
170 }),
171 );
172 });
173 }}
174 >
175 {gt`Keep it here`}
176 </Button>
177 ),
178 };
179 case "departing":
180 return { id, variant: "info", icon, title: gt`Moving to ${{ machine }}…` };
181 case "departed": {
182 const there = scopeThreadRef(handoff.environmentId, handoff.threadId);
183 return {
184 id,
185 variant: "info",
186 icon,
187 title: gt`This thread continues on ${{ machine }}`,
188 description: gt`This copy is read-only.`,
189 actions: (
190 <Button
191 size="xs"
192 variant="ghost"
193 onClick={() =>
194 // Without a connection to that machine, this one reads the thread over its link.
195 void (connected.includes(handoff.environmentId)
196 ? navigate({
197 to: "/$environmentId/$threadId",
198 params: buildThreadRouteParams(there),
199 })
200 : navigate({
201 to: "/linked/$viaEnvironmentId/$linkedEnvironmentId/$linkedThreadId",
202 params: linkedThreadRouteParams({
203 viaEnvironmentId: shell.environmentId,
204 ...there,
205 }),
206 }))
207 }
208 >
209 {gt`Open on ${{ machine }}`}
210 <ArrowUpRightIcon />
211 </Button>
212 ),
213 };
214 }
215 case "failed":
216 if (dismissed.has(handoff.handoffId)) return null;
217 return {
218 id,
219 variant: "error",
220 icon: <TriangleAlertIcon />,
221 title: gt`Could not move to ${{ machine }}`,
222 description: handoff.lastError,
223 ...(canMove
224 ? {
225 actions: (
226 <Button
227 size="xs"
228 variant="ghost"
229 onClick={() =>
230 openThreadHandoffDialog(scopeThreadRef(shell.environmentId, shell.id))
231 }
232 >
233 {gt`Try again`}
234 </Button>
235 ),
236 }
237 : {}),
238 dismissLabel: gt`Dismiss`,
239 onDismiss: () =>
240 appAtomRegistry.set(
241 dismissedThreadHandoffsAtom,
242 new Set([...dismissed, handoff.handoffId]),
243 ),
244 };
245 }