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

PreviewAnnotationSpeech.tsx

193 lines7.1 KB

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 } 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 keys = useRef<DictationKeyHandlers | null>(null);
44 const guestFocused = useRef(false);
45 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- notices focus returning from the preview guest to this window
46 useEffect(() => {
47 const onFocus = () => {
48 guestFocused.current = false;
49 };
50 window.addEventListener("focus", onFocus);
51 window.addEventListener("focusin", onFocus);
52 return () => {
53 window.removeEventListener("focus", onFocus);
54 window.removeEventListener("focusin", onFocus);
55 };
56 }, []);
57 const speech = useEnvironmentSpeechInput({
58 environmentId: threadRef.environmentId,
59 projectId,
60 projectName: project?.title,
61 ownerKey: JSON.stringify(["preview-annotation", threadRef, tabId, config.sessionId]),
62 offerSetup: false,
63 readDraft: () => ({
64 text: draft.current.text,
65 selection: { start: draft.current.cursor, end: draft.current.selectionEnd },
66 }),
67 commitDraft: (next, selection) => {
68 draft.current = { text: next, cursor: selection.start, selectionEnd: selection.end };
69 void publish(current.current.voiceState, { text: next, cursor: selection.start });
70 },
71 });
72 const subscribeKeys = useStableCallback((handlers: DictationKeyHandlers) => {
73 keys.current = handlers;
74 return () => {
75 keys.current = null;
76 };
77 });
78 const shortcutLabel = useDictationShortcut({
79 keybindings,
80 speech,
81 disabled: false,
82 terminalOpen: false,
83 modelPickerOpen: false,
84 previewFocus: true,
85 ownsFocus: () => guestFocused.current,
86 subscribeKeys,
87 });
88 const { available, state, preview, freezesEditor, blocksSubmission, level } = speech;
89 const voiceState = {
90 tabId,
91 sessionId: config.sessionId,
92 available,
93 phase: state.phase,
94 errorAction: state.errorAction,
95 status: resolveSpeechPresentation(state, null).status,
96 preview: preview ? preview.committed + preview.tentative : null,
97 level,
98 shortcutLabel,
99 freezesEditor,
100 blocksSubmission,
101 };
102 const current = useRef({ speech, voiceState });
103 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes committed speech actions and state to the desktop IPC listener
104 useEffect(() => {
105 current.current = { speech, voiceState };
106 });
107 const publish = useStableCallback(
108 async (voice: typeof voiceState, nextDraft: { text: string; cursor: number } | null) => {
109 try {
110 await previewBridge?.annotationVoice.update({ ...voice, draft: nextDraft });
111 } catch (error) {
112 current.current.speech.cancel();
113 toastManager.add({
114 type: "error",
115 title: "Could not update annotation voice input",
116 description: error instanceof Error ? error.message : String(error),
117 });
118 }
119 },
120 );
121 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- mirrors every committed voice state change into the preview guest
122 useEffect(() => {
123 void publish(voiceState, null);
124 }, [publish, voiceState]);
125 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to gestures the preview guest relays for this session
126 useEffect(
127 () =>
128 previewBridge?.annotationVoice.onEvent(
129 (eventTabId, event: DesktopPreviewAnnotationVoiceEvent) => {
130 if (eventTabId !== tabId || event.sessionId !== config.sessionId) return;
131 draft.current = {
132 text: event.text,
133 cursor: Math.min(event.cursor, event.text.length),
134 selectionEnd: Math.min(event.selectionEnd ?? event.cursor, event.text.length),
135 };
136 if (event.action === "focus" || event.action === "key" || event.action === "start")
137 guestFocused.current = true;
138 if (event.action === "blur") guestFocused.current = false;
139 const value = current.current.speech;
140 switch (event.action) {
141 case "focus":
142 case "sync":
143 void publish(current.current.voiceState, null);
144 break;
145 case "start":
146 void value.start();
147 break;
148 case "stop":
149 void value.stop();
150 break;
151 case "cancel":
152 value.cancel();
153 break;
154 case "settings":
155 value.cancel();
156 void navigate({ to: "/settings/voice" });
157 break;
158 case "skip":
159 value.skipPostProcessing();
160 break;
161 case "blur":
162 keys.current?.blur();
163 break;
164 case "key": {
165 if (!event.keyboard) break;
166 keys.current?.[event.keyboard.type](
167 new KeyboardEvent(event.keyboard.type, event.keyboard),
168 );
169 break;
170 }
171 }
172 },
173 ),
174 [tabId, config.sessionId, publish, navigate],
175 );
176 return (
177 <VoiceInputSetup
178 environmentId={speech.transcriptionEnvironmentId}
179 open={speech.setup.open}
180 step={speech.setup.step}
181 status={speech.status}
182 model={speech.setup.model}
183 language={speech.setup.language}
184 downloading={speech.setup.downloading}
185 error={speech.setup.error}
186 onOpenChange={speech.setup.setOpen}
187 onRetryCatalog={speech.setup.retryCatalog}
188 onDownload={() => void speech.setup.download()}
189 onCancelDownload={() => void speech.setup.cancelDownload()}
190 onStartRecording={() => void speech.setup.startRecording()}
191 />
192 );