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

main
ts 78 lines 2.66 KB
Raw
1 import { findErrorTraceId, thrownErrorMessage } from "@t3tools/client-runtime/errors";
2 import {
3 isAtomCommandInterrupted,
4 squashAtomCommandFailure,
5 } from "@t3tools/client-runtime/state/runtime";
6 import { msg } from "gt-react";
7 import { useState } from "react";
8
9 import {
10 createManagedRelayT3ChatLinkRequestCommand,
11 unlinkManagedRelayT3ChatCommand,
12 useManagedRelayT3ChatLink,
13 } from "../../cloud/managedRelayState";
14 import { m } from "../../i18n/messages";
15 import { readLocalApi } from "../../localApi";
16 import { useAtomCommand } from "../../state/use-atom-command";
17 import { toastManager } from "../ui/toast";
18
19 function reportFailure(title: string, cause: unknown) {
20 const traceId = findErrorTraceId(cause);
21 toastManager.add({
22 type: "error",
23 title,
24 description: thrownErrorMessage(cause, m) ?? m(msg("Try again.")),
25 data: traceId
26 ? {
27 secondaryActionProps: {
28 children: m(msg("Copy trace ID")),
29 onClick: () => void navigator.clipboard?.writeText(traceId),
30 },
31 }
32 : undefined,
33 });
34 }
35
36 /** Starts and removes the T3 Chat link that raises the T3 Connect tunnel cap. */
37 export function useT3ChatLink() {
38 const linkState = useManagedRelayT3ChatLink();
39 const createLinkRequest = useAtomCommand(createManagedRelayT3ChatLinkRequestCommand, {
40 reportFailure: false,
41 });
42 const unlinkCommand = useAtomCommand(unlinkManagedRelayT3ChatCommand, { reportFailure: false });
43 const [pending, setPending] = useState<"link" | "unlink" | null>(null);
44 // Kept so a blocked popup still leaves the user a link to open.
45 const [linkUrl, setLinkUrl] = useState<string | null>(null);
46
47 const link = async () => {
48 const accountId = linkState.accountId;
49 if (!accountId || pending) return;
50 setPending("link");
51 const result = await createLinkRequest({ accountId });
52 if (result._tag === "Success") {
53 setLinkUrl(result.value);
54 await readLocalApi()
55 ?.shell.openExternal(result.value)
56 .catch(() => undefined);
57 } else if (!isAtomCommandInterrupted(result)) {
58 reportFailure(m(msg("Could not start linking")), squashAtomCommandFailure(result));
59 }
60 setPending(null);
61 };
62
63 const unlink = async () => {
64 const accountId = linkState.accountId;
65 if (!accountId || pending) return;
66 setPending("unlink");
67 const result = await unlinkCommand({ accountId });
68 if (result._tag === "Success") {
69 setLinkUrl(null);
70 linkState.refresh();
71 } else if (!isAtomCommandInterrupted(result)) {
72 reportFailure(m(msg("Could not unlink T3 Chat")), squashAtomCommandFailure(result));
73 }
74 setPending(null);
75 };
76
77 return { linkState, pending, linkUrl, link, unlink };
78 }