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

native.test.ts

317 lines11.1 KB

1// @effect-diagnostics nodeBuiltinImport:off - verifies isolated native worker processes and their exit events.
2import { expect, it } from "vite-plus/test";
3​
4import { loadNativeSpeechModel } from "./native.ts";
5​
6const fixture = (transcribe: string, maxAudioMs = 0, supportsVocabulary = false) =>
7 `data:text/javascript,${encodeURIComponent(`export const TranscribeModel = { load: async () => ({ capabilities: { supportsStreaming: false, maxAudioMs: ${maxAudioMs} }, supports: (feature) => feature === "vocabulary" && ${supportsVocabulary}, transcribe: ${transcribe} }) };`)}`;
8​
9const fixtureWithUnrelatedIpcMessage = () =>
10 `data:text/javascript,${encodeURIComponent(`
11 process.send?.({ type: "unrelated-control-message" });
12 export const TranscribeModel = {
13 load: async () => ({ capabilities: { supportsStreaming: false }, supports: () => false, transcribe: async () => ({ text: "hello" }) }),
14 };
15 `)}`;
16​
17const streamingFixture = (feed: string, supportsVocabulary = false) =>
18 `data:text/javascript,${encodeURIComponent(`
19 export const TranscribeModel = { load: async () => ({
20 capabilities: { supportsStreaming: true },
21 supports: (feature) => feature === "vocabulary" && ${supportsVocabulary},
22 createSession: () => ({
23 dispose() {},
24 stream: async (opts) => ({
25 feed: ${feed},
26 finalize: async () => {},
27 text: { full: opts.vocabulary?.join(" / ") ?? opts.language ?? "hello world", committed: "hello ", tentative: "world" },
28 reset() {},
29 }),
30 }),
31 }) };
32`)}`;
33​
34it("returns transcription from an isolated process and disposes it", async () => {
35 const model = await loadNativeSpeechModel(
36 "unused.gguf",
37 new AbortController().signal,
38 fixture("async (pcm) => ({ text: String(pcm[0]) })"),
39 );
40 try {
41 expect(
42 await model.transcribe(
43 new Float32Array([0.25]),
44 { timestamps: "none", language: "en" },
45 false,
46 ),
47 ).toEqual({ text: "0.25" });
48 } finally {
49 await model.dispose();
50 }
51});
52​
53it("probes generic vocabulary support and delivers ordered terms to offline inference", async () => {
54 for (const supported of [false, true]) {
55 const model = await loadNativeSpeechModel(
56 "unused.gguf",
57 new AbortController().signal,
58 fixture("async (_pcm, options) => ({ text: JSON.stringify(options) })", 0, supported),
59 );
60 try {
61 expect(model.supportsVocabulary).toBe(supported);
62 const options = {
63 timestamps: "none" as const,
64 language: "en",
65 ...(supported ? { vocabulary: ["T3 Code", "GitHub"] } : {}),
66 };
67 const result = await model.transcribe(new Float32Array([0.25]), options, false);
68 expect(JSON.parse(result.text)).toEqual(options);
69 } finally {
70 await model.dispose();
71 }
72 }
73});
74​
75it("ignores IPC messages that do not belong to the speech protocol", async () => {
76 const model = await loadNativeSpeechModel(
77 "unused.gguf",
78 new AbortController().signal,
79 fixtureWithUnrelatedIpcMessage(),
80 );
81 try {
82 await expect(
83 model.transcribe(new Float32Array([0.25]), { timestamps: "none", language: "en" }, false),
84 ).resolves.toEqual({ text: "hello" });
85 } finally {
86 await model.dispose();
87 }
88});
89​
90it("terminates hung native inference when the service shuts down", async () => {
91 const controller = new AbortController();
92 const model = await loadNativeSpeechModel(
93 "unused.gguf",
94 controller.signal,
95 fixture("async () => { while (true) {} }"),
96 );
97 const pending = model.transcribe(
98 new Float32Array([0.25]),
99 {
100 timestamps: "none",
101 language: "en",
102 },
103 false,
104 );
105 const rejected = expect(pending).rejects.toThrow();
106 controller.abort();
107 await model.dispose();
108 await rejected;
109});
110​
111it("returns streaming previews and final text from an isolated process", async () => {
112 const model = await loadNativeSpeechModel(
113 "unused.gguf",
114 new AbortController().signal,
115 streamingFixture(
116 "async () => ({ revision: 1, committedChanged: true, tentativeChanged: true })",
117 true,
118 ),
119 );
120 try {
121 expect(model.supportsStreaming).toBe(true);
122 await model.begin({ timestamps: "none" }, false);
123 expect(await model.feed(new Float32Array(512).fill(0.25))).toEqual({
124 revision: 1,
125 text: { committed: "hello ", tentative: "world" },
126 });
127 expect(await model.finish()).toBe("hello world");
128 await model.begin({ timestamps: "none", language: "fr" }, false);
129 await model.reset();
130 await model.begin({ timestamps: "none", language: "fr" }, false);
131 await model.feed(new Float32Array(512));
132 expect(await model.finish()).toBe("fr");
133 await model.begin(
134 { timestamps: "none", language: "fr", vocabulary: ["T3 Code", "GitHub"] },
135 false,
136 );
137 await model.feed(new Float32Array(512).fill(0.25));
138 expect(await model.finish()).toBe("T3 Code / GitHub");
139 } finally {
140 await model.dispose();
141 }
142});
143​
144it("kills a hung streaming feed without waiting for native cleanup", async () => {
145 const controller = new AbortController();
146 const model = await loadNativeSpeechModel(
147 "unused.gguf",
148 controller.signal,
149 streamingFixture("async () => { while (true) {} }"),
150 );
151 await model.begin({ timestamps: "none" }, false);
152 const rejected = expect(model.feed(new Float32Array(512).fill(0.25))).rejects.toThrow();
153 controller.abort();
154 await model.dispose();
155 await rejected;
156});
157const vadFixture = ({
158 streaming = false,
159 failVad = false,
160 failVadLoad = false,
161 failAsr = false,
162 maxAudioMs = 4000,
163} = {}) =>
164 `data:text/javascript,${encodeURIComponent(`
165 const summarize = pcm => String(pcm.length) + ":" + pcm[0].toFixed(2) + ":" + pcm[pcm.length - 1].toFixed(2);
166 export const TranscribeModel = { load: async (path, options) => {
167 if (path === "vad.gguf") {
168 if (${failVadLoad}) throw new Error("VAD unavailable");
169 if (options.backend !== "cpu") throw new Error("VAD must use CPU");
170 return { vadInfo: { sampleRate: 16000, frameSamples: 512 }, dispose() {},
171 createVadSession: ({ nThreads }) => {
172 if (nThreads !== 1) throw new Error("VAD thread count");
173 let pending = []; let at = 0;
174 const score = final => {
175 const firstFrame = at;
176 const probs = [];
177 while (pending.length >= 512 || final && pending.length) {
178 probs.push(pending[0] > 0.5 ? 0.9 : 0);
179 pending.splice(0, 512); at++;
180 }
181 return { firstFrame, probs };
182 };
183 return { dispose() {}, streamReset: async () => { pending = []; at = 0; },
184 streamFeed: async pcm => {
185 if (${failVad} && pcm[0] < 0) throw new Error("VAD fixture failed");
186 pending.push(...pcm); return score(false);
187 },
188 streamFlush: async () => score(true),
189 };
190 },
191 };
192 }
193 return { backend: "CPU", supports: () => false,
194 capabilities: { supportsStreaming: ${streaming}, maxAudioMs: ${maxAudioMs} },
195 transcribe: async pcm => { if (${failAsr}) throw new Error("ASR fixture failed"); return { text: summarize(pcm) }; },
196 createSession: () => {
197 let all = [];
198 return { dispose() {}, stream: async () => ({
199 feed: async pcm => { all.push(...pcm); return { committedChanged: true }; },
200 finalize: async () => {}, reset() { all = []; },
201 get text() { const full = summarize(all); return { committed: full, tentative: "", full }; },
202 }) };
203 },
204 };
205 }};
206 `)}`;
207​
208it("filters silence and preserves partial speech through the production worker and resets between recordings", async () => {
209 for (const streaming of [false, true]) {
210 const model = await loadNativeSpeechModel(
211 "asr.gguf",
212 new AbortController().signal,
213 vadFixture({ streaming }),
214 "cpu",
215 );
216 try {
217 expect(
218 await model.transcribe(new Float32Array(2000), { timestamps: "none" }, true, "vad.gguf"),
219 ).toEqual({ text: "" });
220 expect(
221 await model.transcribe(
222 new Float32Array([0.8, 0.6]),
223 { timestamps: "none" },
224 true,
225 "vad.gguf",
226 ),
227 ).toEqual({ text: "2:0.80:0.60" });
228 expect(
229 await model.transcribe(new Float32Array(2000), { timestamps: "none" }, false, "vad.gguf"),
230 ).toEqual({ text: "2000:0.00:0.00" });
231 for (const cancel of [true, false]) {
232 await model.begin({ timestamps: "none" }, true, "vad.gguf");
233 await model.feed(new Float32Array(600));
234 expect(await model.finish()).toBe("");
235 await model.begin({ timestamps: "none" }, true, "vad.gguf");
236 await model.feed(new Float32Array(511).fill(0.8));
237 if (cancel) await model.reset();
238 else expect(await model.finish()).toBe("511:0.80:0.80");
239 }
240 } finally {
241 await model.dispose();
242 }
243 }
244});
245​
246it("decodes complete stable chunks before Stop and returns the ordered final tail", async () => {
247 const model = await loadNativeSpeechModel(
248 "asr.gguf",
249 new AbortController().signal,
250 vadFixture(),
251 "cpu",
252 );
253 try {
254 await model.begin({ timestamps: "none" }, false, "vad.gguf");
255 await model.feed(new Float32Array(16000).fill(0.1));
256 await model.feed(new Float32Array(16000).fill(0.2));
257 const update = await model.feed(new Float32Array(16000).fill(0.3));
258 expect(update.text).toEqual({ committed: "32000:0.10:0.20", tentative: "" });
259 await model.feed(new Float32Array([0.4, 0.5]));
260 expect(await model.finish()).toBe("32000:0.10:0.20 16002:0.30:0.50");
261 } finally {
262 await model.dispose();
263 }
264});
265​
266it("preserves withheld audio on VAD failure while keeping ASR failures distinct", async () => {
267 for (const streaming of [false, true]) {
268 const model = await loadNativeSpeechModel(
269 "asr.gguf",
270 new AbortController().signal,
271 vadFixture({ streaming, failVad: true }),
272 "cpu",
273 );
274 try {
275 await model.begin({ timestamps: "none" }, true, "vad.gguf");
276 await model.feed(new Float32Array(512).fill(0.1));
277 await model.feed(new Float32Array(512).fill(-0.2));
278 expect(await model.finish()).toBe("1024:0.10:-0.20");
279 await model.begin({ timestamps: "none" }, true, "vad.gguf");
280 await model.feed(new Float32Array(512));
281 expect(await model.finish()).toBe("");
282 } finally {
283 await model.dispose();
284 }
285 }
286 const unavailable = await loadNativeSpeechModel(
287 "asr.gguf",
288 new AbortController().signal,
289 vadFixture({ failVadLoad: true }),
290 "cpu",
291 );
292 try {
293 expect(
294 await unavailable.transcribe(
295 new Float32Array(2000).fill(0.1),
296 { timestamps: "none" },
297 true,
298 "vad.gguf",
299 ),
300 ).toEqual({ text: "2000:0.10:0.10" });
301 } finally {
302 await unavailable.dispose();
303 }
304 const model = await loadNativeSpeechModel(
305 "asr.gguf",
306 new AbortController().signal,
307 vadFixture({ failAsr: true }),
308 "cpu",
309 );
310 try {
311 await expect(
312 model.transcribe(new Float32Array(512).fill(0.8), { timestamps: "none" }, true, "vad.gguf"),
313 ).rejects.toThrow("ASR fixture failed");
314 } finally {
315 await model.dispose();
316 }
317});