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

useStartTriage.ts

116 lines4.7 KB

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