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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions apps/desktop/src/window/DesktopWindow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,10 @@ function makeFakeBrowserWindow() {
reload: vi.fn(),
replaceMisspelling: vi.fn(),
send: vi.fn(),
session: {
setPermissionCheckHandler: vi.fn(),
setPermissionRequestHandler: vi.fn(),
},
setBackgroundThrottling: vi.fn(),
setWindowOpenHandler: vi.fn(),
};
Expand Down
5 changes: 5 additions & 0 deletions apps/desktop/src/window/DesktopWindow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import * as PreviewManager from "../preview/Manager.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopClientSettings from "../settings/DesktopClientSettings.ts";
import * as ElectronApp from "../electron/ElectronApp.ts";
import { installMainWindowPermissionHandlers } from "./MainWindowPermissions.ts";
import { makeQuitShortcutHandler } from "./QuitHold.ts";

const TITLEBAR_HEIGHT = 40;
Expand Down Expand Up @@ -423,6 +424,10 @@ export const make = Effect.gen(function* () {
if (environment.platform === "darwin") {
window.setAutoHideCursor(false);
}
installMainWindowPermissionHandlers(window.webContents.session, {
appUrl: applicationUrl,
platform: environment.platform,
});
let boundsPersistFiber: Fiber.Fiber<void, never> | undefined;
let pendingBoundsPersistFiber: Fiber.Fiber<void, never> | undefined;
let boundsPersistenceEnabled = persistedBounds === null || restoredPersistedBounds;
Expand Down
46 changes: 46 additions & 0 deletions apps/desktop/src/window/MainWindowPermissions.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { describe, expect, it } from "vite-plus/test";

import { decideMainWindowMediaRequest, isAppUrl } from "./MainWindowPermissions.ts";

const APP_URL = "t3code://app/";

function decide(overrides: Partial<Parameters<typeof decideMainWindowMediaRequest>[0]> = {}) {
return decideMainWindowMediaRequest({
requestingUrl: "t3code://app/threads/abc",
appUrl: APP_URL,
mediaTypes: ["audio"],
platform: "darwin",
microphoneStatus: () => "granted",
...overrides,
});
}

describe("isAppUrl", () => {
it("matches the app shell and nothing that merely shares its prefix", () => {
expect(isAppUrl("t3code://app", APP_URL)).toBe(true);
expect(isAppUrl("t3code://app/settings", APP_URL)).toBe(true);
expect(isAppUrl("t3code://application/", APP_URL)).toBe(false);
expect(isAppUrl("https://example.com/", APP_URL)).toBe(false);
expect(isAppUrl(undefined, APP_URL)).toBe(false);
});
});

describe("decideMainWindowMediaRequest", () => {
it("denies media to frames outside the app shell", () => {
expect(decide({ requestingUrl: "https://example.com/embed" })).toBe("deny");
});

it("asks macOS for the microphone until the user has granted it", () => {
expect(decide({ microphoneStatus: () => "not-determined" })).toBe("ask-microphone");
expect(decide({ microphoneStatus: () => "denied" })).toBe("ask-microphone");
expect(decide()).toBe("grant");
});

it("grants the microphone directly off macOS", () => {
expect(decide({ platform: "win32", microphoneStatus: () => "unknown" })).toBe("grant");
});

it("keeps granting video-only capture such as preview tab recording", () => {
expect(decide({ mediaTypes: ["video"], microphoneStatus: () => "denied" })).toBe("grant");
});
});
63 changes: 63 additions & 0 deletions apps/desktop/src/window/MainWindowPermissions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import * as Electron from "electron";

export type MediaPermissionDecision = "grant" | "deny" | "ask-microphone";

/** Whether `url` belongs to the app shell served from `appUrl` (e.g. `t3code://app/`). */
export function isAppUrl(url: string | undefined, appUrl: string): boolean {
if (!url) return false;
// Custom schemes have an opaque WHATWG origin, so compare the serialized prefix.
const appOrigin = appUrl.endsWith("/") ? appUrl.slice(0, -1) : appUrl;
return url === appOrigin || url.startsWith(`${appOrigin}/`);
}

/**
* Media requests come from the app shell (voice conversations use the
* microphone; preview tab recording routes `getDisplayMedia` through the same
* permission). Frames from any other origin never get media. On macOS the
* microphone also needs the system's consent, asked for on first use.
*/
export function decideMainWindowMediaRequest(input: {
readonly requestingUrl: string;
readonly appUrl: string;
readonly mediaTypes: ReadonlyArray<"audio" | "video">;
readonly platform: NodeJS.Platform;
readonly microphoneStatus: () => string;
}): MediaPermissionDecision {
if (!isAppUrl(input.requestingUrl, input.appUrl)) return "deny";
if (!input.mediaTypes.includes("audio") || input.platform !== "darwin") return "grant";
return input.microphoneStatus() === "granted" ? "grant" : "ask-microphone";
}

/**
* Installs the main window session's permission handlers. Only `media` is
* decided here; every other permission keeps Electron's default of allowing
* it, which is what this session did before it had handlers.
*/
export function installMainWindowPermissionHandlers(
session: Electron.Session,
options: { readonly appUrl: string; readonly platform: NodeJS.Platform },
): void {
session.setPermissionRequestHandler((_webContents, permission, callback, details) => {
if (permission !== "media") {
callback(true);
return;
}
const decision = decideMainWindowMediaRequest({
requestingUrl: details.requestingUrl,
appUrl: options.appUrl,
mediaTypes: "mediaTypes" in details ? (details.mediaTypes ?? []) : [],
platform: options.platform,
microphoneStatus: () => Electron.systemPreferences.getMediaAccessStatus("microphone"),
});
if (decision !== "ask-microphone") {
callback(decision === "grant");
return;
}
Electron.systemPreferences.askForMediaAccess("microphone").then(callback, () => {
callback(false);
});
});
session.setPermissionCheckHandler((_webContents, permission, requestingOrigin) =>
permission === "media" ? isAppUrl(requestingOrigin, options.appUrl) : true,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High window/MainWindowPermissions.ts:61

Trusted media checks return true, so Electron skips setPermissionRequestHandler and never calls askForMediaAccess("microphone"). On macOS, users with microphoneStatus() set to "not-determined" therefore receive no system consent prompt and voice capture remains unauthorized. Return false for media checks so the request handler can grant or deny the request and trigger the prompt.

-    permission === "media" ? isAppUrl(requestingOrigin, options.appUrl) : true,
+    permission === "media" ? false : true,
🤖 Copy this AI Prompt to have your agent fix this:
In file @apps/desktop/src/window/MainWindowPermissions.ts around line 61:

Trusted `media` checks return `true`, so Electron skips `setPermissionRequestHandler` and never calls `askForMediaAccess("microphone")`. On macOS, users with `microphoneStatus()` set to `"not-determined"` therefore receive no system consent prompt and voice capture remains unauthorized. Return `false` for `media` checks so the request handler can grant or deny the request and trigger the prompt.

);
}
22 changes: 18 additions & 4 deletions apps/mobile/app.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,10 @@ const sharingPlugin: NonNullable<ExpoConfig["plugins"]>[number] = [
},
];

const MICROPHONE_PERMISSION =
"Allow T3 Code to use your microphone for voice input and voice conversations.";
const CAMERA_PERMISSION = "Allow T3 Code to access your camera so you can scan pairing QR codes.";

// These aliases match the fonts' PostScript names on iOS. Register the same
// names on Android so React Native and the native composer use one set of
// family names without waiting for runtime font loading.
Expand Down Expand Up @@ -287,6 +291,8 @@ const config: ExpoConfig = {
foregroundImage: variant.assets.androidAdaptiveForeground,
monochromeImage: variant.assets.androidMonochromeIcon,
},
// react-native-webrtc's plugin requests overlay access for screen sharing, which voice does not use.
blockedPermissions: ["android.permission.SYSTEM_ALERT_WINDOW"],
// Opts into OnBackInvokedCallback-based back dispatch (Android 13+).
// JS back handling survives it via react-native's Android 16 shim plus
// withAndroidPredictiveBackCompat on Android 13-15.
Expand Down Expand Up @@ -357,22 +363,30 @@ const config: ExpoConfig = {
[
"expo-audio",
{
microphonePermission: "Allow T3 Code to use your microphone for voice input.",
recordAudioAndroid: false,
microphonePermission: MICROPHONE_PERMISSION,
recordAudioAndroid: true,
enableBackgroundPlayback: false,
enableBackgroundRecording: false,
},
],
// Voice conversations run over WebRTC. Pass both usage strings so its
// plugin cannot fall back to generic ones.
[
"@config-plugins/react-native-webrtc",
{ cameraPermission: CAMERA_PERMISSION, microphonePermission: MICROPHONE_PERMISSION },
],
[
"expo-camera",
{
cameraPermission: "Allow T3 Code to access your camera so you can scan pairing QR codes.",
cameraPermission: CAMERA_PERMISSION,
microphonePermission: false,
barcodeScannerEnabled: true,
recordAudioAndroid: false,
},
],
["expo-image-picker", { photosPermission: false, microphonePermission: false }],
// `microphonePermission: false` would block RECORD_AUDIO on Android for every
// package, including voice conversations, so share the app's usage string.
["expo-image-picker", { photosPermission: false, microphonePermission: MICROPHONE_PERMISSION }],
[
"expo-splash-screen",
{
Expand Down
2 changes: 2 additions & 0 deletions apps/mobile/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -121,13 +121,15 @@
"react-native-screens": "~4.26.0",
"react-native-shiki-engine": "^0.3.12",
"react-native-svg": "15.15.4",
"react-native-webrtc": "124.0.8",
"react-native-webview": "^13.16.1",
"react-native-worklets": "0.11.4",
"shiki": "4.2.0",
"tailwind-merge": "^3.5.0",
"uniwind": "1.11.0"
},
"devDependencies": {
"@config-plugins/react-native-webrtc": "15.0.2",
"@effect/vitest": "catalog:",
"@pierre/trees": "1.0.0-beta.4",
"@types/react": "~19.2.0",
Expand Down
4 changes: 4 additions & 0 deletions apps/mobile/src/components/AppSymbol.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ import IconLayoutSidebar from "@tabler/icons-react-native/IconLayoutSidebar";
import IconLayoutSidebarRight from "@tabler/icons-react-native/IconLayoutSidebarRight";
import IconLetterSpacing from "@tabler/icons-react-native/IconLetterSpacing";
import IconMicrophone from "@tabler/icons-react-native/IconMicrophone";
import IconMicrophoneOff from "@tabler/icons-react-native/IconMicrophoneOff";
import IconLink from "@tabler/icons-react-native/IconLink";
import IconListNumbers from "@tabler/icons-react-native/IconListNumbers";
import IconMenu2 from "@tabler/icons-react-native/IconMenu2";
Expand Down Expand Up @@ -107,6 +108,7 @@ import IconTypography from "@tabler/icons-react-native/IconTypography";
import IconUpload from "@tabler/icons-react-native/IconUpload";
import IconUserCircle from "@tabler/icons-react-native/IconUserCircle";
import IconUsers from "@tabler/icons-react-native/IconUsers";
import IconWaveSine from "@tabler/icons-react-native/IconWaveSine";
import IconWifiOff from "@tabler/icons-react-native/IconWifiOff";
import IconWorld from "@tabler/icons-react-native/IconWorld";
import IconX from "@tabler/icons-react-native/IconX";
Expand Down Expand Up @@ -188,6 +190,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = {
macstudio: IconDeviceDesktop,
magnifyingglass: IconSearch,
mic: IconMicrophone,
"mic.slash": IconMicrophoneOff,
paintbrush: IconPalette,
pencil: IconPencil,
"person.crop.circle": IconUserCircle,
Expand Down Expand Up @@ -224,6 +227,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = {
"textformat.size.smaller": IconTextDecrease,
"tray.and.arrow.up": IconUpload,
trash: IconTrash,
waveform: IconWaveSine,
"wifi.slash": IconWifiOff,
xmark: IconX,
"xmark.circle.fill": IconCircleXFilled,
Expand Down
36 changes: 36 additions & 0 deletions apps/mobile/src/features/threads/ThreadComposer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,9 @@ import {
} from "../voice-input/ComposerDictationControl";
import { useVoiceInputController } from "../voice-input/useVoiceInputController";
import { resolveVoiceComposerPresentation } from "../voice-input/voiceInputPresentation";
import { ComposerVoiceModeButton, ComposerVoiceStrip } from "../voice-mode/ComposerVoiceMode";
import { useVoiceModePhase, useVoiceModeThreadLifecycle } from "../voice-mode/useVoiceMode";
import { voiceMode, voiceModeSupported } from "../voice-mode/voiceMode";
import {
rememberModelOptions,
withRememberedModelOptions,
Expand Down Expand Up @@ -502,13 +505,39 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
onUsageLimits:
usageLimitsOffered && props.draftAttachments.length === 0 ? openUsageLimits : undefined,
});
const voiceTarget = useMemo(
() => ({ environmentId: props.environmentId, threadId: props.selectedThread.id }),
[props.environmentId, props.selectedThread.id],
);
const voicePhase = useVoiceModePhase(voiceTarget);
useVoiceModeThreadLifecycle(voiceTarget);
// Dictation and a voice conversation both need the microphone.
const voiceConversationLive = voicePhase !== "idle";
const voiceInput = useVoiceInputController({
ownerKey: composerOwnerKey,
draftMessage: props.draftMessage,
selection: composerMenu.selection,
disabled: voiceConversationLive,
onChangeDraftMessage: props.onChangeDraftMessage,
onChangeSelection: composerMenu.onSelectionChange,
});
const offersVoiceConversation =
voiceModeSupported && selectedProviderStatus?.supportsVoice === true;
// The server attaches voice to the thread's provider thread, which the first
// run creates. An optimistic pending thread already has a message timestamp.
const canToggleVoiceConversation =
voiceConversationLive ||
(props.connectionState === "connected" &&
props.selectedThread.activeProviderThreadId !== null &&
!voiceInput.isBusy);
const toggleVoiceConversation = useCallback(() => voiceMode.toggle(voiceTarget), [voiceTarget]);
const voiceModeButton = offersVoiceConversation ? (
<ComposerVoiceModeButton
phase={voicePhase}
disabled={!canToggleVoiceConversation}
onPress={toggleVoiceConversation}
/>
) : null;
const voicePresentation = resolveVoiceComposerPresentation(
voiceInput.state,
voiceInput.elapsedSeconds,
Expand Down Expand Up @@ -794,6 +823,9 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
{selectedProviderStatus.compatibilityAdvisory.message}
</Text>
) : null}

{voiceConversationLive ? <ComposerVoiceStrip /> : null}

{modelUnavailable ? (
<Pressable accessibilityRole="button" className="px-3 py-2" onPress={openSettings}>
<Text className="text-xs text-foreground">Model unavailable. Open model settings.</Text>
Expand Down Expand Up @@ -1036,9 +1068,11 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
) : null}
{!isExpanded ? (
<View className="flex-row items-center">
{voiceModeButton}
<ComposerDictationStartAction
state={voiceInput.state}
isAvailable={voiceInput.isAvailable}
disabled={voiceConversationLive}
onStart={voiceInput.start}
onCancel={voiceInput.cancel}
/>
Expand Down Expand Up @@ -1128,10 +1162,12 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
</View>
)}
<View className="shrink-0 flex-row items-center">
{isVoiceInputPresented ? null : voiceModeButton}
<ComposerDictationPrimaryAction
state={voiceInput.state}
presentation={voicePresentation}
isAvailable={voiceInput.isAvailable}
disabled={voiceConversationLive}
onStart={voiceInput.start}
onConfirm={voiceInput.stop}
onCancel={voiceInput.cancel}
Expand Down
10 changes: 10 additions & 0 deletions apps/mobile/src/features/threads/ThreadDetailScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,8 @@ import { ComposerQueuedEditBanner } from "./ComposerQueuedEdit";
import { useThreadQueuedCount } from "./ThreadQueueControl";
import type { ThreadContentPresentation } from "./threadContentPresentation";
import { resolveThreadFeedSubmissionAnchor } from "./thread-feed-live-follow";
import { ComposerVoiceStrip } from "../voice-mode/ComposerVoiceMode";
import { useVoiceModePhase } from "../voice-mode/useVoiceMode";

export interface ThreadDetailScreenProps {
readonly worktreeSetup?: WorktreeSetupCardProps | null;
Expand Down Expand Up @@ -512,6 +514,11 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
const [collapsedUserInputRequestId, setCollapsedUserInputRequestId] =
useState<RuntimeRequestId | null>(null);
const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null;
const voiceTarget = useMemo(
() => ({ environmentId: props.environmentId, threadId: props.selectedThread.id }),
[props.environmentId, props.selectedThread.id],
);
const voiceLiveHere = useVoiceModePhase(voiceTarget) !== "idle";
// The open /usage-limits panel for this thread, model and turn. Only the open
// moment is stored: the rows read live provider data, so a redeemed reset
// credit or refreshed probe shows through. Anything that spends quota closes
Expand Down Expand Up @@ -1239,6 +1246,9 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
) : null}
</View>

{/* The composer below hides for a question card; keep a live
voice conversation's mute and stop controls reachable. */}
{activeUserInputRequestId !== null && voiceLiveHere ? <ComposerVoiceStrip /> : null}
{/* Hidden (not unmounted) while a user-input request owns the
composer slot, so composer drafts and editor state survive.
A rejected creation has no thread to send to; the failure card
Expand Down
Loading
Loading