diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts index 8d70ab4c4791f..b075d4b4ac28b 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts @@ -955,6 +955,42 @@ describe("DesktopBackendConfiguration", () => { }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); + it.effect("hands the packaged Apple speech helper only to a macOS backend", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-desktop-backend-config-test-", + }); + const resourcesPath = path.join(baseDir, "resources"); + const helperPath = path.join(resourcesPath, "apple-speech/t3-apple-speech"); + yield* fileSystem.makeDirectory(path.dirname(helperPath), { recursive: true }); + yield* fileSystem.writeFileString(helperPath, "binary"); + yield* fileSystem.chmod(helperPath, 0o755); + + const resolveBootstrap = (platform: NodeJS.Platform) => + Effect.gen(function* () { + const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; + return (yield* configuration.resolvePrimary).bootstrap; + }).pipe( + Effect.provide( + layerBackendConfiguration().pipe( + Layer.provideMerge(layerServerExposure), + Layer.provideMerge(DesktopAppSettings.layerTest()), + Layer.provideMerge(DesktopWslServerTree.layerTest()), + Layer.provideMerge(DesktopWslEnvironment.layerTest()), + Layer.provideMerge( + layerEnvironment(baseDir, { platform, isPackaged: true, resourcesPath }), + ), + ), + ), + ); + + assert.equal((yield* resolveBootstrap("darwin")).appleSpeechHelperPath, helperPath); + assert.notProperty(yield* resolveBootstrap("linux"), "appleSpeechHelperPath"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + it("resolvePrimaryLabel is runSync-safe against the real WSL availability probe", async () => { // oxlint-disable-next-line t3code/no-manual-effect-runtime-in-tests -- This test intentionally replicates the sync IPC handler's runSync path to catch a regression to async-only resolution; it.effect would mask it. const runtime = ManagedRuntime.make( diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts index dadbe8acc743b..68f43a0c17004 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -170,38 +170,60 @@ function resourceMonitorBinaryName(platform: NodeJS.Platform): string { return platform === "win32" ? "t3-resource-monitor.exe" : "t3-resource-monitor"; } +const resolveBundledHelperPath = Effect.fn("desktop.backendConfiguration.resolveBundledHelperPath")( + function* (input: { + readonly directory: string; + readonly binaryName: string; + readonly devBuildDirectories: ReadonlyArray; + }) { + const environment = yield* DesktopEnvironment.DesktopEnvironment; + const fileSystem = yield* FileSystem.FileSystem; + const candidates = environment.isDevelopment + ? input.devBuildDirectories.map((directory) => + environment.path.join(environment.rootDir, directory, input.binaryName), + ) + : environment.isPackaged + ? [environment.path.join(environment.resourcesPath, input.directory, input.binaryName)] + : environment.resolveResourcePathCandidates( + environment.path.join(input.directory, input.binaryName), + ); + + for (const candidate of candidates) { + if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) { + return Option.some(candidate); + } + } + + return Option.none(); + }, +); + const resolveResourceMonitorPath = Effect.fn( "desktop.backendConfiguration.resolveResourceMonitorPath", )(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; - const fileSystem = yield* FileSystem.FileSystem; - const binaryName = resourceMonitorBinaryName(environment.platform); - const candidates = environment.isDevelopment - ? [ - environment.path.join( - environment.rootDir, - "native/resource-monitor/target/release", - binaryName, - ), - environment.path.join( - environment.rootDir, - "native/resource-monitor/target/debug", - binaryName, - ), - ] - : environment.isPackaged - ? [environment.path.join(environment.resourcesPath, "resource-monitor", binaryName)] - : environment.resolveResourcePathCandidates( - environment.path.join("resource-monitor", binaryName), - ); + return yield* resolveBundledHelperPath({ + directory: "resource-monitor", + binaryName: resourceMonitorBinaryName(environment.platform), + devBuildDirectories: [ + "native/resource-monitor/target/release", + "native/resource-monitor/target/debug", + ], + }); +}); - for (const candidate of candidates) { - if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) { - return Option.some(candidate); - } +const resolveAppleSpeechHelperPath = Effect.fn( + "desktop.backendConfiguration.resolveAppleSpeechHelperPath", +)(function* () { + const environment = yield* DesktopEnvironment.DesktopEnvironment; + if (environment.platform !== "darwin") { + return Option.none(); } - - return Option.none(); + return yield* resolveBundledHelperPath({ + directory: "apple-speech", + binaryName: "t3-apple-speech", + devBuildDirectories: ["native/apple-speech/build"], + }); }); const readPersistedBackendObservabilitySettings = Effect.gen(function* () { @@ -500,6 +522,7 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv function* ( input: SharedBootstrapInput & { readonly resourceMonitorPath: Option.Option; + readonly appleSpeechHelperPath: Option.Option; readonly cliPath: Option.Option; readonly shellEnvironmentPrepared: boolean; }, @@ -532,6 +555,10 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv onNone: () => ({}), onSome: (resourceMonitorPath) => ({ resourceMonitorPath }), }), + ...Option.match(input.appleSpeechHelperPath, { + onNone: () => ({}), + onSome: (appleSpeechHelperPath) => ({ appleSpeechHelperPath }), + }), ...buildObservabilityFragment(input.observabilitySettings), }; @@ -817,6 +844,10 @@ export const make = Effect.gen(function* () { Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment), ); + const appleSpeechHelperPath = yield* resolveAppleSpeechHelperPath().pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment), + ); const cliPath = yield* DesktopCliShim.install.pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment), @@ -825,6 +856,7 @@ export const make = Effect.gen(function* () { return yield* resolvePrimaryStartConfig({ ...shared, resourceMonitorPath, + appleSpeechHelperPath, cliPath, shellEnvironmentPrepared, }).pipe( diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index 9066cf6f1a67c..b685ca28feb36 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -309,10 +309,10 @@ export const openSystemSettings = DesktopIpc.makeIpcMethod({ if (environment.platform !== "darwin") return false; const owner = Electron.BrowserWindow.getFocusedWindow(); const opened = yield* shell.openSystemSettings(pane); - if (opened && environment.isPackaged) { + // The helper explains dragging T3 Code into the list; the microphone pane has no add button. + if (opened && environment.isPackaged && pane === "full-disk-access") { const permissions = yield* MacPermissions.MacPermissions; - const isGranted = yield* safariPermissionCheck; - yield* permissions.showHelper(pane, owner, isGranted); + yield* permissions.showHelper(pane, owner, yield* safariPermissionCheck); } return opened; }), diff --git a/apps/desktop/src/permissions/MacPermission.ts b/apps/desktop/src/permissions/MacPermission.ts index e72d796c876ad..7699b4af9ee39 100644 --- a/apps/desktop/src/permissions/MacPermission.ts +++ b/apps/desktop/src/permissions/MacPermission.ts @@ -4,6 +4,7 @@ export const MAC_PERMISSION_SETTINGS_URLS = { accessibility: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility", "full-disk-access": "x-apple.systempreferences:com.apple.settings.PrivacySecurity.extension?Privacy_AllFiles", + microphone: "x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone", }; export type MacPermission = keyof typeof MAC_PERMISSION_SETTINGS_URLS; @@ -12,4 +13,5 @@ export const MAC_PERMISSION_TITLES: Record = { "screen-recording": "Screen Recording", accessibility: "Accessibility", "full-disk-access": "Full Disk Access", + microphone: "Microphone", }; diff --git a/apps/mobile/src/features/voice-input/ComposerDictationControl.tsx b/apps/mobile/src/features/voice-input/ComposerDictationControl.tsx index 3e7d852be7554..77b284faacd34 100644 --- a/apps/mobile/src/features/voice-input/ComposerDictationControl.tsx +++ b/apps/mobile/src/features/voice-input/ComposerDictationControl.tsx @@ -24,8 +24,8 @@ import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; import { AppText as Text } from "../../components/ui/AppText"; import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol"; import { cn } from "../../lib/cn"; +import { VOICE_WAVEFORM_SAMPLE_COUNT } from "@t3tools/client-runtime/voice-input"; import type { VoiceComposerPresentation } from "./voiceInputPresentation"; -import { VOICE_WAVEFORM_SAMPLE_COUNT } from "./voiceInputMetering"; const DICTATION_TIMING = { duration: 220, diff --git a/apps/mobile/src/features/voice-input/VoiceInputProvider.tsx b/apps/mobile/src/features/voice-input/VoiceInputProvider.tsx index 48f75b4ff32ec..ccbd8f4e1dbb1 100644 --- a/apps/mobile/src/features/voice-input/VoiceInputProvider.tsx +++ b/apps/mobile/src/features/voice-input/VoiceInputProvider.tsx @@ -33,12 +33,13 @@ import { getLocalVoiceTranscriber } from "../../native/voiceTranscription"; import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; import { getNativeShowcaseScene } from "../showcase/nativeShowcaseScene"; import { + normalizeVoiceInputDecibels, VOICE_RECORDING_LIMIT_SECONDS, + VOICE_WAVEFORM_SAMPLE_COUNT, voiceInputBlocksSubmission, type VoiceInputState, } from "@t3tools/client-runtime/voice-input"; import { createLazyVoiceRecorder, type LazyVoiceRecorder } from "./lazyVoiceRecorder"; -import { normalizeVoiceInputDecibels, VOICE_WAVEFORM_SAMPLE_COUNT } from "./voiceInputMetering"; import { VoiceInputSession } from "./voiceInputSession"; const INITIAL_STATE: VoiceInputState = { phase: "idle", error: null, errorAction: null }; diff --git a/apps/mobile/src/features/voice-input/lazyVoiceRecorder.test.ts b/apps/mobile/src/features/voice-input/lazyVoiceRecorder.test.ts index d3236bc7c992b..7354a18fcf4c5 100644 --- a/apps/mobile/src/features/voice-input/lazyVoiceRecorder.test.ts +++ b/apps/mobile/src/features/voice-input/lazyVoiceRecorder.test.ts @@ -88,13 +88,14 @@ describe("createLazyVoiceRecorder", () => { configureRecording: async () => undefined, releaseRecording: async () => undefined, deleteRecording: (uri) => deleted.push(uri), + retainFailedRecordings: false, readDraft: () => ({ ownerKey: "thread", text: "", selection: { start: 0, end: 0 }, revision: 0, }), - commitDraft: () => undefined, + commitDraft: () => true, onStateChange: () => undefined, }); return { ...harness, controller, deleted }; diff --git a/apps/mobile/src/features/voice-input/voiceInputMetering.ts b/apps/mobile/src/features/voice-input/voiceInputMetering.ts deleted file mode 100644 index c3ba75ab4968a..0000000000000 --- a/apps/mobile/src/features/voice-input/voiceInputMetering.ts +++ /dev/null @@ -1,13 +0,0 @@ -export const VOICE_WAVEFORM_SAMPLE_COUNT = 64; - -const VOICE_NOISE_FLOOR_DECIBELS = -60; -const VOICE_NOISE_FLOOR_AMPLITUDE = 10 ** (VOICE_NOISE_FLOOR_DECIBELS / 20); - -export function normalizeVoiceInputDecibels(decibels: number | undefined) { - if (decibels === undefined || !Number.isFinite(decibels)) return 0; - if (decibels <= VOICE_NOISE_FLOOR_DECIBELS) return 0; - if (decibels >= 0) return 1; - - const amplitude = 10 ** (decibels / 20); - return Math.sqrt((amplitude - VOICE_NOISE_FLOOR_AMPLITUDE) / (1 - VOICE_NOISE_FLOOR_AMPLITUDE)); -} diff --git a/apps/mobile/src/features/voice-input/voiceInputSession.test.ts b/apps/mobile/src/features/voice-input/voiceInputSession.test.ts index b57aa0916c687..f3ddf4c8196d7 100644 --- a/apps/mobile/src/features/voice-input/voiceInputSession.test.ts +++ b/apps/mobile/src/features/voice-input/voiceInputSession.test.ts @@ -1,5 +1,8 @@ import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; -import type { PreparedVoiceTranscription } from "@t3tools/client-runtime/voice-input"; +import { + VoiceTranscriptionError, + type PreparedVoiceTranscription, +} from "@t3tools/client-runtime/voice-input"; import { Atom, AtomRegistry } from "effect/reactivity"; import { resetVoiceInputGlobalsForTests } from "../../../../../packages/client-runtime/src/voice-input/controller"; @@ -29,16 +32,17 @@ function createSession() { locale: "en-US", transcribe: async () => "spoken text", })); + const deleteRecording = vi.fn(); const session = new VoiceInputSession({ recorder, getTranscriber: () => ({ prepare }), requestPermission: async () => ({ granted: true, canAskAgain: true }), configureRecording: async () => {}, releaseRecording: vi.fn(async () => {}), - deleteRecording: vi.fn(), + deleteRecording, onStateChange: vi.fn(), }); - return { session, recorder, prepare }; + return { session, recorder, prepare, deleteRecording }; } describe("global voice input", () => { @@ -153,6 +157,24 @@ describe("global voice input", () => { }, ); + it("deletes a recording whose transcription failed, since retry records anew", async () => { + const { session, recorder, prepare, deleteRecording } = createSession(); + prepare.mockResolvedValueOnce({ + locale: "en-US", + transcribe: async () => { + throw new VoiceTranscriptionError("transcription-failed", "Upload failed", { + retryable: true, + }); + }, + }); + await session.start(createTarget("first", () => "hello", vi.fn(), { start: 5, end: 5 })); + await session.controller.stop(); + + expect(session.controller.currentState.phase).toBe("error"); + expect(session.controller.currentState.errorAction).not.toBe("retry-transcription"); + expect(deleteRecording).toHaveBeenCalledWith(recorder.uri); + }); + it("finishes the original draft at the recording limit while it is off screen", async () => { const { session, recorder } = createSession(); const commit = vi.fn(); diff --git a/apps/mobile/src/features/voice-input/voiceInputSession.ts b/apps/mobile/src/features/voice-input/voiceInputSession.ts index 372c1081d6747..21a8b7423edb8 100644 --- a/apps/mobile/src/features/voice-input/voiceInputSession.ts +++ b/apps/mobile/src/features/voice-input/voiceInputSession.ts @@ -9,7 +9,7 @@ export type VoiceInputTarget = { readonly ownerKey: string; readonly label?: string; readonly readDraft: () => VoiceDraftSnapshot | null; - readonly commitDraft: VoiceInputControllerDependencies["commitDraft"]; + readonly commitDraft: (text: string, selection: VoiceDraftSnapshot["selection"]) => void; readonly subscribe: () => () => void; }; @@ -47,9 +47,15 @@ export class VoiceInputSession { private target: VoiceInputTarget | null = null; private unsubscribe: (() => void) | null = null; - constructor(dependencies: Omit) { + constructor( + dependencies: Omit< + VoiceInputControllerDependencies, + "readDraft" | "commitDraft" | "retainFailedRecordings" + >, + ) { this.controller = new VoiceInputController({ ...dependencies, + retainFailedRecordings: false, onStateChange: (state) => { if (!voiceInputBlocksSubmission(state)) { this.unsubscribe?.(); @@ -58,7 +64,11 @@ export class VoiceInputSession { dependencies.onStateChange(state); }, readDraft: () => this.target?.readDraft() ?? null, - commitDraft: (text, selection) => this.target?.commitDraft(text, selection), + commitDraft: (text, selection) => { + if (!this.target) return false; + this.target.commitDraft(text, selection); + return true; + }, }); } diff --git a/apps/server/src/assets/AttachmentUpload.ts b/apps/server/src/assets/AttachmentUpload.ts index efbe6a5ba6a87..f50fdc3f0b1ef 100644 --- a/apps/server/src/assets/AttachmentUpload.ts +++ b/apps/server/src/assets/AttachmentUpload.ts @@ -64,7 +64,7 @@ function decodeClaims(encodedPayload: string): AttachmentUploadClaims | null { } } -const loadSigningSecret = Effect.gen(function* () { +export const loadUploadSigningSecret = Effect.gen(function* () { const secretStore = yield* ServerSecretStore.ServerSecretStore; return yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32); }); @@ -72,7 +72,7 @@ const loadSigningSecret = Effect.gen(function* () { export const issueAttachmentUploadUrl = Effect.fn("AttachmentUpload.issueUrl")(function* ( input: AttachmentCreateUploadUrlInput, ) { - const secret = yield* loadSigningSecret.pipe( + const secret = yield* loadUploadSigningSecret.pipe( Effect.mapError((cause) => new AttachmentUploadSigningKeyError({ cause })), ); const config = yield* ServerConfig.ServerConfig; @@ -125,7 +125,7 @@ export const validateAttachmentUploadToken = Effect.fn("AttachmentUpload.validat return null; } - const secret = yield* loadSigningSecret.pipe( + const secret = yield* loadUploadSigningSecret.pipe( Effect.tapError((cause) => Effect.logError("Failed to load the attachment upload signing key.", { cause }), ), diff --git a/apps/server/src/cli/config.ts b/apps/server/src/cli/config.ts index c7271b795b555..d670d13acbd18 100644 --- a/apps/server/src/cli/config.ts +++ b/apps/server/src/cli/config.ts @@ -370,6 +370,7 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct const desktopBrowserFd = bootstrap?.desktopBrowserFd; const desktopBrowserControlFd = bootstrap?.desktopBrowserControlFd; const resourceMonitorPath = bootstrap?.resourceMonitorPath; + const appleSpeechHelperPath = bootstrap?.appleSpeechHelperPath; const autoBootstrapProjectFromCwd = Option.getOrElse( resolveOptionPrecedence( Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd), @@ -477,6 +478,7 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct desktopBrowserFd, desktopBrowserControlFd, resourceMonitorPath, + appleSpeechHelperPath, autoBootstrapProjectFromCwd, logWebSocketEvents, tailscaleServeEnabled, diff --git a/apps/server/src/cloud/CloudLink.lifecycle.test.ts b/apps/server/src/cloud/CloudLink.lifecycle.test.ts index 7264afd6a452b..e68fef4498c30 100644 --- a/apps/server/src/cloud/CloudLink.lifecycle.test.ts +++ b/apps/server/src/cloud/CloudLink.lifecycle.test.ts @@ -177,6 +177,7 @@ describe("releaseManagedTunnelOnShutdown", () => { ServerEnvironment.ServerEnvironment.of({ getEnvironmentId: Effect.succeed(EnvironmentId.make("env_123")), getDescriptor: Effect.die("unused"), + streamDescriptorChanges: Stream.die("unused"), }), ), Effect.provideService( diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index ef6f71a46a2e2..1fc01b6039b78 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -81,6 +81,7 @@ export class ServerConfig extends Context.Service< readonly desktopBrowserFd?: number | undefined; readonly desktopBrowserControlFd?: number | undefined; readonly resourceMonitorPath?: string | undefined; + readonly appleSpeechHelperPath?: string | undefined; readonly autoBootstrapProjectFromCwd: boolean; readonly logWebSocketEvents: boolean; readonly tailscaleServeEnabled: boolean; @@ -221,6 +222,7 @@ const makeTest = Effect.fn("ServerConfig.makeTest")(function* ( desktopBrowserFd: undefined, desktopBrowserControlFd: undefined, resourceMonitorPath: undefined, + appleSpeechHelperPath: undefined, staticDir: undefined, devUrl, devAllowedOrigins: [], diff --git a/apps/server/src/environment/ServerEnvironment.test.ts b/apps/server/src/environment/ServerEnvironment.test.ts index 7cebccb2a1f7c..161bd95091348 100644 --- a/apps/server/src/environment/ServerEnvironment.test.ts +++ b/apps/server/src/environment/ServerEnvironment.test.ts @@ -6,6 +6,7 @@ import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Stream from "effect/Stream"; import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -18,11 +19,13 @@ import { RELAY_URL_SECRET, } from "../cloud/config.ts"; import * as ServerConfig from "../config.ts"; +import * as AppleSpeechHelper from "../voiceTranscription/AppleSpeechHelper.ts"; import * as ServerEnvironment from "./ServerEnvironment.ts"; const layerServerEnvironment = (baseDir: string) => ServerEnvironment.layer.pipe( Layer.provide(ServerSecretStore.layer), + Layer.provide(AppleSpeechHelper.layerUnavailable), Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)), ); @@ -98,6 +101,7 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => { Effect.provide( ServerEnvironment.layer.pipe( Layer.provide(layerEmptySecretStore), + Layer.provide(AppleSpeechHelper.layerUnavailable), Layer.provide(ServerConfig.layer({ ...config, mode })), ), ), @@ -228,6 +232,40 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => { }), ); + it.effect.each([true, false])( + "advertises Apple on-device transcription as %s from the helper's latest answer", + (available) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const baseDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-server-environment-apple-speech-test-", + }); + const descriptor = yield* Effect.gen(function* () { + const serverEnvironment = yield* ServerEnvironment.ServerEnvironment; + return yield* serverEnvironment.getDescriptor; + }).pipe( + Effect.provide( + ServerEnvironment.layer.pipe( + Layer.provide(ServerSecretStore.layer), + Layer.provide( + Layer.succeed( + AppleSpeechHelper.AppleSpeechHelper, + AppleSpeechHelper.AppleSpeechHelper.of({ + available: Effect.succeed(available), + streamAvailableChanges: Stream.make(available), + availability: Effect.die("the descriptor must not wait for a probe"), + transcribe: () => Effect.die("unused"), + }), + ), + ), + Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)), + ), + ), + ); + expect(descriptor.capabilities.appleOnDeviceTranscription).toBe(available); + }), + ); + it.effect("reports agent activity publishing from the current secret state", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -235,7 +273,10 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => { prefix: "t3-server-environment-publish-test-", }); const layerTest = Layer.mergeAll( - ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer)), + ServerEnvironment.layer.pipe( + Layer.provide(ServerSecretStore.layer), + Layer.provide(AppleSpeechHelper.layerUnavailable), + ), ServerSecretStore.layer, ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir))); diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index fbb5970560bc6..68c579c9d40c4 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -12,6 +12,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; import packageJson from "../../package.json" with { type: "json" }; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; @@ -21,6 +22,7 @@ import { resolveServerSelfUpdateCapability } from "../cloud/selfUpdate.ts"; import { resolveServiceLauncherMode } from "../cloud/serviceLauncherClient.ts"; import * as ServerConfig from "../config.ts"; import * as ProcessRunner from "../processRunner.ts"; +import * as AppleSpeechHelper from "../voiceTranscription/AppleSpeechHelper.ts"; import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts"; import { detectServerEnvironmentMachineKind } from "./ServerEnvironmentMachine.ts"; @@ -45,6 +47,8 @@ export class ServerEnvironment extends Context.Service< { readonly getEnvironmentId: Effect.Effect; readonly getDescriptor: Effect.Effect; + /** The descriptor now, then again each time the Apple speech probe changes it. */ + readonly streamDescriptorChanges: Stream.Stream; } >()("t3/environment/ServerEnvironment") {} @@ -185,6 +189,7 @@ export const make = Effect.gen(function* () { const path = yield* Path.Path; const serverConfig = yield* ServerConfig.ServerConfig; const secrets = yield* ServerSecretStore.ServerSecretStore; + const appleSpeech = yield* AppleSpeechHelper.AppleSpeechHelper; const identity = yield* ServerEnvironmentIdentity; const hostPlatform = yield* HostProcess.Platform; const hostArchitecture = yield* HostProcess.Architecture; @@ -269,16 +274,24 @@ export const make = Effect.gen(function* () { }, }; + // The publish opt-in and relay link change at runtime (`t3 connect + // publish`, the client settings toggle), so the capability is read per + // descriptor request rather than baked in at startup. + const getDescriptor = Effect.all({ + agentActivityPublishing: readAgentActivityPublishingActive(secrets), + appleOnDeviceTranscription: appleSpeech.available, + }).pipe( + Effect.map((capabilities) => ({ + ...descriptor, + capabilities: { ...descriptor.capabilities, ...capabilities }, + })), + ); + return ServerEnvironment.of({ getEnvironmentId: Effect.succeed(environmentId), - // The publish opt-in and relay link change at runtime (`t3 connect - // publish`, the client settings toggle), so the capability is read per - // descriptor request rather than baked in at startup. - getDescriptor: readAgentActivityPublishingActive(secrets).pipe( - Effect.map((agentActivityPublishing) => ({ - ...descriptor, - capabilities: { ...descriptor.capabilities, agentActivityPublishing }, - })), + getDescriptor, + streamDescriptorChanges: appleSpeech.streamAvailableChanges.pipe( + Stream.mapEffect(() => getDescriptor), ), }); }); diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index 6ba9579f04bd9..af8542653ccd0 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -3,6 +3,8 @@ import { AuthOrchestrationOperateScope, AuthOrchestrationReadScope, EnvironmentHttpApi, + type VoiceTranscriptionFailure, + type VoiceTranscriptionFailureCode, } from "@t3tools/contracts"; import { isDevProxiedPath } from "@t3tools/shared/devProxy"; import { injectMcpAppCookieBootstrap, injectMcpAppThemeBootstrap } from "@t3tools/shared/mcpApp"; @@ -20,6 +22,7 @@ import { cast } from "effect/Function"; import { HttpClient, HttpClientResponse, + HttpIncomingMessage, HttpMiddleware, HttpRouter, HttpServerResponse, @@ -48,6 +51,7 @@ import { failEnvironmentInternal, } from "./auth/http.ts"; import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; +import * as VoiceTranscription from "./voiceTranscription/VoiceTranscription.ts"; import { WEBHOOK_ROUTE_PREFIX } from "./scheduledTasks/ScheduledTaskService.ts"; import { browserApiCorsAllowedHeaders, @@ -397,8 +401,12 @@ const UNTRACED_REQUEST_PATHS: ReadonlySet = new Set([OTLP_TRACES_PROXY_P const layerUntracedRequests = Layer.succeed(HttpMiddleware.TracerDisabledWhen)((request) => { const queryIndex = request.url.indexOf("?"); const path = queryIndex === -1 ? request.url : request.url.slice(0, queryIndex); - // Webhook URLs carry their secret token in the path, so they never reach a trace. - return UNTRACED_REQUEST_PATHS.has(path) || path.startsWith(`${WEBHOOK_ROUTE_PREFIX}/`); + // Webhook and voice upload URLs carry a secret token in the path, so they never reach a trace. + return ( + UNTRACED_REQUEST_PATHS.has(path) || + path.startsWith(`${WEBHOOK_ROUTE_PREFIX}/`) || + path.startsWith(`${VoiceTranscription.VOICE_TRANSCRIPTION_ROUTE_PREFIX}/`) + ); }); export const withUntracedRequests = Layer.provide(layerUntracedRequests); @@ -495,6 +503,91 @@ export const layerAttachmentUploadRoute = HttpRouter.add( }), ); +const VOICE_TRANSCRIPTION_FAILURE_STATUS = { + invalid_upload: 400, + not_configured: 409, + upstream_rejected_credentials: 502, + upstream_failed: 502, + internal: 500, +} as const satisfies Record; + +const voiceTranscriptionFailure = (code: VoiceTranscriptionFailureCode, message: string) => + HttpServerResponse.jsonUnsafe({ code, message } satisfies VoiceTranscriptionFailure, { + status: VOICE_TRANSCRIPTION_FAILURE_STATUS[code], + headers: { "cache-control": "no-store" }, + }); + +export const layerVoiceTranscriptionRoute = HttpRouter.add( + "POST", + `${VoiceTranscription.VOICE_TRANSCRIPTION_ROUTE_PREFIX}/*`, + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const voiceTranscription = yield* VoiceTranscription.VoiceTranscription; + const url = HttpServerRequest.toURL(request); + const claims = Option.isSome(url) + ? yield* voiceTranscription.verifyUploadToken( + url.value.pathname.slice( + `${VoiceTranscription.VOICE_TRANSCRIPTION_ROUTE_PREFIX}/`.length, + ), + ) + : Option.none(); + if (Option.isNone(claims)) { + return voiceTranscriptionFailure( + "invalid_upload", + "This transcription link is invalid or has expired.", + ); + } + const { sizeBytes } = claims.value; + const contentLength = request.headers["content-length"]; + // Tunnels may re-chunk the body. The read cap and transcribe's exact byte count still apply. + if (contentLength !== undefined && Number(contentLength) !== sizeBytes) { + return voiceTranscriptionFailure( + "invalid_upload", + `Content-Length must match the recording size of ${sizeBytes} bytes.`, + ); + } + const audio = yield* request.arrayBuffer.pipe( + Effect.map((buffer) => new Uint8Array(buffer)), + Effect.provideService(HttpIncomingMessage.MaxBodySize, ByteSize.bytes(sizeBytes)), + Effect.option, + ); + if (Option.isNone(audio)) { + return voiceTranscriptionFailure("invalid_upload", "Could not read the recording."); + } + + return yield* voiceTranscription + .transcribe(claims.value, audio.value) + .pipe( + Effect.map((result) => + HttpServerResponse.jsonUnsafe(result, { headers: { "cache-control": "no-store" } }), + ), + ); + }).pipe( + Effect.catchTags({ + VoiceTranscriptionNotConfiguredError: (error) => + Effect.succeed(voiceTranscriptionFailure("not_configured", error.message)), + VoiceTranscriptionInvalidUploadError: (error) => + Effect.succeed(voiceTranscriptionFailure("invalid_upload", error.message)), + VoiceTranscriptionInternalError: (error) => + Effect.succeed(voiceTranscriptionFailure("internal", error.message)), + VoiceTranscriptionCredentialsRejectedError: (error) => + Effect.logWarning("Voice transcription credentials were rejected upstream.", { + cause: error, + }).pipe( + Effect.as(voiceTranscriptionFailure("upstream_rejected_credentials", error.message)), + ), + VoiceTranscriptionUpstreamError: (error) => + Effect.logWarning("Voice transcription failed upstream.", { cause: error }).pipe( + Effect.as(voiceTranscriptionFailure("upstream_failed", error.message)), + ), + AppleSpeechHelperError: (error) => + Effect.logWarning("Voice transcription failed in the Apple speech helper.", { + cause: error, + }).pipe(Effect.as(voiceTranscriptionFailure("upstream_failed", error.message))), + }), + ), +); + const decodeBuildManifest = Schema.decodeUnknownEffect( Schema.fromJsonString( Schema.Record( diff --git a/apps/server/src/mcp/McpSessionRegistry.test.ts b/apps/server/src/mcp/McpSessionRegistry.test.ts index 282c3dffd6d64..e06c9b7f45ba2 100644 --- a/apps/server/src/mcp/McpSessionRegistry.test.ts +++ b/apps/server/src/mcp/McpSessionRegistry.test.ts @@ -4,6 +4,7 @@ import { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts" import * as Effect from "effect/Effect"; import { HttpServer } from "effect/http"; import * as NetAddress from "effect/net/NetAddress"; +import * as Stream from "effect/Stream"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as McpSessionRegistry from "./McpSessionRegistry.ts"; @@ -18,6 +19,7 @@ const fakeHttpServer = makeFakeHttpServer("127.0.0.1"); const fakeEnvironment = ServerEnvironment.ServerEnvironment.of({ getEnvironmentId: Effect.succeed(environmentId), getDescriptor: Effect.die("unused"), + streamDescriptorChanges: Stream.die("unused"), }); const makeRegistry = (now: () => number, httpServer = fakeHttpServer) => diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index 3f3942e75d082..4901abf191f51 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -154,6 +154,7 @@ const RPC_AGGREGATES = { [WS_METHODS.assetsPersistChatAttachments]: "orchestration", [WS_METHODS.attachmentsCreateUploadUrl]: "workspace", [WS_METHODS.attachmentsDelete]: "workspace", + [WS_METHODS.voiceCreateTranscriptionUrl]: "voice", [WS_METHODS.providerUploadFeedback]: "provider", [WS_METHODS.mcpAppsCallTool]: "provider", [WS_METHODS.mcpAppsToolInfo]: "provider", diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index b60758e80c728..28a302567b616 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -578,6 +578,7 @@ const fakeHttpServer = HttpServer.HttpServer.of({ const fakeEnvironment = ServerEnvironment.ServerEnvironment.of({ getEnvironmentId: Effect.succeed(EnvironmentId.make("environment-provider-session-manager")), getDescriptor: Effect.die("unused"), + streamDescriptorChanges: Stream.die("unused"), }); const layerTestMcpRegistry = Layer.effect( diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.ts index ac4a785f207f3..44ff0641d0de2 100644 --- a/apps/server/src/preview/ServerBrowser.test.ts +++ b/apps/server/src/preview/ServerBrowser.test.ts @@ -255,6 +255,7 @@ const dependencies = Layer.mergeAll( Layer.succeed(ServerEnvironment.ServerEnvironment, { getEnvironmentId: Effect.succeed(scope.environmentId), getDescriptor: Effect.die("unused descriptor"), + streamDescriptorChanges: Stream.die("unused descriptor"), }), Layer.succeed(PreviewBrowser.PreviewBrowser, { executable: Effect.die("mock Chromium does not need an executable"), diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.ts index 64b71140fdcf1..19c2fffbfa614 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.test.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts @@ -256,6 +256,7 @@ const makeTestRelay = Effect.fnUntraced(function* ( Effect.provideService(ServerEnvironment.ServerEnvironment, { getEnvironmentId: Effect.succeed(EnvironmentId.make("relay-environment")), getDescriptor: unused(), + streamDescriptorChanges: Stream.die("unused"), }), Effect.provideService(ProjectService.ProjectService, { create: unused, diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 48d701103c077..51d2fae746405 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -93,6 +93,8 @@ import * as ProviderAdapterRegistry from "./orchestration-v2/ProviderAdapterRegi import * as ProviderRegistry from "./provider/ProviderRegistry.ts"; import * as ProviderUsageLimitsIngestion from "./provider/ProviderUsageLimitsIngestion.ts"; import * as UsageLimitSources from "./usage/UsageLimitSources.ts"; +import * as AppleSpeechHelper from "./voiceTranscription/AppleSpeechHelper.ts"; +import * as VoiceTranscription from "./voiceTranscription/VoiceTranscription.ts"; import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts"; import * as T3ProjectFileLoader from "./project/T3ProjectFileLoader.ts"; import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts"; @@ -277,6 +279,12 @@ const layerUsage = UsageService.layer.pipe( Layer.provide(layerServerSettings), ); +const layerVoiceTranscription = VoiceTranscription.layer.pipe( + Layer.provide(layerServerSettings), + Layer.provide(ServerSecretStore.layer), + Layer.provide(AppleSpeechHelper.layer), +); + const layerResourceDiagnostics = Layer.mergeAll( HostResources.layer, layerResourceTelemetry, @@ -456,7 +464,10 @@ const layerProjectFaviconResolver = ProjectFaviconResolver.layer.pipe( Layer.provide(T3ProjectFileLoader.layer), ); -const layerServerEnvironment = ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer)); +const layerServerEnvironment = ServerEnvironment.layer.pipe( + Layer.provide(ServerSecretStore.layer), + Layer.provide(AppleSpeechHelper.layer), +); const layerAuth = EnvironmentAuth.layer.pipe( Layer.provideMerge(layerPersistence), @@ -669,6 +680,7 @@ const layerRuntimeCoreDependencies = layerRuntimeCoreDependenciesBase.pipe( const layerRuntimeDependencies = layerRuntimeCoreDependencies.pipe( Layer.provideMerge(layerUsage), + Layer.provideMerge(layerVoiceTranscription), Layer.provideMerge(layerBackground), Layer.provideMerge(layerResourceDiagnostics), Layer.provideMerge(TraceDiagnostics.layer), @@ -704,6 +716,7 @@ const layerMakeRoutes = Layer.mergeAll( ServerHttp.layerOtlpTracesProxyRoute, ServerHttp.layerAssetRoute, ServerHttp.layerAttachmentUploadRoute, + ServerHttp.layerVoiceTranscriptionRoute, DeviceHubProxy.layer, ServerBrowserStream.routeLayer, ServerHttp.layerStaticAndDevRoute, @@ -1052,7 +1065,12 @@ const layerMakeServer = Layer.unwrap( Layer.provideMerge(layerRuntimeServices), Layer.provideMerge( McpSessionRegistry.layer.pipe( - Layer.provide(ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer))), + Layer.provide( + ServerEnvironment.layer.pipe( + Layer.provide(ServerSecretStore.layer), + Layer.provide(AppleSpeechHelper.layer), + ), + ), ), ), Layer.provide(layerActivation), diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index a23d44fc282d1..9150387ff8680 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -1267,6 +1267,87 @@ it.layer(NodeServices.layer)("server settings", (it) => { }).pipe(Effect.provide(layerServerSettingsWithSecrets())), ); + it.effect( + "stores the voice transcription key as a secret and keeps it across partial patches", + () => + Effect.gen(function* () { + const service = yield* ServerSettingsModule.ServerSettingsService; + const config = yield* ServerConfig.ServerConfig; + const fs = yield* FileSystem.FileSystem; + const store = yield* ServerSecretStore.ServerSecretStore; + const saved = yield* service.updateSettings({ + voiceTranscription: { enabled: true, apiKey: "sk-voice-secret" }, + }); + assert.strictEqual(saved.voiceTranscription.apiKey, "sk-voice-secret"); + assert.notInclude(yield* fs.readFileString(config.settingsPath), "sk-voice-secret"); + assert.isTrue(Option.isSome(yield* store.get("voice-transcription-api-key"))); + const client = ServerSettingsModule.redactServerSettingsForClient(saved); + assert.strictEqual(client.voiceTranscription.apiKey, "••••••"); + assert.notInclude(JSON.stringify(client), "sk-voice-secret"); + + const edited = yield* service.updateSettings({ + voiceTranscription: { model: "whisper-1" }, + }); + assert.deepInclude(edited.voiceTranscription, { + enabled: true, + model: "whisper-1", + apiKey: "sk-voice-secret", + }); + const echoed = yield* service.updateSettings({ + voiceTranscription: { apiKey: client.voiceTranscription.apiKey }, + }); + assert.strictEqual(echoed.voiceTranscription.apiKey, "sk-voice-secret"); + assert.strictEqual( + (yield* service.getSettings).voiceTranscription.apiKey, + "sk-voice-secret", + ); + + const removed = yield* service.updateSettings({ voiceTranscription: { apiKey: "" } }); + assert.strictEqual(removed.voiceTranscription.apiKey, ""); + assert.isTrue(Option.isNone(yield* store.get("voice-transcription-api-key"))); + }).pipe(Effect.provide(layerServerSettingsWithSecrets())), + ); + + it.effect.each([ + { + name: "a base URL on another origin", + patch: { baseUrl: "https://transcribe.example.com/v1" }, + keeps: false, + }, + { name: "another provider", patch: { provider: "xai" }, keeps: false }, + { + name: "a path on the same origin", + patch: { baseUrl: "https://api.openai.com/v2" }, + keeps: true, + }, + { name: "a model change", patch: { model: "whisper-1" }, keeps: true }, + ] as const)("keeps the voice transcription key across $name: $keeps", ({ patch, keeps }) => + Effect.gen(function* () { + const service = yield* ServerSettingsModule.ServerSettingsService; + const store = yield* ServerSecretStore.ServerSecretStore; + yield* service.updateSettings({ + voiceTranscription: { enabled: true, apiKey: "sk-voice-secret" }, + }); + const moved = yield* service.updateSettings({ voiceTranscription: patch }); + assert.strictEqual(moved.voiceTranscription.apiKey, keeps ? "sk-voice-secret" : ""); + assert.strictEqual(Option.isSome(yield* store.get("voice-transcription-api-key")), keeps); + }).pipe(Effect.provide(layerServerSettingsWithSecrets())), + ); + + it.effect("saves a key sent together with a move to another origin", () => + Effect.gen(function* () { + const service = yield* ServerSettingsModule.ServerSettingsService; + yield* service.updateSettings({ + voiceTranscription: { enabled: true, apiKey: "sk-voice-secret" }, + }); + const moved = yield* service.updateSettings({ + voiceTranscription: { baseUrl: "https://transcribe.example.com/v1", apiKey: "sk-new" }, + }); + assert.strictEqual(moved.voiceTranscription.apiKey, "sk-new"); + assert.strictEqual((yield* service.getSettings).voiceTranscription.apiKey, "sk-new"); + }).pipe(Effect.provide(layerServerSettingsWithSecrets())), + ); + it.effect("moves saved provider credentials to the secret store when settings load", () => Effect.gen(function* () { const service = yield* ServerSettingsModule.ServerSettingsService; diff --git a/apps/server/src/settingsSecrets.ts b/apps/server/src/settingsSecrets.ts index b80ccabc03603..984ad606ada14 100644 --- a/apps/server/src/settingsSecrets.ts +++ b/apps/server/src/settingsSecrets.ts @@ -5,6 +5,7 @@ import { EasDeviceHostConfig, type ServerSettings, UsageLimitSourceConfig, + VoiceTranscriptionSettings, secretSettingsFields, } from "@t3tools/contracts"; import { acpRegistryClient } from "@t3tools/provider-acp-registry/client"; @@ -33,6 +34,7 @@ const providerSecretFields = new Map([ ]); const usageLimitSecretFields = secretSettingsFields(UsageLimitSourceConfig); const easDeviceHostSecretFields = secretSettingsFields(EasDeviceHostConfig); +const voiceTranscriptionSecretFields = secretSettingsFields(VoiceTranscriptionSettings); const encode = (value: string) => Buffer.from(value, "utf8").toString("base64url"); export interface SettingsSecret { @@ -155,5 +157,18 @@ export function mapSettingsSecrets( ) as EasDeviceHostConfig, ); - return { ...settings, providerInstances, sourceControlHosts, usageLimitSources, easDeviceHosts }; + const voiceTranscription = mapFields( + settings.voiceTranscription, + voiceTranscriptionSecretFields, + () => "voice-transcription-api-key", + ) as ServerSettings["voiceTranscription"]; + + return { + ...settings, + providerInstances, + sourceControlHosts, + usageLimitSources, + easDeviceHosts, + voiceTranscription, + }; } diff --git a/apps/server/src/voiceTranscription/AppleSpeechHelper.test.ts b/apps/server/src/voiceTranscription/AppleSpeechHelper.test.ts new file mode 100644 index 0000000000000..ff64e32d1f2f9 --- /dev/null +++ b/apps/server/src/voiceTranscription/AppleSpeechHelper.test.ts @@ -0,0 +1,356 @@ +// @effect-diagnostics nodeBuiltinImport:off - The skip gate for the real helper runs before any Effect runtime exists. +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { assert, describe, expect, it } from "@effect/vitest"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as NodeFS from "node:fs"; +import * as TestClock from "effect/testing/TestClock"; +import { ChildProcessSpawner } from "effect/process"; + +import * as ServerConfig from "../config.ts"; +import * as ProcessRunner from "../processRunner.ts"; +import * as AppleSpeechHelper from "./AppleSpeechHelper.ts"; + +const devHelperPath = `${import.meta.dirname}/../../../../native/apple-speech/build/t3-apple-speech`; +const realHelperUsable = + HostProcess.Platform.defaultValue() === "darwin" && + Number.parseInt(AppleSpeechHelper.AppleSpeechHostKernelRelease.defaultValue(), 10) >= 25 && + NodeFS.existsSync(devHelperPath); + +const audio = new Uint8Array([82, 73, 70, 70, 1, 2, 3, 4]); +const probeAvailable = + '{"available":true,"supportedLocales":["en_US"],"installedLocales":["en_US"]}'; + +const output = ( + fields: Partial = {}, +): ProcessRunner.ProcessRunOutput => ({ + stdout: "", + stderr: "", + code: ChildProcessSpawner.ExitCode(0), + timedOut: false, + stdoutTruncated: false, + stderrTruncated: false, + stdoutInvalidUtf8: false, + stderrInvalidUtf8: false, + ...fields, +}); + +const failed = (stdout: string) => output({ code: ChildProcessSpawner.ExitCode(1), stdout }); + +const timedOut = (input: ProcessRunner.ProcessRunInput) => + new ProcessRunner.ProcessTimeoutError({ + command: input.command, + argumentCount: input.args.length, + timeoutMs: 1, + }); + +type Handler = ( + input: ProcessRunner.ProcessRunInput, +) => Effect.Effect; + +const setup = Effect.fn(function* ( + host: { readonly platform: NodeJS.Platform; readonly kernelRelease: string }, + handle: Handler, +) { + const fileSystem = yield* FileSystem.FileSystem; + const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-apple-speech-test-" }); + const helperPath = `${baseDir}/t3-apple-speech`; + yield* fileSystem.writeFileString(helperPath, "helper"); + const runs: Array = []; + const service = yield* AppleSpeechHelper.make.pipe( + Effect.provide(ServerConfig.layerTest(process.cwd(), baseDir)), + Effect.provideService( + ProcessRunner.ProcessRunner, + ProcessRunner.ProcessRunner.of({ + run: (input) => + Effect.suspend(() => { + runs.push(input); + return handle(input); + }), + }), + ), + Effect.provideService(HostProcess.Platform, host.platform), + Effect.provideService(HostProcess.Environment, { T3CODE_APPLE_SPEECH_PATH: helperPath }), + Effect.provideService(AppleSpeechHelper.AppleSpeechHostKernelRelease, host.kernelRelease), + ); + return { service, runs, helperPath }; +}); + +const macOS26 = { platform: "darwin", kernelRelease: "25.0.0" } as const; + +const helperThat = + (onTranscribe: Handler): Handler => + (input) => + input.args[0] === "probe" + ? Effect.succeed(output({ stdout: probeAvailable })) + : onTranscribe(input); + +describe("AppleSpeechHelper", () => { + it.effect.skipIf(!realHelperUsable)("probes the built helper through the real layer", () => + Effect.gen(function* () { + const service = yield* AppleSpeechHelper.AppleSpeechHelper; + expect(yield* service.availability).toBe("available"); + expect(yield* service.available).toBe(true); + }).pipe( + Effect.provide( + AppleSpeechHelper.layer.pipe( + Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-apple-speech-real-" })), + Layer.provide(NodeServices.layer), + ), + ), + Effect.provideService(HostProcess.Environment, { T3CODE_APPLE_SPEECH_PATH: devHelperPath }), + ), + ); + + it.effect.each([ + { platform: "linux", kernelRelease: "6.8.0" }, + { platform: "win32", kernelRelease: "10.0.22631" }, + { platform: "darwin", kernelRelease: "24.6.0" }, + ] as const)("never spawns the helper on $platform $kernelRelease", (host) => + Effect.gen(function* () { + const { service, runs } = yield* setup(host, () => Effect.die("must not spawn")); + expect(yield* service.availability).toBe("unsupported-host"); + expect(yield* service.available).toBe(false); + const error = yield* Effect.flip(service.transcribe({ audio, locale: "en" })); + assert.instanceOf(error, AppleSpeechHelper.AppleSpeechHelperError); + expect(error.reason).toBe("unavailable"); + expect(runs).toHaveLength(0); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect.each([ + { name: "available", probe: output({ stdout: probeAvailable }), available: true }, + { + name: "unavailable", + probe: output({ stdout: '{"available":false,"supportedLocales":[],"installedLocales":[]}' }), + available: false, + }, + { + name: "malformed", + probe: output({ stdout: "Speech framework crashed\n" }), + available: false, + }, + { + name: "failing", + probe: failed('{"error":{"code":"failed","message":"boom"}}'), + available: false, + }, + { name: "hung", probe: output({ code: null, timedOut: true }), available: false }, + ])("reads a $name probe once and caches it", ({ probe, available }) => + Effect.gen(function* () { + const { service, runs, helperPath } = yield* setup(macOS26, () => Effect.succeed(probe)); + expect(yield* service.availability).toBe(available ? "available" : "unavailable"); + expect(yield* service.available).toBe(available); + expect(yield* service.available).toBe(available); + expect(runs).toHaveLength(1); + expect(runs[0]).toMatchObject({ command: helperPath, args: ["probe"] }); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("reports unavailable without waiting while the first probe is still running", () => + Effect.gen(function* () { + const release = yield* Deferred.make(); + const { service } = yield* setup(macOS26, () => + Deferred.await(release).pipe(Effect.as(output({ stdout: probeAvailable }))), + ); + expect(yield* service.available).toBe(false); + yield* Deferred.succeed(release, undefined); + expect(yield* service.availability).toBe("available"); + expect(yield* service.available).toBe(true); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("retries a probe that timed out, but not before a minute has passed", () => + Effect.gen(function* () { + let probes = 0; + const { service, runs } = yield* setup(macOS26, () => + Effect.sync(() => + probes++ === 0 + ? output({ code: null, timedOut: true }) + : output({ stdout: probeAvailable }), + ), + ); + expect(yield* service.availability).toBe("unavailable"); + expect(yield* service.available).toBe(false); + yield* TestClock.adjust("59 seconds"); + expect(runs).toHaveLength(1); + yield* TestClock.adjust("1 second"); + expect(runs).toHaveLength(2); + expect(yield* service.available).toBe(true); + expect(yield* service.availability).toBe("available"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("gives up on a probe that keeps timing out after five tries", () => + Effect.gen(function* () { + const { service, runs } = yield* setup(macOS26, () => + Effect.succeed(output({ code: null, timedOut: true })), + ); + expect(yield* service.availability).toBe("unavailable"); + yield* TestClock.adjust("1 day"); + expect(runs).toHaveLength(5); + expect(yield* service.available).toBe(false); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("treats a helper that fails to launch as unavailable", () => + Effect.gen(function* () { + const { service, runs } = yield* setup(macOS26, (input) => + Effect.fail( + new ProcessRunner.ProcessSpawnError({ + command: input.command, + argumentCount: input.args.length, + cause: new Error("dyld: Symbol not found"), + }), + ), + ); + expect(yield* service.availability).toBe("unavailable"); + expect(yield* service.available).toBe(false); + expect(runs).toHaveLength(1); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("transcribes a WAV through a temp file that is gone afterwards", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + let wavPath = ""; + const { service, runs, helperPath } = yield* setup( + macOS26, + helperThat((input) => + Effect.gen(function* () { + wavPath = input.args.at(-1)!; + expect(new Uint8Array(yield* Effect.orDie(fileSystem.readFile(wavPath)))).toEqual( + audio, + ); + return output({ stdout: '{"text":"hello apple","locale":"en_US"}\n' }); + }), + ), + ); + const transcript = yield* service.transcribe({ audio, locale: "en" }); + expect(transcript).toEqual({ text: "hello apple", locale: "en_US" }); + expect(runs).toHaveLength(2); + const run = runs[1]!; + expect(run.command).toBe(helperPath); + expect(run.args).toEqual(["transcribe", "--locale", "en", wavPath]); + expect(yield* fileSystem.exists(wavPath)).toBe(false); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("gives up on a helper that never answers with a timeout error", () => + Effect.gen(function* () { + const spawned = yield* Deferred.make(); + const hungRunner = yield* ProcessRunner.make().pipe( + Effect.provideService( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Deferred.succeed(spawned, undefined).pipe(Effect.andThen(Effect.never)), + ), + ), + ); + const { service } = yield* setup(macOS26, helperThat(hungRunner.run)); + const transcription = yield* service + .transcribe({ audio, locale: "en" }) + .pipe(Effect.flip, Effect.forkChild); + yield* Deferred.await(spawned); + yield* TestClock.adjust("2 minutes"); + const error = yield* Fiber.join(transcription); + assert.instanceOf(error, AppleSpeechHelper.AppleSpeechHelperError); + expect(error.reason).toBe("timeout"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("passes an empty locale through so the helper uses the system language", () => + Effect.gen(function* () { + const { service, runs } = yield* setup( + macOS26, + helperThat(() => Effect.succeed(output({ stdout: '{"text":"","locale":"en_US"}' }))), + ); + expect(yield* service.transcribe({ audio, locale: "" })).toEqual({ + text: "", + locale: "en_US", + }); + expect(runs[1]!.args.slice(0, 3)).toEqual(["transcribe", "--locale", ""]); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect.each([ + { + name: "unsupported_locale", + result: () => + Effect.succeed(failed('{"error":{"code":"unsupported_locale","message":"no model"}}')), + tag: "AppleSpeechUnsupportedLocaleError", + reason: undefined, + message: "does not support the language 'xx-YY'", + }, + { + name: "assets_failed", + result: () => + Effect.succeed(failed('{"error":{"code":"assets_failed","message":"offline"}}')), + tag: "AppleSpeechHelperError", + reason: "assets_failed", + message: "language model could not be downloaded", + }, + { + name: "unavailable", + result: () => Effect.succeed(failed('{"error":{"code":"unavailable","message":"off"}}')), + tag: "AppleSpeechHelperError", + reason: "unavailable", + message: "not available on this Mac", + }, + { + name: "failed", + result: () => Effect.succeed(failed('{"error":{"code":"failed","message":"bad wav"}}')), + tag: "AppleSpeechHelperError", + reason: "failed", + message: "transcription failed", + }, + { + name: "crash without JSON", + result: () => Effect.succeed(failed("Segmentation fault")), + tag: "AppleSpeechHelperError", + reason: "failed", + message: "transcription failed", + }, + { + name: "unexpected success output", + result: () => Effect.succeed(output({ stdout: '{"transcript":"wrong shape"}' })), + tag: "AppleSpeechHelperError", + reason: "failed", + message: "transcription failed", + }, + { + name: "timeout", + result: (input: ProcessRunner.ProcessRunInput) => Effect.fail(timedOut(input)), + tag: "AppleSpeechHelperError", + reason: "timeout", + message: "did not finish within 120 seconds", + }, + ])( + "maps a $name helper result and still deletes the temp file", + ({ result, tag, reason, message }) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + let wavPath = ""; + const { service } = yield* setup( + macOS26, + helperThat((input) => { + wavPath = input.args.at(-1)!; + return result(input); + }), + ); + const error = yield* Effect.flip(service.transcribe({ audio, locale: "xx-YY" })); + expect(error._tag).toBe(tag); + if (reason !== undefined) { + assert.instanceOf(error, AppleSpeechHelper.AppleSpeechHelperError); + expect(error.reason).toBe(reason); + } + expect(error.message).toContain(message); + expect(wavPath).not.toBe(""); + expect(yield* fileSystem.exists(wavPath)).toBe(false); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); +}); diff --git a/apps/server/src/voiceTranscription/AppleSpeechHelper.ts b/apps/server/src/voiceTranscription/AppleSpeechHelper.ts new file mode 100644 index 0000000000000..5bd7a717ed7ad --- /dev/null +++ b/apps/server/src/voiceTranscription/AppleSpeechHelper.ts @@ -0,0 +1,277 @@ +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Context from "effect/Context"; +import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Schedule from "effect/Schedule"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; +import * as SubscriptionRef from "effect/SubscriptionRef"; +import * as NodeOS from "node:os"; + +import * as ServerConfig from "../config.ts"; +import * as ProcessRunner from "../processRunner.ts"; + +const HELPER_NAME = "t3-apple-speech"; +// Darwin 25 is macOS 26, the first release with SpeechAnalyzer. +const MIN_DARWIN_MAJOR = 25; +const PROBE_TIMEOUT = "10 seconds"; +const PROBE_RETRY_DELAY = Duration.minutes(1); +const PROBE_ATTEMPTS = 5; +// The first transcription in a language downloads its model through AssetInventory. +const TRANSCRIBE_TIMEOUT_SECONDS = 120; +const CAUSE_MAX_LENGTH = 300; + +const ProbeOutput = Schema.Struct({ available: Schema.Boolean }); + +const TranscribeOutput = Schema.Struct({ + text: Schema.String, + locale: Schema.String, +}); +type AppleSpeechTranscript = typeof TranscribeOutput.Type; + +const HelperErrorOutput = Schema.Struct({ + error: Schema.Struct({ + code: Schema.Literals(["unsupported_locale", "unavailable", "assets_failed", "failed"]), + message: Schema.String, + }), +}); + +const decodeProbe = Schema.decodeUnknownOption(Schema.fromJsonString(ProbeOutput)); +const decodeTranscript = Schema.decodeUnknownOption(Schema.fromJsonString(TranscribeOutput)); +const decodeHelperError = Schema.decodeUnknownOption(Schema.fromJsonString(HelperErrorOutput)); + +export class AppleSpeechUnsupportedLocaleError extends Schema.TaggedError()( + "AppleSpeechUnsupportedLocaleError", + { + locale: Schema.String, + }, +) { + override get message(): string { + return this.locale + ? `Apple on-device transcription does not support the language '${this.locale}'.` + : "Apple on-device transcription does not support this Mac's system language."; + } +} + +export class AppleSpeechHelperError extends Schema.TaggedError()( + "AppleSpeechHelperError", + { + reason: Schema.Literals(["unavailable", "assets_failed", "timeout", "failed"]), + cause: Schema.optional(Schema.Defect()), + }, +) { + override get message(): string { + switch (this.reason) { + case "unavailable": + return "Apple on-device transcription is not available on this Mac."; + case "assets_failed": + return "The Apple speech language model could not be downloaded."; + case "timeout": + return `Apple on-device transcription did not finish within ${TRANSCRIBE_TIMEOUT_SECONDS} seconds.`; + case "failed": + return "Apple on-device transcription failed."; + } + } +} + +class AppleSpeechProbeTimedOut extends Schema.TaggedError()( + "AppleSpeechProbeTimedOut", + { + helperPath: Schema.String, + }, +) { + override get message(): string { + return `The Apple speech helper at '${this.helperPath}' did not answer its probe within ${PROBE_TIMEOUT}.`; + } +} + +/** `unsupported-host` is anything older than macOS 26, where the helper is never spawned. */ +export type AppleSpeechAvailability = "available" | "unavailable" | "unsupported-host"; + +export class AppleSpeechHelper extends Context.Service< + AppleSpeechHelper, + { + /** The latest probe answer without waiting, false until one arrives; descriptor reads use it. */ + readonly available: Effect.Effect; + readonly streamAvailableChanges: Stream.Stream; + /** Waits for the first probe to answer. */ + readonly availability: Effect.Effect; + readonly transcribe: (input: { + readonly audio: Uint8Array; + readonly locale: string; + }) => Effect.Effect< + AppleSpeechTranscript, + AppleSpeechHelperError | AppleSpeechUnsupportedLocaleError + >; + } +>()("t3/voiceTranscription/AppleSpeechHelper") {} + +export const AppleSpeechHostKernelRelease = Context.Reference( + "t3/voiceTranscription/AppleSpeechHostKernelRelease", + { + defaultValue: () => NodeOS.release(), + }, +); + +const hostSupportsSpeechAnalyzer = (platform: NodeJS.Platform, kernelRelease: string) => + platform === "darwin" && Number.parseInt(kernelRelease, 10) >= MIN_DARWIN_MAJOR; + +/** The helper's stdout may hold the user's words, so a cause built from it records only its size. */ +const sizeOnlyCause = (stdout: string) => + new Error(`The helper printed ${stdout.length} bytes, not a transcript.`); + +export const make = Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const processRunner = yield* ProcessRunner.ProcessRunner; + const platform = yield* HostProcess.Platform; + const environment = yield* HostProcess.Environment; + const kernelRelease = yield* AppleSpeechHostKernelRelease; + + const candidates = [ + environment.T3CODE_APPLE_SPEECH_PATH, + config.appleSpeechHelperPath, + path.resolve(import.meta.dirname, "../../../../native/apple-speech/build", HELPER_NAME), + path.resolve(import.meta.dirname, "../../../native/apple-speech/build", HELPER_NAME), + ].filter((candidate): candidate is string => Boolean(candidate)); + + const locate = Effect.gen(function* () { + for (const candidate of candidates) { + if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) { + return Option.some(candidate); + } + } + yield* Effect.logDebug("No Apple speech helper found.", { candidates }); + return Option.none(); + }); + + const probe = Effect.fn("AppleSpeechHelper.probe")(function* (helperPath: string) { + const result = yield* processRunner + .run({ + command: helperPath, + args: ["probe"], + timeout: PROBE_TIMEOUT, + timeoutBehavior: "timedOutResult", + }) + .pipe(Effect.option); + if (Option.isSome(result) && result.value.timedOut) { + return yield* new AppleSpeechProbeTimedOut({ helperPath }); + } + const available = + Option.isSome(result) && + result.value.code === 0 && + Option.exists(decodeProbe(result.value.stdout), (output) => output.available); + if (!available) { + yield* Effect.logWarning("The Apple speech helper is present but unusable.", { helperPath }); + } + return available ? Option.some(helperPath) : Option.none(); + }); + + const hostSupported = hostSupportsSpeechAnalyzer(platform, kernelRelease); + const helperPath = yield* SubscriptionRef.make(Option.none()); + const firstProbeAnswered = yield* Deferred.make(); + const locateOnce = yield* Effect.cached(locate); + + const probeInBackground = locateOnce.pipe( + Effect.flatMap(Option.match({ onNone: () => Effect.succeedNone, onSome: probe })), + Effect.flatMap((found) => SubscriptionRef.set(helperPath, found)), + Effect.ensuring(Deferred.succeed(firstProbeAnswered, undefined)), + Effect.retry({ schedule: Schedule.spaced(PROBE_RETRY_DELAY), times: PROBE_ATTEMPTS - 1 }), + Effect.ignore({ log: true }), + ); + if (hostSupported) { + yield* Effect.forkScoped(probeInBackground); + } else { + yield* Deferred.succeed(firstProbeAnswered, undefined); + } + + const answeredHelperPath = Deferred.await(firstProbeAnswered).pipe( + Effect.andThen(SubscriptionRef.get(helperPath)), + ); + const availability: Effect.Effect = hostSupported + ? Effect.map(answeredHelperPath, (found) => + Option.isSome(found) ? "available" : "unavailable", + ) + : Effect.succeed("unsupported-host"); + + const transcribe = Effect.fn("AppleSpeechHelper.transcribe")(function* (input: { + readonly audio: Uint8Array; + readonly locale: string; + }) { + const command = yield* answeredHelperPath; + if (Option.isNone(command)) { + return yield* new AppleSpeechHelperError({ reason: "unavailable" }); + } + const directory = yield* fileSystem + .makeTempDirectoryScoped({ prefix: "t3-apple-speech-" }) + .pipe(Effect.mapError((cause) => new AppleSpeechHelperError({ reason: "failed", cause }))); + const wavPath = path.join(directory, "recording.wav"); + yield* fileSystem + .writeFile(wavPath, input.audio) + .pipe(Effect.mapError((cause) => new AppleSpeechHelperError({ reason: "failed", cause }))); + const result = yield* processRunner + .run({ + command: command.value, + args: ["transcribe", "--locale", input.locale, wavPath], + timeout: `${TRANSCRIBE_TIMEOUT_SECONDS} seconds`, + }) + .pipe( + Effect.mapError( + (cause) => + new AppleSpeechHelperError({ + reason: cause._tag === "ProcessTimeoutError" ? "timeout" : "failed", + cause, + }), + ), + ); + if (result.code !== 0) { + const reported = decodeHelperError(result.stdout); + if (Option.isNone(reported)) { + return yield* new AppleSpeechHelperError({ + reason: "failed", + cause: new Error(result.stderr.slice(0, CAUSE_MAX_LENGTH)), + }); + } + const { code, message } = reported.value.error; + return yield* code === "unsupported_locale" + ? new AppleSpeechUnsupportedLocaleError({ locale: input.locale }) + : new AppleSpeechHelperError({ + reason: code, + cause: new Error(message.slice(0, CAUSE_MAX_LENGTH)), + }); + } + return yield* Option.match(decodeTranscript(result.stdout), { + onNone: () => + new AppleSpeechHelperError({ reason: "failed", cause: sizeOnlyCause(result.stdout) }), + onSome: Effect.succeed, + }); + }, Effect.scoped); + + return AppleSpeechHelper.of({ + available: Effect.map(SubscriptionRef.get(helperPath), Option.isSome), + streamAvailableChanges: SubscriptionRef.changes(helperPath).pipe( + Stream.map(Option.isSome), + Stream.changes, + ), + availability, + transcribe, + }); +}); + +export const layer = Layer.effect(AppleSpeechHelper, make).pipe(Layer.provide(ProcessRunner.layer)); + +export const layerUnavailable = Layer.succeed( + AppleSpeechHelper, + AppleSpeechHelper.of({ + available: Effect.succeed(false), + streamAvailableChanges: Stream.make(false), + availability: Effect.succeed("unavailable"), + transcribe: () => new AppleSpeechHelperError({ reason: "unavailable" }), + }), +); diff --git a/apps/server/src/voiceTranscription/VoiceTranscription.fetch.test.ts b/apps/server/src/voiceTranscription/VoiceTranscription.fetch.test.ts new file mode 100644 index 0000000000000..0ca8e9967c7c4 --- /dev/null +++ b/apps/server/src/voiceTranscription/VoiceTranscription.fetch.test.ts @@ -0,0 +1,186 @@ +// @effect-diagnostics nodeBuiltinImport:off - the test runs a real HTTP server for undici fetch to call. +import * as NodeHttp from "node:http"; +import type * as NodeNet from "node:net"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Stream from "effect/Stream"; +import { FetchHttpClient } from "effect/http"; + +import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; +import * as ServerConfig from "../config.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import * as AppleSpeechHelper from "./AppleSpeechHelper.ts"; +import * as VoiceTranscription from "./VoiceTranscription.ts"; + +const audio = new Uint8Array(1024 * 1024).fill(7); + +const claims = { + version: 1, + kind: "voice-transcription", + nonce: "nonce", + mimeType: "audio/webm", + sizeBytes: audio.byteLength, + expiresAt: Number.MAX_SAFE_INTEGER, +} as const; + +type Upstream = (response: NodeHttp.ServerResponse) => void; + +const upstreamServer = (answer: Upstream) => + Effect.acquireRelease( + Effect.callback<{ readonly server: NodeHttp.Server; readonly port: number }>((resume) => { + // Answers before reading the upload, as a server rejecting the key does. + const server = NodeHttp.createServer((_request, response) => answer(response)); + server.listen(0, "127.0.0.1", () => + resume(Effect.succeed({ server, port: (server.address() as NodeNet.AddressInfo).port })), + ); + }), + ({ server }) => + Effect.callback((resume) => { + server.closeAllConnections(); + server.close(() => resume(Effect.void)); + }), + ); + +const processFailures = Effect.acquireRelease( + Effect.sync(() => { + const failures: Array = []; + const record = (failure: unknown) => failures.push(failure); + process.on("uncaughtException", record); + process.on("unhandledRejection", record); + return { failures, record }; + }), + ({ record }) => + Effect.sync(() => { + process.off("uncaughtException", record); + process.off("unhandledRejection", record); + }), +); + +// Not needed to pass. It gives a returning undici crash, which no event marks, time to land. +const settleProcess = Effect.sleep("200 millis"); + +const transcribeAgainst = (answer: Upstream) => + Effect.gen(function* () { + const { failures } = yield* processFailures; + const { port } = yield* upstreamServer(answer); + const layer = VoiceTranscription.layer.pipe( + Layer.provide( + ServerSettings.layerTest({ + voiceTranscription: { + enabled: true, + apiKey: "sk-test", + baseUrl: `http://127.0.0.1:${port}/v1`, + model: "whisper-1", + }, + }), + ), + Layer.provide(FetchHttpClient.layer), + Layer.provide( + Layer.succeed( + AppleSpeechHelper.AppleSpeechHelper, + AppleSpeechHelper.AppleSpeechHelper.of({ + available: Effect.succeed(false), + streamAvailableChanges: Stream.make(false), + availability: Effect.succeed("unsupported-host"), + transcribe: () => Effect.die("unused"), + }), + ), + ), + Layer.provide(ServerSecretStore.layer), + Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-voice-fetch-test-" })), + Layer.provide(NodeServices.layer), + ); + const result = yield* Effect.gen(function* () { + const voice = yield* VoiceTranscription.VoiceTranscription; + return yield* voice.transcribe(claims, audio); + }).pipe(Effect.provide(layer), Effect.result); + yield* settleProcess; + return { result, failures }; + }).pipe(Effect.scoped); + +const json = (status: number, body: unknown) => (response: NodeHttp.ServerResponse) => { + const text = JSON.stringify(body); + response.writeHead(status, { + "content-type": "application/json", + "content-length": Buffer.byteLength(text), + }); + response.end(text); +}; + +describe("VoiceTranscription over undici fetch", () => { + it.live("reports rejected credentials without crashing the process", () => + Effect.gen(function* () { + const { result, failures } = yield* transcribeAgainst( + json(401, { error: { message: "Incorrect API key provided" } }), + ); + expect(result).toMatchObject({ + failure: { + _tag: "VoiceTranscriptionCredentialsRejectedError", + status: 401, + cause: { message: "Incorrect API key provided" }, + }, + }); + expect(failures).toEqual([]); + }), + ); + + it.live("returns the transcript without crashing the process", () => + Effect.gen(function* () { + const { result, failures } = yield* transcribeAgainst(json(200, { text: "hi" })); + expect(result).toMatchObject({ success: { text: "hi" } }); + expect(failures).toEqual([]); + }), + ); + + it.live("refuses a chunked body over the cap without crashing the process", () => + Effect.gen(function* () { + const { result, failures } = yield* transcribeAgainst((response) => { + response.writeHead(200, { "content-type": "application/json" }); + const chunk = Buffer.alloc(256 * 1024, " "); + for (let index = 0; index < 6; index++) response.write(chunk); + response.end("{}"); + }); + expect(result).toMatchObject({ + failure: { + _tag: "VoiceTranscriptionUpstreamError", + stage: "response", + cause: { _tag: "VoiceTranscriptionUpstreamBodyTooLargeError" }, + }, + }); + expect(failures).toEqual([]); + }), + ); + + it.live("reports rejected credentials sent without a length without crashing", () => + Effect.gen(function* () { + const { result, failures } = yield* transcribeAgainst((response) => { + response.writeHead(401, { "content-type": "application/json" }); + response.write(JSON.stringify({ error: { message: "Incorrect API key provided" } })); + response.end(); + }); + expect(result).toMatchObject({ + failure: { + _tag: "VoiceTranscriptionCredentialsRejectedError", + cause: { message: "Incorrect API key provided" }, + }, + }); + expect(failures).toEqual([]); + }), + ); + + it.live("reports a 500 with an empty body without crashing the process", () => + Effect.gen(function* () { + const { result, failures } = yield* transcribeAgainst((response) => { + response.writeHead(500, { "content-length": 0 }); + response.end(); + }); + expect(result).toMatchObject({ + failure: { _tag: "VoiceTranscriptionUpstreamError", stage: "status", status: 500 }, + }); + expect(failures).toEqual([]); + }), + ); +}); diff --git a/apps/server/src/voiceTranscription/VoiceTranscription.test.ts b/apps/server/src/voiceTranscription/VoiceTranscription.test.ts new file mode 100644 index 0000000000000..cf146277c100a --- /dev/null +++ b/apps/server/src/voiceTranscription/VoiceTranscription.test.ts @@ -0,0 +1,660 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { describe, expect, it } from "@effect/vitest"; +import { + ServerSettingsError, + type VoiceTranscriptionAudioMimeType, + type VoiceTranscriptionSettings, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; +import { + HttpClient, + type HttpClientRequest, + HttpClientResponse, + HttpMiddleware, + HttpRouter, + HttpServerRequest, + HttpServerResponse, +} from "effect/http"; + +import { issueAttachmentUploadUrl } from "../assets/AttachmentUpload.ts"; +import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; +import * as ServerConfig from "../config.ts"; +import * as ServerHttp from "../http.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import * as AppleSpeechHelper from "./AppleSpeechHelper.ts"; +import * as VoiceTranscription from "./VoiceTranscription.ts"; + +const audio = new Uint8Array([1, 2, 3, 4, 5, 6]); + +const appleSpeechWith = ( + availability: AppleSpeechHelper.AppleSpeechAvailability, + transcribe: AppleSpeechHelper.AppleSpeechHelper["Service"]["transcribe"] = () => + Effect.die("the Apple speech helper is unavailable"), +) => + AppleSpeechHelper.AppleSpeechHelper.of({ + available: Effect.succeed(availability === "available"), + streamAvailableChanges: Stream.make(availability === "available"), + availability: Effect.succeed(availability), + transcribe, + }); + +const appleSpeechUnavailable = appleSpeechWith("unsupported-host"); + +const appleSpeechAvailable = ( + transcribe: AppleSpeechHelper.AppleSpeechHelper["Service"]["transcribe"], +) => appleSpeechWith("available", transcribe); + +function setup( + settings: Partial, + upstream: (request: HttpClientRequest.HttpClientRequest) => Effect.Effect = () => + Effect.succeed(Response.json({ text: "hello world" })), + appleSpeech = appleSpeechUnavailable, + overrides: { + readonly settingsService?: Layer.Layer; + readonly secretStore?: Layer.Layer; + } = {}, +) { + const requests: Array = []; + const client = HttpClient.make((request) => + Effect.suspend(() => { + requests.push(request); + return upstream(request); + }).pipe(Effect.map((response) => HttpClientResponse.fromWeb(request, response))), + ); + const layer = VoiceTranscription.layer.pipe( + Layer.provideMerge( + overrides.settingsService ?? + ServerSettings.layerTest({ + voiceTranscription: { enabled: true, apiKey: "sk-test", ...settings }, + }), + ), + Layer.provide(Layer.succeed(HttpClient.HttpClient, client)), + Layer.provide(Layer.succeed(AppleSpeechHelper.AppleSpeechHelper, appleSpeech)), + Layer.provideMerge(overrides.secretStore ?? ServerSecretStore.layer), + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-voice-test-" })), + Layer.provideMerge(NodeServices.layer), + ); + return { layer, requests }; +} + +const mintAs = (mimeType: VoiceTranscriptionAudioMimeType) => + Effect.gen(function* () { + const voice = yield* VoiceTranscription.VoiceTranscription; + return yield* voice.createUploadUrl({ mimeType, sizeBytes: audio.byteLength }); + }); +const mint = mintAs("audio/webm"); + +const xai = { + provider: "xai", + baseUrl: "https://api.x.ai/v1", + model: "grok-voice-transcribe-2.0", +} as const; + +const apple = { provider: "apple-on-device", baseUrl: "", model: "", apiKey: "" } as const; + +const post = ( + relativeUrl: string, + options: { readonly body?: Uint8Array; readonly contentLength?: number | null } = {}, +) => + Effect.gen(function* () { + const body = options.body ?? audio; + const app = yield* HttpRouter.toHttpEffect(ServerHttp.layerVoiceTranscriptionRoute); + const request = new Request(`http://t3.test${relativeUrl}`, { + method: "POST", + body: new Blob([new Uint8Array(body)]), + headers: { + "content-type": "audio/webm", + ...(options.contentLength === null + ? {} + : { "content-length": String(options.contentLength ?? body.byteLength) }), + }, + }); + const response = HttpServerResponse.toWeb( + yield* app.pipe( + Effect.provideService( + HttpServerRequest.HttpServerRequest, + HttpServerRequest.fromWeb(request), + ), + ), + ); + return { + status: response.status, + body: (yield* Effect.promise(() => response.json())) as Record, + }; + }).pipe(Effect.scoped); + +const formOf = (request: HttpClientRequest.HttpClientRequest) => { + const { body } = request; + if (body._tag !== "Uint8Array") throw new Error(`expected bytes, got ${body._tag}`); + const headers = { "content-type": request.headers["content-type"] ?? "" }; + return Effect.promise(() => new Response(body.body, { headers }).formData()); +}; + +describe("VoiceTranscription", () => { + it("lets the cross-origin hosted web app read the transcript", async () => { + const layerApp = Layer.mergeAll( + ServerHttp.layerVoiceTranscriptionRoute, + ServerHttp.layerBrowserApiCors, + ).pipe( + Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-voice-cors-test-" })), + Layer.provide(NodeServices.layer), + ); + const { handler, dispose } = HttpRouter.toWebHandler(layerApp, { disableLogger: true }); + const services = Context.make( + VoiceTranscription.VoiceTranscription, + VoiceTranscription.VoiceTranscription.of({ + createUploadUrl: () => Effect.die("unused"), + verifyUploadToken: () => + Effect.succeedSome({ + version: 1, + kind: "voice-transcription", + nonce: "nonce", + mimeType: "audio/webm", + sizeBytes: audio.byteLength, + expiresAt: Number.MAX_SAFE_INTEGER, + } as const), + transcribe: () => Effect.succeed({ text: "hello world" }), + }), + ); + try { + const url = "https://backend.example/api/voice/transcriptions/token"; + const preflight = await handler( + new Request(url, { + method: "OPTIONS", + headers: { + origin: "https://app.t3.codes", + "access-control-request-method": "POST", + "access-control-request-headers": "content-type", + }, + }), + services, + ); + expect(preflight.status).toBe(204); + expect(preflight.headers.get("access-control-allow-origin")).toBe("*"); + + const response = await handler( + new Request(url, { + method: "POST", + body: new Blob([audio]), + headers: { + origin: "https://app.t3.codes", + "content-type": "audio/webm", + "content-length": String(audio.byteLength), + }, + }), + services, + ); + expect(response.status).toBe(200); + expect(response.headers.get("access-control-allow-origin")).toBe("*"); + expect(await response.json()).toEqual({ text: "hello world" }); + } finally { + await dispose(); + } + }); + + it.effect.each([ + { settings: { enabled: false }, message: "turned off" }, + { settings: { apiKey: "" }, message: "OpenAI API key" }, + { settings: { ...xai, apiKey: "" }, message: "xAI API key" }, + { settings: xai, message: "xAI does not accept audio/webm recordings." }, + { settings: apple, message: "Apple on-device transcription needs macOS 26 or later" }, + { + settings: apple, + appleSpeech: appleSpeechWith("unavailable"), + message: "Apple on-device transcription is unavailable on the machine running T3 Code.", + }, + { settings: { model: "" }, message: "model name" }, + { settings: { baseUrl: "" }, message: "endpoint URL" }, + { settings: { baseUrl: "ftp://whisper.local" }, message: "not valid" }, + { settings: { baseUrl: "http://api.example.com/v1" }, message: "only over https" }, + ] as const)("refuses to mint an upload URL when $message", (expected) => { + const { settings, message } = expected; + const { layer } = setup( + settings, + undefined, + "appleSpeech" in expected ? expected.appleSpeech : undefined, + ); + return Effect.gen(function* () { + const error = yield* Effect.flip(mint); + expect(error._tag).toBe("VoiceTranscriptionNotConfiguredError"); + expect(error.message).toContain(message); + }).pipe(Effect.provide(layer)); + }); + + it.effect("transcribes through a keyless local server with the singular language hint", () => { + const { layer, requests } = setup({ + baseUrl: "http://whisper.local:8080/v1/", + model: "whisper-1", + language: "en", + apiKey: "", + }); + return Effect.gen(function* () { + const issued = yield* mint; + expect(issued.relativeUrl.startsWith("/api/voice/transcriptions/")).toBe(true); + const response = yield* post(issued.relativeUrl); + + expect(response).toEqual({ status: 200, body: { text: "hello world" } }); + expect(requests).toHaveLength(1); + const request = requests[0]!; + expect(request.url).toBe("http://whisper.local:8080/v1/audio/transcriptions"); + expect(request.headers.authorization).toBeUndefined(); + const form = yield* formOf(request); + expect(form.get("model")).toBe("whisper-1"); + expect(form.get("response_format")).toBe("json"); + expect(form.getAll("language")).toEqual(["en"]); + expect(form.has("languages[]")).toBe(false); + const file = form.get("file") as File; + expect(file.name).toBe("audio.webm"); + expect(file.type).toBe("audio/webm"); + expect(new Uint8Array(yield* Effect.promise(() => file.arrayBuffer()))).toEqual(audio); + }).pipe(Effect.provide(layer)); + }); + + it.effect.each([ + { baseUrl: "http://localhost:8080/v1", apiKey: "sk-test" }, + { baseUrl: "http://127.0.0.2:8080/v1", apiKey: "sk-test" }, + { baseUrl: "http://[::1]:8080/v1", apiKey: "sk-test" }, + { baseUrl: "http://192.168.1.20/v1", apiKey: "sk-test" }, + { baseUrl: "http://10.0.0.5/v1", apiKey: "sk-test" }, + { baseUrl: "http://172.20.0.5/v1", apiKey: "sk-test" }, + { baseUrl: "http://169.254.10.1/v1", apiKey: "sk-test" }, + { baseUrl: "http://[fd12::5]/v1", apiKey: "sk-test" }, + { baseUrl: "http://gpu-box.local/v1", apiKey: "sk-test" }, + { baseUrl: "http://api.example.com/v1", apiKey: "" }, + ])("allows http to a private endpoint, or anywhere without a key: $baseUrl", (settings) => { + const { layer, requests } = setup({ ...settings, model: "whisper-1" }); + return Effect.gen(function* () { + expect((yield* post((yield* mint).relativeUrl)).status).toBe(200); + expect(requests[0]!.headers.authorization).toBe( + settings.apiKey ? `Bearer ${settings.apiKey}` : undefined, + ); + }).pipe(Effect.provide(layer)); + }); + + it.effect.each([ + { language: "fr", languages: ["fr"] }, + { language: "", languages: [] }, + ])( + "sends gpt-transcribe language hint $language as languages with the key", + ({ language, languages }) => { + const { layer, requests } = setup({ language }); + return Effect.gen(function* () { + expect((yield* post((yield* mint).relativeUrl)).status).toBe(200); + const request = requests[0]!; + expect(request.url).toBe("https://api.openai.com/v1/audio/transcriptions"); + expect(request.headers.authorization).toBe("Bearer sk-test"); + const form = yield* formOf(request); + expect(form.get("model")).toBe("gpt-transcribe"); + expect(form.getAll("languages[]")).toEqual(languages); + expect(form.has("language")).toBe(false); + }).pipe(Effect.provide(layer)); + }, + ); + + it.effect.each([ + { language: "en", fields: ["model", "language", "file"] }, + { language: "", fields: ["model", "file"] }, + ])( + "transcribes through xAI speech-to-text with language hint '$language' and the file last", + ({ language, fields }) => { + const { layer, requests } = setup({ ...xai, language }, () => + Effect.succeed( + Response.json({ text: "hello grok", language: "en", duration: 1.2, words: [] }), + ), + ); + return Effect.gen(function* () { + const response = yield* post((yield* mintAs("audio/wav")).relativeUrl); + + expect(response).toEqual({ status: 200, body: { text: "hello grok" } }); + expect(requests).toHaveLength(1); + const request = requests[0]!; + expect(request.method).toBe("POST"); + expect(request.url).toBe("https://api.x.ai/v1/stt"); + expect(request.headers.authorization).toBe("Bearer sk-test"); + const form = yield* formOf(request); + expect([...form.keys()]).toEqual(fields); + expect(form.get("model")).toBe("grok-voice-transcribe-2.0"); + expect(form.getAll("language")).toEqual(language ? [language] : []); + const file = form.get("file") as File; + expect(file.name).toBe("audio.wav"); + expect(file.type).toBe("audio/wav"); + expect(new Uint8Array(yield* Effect.promise(() => file.arrayBuffer()))).toEqual(audio); + }).pipe(Effect.provide(layer)); + }, + ); + + it.effect("mints WAV but not WebM for Apple on-device without a key, URL, or model", () => { + const { layer } = setup( + apple, + undefined, + appleSpeechAvailable(() => Effect.die("unused")), + ); + return Effect.gen(function* () { + const error = yield* Effect.flip(mint); + expect(error.message).toBe( + "Apple on-device transcription does not accept audio/webm recordings.", + ); + const issued = yield* mintAs("audio/wav"); + expect(issued.relativeUrl.startsWith("/api/voice/transcriptions/")).toBe(true); + }).pipe(Effect.provide(layer)); + }); + + it.effect("transcribes WAV through the Apple speech helper without an HTTP request", () => { + const transcribed: Array<{ readonly audio: Uint8Array; readonly locale: string }> = []; + const { layer, requests } = setup( + { ...apple, language: "en" }, + undefined, + appleSpeechAvailable((input) => { + transcribed.push(input); + return Effect.succeed({ text: "hello apple", locale: "en_US" }); + }), + ); + return Effect.gen(function* () { + const response = yield* post((yield* mintAs("audio/wav")).relativeUrl); + expect(response).toEqual({ status: 200, body: { text: "hello apple" } }); + expect(requests).toHaveLength(0); + expect(transcribed).toEqual([{ audio, locale: "en" }]); + }).pipe(Effect.provide(layer)); + }); + + it.effect.each([ + { + failure: new AppleSpeechHelper.AppleSpeechUnsupportedLocaleError({ locale: "xx-YY" }), + status: 409, + code: "not_configured", + message: "Apple on-device transcription does not support the language 'xx-YY'.", + }, + { + failure: new AppleSpeechHelper.AppleSpeechHelperError({ reason: "assets_failed" }), + status: 502, + code: "upstream_failed", + message: "The Apple speech language model could not be downloaded.", + }, + ])("answers $code when the Apple speech helper fails with $failure._tag", (expected) => { + const { layer } = setup( + apple, + undefined, + appleSpeechAvailable(() => expected.failure), + ); + return Effect.gen(function* () { + const response = yield* post((yield* mintAs("audio/wav")).relativeUrl); + expect(response).toEqual({ + status: expected.status, + body: { code: expected.code, message: expected.message }, + }); + }).pipe(Effect.provide(layer)); + }); + + it.effect("refuses a WebM upload minted before switching to xAI without calling upstream", () => { + const { layer, requests } = setup({}); + return Effect.gen(function* () { + const issued = yield* mint; + const settings = yield* ServerSettings.ServerSettingsService; + yield* settings.updateSettings({ voiceTranscription: { ...xai, apiKey: "sk-xai" } }); + const response = yield* post(issued.relativeUrl); + expect(response).toEqual({ + status: 409, + body: { code: "not_configured", message: "xAI does not accept audio/webm recordings." }, + }); + expect(requests).toHaveLength(0); + }).pipe(Effect.provide(layer)); + }); + + it.effect.each([ + { + upstream: Response.json( + { error: { message: "Incorrect API key provided: sk-test." } }, + { status: 401 }, + ), + code: "upstream_rejected_credentials", + message: "The transcription service at api.openai.com rejected the API key (HTTP 401).", + cause: "Incorrect API key provided: [key].", + }, + { + upstream: Response.json({ error: "model not loaded" }, { status: 500 }), + code: "upstream_failed", + message: "The transcription service at api.openai.com answered HTTP 500.", + cause: "model not loaded", + }, + { + upstream: new Response("bad gateway", { status: 503 }), + code: "upstream_failed", + message: "The transcription service at api.openai.com answered HTTP 503.", + cause: undefined, + }, + { + upstream: Response.json({ transcript: "wrong shape" }), + code: "upstream_failed", + message: "The transcription service at api.openai.com returned an unexpected response.", + cause: undefined, + }, + ])( + "answers $code with a 502 for upstream HTTP $upstream.status", + ({ upstream, code, message, cause }) => { + const { layer } = setup({}, () => Effect.succeed(upstream.clone())); + return Effect.gen(function* () { + const response = yield* post((yield* mint).relativeUrl); + expect(response).toEqual({ status: 502, body: { code, message } }); + + const voice = yield* VoiceTranscription.VoiceTranscription; + const token = (yield* mint).relativeUrl.split("/").at(-1)!; + const claims = Option.getOrThrow(yield* voice.verifyUploadToken(token)); + const error = yield* Effect.flip(voice.transcribe(claims, audio)); + if (cause !== undefined) { + expect(error.cause).toBeInstanceOf(Error); + expect((error.cause as Error).message).toBe(cause); + } + }).pipe(Effect.provide(layer)); + }, + ); + + it.effect.each([200, 500])("stops reading an upstream HTTP %s body past 1 MiB", (status) => { + const chunk = new Uint8Array(64 * 1024).fill(0x61); + let sentBytes = 0; + const { layer } = setup({}, () => + Effect.succeed( + new Response( + new ReadableStream({ + pull: (controller) => { + if (sentBytes > 2 * 1024 * 1024) return new Promise(() => {}); + sentBytes += chunk.byteLength; + controller.enqueue(chunk); + }, + }), + { status }, + ), + ), + ); + return Effect.gen(function* () { + const response = yield* post((yield* mint).relativeUrl); + expect(response).toEqual({ + status: 502, + body: { + code: "upstream_failed", + message: + status === 200 + ? "The transcription service at api.openai.com returned an unexpected response." + : "The transcription service at api.openai.com answered HTTP 500.", + }, + }); + expect(sentBytes).toBeLessThan(2 * 1024 * 1024); + }).pipe(Effect.provide(layer)); + }); + + it.effect("answers internal when the settings cannot be read", () => { + const { layer } = setup({}, undefined, undefined, { + settingsService: Layer.mock(ServerSettings.ServerSettingsService)({ + getSettings: Effect.fail( + new ServerSettingsError({ settingsPath: "settings.json", operation: "read-file" }), + ), + }), + }); + return Effect.gen(function* () { + const error = yield* Effect.flip(mint); + expect(error._tag).toBe("VoiceTranscriptionInternalError"); + expect(error.message).toBe("Voice transcription hit a server error."); + }).pipe(Effect.provide(layer)); + }); + + it.effect("answers internal instead of an invalid link when the signing key cannot load", () => { + const { layer, requests } = setup({}, undefined, undefined, { + secretStore: Layer.mock(ServerSecretStore.ServerSecretStore)({ + getOrCreateRandom: () => + Effect.fail( + new ServerSecretStore.SecretStoreReadError({ + resource: "upload signing key", + cause: new Error("disk unreadable"), + }), + ), + }), + }); + return Effect.gen(function* () { + const response = yield* post("/api/voice/transcriptions/payload.signature"); + expect(response).toEqual({ + status: 500, + body: { code: "internal", message: "Voice transcription hit a server error." }, + }); + expect(requests).toHaveLength(0); + }).pipe(Effect.provide(layer)); + }); + + it.effect("answers upstream_failed when the service does not answer in time", () => + Effect.gen(function* () { + const reached = yield* Deferred.make(); + const { layer } = setup({}, () => + Deferred.succeed(reached, undefined).pipe(Effect.andThen(Effect.never)), + ); + yield* Effect.gen(function* () { + const pending = yield* Effect.forkChild(post((yield* mint).relativeUrl)); + yield* Deferred.await(reached); + yield* TestClock.adjust("90 seconds"); + const response = yield* Fiber.join(pending); + expect(response.status).toBe(502); + expect(response.body).toEqual({ + code: "upstream_failed", + message: "The transcription service at api.openai.com did not answer within 90 seconds.", + }); + }).pipe(Effect.provide(layer)); + }), + ); + + it.effect( + "rejects tampered, expired, foreign, and mis-sized uploads before calling upstream", + () => { + const { layer, requests } = setup({}); + return Effect.gen(function* () { + const attachment = yield* issueAttachmentUploadUrl({ + type: "file", + name: "audio.webm", + mimeType: "audio/webm", + sizeBytes: audio.byteLength, + }); + const attachmentToken = attachment.relativeUrl.split("/").at(-1)!; + const rejected = [ + yield* post(`${(yield* mint).relativeUrl}x`), + yield* post(`/api/voice/transcriptions/${attachmentToken}`), + yield* post((yield* mint).relativeUrl, { contentLength: audio.byteLength + 1 }), + yield* post((yield* mint).relativeUrl, { + body: audio.slice(1), + contentLength: audio.byteLength - 1, + }), + ]; + const expiring = yield* mint; + yield* TestClock.adjust("2 minutes"); + rejected.push(yield* post(expiring.relativeUrl)); + + for (const response of rejected) { + expect(response.status).toBe(400); + expect(response.body.code).toBe("invalid_upload"); + } + expect(requests).toHaveLength(0); + }).pipe(Effect.provide(layer)); + }, + ); + + it.effect("accepts a re-chunked upload without Content-Length but still checks its size", () => { + const { layer, requests } = setup({}); + return Effect.gen(function* () { + expect(yield* post((yield* mint).relativeUrl, { contentLength: null })).toEqual({ + status: 200, + body: { text: "hello world" }, + }); + const longer = yield* post((yield* mint).relativeUrl, { + body: new Uint8Array([...audio, 7]), + contentLength: null, + }); + const shorter = yield* post((yield* mint).relativeUrl, { + body: audio.slice(1), + contentLength: null, + }); + for (const response of [longer, shorter]) { + expect(response.status).toBe(400); + expect(response.body.code).toBe("invalid_upload"); + } + expect(requests).toHaveLength(1); + }).pipe(Effect.provide(layer)); + }); + + it.effect("accepts each upload link once", () => { + const { layer, requests } = setup({}); + return Effect.gen(function* () { + const issued = yield* mint; + expect((yield* post(issued.relativeUrl)).status).toBe(200); + expect(yield* post(issued.relativeUrl)).toEqual({ + status: 400, + body: { + code: "invalid_upload", + message: "This transcription link is invalid or has expired.", + }, + }); + expect((yield* post((yield* mint).relativeUrl)).status).toBe(200); + expect(requests).toHaveLength(2); + }).pipe(Effect.provide(layer)); + }); + + it.effect("keeps upload links out of traces", () => + Effect.gen(function* () { + const traced = yield* Deferred.make<(path: string) => boolean>(); + yield* Layer.build( + ServerHttp.withUntracedRequests( + Layer.effectDiscard( + Effect.gen(function* () { + const disabled = yield* HttpMiddleware.TracerDisabledWhen; + yield* Deferred.succeed( + traced, + (path) => + !disabled(HttpServerRequest.fromWeb(new Request(`http://t3.test${path}`))), + ); + }), + ), + ), + ); + const isTraced = yield* Deferred.await(traced); + expect(isTraced("/api/voice/transcriptions/payload.signature")).toBe(false); + expect(isTraced("/api/attachments/upload/payload.signature")).toBe(true); + }).pipe(Effect.scoped), + ); + + it.effect("answers not_configured when transcription is turned off after minting", () => { + const { layer, requests } = setup({}); + return Effect.gen(function* () { + const issued = yield* mint; + const settings = yield* ServerSettings.ServerSettingsService; + yield* settings.updateSettings({ voiceTranscription: { enabled: false } }); + const response = yield* post(issued.relativeUrl); + expect(response.status).toBe(409); + expect(response.body).toEqual({ + code: "not_configured", + message: "Voice transcription is turned off for this environment.", + }); + expect(requests).toHaveLength(0); + }).pipe(Effect.provide(layer)); + }); +}); diff --git a/apps/server/src/voiceTranscription/VoiceTranscription.ts b/apps/server/src/voiceTranscription/VoiceTranscription.ts new file mode 100644 index 0000000000000..c982bf3a09ed1 --- /dev/null +++ b/apps/server/src/voiceTranscription/VoiceTranscription.ts @@ -0,0 +1,483 @@ +import { + VOICE_TRANSCRIPTION_PROVIDER_DEFAULTS, + VOICE_TRANSCRIPTION_URL_TTL_MS, + VoiceTranscriptionAudioMimeType, + type VoiceTranscriptionCreateUrlInput, + type VoiceTranscriptionCreateUrlResult, + VoiceTranscriptionInternalError, + VoiceTranscriptionNotConfiguredError, + type VoiceTranscriptionNotConfiguredReason, + type VoiceTranscriptionProvider, + type VoiceTranscriptionResult, + type VoiceTranscriptionSettings, +} from "@t3tools/contracts"; +import { isPrivateNetworkHost } from "@t3tools/shared/hostClassification"; +import * as Clock from "effect/Clock"; +import * as Context from "effect/Context"; +import * as Crypto from "effect/Crypto"; +import * as Effect from "effect/Effect"; +import { identity } from "effect/Function"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Ref from "effect/Ref"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; +import { HttpClient, HttpClientRequest, type HttpClientResponse } from "effect/http"; + +import { loadUploadSigningSecret } from "../assets/AttachmentUpload.ts"; +import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; +import { + base64UrlDecodeUtf8, + base64UrlEncode, + signPayload, + timingSafeEqualBase64Url, +} from "../auth/utils.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import * as AppleSpeechHelper from "./AppleSpeechHelper.ts"; + +export const VOICE_TRANSCRIPTION_ROUTE_PREFIX = "/api/voice/transcriptions"; + +const UPSTREAM_TIMEOUT_SECONDS = 90; +const UPSTREAM_MESSAGE_MAX_LENGTH = 300; +const UPSTREAM_BODY_MAX_BYTES = 1024 * 1024; + +export class VoiceTranscriptionInvalidUploadError extends Schema.TaggedError()( + "VoiceTranscriptionInvalidUploadError", + { + expectedBytes: Schema.Number, + receivedBytes: Schema.Number, + }, +) { + override get message(): string { + return `The recording was ${this.receivedBytes} bytes, expected ${this.expectedBytes}.`; + } +} + +export class VoiceTranscriptionCredentialsRejectedError extends Schema.TaggedError()( + "VoiceTranscriptionCredentialsRejectedError", + { + host: Schema.String, + status: Schema.Number, + cause: Schema.optional(Schema.Defect()), + }, +) { + override get message(): string { + return `The transcription service at ${this.host} rejected the API key (HTTP ${this.status}).`; + } +} + +export class VoiceTranscriptionUpstreamError extends Schema.TaggedError()( + "VoiceTranscriptionUpstreamError", + { + host: Schema.String, + stage: Schema.Literals(["request", "timeout", "status", "response"]), + status: Schema.optional(Schema.Number), + cause: Schema.optional(Schema.Defect()), + }, +) { + override get message(): string { + switch (this.stage) { + case "request": + return `Could not reach the transcription service at ${this.host}.`; + case "timeout": + return `The transcription service at ${this.host} did not answer within ${UPSTREAM_TIMEOUT_SECONDS} seconds.`; + case "status": + return `The transcription service at ${this.host} answered HTTP ${this.status}.`; + case "response": + return `The transcription service at ${this.host} returned an unexpected response.`; + } + } +} + +class VoiceTranscriptionUpstreamBodyTooLargeError extends Schema.TaggedError()( + "VoiceTranscriptionUpstreamBodyTooLargeError", + { + maxBytes: Schema.Number, + }, +) { + override get message(): string { + return `The transcription service answered with more than ${this.maxBytes} bytes.`; + } +} + +const VoiceTranscriptionClaims = Schema.Struct({ + version: Schema.Literal(1), + kind: Schema.Literal("voice-transcription"), + /** Keeps two otherwise identical links distinct, since each is accepted once. */ + nonce: Schema.String, + mimeType: VoiceTranscriptionAudioMimeType, + sizeBytes: Schema.Number, + expiresAt: Schema.Number, +}); +export type VoiceTranscriptionClaims = typeof VoiceTranscriptionClaims.Type; + +const claimsJson = Schema.fromJsonString(VoiceTranscriptionClaims); +const decodeClaims = Schema.decodeUnknownOption(claimsJson); +const encodeClaims = Schema.encodeSync(claimsJson); + +const decodeTranscript = Schema.decodeUnknownEffect( + Schema.fromJsonString(Schema.Struct({ text: Schema.String })), +); +// OpenAI nests the message under `error`; some compatible servers send `error` as a plain string. +const decodeUpstreamError = Schema.decodeUnknownOption( + Schema.fromJsonString( + Schema.Struct({ + error: Schema.Union([Schema.Struct({ message: Schema.String }), Schema.String]), + }), + ), +); + +const AUDIO_FILE_EXTENSIONS = { + "audio/webm": "webm", + "audio/ogg": "ogg", + "audio/mp4": "mp4", + "audio/mpeg": "mp3", + "audio/wav": "wav", +} as const satisfies Record; + +interface TranscriptionFormInput { + readonly model: string; + readonly language: string; + readonly file: Blob; + readonly fileName: string; +} + +interface ProviderBackendBase { + readonly name: string; + readonly acceptedMimeTypes: ReadonlyArray; +} + +interface HttpProviderBackend extends ProviderBackendBase { + readonly kind: "http"; + readonly path: string; + readonly hostedBaseUrl: string; + readonly form: (input: TranscriptionFormInput) => FormData; +} + +interface AppleProviderBackend extends ProviderBackendBase { + readonly kind: "apple"; +} + +type ProviderBackend = HttpProviderBackend | AppleProviderBackend; + +const PROVIDER_BACKENDS = { + "openai-compatible": { + kind: "http", + name: "OpenAI", + path: "audio/transcriptions", + hostedBaseUrl: VOICE_TRANSCRIPTION_PROVIDER_DEFAULTS["openai-compatible"].baseUrl, + acceptedMimeTypes: VoiceTranscriptionAudioMimeType.literals, + form: ({ model, language, file, fileName }) => { + const form = new FormData(); + form.append("file", file, fileName); + form.append("model", model); + form.append("response_format", "json"); + if (language) { + // gpt-transcribe takes a `languages` array instead of `language` and rejects both together. + form.append(model.startsWith("gpt-transcribe") ? "languages[]" : "language", language); + } + return form; + }, + }, + xai: { + kind: "http", + name: "xAI", + path: "stt", + hostedBaseUrl: VOICE_TRANSCRIPTION_PROVIDER_DEFAULTS.xai.baseUrl, + acceptedMimeTypes: ["audio/ogg", "audio/mp4", "audio/mpeg", "audio/wav"], + form: ({ model, language, file, fileName }) => { + const form = new FormData(); + form.append("model", model); + if (language) form.append("language", language); + // xAI may ignore fields sent after `file`, so it must be last. + form.append("file", file, fileName); + return form; + }, + }, + "apple-on-device": { + kind: "apple", + name: "Apple on-device transcription", + acceptedMimeTypes: ["audio/wav"], + }, +} as const satisfies Record; + +type HttpTranscriptionEndpoint = HttpProviderBackend & { + readonly url: string; + readonly host: string; + readonly model: string; + readonly language: string; + readonly apiKey: string; +}; + +type TranscriptionEndpoint = + | HttpTranscriptionEndpoint + | (AppleProviderBackend & { readonly language: string }); + +const acceptsMimeType = (backend: ProviderBackend, mimeType: VoiceTranscriptionAudioMimeType) => + backend.acceptedMimeTypes.includes(mimeType); + +const orInternalError = + (stage: VoiceTranscriptionInternalError["stage"]) => + (effect: Effect.Effect) => + effect.pipe( + Effect.tapError((cause) => + Effect.logError("Voice transcription hit a server error.", { stage, cause }), + ), + Effect.mapError((cause) => new VoiceTranscriptionInternalError({ stage, cause })), + ); + +export class VoiceTranscription extends Context.Service< + VoiceTranscription, + { + readonly createUploadUrl: ( + input: VoiceTranscriptionCreateUrlInput, + ) => Effect.Effect< + VoiceTranscriptionCreateUrlResult, + VoiceTranscriptionNotConfiguredError | VoiceTranscriptionInternalError + >; + readonly verifyUploadToken: ( + token: string, + ) => Effect.Effect, VoiceTranscriptionInternalError>; + readonly transcribe: ( + claims: VoiceTranscriptionClaims, + audio: Uint8Array, + ) => Effect.Effect< + VoiceTranscriptionResult, + | VoiceTranscriptionNotConfiguredError + | VoiceTranscriptionInvalidUploadError + | VoiceTranscriptionCredentialsRejectedError + | VoiceTranscriptionUpstreamError + | VoiceTranscriptionInternalError + | AppleSpeechHelper.AppleSpeechHelperError + >; + } +>()("t3/voiceTranscription/VoiceTranscription") {} + +const make = Effect.gen(function* () { + const settingsService = yield* ServerSettings.ServerSettingsService; + const secretStore = yield* ServerSecretStore.ServerSecretStore; + const client = yield* HttpClient.HttpClient; + const appleSpeech = yield* AppleSpeechHelper.AppleSpeechHelper; + const crypto = yield* Crypto.Crypto; + const consumedSignatures = yield* Ref.make(new Map()); + + const signingSecret = loadUploadSigningSecret.pipe( + Effect.provideService(ServerSecretStore.ServerSecretStore, secretStore), + orInternalError("load-signing-key"), + ); + + const resolveEndpoint = Effect.fn("VoiceTranscription.resolveEndpoint")(function* ( + settings: VoiceTranscriptionSettings, + ): Effect.fn.Return { + const backend = PROVIDER_BACKENDS[settings.provider]; + const notConfigured = (reason: VoiceTranscriptionNotConfiguredReason) => + new VoiceTranscriptionNotConfiguredError({ reason, providerName: backend.name }); + if (!settings.enabled) return yield* notConfigured("disabled"); + if (backend.kind === "apple") { + const availability = yield* appleSpeech.availability; + if (availability !== "available") { + return yield* notConfigured( + availability === "unsupported-host" ? "apple-unsupported-host" : "apple-unavailable", + ); + } + return { ...backend, language: settings.language }; + } + const baseUrl = settings.baseUrl.replace(/\/+$/, ""); + if (!baseUrl) return yield* notConfigured("missing-base-url"); + if (!settings.model) return yield* notConfigured("missing-model"); + if (!settings.apiKey && baseUrl === backend.hostedBaseUrl) { + return yield* notConfigured("missing-api-key"); + } + const url = URL.parse(`${baseUrl}/${backend.path}`); + if (!url || (url.protocol !== "https:" && url.protocol !== "http:")) { + return yield* notConfigured("invalid-base-url"); + } + if (url.protocol === "http:" && settings.apiKey && !isPrivateNetworkHost(url.hostname)) { + return yield* notConfigured("insecure-base-url"); + } + return { + ...backend, + url: url.toString(), + host: url.host, + model: settings.model, + language: settings.language, + apiKey: settings.apiKey, + }; + }); + + const loadEndpoint = Effect.fn("VoiceTranscription.loadEndpoint")(function* ( + mimeType: VoiceTranscriptionAudioMimeType, + ) { + const settings = yield* settingsService.getSettings.pipe(orInternalError("read-settings")); + const endpoint = yield* resolveEndpoint(settings.voiceTranscription); + if (!acceptsMimeType(endpoint, mimeType)) { + return yield* new VoiceTranscriptionNotConfiguredError({ + reason: "unsupported-format", + providerName: endpoint.name, + mimeType, + }); + } + return endpoint; + }); + + const readUpstreamText = Effect.fn("VoiceTranscription.readUpstreamText")(function* ( + response: HttpClientResponse.HttpClientResponse, + ) { + const decoder = new TextDecoder(); + let text = ""; + let receivedBytes = 0; + yield* Stream.runForEach(response.stream, (chunk) => { + receivedBytes += chunk.byteLength; + if (receivedBytes > UPSTREAM_BODY_MAX_BYTES) { + return new VoiceTranscriptionUpstreamBodyTooLargeError({ + maxBytes: UPSTREAM_BODY_MAX_BYTES, + }); + } + text += decoder.decode(chunk, { stream: true }); + return Effect.void; + }); + return text + decoder.decode(); + }); + + const readUpstreamCause = Effect.fn("VoiceTranscription.readUpstreamCause")(function* ( + response: HttpClientResponse.HttpClientResponse, + apiKey: string, + ) { + const body = yield* readUpstreamText(response).pipe(Effect.option); + const reported = Option.getOrUndefined(Option.flatMap(body, decodeUpstreamError)); + if (reported === undefined) return undefined; + const message = typeof reported.error === "string" ? reported.error : reported.error.message; + const redacted = apiKey ? message.replaceAll(apiKey, "[key]") : message; + return new Error(redacted.slice(0, UPSTREAM_MESSAGE_MAX_LENGTH)); + }); + + const createUploadUrl = Effect.fn("VoiceTranscription.createUploadUrl")(function* ( + input: VoiceTranscriptionCreateUrlInput, + ) { + yield* loadEndpoint(input.mimeType); + const secret = yield* signingSecret; + const expiresAt = (yield* Clock.currentTimeMillis) + VOICE_TRANSCRIPTION_URL_TTL_MS; + const encodedPayload = base64UrlEncode( + encodeClaims({ + version: 1, + kind: "voice-transcription", + nonce: yield* crypto.randomUUIDv4().pipe(Effect.orDie), + mimeType: input.mimeType, + sizeBytes: input.sizeBytes, + expiresAt, + }), + ); + return { + relativeUrl: `${VOICE_TRANSCRIPTION_ROUTE_PREFIX}/${encodedPayload}.${signPayload(encodedPayload, secret)}`, + expiresAt, + }; + }); + + const verifyUploadToken = Effect.fn("VoiceTranscription.verifyUploadToken")(function* ( + token: string, + ) { + const [encodedPayload, signature, unexpectedSegment] = token.split("."); + if (!encodedPayload || !signature || unexpectedSegment !== undefined) { + return Option.none(); + } + const secret = yield* signingSecret; + if (!timingSafeEqualBase64Url(signature, signPayload(encodedPayload, secret))) { + return Option.none(); + } + const claims = Option.flatMap( + Option.liftThrowable(base64UrlDecodeUtf8)(encodedPayload), + decodeClaims, + ); + const nowMs = yield* Clock.currentTimeMillis; + if (Option.isNone(claims) || claims.value.expiresAt <= nowMs) return Option.none(); + const firstUse = yield* Ref.modify(consumedSignatures, (consumed) => { + const live = new Map([...consumed].filter(([, expiresAt]) => expiresAt > nowMs)); + if (live.has(signature)) return [false, live]; + live.set(signature, claims.value.expiresAt); + return [true, live]; + }); + return firstUse ? claims : Option.none(); + }); + + const transcribe = Effect.fn("VoiceTranscription.transcribe")(function* ( + claims: VoiceTranscriptionClaims, + audio: Uint8Array, + ) { + if (audio.byteLength !== claims.sizeBytes) { + return yield* new VoiceTranscriptionInvalidUploadError({ + expectedBytes: claims.sizeBytes, + receivedBytes: audio.byteLength, + }); + } + const endpoint = yield* loadEndpoint(claims.mimeType); + if (endpoint.kind === "apple") { + const { text } = yield* appleSpeech.transcribe({ audio, locale: endpoint.language }).pipe( + Effect.catchTags({ + AppleSpeechUnsupportedLocaleError: ({ locale }) => + new VoiceTranscriptionNotConfiguredError({ + reason: "unsupported-locale", + providerName: endpoint.name, + locale, + }), + }), + ); + return { text } satisfies VoiceTranscriptionResult; + } + const upstreamError = ( + fields: Omit[0], "host">, + ) => new VoiceTranscriptionUpstreamError({ host: endpoint.host, ...fields }); + + // Sent as bytes, not FormData. On a 401, Node 24's bundled undici re-encodes a FormData body + // in a detached task, which throws and exits the process when the fetch is then aborted. + const encodedForm = new Response( + endpoint.form({ + model: endpoint.model, + language: endpoint.language, + file: new Blob([audio], { type: claims.mimeType }), + fileName: `audio.${AUDIO_FILE_EXTENSIONS[claims.mimeType]}`, + }), + ); + const formBytes = new Uint8Array(yield* Effect.promise(() => encodedForm.arrayBuffer())); + const request = HttpClientRequest.post(endpoint.url).pipe( + HttpClientRequest.bodyUint8Array( + formBytes, + encodedForm.headers.get("content-type") ?? undefined, + ), + endpoint.apiKey ? HttpClientRequest.bearerToken(endpoint.apiKey) : identity, + HttpClientRequest.acceptJson, + ); + return yield* Effect.gen(function* () { + const response = yield* client + .execute(request) + .pipe(Effect.mapError((cause) => upstreamError({ stage: "request", cause }))); + if (response.status === 401 || response.status === 403) { + return yield* new VoiceTranscriptionCredentialsRejectedError({ + host: endpoint.host, + status: response.status, + cause: yield* readUpstreamCause(response, endpoint.apiKey), + }); + } + if (response.status < 200 || response.status >= 300) { + return yield* upstreamError({ + stage: "status", + status: response.status, + cause: yield* readUpstreamCause(response, endpoint.apiKey), + }); + } + const { text } = yield* readUpstreamText(response).pipe( + Effect.flatMap(decodeTranscript), + Effect.mapError((cause) => upstreamError({ stage: "response", cause })), + ); + return { text } satisfies VoiceTranscriptionResult; + }).pipe( + Effect.timeoutOrElse({ + duration: `${UPSTREAM_TIMEOUT_SECONDS} seconds`, + orElse: () => Effect.fail(upstreamError({ stage: "timeout" })), + }), + ); + }); + + return VoiceTranscription.of({ createUploadUrl, verifyUploadToken, transcribe }); +}); + +export const layer = Layer.effect(VoiceTranscription, make); diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index a9a028ec94bdf..4f35f5ed1a3a4 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -12,13 +12,16 @@ import { type ServerConfig, type ServerConfigStreamEvent, } from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as PubSub from "effect/PubSub"; import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; import { Headers } from "effect/http"; +import { ChildProcessSpawner } from "effect/process"; import { RpcGroup, RpcMessage, RpcServer } from "effect/rpc"; import * as SqlClient from "effect/sql/SqlClient"; @@ -49,6 +52,7 @@ import * as PairingGrantStore from "./auth/PairingGrantStore.ts"; import * as PortScanner from "./preview/PortScanner.ts"; import * as PreviewManager from "./preview/Manager.ts"; import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts"; +import * as ProcessRunner from "./processRunner.ts"; import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts"; import * as ProjectCloneTracker from "./project/ProjectCloneTracker.ts"; import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts"; @@ -84,6 +88,8 @@ import * as UsageLimitSources from "./usage/UsageLimitSources.ts"; import * as UsageService from "./usage/UsageService.ts"; import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts"; import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts"; +import * as AppleSpeechHelper from "./voiceTranscription/AppleSpeechHelper.ts"; +import * as VoiceTranscription from "./voiceTranscription/VoiceTranscription.ts"; import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts"; import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts"; import * as WorktreeSetupTracker from "./project/WorktreeSetupTracker.ts"; @@ -110,7 +116,7 @@ import { subscribeOrchestrationV2Shell, subscribeOrchestrationV2Thread, WS_RPC_SERVER_OPTIONS, - withLateEditorConfig, + withLateConfig, } from "./ws.ts"; const snapshotConfig = (fields: Partial) => @@ -125,7 +131,7 @@ const settingsUpdated = (settings: object): ServerConfigStreamEvent => ({ it.effect("resends late editors without rolling back updates already sent", () => Effect.gen(function* () { const settingsSent = yield* Deferred.make(); - const events = yield* withLateEditorConfig( + const events = yield* withLateConfig( snapshotConfig({ settings: { enableProviderUpdateChecks: true } as never }), Stream.make(settingsUpdated({ enableProviderUpdateChecks: false })), { @@ -133,6 +139,7 @@ it.effect("resends late editors without rolling back updates already sent", () = resolveFileManagerRevealKind: () => Deferred.await(settingsSent).pipe(Effect.as("file-explorer" as const)), }, + Stream.empty, ).pipe( Stream.tap((event) => event.type === "settingsUpdated" ? Deferred.succeed(settingsSent, undefined) : Effect.void, @@ -154,13 +161,14 @@ it.effect("resends late editors without rolling back updates already sent", () = it.effect("resends a file manager reveal kind that missed the snapshot", () => Effect.gen(function* () { - const events = yield* withLateEditorConfig( + const events = yield* withLateConfig( snapshotConfig({ availableEditors: ["file-manager"] }), Stream.empty, { resolveAvailableEditors: () => Effect.succeed(["file-manager"]), resolveFileManagerRevealKind: () => Effect.succeed("file-explorer"), }, + Stream.empty, ).pipe(Stream.runCollect); const [late] = Array.from(events); @@ -352,6 +360,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(UsageService.UsageService)({}), Layer.mock(VcsProvisioningService.VcsProvisioningService)({}), Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({}), + Layer.mock(VoiceTranscription.VoiceTranscription)({}), Layer.mock(WorkspaceEntries.WorkspaceEntries)({}), Layer.mock(WorkspaceFileSystem.WorkspaceFileSystem)({}), Layer.mock(WorktreeSetupTracker.WorktreeSetupTracker)({}), @@ -370,6 +379,80 @@ const layerConfigSources = Layer.mergeAll( Layer.provideMerge(NodeServices.layer), ); +const layerStaticConfigRpcServices = Layer.mergeAll( + layerUnusedConfigRpcServices, + Layer.mock(ProviderRegistry.ProviderRegistry)({ + getProviders: Effect.succeed([]), + streamChanges: Stream.never, + }), + Layer.mock(UsageLimitSources.UsageLimitSources)({ streamChanges: Stream.make([]) }), + Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({ + resolveTargets: () => Effect.succeed([]), + }), + Layer.mock(DirectEndpoints.DirectEndpoints)({ resolve: () => Effect.succeed([]) }), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + scratchRoot: Effect.succeedNone, + namedProjectsRoot: process.cwd(), + }), + Layer.mock(EnvironmentAuth.EnvironmentAuth)({ + getDescriptor: () => + Effect.succeed({ + policy: "loopback-browser", + bootstrapMethods: [], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "config-test-session", + }), + }), +); + +const serveConfigRpc = (configRpcServices: Layer.Layer) => + Effect.gen(function* () { + const responses = yield* Queue.unbounded(); + const server = yield* RpcServer.makeNoSerialization(RpcGroup.make(WsSubscribeServerConfigRpc), { + ...WS_RPC_SERVER_OPTIONS, + onFromServer: (response) => + response._tag === "Chunk" + ? Effect.forEach(response.values, (event) => Queue.offer(responses, event), { + discard: true, + }) + : Effect.void, + }).pipe( + Effect.provide( + layerWsRpc( + { + sessionId: AuthSessionId.make("config-test"), + subject: "config-test", + method: "browser-session-cookie", + scopes: [], + }, + {}, + {}, + yield* PreviewAutomationBroker.PreviewAutomationBroker, + yield* ServerBrowser.ServerBrowser, + ).pipe(Layer.provide(configRpcServices)), + ), + ); + const requestId = RpcMessage.RequestId("config"); + return { + responses, + subscribe: server.write(0, { + _tag: "Request", + id: requestId, + tag: WS_METHODS.subscribeServerConfig, + payload: {}, + headers: Headers.empty, + }), + acknowledge: server.write(0, { _tag: "Ack", requestId }), + unsubscribe: server.write(0, { _tag: "Interrupt", requestId, interruptors: [] }), + }; + }); + +const layerConfigRpcTest = Layer.mergeAll( + Layer.fresh(layerConfigSources), + Layer.mock(PreviewAutomationBroker.PreviewAutomationBroker)({}), + Layer.mock(ServerBrowser.ServerBrowser)({}), +); + it.effect( "preserves settings during discovery and keybindings during snapshot ACK at the config RPC boundary", () => @@ -387,102 +470,47 @@ it.effect( const initialKeybindings = (yield* keybindings.getSnapshot).keybindings; const discoveryStarted = yield* Deferred.make(); const finishDiscovery = yield* Deferred.make(); - const responses = yield* Queue.unbounded(); - const configRpcServices = Layer.mergeAll( - layerUnusedConfigRpcServices, - Layer.mock(ExternalLauncher.ExternalLauncher)({ - resolveAvailableEditors: () => - Deferred.succeed(discoveryStarted, undefined).pipe( - Effect.andThen(Deferred.await(finishDiscovery)), - Effect.as([]), - ), - resolveFileManagerRevealKind: () => Effect.succeed(undefined), - }), - Layer.mock(ProviderRegistry.ProviderRegistry)({ - getProviders: Effect.succeed([]), - streamChanges: Stream.never, - }), - Layer.mock(UsageLimitSources.UsageLimitSources)({ streamChanges: Stream.make([]) }), - Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({ - resolveTargets: () => Effect.succeed([]), - }), - Layer.mock(DirectEndpoints.DirectEndpoints)({ resolve: () => Effect.succeed([]) }), - Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ - scratchRoot: Effect.succeedNone, - namedProjectsRoot: process.cwd(), - }), - Layer.mock(ServerEnvironment.ServerEnvironment)({ - getDescriptor: Effect.succeed({ - environmentId: EnvironmentId.make("config-test"), - label: "Config test", - platform: { os: "linux", arch: "x64" }, - serverVersion: "0.0.0", - capabilities: { repositoryIdentity: false }, + const config = yield* serveConfigRpc( + Layer.mergeAll( + layerStaticConfigRpcServices, + Layer.mock(ExternalLauncher.ExternalLauncher)({ + resolveAvailableEditors: () => + Deferred.succeed(discoveryStarted, undefined).pipe( + Effect.andThen(Deferred.await(finishDiscovery)), + Effect.as([]), + ), + resolveFileManagerRevealKind: () => Effect.succeed(undefined), }), - }), - Layer.mock(EnvironmentAuth.EnvironmentAuth)({ - getDescriptor: () => - Effect.succeed({ - policy: "loopback-browser", - bootstrapMethods: [], - sessionMethods: ["browser-session-cookie"], - sessionCookieName: "config-test-session", + Layer.mock(ServerEnvironment.ServerEnvironment)({ + getDescriptor: Effect.succeed({ + environmentId: EnvironmentId.make("config-test"), + label: "Config test", + platform: { os: "linux", arch: "x64" }, + serverVersion: "0.0.0", + capabilities: { repositoryIdentity: false }, }), - }), - // Signal subscription on either accessor so the test also fails, rather - // than hangs, against a handler that subscribes after the snapshot. - Layer.succeed(Keybindings.Keybindings, { - ...keybindings, - streamChanges: Stream.unwrap(keybindingsChanges), - subscribeChanges: keybindingsChanges, - }), - Layer.succeed(ServerSettings.ServerSettingsService, { - ...settings, - streamChanges: Stream.unwrap(settingsChanges), - subscribeChanges: settingsChanges, - }), - ); - const server = yield* RpcServer.makeNoSerialization( - RpcGroup.make(WsSubscribeServerConfigRpc), - { - ...WS_RPC_SERVER_OPTIONS, - onFromServer: (response) => - response._tag === "Chunk" - ? Effect.forEach(response.values, (event) => Queue.offer(responses, event), { - discard: true, - }) - : Effect.void, - }, - ).pipe( - Effect.provide( - layerWsRpc( - { - sessionId: AuthSessionId.make("config-test"), - subject: "config-test", - method: "browser-session-cookie", - scopes: [], - }, - {}, - {}, - yield* PreviewAutomationBroker.PreviewAutomationBroker, - yield* ServerBrowser.ServerBrowser, - ).pipe(Layer.provide(configRpcServices)), + streamDescriptorChanges: Stream.never, + }), + // Signal subscription on either accessor so the test also fails, rather + // than hangs, against a handler that subscribes after the snapshot. + Layer.succeed(Keybindings.Keybindings, { + ...keybindings, + streamChanges: Stream.unwrap(keybindingsChanges), + subscribeChanges: keybindingsChanges, + }), + Layer.succeed(ServerSettings.ServerSettingsService, { + ...settings, + streamChanges: Stream.unwrap(settingsChanges), + subscribeChanges: settingsChanges, + }), ), ); - const requestId = RpcMessage.RequestId("config"); - const acknowledge = server.write(0, { _tag: "Ack", requestId }); - yield* server.write(0, { - _tag: "Request", - id: requestId, - tag: WS_METHODS.subscribeServerConfig, - payload: {}, - headers: Headers.empty, - }); + yield* config.subscribe; yield* Deferred.await(discoveryStarted); const duringDiscovery = yield* settings.updateSettings({ defaultAutoPull: true }); yield* Deferred.succeed(finishDiscovery, undefined); - const snapshot = yield* Queue.take(responses); + const snapshot = yield* Queue.take(config.responses); assert.equal(snapshot.type, "snapshot"); if (snapshot.type !== "snapshot") return yield* Effect.die("Missing initial snapshot"); assert.isFalse(snapshot.config.settings.defaultAutoPull); @@ -491,7 +519,7 @@ it.effect( key: "mod+alt+y", command: "terminal.toggle", }); - yield* acknowledge; + yield* config.acknowledge; yield* Deferred.await(keybindingsSubscribed); yield* Deferred.await(settingsSubscribed); @@ -507,7 +535,7 @@ it.effect( const expectedKeybindings = [duringAck, latestKeybindings]; // The two sources can interleave, but each must retain its own publication order. for (let i = 0; i < 4; i++) { - const event = yield* Queue.take(responses); + const event = yield* Queue.take(config.responses); if (event.type === "settingsUpdated") { assert.deepEqual(event.payload.settings, expectedSettings.shift()); } else { @@ -517,21 +545,73 @@ it.effect( assert.deepEqual(event.payload.keybindings, expectedKeybindings.shift()); assert.deepEqual(event.payload.issues, []); } - yield* acknowledge; + yield* config.acknowledge; } assert.isEmpty(expectedSettings); assert.isEmpty(expectedKeybindings); - yield* server.write(0, { _tag: "Interrupt", requestId, interruptors: [] }); - }).pipe( - Effect.provide( + yield* config.unsubscribe; + }).pipe(Effect.provide(layerConfigRpcTest), Effect.scoped), +); + +it.effect( + "re-sends the config snapshot when the Apple speech probe answers after subscribing", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const helperDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-config-apple-speech-test-", + }); + const helperPath = `${helperDir}/t3-apple-speech`; + yield* fileSystem.writeFileString(helperPath, "helper"); + const probeAnswer = yield* Deferred.make(); + const appleSpeech = yield* AppleSpeechHelper.make.pipe( + Effect.provideService( + ProcessRunner.ProcessRunner, + ProcessRunner.ProcessRunner.of({ + run: () => + Deferred.await(probeAnswer).pipe( + Effect.as({ + stdout: '{"available":true}', + stderr: "", + code: ChildProcessSpawner.ExitCode(0), + timedOut: false, + stdoutTruncated: false, + stderrTruncated: false, + stdoutInvalidUtf8: false, + stderrInvalidUtf8: false, + }), + ), + }), + ), + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService(HostProcess.Environment, { T3CODE_APPLE_SPEECH_PATH: helperPath }), + Effect.provideService(AppleSpeechHelper.AppleSpeechHostKernelRelease, "25.0.0"), + ); + const config = yield* serveConfigRpc( Layer.mergeAll( - Layer.fresh(layerConfigSources), - Layer.mock(PreviewAutomationBroker.PreviewAutomationBroker)({}), - Layer.mock(ServerBrowser.ServerBrowser)({}), + layerStaticConfigRpcServices, + Layer.mock(ExternalLauncher.ExternalLauncher)({ + resolveAvailableEditors: () => Effect.succeed([]), + resolveFileManagerRevealKind: () => Effect.succeed(undefined), + }), + ServerEnvironment.layer.pipe( + Layer.provide(Layer.succeed(AppleSpeechHelper.AppleSpeechHelper, appleSpeech)), + Layer.provide(ServerSecretStore.layer), + ), ), - ), - Effect.scoped, - ), + ); + yield* config.subscribe; + const initial = yield* Queue.take(config.responses); + if (initial.type !== "snapshot") return yield* Effect.die("Missing initial snapshot"); + assert.notEqual(initial.config.environment.capabilities.appleOnDeviceTranscription, true); + yield* config.acknowledge; + + yield* Deferred.succeed(probeAnswer, undefined); + const update = yield* Queue.take(config.responses); + if (update.type !== "snapshot") return yield* Effect.die(`Unexpected ${update.type} event`); + assert.isTrue(update.config.environment.capabilities.appleOnDeviceTranscription); + yield* config.unsubscribe; + }).pipe(Effect.provide(layerConfigRpcTest), Effect.scoped), ); // Compaction keeps the oldest and newest event per message, so a cursor older diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 763365ceeddc1..12d2b4db10e4b 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -255,6 +255,7 @@ import { import * as AgentSessionScanner from "./project/AgentSessionScanner.ts"; import * as AgentSessionImporter from "./project/AgentSessionImporter.ts"; import * as UsageLimitSources from "./usage/UsageLimitSources.ts"; +import * as VoiceTranscription from "./voiceTranscription/VoiceTranscription.ts"; const CONFIG_DISCOVERY_TIMEOUT = Duration.seconds(5); const isProviderUploadFeedbackError = Schema.is(ProviderUploadFeedbackError); @@ -299,10 +300,13 @@ const resolveEditorConfig = Effect.fn("ws.resolveEditorConfig")(function* }; }); -export const withLateEditorConfig = ( +// Late config goes out as a whole snapshot, not a new event type, because shipped +// clients decode this stream against their own event union. +export const withLateConfig = ( config: ClientServerConfig, liveUpdates: Stream.Stream, launcher: EditorDiscovery, + environmentChanges: Stream.Stream, ) => { const lateEditorConfig = Stream.fromEffect(launcher.resolveAvailableEditors()).pipe( Stream.filter( @@ -322,8 +326,11 @@ export const withLateEditorConfig = ( ), Stream.map((editorConfig) => ({ type: "editorsResolved" as const, editorConfig })), ); + const environmentUpdates = environmentChanges.pipe( + Stream.map((environment) => ({ type: "environmentChanged" as const, environment })), + ); - return Stream.merge(liveUpdates, lateEditorConfig).pipe( + return Stream.merge(liveUpdates, Stream.merge(lateEditorConfig, environmentUpdates)).pipe( Stream.mapAccum( (): ClientServerConfig => config, (current, event): readonly [ClientServerConfig, ReadonlyArray] => { @@ -338,6 +345,13 @@ export const withLateEditorConfig = ( const next = { ...rest, ...event.editorConfig }; return [next, [{ version: 1, type: "snapshot", config: next }]]; } + case "environmentChanged": { + if (JSON.stringify(event.environment) === JSON.stringify(current.environment)) { + return [current, []]; + } + const next = { ...current, environment: event.environment }; + return [next, [{ version: 1, type: "snapshot", config: next }]]; + } case "keybindingsUpdated": return [{ ...current, ...event.payload }, [event]]; case "providerStatuses": @@ -1286,6 +1300,7 @@ export const layerWsRpc = ( const serverSettings = yield* ServerSettings.ServerSettingsService; const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup; const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; + const voiceTranscription = yield* VoiceTranscription.VoiceTranscription; const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem; const serverEnvironment = yield* ServerEnvironment.ServerEnvironment; const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy; @@ -2709,6 +2724,8 @@ export const layerWsRpc = ( ), [WS_METHODS.attachmentsCreateUploadUrl]: (input) => issueAttachmentUploadUrl(input), [WS_METHODS.attachmentsDelete]: (input) => deletePendingAttachment(input.attachmentId), + [WS_METHODS.voiceCreateTranscriptionUrl]: (input) => + voiceTranscription.createUploadUrl(input), [WS_METHODS.agentSessionsScan]: () => agentSessionScanner.scan, [WS_METHODS.agentSessionsImport]: (input) => agentSessionImporter.importRecentAgentThreads(input), @@ -3051,7 +3068,12 @@ export const layerWsRpc = ( return Stream.concat( rpcInitialItems([{ version: 1 as const, type: "snapshot" as const, config }]), - withLateEditorConfig(config, liveUpdates, externalLauncher), + withLateConfig( + config, + liveUpdates, + externalLauncher, + serverEnvironment.streamDescriptorChanges, + ), ); }), ), diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 1f9eb813a455f..cb41ea00652c5 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -5869,6 +5869,10 @@ export default function ChatView(props: ChatViewProps) { "composer.effort": openComposerControl("composer.effort"), "composer.mode": openComposerControl("composer.mode"), "composer.workspace": openComposerControl("composer.workspace"), + "composer.toggleDictation": ({ event }) => { + if (event.repeat) return; + return composerRef.current?.toggleDictation() === true; + }, "composer.cycleHost": ({ event }) => { if (!canChangeEnvironment) return false; if (event.repeat) return; diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 055c2d76c4fd3..d2d309760414b 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -67,6 +67,7 @@ import { MessageSquareDashedIcon, LinkIcon, MessageSquareIcon, + MicIcon, MonitorIcon, MoonIcon, PaletteIcon, @@ -121,6 +122,7 @@ import { useEnvironmentQuery } from "../state/query"; import { serverEnvironment } from "../state/server"; import { threadEnvironment } from "../state/threads"; import { readEnvironmentScope, useEnvironmentScope } from "~/state/session"; +import { voiceTranscriptionEnvironment } from "~/state/voiceTranscription"; import { sourceControlEnvironment } from "../state/sourceControl"; import { useAtomCommand } from "../state/use-atom-command"; import { useAtomQueryRunner } from "../state/use-atom-query-runner"; @@ -240,7 +242,11 @@ import { Kbd, KbdGroup } from "./ui/kbd"; import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select"; import { stackedThreadToast, toastManager } from "./ui/toast"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; -import { ComposerHandleContext, useComposerHandleContext } from "../composerHandleContext"; +import { + ComposerHandleContext, + useComposerHandleContext, + type ComposerHandleRef, +} from "../composerHandleContext"; import type { ChatComposerHandle } from "./chat/ChatComposer"; import { getProjectOrderKey } from "../logicalProject"; import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore"; @@ -703,6 +709,15 @@ function CommandPaletteDialog(props: { ); } +function toggleComposerDictation(composerHandleRef: ComposerHandleRef | null): void { + if (composerHandleRef?.current?.toggleDictation() === true) return; + toastManager.add({ + type: "warning", + title: "Voice input is not available right now", + description: "The composer is not accepting text at the moment.", + }); +} + function OpenCommandPaletteDialog(props: { readonly openIntent: CommandPaletteOpenIntent | null; readonly setOpen: (open: boolean) => void; @@ -1006,6 +1021,16 @@ function OpenCommandPaletteDialog(props: { const currentProjectEnvironmentId = activeThread?.environmentId ?? activeDraftThread?.environmentId ?? null; const currentProjectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? null; + const canCreateTranscriptionUrl = useAtomValue( + voiceTranscriptionEnvironment.createTranscriptionUrl.permissionAtom( + currentProjectEnvironmentId, + ), + ); + const voiceInputAvailable = + canCreateTranscriptionUrl && + environments.find((environment) => environment.environmentId === currentProjectEnvironmentId) + ?.serverConfig?.settings.voiceTranscription.enabled === true; + const composerHandleRef = useComposerHandleContext(); const scratchTargetEnvironmentId = scratchEnvironmentId( currentProjectEnvironmentId ?? primaryEnvironmentId, ); @@ -1648,6 +1673,18 @@ function OpenCommandPaletteDialog(props: { }); } + if (voiceInputAvailable) { + actionItems.push({ + kind: "action", + value: "voice-input", + title: "Voice input", + searchTerms: ["dictate", "dictation", "microphone", "speech", "transcribe", "voice"], + icon: , + shortcutCommand: "composer.toggleDictation", + run: async () => toggleComposerDictation(composerHandleRef), + }); + } + const promptLinkTarget = paletteRouteTarget ? paletteRouteTarget.kind === "server" ? paletteRouteTarget.threadRef diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index f600b831c53e6..87c0454d88192 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -1,3 +1,4 @@ +import { useAtomValue } from "@effect/atom-react"; import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills"; import { useComposerTypingGuard } from "./useComposerTypingGuard"; import { insertAttachmentReferencesForDraft } from "./composerAttachmentReferences"; @@ -5,6 +6,7 @@ import { DESKTOP_PASTE_AS_TEXT_EVENT } from "../../lib/desktopPasteAsText"; import { runtimeModeConfig, runtimeModeOptions as runtimeModes } from "./runtimeModeConfig"; import { isLocalEnvironmentDisabled } from "../../localEnvironment"; import { usePrimaryEnvironmentId } from "../../state/environments"; +import { voiceTranscriptionEnvironment } from "~/state/voiceTranscription"; import { useRightPanelStore } from "~/rightPanelStore"; import { AttachmentFilePreview } from "../files/AttachmentFilePreview"; import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog"; @@ -1066,6 +1068,9 @@ import { } from "lucide-react"; import { proposedPlanTitle } from "@t3tools/shared/proposedPlanText"; import { hasProviderSetup } from "./ProviderStatusBanner"; +import { voiceInputBannerItem } from "./ComposerVoiceInputBanner"; +import { ComposerVoiceInputControl } from "./ComposerVoiceInputControl"; +import { useComposerVoiceInput } from "./useComposerVoiceInput"; import { applyProviderInstanceSettings, deriveProviderInstanceEntries, @@ -1458,6 +1463,7 @@ export interface ChatComposerHandle { isModelPickerOpen: () => boolean; isCaretAtStart: () => boolean; compactContext: () => void; + toggleDictation: () => boolean; readSnapshot: () => { value: string; cursor: number; @@ -1893,6 +1899,16 @@ function useComposerImageGroups( const NO_PROVIDER_SKILLS: ServerProvider["skills"] = []; const NO_PROVIDER_SLASH_COMMANDS: ServerProvider["slashCommands"] = []; +/** The editor's selection indexes only the text it was read from. */ +function editorSelectionFor( + editor: ComposerPromptEditorHandle | null, + text: string, +): { start: number; end: number } { + return editor && editor.readSnapshot().value === text + ? editor.readSelectionRange() + : { start: text.length, end: text.length }; +} + export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) { const { composerDraftTarget, @@ -2078,6 +2094,43 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }); const questionPreparations = useQuestionAttachmentPreparation((state) => state.counts); const prompt = composerDraft.prompt; + const composerEditorRef = useRef(null); + const composerFormRef = useRef(null); + // A pending question swaps the composer's text for its answer, so a recording that + // started on the draft must not land there. + const voiceOwnerKey = + pendingUserInputs[0] && activePendingProgress?.activeQuestion + ? `${composerDraftTargetKey}:${pendingUserInputs[0].requestId}:${activePendingProgress.activeQuestion.id}` + : composerDraftTargetKey; + const readVoiceDraftStable = useStableCallback(() => { + const text = promptRef.current; + return { + ownerKey: voiceOwnerKey, + text, + selection: editorSelectionFor(composerEditorRef.current, text), + }; + }); + // The React Compiler rejects a closure over applyPromptReplacement, a const declared + // after this hook, so the layout effect below that declaration fills in the ref. + const voiceCommitRef = useRef< + ((text: string, selection: { readonly start: number; readonly end: number }) => boolean) | null + >(null); + const commitVoiceDraftStable = useStableCallback( + (text: string, selection: { readonly start: number; readonly end: number }) => + voiceCommitRef.current?.(text, selection) ?? false, + ); + const canCreateTranscriptionUrl = useAtomValue( + voiceTranscriptionEnvironment.createTranscriptionUrl.permissionAtom(environmentId), + ); + const voiceInput = useComposerVoiceInput({ + environmentId, + ownerKey: voiceOwnerKey, + language: settings.voiceTranscription.language, + draftText: prompt, + composerRef: composerFormRef, + readDraft: readVoiceDraftStable, + commitDraft: commitVoiceDraftStable, + }); const composerImages = attachmentDraft.images; const composerFiles = attachmentDraft.files; const inlineFileIdSet = (() => { @@ -2356,6 +2409,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ); const sendDisabledReason = externalSendDisabledReason ?? + (voiceInput.busy ? "Finish voice input first." : null) ?? (multipleModelSelections?.length === 0 ? "Select at least one model." : null) ?? (activePendingProgress ? attachmentBlockReason @@ -2480,14 +2534,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) !hasMultilinePrompt && pendingUserInputs.length === 0; - const composerEditorRef = useRef(null); const pasteAsTextShortcutUntilRef = useRef(0); const pastedTextFileNamesRef = useRef<{ targetKey: string; names: Set }>({ targetKey: "", names: new Set(), }); const attachmentInputRef = useRef(null); - const composerFormRef = useRef(null); const composerSurfaceRef = useRef(null); const providerInputRejectedRef = useRef(false); const composerSelectLockRef = useRef(false); @@ -2843,7 +2895,16 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) (!activePendingProgress || (supportsQuestionAttachments && activePendingProgress.activeQuestion?.allowCustomAnswer !== false)); + const showComposerVoiceAction = + settings.voiceTranscription.enabled && + canCreateTranscriptionUrl && + environmentUnavailable === null && + !isComposerApprovalState && + !projectSelectionRequired && + !isChoiceOnlyPendingQuestion && + !activePendingIsResponding; const composerFooterHasWideActions = showPlanFollowUpPrompt || activePendingProgress !== null; + const composerFooterHasActiveVoiceControl = voiceInput.busy; const isComposerMenuLoading = (composerTriggerKind === "path" && pathTriggerQuery.length > 0 && workspaceEntries.isPending) || @@ -3480,11 +3541,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const composerFormWidth = measureComposerFormWidth(); const footerCompact = shouldUseCompactComposerFooter(composerFormWidth, { hasWideActions: composerFooterHasWideActions, + hasActiveVoiceControl: composerFooterHasActiveVoiceControl, }); const primaryActionsCompact = footerCompact && shouldUseCompactComposerPrimaryActions(composerFormWidth, { hasWideActions: composerFooterHasWideActions, + hasActiveVoiceControl: composerFooterHasActiveVoiceControl, }); return { primaryActionsCompact, @@ -3506,7 +3569,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) previous === nextCompactness.footerCompact ? previous : nextCompactness.footerCompact, ); }); - }, [composerFooterHasWideActions]); + }, [composerFooterHasWideActions, composerFooterHasActiveVoiceControl]); useEffect(() => { let cancelled = false; @@ -3784,6 +3847,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) return true; }; const applyPromptReplacementStable = useStableCallback(applyPromptReplacement); + useLayoutEffect(() => { + voiceCommitRef.current = (text, selection) => + applyPromptReplacement(0, promptRef.current.length, text, { + expandedCursorAfterReplace: selection.start, + }); + }); const readComposerSnapshot = (): { value: string; @@ -5334,9 +5403,16 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) content: activityStackContent, } : null; - const bannerStackItems = activityStackItem - ? [activityStackItem, ...props.bannerItems] - : props.bannerItems; + const voiceBannerItem = voiceInputBannerItem({ + state: voiceInput.state, + onRetry: voiceInput.retry, + onDismiss: voiceInput.cancel, + }); + const bannerStackItems = [ + ...(voiceBannerItem ? [voiceBannerItem] : []), + ...(activityStackItem ? [activityStackItem] : []), + ...props.bannerItems, + ]; const [tasksDrawerThreadId, setTasksDrawerThreadId] = useState(activeThreadId); if ( isTasksDrawerOpen && @@ -6117,6 +6193,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) focusAt: (cursor: number) => { composerEditorRef.current?.focusAt(cursor); }, + toggleDictation: () => { + if (!showComposerVoiceAction && !voiceInput.busy) return false; + voiceInput.toggle(); + return true; + }, restoreAfterTimelineReachedEnd, collapseForTimelineScrollKey: (key) => { const scrollNode = getTimelineScrollableNode(); @@ -6394,6 +6475,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) getTimelineScrollableNode, isTimelineAtLogicalEnd, setIsComposerScrollCollapsed, + showComposerVoiceAction, + voiceInput.busy, + voiceInput.toggle, ], ); @@ -7207,7 +7291,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) isComposerApprovalState || projectSelectionRequired || isChoiceOnlyPendingQuestion || - activePendingIsResponding + activePendingIsResponding || + voiceInput.busy } /> @@ -7322,6 +7407,20 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ) : null} + {showComposerVoiceAction || voiceInput.busy ? ( + + ) : null} (element as HTMLElement).click()); +} + +describe("voiceInputBannerItem", () => { + it("explains a failed System Settings launch instead of leaving a rejected promise", async () => { + using add = vi.spyOn(toastManager, "add").mockImplementation(() => "toast"); + const item = voiceInputBannerItem({ + state: denied, + errorContext: { secureContext: true, permissionHost: "macos" }, + openSettings: async () => { + throw new Error("Unable to open System Settings."); + }, + onRetry: () => {}, + onDismiss: () => {}, + }); + await using screen = await render(); + expect(screen.getByRole("alert").element().textContent).toContain("System Settings"); + + await click(screen.getByRole("button", { name: "Open settings" }).element()); + expect(add).toHaveBeenCalledWith( + expect.objectContaining({ type: "error", description: "Unable to open System Settings." }), + ); + }); + + it.each([ + ["Open settings", denied, "macos"], + [ + "Retry", + { phase: "error", error: "Upload failed.", errorAction: "retry-transcription" }, + "browser", + ], + ] as const)("leaves focus in the composer when %s is pressed", async (name, state, host) => { + const item = voiceInputBannerItem({ + state, + errorContext: { secureContext: true, permissionHost: host }, + openSettings: async () => {}, + onRetry: () => {}, + onDismiss: () => {}, + }); + await using screen = await render( + <> +