Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/mobile/src/features/threads/ThreadComposer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
ownerKey: composerDraftKey,
label: props.selectedThread.title || "Untitled thread",
environmentId: props.environmentId,
threadId: props.selectedThread.id,
readDraftMessage: () => getComposerDraftSnapshot(composerDraftKey).text,
subscribeToDraftChanges: (onChange) => appAtomRegistry.subscribe(composerDraftsAtom, onChange),
selection: composerMenu.selection,
Expand Down
22 changes: 22 additions & 0 deletions apps/mobile/src/features/voice-input/GlobalVoiceInputControl.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import { FullWindowOverlay } from "react-native-screens";

import { AppText as Text } from "../../components/ui/AppText";
import { Toast } from "../../components/ui/Toast";
import { SymbolView } from "../../components/ui/AppSymbol";
import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing";
import { cn } from "../../lib/cn";
Expand Down Expand Up @@ -53,10 +54,31 @@ export function GlobalVoiceInputControl(props: { readonly children: ReactNode })
{props.children}
</View>
{pill && Platform.OS === "ios" ? <FullWindowOverlay>{pill}</FullWindowOverlay> : pill}
{voice.cleanupNotice ? (
<CleanupNotice message={voice.cleanupNotice} onDismiss={voice.dismissCleanupNotice} />
) : null}
</>
);
}

function CleanupNotice(props: { readonly message: string; readonly onDismiss: () => void }) {
const insets = useSafeAreaInsets();
return (
<Animated.View
entering={ENTERING}
className="absolute inset-x-3"
style={{ top: insets.top + 8 }}
pointerEvents="box-none"
>
<Toast
message="Inserted the transcript without cleanup"
description={props.message}
onDismiss={props.onDismiss}
/>
</Animated.View>
);
}

