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

main
tsx 236 lines 8.22 KB
Raw
1 import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2 import { useParams } from "@tanstack/react-router";
3 import { scopeProjectRef } from "@t3tools/client-runtime/environment";
4 import {
5 type AtomCommandResult,
6 isAtomCommandInterrupted,
7 squashAtomCommandFailure,
8 } from "@t3tools/client-runtime/state/runtime";
9 import {
10 projectCloneDisplayName,
11 type EnvironmentId,
12 type ProjectCloneSnapshot,
13 type ProjectId,
14 } from "@t3tools/contracts";
15 import { projectCloneProgressSummary } from "@t3tools/client-runtime/contract-labels";
16 import { useEffect, useRef } from "react";
17 import { msg } from "gt-react";
18
19 import { m } from "../i18n/messages";
20 import { useNewThreadHandler } from "../hooks/useHandleNewThread";
21 import { useRemoveClonedProject } from "../hooks/useRemoveClonedProject";
22 import { useEnvironments } from "../state/environments";
23 import {
24 isProjectCloneToastSilenced,
25 silenceProjectCloneToasts,
26 useEnvironmentProjectClones,
27 } from "../state/projectClones";
28 import { sourceControlEnvironment } from "../state/sourceControl";
29 import { useAtomCommand } from "../state/use-atom-command";
30 import { type DraftId, useComposerDraftStore } from "../composerDraftStore";
31 import { toastManager } from "./ui/toast";
32 import { stackedThreadToast } from "./ui/toastHelpers";
33
34 export function ProjectCloneToastCoordinator() {
35 const { environments } = useEnvironments();
36 return environments.map((environment) => (
37 <EnvironmentCloneToasts
38 key={environment.environmentId}
39 environmentId={environment.environmentId}
40 />
41 ));
42 }
43
44 interface TrackedToast {
45 readonly toastId: ReturnType<typeof toastManager.add>;
46 readonly renderedKey: string;
47 readonly phase: ProjectCloneSnapshot["phase"];
48 }
49
50 function renderKey(clone: ProjectCloneSnapshot): string {
51 return `${clone.phase}:${clone.stage}:${clone.percent ?? ""}:${clone.detail ?? ""}:${clone.stalled === true}:${clone.error ?? ""}`;
52 }
53
54 async function runCloneAction(
55 title: string,
56 action: () => Promise<AtomCommandResult<unknown, unknown>>,
57 ) {
58 const result = await action();
59 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
60 const error = squashAtomCommandFailure(result);
61 toastManager.add(
62 stackedThreadToast({
63 type: "error",
64 title,
65 description: thrownErrorMessage(error, m) ?? m(msg("An error occurred.")),
66 }),
67 );
68 }
69 }
70
71 function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentId }) {
72 const clones = useEnvironmentProjectClones(environmentId);
73 const handleNewThread = useNewThreadHandler();
74 const { draftId: routeDraftId } = useParams({ strict: false });
75 const cancelClone = useAtomCommand(sourceControlEnvironment.cancelProjectClone, {
76 reportFailure: false,
77 });
78 const retryClone = useAtomCommand(sourceControlEnvironment.retryProjectClone, {
79 reportFailure: false,
80 });
81 const removeClonedProject = useRemoveClonedProject();
82 const toasts = useRef(new Map<ProjectId, TrackedToast>());
83
84 const isViewingProjectDraft = (projectId: ProjectId) => {
85 if (!routeDraftId) return false;
86 const draft = useComposerDraftStore.getState().getDraftSession(routeDraftId as DraftId);
87 return draft?.environmentId === environmentId && draft.projectId === projectId;
88 };
89
90 const openProject = (projectId: ProjectId) => {
91 void handleNewThread(scopeProjectRef(environmentId, projectId));
92 };
93
94 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- opens, updates and closes imperative toastManager toasts to match the current project clones
95 useEffect(() => {
96 const seen = new Set<ProjectId>();
97 for (const clone of clones) {
98 seen.add(clone.projectId);
99 const key = renderKey(clone);
100 const tracked = toasts.current.get(clone.projectId);
101 const name = projectCloneDisplayName(clone);
102 const closeToast = () => {
103 const current = toasts.current.get(clone.projectId);
104 if (!current) return;
105 toastManager.close(current.toastId);
106 toasts.current.delete(clone.projectId);
107 };
108 const ref = { environmentId, projectId: clone.projectId };
109 if (isViewingProjectDraft(clone.projectId)) {
110 silenceProjectCloneToasts(ref);
111 closeToast();
112 continue;
113 }
114 if (tracked?.renderedKey === key) continue;
115 if (
116 isProjectCloneToastSilenced(ref) &&
117 (clone.phase === "running" || clone.phase === "done")
118 ) {
119 closeToast();
120 continue;
121 }
122
123 if (clone.phase === "running") {
124 const options = stackedThreadToast({
125 type: "loading",
126 title: m(msg("Cloning {name}", { name })),
127 description: projectCloneProgressSummary(clone, m),
128 timeout: 0,
129 actionProps: {
130 children: m(msg("Cancel")),
131 onClick: () => {
132 void runCloneAction(m(msg("Failed to cancel clone")), () =>
133 cancelClone({ environmentId, input: { projectId: clone.projectId } }),
134 );
135 },
136 },
137 data: { hideCopyButton: true },
138 });
139 if (tracked) {
140 toastManager.update(tracked.toastId, options);
141 toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: "running" });
142 } else {
143 const toastId = toastManager.add(options);
144 toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: "running" });
145 }
146 continue;
147 }
148
149 if (clone.phase === "done") {
150 const options = stackedThreadToast({
151 type: "success",
152 title: m(msg("Cloned {name}", { name })),
153 description: clone.destinationPath,
154 timeout: 8_000,
155 actionProps: {
156 children: m(msg("Open project")),
157 onClick: () => {
158 closeToast();
159 openProject(clone.projectId);
160 },
161 },
162 data: { hideCopyButton: true },
163 });
164 if (tracked) {
165 toastManager.update(tracked.toastId, options);
166 toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: "done" });
167 } else {
168 const toastId = toastManager.add(options);
169 toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: "done" });
170 }
171 continue;
172 }
173
174 const cancelled = clone.phase === "cancelled";
175 const options = stackedThreadToast({
176 type: cancelled ? "info" : "error",
177 title: cancelled
178 ? m(msg("Cancelled cloning {name}", { name }))
179 : m(msg("Failed to clone {name}", { name })),
180 description: cancelled
181 ? clone.destinationPath
182 : (clone.error ?? m(msg("The clone failed."))),
183 timeout: 0,
184 actionProps: {
185 children: m(msg("Retry")),
186 onClick: () => {
187 void runCloneAction(m(msg("Failed to retry clone")), () =>
188 retryClone({ environmentId, input: { projectId: clone.projectId } }),
189 );
190 },
191 },
192 data: {
193 ...(cancelled ? { hideCopyButton: true } : {}),
194 secondaryActionProps: {
195 children: m(msg("Remove project")),
196 onClick: () => {
197 void removeClonedProject({ environmentId, projectId: clone.projectId });
198 },
199 },
200 },
201 });
202 if (tracked) {
203 toastManager.update(tracked.toastId, options);
204 toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: clone.phase });
205 } else {
206 const toastId = toastManager.add(options);
207 toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: clone.phase });
208 }
209 }
210
211 for (const [projectId, tracked] of toasts.current) {
212 if (seen.has(projectId)) continue;
213 if (tracked.phase !== "done") toastManager.close(tracked.toastId);
214 toasts.current.delete(projectId);
215 }
216 }, [
217 cancelClone,
218 clones,
219 environmentId,
220 isViewingProjectDraft,
221 openProject,
222 removeClonedProject,
223 retryClone,
224 ]);
225
226 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- closes every tracked clone toast in toastManager when the coordinator unmounts
227 useEffect(
228 () => () => {
229 for (const tracked of toasts.current.values()) toastManager.close(tracked.toastId);
230 toasts.current.clear();
231 },
232 [],
233 );
234
235 return null;
236 }