@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 481 lines 17.2 KB
Raw
1 import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2 import { m } from "~/i18n/messages";
3 import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
4 import {
5 getAddProjectInitialQuery,
6 getCloneDestinationPath,
7 getCloneDirectoryPath,
8 } from "@t3tools/client-runtime/operations/projects";
9 import {
10 findPromptLinkProjects,
11 findPromptLinkPullRequestThread,
12 pickPromptLinkPullRequestThread,
13 resolvePromptLinkModelSelection,
14 } from "@t3tools/client-runtime/prompt-links";
15 import {
16 isAtomCommandInterrupted,
17 squashAtomCommandFailure,
18 } from "@t3tools/client-runtime/state/runtime";
19 import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
20 import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
21 import {
22 type NewThreadLink,
23 type PromptLinkRepository,
24 promptLinkPullRequestUrl,
25 } from "@t3tools/shared/promptLinks";
26 import { useAtomValue } from "@effect/atom-react";
27 import { useLocation, useNavigate } from "@tanstack/react-router";
28 import { Atom } from "effect/reactivity";
29 import { T, useGT } from "gt-react";
30 import { type ReactNode, useEffect, useEffectEvent, useRef, useState } from "react";
31
32 import { useComposerDraftStore } from "~/composerDraftStore";
33 import { isElectron } from "~/env";
34 import { useNewThreadHandler } from "~/hooks/useHandleNewThread";
35 import { useScratchProject } from "~/hooks/useScratchProject";
36 import { newProjectId } from "~/lib/utils";
37 import { useProjects, useThreadShells, waitForProject } from "~/state/entities";
38 import { appAtomRegistry } from "~/rpc/atomRegistry";
39 import { useEnvironments, usePrimaryEnvironmentId } from "~/state/environments";
40 import { environmentPresentations } from "~/state/presentation";
41 import { allReachableShellsLiveAtom, environmentShell } from "~/state/shell";
42 import { sourceControlEnvironment } from "~/state/sourceControl";
43 import { pullRequestEnvironment } from "~/state/pullRequests";
44 import { useAtomCommand } from "~/state/use-atom-command";
45
46 import { usePullRequestHandoffs } from "../pullRequest/usePullRequestActions";
47 import { sortScopedProjectsForSidebar } from "../Sidebar.logic";
48 import { Button } from "../ui/button";
49 import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "../ui/empty";
50 import { SidebarInset } from "../ui/sidebar";
51 import { stackedThreadToast, toastManager } from "../ui/toast";
52 import { suggestAppAccessForRemote } from "../sourceControlAppAccessToast";
53 import { WorkspacePageHeader } from "../WorkspacePageHeader";
54 import { placeLinkedPrompt, warnAboutHiddenCharacters } from "./linkedPrompt";
55
56 type 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
66 type 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
75 const openedLinkKeys = new Set<string>();
76
77 type 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.
85 const 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
105 const NO_PULL_REQUEST_THREAD_LOOKUP = Atom.make(null);
106
107 export 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(
172 "The link asked for {provider}, which is not set up here, so your default model is used.",
173 { provider: link.provider },
174 )
175 : gt(
176 "The link asked for {model}, which {provider} does not offer here, so its default model is used.",
177 { model: link.model, provider: link.provider },
178 ),
179 );
180 }
181 }
182 const text = [link.prompt?.text, extraPrompt].filter(Boolean).join("\n\n");
183 if (text.length === 0) return;
184 placeLinkedPrompt(
185 opened.draftId,
186 { text, hiddenCharacters: link.prompt?.hiddenCharacters ?? 0 },
187 notes,
188 );
189 };
190
191 const openScratchDraft = async () => {
192 const environmentId = scratchEnvironmentId(lastActiveEnvironmentId());
193 const project = environmentId === null ? null : await openScratchProject(environmentId);
194 if (project === null) {
195 setState({
196 status: "failed",
197 message: gt("None of your machines can start a thread without a project right now."),
198 });
199 return;
200 }
201 await openDraft(
202 project,
203 link.kind === "pull-request" ? promptLinkPullRequestUrl(link.pullRequest) : undefined,
204 );
205 };
206
207 const openWithoutProject = () => {
208 setState({ status: "opening" });
209 void openScratchDraft();
210 };
211
212 const cloneRepository = async (repository: PromptLinkRepository) => {
213 const environmentId = lastActiveEnvironmentId();
214 const environment = environments.find((entry) => entry.environmentId === environmentId);
215 const serverConfig = environment?.serverConfig ?? null;
216 const newProjectsRoot = serverConfig?.newProjectsRoot ?? null;
217 if (environmentId === null || serverConfig === null || newProjectsRoot === null) {
218 setState({
219 status: "failed",
220 message: gt(
221 "This machine cannot clone from a link. Update T3 Code on it, or clone the repository from the command palette.",
222 ),
223 });
224 return;
225 }
226 setState({ status: "opening" });
227 const remoteUrl = `https://github.com/${repository.owner}/${repository.name}.git`;
228 const settings = serverConfig.settings;
229 const result = await startProjectClone({
230 environmentId,
231 input: {
232 projectId: newProjectId(),
233 title: repository.name,
234 createdAt: new Date().toISOString(),
235 remoteUrl,
236 destinationPath: getCloneDestinationPath(
237 settings.ghqCloneLayout
238 ? getAddProjectInitialQuery(settings.addProjectBaseDirectory)
239 : newProjectsRoot,
240 getCloneDirectoryPath(remoteUrl, settings.ghqCloneLayout === true),
241 ),
242 },
243 });
244 if (result._tag === "Failure") {
245 if (!isAtomCommandInterrupted(result)) {
246 const error = squashAtomCommandFailure(result);
247 toastManager.add(
248 stackedThreadToast({
249 type: "error",
250 title: gt("Clone failed"),
251 description: thrownErrorMessage(error, m) ?? gt("An error occurred."),
252 }),
253 );
254 }
255 setState({ status: "missing-repository", repository });
256 return;
257 }
258 void suggestAppAccessForRemote(
259 environmentId,
260 `https://github.com/${repository.owner}/${repository.name}.git`,
261 );
262 const project = await waitForProject(
263 scopeProjectRef(environmentId, result.value.projectId),
264 5_000,
265 ).catch(() => null);
266 if (project === null) {
267 setState({
268 status: "failed",
269 message: gt("The clone started, but its project did not appear."),
270 });
271 return;
272 }
273 if (link.kind === "pull-request") {
274 setState({
275 status: "failed",
276 title: gt("Cloning {repository}", {
277 repository: `${repository.owner}/${repository.name}`,
278 }),
279 message: gt("Open this link again when the clone finishes."),
280 });
281 return;
282 }
283 await openDraft(project);
284 };
285
286 const localPullRequestThread =
287 ready && link.kind === "pull-request"
288 ? findPromptLinkPullRequestThread(threads, link.pullRequest)
289 : undefined;
290 // Mounted only while deciding, so "Open it again" asks the server again.
291 const lookupProjects =
292 ready &&
293 state.status === "opening" &&
294 !started &&
295 link.kind === "pull-request" &&
296 localPullRequestThread === undefined
297 ? findPromptLinkProjects(recentProjects(), link.pullRequest)
298 : [];
299 const serverPullRequestThread = useAtomValue(
300 link.kind === "pull-request" && lookupProjects.length > 0
301 ? pullRequestThreadLookupAtom(
302 JSON.stringify({
303 targets: lookupProjects.map((project) => [project.environmentId, project.id]),
304 repository: `${link.pullRequest.owner}/${link.pullRequest.name}`,
305 number: link.pullRequest.number,
306 } satisfies PullRequestThreadLookup),
307 )
308 : NO_PULL_REQUEST_THREAD_LOOKUP,
309 );
310
311 if (ready && serverPullRequestThread !== undefined && state.status === "opening" && !started) {
312 setStarted(true);
313 const pullRequestThread = localPullRequestThread ?? serverPullRequestThread ?? undefined;
314 const repository = link.kind === "new" ? link.repository : link.pullRequest;
315 const project =
316 repository === null ? undefined : findPromptLinkProjects(recentProjects(), repository)[0];
317 if (pullRequestThread !== undefined) {
318 setState({ status: "opened" });
319 setLaunch({ kind: "thread", thread: pullRequestThread });
320 } else if (repository === null) {
321 setLaunch({ kind: "scratch" });
322 } else if (project === undefined) {
323 setState({ status: "missing-repository", repository });
324 setLaunch({ kind: "settled" });
325 } else if (link.kind === "pull-request") {
326 setState({ status: "pull-request-checkout", project });
327 setLaunch({ kind: "settled" });
328 } else {
329 setLaunch({ kind: "draft", project });
330 }
331 }
332
333 const runLaunch = useEffectEvent((next: LinkLaunch) => {
334 openedLinkKeys.add(locationKey);
335 switch (next.kind) {
336 case "thread": {
337 const threadRef = scopeThreadRef(next.thread.environmentId, next.thread.id);
338 if (link.prompt !== null) placeLinkedPrompt(threadRef, link.prompt);
339 void navigate({
340 to: "/$environmentId/$threadId",
341 params: { environmentId: next.thread.environmentId, threadId: next.thread.id },
342 replace: true,
343 });
344 return;
345 }
346 case "scratch":
347 void openScratchDraft();
348 return;
349 case "draft":
350 void openDraft(next.project);
351 return;
352 case "settled":
353 }
354 });
355
356 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- runs each launch decision once: navigates to the thread or opens a draft
357 useEffect(() => {
358 if (launch === null || launchedRef.current === launch) return;
359 launchedRef.current = launch;
360 runLaunch(launch);
361 }, [launch]);
362
363 switch (state.status) {
364 case "opening":
365 return <LinkPage title={gt("Opening the link...")} />;
366 case "opened":
367 return (
368 <LinkPage title={gt("This link is open")}>
369 <Button
370 size="sm"
371 variant="outline"
372 onClick={() => {
373 openedLinkKeys.delete(locationKey);
374 setStarted(false);
375 setState({ status: "opening" });
376 }}
377 >
378 <T>Open it again</T>
379 </Button>
380 </LinkPage>
381 );
382 case "failed":
383 return (
384 <LinkPage
385 title={state.title ?? gt("Could not open the link")}
386 description={state.message}
387 />
388 );
389 case "missing-repository": {
390 const name = `${state.repository.owner}/${state.repository.name}`;
391 return (
392 <LinkPage
393 title={gt("You don't have {repository}", { repository: name })}
394 description={gt("Clone it to work on it here, or start without a project.")}
395 >
396 <Button size="sm" onClick={() => void cloneRepository(state.repository)}>
397 {gt("Clone {repository}", { repository: name })}
398 </Button>
399 <Button size="sm" variant="outline" onClick={openWithoutProject}>
400 <T>Use without project</T>
401 </Button>
402 </LinkPage>
403 );
404 }
405 case "pull-request-checkout":
406 return link.kind === "pull-request" ? (
407 <PullRequestLinkCheckout link={link} project={state.project} />
408 ) : null;
409 }
410 }
411
412 /** Checkout runs setup from PR code, so links alone must not start it. */
413 function PullRequestLinkCheckout({
414 link,
415 project,
416 }: {
417 readonly link: Extract<NewThreadLink, { kind: "pull-request" }>;
418 readonly project: EnvironmentProject;
419 }) {
420 const { handoff, startHandoff } = usePullRequestHandoffs({
421 environmentId: project.environmentId,
422 detail: {
423 projectId: project.id,
424 workspaceRoot: project.workspaceRoot,
425 url: promptLinkPullRequestUrl(link.pullRequest),
426 },
427 });
428 const gt = useGT();
429 const warnedRef = useRef(false);
430 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- shows the hidden-characters warning toast once per linked prompt
431 useEffect(() => {
432 if (warnedRef.current || link.prompt === null) return;
433 warnedRef.current = true;
434 warnAboutHiddenCharacters(link.prompt);
435 }, [link.prompt]);
436 const { owner, name, number } = link.pullRequest;
437 return (
438 <LinkPage
439 title={gt("Check out {pullRequest}?", { pullRequest: `${owner}/${name}#${number}` })}
440 description={gt(
441 "This puts the pull request's code in a new worktree and runs your project's setup script on it.",
442 )}
443 >
444 <Button
445 size="sm"
446 disabled={handoff !== null}
447 onClick={() =>
448 void startHandoff(
449 "prompt-link",
450 link.prompt === null ? null : { prompt: link.prompt.text },
451 )
452 }
453 >
454 {handoff !== null ? gt("Checking out...") : gt("Check out")}
455 </Button>
456 </LinkPage>
457 );
458 }
459
460 function LinkPage({
461 title,
462 description,
463 children,
464 }: {
465 readonly title: string;
466 readonly description?: string;
467 readonly children?: ReactNode;
468 }) {
469 return (
470 <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none">
471 {isElectron ? <WorkspacePageHeader electron /> : null}
472 <Empty className="flex-1">
473 <EmptyHeader className="max-w-md">
474 <EmptyTitle>{title}</EmptyTitle>
475 {description ? <EmptyDescription>{description}</EmptyDescription> : null}
476 {children ? <div className="mt-5 flex justify-center gap-2">{children}</div> : null}
477 </EmptyHeader>
478 </Empty>
479 </SidebarInset>
480 );
481 }