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

PreviewAnnotationSpeech.tsx

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