feat(desktop): add opt-in Cua Driver computer use #10899
Closedf-trycua(GitHub profile, opens in a new tab)wants to merge 23 commits into
main fromrefs/pull/10899/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/cua/CuaDriver.ts lines 206 to 207OutdatedResolvedby f-trycua(GitHub profile, opens in a new tab)@@ -0,0 +187,21 @@187+ if (!releasing) {188+ retired = true;189+ abort.abort();190+ releasing = (async () => {191+ try {192+ await starting;193+ } catch {194+ /* Failed starts still own a host. */195+ }196+ try {197+ await host.stop();198+ } catch {199+ /* Destruction must still run. */200+ }201+ try {202+ await monitoring;203+ } catch {204+ /* Cancellation ends the monitor. */205+ }206+ host.uniffiDestroy();207+ occupied = false;
- @@ -43 +43,21 @@434344+## Let agents use the host computer45+46+**Cua computer use** lets agents control the machine running your T3 Code server47+through Cua Driver. It is off by default, applies to the whole environment with no48+project override, and is separate from **Agent browser access**. Every provider49+receives it, unless you already configured a `cua-driver` MCP server of your own50+for that provider.51+52+Turn it on in **Settings > Integrations** with the host machine selected. On the53+desktop app that owns the machine, T3 Code walks you through granting Accessibility54+and Screen Recording before the switch turns on. The **Permissions** button next to55+the switch reopens that check later. From another computer or phone, the switch turns56+on immediately, but you still have to grant those permissions to T3 Code on the host.57+58+Packaged T3 Code desktop includes Cua Driver. For a standalone server, set59+`T3CODE_CUA_DRIVER_PATH` to the absolute path of your Cua Driver executable before60+starting the server. Agent sessions started after enabling get the computer use tools.61+Turning the switch off revokes T3 Code's managed access without touching MCP servers62+you configured yourself.63+
github-actions[bot](GitHub profile, opens in a new tab) removed labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
- @@ -806,3 +807,4 @@806807 url: mcp.endpoint,807808 headers: [{ name: "Authorization", value: mcp.authorizationHeader }],808809 },810+ ...(mcp.cuaDriver ? [cuaAcpMcpServer(mcp.cuaDriver)] : []),@@ -292,8 +294,14 @@292294 }293295294296 export function buildMessageContext(input: {297+ /** Outgoing text; app references carry their payload in the link itself. */298+ prompt?: string;295299 terminalContexts: ReadonlyArray<TerminalContextDraft>;296300 reviewComments: ReadonlyArray<ReviewCommentContext>;297301 previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;298302 attachments?: ReadonlyArray<BoundComposerAttachment>;299303 }): OrchestrationMessageContext | undefined {304+ const appRecords = new Map<string, AppContextRecord>();305+ for (const occurrence of collectComposerContextReferences(input.prompt ?? "")) {306+ if (occurrence.kind !== "app" || appRecords.has(occurrence.contextId)) continue;307+ const record = appContextRecordFromReference(occurrence);@@ -2281,11 +2301,5 @@22812301 const composerMenuItems = useMemo<ComposerCommandItem[]>(() => {22822302 if (!composerTrigger) return [];22832303 if (composerTrigger.kind === "path") {2284- return workspaceEntries.entries.map((entry) => ({2285- id: `path:${entry.kind}:${entry.path}`,2286- type: "path",2287- path: entry.path,2288- pathKind: entry.kind,2289- label: basenameOfPath(entry.path),2290- description: entry.path.slice(0, Math.max(0, entry.path.lastIndexOf("/"))),2291- }));2304+ const appItems: ComposerCommandItem[] =2305+ installedApps.data?.supported && cuaHost.ready@@ -0,0 +10,21 @@10+const CACHE_TTL_MS = 5_000;11+let cached: { readonly at: number; readonly value: CuaHostPermissions } | null = null;12+let inFlight: Promise<CuaHostPermissions | null> | null = null;13+14+/** Whether this desktop can act on its own screen right now. Null where no desktop can answer. */15+export function readCuaHostPermissions(): Promise<CuaHostPermissions | null> {16+ const bridge = isElectron ? window.desktopBridge : undefined;17+ if (!bridge?.checkSystemPermission || bridge.getClientPlatform?.() !== "darwin") {18+ return Promise.resolve(null);19+ }20+ if (cached && Date.now() - cached.at < CACHE_TTL_MS) return Promise.resolve(cached.value);21+ inFlight ??= Promise.all([22+ bridge.checkSystemPermission("accessibility"),23+ bridge.checkSystemPermission("screen-recording"),24+ ])25+ .then(([accessibility, screenRecording]) => {26+ const value = { accessibility, screenRecording };27+ cached = { at: Date.now(), value };28+ return value;29+ })30+ .catch(() => null)@@ -350,3 +350,4 @@350350 {record.kind === "mention" ? (351351 <ContextField label="Path" value={record.path} code />352352 ) : null}353+ {record.kind === "app" ? (@@ -0,0 +1,20 @@1+import { useCallback, useEffect, useState } from "react";2+3+import { isElectron } from "../env";4+5+export interface CuaHostPermissions {6+ readonly accessibility: boolean;7+ readonly screenRecording: boolean;8+}9+10+const CACHE_TTL_MS = 5_000;11+let cached: { readonly at: number; readonly value: CuaHostPermissions } | null = null;12+let inFlight: Promise<CuaHostPermissions | null> | null = null;13+14+/** Whether this desktop can act on its own screen right now. Null where no desktop can answer. */15+export function readCuaHostPermissions(): Promise<CuaHostPermissions | null> {16+ const bridge = isElectron ? window.desktopBridge : undefined;17+ if (!bridge?.checkSystemPermission || bridge.getClientPlatform?.() !== "darwin") {18+ return Promise.resolve(null);19+ }20+ if (cached && Date.now() - cached.at < CACHE_TTL_MS) return Promise.resolve(cached.value);@@ -2857,3 +2882,7 @@28572882 },28582883 }),28592884 );2885+ if (mcpSession.cuaDriver) {2886+ const cuaDriver = mcpSession.cuaDriver;2887+ yield* runOpenCodeSdk("mcp.add", () =>2888+ client.mcp.add({@@ -454,0 +506,21 @@506+ </Button>507+ ) : null}508+ <Switch509+ aria-label="Cua computer use"510+ mixed={mixedCua}511+ checked={mixedCua ? false : settings.enableCua || cuaSetupOpen}512+ onCheckedChange={(enabled) => {513+ if (enabled && cuaSetupAvailable) setCuaSetupOpen(true);514+ else void updateSettings({ enableCua: enabled });515+ }}516+ />517+ </>518+ }519+ />520+ {cuaSetupOpen ? (521+ <CuaSetupDialog522+ enabled={settings.enableCua}523+ onCheck={checkCuaPermission}524+ onAllow={allowCuaPermission}525+ onEnable={async () => {526+ if (!settings.enableCua) await updateSettings({ enableCua: true });
- @@ -0,0 +1,16 @@1+import { createCuaEnvironmentAtoms } from "@t3tools/client-runtime/state/cua";2+import type { CuaWindowPreviewState, ScopedThreadRef } from "@t3tools/contracts";3+4+import { connectionAtomRuntime } from "../connection/runtime";5+import { useEnvironmentQuery } from "./query";6+7+export const cuaEnvironment = createCuaEnvironmentAtoms(connectionAtomRuntime);8+9+const IDLE: CuaWindowPreviewState = { status: "idle" };10+11+/** Subscribes while mounted; the server captures only for mounted subscribers. */12+export function useCuaWindowPreview(threadRef: ScopedThreadRef | null): CuaWindowPreviewState {13+ const query = useEnvironmentQuery(14+ threadRef === null15+ ? null16+ : cuaEnvironment.windowPreview({@@ -0,0 +85,21 @@85+ * before the adapter sees it, so its screenshots are never recoverable.86+ */87+export function cuaToolResultOf(data: unknown): unknown {88+ const record = asRecord(data);89+ if (!record) return undefined;90+ return asRecord(record.item)?.result ?? record.result ?? record.rawOutput ?? record.content;91+}92+93+/**94+ * Persists the screenshot a Cua tool returned so clients can show what the95+ * agent last looked at. Only capture tools return images, so any image block96+ * qualifies. Failures are logged, never raised into the provider event path.97+ */98+export const saveCuaScreenshot = Effect.fn("cua.saveScreenshot")(function* (input: {99+ readonly threadId: ThreadId;100+ readonly result: unknown;101+}) {102+ const image = findImageBlock(input.result);103+ if (!image) return undefined;104+ const bytes = Buffer.from(image.base64, "base64");105+ if (bytes.byteLength === 0 || bytes.byteLength > MAX_IMAGE_BYTES) return undefined;@@ -0,0 +471,21 @@471+ });472+ }),473+ stop: Effect.gen(function* () {474+ if (!requested) {475+ pending.delete(requestId);476+ exits.delete(requestId);477+ return;478+ }479+ const stopId = NodeCrypto.randomUUID();480+ const stopped = yield* Deferred.make<DesktopCuaDriverReport>();481+ pending.set(stopId, stopped);482+ yield* receiver.requestCuaDriver(stopId, false).pipe(483+ Effect.mapError((cause) => new CuaDriverDesktopStopError({ requestId: stopId, cause })),484+ Effect.andThen(Deferred.await(stopped)),485+ Effect.ensuring(486+ Effect.sync(() => {487+ pending.delete(stopId);488+ pending.delete(requestId);489+ exits.delete(requestId);490+ }),491+ ),@@ -105,3 +105,4 @@105105 [WS_METHODS.projectsReadFile]: AuthOrchestrationReadScope,106106 [WS_METHODS.projectsSearchContents]: AuthOrchestrationReadScope,107107 [WS_METHODS.projectsSearchEntries]: AuthOrchestrationReadScope,108+ [WS_METHODS.appsList]: AuthOrchestrationReadScope,
- @@ -0,0 +114,21 @@114+ const entry = parseDesktopEntry(contents.value, path.basename(fileName, ".desktop"));115+ if (entry) entries.push(entry);116+ }117+ }118+ return entries;119+});120+121+/**122+ * `Icon=` is either an absolute path or a theme name looked up in hicolor by123+ * size, then in pixmaps. A relative path with separators is rejected rather124+ * than joined, since the entry could point anywhere.125+ */126+const resolveIconFile = Effect.fn("NativeAppIconResolver.linux.resolveIconFile")(function* (127+ icon: string,128+ iconDirectories: ReadonlyArray<string>,129+) {130+ const path = yield* Path.Path;131+ if (path.isAbsolute(icon)) {132+ const extension = path.extname(icon).toLowerCase();133+ return (ICON_EXTENSIONS as ReadonlyArray<string>).includes(extension)134+ ? yield* existingFile(icon)
juliusmarminge closed this
juliusmarminge reopened this
t3dotgg(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
Note
Reviews paused#
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
📝 Walkthrough
Walkthrough#
The pull request adds managed CUA driver support across contracts, desktop and server runtimes, provider integrations, macOS permissions, desktop packaging, settings, and documentation. It also adds lifecycle, configuration, packaging, and integration tests.
Changes#
CUA contracts and settings
packages/contracts/src/cua.ts,packages/contracts/src/resourceTelemetry.ts,packages/contracts/src/settings.ts,packages/contracts/src/ipc.ts,packages/contracts/src/index.tsenableCuasetting, new macOS permission panes, and contract exports.packages/contracts/src/settings.test.tsenableCua.Desktop runtime
apps/desktop/src/telemetry/DesktopTelemetryPublisher.ts,apps/desktop/src/backend/DesktopBackendManager.ts,apps/desktop/src/app/DesktopApp.ts,apps/desktop/src/main.tsapps/desktop/src/cua/DesktopCuaDriver.ts,apps/desktop/src/cua/DesktopCuaDriver.test.tsapps/desktop/src/permissions/*,apps/desktop/src/ipc/methods/window.tsServer runtime and providers
apps/server/src/cua/CuaDriver.ts,apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts,apps/server/src/server.ts,apps/server/package.jsonapps/server/src/provider/Layers/ProviderService.ts,apps/server/src/mcp/McpProviderSession.ts,apps/server/src/cua/cuaMcpServer.tsapps/server/src/provider/Layers/*Adapter.tsapps/server/src/cua/codexCuaConfiguration.ts,apps/server/src/cua/resolveCodexCua.ts,apps/server/src/provider/Layers/CodexAdapter.ts,apps/server/src/provider/Layers/CodexSessionRuntime.tsapps/server/src/cua/*.test.ts,apps/server/src/provider/Layers/*test.tsPackaging and settings
scripts/build-desktop-artifact.ts,scripts/build-desktop-artifact.test.ts,scripts/lib/*external-packages*apps/web/src/components/settings/*,apps/web/src/components/settings/SettingsPanels.tsx,apps/web/src/components/settings/settingsSearch.tsdocs/user/project-settings.md,third-party-licenses.config.jsonPriority: ➖ Normal
Estimated code review effort: 5 (Critical) | ~90 minutes
Merge Risk: 🟡 Moderate · up to
8ba05A code path that manages access to computer-use tooling can, in a narrow restart scenario, keep serving a stale session configuration (including previously granted managed computer-use access) after credential issuance fails to renew it. This should be fixed before merge to avoid unintended persistence of managed access or stale provider credentials; it is a scoped, low-effort fix in the provider session-preparation logic.
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
Full details: Docstring Coverage
Explanation
Docstring coverage is 31.82% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 22 functions across 53 files. (1 skipped: 1 unsupported.)
✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands.