Open History to see the last commit
1import { scopeProjectRef } from "@t3tools/client-runtime/environment";
2import type {
3 DesktopPreviewAnnotationVoiceConfig,
4 DesktopPreviewAnnotationVoiceEvent,
5 ScopedThreadRef,
6} from "@t3tools/contracts";
7import { useNavigate } from "@tanstack/react-router";
8import { useEffect, useRef, useState } from "react";
9
10import { resolveSpeechPresentation } from "~/components/chat/ComposerSpeechButton";
11import { VoiceInputSetup } from "~/components/chat/VoiceInputSetup";
12import { toastManager } from "~/components/ui/toast";
13import { useComposerDraftStore } from "~/composerDraftStore";
14import { useStableCallback } from "~/hooks/useStableCallback";
15import { useDictationShortcut, type DictationKeyHandlers } from "~/speech/useDictationShortcut";
16import { useEnvironmentSpeechInput } from "~/speech/useEnvironmentSpeechInput";
17import { useProject, useThreadShell } from "~/state/entities";
18import { previewBridge } from "./previewBridge";
19
20/**
21 * The annotation editor lives inside the preview guest, which only forwards trusted gestures
22 * and mirrors state. Recording, consent, and transcription stay in this renderer.
23 */
24export function PreviewAnnotationSpeech({
25 threadRef,
26 tabId,
27 config,
28 keybindings,
29}: {
30 threadRef: ScopedThreadRef;
31 tabId: string;
32 config: DesktopPreviewAnnotationVoiceConfig;
33 keybindings: Parameters<typeof useDictationShortcut>[0]["keybindings"];
34}) {
35 const navigate = useNavigate();
36 const thread = useThreadShell(threadRef);
37 const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef));
38 const projectId = thread?.projectId ?? draftThread?.projectId ?? null;
39 const project = useProject(
40 projectId ? scopeProjectRef(threadRef.environmentId, projectId) : null,
41 );
42 const draft = useRef({ text: "", cursor: 0, selectionEnd: 0 });
43 const [text, setText] = useState("");
44 const keys = useRef<DictationKeyHandlers | null>(null);
45 const guestFocused = useRef(false);
46 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- notices focus returning from the preview guest to this window
47 useEffect(() => {
48 const onFocus = () => {
49 guestFocused.current = false;
50 };
51 window.addEventListener("focus", onFocus);
52 window.addEventListener("focusin", onFocus);
53 return () => {
54 window.removeEventListener("focus", onFocus);
55 window.removeEventListener("focusin", onFocus);
56 };
57 }, []);
58 const speech = useEnvironmentSpeechInput({
59 environmentId: threadRef.environmentId,
60 projectId,
61 projectName: project?.title,
62 ownerKey: JSON.stringify(["preview-annotation", threadRef, tabId, config.sessionId]),
63 draftText: text,
64 offerSetup: false,
65 readDraft: () => ({
66 text: draft.current.text,
67 selection: { start: draft.current.cursor, end: draft.current.selectionEnd },
68 }),
69 commitDraft: (next, selection) => {
70 draft.current = { text: next, cursor: selection.start, selectionEnd: selection.end };
71 setText(next);
72 void publish(current.current.voiceState, { text: next, cursor: selection.start });
73 },
74 });
75 const subscribeKeys = useStableCallback((handlers: DictationKeyHandlers) => {
76 keys.current = handlers;
77 return () => {
78 keys.current = null;
79 };
80 });
81 const shortcutLabel = useDictationShortcut({
82 keybindings,
83 speech,
84 disabled: false,
85 terminalOpen: false,
86 modelPickerOpen: false,
87 previewFocus: true,
88 ownsFocus: () => guestFocused.current,
89 subscribeKeys,
90 });
91 const { available, state, preview, freezesEditor, blocksSubmission, level } = speech;
92 const voiceState = {
93 tabId,
94 sessionId: config.sessionId,
95 available,
96 phase: state.phase,
97 errorAction: state.errorAction,
98 status: resolveSpeechPresentation(state, null).status,
99 preview: preview ? preview.committed + preview.tentative : null,
100 level,
101 shortcutLabel,
102 freezesEditor,
103 blocksSubmission,
104 };
105 const current = useRef({ speech, voiceState });
106 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes committed speech actions and state to the desktop IPC listener
107 useEffect(() => {
108 current.current = { speech, voiceState };
109 });
110 const publish = useStableCallback(
111 async (voice: typeof voiceState, nextDraft: { text: string; cursor: number } | null) => {
112 try {
113 await previewBridge?.annotationVoice.update({ ...voice, draft: nextDraft });
114 } catch (error) {
115 current.current.speech.cancel();
116 toastManager.add({
117 type: "error",
118 title: "Could not update annotation voice input",
119 description: error instanceof Error ? error.message : String(error),
120 });
121 }
122 },
123 );
124 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- mirrors every committed voice state change into the preview guest
125 useEffect(() => {
126 void publish(voiceState, null);
127 }, [publish, voiceState]);
128 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to gestures the preview guest relays for this session
129 useEffect(
130 () =>
131 previewBridge?.annotationVoice.onEvent(
132 (eventTabId, event: DesktopPreviewAnnotationVoiceEvent) => {
133 if (eventTabId !== tabId || event.sessionId !== config.sessionId) return;
134 draft.current = {
135 text: event.text,
136 cursor: Math.min(event.cursor, event.text.length),
137 selectionEnd: Math.min(event.selectionEnd ?? event.cursor, event.text.length),
138 };
139 setText(event.text);
140 if (event.action === "focus" || event.action === "key" || event.action === "start")
141 guestFocused.current = true;
142 if (event.action === "blur") guestFocused.current = false;
143 const value = current.current.speech;
144 switch (event.action) {
145 case "focus":
146 case "sync":
147 void publish(current.current.voiceState, null);
148 break;
149 case "start":
150 void value.start();
151 break;
152 case "stop":
153 void value.stop();
154 break;
155 case "cancel":
156 value.cancel();
157 break;
158 case "settings":
159 value.cancel();
160 void navigate({ to: "/settings/voice" });
161 break;
162 case "skip":
163 value.skipPostProcessing();
164 break;
165 case "blur":
166 keys.current?.blur();
167 break;
168 case "key": {
169 if (!event.keyboard) break;
170 keys.current?.[event.keyboard.type](
171 new KeyboardEvent(event.keyboard.type, event.keyboard),
172 );
173 break;
174 }
175 }
176 },
177 ),
178 [tabId, config.sessionId, publish, navigate],
179 );
180 return (
181 <VoiceInputSetup
182 environmentId={speech.transcriptionEnvironmentId}
183 open={speech.setup.open}
184 step={speech.setup.step}
185 status={speech.status}
186 model={speech.setup.model}
187 language={speech.setup.language}
188 downloading={speech.setup.downloading}
189 error={speech.setup.error}
190 onOpenChange={speech.setup.setOpen}
191 onRetryCatalog={speech.setup.retryCatalog}
192 onDownload={() => void speech.setup.download()}
193 onCancelDownload={() => void speech.setup.cancelDownload()}
194 onStartRecording={() => void speech.setup.startRecording()}
195 />
196 );
197}