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