Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

NewThreadLinkView.tsx

447 lines16.2 KB

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 { suggestAppAccessForRemote } from "../sourceControlAppAccessToast";
46import { WorkspacePageHeader } from "../WorkspacePageHeader";
47import { placeLinkedPrompt, warnAboutHiddenCharacters } from "./linkedPrompt";
48​
49type LinkState =
50 | { readonly status: "opening" }
51 | { readonly status: "opened" }
52 | { readonly status: "failed"; readonly message: string; readonly title?: string }
53 | { readonly status: "missing-repository"; readonly repository: PromptLinkRepository }
54 | {
55 readonly status: "pull-request-checkout";
56 readonly project: EnvironmentProject;
57 };
58​
59type LinkLaunch =
60 | {
61 readonly kind: "thread";
62 readonly thread: Pick<ReturnType<typeof useThreadShells>[number], "environmentId" | "id">;
63 }
64 | { readonly kind: "draft"; readonly project: EnvironmentProject }
65 | { readonly kind: "scratch" }
66 | { readonly kind: "settled" };
67​
68const openedLinkKeys = new Set<string>();
69​
70type PullRequestThreadLookup = {
71 readonly targets: ReadonlyArray<readonly [environmentId: EnvironmentId, projectId: ProjectId]>;
72 readonly repository: string;
73 readonly number: number;
74};
75​
76// A pull request's thread can be an older settled thread no shell holds, so ask every
77// environment with the repository.
78const pullRequestThreadLookupAtom = Atom.family((key: string) => {
79 const { targets, repository, number } = JSON.parse(key) as PullRequestThreadLookup;
80 return Atom.make((get) =>
81 pickPromptLinkPullRequestThread(
82 targets
83 // A shell that is not live cannot answer, and its lookup would wait forever.
84 .filter(([environmentId]) => get(environmentShell.statusAtom(environmentId)) === "live")
85 .map(([environmentId, projectId]) => ({
86 environmentId,
87 result: get(
88 pullRequestEnvironment.linkedThreadsUncached({
89 environmentId,
90 input: { projectId, repository, number },
91 }),
92 ),
93 })),
94 ),
95 ).pipe(Atom.withLabel(`web-prompt-link-pull-request-thread:${key}`));
96});
97​
98const NO_PULL_REQUEST_THREAD_LOOKUP = Atom.make(null);
99​
100export function NewThreadLinkView({ link }: { readonly link: NewThreadLink }) {
101 const locationKey = useLocation({ select: (location) => location.state.__TSR_key ?? "" });
102 const navigate = useNavigate();
103 const ready = useAtomValue(allReachableShellsLiveAtom);
104 const projects = useProjects();
105 const threads = useThreadShells();
106 const { environments } = useEnvironments();
107 const primaryEnvironmentId = usePrimaryEnvironmentId();
108 const handleNewThread = useNewThreadHandler();
109 const { scratchEnvironmentId, openScratchProject } = useScratchProject();
110 const startProjectClone = useAtomCommand(sourceControlEnvironment.startProjectClone, {
111 reportFailure: false,
112 });
113 const [state, setState] = useState<LinkState>(() =>
114 openedLinkKeys.has(locationKey) ? { status: "opened" } : { status: "opening" },
115 );
116 const [started, setStarted] = useState(false);
117 const [launch, setLaunch] = useState<LinkLaunch | null>(null);
118 const launchedRef = useRef<LinkLaunch | null>(null);
119​
120 const recentProjects = () =>
121 sortScopedProjectsForSidebar(
122 projects.filter((project) => project.isScratch !== true),
123 threads,
124 "updated_at",
125 );
126​
127 const lastActiveEnvironmentId = () => {
128 let latest: (typeof threads)[number] | undefined;
129 for (const thread of threads) {
130 if (latest === undefined || thread.updatedAt > latest.updatedAt) latest = thread;
131 }
132 return latest?.environmentId ?? primaryEnvironmentId;
133 };
134​
135 const openDraft = async (project: EnvironmentProject, extraPrompt?: string) => {
136 const opened = await handleNewThread(scopeProjectRef(project.environmentId, project.id), {
137 replace: true,
138 }).catch(() => null);
139 if (opened === null) {
140 setState({ status: "failed", message: "T3 Code could not open a new thread." });
141 return;
142 }
143 setState({ status: "opened" });
144 const notes: Array<string> = [];
145 if (link.kind === "new" && link.provider !== null) {
146 const providers =
147 appAtomRegistry
148 .get(environmentPresentations.providersByEnvironmentAtom)
149 .get(project.environmentId) ?? [];
150 const resolved = resolvePromptLinkModelSelection(providers, {
151 provider: link.provider,
152 model: link.model,
153 });
154 if (resolved !== null) {
155 useComposerDraftStore.getState().setModelSelection(opened.draftId, resolved.selection, {
156 explicit: true,
157 replaceOptions: true,
158 });
159 }
160 if (resolved === null || !resolved.exact) {
161 notes.push(
162 resolved === null
163 ? `The link asked for ${link.provider}, which is not set up here, so your default model is used.`
164 : `The link asked for ${link.model}, which ${link.provider} does not offer here, so its default model is used.`,
165 );
166 }
167 }
168 const text = [link.prompt?.text, extraPrompt].filter(Boolean).join("\n\n");
169 if (text.length === 0) return;
170 placeLinkedPrompt(
171 opened.draftId,
172 { text, hiddenCharacters: link.prompt?.hiddenCharacters ?? 0 },
173 notes,
174 );
175 };
176​
177 const openScratchDraft = async () => {
178 const environmentId = scratchEnvironmentId(lastActiveEnvironmentId());
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 (environmentId === null || newProjectsRoot === null) {
203 setState({
204 status: "failed",
205 message:
206 "This machine cannot clone from a link. Update T3 Code on it, or clone the repository from the command palette.",
207 });
208 return;
209 }
210 setState({ status: "opening" });
211 const projectId = newProjectId();
212 const result = await startProjectClone({
213 environmentId,
214 input: {
215 projectId,
216 title: repository.name,
217 createdAt: new Date().toISOString(),
218 remoteUrl: `https://github.com/${repository.owner}/${repository.name}.git`,
219 destinationPath: getCloneDestinationPath(newProjectsRoot, repository.name),
220 },
221 });
222 if (result._tag === "Failure") {
223 if (!isAtomCommandInterrupted(result)) {
224 const error = squashAtomCommandFailure(result);
225 toastManager.add(
226 stackedThreadToast({
227 type: "error",
228 title: "Clone failed",
229 description: error instanceof Error ? error.message : "An error occurred.",
230 }),
231 );
232 }
233 setState({ status: "missing-repository", repository });
234 return;
235 }
236 void suggestAppAccessForRemote(
237 environmentId,
238 `https://github.com/${repository.owner}/${repository.name}.git`,
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 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- runs each launch decision once: navigates to the thread or opens a draft
329 useEffect(() => {
330 if (launch === null || launchedRef.current === launch) return;
331 launchedRef.current = launch;
332 runLaunch(launch);
333 }, [launch]);
334​
335 switch (state.status) {
336 case "opening":
337 return <LinkPage title="Opening the link..." />;
338 case "opened":
339 return (
340 <LinkPage title="This link is open">
341 <Button
342 size="sm"
343 variant="outline"
344 onClick={() => {
345 openedLinkKeys.delete(locationKey);
346 setStarted(false);
347 setState({ status: "opening" });
348 }}
349 >
350 Open it again
351 </Button>
352 </LinkPage>
353 );
354 case "failed":
355 return (
356 <LinkPage title={state.title ?? "Could not open the link"} description={state.message} />
357 );
358 case "missing-repository": {
359 const name = `${state.repository.owner}/${state.repository.name}`;
360 return (
361 <LinkPage
362 title={`You don't have ${name}`}
363 description="Clone it to work on it here, or start without a project."
364 >
365 <Button size="sm" onClick={() => void cloneRepository(state.repository)}>
366 Clone {name}
367 </Button>
368 <Button size="sm" variant="outline" onClick={openWithoutProject}>
369 Use without project
370 </Button>
371 </LinkPage>
372 );
373 }
374 case "pull-request-checkout":
375 return link.kind === "pull-request" ? (
376 <PullRequestLinkCheckout link={link} project={state.project} />
377 ) : null;
378 }
380​
381/** Checkout runs setup from PR code, so links alone must not start it. */
382function PullRequestLinkCheckout({
383 link,
384 project,
385}: {
386 readonly link: Extract<NewThreadLink, { kind: "pull-request" }>;
387 readonly project: EnvironmentProject;
388}) {
389 const { handoff, startHandoff } = usePullRequestHandoffs({
390 environmentId: project.environmentId,
391 detail: {
392 projectId: project.id,
393 workspaceRoot: project.workspaceRoot,
394 url: promptLinkPullRequestUrl(link.pullRequest),
395 },
396 });
397 const warnedRef = useRef(false);
398 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- shows the hidden-characters warning toast once per linked prompt
399 useEffect(() => {
400 if (warnedRef.current || link.prompt === null) return;
401 warnedRef.current = true;
402 warnAboutHiddenCharacters(link.prompt);
403 }, [link.prompt]);
404 const { owner, name, number } = link.pullRequest;
405 return (
406 <LinkPage
407 title={`Check out ${owner}/${name}#${number}?`}
408 description="This puts the pull request's code in a new worktree and runs your project's setup script on it."
409 >
410 <Button
411 size="sm"
412 disabled={handoff !== null}
413 onClick={() =>
414 void startHandoff(
415 "prompt-link",
416 link.prompt === null ? null : { prompt: link.prompt.text },
417 )
418 }
419 >
420 {handoff !== null ? "Checking out..." : "Check out"}
421 </Button>
422 </LinkPage>
423 );
425​
426function LinkPage({
427 title,
428 description,
429 children,
430}: {
431 readonly title: string;
432 readonly description?: string;
433 readonly children?: ReactNode;
434}) {
435 return (
436 <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none">
437 {isElectron ? <WorkspacePageHeader electron /> : null}
438 <Empty className="flex-1">
439 <EmptyHeader className="max-w-md">
440 <EmptyTitle>{title}</EmptyTitle>
441 {description ? <EmptyDescription>{description}</EmptyDescription> : null}
442 {children ? <div className="mt-5 flex justify-center gap-2">{children}</div> : null}
443 </EmptyHeader>
444 </Empty>
445 </SidebarInset>
446 );