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

useStartTriage.ts

107 lines4.5 KB

1import { scopeProjectRef } from "@t3tools/client-runtime/environment";
2import {
3 type AtomCommandResult,
4 isAtomCommandInterrupted,
5 squashAtomCommandFailure,
6} from "@t3tools/client-runtime/state/runtime";
7import { type EnvironmentId, TRIAGE_PROMPT_FILE_NAME } from "@t3tools/contracts";
8import { useRouter } from "@tanstack/react-router";
9​
10import { stackedThreadToast, toastManager } from "~/components/ui/toast";
11import { currentClientMetadata } from "~/connection/platform";
12import { projectEnvironment } from "~/state/projects";
13import { serverEnvironment } from "~/state/server";
14import { useAtomCommand } from "~/state/use-atom-command";
15import { writeTextToClipboard } from "./useCopyToClipboard";
16import { useNewThreadHandler } from "./useHandleNewThread";
17import { useScratchProject } from "./useScratchProject";
18​
19export const TRIAGE_CLI_COMMAND = "npx t3 triage";
20​
21const copyTriageCliCommand = () =>
22 writeTextToClipboard(TRIAGE_CLI_COMMAND, "command").catch(() =>
23 toastManager.add({
24 type: "error",
25 title: `Could not copy. Type ${TRIAGE_CLI_COMMAND} instead.`,
26 }),
27 );
28​
29/** A draft is a triage draft while its message still links the playbook file. */
30export const isTriagePrompt = (prompt: string) => prompt.includes(`[${TRIAGE_PROMPT_FILE_NAME}](`);
31​
32/**
33 * In-app `t3 triage`: the server writes the session files and starts cloning
34 * the matching source, then a No project draft opens with the playbook linked.
35 * The draft hero explains the rest; the user picks a provider and describes
36 * the problem.
37 */
38export function useStartTriage() {
39 const router = useRouter();
40 const { scratchWorkspaceRootFor } = useScratchProject();
41 const handleNewThread = useNewThreadHandler();
42 const prepare = useAtomCommand(serverEnvironment.prepareTriage, { reportFailure: false });
43 const openScratch = useAtomCommand(projectEnvironment.openScratch, { reportFailure: false });
44​
45 // With no draft to show, a toast is the only place to point at the CLI.
46 const fail = (description: string) =>
47 toastManager.add(
48 stackedThreadToast({
49 type: "error",
50 title: "Could not start triage",
51 description: `${description} Run ${TRIAGE_CLI_COMMAND} in a terminal on that machine instead.`,
52 timeout: 0,
53 actionProps: { children: "Copy command", onClick: () => void copyTriageCliCommand() },
54 // "Copy command" is the copy that helps here, not the error text.
55 data: { hideCopyButton: true },
56 }),
57 );
58 const failWith = (
59 result: Extract<AtomCommandResult<unknown, unknown>, { readonly _tag: "Failure" }>,
60 ) => {
61 if (isAtomCommandInterrupted(result)) return;
62 const error = squashAtomCommandFailure(result);
63 fail(error instanceof Error ? error.message : "An error occurred.");
64 };
65​
66 // `routeChanged` tells the steps the user went elsewhere while they waited;
67 // the draft then stays closed instead of pulling them away.
68 const openTriageDraft = async (environmentId: EnvironmentId, routeChanged: () => boolean) => {
69 const prepared = await prepare({
70 environmentId,
71 input: { client: currentClientMetadata() },
72 });
73 if (prepared._tag === "Failure") return failWith(prepared);
74 const project = await openScratch({ environmentId, input: {} });
75 if (project._tag === "Failure") return failWith(project);
76 if (routeChanged()) return;
77 // A null result means the user went elsewhere; only a throw is a failure.
78 await handleNewThread(scopeProjectRef(project.value.environmentId, project.value.id), {
79 prompt: prepared.value.prompt,
80 }).catch(() => fail("T3 Code could not open a new thread."));
81 };
82​
83 return async (environmentId: EnvironmentId) => {
84 if (scratchWorkspaceRootFor(environmentId) === null) {
85 fail("This machine cannot start threads without a project.");
86 return;
87 }
88 const requestingRouteHref = router.state.location.href;
89 // The palette is already closed, and a slow network can hold up the source
90 // lookup, so say something when the draft does not open at once.
91 let pendingToastId: ReturnType<typeof toastManager.add> | undefined;
92 const pendingTimer = setTimeout(() => {
93 pendingToastId = toastManager.add({
94 type: "loading",
95 title: "Starting triage…",
96 timeout: 0,
97 });
98 }, 400);
99 await openTriageDraft(
100 environmentId,
101 () => router.state.location.href !== requestingRouteHref,
102 ).finally(() => {
103 clearTimeout(pendingTimer);
104 if (pendingToastId !== undefined) toastManager.close(pendingToastId);
105 });
106 };