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 if (launch === null || launchedRef.current === launch) return;
271 launchedRef.current = launch;
272 runLaunch(launch);
273 }, [launch]);
274
275 switch (state.status) {
276 case "opening":
277 return <LinkPage title="Opening the link..." />;
278 case "opened":
279 return (
280 <LinkPage title="This link is open">
281 <Button
282 size="sm"
283 variant="outline"
284 onClick={() => {
285 openedLinkKeys.delete(locationKey);
286 setStarted(false);
287 setState({ status: "opening" });
288 }}
289 >
290 Open it again
291 </Button>
292 </LinkPage>
293 );
294 case "failed":
295 return (
296 <LinkPage title={state.title ?? "Could not open the link"} description={state.message} />
297 );
298 case "missing-repository": {
299 const name = `${state.repository.owner}/${state.repository.name}`;
300 return (
301 <LinkPage
302 title={`You don't have ${name}`}
303 description="Clone it to work on it here, or start without a project."
304 >
305 <Button size="sm" onClick={() => void cloneRepository(state.repository)}>
306 Clone {name}
307 </Button>
308 <Button size="sm" variant="outline" onClick={openWithoutProject}>
309 Use without project
310 </Button>
311 </LinkPage>
312 );
313 }
314 case "pull-request-checkout":
315 return link.kind === "pull-request" ? (
316 <PullRequestLinkCheckout link={link} project={state.project} />
317 ) : null;
318 }
319}
320
321/** Checkout runs setup from PR code, so links alone must not start it. */
322function PullRequestLinkCheckout({
323 link,
324 project,
325}: {
326 readonly link: Extract<NewThreadLink, { kind: "pull-request" }>;
327 readonly project: EnvironmentProject;
328}) {
329 const { handoff, startHandoff } = usePullRequestHandoffs({
330 environmentId: project.environmentId,
331 detail: {
332 projectId: project.id,
333 workspaceRoot: project.workspaceRoot,
334 url: promptLinkPullRequestUrl(link.pullRequest),
335 },
336 });
337 const warnedRef = useRef(false);
338 useEffect(() => {
339 if (warnedRef.current || link.prompt === null) return;
340 warnedRef.current = true;
341 warnAboutHiddenCharacters(link.prompt);
342 }, [link.prompt]);
343 const { owner, name, number } = link.pullRequest;
344 return (
345 <LinkPage
346 title={`Check out ${owner}/${name}#${number}?`}
347 description="This puts the pull request's code in a new worktree and runs your project's setup script on it."
348 >
349 <Button
350 size="sm"
351 disabled={handoff !== null}
352 onClick={() =>
353 void startHandoff(
354 "prompt-link",
355 link.prompt === null ? null : { prompt: link.prompt.text },
356 )
357 }
358 >
359 {handoff !== null ? "Checking out..." : "Check out"}
360 </Button>
361 </LinkPage>
362 );
363}
364
365function LinkPage({
366 title,
367 description,
368 children,
369}: {
370 readonly title: string;
371 readonly description?: string;
372 readonly children?: ReactNode;
373}) {
374 return (
375 <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none">
376 {isElectron ? <WorkspacePageHeader electron /> : null}
377 <Empty className="flex-1">
378 <EmptyHeader className="max-w-md">
379 <EmptyTitle>{title}</EmptyTitle>
380 {description ? <EmptyDescription>{description}</EmptyDescription> : null}
381 {children ? <div className="mt-5 flex justify-center gap-2">{children}</div> : null}
382 </EmptyHeader>
383 </Empty>
384 </SidebarInset>
385 );
386}