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

NewThreadLinkView.tsx

359 lines12.5 KB

1import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
2import { getCloneDestinationPath } from "@t3tools/client-runtime/operations/projects";
3import {
4 findPromptLinkProject,
5 findPromptLinkPullRequestThread,
6 resolvePromptLinkModelSelection,
7} from "@t3tools/client-runtime/prompt-links";
8import {
9 isAtomCommandInterrupted,
10 squashAtomCommandFailure,
11} from "@t3tools/client-runtime/state/runtime";
12import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
13import {
14 type NewThreadLink,
15 type PromptLinkRepository,
16 promptLinkPullRequestUrl,
17} from "@t3tools/shared/promptLinks";
18import { useAtomValue } from "@effect/atom-react";
19import { useLocation, useNavigate } from "@tanstack/react-router";
20import { type ReactNode, useEffect, useEffectEvent, useRef, useState } from "react";
21​
22import { useComposerDraftStore } from "~/composerDraftStore";
23import { isElectron } from "~/env";
24import { useNewThreadHandler } from "~/hooks/useHandleNewThread";
25import { useScratchProject } from "~/hooks/useScratchProject";
26import { newProjectId } from "~/lib/utils";
27import { useProjects, useThreadShells, waitForProject } from "~/state/entities";
28import { useEnvironments, usePrimaryEnvironmentId } from "~/state/environments";
29import { allReachableShellsLiveAtom } from "~/state/shell";
30import { sourceControlEnvironment } from "~/state/sourceControl";
31import { useAtomCommand } from "~/state/use-atom-command";
32​
33import { usePullRequestHandoffs } from "../pullRequest/usePullRequestActions";
34import { sortScopedProjectsForSidebar } from "../Sidebar.logic";
35import { Button } from "../ui/button";
36import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "../ui/empty";
37import { SidebarInset } from "../ui/sidebar";
38import { stackedThreadToast, toastManager } from "../ui/toast";
39import { WorkspacePageHeader } from "../WorkspacePageHeader";
40import { placeLinkedPrompt, warnAboutHiddenCharacters } from "./linkedPrompt";
41​
42type LinkState =
43 | { readonly status: "opening" }
44 | { readonly status: "opened" }
45 | { readonly status: "failed"; readonly message: string; readonly title?: string }
46 | { readonly status: "missing-repository"; readonly repository: PromptLinkRepository }
47 | {
48 readonly status: "pull-request-checkout";
49 readonly project: EnvironmentProject;
50 };
51​
52const openedLinkKeys = new Set<string>();
53​
54export function NewThreadLinkView({ link }: { readonly link: NewThreadLink }) {
55 const locationKey = useLocation({ select: (location) => location.state.__TSR_key ?? "" });
56 const navigate = useNavigate();
57 const ready = useAtomValue(allReachableShellsLiveAtom);
58 const projects = useProjects();
59 const threads = useThreadShells();
60 const { environments } = useEnvironments();
61 const primaryEnvironmentId = usePrimaryEnvironmentId();
62 const handleNewThread = useNewThreadHandler();
63 const { scratchEnvironmentId, openScratchProject } = useScratchProject();
64 const startProjectClone = useAtomCommand(sourceControlEnvironment.startProjectClone, {
65 reportFailure: false,
66 });
67 const [state, setState] = useState<LinkState>(() =>
68 openedLinkKeys.has(locationKey) ? { status: "opened" } : { status: "opening" },
69 );
70 const startedRef = useRef(false);
71​
72 const recentProjects = () =>
73 sortScopedProjectsForSidebar(
74 projects.filter((project) => project.isScratch !== true),
75 threads,
76 "updated_at",
77 );
78​
79 const lastActiveEnvironmentId = () => {
80 let latest: (typeof threads)[number] | undefined;
81 for (const thread of threads) {
82 if (latest === undefined || thread.updatedAt > latest.updatedAt) latest = thread;
83 }
84 return latest?.environmentId ?? primaryEnvironmentId;
85 };
86​
87 const openDraft = async (project: EnvironmentProject, extraPrompt?: string) => {
88 const opened = await handleNewThread(scopeProjectRef(project.environmentId, project.id), {
89 replace: true,
90 }).catch(() => null);
91 if (opened === null) {
92 setState({ status: "failed", message: "T3 Code could not open a new thread." });
93 return;
94 }
95 setState({ status: "opened" });
96 const notes: Array<string> = [];
97 if (link.kind === "new" && link.provider !== null) {
98 const providers =
99 environments.find((environment) => environment.environmentId === project.environmentId)
100 ?.serverConfig?.providers ?? [];
101 const resolved = resolvePromptLinkModelSelection(providers, {
102 provider: link.provider,
103 model: link.model,
104 });
105 if (resolved !== null) {
106 useComposerDraftStore.getState().setModelSelection(opened.draftId, resolved.selection, {
107 explicit: true,
108 replaceOptions: true,
109 });
110 }
111 if (resolved === null || !resolved.exact) {
112 notes.push(
113 resolved === null
114 ? `The link asked for ${link.provider}, which is not set up here, so your default model is used.`
115 : `The link asked for ${link.model}, which ${link.provider} does not offer here, so its default model is used.`,
116 );
117 }
118 }
119 const text = [link.prompt?.text, extraPrompt].filter(Boolean).join("\n\n");
120 if (text.length === 0) return;
121 placeLinkedPrompt(
122 opened.draftId,
123 { text, hiddenCharacters: link.prompt?.hiddenCharacters ?? 0 },
124 notes,
125 );
126 };
127​
128 const openWithoutProject = async () => {
129 setState({ status: "opening" });
130 const environmentId =
131 scratchEnvironmentId(lastActiveEnvironmentId()) ?? scratchEnvironmentId(null);
132 const project = environmentId === null ? null : await openScratchProject(environmentId);
133 if (project === null) {
134 setState({
135 status: "failed",
136 message: "None of your machines can start a thread without a project right now.",
137 });
138 return;
139 }
140 await openDraft(
141 project,
142 link.kind === "pull-request" ? promptLinkPullRequestUrl(link.pullRequest) : undefined,
143 );
144 };
145​
146 const cloneRepository = async (repository: PromptLinkRepository) => {
147 const environmentId = lastActiveEnvironmentId();
148 const environment = environments.find((entry) => entry.environmentId === environmentId);
149 const newProjectsRoot = environment?.serverConfig?.newProjectsRoot ?? null;
150 if (
151 environmentId === null ||
152 newProjectsRoot === null ||
153 environment?.serverConfig?.environment.capabilities.projectCloneTracking !== true
154 ) {
155 setState({
156 status: "failed",
157 message:
158 "This machine cannot clone from a link. Update T3 Code on it, or clone the repository from the command palette.",
159 });
160 return;
161 }
162 setState({ status: "opening" });
163 const projectId = newProjectId();
164 const result = await startProjectClone({
165 environmentId,
166 input: {
167 projectId,
168 title: repository.name,
169 createdAt: new Date().toISOString(),
170 remoteUrl: `https://github.com/${repository.owner}/${repository.name}.git`,
171 destinationPath: getCloneDestinationPath(newProjectsRoot, repository.name),
172 },
173 });
174 if (result._tag === "Failure") {
175 if (!isAtomCommandInterrupted(result)) {
176 const error = squashAtomCommandFailure(result);
177 toastManager.add(
178 stackedThreadToast({
179 type: "error",
180 title: "Clone failed",
181 description: error instanceof Error ? error.message : "An error occurred.",
182 }),
183 );
184 }
185 setState({ status: "missing-repository", repository });
186 return;
187 }
188 const project = await waitForProject(scopeProjectRef(environmentId, projectId), 5_000).catch(
189 () => null,
190 );
191 if (project === null) {
192 setState({ status: "failed", message: "The clone started, but its project did not appear." });
193 return;
194 }
195 if (link.kind === "pull-request") {
196 setState({
197 status: "failed",
198 title: `Cloning ${repository.owner}/${repository.name}`,
199 message: "Open this link again when the clone finishes.",
200 });
201 return;
202 }
203 await openDraft(project);
204 };
205​
206 const start = useEffectEvent(() => {
207 if (startedRef.current) return;
208 startedRef.current = true;
209 openedLinkKeys.add(locationKey);
210 if (link.kind === "pull-request") {
211 const thread = findPromptLinkPullRequestThread(threads, link.pullRequest);
212 if (thread !== undefined) {
213 setState({ status: "opened" });
214 const threadRef = scopeThreadRef(thread.environmentId, thread.id);
215 if (link.prompt !== null) placeLinkedPrompt(threadRef, link.prompt);
216 void navigate({
217 to: "/$environmentId/$threadId",
218 params: { environmentId: thread.environmentId, threadId: thread.id },
219 replace: true,
220 });
221 return;
222 }
223 }
224 const repository = link.kind === "new" ? link.repository : link.pullRequest;
225 if (repository === null) {
226 void openWithoutProject();
227 return;
228 }
229 const project = findPromptLinkProject(recentProjects(), repository);
230 if (project === undefined) {
231 setState({ status: "missing-repository", repository });
232 return;
233 }
234 if (link.kind === "pull-request") {
235 setState({ status: "pull-request-checkout", project });
236 return;
237 }
238 void openDraft(project);
239 });
240​
241 useEffect(() => {
242 if (ready && state.status === "opening") start();
243 }, [ready, state.status]);
244​
245 switch (state.status) {
246 case "opening":
247 return <LinkPage title="Opening the link..." />;
248 case "opened":
249 return (
250 <LinkPage title="This link is open">
251 <Button
252 size="sm"
253 variant="outline"
254 onClick={() => {
255 openedLinkKeys.delete(locationKey);
256 startedRef.current = false;
257 setState({ status: "opening" });
258 }}
259 >
260 Open it again
261 </Button>
262 </LinkPage>
263 );
264 case "failed":
265 return (
266 <LinkPage title={state.title ?? "Could not open the link"} description={state.message} />
267 );
268 case "missing-repository": {
269 const name = `${state.repository.owner}/${state.repository.name}`;
270 return (
271 <LinkPage
272 title={`You don't have ${name}`}
273 description="Clone it to work on it here, or start without a project."
274 >
275 <Button size="sm" onClick={() => void cloneRepository(state.repository)}>
276 Clone {name}
277 </Button>
278 <Button size="sm" variant="outline" onClick={() => void openWithoutProject()}>
279 Use without project
280 </Button>
281 </LinkPage>
282 );
283 }
284 case "pull-request-checkout":
285 return link.kind === "pull-request" ? (
286 <PullRequestLinkCheckout link={link} project={state.project} />
287 ) : null;
288 }
290​
291/**
292 * The checkout runs the project's setup script on code from the pull request, so a link alone
293 * never starts it.
294 */
295function PullRequestLinkCheckout({
296 link,
297 project,
298}: {
299 readonly link: Extract<NewThreadLink, { kind: "pull-request" }>;
300 readonly project: EnvironmentProject;
301}) {
302 const { handoff, startHandoff } = usePullRequestHandoffs({
303 environmentId: project.environmentId,
304 detail: {
305 projectId: project.id,
306 workspaceRoot: project.workspaceRoot,
307 url: promptLinkPullRequestUrl(link.pullRequest),
308 },
309 });
310 const warnedRef = useRef(false);
311 useEffect(() => {
312 if (warnedRef.current || link.prompt === null) return;
313 warnedRef.current = true;
314 warnAboutHiddenCharacters(link.prompt);
315 }, [link.prompt]);
316 const { owner, name, number } = link.pullRequest;
317 return (
318 <LinkPage
319 title={`Check out ${owner}/${name}#${number}?`}
320 description="This puts the pull request's code in a new worktree and runs your project's setup script on it."
321 >
322 <Button
323 size="sm"
324 disabled={handoff !== null}
325 onClick={() =>
326 void startHandoff(
327 "prompt-link",
328 link.prompt === null ? null : { prompt: link.prompt.text },
329 )
330 }
331 >
332 {handoff !== null ? "Checking out..." : "Check out"}
333 </Button>
334 </LinkPage>
335 );
337​
338function LinkPage({
339 title,
340 description,
341 children,
342}: {
343 readonly title: string;
344 readonly description?: string;
345 readonly children?: ReactNode;
346}) {
347 return (
348 <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none">
349 {isElectron ? <WorkspacePageHeader electron /> : null}
350 <Empty className="flex-1">
351 <EmptyHeader className="max-w-md">
352 <EmptyTitle>{title}</EmptyTitle>
353 {description ? <EmptyDescription>{description}</EmptyDescription> : null}
354 {children ? <div className="mt-5 flex justify-center gap-2">{children}</div> : null}
355 </EmptyHeader>
356 </Empty>
357 </SidebarInset>
358 );