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