Open History to see the last commit
1import { EnvironmentId } from "@t3tools/contracts";
2import { Atom } from "effect/reactivity";
3import { expect, it, vi } from "vite-plus/test";
4import { appAtomRegistry } from "../../state/atom-registry";
5import { chooseVoiceDestination, voiceGrantAtom, voiceRouteAtom } from "./voiceDestination";
6import { readVoiceGrant } from "./voiceGrantStorage";
7
8const mocks = vi.hoisted(() => ({
9 read: vi.fn<() => Promise<string | null>>(async () => null),
10 write: vi.fn(),
11 markerRead: vi.fn<() => string>(),
12 markerWrite: vi.fn<(id: string) => void>(),
13 probe: vi.fn(),
14 fetch: vi.fn<typeof fetch>(),
15}));
16vi.mock("expo", () => ({
17 requireOptionalNativeModule: () => ({ decodeRecording: async () => new Uint8Array([0, 0]) }),
18}));
19vi.mock("expo/fetch", () => ({ fetch: mocks.fetch }));
20vi.mock("expo-file-system", () => ({
21 Paths: { document: "file:///app/" },
22 File: class {
23 textSync = mocks.markerRead;
24 writeSync = mocks.markerWrite;
25 write(id: string) {
26 return Promise.resolve().then(() => mocks.markerWrite(id));
27 }
28 },
29}));
30vi.mock("expo-secure-store", () => ({
31 getItemAsync: mocks.read,
32 setItem: mocks.write,
33 WHEN_UNLOCKED_THIS_DEVICE_ONLY: 6,
34}));
35vi.mock("../../lib/uuid", () => {
36 let nextGrant = 0;
37 return { uuidv4: () => `test-grant-${++nextGrant}` };
38});
39vi.mock("../../lib/protectedData", () => ({ whenProtectedDataAvailable: async () => {} }));
40vi.mock("../../connection/runtime", async () => ({
41 connectionAtomRuntime: Atom.runtime((await import("effect/http")).FetchHttpClient.layer),
42}));
43vi.mock("../../state/presentation", () => ({
44 environmentPresentations: {
45 presentationAtom: Atom.family((id: string) => {
46 mocks.probe(id);
47 return Atom.make({
48 connection: { phase: id === "offline" ? "offline" : "connected" },
49 serverConfig: { environment: { capabilities: { voiceTranscription: true } } },
50 });
51 }),
52 },
53}));
54vi.mock("../../state/session", async () => {
55 const Option = await import("effect/Option");
56 return {
57 environmentSession: {
58 preparedConnectionValueAtom: Atom.family((environmentId: string) =>
59 Atom.make(
60 Option.some({
61 environmentId,
62 httpBaseUrl: `https://${environmentId}.test`,
63 httpAuthorization: { _tag: "Bearer", token: "fixture" },
64 }),
65 ),
66 ),
67 sessionStateAtom: Atom.family((_id: string) => Atom.make(true)),
68 },
69 sessionHasScope: () => true,
70 };
71});
72
73it.each(["secure store", "marker"])(
74 "revokes across restarts when writing the %s fails",
75 async (failedStore) => {
76 let saved: string | null = null;
77 let marker = "";
78 mocks.read.mockImplementation(async () => saved);
79 mocks.write.mockImplementation((_key: string, value: string) => {
80 saved = value;
81 });
82 mocks.markerRead.mockImplementation(() => marker);
83 mocks.markerWrite.mockImplementation((id) => {
84 marker = id;
85 });
86 const host = EnvironmentId.make("my-server");
87 try {
88 chooseVoiceDestination(host);
89 expect(marker).toBe(appAtomRegistry.get(voiceGrantAtom)?.id);
90 expect((await readVoiceGrant())?.destination.environmentId).toBe(host);
91 mocks.markerRead.mockReturnValueOnce("");
92 expect(await readVoiceGrant()).toBeNull();
93 const old = { saved, marker };
94 const failedWrite = failedStore === "secure store" ? mocks.write : mocks.markerWrite;
95 failedWrite.mockImplementationOnce(() => {
96 throw new Error("storage unavailable");
97 });
98 chooseVoiceDestination(null);
99 expect(failedStore === "secure store" ? saved : marker).toBe(
100 failedStore === "secure store" ? old.saved : old.marker,
101 );
102 expect(await readVoiceGrant()).toBeNull();
103 chooseVoiceDestination(host);
104 failedWrite.mockImplementationOnce(() => {
105 throw new Error("storage unavailable");
106 });
107 expect(() => chooseVoiceDestination(EnvironmentId.make("other-host"))).toThrow();
108 expect(appAtomRegistry.get(voiceGrantAtom)).toBeNull();
109 expect(await readVoiceGrant()).toBeNull();
110 } finally {
111 mocks.read.mockReset();
112 mocks.write.mockReset();
113 mocks.markerRead.mockReset();
114 mocks.markerWrite.mockReset();
115 appAtomRegistry.reset();
116 }
117 },
118);
119
120it("keeps local as the default and never reuses consent for an offline or reselected host", async () => {
121 const unmount = appAtomRegistry.mount(voiceRouteAtom);
122 try {
123 expect(appAtomRegistry.get(voiceRouteAtom)).toBeNull();
124 expect(mocks.probe).not.toHaveBeenCalled();
125 chooseVoiceDestination(EnvironmentId.make("offline"));
126 expect(appAtomRegistry.get(voiceRouteAtom)).toEqual({ transcriber: null });
127 const host = EnvironmentId.make("my-server");
128 chooseVoiceDestination(host);
129 const first = appAtomRegistry.get(voiceRouteAtom)?.transcriber;
130 expect(first).toBeTruthy();
131 chooseVoiceDestination(null);
132 expect(appAtomRegistry.get(voiceRouteAtom)).toBeNull();
133 chooseVoiceDestination(host);
134 const current = appAtomRegistry.get(voiceRouteAtom)?.transcriber;
135 await expect(first!.prepare({ signal: new AbortController().signal })).rejects.toThrow(
136 "Your transcription choice changed.",
137 );
138 expect(mocks.fetch).not.toHaveBeenCalled();
139 mocks.fetch
140 .mockResolvedValueOnce(
141 Response.json({
142 supported: true,
143 state: "ready",
144 modelId: "fixture",
145 model: "Fixture",
146 size: 1,
147 supportsStreaming: false,
148 supportsTranslation: false,
149 acceleration: "cpu",
150 modelUnloadTimeout: "never",
151 gpuDevices: [],
152 }),
153 )
154 .mockResolvedValueOnce(Response.json({ text: "hello" }));
155 const options = { signal: new AbortController().signal };
156 const recording = await current!.prepare(options);
157 await expect(recording.transcribe("file:///voice.m4a", options)).resolves.toBe("hello");
158 expect(mocks.fetch.mock.calls.map(([url, init]) => [String(url), init?.redirect])).toEqual([
159 ["https://my-server.test/api/voice/status", "error"],
160 ["https://my-server.test/api/voice/transcribe", "error"],
161 ]);
162 const failWrite = () => {
163 throw new Error("Device storage is unavailable");
164 };
165 mocks.markerWrite.mockImplementationOnce(failWrite);
166 mocks.write.mockImplementationOnce(failWrite);
167 expect(() => chooseVoiceDestination(null)).toThrow("Device storage is unavailable");
168 expect(appAtomRegistry.get(voiceGrantAtom)).toBeNull();
169 await expect(current!.prepare(options)).rejects.toThrow("Your transcription choice changed.");
170 } finally {
171 unmount();
172 appAtomRegistry.reset();
173 }
174});