The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { m } from "../i18n/messages"; |
| 2 | import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; |
| 3 | import { useAtomValue } from "@effect/atom-react"; |
| 4 | import { scopeThreadRef } from "@t3tools/client-runtime/environment"; |
| 5 | import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; |
| 6 | import { ProviderInstanceId, type ThreadId } from "@t3tools/contracts"; |
| 7 | import { useNavigate, useParams } from "@tanstack/react-router"; |
| 8 | import { useEffect, useEffectEvent, useState } from "react"; |
| 9 | import { T, useGT, Var } from "gt-react"; |
| 10 | |
| 11 | import { newMessageId, newThreadId } from "~/lib/utils"; |
| 12 | import { useProjects, useThreadShell } from "../state/entities"; |
| 13 | import { usePrimaryEnvironmentId } from "../state/environments"; |
| 14 | import { primaryServerProvidersAtom } from "../state/server"; |
| 15 | import { threadEnvironment } from "../state/threads"; |
| 16 | import { useOrchestrationCommand } from "../state/use-orchestration-command"; |
| 17 | import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes"; |
| 18 | import { Button } from "./ui/button"; |
| 19 | import { Dialog, DialogHeader, DialogPanel, DialogPopup, DialogTitle } from "./ui/dialog"; |
| 20 | import { toastManager } from "./ui/toast"; |
| 21 | |
| 22 | // Dev servers register this free ACP agent; see ProviderInstanceRegistryHydration.ts. |
| 23 | const DEV_REPLAY_INSTANCE_ID = ProviderInstanceId.make("devReplay"); |
| 24 | |
| 25 | /** |
| 26 | * Starts free replay threads on the primary environment in dev builds. Ctrl+Alt+Shift+R |
| 27 | * opens a picker, and `window.t3dev.replay(scenario)` does the same from the console. |
| 28 | */ |
| 29 | export function DevReplayHost() { |
| 30 | const gt = useGT(); |
| 31 | const [open, setOpen] = useState(false); |
| 32 | const navigate = useNavigate(); |
| 33 | const environmentId = usePrimaryEnvironmentId(); |
| 34 | const providers = useAtomValue(primaryServerProvidersAtom); |
| 35 | const projects = useProjects(); |
| 36 | const target = resolveThreadRouteTarget(useParams({ strict: false })); |
| 37 | const routeThread = useThreadShell(target?.kind === "server" ? target.threadRef : null); |
| 38 | const startTurn = useOrchestrationCommand(threadEnvironment.startTurn, { reportFailure: false }); |
| 39 | |
| 40 | const replayProvider = providers.find( |
| 41 | (provider) => provider.instanceId === DEV_REPLAY_INSTANCE_ID && provider.enabled, |
| 42 | ); |
| 43 | const scenarios = replayProvider?.models ?? []; |
| 44 | const environmentProjects = projects.filter((project) => project.environmentId === environmentId); |
| 45 | const project = |
| 46 | environmentProjects.find((candidate) => candidate.id === routeThread?.projectId) ?? |
| 47 | environmentProjects[0]; |
| 48 | |
| 49 | const replay = async (scenario?: string): Promise<ThreadId> => { |
| 50 | const model = scenario ?? scenarios[0]?.slug; |
| 51 | if (environmentId === null || project === undefined || model === undefined) { |
| 52 | throw new Error( |
| 53 | gt("Replay needs a dev server with a project and the Replay (dev) provider."), |
| 54 | ); |
| 55 | } |
| 56 | if (!scenarios.some((candidate) => candidate.slug === model)) { |
| 57 | throw new Error(gt('Unknown replay scenario "{model}".', { model })); |
| 58 | } |
| 59 | const threadId = newThreadId(); |
| 60 | const modelSelection = { instanceId: DEV_REPLAY_INSTANCE_ID, model }; |
| 61 | const title = `Replay: ${model}`; |
| 62 | const createdAt = new Date().toISOString(); |
| 63 | const result = await startTurn({ |
| 64 | environmentId, |
| 65 | input: { |
| 66 | threadId, |
| 67 | message: { messageId: newMessageId(), role: "user", text: title, attachments: [] }, |
| 68 | modelSelection, |
| 69 | runtimeMode: "approval-required", |
| 70 | interactionMode: "default", |
| 71 | bootstrap: { |
| 72 | createThread: { |
| 73 | projectId: project.id, |
| 74 | title, |
| 75 | modelSelection, |
| 76 | runtimeMode: "approval-required", |
| 77 | interactionMode: "default", |
| 78 | branch: null, |
| 79 | worktreePath: null, |
| 80 | createdAt, |
| 81 | }, |
| 82 | }, |
| 83 | createdAt, |
| 84 | }, |
| 85 | }); |
| 86 | if (result._tag === "Failure") throw squashAtomCommandFailure(result); |
| 87 | await navigate({ |
| 88 | to: "/$environmentId/$threadId", |
| 89 | params: buildThreadRouteParams(scopeThreadRef(environmentId, threadId)), |
| 90 | }); |
| 91 | return threadId; |
| 92 | }; |
| 93 | |
| 94 | const replayFromConsole = useEffectEvent(replay); |
| 95 | const listScenarios = useEffectEvent(() => scenarios.map((scenario) => scenario.slug)); |
| 96 | |
| 97 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- exposes the console API on window and listens for the hidden window hotkey |
| 98 | useEffect(() => { |
| 99 | window.t3dev = { |
| 100 | replayScenarios: () => listScenarios(), |
| 101 | replay: (scenario) => replayFromConsole(scenario), |
| 102 | }; |
| 103 | const onKeyDown = (event: KeyboardEvent) => { |
| 104 | if (event.repeat) return; |
| 105 | if (event.ctrlKey && event.altKey && event.shiftKey && event.code === "KeyR") { |
| 106 | event.preventDefault(); |
| 107 | setOpen((current) => !current); |
| 108 | } |
| 109 | }; |
| 110 | window.addEventListener("keydown", onKeyDown); |
| 111 | return () => { |
| 112 | delete window.t3dev; |
| 113 | window.removeEventListener("keydown", onKeyDown); |
| 114 | }; |
| 115 | }, []); |
| 116 | |
| 117 | const start = (scenario: string) => { |
| 118 | setOpen(false); |
| 119 | replay(scenario).catch((error: unknown) => |
| 120 | toastManager.add({ |
| 121 | type: "error", |
| 122 | title: gt("Replay failed"), |
| 123 | description: thrownErrorMessage(error, m) ?? String(error), |
| 124 | }), |
| 125 | ); |
| 126 | }; |
| 127 | |
| 128 | return ( |
| 129 | <Dialog open={open} onOpenChange={setOpen}> |
| 130 | <DialogPopup className="sm:max-w-sm"> |
| 131 | <DialogHeader> |
| 132 | <DialogTitle> |
| 133 | {project === undefined ? ( |
| 134 | <T>Replay a recorded turn</T> |
| 135 | ) : ( |
| 136 | <T> |
| 137 | Replay in <Var>{project.title}</Var> |
| 138 | </T> |
| 139 | )} |
| 140 | </DialogTitle> |
| 141 | </DialogHeader> |
| 142 | <DialogPanel> |
| 143 | {scenarios.length === 0 || project === undefined ? ( |
| 144 | <p className="text-sm text-muted-foreground"> |
| 145 | <T>Needs a project and the Replay (dev) provider, which dev servers start.</T> |
| 146 | </p> |
| 147 | ) : ( |
| 148 | <div className="flex flex-col items-start gap-1"> |
| 149 | {scenarios.map((scenario) => ( |
| 150 | <Button key={scenario.slug} variant="ghost" onClick={() => start(scenario.slug)}> |
| 151 | {scenario.name} |
| 152 | </Button> |
| 153 | ))} |
| 154 | </div> |
| 155 | )} |
| 156 | </DialogPanel> |
| 157 | </DialogPopup> |
| 158 | </Dialog> |
| 159 | ); |
| 160 | } |