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