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