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

DevReplayHost.tsx

158 lines6.1 KB

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