function EdgeDictationPill(props: { readonly collapseRef: RefObject<(() => void) | null> }) {
const voice = useGlobalVoiceInput();
const insets = useSafeAreaInsets();
Expand Down
20 changes: 18 additions & 2 deletions apps/mobile/src/features/voice-input/VoiceInputProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ import { VoiceInputSession } from "./voiceInputSession";

const INITIAL_STATE: VoiceInputState = { phase: "idle", error: null, errorAction: null };
const VOICE_METERING_INTERVAL_MS = 80;
const CLEANUP_NOTICE_MS = 6_000;
// The native constructor expects platform-flattened options, as built by useAudioRecorder.
const { ios: IOS_RECORDING_OPTIONS, android: ANDROID_RECORDING_OPTIONS } =
RecordingPresets.HIGH_QUALITY;
Expand Down Expand Up @@ -119,6 +120,14 @@ function useVoiceInputRuntime() {
});
}, []);
const [elapsedSeconds, setElapsedSeconds] = useState(0);
// The transcript is still inserted; this only says why it was not cleaned up.
const [cleanupNotice, setCleanupNotice] = useState<string | null>(null);
useEffect(() => {
if (cleanupNotice === null) return;
const timeout = setTimeout(() => setCleanupNotice(null), CLEANUP_NOTICE_MS);
return () => clearTimeout(timeout);
}, [cleanupNotice]);
const dismissCleanupNotice = useCallback(() => setCleanupNotice(null), []);
const keepAwakeId = useId();
const keepAwakeSessionRef = useRef(0);
const elapsedSecondsRef = useRef(0);
Expand Down Expand Up @@ -162,8 +171,13 @@ function useVoiceInputRuntime() {
getTranscriber: () => {
const environmentId = sessionRef.current?.environmentId ?? null;
return (
(environmentId ? getEnvironmentVoiceTranscriber(environmentId) : null) ??
getLocalVoiceTranscriber()
(environmentId
? getEnvironmentVoiceTranscriber(
environmentId,
sessionRef.current?.threadId ?? null,
setCleanupNotice,
)
: null) ?? getLocalVoiceTranscriber()
);
},
requestPermission: async () => {
Expand Down Expand Up @@ -270,6 +284,8 @@ function useVoiceInputRuntime() {
state,
audioLevels,
elapsedSeconds,
cleanupNotice,
dismissCleanupNotice,
isBusy: voiceInputBlocksSubmission(state),
ownerKey,
label,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@ import {
environmentSpeechToTextAvailable,
type VoiceTranscriber,
} from "@t3tools/client-runtime/voice-input";
import { AuthOrchestrationOperateScope, type EnvironmentId } from "@t3tools/contracts";
import {
AuthOrchestrationOperateScope,
AuthOrchestrationReadScope,
type EnvironmentId,
type ThreadId,
} from "@t3tools/contracts";
import * as Option from "effect/Option";

import { appAtomRegistry } from "../../state/atom-registry";
Expand All @@ -27,6 +32,8 @@ export function environmentVoiceTranscriptionAvailable(environmentId: Environmen
/** Sends recordings to the environment when it has a speech-to-text service set up. */
export function getEnvironmentVoiceTranscriber(
environmentId: EnvironmentId,
threadId: ThreadId | null,
onCleanupError: (message: string) => void,
): VoiceTranscriber | null {
if (!environmentVoiceTranscriptionAvailable(environmentId)) return null;
const config = appAtomRegistry.get(serverEnvironment.configValueAtom(environmentId));
Expand All @@ -41,7 +48,16 @@ export function getEnvironmentVoiceTranscriber(
const result = await runAtomCommand(
appAtomRegistry,
serverEnvironment.createSpeechToTextUploadUrl,
{ environmentId, input },
{
environmentId,
input: {
...input,
// Naming a thread needs read access; without it cleanup runs without context.
...(threadId && readEnvironmentScope(environmentId, AuthOrchestrationReadScope)
? { threadId }
: {}),
},
},
{ reportFailure: false },
);
if (result._tag !== "Success") {
Expand All @@ -62,6 +78,7 @@ export function getEnvironmentVoiceTranscriber(
if (!url) throw new Error("This environment is not connected.");
return url;
},
onCleanupError,
upload: async ({ url, uri, mimeType, signal }) => {
const { File, UploadType } = await import("expo-file-system");
const result = await new File(uri).upload(url, {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@ import {

import { useAtomValue } from "@effect/atom-react";
import { environmentSpeechToTextAvailable } from "@t3tools/client-runtime/voice-input";
import { AuthOrchestrationOperateScope, type EnvironmentId } from "@t3tools/contracts";
import {
AuthOrchestrationOperateScope,
type EnvironmentId,
type ThreadId,
} from "@t3tools/contracts";
import { Atom } from "effect/reactivity";

import type { ComposerEditorSelection } from "../../components/ComposerEditor";
Expand All @@ -24,6 +28,7 @@ export function useVoiceInputController(input: {
readonly label: string;
/** Lets the environment's speech-to-text service transcribe this draft when one is set up. */
readonly environmentId: EnvironmentId | null;
readonly threadId?: ThreadId | null;
readonly readDraftMessage: () => string | null;
readonly subscribeToDraftChanges: (onChange: () => void) => () => void;
readonly selection: ComposerEditorSelection;
Expand Down Expand Up @@ -77,6 +82,7 @@ export function useVoiceInputController(input: {
),
label: captured.label,
environmentId: captured.environmentId,
threadId: captured.threadId ?? null,
});
}, [session]);
const state = global.ownerKey === input.ownerKey ? global.state : IDLE_STATE;
Expand Down
8 changes: 7 additions & 1 deletion apps/mobile/src/features/voice-input/voiceInputSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ import {
type VoiceDraftSnapshot,
type VoiceInputControllerDependencies,
} from "@t3tools/client-runtime/voice-input";
import type { EnvironmentId } from "@t3tools/contracts";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";

export type VoiceInputTarget = {
readonly ownerKey: string;
readonly label?: string;
/** The environment whose speech-to-text service may transcribe this draft. */
readonly environmentId?: EnvironmentId | null;
/** Gives dictation cleanup the thread's recent messages for spelling. */
readonly threadId?: ThreadId | null;
readonly readDraft: () => VoiceDraftSnapshot | null;
readonly commitDraft: VoiceInputControllerDependencies["commitDraft"];
readonly subscribe: () => () => void;
Expand Down Expand Up @@ -77,6 +79,10 @@ export class VoiceInputSession {
return this.target?.environmentId ?? null;
}

get threadId(): ThreadId | null {
return this.target?.threadId ?? null;
}

cancel(ownerKey: string | null): void {
if (ownerKey !== null && this.ownerKey === ownerKey) this.controller.cancel();
}
Expand Down
38 changes: 38 additions & 0 deletions apps/server/src/auth/RpcAuthorization.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,44 @@ it.effect("separates host file URLs from readable attachment URLs", () =>
}).pipe(Effect.scoped),
);

it.effect("requires thread read access before dictation may use a thread as context", () =>
Effect.gen(function* () {
const group = WsRpcGroup.omit(
...[...WsRpcGroup.requests.keys()].filter(
(
tag,
): tag is Exclude<
keyof typeof RPC_REQUIRED_SCOPES,
typeof WS_METHODS.speechToTextCreateUploadUrl
> => tag !== WS_METHODS.speechToTextCreateUploadUrl,
),
);
let handled = 0;
const client = yield* RpcTest.makeClient(group).pipe(
Effect.provide(
Layer.mergeAll(
group.toLayerHandler(WS_METHODS.speechToTextCreateUploadUrl, () =>
Effect.sync(() => {
handled++;
return { relativeUrl: "/api/speech-to-text/transcriptions/token", expiresAt: 1 };
}),
),
RpcAuthorization.layer([AuthOrchestrationOperateScope]),
),
),
);
const upload = { mimeType: "audio/webm", sizeBytes: 1 };
yield* client[WS_METHODS.speechToTextCreateUploadUrl](upload);
expect(
yield* client[WS_METHODS.speechToTextCreateUploadUrl]({
...upload,
threadId: ThreadId.make("thread"),
}).pipe(Effect.flip),
).toMatchObject({ requiredScope: AuthOrchestrationReadScope });
expect(handled).toBe(1);
}).pipe(Effect.scoped),
);

it.effect("denies manual cleanup before the handler without settings permission", () =>
Effect.gen(function* () {
const group = WsRpcGroup.omit(
Expand Down
9 changes: 9 additions & 0 deletions apps/server/src/auth/RpcAuthorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
ProviderInstanceMutation,
requiredScopesForServerSettingsPatch,
requiredScopesForProjectMutation,
SpeechToTextCreateUploadUrlInput,
ProjectMutation,
AuthSettingsWriteScope,
AuthProvidersManageScope,
Expand Down Expand Up @@ -244,6 +245,7 @@ const requiredScopesForSettingsUpdate = (payload: unknown) => {
};

const decodeProjectMutation = Schema.decodeUnknownSync(ProjectMutation);
const decodeSpeechToTextUploadUrlInput = Schema.decodeUnknownSync(SpeechToTextCreateUploadUrlInput);

const requiredScopesForRpcCall = (
method: string,
Expand All @@ -262,6 +264,13 @@ const requiredScopesForRpcCall = (
: AuthOrchestrationReadScope,
];
}
if (method === WS_METHODS.speechToTextCreateUploadUrl) {
// Thread context sends that thread's messages to the cleanup model, which is a read.
const { threadId } = decodeSpeechToTextUploadUrlInput(payload);
return threadId === undefined
? [AuthOrchestrationOperateScope]
: [AuthOrchestrationOperateScope, AuthOrchestrationReadScope];
}
if (method === WS_METHODS.serverUpdateSettings) return requiredScopesForSettingsUpdate(payload);
if (method === WS_METHODS.projectsMutate) {
return requiredScopesForProjectMutation(decodeProjectMutation(payload));
Expand Down
8 changes: 8 additions & 0 deletions apps/server/src/provider/Drivers/CodexManagedProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
} from "@t3tools/provider-core/server/driver";
import { codexContinuationIdentity } from "./CodexHomeLayout.ts";
import { withInstanceIdentity } from "@t3tools/provider-core/server/instanceIdentity";
import type { DictationCleanupInput } from "@t3tools/provider-core/server/textGeneration";
import { HttpClient } from "effect/http";
const DRIVER = ProviderDriverKind.make("codex");

Expand Down Expand Up @@ -273,6 +274,7 @@ export const makeManagedCodexProvider = Effect.fn("makeManagedCodexProvider")(fu
}),
),
);
const nativeCleanDictation = nativeGeneration.cleanDictation;
const textGeneration: ProviderInstance["textGeneration"] = {
generateCommitMessage: (value) =>
protect("generateCommitMessage", nativeGeneration.generateCommitMessage(value)),
Expand All @@ -284,6 +286,12 @@ export const makeManagedCodexProvider = Effect.fn("makeManagedCodexProvider")(fu
protect("generateThreadTitle", nativeGeneration.generateThreadTitle(value)),
generateReviewGuide: (value) =>
protect("generateReviewGuide", nativeGeneration.generateReviewGuide(value)),
...(nativeCleanDictation
? {
cleanDictation: (value: DictationCleanupInput) =>
protect("cleanDictation", nativeCleanDictation(value)),
}
: {}),
};
return {
instanceId,
Expand Down
8 changes: 8 additions & 0 deletions apps/server/src/serverSettings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1301,13 +1301,21 @@ it.layer(NodeServices.layer)("server settings", (it) => {
provider: "groq",
language: "de",
providers: { groq: { apiKey: "groq-secret", model: "whisper-large-v3" } },
cleanup: { mode: "openai-compatible", apiKey: "cleanup-secret" },
},
});
assert.strictEqual(saved.speechToText.cleanup.apiKey, "cleanup-secret");
assert.strictEqual(
ServerSettingsModule.redactServerSettingsForClient(saved).speechToText.cleanup.apiKey,
"••••••",
);
assert.isTrue(Option.isSome(yield* store.get("speech-to-text-cleanup-YXBpS2V5")));
assert.strictEqual(saved.speechToText.providers.groq?.apiKey, "groq-secret");
const client = ServerSettingsModule.redactServerSettingsForClient(saved);
assert.strictEqual(client.speechToText.providers.groq?.apiKey, "••••••");
assert.strictEqual(client.speechToText.providers.groq?.model, "whisper-large-v3");
assert.notInclude(yield* fs.readFileString(config.settingsPath), "groq-secret");
assert.notInclude(yield* fs.readFileString(config.settingsPath), "cleanup-secret");
const secretName = "speech-to-text-Z3JvcQ-YXBpS2V5";
assert.isTrue(Option.isSome(yield* store.get(secretName)));

Expand Down
12 changes: 11 additions & 1 deletion apps/server/src/settingsSecrets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
CodexSettings,
EasDeviceHostConfig,
type ServerSettings,
SpeechToTextCleanupSettings,
SpeechToTextProviderSettings,
UsageLimitSourceConfig,
secretSettingsFields,
Expand Down Expand Up @@ -35,6 +36,7 @@ const providerSecretFields = new Map([
const usageLimitSecretFields = secretSettingsFields(UsageLimitSourceConfig);
const easDeviceHostSecretFields = secretSettingsFields(EasDeviceHostConfig);
const speechToTextSecretFields = secretSettingsFields(SpeechToTextProviderSettings);
const speechToTextCleanupSecretFields = secretSettingsFields(SpeechToTextCleanupSettings);
const encode = (value: string) => Buffer.from(value, "utf8").toString("base64url");

export interface SettingsSecret {
Expand Down Expand Up @@ -174,6 +176,14 @@ export function mapSettingsSecrets(
sourceControlHosts,
usageLimitSources,
easDeviceHosts,
speechToText: { ...settings.speechToText, providers: speechToTextProviders },
speechToText: {
...settings.speechToText,
providers: speechToTextProviders,
cleanup: mapFields(
settings.speechToText.cleanup,
speechToTextCleanupSecretFields,
(field) => `speech-to-text-cleanup-${encode(field)}`,
) as ServerSettings["speechToText"]["cleanup"],
},
};
}
Loading
Loading