Skip to content

Commit a7c5392

Browse files
voltcrashcodex
andcommitted
fix(web): retain session permissions during confirmed dictation
Co-Authored-By: GPT-6.1 Sol <[email protected]>
1 parent b16777a commit a7c5392

2 files changed

Lines changed: 61 additions & 14 deletions

File tree

‎apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx‎

Lines changed: 53 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { page, userEvent } from "vite-plus/test/browser";
44
import * as Deferred from "effect/Deferred";
55
import * as Effect from "effect/Effect";
66
import * as Option from "effect/Option";
7+
import { AsyncResult, Atom } from "effect/reactivity";
78
import type { PreparedConnection } from "@t3tools/client-runtime/connection";
89
import { getEnvironmentSpeechModels } from "@t3tools/client-runtime/voice-input";
910
import {
@@ -17,7 +18,7 @@ import {
1718
type SpeechTranscriptionOptions,
1819
} from "@t3tools/contracts";
1920

20-
import { act, render, stubGlobal } from "../../test/render";
21+
import { act, fakeTimers, render, stubGlobal } from "../../test/render";
2122
import { VoiceInputSetup } from "../components/chat/VoiceInputSetup";
2223
import type { createBrowserVoiceInputPlatform } from "./browserVoiceInput";
2324
import { useEnvironmentSpeechInput } from "./useEnvironmentSpeechInput";
@@ -28,6 +29,7 @@ import {
2829
pendingCloudAudioChoice,
2930
} from "./voiceConsent";
3031
import { writeBrowserClientSettings } from "../clientPersistenceStorage";
32+
import { AppAtomRegistryProvider } from "../rpc/atomRegistry";
3133

3234
const mocks = vi.hoisted(() => ({
3335
voice: undefined as unknown as ReturnType<typeof useEnvironmentSpeechInput>,
@@ -36,6 +38,7 @@ const mocks = vi.hoisted(() => ({
3638
voiceCapable: new Set<string>(),
3739
cloudVoiceCapable: new Set<string>(),
3840
canDictate: new Set<string>(),
41+
sessionAtoms: new Map<string, Atom.Atom<AsyncResult.AsyncResult<boolean>>>(),
3942
prepared: new Map<string, unknown>(),
4043
primaryEnvironmentId: "primary-env",
4144
statusRequests: [] as string[],
@@ -62,18 +65,33 @@ const mocks = vi.hoisted(() => ({
6265
drafts: {} as Record<string, string>,
6366
}));
6467

65-
vi.mock("../state/session", () => ({
66-
useEnvironmentScope: (id: string) => mocks.canDictate.has(id),
67-
usePreparedConnection: (environmentId: string | null) => {
68-
if (!environmentId || !mocks.connected.has(environmentId)) return Option.none();
69-
let prepared = mocks.prepared.get(environmentId);
70-
if (!prepared) {
71-
prepared = { environmentId, label: environmentId };
72-
mocks.prepared.set(environmentId, prepared);
68+
vi.mock("../state/session", async () => {
69+
const { useAtomValue } = await import("@effect/atom-react");
70+
const { AsyncResult, Atom } = await import("effect/reactivity");
71+
const sessionStateAtom = (id: string) => {
72+
let atom = mocks.sessionAtoms.get(id);
73+
if (!atom) {
74+
atom = Atom.make(AsyncResult.success(true));
75+
mocks.sessionAtoms.set(id, atom);
7376
}
74-
return Option.some(prepared);
75-
},
76-
}));
77+
return atom;
78+
};
79+
return {
80+
environmentSession: { sessionStateAtom },
81+
useEnvironmentScope: (id: string) =>
82+
AsyncResult.getOrElse(useAtomValue(sessionStateAtom(id)), () => false) &&
83+
mocks.canDictate.has(id),
84+
usePreparedConnection: (environmentId: string | null) => {
85+
if (!environmentId || !mocks.connected.has(environmentId)) return Option.none();
86+
let prepared = mocks.prepared.get(environmentId);
87+
if (!prepared) {
88+
prepared = { environmentId, label: environmentId };
89+
mocks.prepared.set(environmentId, prepared);
90+
}
91+
return Option.some(prepared);
92+
},
93+
};
94+
});
7795
vi.mock("../state/environments", () => ({
7896
usePrimaryEnvironmentId: () => mocks.primaryEnvironmentId,
7997
useEnvironment: (environmentId: string | null) =>
@@ -215,6 +233,7 @@ function setup(options: { readonly destination?: string | null } = {}) {
215233
mocks.voiceCapable = new Set(["primary-env", THREAD_ENV, "env-a", "env-b"]);
216234
mocks.cloudVoiceCapable.clear();
217235
mocks.canDictate = new Set(mocks.voiceCapable);
236+
mocks.sessionAtoms.clear();
218237
mocks.prepared.clear();
219238
mocks.statusRequests = [];
220239
mocks.statusUnavailable = false;
@@ -365,7 +384,15 @@ it.each([
365384
expect(mocks.committed).not.toHaveBeenCalled();
366385
});
367386

368-
function SubmissionProbe({
387+
function SubmissionProbe(props: Parameters<typeof SubmissionProbeContent>[0]) {
388+
return (
389+
<AppAtomRegistryProvider>
390+
<SubmissionProbeContent {...props} />
391+
</AppAtomRegistryProvider>
392+
);
393+
}
394+
395+
function SubmissionProbeContent({
369396
owner,
370397
environmentId = THREAD_ENV,
371398
}: {
@@ -439,10 +466,21 @@ it.each([
439466
["transcribing", "cancel"],
440467
["post-processing", "cancel"],
441468
["post-processing", "skip"],
469+
["transcribing", "finish after session expiry"],
442470
] as const)(
443471
"reattaches a confirmed %s submission after remount to %s it",
444472
async (phase, action) => {
445473
setup({ destination: "env-a" });
474+
const expires = action === "finish after session expiry";
475+
if (expires) {
476+
let reads = 0;
477+
mocks.sessionAtoms.set(
478+
"env-a",
479+
Atom.make(Effect.suspend(() => (++reads === 1 ? Effect.succeed(true) : Effect.never))).pipe(
480+
Atom.setIdleTTL(5 * 60_000),
481+
),
482+
);
483+
}
446484
let finish!: (text: string) => void;
447485
const result = new Promise<string>((resolve) => {
448486
finish = resolve;
@@ -461,10 +499,12 @@ it.each([
461499
const submit = vi.fn();
462500
const cancel = vi.fn();
463501
await using screen = await render(<SubmissionProbe owner="thread-a" />);
502+
using _timers = expires ? fakeTimers() : { [Symbol.dispose]() {} };
464503
await act(() => mocks.voice.start());
465504
await act(() => mocks.voice.submitAfterDictation(submit, cancel));
466505
await vi.waitFor(() => expect(mocks.voice.state.phase).toBe(phase));
467506
await screen.rerender(<div />);
507+
if (expires) await act(() => vi.advanceTimersByTimeAsync(6 * 60_000));
468508
await screen.rerender(<SubmissionProbe owner="thread-b" />);
469509
expect(mocks.voice.state.phase).toBe("idle");
470510
await act(() => mocks.voice.cancel());

‎apps/web/src/speech/useEnvironmentSpeechInput.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,8 @@ import {
3636
useEnvironmentSettings,
3737
} from "../hooks/useSettings";
3838
import { useEnvironment } from "../state/environments";
39-
import { useEnvironmentScope, usePreparedConnection } from "../state/session";
39+
import { appAtomRegistry } from "../rpc/atomRegistry";
40+
import { environmentSession, useEnvironmentScope, usePreparedConnection } from "../state/session";
4041
import { createBrowserVoiceInputPlatform } from "./browserVoiceInput";
4142
import { preferredSpeechLanguages } from "./preferredSpeechLanguages";
4243
import { runEnvironmentSpeech } from "./runEnvironmentSpeech";
@@ -136,6 +137,7 @@ type ConfirmedSubmission = {
136137
readonly grantId: string;
137138
readonly state: VoiceInputState;
138139
readonly cancel: () => void;
140+
readonly releaseSession: () => void;
139141
unsubscribeConsent: () => void;
140142
};
141143

@@ -158,6 +160,7 @@ function clearConfirmedSubmission(pending: PendingSubmission) {
158160
const entry = confirmedSubmissions.get(key);
159161
if (entry?.pending !== pending) return;
160162
entry.unsubscribeConsent();
163+
entry.releaseSession();
161164
confirmedSubmissions.delete(key);
162165
notifySubmissions();
163166
}
@@ -616,6 +619,10 @@ export function useEnvironmentSpeechInput(input: HookInput) {
616619
prepared,
617620
grantId,
618621
state: controller.currentState,
622+
// Remounts must not mistake an expired permission cache for revoked access.
623+
releaseSession: appAtomRegistry.mount(
624+
environmentSession.sessionStateAtom(prepared.environmentId),
625+
),
619626
cancel: () => {
620627
cancelSubmission();
621628
controller.dispose();

0 commit comments

Comments
 (0)