@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
ts 119 lines 4.76 KB
Raw
1 import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2 import { scopeProjectRef } from "@t3tools/client-runtime/environment";
3 import {
4 type AtomCommandResult,
5 isAtomCommandInterrupted,
6 squashAtomCommandFailure,
7 } from "@t3tools/client-runtime/state/runtime";
8 import type { EnvironmentId } from "@t3tools/contracts";
9 import { useRouter } from "@tanstack/react-router";
10 import { msg } from "gt-react";
11
12 import { stackedThreadToast, toastManager } from "~/components/ui/toast";
13 import { currentClientMetadata } from "~/connection/platform";
14 import { m } from "~/i18n/messages";
15 import { projectEnvironment } from "~/state/projects";
16 import { serverEnvironment } from "~/state/server";
17 import { useAtomCommand } from "~/state/use-atom-command";
18 import { writeTextToClipboard } from "./useCopyToClipboard";
19 import { useNewThreadHandler } from "./useHandleNewThread";
20 import { useScratchProject } from "./useScratchProject";
21
22 export const TRIAGE_CLI_COMMAND = "npx t3 triage";
23
24 const 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} instead.", { command: TRIAGE_CLI_COMMAND })),
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 */
42 export 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} in a terminal on that machine instead.", {
57 description,
58 command: TRIAGE_CLI_COMMAND,
59 }),
60 ),
61 timeout: 0,
62 actionProps: {
63 children: m(msg("Copy command")),
64 onClick: () => void copyTriageCliCommand(),
65 },
66 // "Copy command" is the copy that helps here, not the error text.
67 data: { hideCopyButton: true },
68 }),
69 );
70 const failWith = (
71 result: Extract<AtomCommandResult<unknown, unknown>, { readonly _tag: "Failure" }>,
72 ) => {
73 if (isAtomCommandInterrupted(result)) return;
74 const error = squashAtomCommandFailure(result);
75 fail(thrownErrorMessage(error, m) ?? m(msg("An error occurred.")));
76 };
77
78 // `routeChanged` tells the steps the user went elsewhere while they waited;
79 // the draft then stays closed instead of pulling them away.
80 const openTriageDraft = async (environmentId: EnvironmentId, routeChanged: () => boolean) => {
81 const prepared = await prepare({
82 environmentId,
83 input: { client: currentClientMetadata() },
84 });
85 if (prepared._tag === "Failure") return failWith(prepared);
86 const project = await openScratch({ environmentId, input: {} });
87 if (project._tag === "Failure") return failWith(project);
88 if (routeChanged()) return;
89 // A null result means the user went elsewhere; only a throw is a failure.
90 await handleNewThread(scopeProjectRef(project.value.environmentId, project.value.id), {
91 prompt: prepared.value.prompt,
92 }).catch(() => fail(m(msg("T3 Code could not open a new thread."))));
93 };
94
95 return async (environmentId: EnvironmentId) => {
96 if (scratchWorkspaceRootFor(environmentId) === null) {
97 fail(m(msg("This machine cannot start threads without a project.")));
98 return;
99 }
100 const requestingRouteHref = router.state.location.href;
101 // The palette is already closed, and a slow network can hold up the source
102 // lookup, so say something when the draft does not open at once.
103 let pendingToastId: ReturnType<typeof toastManager.add> | undefined;
104 const pendingTimer = setTimeout(() => {
105 pendingToastId = toastManager.add({
106 type: "loading",
107 title: m(msg("Starting triage…")),
108 timeout: 0,
109 });
110 }, 400);
111 await openTriageDraft(
112 environmentId,
113 () => router.state.location.href !== requestingRouteHref,
114 ).finally(() => {
115 clearTimeout(pendingTimer);
116 if (pendingToastId !== undefined) toastManager.close(pendingToastId);
117 });
118 };
119 }