diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index fd09f944af2f2..29b10daa75a72 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -224,6 +224,7 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.deviceDetail]: AuthOrchestrationReadScope, [WS_METHODS.deviceAction]: AuthOrchestrationOperateScope, [WS_METHODS.subscribeDeviceState]: AuthOrchestrationReadScope, + [WS_METHODS.subscribeCuaWindowPreview]: AuthOrchestrationReadScope, [WS_METHODS.subscribeServerConfig]: AuthOrchestrationReadScope, [WS_METHODS.subscribeServerLifecycle]: AuthOrchestrationReadScope, [WS_METHODS.subscribeAuthAccess]: AuthAccessReadScope, diff --git a/apps/server/src/cua/CuaWindowPreview.test.ts b/apps/server/src/cua/CuaWindowPreview.test.ts new file mode 100644 index 0000000000000..1c1db464e3ef4 --- /dev/null +++ b/apps/server/src/cua/CuaWindowPreview.test.ts @@ -0,0 +1,175 @@ +import { it } from "@effect/vitest"; +import type { OrchestrationV2DomainEvent } from "@t3tools/contracts"; +import { ThreadId } from "@t3tools/contracts"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Layer from "effect/Layer"; +import * as PubSub from "effect/PubSub"; +import * as Stream from "effect/Stream"; +import { describe, expect } from "vite-plus/test"; + +import type { McpProviderSessionConfig } from "@t3tools/provider-core/server/mcpSession"; +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; +import { cuaToolPresentation } from "@t3tools/provider-core/server/cuaToolPresentation"; +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import * as CuaWindowPreview from "./CuaWindowPreview.ts"; + +const threadId = ThreadId.make("11111111-2222-4333-8444-555555555555"); +const png = "iVBORw0KGgo="; + +const turnEvent = (type: "turn.started" | "turn.completed") => + ({ + type: "provider-turn.updated", + threadId, + payload: { status: type === "turn.started" ? "running" : "completed" }, + }) as unknown as OrchestrationV2DomainEvent; + +const makeHarness = Effect.fn(function* () { + const events = yield* PubSub.unbounded(); + const captures: string[] = []; + let clients = 0; + let destroyed = 0; + const fakeClient = { + getWindowState: (input: { pid: number; windowId: bigint }) => + Promise.resolve({ + pid: input.pid, + windowId: input.windowId, + appName: "Calendar", + windowTitle: "December 2026", + screenshotWidth: 640, + screenshotHeight: 400, + images: [{ mimeType: "image/png", dataBase64: png }], + }), + getDesktopState: () => { + captures.push("desktop"); + return Promise.resolve({ + text: "", + images: [{ mimeType: "image/png", dataBase64: png }], + isError: false, + degraded: false, + rawJson: "{}", + }); + }, + shutdown: () => Promise.resolve(), + uniffiDestroy: () => { + destroyed += 1; + }, + }; + const sdk = { + CuaDriver: { + connect: () => { + clients += 1; + return fakeClient; + }, + }, + GetWindowStateInput: { new: (input: unknown) => input }, + GetDesktopStateInput: { new: (input: unknown) => input }, + } as unknown as CuaWindowPreview.SdkModule; + const service = yield* CuaWindowPreview.make({ + loadSdk: Effect.succeed(sdk), + refreshInterval: Duration.millis(20), + }).pipe( + Effect.provideService(Orchestrator.OrchestratorV2, { + streamDomainEvents: Stream.fromPubSub(events), + } as unknown as Orchestrator.OrchestratorV2["Service"]), + ); + return { + service, + emit: (event: OrchestrationV2DomainEvent) => PubSub.publish(events, event), + captures, + counts: () => ({ clients, destroyed }), + }; +}); + +const layer = Layer.merge(NodeServices.layer, McpProviderSessions.layer); + +const setCuaSession = Effect.flatMap(McpProviderSessions.McpProviderSessions, (sessions) => + sessions.set({ + threadId, + endpoint: "http://127.0.0.1/mcp", + authorizationHeader: "Bearer x", + capabilities: new Set(), + cuaDriver: { command: "/driver", args: [], environment: [], socketPath: "/tmp/cua.sock" }, + } as unknown as McpProviderSessionConfig), +); + +describe("CuaWindowPreview", () => { + it.live("captures only while a client subscribes during a Cua turn", () => + Effect.gen(function* () { + yield* setCuaSession; + const harness = yield* makeHarness(); + const live = yield* Deferred.make(); + const idle = yield* Deferred.make(); + const states: string[] = []; + const subscriber = yield* harness.service.stream(threadId).pipe( + Stream.tap((state) => + Effect.gen(function* () { + states.push(state.status); + if (state.status === "live") yield* Deferred.succeed(live, undefined); + if (state.status === "idle" && states.length > 1) + yield* Deferred.succeed(idle, undefined); + }), + ), + Stream.runDrain, + Effect.forkScoped, + ); + yield* Effect.yieldNow; + expect(states).toEqual(["idle"]); + expect(harness.counts().clients).toBe(0); + + yield* harness.emit(turnEvent("turn.started")); + yield* Deferred.await(live); + expect(harness.counts().clients).toBe(1); + expect(harness.captures.length).toBeGreaterThan(0); + + yield* harness.emit(turnEvent("turn.completed")); + yield* Deferred.await(idle); + expect(harness.counts().destroyed).toBe(1); + yield* Fiber.interrupt(subscriber); + }).pipe(Effect.scoped, Effect.provide(layer)), + ); + + it.live("prefers the window the agent last targeted", () => + Effect.gen(function* () { + yield* setCuaSession; + cuaToolPresentation({ + threadId, + rawToolName: "cua-driver/click", + args: { pid: 42, window_id: "7", x: 1, y: 1 }, + status: "completed", + }); + const harness = yield* makeHarness(); + const first = yield* harness.service.stream(threadId).pipe( + Stream.filter((state) => state.status === "live"), + Stream.runHead, + Effect.forkScoped, + ); + yield* Effect.yieldNow; + yield* harness.emit(turnEvent("turn.started")); + const state = yield* Fiber.join(first); + expect(state._tag).toBe("Some"); + if (state._tag !== "Some") return; + expect(state.value.frame).toMatchObject({ + appName: "Calendar", + windowTitle: "December 2026", + width: 640, + height: 400, + mimeType: "image/png", + }); + expect(harness.captures).toEqual([]); + }).pipe(Effect.scoped, Effect.provide(layer)), + ); + + it.live("stays idle for sessions without a managed driver socket", () => + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* harness.emit(turnEvent("turn.started")); + const state = yield* harness.service.stream(threadId).pipe(Stream.runHead); + expect(state._tag === "Some" ? state.value : null).toEqual({ status: "idle" }); + expect(harness.counts().clients).toBe(0); + }).pipe(Effect.scoped, Effect.provide(layer)), + ); +}); diff --git a/apps/server/src/cua/CuaWindowPreview.ts b/apps/server/src/cua/CuaWindowPreview.ts new file mode 100644 index 0000000000000..987b3ac23eede --- /dev/null +++ b/apps/server/src/cua/CuaWindowPreview.ts @@ -0,0 +1,325 @@ +import * as NodeModule from "node:module"; + +import type { + CuaWindowPreviewFrame, + CuaWindowPreviewState, + OrchestrationV2DomainEvent, + ThreadId, +} from "@t3tools/contracts"; +import type * as CuaSdk from "@trycua/cua-driver"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +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 PubSub from "effect/PubSub"; +import * as Schedule from "effect/Schedule"; +import * as Schema from "effect/Schema"; +import * as Scope from "effect/Scope"; +import * as Semaphore from "effect/Semaphore"; +import * as Stream from "effect/Stream"; + +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import { + readCuaWindowTarget, + type CuaWindowTarget, +} from "@t3tools/provider-core/server/cuaToolPresentation"; + +export class CuaWindowPreviewSdkError extends Schema.TaggedError()( + "CuaWindowPreviewSdkError", + { cause: Schema.Defect() }, +) { + override get message() { + return "Could not load the Cua Driver SDK for window previews."; + } +} + +export class CuaWindowPreviewCaptureError extends Schema.TaggedError()( + "CuaWindowPreviewCaptureError", + { cause: Schema.Defect() }, +) { + override get message() { + return "Could not capture the window the agent is driving."; + } +} + +export class CuaWindowPreview extends Context.Service< + CuaWindowPreview, + { + /** Current state first, then every change while the subscriber stays attached. */ + readonly stream: (threadId: ThreadId) => Stream.Stream; + } +>()("t3/cua/CuaWindowPreview") {} + +export type SdkModule = Pick< + typeof CuaSdk, + "CuaDriver" | "GetWindowStateInput" | "GetDesktopStateInput" +>; +// `connect` is typed as the interface, but every implementation is the +// generated class with the native handle to release. +type SdkClient = Pick< + CuaSdk.CuaDriver, + "getWindowState" | "getDesktopState" | "shutdown" | "uniffiDestroy" +>; + +const REFRESH_INTERVAL = Duration.seconds(1.5); +/** Long edge of the preview frame; small enough for a floating card over the app WS. */ +const MAX_DIMENSION = 800; +const IDLE_STATE: CuaWindowPreviewState = { status: "idle" }; + +const requireForCuaDriver = NodeModule.createRequire(import.meta.url); + +/** Same resolution as the embedded host loader: the package only exports `import` conditions. */ +const loadSdk = Effect.fn("CuaWindowPreview.loadSdk")(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + for (const lookupPath of requireForCuaDriver.resolve.paths("@trycua/cua-driver") ?? []) { + const packageDir = path.join(lookupPath, "@trycua", "cua-driver"); + if ( + yield* fs + .exists(path.join(packageDir, "package.json")) + .pipe(Effect.orElseSucceed(() => false)) + ) { + return yield* Effect.try({ + try: () => requireForCuaDriver(path.join(packageDir, "dist", "index.js")) as SdkModule, + catch: (cause) => new CuaWindowPreviewSdkError({ cause }), + }); + } + } + return yield* new CuaWindowPreviewSdkError({ cause: "@trycua/cua-driver is not installed." }); +}); + +/** + * Captures the window the agent last targeted, or the whole desktop before it + * has named one. A window that disappeared falls back to the desktop rather + * than failing, so the card keeps showing something while the agent moves on. + */ +const captureFrame = Effect.fn("CuaWindowPreview.capture")(function* ( + sdk: SdkModule, + client: SdkClient, + target: CuaWindowTarget | undefined, +) { + const capturedAt = DateTime.formatIso(yield* DateTime.now); + if (target) { + const window = yield* Effect.tryPromise({ + try: (signal) => + client.getWindowState( + sdk.GetWindowStateInput.new({ + pid: target.pid, + windowId: target.windowId, + includeAccessibilityTree: false, + includeScreenshot: true, + maxDimension: MAX_DIMENSION, + }), + { signal }, + ), + catch: (cause) => new CuaWindowPreviewCaptureError({ cause }), + }).pipe(Effect.option); + const image = Option.isSome(window) ? window.value.images[0] : undefined; + if (Option.isSome(window) && image) { + return { + ...(window.value.appName ? { appName: window.value.appName } : {}), + ...(window.value.windowTitle ? { windowTitle: window.value.windowTitle } : {}), + width: window.value.screenshotWidth ?? 0, + height: window.value.screenshotHeight ?? 0, + mimeType: image.mimeType, + dataBase64: image.dataBase64, + capturedAt, + } satisfies CuaWindowPreviewFrame; + } + } + const desktop = yield* Effect.tryPromise({ + try: (signal) => client.getDesktopState(sdk.GetDesktopStateInput.new({}), { signal }), + catch: (cause) => new CuaWindowPreviewCaptureError({ cause }), + }); + const image = desktop.images[0]; + if (desktop.isError || !image) { + return yield* new CuaWindowPreviewCaptureError({ + cause: desktop.errorCode ?? desktop.text ?? "no image", + }); + } + return { + width: 0, + height: 0, + mimeType: image.mimeType, + dataBase64: image.dataBase64, + capturedAt, + } satisfies CuaWindowPreviewFrame; +}); + +interface ThreadPreview { + readonly changes: PubSub.PubSub; + state: CuaWindowPreviewState; + subscribers: number; + /** Set while the thread's provider session has a turn in flight with Cua attached. */ + live: boolean; + loop: Scope.Closeable | undefined; +} + +export interface CuaWindowPreviewOptions { + /** Test seam: replaces the SDK load so the loop can run against a fake driver. */ + readonly loadSdk?: Effect.Effect; + readonly refreshInterval?: Duration.Duration; +} + +export const make = Effect.fn("CuaWindowPreview.make")(function* ( + options: CuaWindowPreviewOptions = {}, +) { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const scope = yield* Effect.scope; + const mutex = yield* Semaphore.make(1); + const threads = new Map(); + const refreshInterval = options.refreshInterval ?? REFRESH_INTERVAL; + const loadSdkModule = + options.loadSdk ?? + loadSdk().pipe( + Effect.provideService(FileSystem.FileSystem, fs), + Effect.provideService(Path.Path, path), + ); + let sdk: SdkModule | undefined; + + const publish = (preview: ThreadPreview, state: CuaWindowPreviewState) => + Effect.suspend(() => { + preview.state = state; + return PubSub.publish(preview.changes, state); + }); + + const previewFor = Effect.fn("CuaWindowPreview.previewFor")(function* (threadId: ThreadId) { + const existing = threads.get(threadId); + if (existing) return existing; + const created: ThreadPreview = { + changes: yield* PubSub.sliding(2), + state: IDLE_STATE, + subscribers: 0, + live: false, + loop: undefined, + }; + threads.set(threadId, created); + return created; + }); + + /** + * One capture loop per thread, running only while a client is subscribed + * and the agent is mid-turn with Cua attached. The SDK client lives for the + * loop; every stop releases the native handle. + */ + const refreshLoop = Effect.fn("CuaWindowPreview.refreshLoop")( + function* (threadId: ThreadId, preview: ThreadPreview, socketPath: string) { + sdk ??= yield* loadSdkModule; + const module = sdk; + const client = yield* Effect.acquireRelease( + Effect.try({ + try: () => module.CuaDriver.connect(socketPath) as unknown as SdkClient, + catch: (cause) => new CuaWindowPreviewSdkError({ cause }), + }), + (client) => + Effect.promise(() => client.shutdown()).pipe( + Effect.ignore, + Effect.andThen(Effect.sync(() => client.uniffiDestroy())), + ), + ); + yield* captureFrame(module, client, readCuaWindowTarget(threadId)).pipe( + Effect.flatMap((frame) => publish(preview, { status: "live", frame })), + Effect.catchTags({ + CuaWindowPreviewCaptureError: (error) => + publish(preview, { + status: "unavailable", + detail: typeof error.cause === "string" ? error.cause : error.message, + }), + }), + Effect.repeat(Schedule.spaced(refreshInterval)), + ); + }, + (effect, _threadId, preview) => + effect.pipe( + Effect.catch((error: CuaWindowPreviewSdkError) => + publish(preview, { status: "unavailable", detail: error.message }), + ), + ), + ); + + const reconcile = (threadId: ThreadId) => + mutex.withPermits(1)( + Effect.gen(function* () { + const preview = threads.get(threadId); + if (!preview) return; + const socketPath = (yield* mcpSessions.read(threadId))?.cuaDriver?.socketPath; + const shouldRun = preview.live && preview.subscribers > 0 && socketPath !== undefined; + if (shouldRun && !preview.loop) { + const loopScope = yield* Scope.fork(scope); + preview.loop = loopScope; + yield* refreshLoop(threadId, preview, socketPath).pipe( + Effect.scoped, + Effect.forkIn(loopScope), + ); + return; + } + if (!shouldRun && preview.loop) { + const loopScope = preview.loop; + preview.loop = undefined; + yield* Scope.close(loopScope, Exit.void); + if (preview.subscribers === 0) { + threads.delete(threadId); + } else if (!preview.live) { + yield* publish(preview, IDLE_STATE); + } + } + }), + ); + + // A provider turn running on a thread with Cua attached makes it live; any + // terminal status ends it. + const onDomainEvent = Effect.fn("CuaWindowPreview.onDomainEvent")(function* ( + event: OrchestrationV2DomainEvent, + ) { + if (event.type !== "provider-turn.updated") return; + const status = event.payload.status; + if (status === "running") { + const preview = yield* previewFor(event.threadId); + preview.live = (yield* mcpSessions.read(event.threadId))?.cuaDriver?.socketPath !== undefined; + yield* reconcile(event.threadId); + } else if (status !== "pending") { + const preview = threads.get(event.threadId); + if (!preview) return; + preview.live = false; + yield* reconcile(event.threadId); + } + }); + + yield* orchestrator.streamDomainEvents.pipe( + Stream.runForEach(onDomainEvent), + Effect.catchCause((cause) => + Effect.logWarning("Computer use preview stopped following turns.", { cause }), + ), + Effect.forkScoped, + ); + + const stream = (threadId: ThreadId): Stream.Stream => + Stream.unwrap( + Effect.gen(function* () { + const preview = yield* previewFor(threadId); + const subscription = yield* PubSub.subscribe(preview.changes); + preview.subscribers += 1; + yield* Effect.addFinalizer(() => + Effect.suspend(() => { + preview.subscribers -= 1; + return reconcile(threadId); + }), + ); + yield* reconcile(threadId); + return Stream.concat(Stream.make(preview.state), Stream.fromSubscription(subscription)); + }), + ).pipe(Stream.scoped); + + return CuaWindowPreview.of({ stream }); +}); + +export const layer = Layer.effect(CuaWindowPreview, make()); diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index 2e5f6c25ef0e8..6fea413245ec6 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -244,6 +244,7 @@ const RPC_AGGREGATES = { [WS_METHODS.deviceDetail]: "device", [WS_METHODS.deviceAction]: "device", [WS_METHODS.subscribeDeviceState]: "device", + [WS_METHODS.subscribeCuaWindowPreview]: "workspace", [WS_METHODS.subscribeServerConfig]: "server", [WS_METHODS.subscribeServerLifecycle]: "server", [WS_METHODS.subscribeAuthAccess]: "auth", diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 4124df4e9da15..55b589eb65d62 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -203,6 +203,7 @@ import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts"; import * as TriageService from "./triage/TriageService.ts"; import * as DesktopTelemetryReceiver from "./resourceTelemetry/DesktopTelemetryReceiver.ts"; import * as CuaDriver from "./cua/CuaDriver.ts"; +import * as CuaWindowPreview from "./cua/CuaWindowPreview.ts"; import * as NativeTelemetryClient from "./resourceTelemetry/NativeTelemetryClient.ts"; import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts"; import * as ResourceMonitorBinary from "./resourceTelemetry/ResourceMonitorBinary.ts"; @@ -695,6 +696,7 @@ const layerServerRestart = Layer.effect( const layerRuntimeCoreDependenciesBase = Layer.mergeAll( AgentAwarenessRelay.layer, + CuaWindowPreview.layer, HeldHooksWaker.layer, layerThreadSettlementWorker, layerIdleCompactionWorker, diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index c5ca5905af36b..213996498cc1b 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -198,6 +198,7 @@ import { terminalOutputStream, withOutputWindow } from "./terminal/OutputProtoco import * as ServerBrowser from "./preview/ServerBrowser.ts"; import * as DeviceService from "./device/DeviceService.ts"; import * as CuaDriver from "./cua/CuaDriver.ts"; +import * as CuaWindowPreview from "./cua/CuaWindowPreview.ts"; import { remoteSshDeviceHosts } from "./device/localSshDeviceHost.ts"; import * as PreviewManager from "./preview/Manager.ts"; import { issueAssetUrl } from "./assets/AssetAccess.ts"; @@ -3318,6 +3319,16 @@ export const layerWsRpc = ( [WS_METHODS.deviceAction]: (input) => deviceService.action(input), [WS_METHODS.subscribeDeviceState]: (_input) => DeviceService.stateStream(deviceService), [WS_METHODS.previewStopLocalServer]: (input) => portDiscovery.stopServer(input), + [WS_METHODS.subscribeCuaWindowPreview]: (input) => + Stream.unwrap( + Effect.serviceOption(CuaWindowPreview.CuaWindowPreview).pipe( + Effect.map((preview) => + Option.isSome(preview) + ? preview.value.stream(input.threadId) + : Stream.make({ status: "idle" as const }), + ), + ), + ), [WS_METHODS.subscribeDiscoveredLocalServers]: (input) => Stream.callback((queue) => Effect.gen(function* () { diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index 1992b748331a2..6e50ca0ced018 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -157,6 +157,8 @@ export function shouldRenderPreviewMiniPlayer( renderedRightPanelSurface: RightPanelSurface | null, ): boolean { if (source === null) return false; + // The computer card has no panel counterpart. + if (source.kind === "computer") return true; if (source.kind === "browser") { return !( renderedRightPanelSurface?.kind === "preview" && diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index e69de418cd3ee..a4011cf0678c8 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -1,6 +1,6 @@ import { m } from "../i18n/messages"; import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; -import { useGT, useMessages } from "gt-react"; +import { T, useGT, useMessages } from "gt-react"; import { ChildThreadApprovals } from "./chat/ChildThreadApprovals"; import { workspaceAreaProps } from "../lib/workspaceFocus"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; @@ -188,11 +188,13 @@ import { useThreadPreviewCanvasSource, } from "./preview/ThreadPreviewMiniPlayer"; import { createChatCanvasStore, resolveChatCanvasModel } from "./chat/canvasStore"; +import { isRunUsingComputer, selectLatestComputerUse } from "./preview/computerUsePreview"; import { usePreviewSession } from "./preview/usePreviewSession"; import { getConfiguredPreviewUrls } from "./preview/previewEmptyStateLogic"; import { previewMiniPlayerSourceKey, + COMPUTER_MINI_PLAYER_SOURCE, selectThreadPreviewMiniPlayer, usePreviewMiniPlayerStore, } from "../previewMiniPlayerStore"; @@ -207,6 +209,8 @@ import { isEditableFocused } from "../lib/editableFocus"; import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings"; import { shortcutLabelForCommand } from "../keybindings"; import { cn } from "~/lib/utils"; +import { MonitorIcon } from "lucide-react"; +import { Button } from "./ui/button"; import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar"; import { toastManager } from "./ui/toast"; import { projectScriptIdFromCommand } from "~/projectScripts"; @@ -223,6 +227,7 @@ import { shouldShowInstanceBadge, } from "../providerInstances"; import { + getClientSettings, useClientSettings, useClientSettingsHydrated, useEnvironmentSettings, @@ -2017,6 +2022,21 @@ export default function ChatView(props: ChatViewProps) { const { state: deviceState, loaded: deviceStateLoaded } = useDeviceState( activeThreadRef?.environmentId ?? null, ); + // A computer use call floats the driven window over chat the way an agent-opened device does. + // Each new call reopens a card the user closed; a browser or device already floating stays. + const computerUse = selectLatestComputerUse(serverProjection?.turnItems ?? []); + const lastShownComputerUseItemId = useRef(null); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Floats the computer card when the shown thread's projection reports a new computer use call. + useEffect(() => { + if (!activeThreadRef || !computerUse?.inProgress || shouldUsePlanSidebarSheet) return; + if (lastShownComputerUseItemId.current === computerUse.itemId) return; + lastShownComputerUseItemId.current = computerUse.itemId; + if (!getClientSettings().browserAutoShowFloatingPreview) return; + const current = + usePreviewMiniPlayerStore.getState().byThreadKey[scopedThreadKey(activeThreadRef)]; + if (current && current.source.kind !== "computer") return; + usePreviewMiniPlayerStore.getState().open(activeThreadRef, COMPUTER_MINI_PLAYER_SOURCE); + }, [activeThreadRef, computerUse, shouldUsePlanSidebarSheet]); // The thread's own change request, placed against the project it belongs to. Without a // project there is nothing to resolve it against, so the caller falls back to the browser. const activeProjectRepository = sourceControlClients.repositorySelector( @@ -2629,6 +2649,22 @@ export default function ChatView(props: ChatViewProps) { messages, ) : null; + const usingComputer = isRunUsingComputer(serverProjection?.turnItems ?? [], activeRunningTurnId); + const computerUseBannerItems: ComposerBannerStackItem[] = usingComputer + ? [ + { + id: "computer-use", + variant: "info", + icon: , + title: gt("Using your computer"), + actions: ( + + ), + }, + ] + : []; const composerBannerItems = (() => { const fallbackSelection = draftFallback?.selection; const defaultSelection = @@ -2692,6 +2728,7 @@ export default function ChatView(props: ChatViewProps) { : []; if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) { return [ + ...computerUseBannerItems, ...feedbackBannerItems, ...fallbackItems, ...limitRecoveryItems, @@ -2703,6 +2740,7 @@ export default function ChatView(props: ChatViewProps) { ]; } return [ + ...computerUseBannerItems, ...feedbackBannerItems, ...fallbackItems, ...limitRecoveryItems, @@ -3916,6 +3954,7 @@ export default function ChatView(props: ChatViewProps) { key={`${activeThreadKey}:${previewMiniPlayerSourceKey(shownPreviewMiniPlayer.source)}`} threadRef={activeThreadRef} miniPlayer={shownPreviewMiniPlayer} + computerUse={computerUse} /> ) : null} diff --git a/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx b/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx index 378bcdd88408f..960411e7cf96b 100644 --- a/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx +++ b/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx @@ -1,6 +1,10 @@ import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; import { m } from "~/i18n/messages"; -import { FILL_PREVIEW_VIEWPORT, type ScopedThreadRef } from "@t3tools/contracts"; +import { + type CuaWindowPreviewFrame, + FILL_PREVIEW_VIEWPORT, + type ScopedThreadRef, +} from "@t3tools/contracts"; import { previewPdfAssetUrl } from "@t3tools/shared/preview"; import { useEnvironmentHttpBaseUrl } from "~/state/environments"; import { PanelRightIcon, PictureInPicture2, XIcon } from "lucide-react"; @@ -9,6 +13,7 @@ import { type ReactNode, useEffect, useEffectEvent, + useLayoutEffect, useRef, useState, } from "react"; @@ -52,13 +57,16 @@ import { usePreviewMiniPlayerStore, } from "~/previewMiniPlayerStore"; import { useRightPanelStore } from "~/rightPanelStore"; +import { useCuaWindowPreview } from "~/state/cua"; import { useDeviceState } from "~/state/device"; +import { useAssetUrlState } from "~/assets/assetUrls"; import { DeviceStreamView } from "../device/DeviceStreamView"; import type { DeviceScreenSize } from "@t3tools/client-runtime/device/stream"; import { Atom } from "effect/reactivity"; import { deviceScreenKey, deviceStreamScreenAtom } from "../device/deviceStreamSession"; import type { PreviewStreamViewport } from "@t3tools/client-runtime/preview/server-browser-stream"; +import type { ComputerUsePreview } from "./computerUsePreview"; import { previewBridge } from "./previewBridge"; import { PreviewUnreachable } from "./PreviewUnreachable"; import { showPreviewPopup } from "./showPreviewPopup"; @@ -112,6 +120,8 @@ const useHeldSourceSize = create<{ readonly key: string; readonly source: PreviewMiniPlayerSize; } | null>(() => null); +// Before the first frame arrives, the computer card assumes a laptop-sized window. +const COMPUTER_DEFAULT_SOURCE_SIZE = { width: 1280, height: 800 } as const; const NO_DEVICE_SCREEN_ATOM = Atom.make(null).pipe( Atom.withLabel("device-stream-screen:none"), @@ -185,6 +195,13 @@ export function useThreadPreviewCanvasSource( ? state.source : null, ); + const computerSize = useStreamedSourceSize((state) => + threadRef && + source?.kind === "computer" && + state?.key === streamedSourceKey(threadRef, sourceKey!) + ? state.viewport + : null, + ); if (!miniPlayer || !source || sourceKey === null) return null; if (source.kind === "browser" && !browser.snapshot) return null; return { @@ -196,26 +213,129 @@ export function useThreadPreviewCanvasSource( heldSource ?? (source.kind === "browser" ? browser.sourceSize - : resolveDeviceMiniPlayerSourceSize(source.platform, screen)), + : source.kind === "device" + ? resolveDeviceMiniPlayerSourceSize(source.platform, screen) + : (computerSize ?? COMPUTER_DEFAULT_SOURCE_SIZE)), }; } -export function ThreadPreviewMiniPlayer({ threadRef, miniPlayer }: Props) { +export function ThreadPreviewMiniPlayer({ + threadRef, + miniPlayer, + computerUse = null, +}: Props & { readonly computerUse?: ComputerUsePreview | null }) { const { source } = miniPlayer; - return source.kind === "browser" ? ( - - ) : ( - + ); + case "device": + return ( + + ); + case "computer": + return ( + + ); + } +} + +/** + * The window an agent drives on the host computer. While a computer use turn + * runs, the server captures that window every second and a half and streams + * it here; the capture runs only while this card is mounted. Between turns the + * card keeps the last frame instead of going blank. + */ +function ComputerMiniPlayer({ + threadRef, + miniPlayer, + preview, +}: Props & { readonly preview: ComputerUsePreview | null }) { + const gt = useGT(); + const live = useCuaWindowPreview(threadRef); + const [lastFrame, setLastFrame] = useState(null); + const liveFrame = live.status === "live" ? (live.frame ?? null) : null; + if (liveFrame !== null && liveFrame !== lastFrame) setLastFrame(liveFrame); + const frame = liveFrame ?? lastFrame; + const src = frame ? `data:${frame.mimeType};base64,${frame.dataBase64}` : null; + const sourceSize = + frame && frame.width > 0 && frame.height > 0 + ? { width: frame.width, height: frame.height } + : COMPUTER_DEFAULT_SOURCE_SIZE; + const viewportKey = streamedSourceKey(threadRef, previewMiniPlayerSourceKey(miniPlayer.source)); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Publishes the frame size to the store the chat canvas lays this card out from. + useLayoutEffect(() => { + useStreamedSourceSize.setState( + (state) => + state?.key === viewportKey && + state.viewport.width === sourceSize.width && + state.viewport.height === sourceSize.height + ? state + : { key: viewportKey, viewport: { width: sourceSize.width, height: sourceSize.height } }, + true, + ); + }, [viewportKey, sourceSize.width, sourceSize.height]); + const label = frame?.appName ?? preview?.appName ?? gt("Computer"); + const caption = + frame?.windowTitle && frame.windowTitle !== label ? `${label} · ${frame.windowTitle}` : label; + const appIcon = useAssetUrlState( + threadRef.environmentId, + preview?.app ? { _tag: "native-app-icon", app: preview.app } : null, + ); + + return ( + + sourceSize={sourceSize} + label={gt("Floating computer use preview")} + recording={live.status === "live" || preview?.inProgress === true} + > + {() => ( +
+ {src ? ( + {caption} + ) : ( +
+ {live.status === "unavailable" + ? gt("Preview unavailable") + : gt("Waiting for the agent…")} +
+ )} + {live.status === "unavailable" && live.detail ? ( +
+ {live.detail} +
+ ) : null} +
+ {appIcon._tag === "Success" ? ( + + ) : null} + {caption} +
+
+ )} +
); } @@ -453,7 +573,8 @@ function MiniPlayerShell({ readonly miniPlayer: PreviewMiniPlayerState; readonly sourceSize: PreviewMiniPlayerSize; readonly label: string; - readonly onOpenInPanel: () => void; + /** Omitted for sources that have no panel, such as the computer card. */ + readonly onOpenInPanel?: () => void; readonly pillActions?: ReactNode; readonly recording?: boolean; readonly cornerRadius?: (frame: PreviewMiniPlayerSize) => number; @@ -646,24 +767,26 @@ function MiniPlayerShell({ ) : null} - - event.stopPropagation()} - onClick={onOpenInPanel} - /> - } - > - - - - Open in right panel - - + {onOpenInPanel ? ( + + event.stopPropagation()} + onClick={onOpenInPanel} + /> + } + > + + + + Open in right panel + + + ) : null} {pillActions} > = {}, +) => + ({ + id, + type: "dynamic_tool", + status, + toolName: "mcp__cua-driver__click", + input: {}, + ...extra, + }) as unknown as OrchestrationV2TurnItem; + +describe("selectLatestComputerUse", () => { + it("picks the newest computer use call with its app, whatever the provider", () => { + const safari = { + _tag: "native-app", + app: { _tag: "app-id", appId: "com.apple.Safari" }, + } as const; + expect( + selectLatestComputerUse([ + tool("older", "completed", { toolSurface: "computer" }), + tool("newest", "running", { + toolSurface: "computer", + toolIcon: safari, + toolSource: { key: "native-app:com.apple.safari", name: "Safari", kind: "computer" }, + }), + tool("unrelated", "running"), + ]), + ).toEqual({ + itemId: "newest", + app: safari.app, + appName: "Safari", + inProgress: true, + }); + }); + + it("finds nothing in a thread without computer use", () => { + expect(selectLatestComputerUse([tool("plain", "completed")])).toBeNull(); + }); +}); + +describe("isRunUsingComputer", () => { + const run = "run-1" as RunId; + it("is true only once the running run has made a computer use call", () => { + const earlier = tool("earlier", "completed", { + runId: "run-0" as RunId, + toolSurface: "computer", + }); + const plain = tool("plain", "completed", { runId: run }); + expect(isRunUsingComputer([earlier, plain], run)).toBe(false); + expect( + isRunUsingComputer( + [earlier, plain, tool("click", "completed", { runId: run, toolSurface: "computer" })], + run, + ), + ).toBe(true); + expect(isRunUsingComputer([earlier], null)).toBe(false); + }); +}); diff --git a/apps/web/src/components/preview/computerUsePreview.ts b/apps/web/src/components/preview/computerUsePreview.ts new file mode 100644 index 0000000000000..0417941bf4c59 --- /dev/null +++ b/apps/web/src/components/preview/computerUsePreview.ts @@ -0,0 +1,46 @@ +import type { ThreadStructureTurnItem } from "@t3tools/client-runtime/state/shell"; +import type { RunId, ToolActivityNativeAppReference } from "@t3tools/contracts"; + +/** What the floating computer card shows until the live capture's first frame arrives. */ +export interface ComputerUsePreview { + readonly itemId: string; + readonly app: ToolActivityNativeAppReference | null; + readonly appName: string | null; + /** The newest computer use call is still running. */ + readonly inProgress: boolean; +} + +/** + * The newest computer use call in the thread, in any provider: Cua Driver + * calls carry the `computer` surface and the app they drive. + */ +export function selectLatestComputerUse( + turnItems: ReadonlyArray, +): ComputerUsePreview | null { + for (let index = turnItems.length - 1; index >= 0; index -= 1) { + const item = turnItems[index]!; + if (item.type !== "dynamic_tool" || item.toolSurface !== "computer") continue; + const icon = item.toolIcon ?? item.toolSource?.icon; + return { + itemId: item.id, + app: icon?._tag === "native-app" ? icon.app : null, + appName: item.toolSource?.kind === "computer" ? item.toolSource.name : null, + inProgress: item.status === "running" || item.status === "pending", + }; + } + return null; +} + +/** Whether the running run has used the computer, so the composer can say so beside Stop. */ +export function isRunUsingComputer( + turnItems: ReadonlyArray, + runningRunId: RunId | null, +): boolean { + if (runningRunId === null) return false; + return turnItems.some( + (item) => + item.runId === runningRunId && + item.type === "dynamic_tool" && + item.toolSurface === "computer", + ); +} diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index e470053c47973..2cd874ae88912 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -1640,6 +1640,7 @@ "86a59f2432768c7f": "Das Eingabefeld ist beschäftigt; versuche es erneut, sobald es bereit ist.", "ddbd48554168bc6e": "Nachrichten von Apps brauchen einen gestarteten Thread.", "881cec6c80bb6477": "Die Nachricht der App konnte nicht gesendet werden.", + "77069ea78dc20ef2": "Verwendet deinen Computer", "94d640e2a0d2e849": "Nebenchats können keine Nebenchats starten.", "3208297e5c0ed324": "Subagenten-Threads können keine Nebenchats starten.", "cbf94e4eba3e039f": "Nebenchats sind noch nicht bereit. Versuche es gleich noch einmal.", @@ -1654,6 +1655,7 @@ "0e974f4d7d582b12": "Feedback wird gesendet", "abb59f572874d3b4": "Nachrichten werden geladen", "9c353040cc3010c4": "Worktree wird vorbereitet", + "f624d18fa6181f60": "Stoppen", "536ad0c3529ef1b3": "Die Zwischenablage-API ist beim Kopieren des Befehls nicht verfügbar.", "7e06782c1ee65b02": "Der Befehl konnte nicht in die Zwischenablage kopiert werden.", "61bc68e834fb83af": "Befehl kopieren", @@ -6195,6 +6197,10 @@ "cd312dae87fc794f": "Die Anmerkung wurde ohne Screenshot behalten.", "4616fb6552fd8875": "Die Seite wurde nicht geladen. Auswählen ist erst möglich, wenn die Seite gerendert ist", "770d6036de8dbcb7": "Dieser Tab ist in der T3-Code-Desktop-App geöffnet.", + "5511e975ba69f726": "Computer", + "1ef44b8f78119bba": "Schwebende Vorschau der Computersteuerung", + "e60b3936c5e2190b": "Vorschau nicht verfügbar", + "65ba9047454a5170": "Wartet auf den Agenten…", "b252602c8f71d6af": "Vorschau kann nicht ausgelagert werden", "0fc0a2ff438851b5": "Schwebende Browservorschau", "74892fefe58df8e3": "Ausgelagerte Vorschau schließen", @@ -8342,7 +8348,6 @@ "a6a6dc235b108747": "Agenten den gemeinsamen Browser nutzen lassen. Projekte können das überschreiben.", "ea5fed973bfc1aca": "Standard-Browserzugriff auf Standard zurücksetzen", "19e1f74805f4a1fb": "Browserzugriff für Agenten", - "5511e975ba69f726": "Computer", "72cb818f86f74f1d": "Verbinde die ausgewählte Umgebung, um die Computersteuerung einzurichten.", "3a989eeb48af4c84": "Wähle eine Umgebung, um die Computersteuerung auf ihrem Host einzurichten.", "c97c0f969ce80c8c": "Computersteuerung konnte nicht geprüft werden: {error}", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index e8c65e4600495..9b0002ab1f1a7 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -1641,6 +1641,7 @@ "86a59f2432768c7f": "The composer is busy; try again once it is ready.", "ddbd48554168bc6e": "Messages from apps need a started thread.", "881cec6c80bb6477": "Could not send the app's message.", + "77069ea78dc20ef2": "Using your computer", "94d640e2a0d2e849": "Side chats cannot start side chats.", "3208297e5c0ed324": "Subagent threads cannot start side chats.", "cbf94e4eba3e039f": "Side chats are not ready yet. Try again in a moment.", @@ -1655,6 +1656,7 @@ "0e974f4d7d582b12": "Sending feedback", "abb59f572874d3b4": "Messages loading", "9c353040cc3010c4": "Preparing worktree", + "f624d18fa6181f60": "Stop", "536ad0c3529ef1b3": "Clipboard API is unavailable while copying command.", "7e06782c1ee65b02": "Failed to copy command to the clipboard.", "61bc68e834fb83af": "Copy command", @@ -6199,6 +6201,10 @@ "cd312dae87fc794f": "The annotation was kept without the screenshot.", "4616fb6552fd8875": "Page didn't load. Pick is unavailable until the page renders", "770d6036de8dbcb7": "This tab is open in the T3 Code desktop app.", + "5511e975ba69f726": "Computer", + "1ef44b8f78119bba": "Floating computer use preview", + "e60b3936c5e2190b": "Preview unavailable", + "65ba9047454a5170": "Waiting for the agent…", "b252602c8f71d6af": "Unable to pop out preview", "0fc0a2ff438851b5": "Floating browser preview", "74892fefe58df8e3": "Close popped-out preview", @@ -8349,7 +8355,6 @@ "a6a6dc235b108747": "Allow agents to use the shared browser. Projects can override it.", "ea5fed973bfc1aca": "Reset default browser access to default", "19e1f74805f4a1fb": "Agent browser access", - "5511e975ba69f726": "Computer", "72cb818f86f74f1d": "Connect the selected environment to configure computer use.", "3a989eeb48af4c84": "Choose one environment to configure computer use on its host.", "c97c0f969ce80c8c": "Could not check computer use: {error}", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index eb6b17a726afb..0890fe747d951 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -1641,6 +1641,7 @@ "86a59f2432768c7f": "El cuadro de mensaje está ocupado; vuelve a intentarlo cuando esté listo.", "ddbd48554168bc6e": "Los mensajes de apps necesitan un hilo iniciado.", "881cec6c80bb6477": "No se pudo enviar el mensaje de la app.", + "77069ea78dc20ef2": "Usando tu ordenador", "94d640e2a0d2e849": "Los chats laterales no pueden iniciar chats laterales.", "3208297e5c0ed324": "Los hilos de subagentes no pueden iniciar chats laterales.", "cbf94e4eba3e039f": "Los chats laterales aún no están listos. Vuelve a intentarlo en un momento.", @@ -1655,6 +1656,7 @@ "0e974f4d7d582b12": "Enviando comentarios", "abb59f572874d3b4": "Cargando mensajes", "9c353040cc3010c4": "Preparando el worktree", + "f624d18fa6181f60": "Detener", "536ad0c3529ef1b3": "La API del portapapeles no está disponible al copiar el comando.", "7e06782c1ee65b02": "No se pudo copiar el comando al portapapeles.", "61bc68e834fb83af": "Copiar comando", @@ -6196,6 +6198,10 @@ "cd312dae87fc794f": "La anotación se conservó sin la captura de pantalla.", "4616fb6552fd8875": "La página no se cargó. Seleccionar no está disponible hasta que se renderice", "770d6036de8dbcb7": "Esta pestaña está abierta en la app de escritorio de T3 Code.", + "5511e975ba69f726": "Ordenador", + "1ef44b8f78119bba": "Vista previa flotante del uso del ordenador", + "e60b3936c5e2190b": "Vista previa no disponible", + "65ba9047454a5170": "Esperando al agente…", "b252602c8f71d6af": "No se puede separar la vista previa", "0fc0a2ff438851b5": "Vista previa flotante del navegador", "74892fefe58df8e3": "Cerrar la vista previa separada", @@ -8339,7 +8345,6 @@ "a6a6dc235b108747": "Permite que los agentes usen el navegador compartido. Los proyectos pueden anularlo.", "ea5fed973bfc1aca": "Restablecer el acceso predeterminado al navegador al valor predeterminado", "19e1f74805f4a1fb": "Acceso de agentes al navegador", - "5511e975ba69f726": "Ordenador", "72cb818f86f74f1d": "Conecta el entorno seleccionado para configurar el uso del ordenador.", "3a989eeb48af4c84": "Elige un entorno para configurar el uso del ordenador en su host.", "c97c0f969ce80c8c": "No se pudo comprobar el uso del ordenador: {error}", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index bba268e42d085..c8b67c1f8fd11 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -1641,6 +1641,7 @@ "86a59f2432768c7f": "La zone de saisie est occupée ; réessayez quand elle sera prête.", "ddbd48554168bc6e": "Les messages des apps nécessitent un fil démarré.", "881cec6c80bb6477": "Impossible d’envoyer le message de l’app.", + "77069ea78dc20ef2": "Utilise votre ordinateur", "94d640e2a0d2e849": "Les discussions annexes ne peuvent pas lancer de discussions annexes.", "3208297e5c0ed324": "Les fils de sous-agents ne peuvent pas lancer de discussions annexes.", "cbf94e4eba3e039f": "Les discussions annexes ne sont pas encore prêtes. Réessayez dans un instant.", @@ -1655,6 +1656,7 @@ "0e974f4d7d582b12": "Envoi des commentaires", "abb59f572874d3b4": "Chargement des messages", "9c353040cc3010c4": "Préparation du worktree", + "f624d18fa6181f60": "Arrêter", "536ad0c3529ef1b3": "L’API Presse-papiers n’est pas disponible pour copier la commande.", "7e06782c1ee65b02": "Impossible de copier la commande dans le presse-papiers.", "61bc68e834fb83af": "Copier la commande", @@ -6197,6 +6199,10 @@ "cd312dae87fc794f": "L’annotation a été conservée sans la capture d’écran.", "4616fb6552fd8875": "La page ne s’est pas chargée. La sélection est indisponible tant que la page n’est pas affichée", "770d6036de8dbcb7": "Cet onglet est ouvert dans l’app desktop T3 Code.", + "5511e975ba69f726": "Ordinateur", + "1ef44b8f78119bba": "Aperçu flottant du contrôle de l’ordinateur", + "e60b3936c5e2190b": "Aperçu indisponible", + "65ba9047454a5170": "En attente de l’agent…", "b252602c8f71d6af": "Impossible de détacher l’aperçu", "0fc0a2ff438851b5": "Aperçu flottant du navigateur", "74892fefe58df8e3": "Fermer l’aperçu détaché", @@ -8340,7 +8346,6 @@ "a6a6dc235b108747": "Autorise les agents à utiliser le navigateur partagé. Les projets peuvent remplacer ce paramètre.", "ea5fed973bfc1aca": "Réinitialiser l’accès par défaut au navigateur à la valeur par défaut", "19e1f74805f4a1fb": "Accès des agents au navigateur", - "5511e975ba69f726": "Ordinateur", "72cb818f86f74f1d": "Connectez l’environnement sélectionné pour configurer le contrôle de l’ordinateur.", "3a989eeb48af4c84": "Choisissez un environnement pour configurer le contrôle de l’ordinateur sur son hôte.", "c97c0f969ce80c8c": "Impossible de vérifier le contrôle de l’ordinateur : {error}", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 84d8cf00a77e5..a811891165e2f 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -1640,6 +1640,7 @@ "86a59f2432768c7f": "入力欄がビジー状態です。準備ができてからもう一度お試しください。", "ddbd48554168bc6e": "アプリからのメッセージには開始済みのスレッドが必要です。", "881cec6c80bb6477": "アプリのメッセージを送信できませんでした。", + "77069ea78dc20ef2": "コンピューターを操作中", "94d640e2a0d2e849": "サイドチャットからサイドチャットは開始できません。", "3208297e5c0ed324": "サブエージェントのスレッドではサイドチャットを開始できません。", "cbf94e4eba3e039f": "サイドチャットの準備がまだできていません。しばらくしてからもう一度お試しください。", @@ -1654,6 +1655,7 @@ "0e974f4d7d582b12": "フィードバックを送信しています", "abb59f572874d3b4": "メッセージを読み込んでいます", "9c353040cc3010c4": "ワークツリーを準備しています", + "f624d18fa6181f60": "停止", "536ad0c3529ef1b3": "コマンドをコピーする際にクリップボード API を利用できませんでした。", "7e06782c1ee65b02": "コマンドをクリップボードにコピーできませんでした。", "61bc68e834fb83af": "コマンドをコピー", @@ -6169,6 +6171,10 @@ "cd312dae87fc794f": "注釈はスクリーンショットなしで保持されました。", "4616fb6552fd8875": "ページが読み込まれませんでした。ページが表示されるまで要素の選択は利用できません", "770d6036de8dbcb7": "このタブは T3 Code デスクトップアプリで開いています。", + "5511e975ba69f726": "コンピューター", + "1ef44b8f78119bba": "フローティングのコンピューター操作プレビュー", + "e60b3936c5e2190b": "プレビューを利用できません", + "65ba9047454a5170": "エージェントを待っています…", "b252602c8f71d6af": "プレビューをポップアウトできません", "0fc0a2ff438851b5": "フローティングのブラウザープレビュー", "74892fefe58df8e3": "ポップアウトしたプレビューを閉じる", @@ -8298,7 +8304,6 @@ "a6a6dc235b108747": "エージェントに共有ブラウザーの使用を許可します。プロジェクトごとに上書きできます。", "ea5fed973bfc1aca": "デフォルトのブラウザーアクセスをデフォルトにリセット", "19e1f74805f4a1fb": "エージェントのブラウザーアクセス", - "5511e975ba69f726": "コンピューター", "72cb818f86f74f1d": "コンピューター操作を設定するには、選択した環境に接続してください。", "3a989eeb48af4c84": "ホストでコンピューター操作を設定するには、環境を 1 つ選択してください。", "c97c0f969ce80c8c": "コンピューター操作を確認できませんでした: {error}", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 3b3a18ac89a0a..1682966484211 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -1640,6 +1640,7 @@ "86a59f2432768c7f": "입력창이 사용 중입니다. 준비되면 다시 시도하세요.", "ddbd48554168bc6e": "앱의 메시지를 받으려면 시작된 스레드가 필요합니다.", "881cec6c80bb6477": "앱의 메시지를 보낼 수 없습니다.", + "77069ea78dc20ef2": "컴퓨터를 사용하는 중", "94d640e2a0d2e849": "사이드 채팅에서는 사이드 채팅을 시작할 수 없습니다.", "3208297e5c0ed324": "서브에이전트 스레드에서는 사이드 채팅을 시작할 수 없습니다.", "cbf94e4eba3e039f": "사이드 채팅이 아직 준비되지 않았습니다. 잠시 후 다시 시도하세요.", @@ -1654,6 +1655,7 @@ "0e974f4d7d582b12": "피드백 보내는 중", "abb59f572874d3b4": "메시지 불러오는 중", "9c353040cc3010c4": "워크트리 준비 중", + "f624d18fa6181f60": "중지", "536ad0c3529ef1b3": "명령을 복사하는 중 클립보드 API를 사용할 수 없습니다.", "7e06782c1ee65b02": "명령을 클립보드에 복사하지 못했습니다.", "61bc68e834fb83af": "명령 복사", @@ -6168,6 +6170,10 @@ "cd312dae87fc794f": "주석은 스크린샷 없이 유지되었습니다.", "4616fb6552fd8875": "페이지가 로드되지 않았습니다. 페이지가 렌더링될 때까지 선택할 수 없습니다", "770d6036de8dbcb7": "이 탭은 T3 Code 데스크톱 앱에서 열려 있습니다.", + "5511e975ba69f726": "컴퓨터", + "1ef44b8f78119bba": "떠 있는 컴퓨터 사용 미리 보기", + "e60b3936c5e2190b": "미리 보기를 사용할 수 없음", + "65ba9047454a5170": "에이전트를 기다리는 중…", "b252602c8f71d6af": "미리 보기를 분리할 수 없습니다", "0fc0a2ff438851b5": "떠 있는 브라우저 미리 보기", "74892fefe58df8e3": "분리된 미리 보기 닫기", @@ -8301,7 +8307,6 @@ "a6a6dc235b108747": "에이전트가 공유 브라우저를 사용하도록 허용합니다. 프로젝트별로 재정의할 수 있습니다.", "ea5fed973bfc1aca": "기본 브라우저 액세스 기본값으로 재설정", "19e1f74805f4a1fb": "에이전트 브라우저 액세스", - "5511e975ba69f726": "컴퓨터", "72cb818f86f74f1d": "컴퓨터 사용을 구성하려면 선택한 환경을 연결하세요.", "3a989eeb48af4c84": "호스트에서 컴퓨터 사용을 구성하려면 환경 하나를 선택하세요.", "c97c0f969ce80c8c": "컴퓨터 사용을 확인할 수 없습니다: {error}", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 6789cf03f51af..36b717b596fed 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -1641,6 +1641,7 @@ "86a59f2432768c7f": "O editor de mensagens está ocupado; tente novamente quando estiver pronto.", "ddbd48554168bc6e": "Mensagens de apps precisam de uma thread iniciada.", "881cec6c80bb6477": "Não foi possível enviar a mensagem do app.", + "77069ea78dc20ef2": "Usando seu computador", "94d640e2a0d2e849": "Chats paralelos não podem iniciar chats paralelos.", "3208297e5c0ed324": "Threads de subagentes não podem iniciar chats paralelos.", "cbf94e4eba3e039f": "Os chats paralelos ainda não estão prontos. Tente novamente em instantes.", @@ -1655,6 +1656,7 @@ "0e974f4d7d582b12": "Enviando feedback", "abb59f572874d3b4": "Carregando mensagens", "9c353040cc3010c4": "Preparando o worktree", + "f624d18fa6181f60": "Parar", "536ad0c3529ef1b3": "A API da área de transferência não está disponível ao copiar o comando.", "7e06782c1ee65b02": "Falha ao copiar o comando para a área de transferência.", "61bc68e834fb83af": "Copiar comando", @@ -6196,6 +6198,10 @@ "cd312dae87fc794f": "A anotação foi mantida sem a captura de tela.", "4616fb6552fd8875": "A página não carregou. Escolher elementos fica indisponível até a página renderizar", "770d6036de8dbcb7": "Esta aba está aberta no app para desktop do T3 Code.", + "5511e975ba69f726": "Computador", + "1ef44b8f78119bba": "Pré-visualização flutuante do uso do computador", + "e60b3936c5e2190b": "Pré-visualização indisponível", + "65ba9047454a5170": "Aguardando o agente…", "b252602c8f71d6af": "Não foi possível destacar a pré-visualização", "0fc0a2ff438851b5": "Pré-visualização flutuante do navegador", "74892fefe58df8e3": "Fechar a pré-visualização destacada", @@ -8339,7 +8345,6 @@ "a6a6dc235b108747": "Permite que os agentes usem o navegador compartilhado. Os projetos podem substituir isso.", "ea5fed973bfc1aca": "Redefinir o acesso padrão ao navegador para o padrão", "19e1f74805f4a1fb": "Acesso dos agentes ao navegador", - "5511e975ba69f726": "Computador", "72cb818f86f74f1d": "Conecte o ambiente selecionado para configurar o uso do computador.", "3a989eeb48af4c84": "Escolha um ambiente para configurar o uso do computador no host dele.", "c97c0f969ce80c8c": "Não foi possível verificar o uso do computador: {error}", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index f0c740c0775f4..04fd4b36564bf 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -1641,6 +1641,7 @@ "86a59f2432768c7f": "Поле ввода занято; повторите, когда оно будет готово.", "ddbd48554168bc6e": "Для сообщений из приложений нужен начатый тред.", "881cec6c80bb6477": "Не удалось отправить сообщение приложения.", + "77069ea78dc20ef2": "Использует ваш компьютер", "94d640e2a0d2e849": "Из бокового чата нельзя начать боковой чат.", "3208297e5c0ed324": "Треды субагентов не могут начинать боковые чаты.", "cbf94e4eba3e039f": "Боковые чаты ещё не готовы. Повторите через мгновение.", @@ -1655,6 +1656,7 @@ "0e974f4d7d582b12": "Отправка отзыва", "abb59f572874d3b4": "Загрузка сообщений", "9c353040cc3010c4": "Подготовка рабочего дерева", + "f624d18fa6181f60": "Остановить", "536ad0c3529ef1b3": "API буфера обмена недоступен при копировании команды.", "7e06782c1ee65b02": "Не удалось скопировать команду в буфер обмена.", "61bc68e834fb83af": "Копировать команду", @@ -6196,6 +6198,10 @@ "cd312dae87fc794f": "Аннотация сохранена без скриншота.", "4616fb6552fd8875": "Страница не загрузилась. Выбор недоступен, пока страница не отрисуется", "770d6036de8dbcb7": "Эта вкладка открыта в десктопном приложении T3 Code.", + "5511e975ba69f726": "Компьютер", + "1ef44b8f78119bba": "Плавающий предпросмотр управления компьютером", + "e60b3936c5e2190b": "Предпросмотр недоступен", + "65ba9047454a5170": "Ожидание агента…", "b252602c8f71d6af": "Не удалось вынести предпросмотр", "0fc0a2ff438851b5": "Плавающий предпросмотр браузера", "74892fefe58df8e3": "Закрыть вынесенный предпросмотр", @@ -8341,7 +8347,6 @@ "a6a6dc235b108747": "Разрешить агентам использовать общий браузер. Проекты могут переопределить это.", "ea5fed973bfc1aca": "Сбросить доступ к браузеру к значению по умолчанию", "19e1f74805f4a1fb": "Доступ агентов к браузеру", - "5511e975ba69f726": "Компьютер", "72cb818f86f74f1d": "Подключите выбранное окружение, чтобы настроить управление компьютером.", "3a989eeb48af4c84": "Выберите одно окружение, чтобы настроить управление компьютером на его хосте.", "c97c0f969ce80c8c": "Не удалось проверить управление компьютером: {error}", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 9c9e5e647d577..0830f755540b1 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -1641,6 +1641,7 @@ "86a59f2432768c7f": "Inmatningsfältet är upptaget; försök igen när det är redo.", "ddbd48554168bc6e": "Meddelanden från appar kräver en startad tråd.", "881cec6c80bb6477": "Kunde inte skicka appens meddelande.", + "77069ea78dc20ef2": "Använder din dator", "94d640e2a0d2e849": "Sidochattar kan inte starta sidochattar.", "3208297e5c0ed324": "Subagenttrådar kan inte starta sidochattar.", "cbf94e4eba3e039f": "Sidochattar är inte redo än. Försök igen om en stund.", @@ -1655,6 +1656,7 @@ "0e974f4d7d582b12": "Skickar feedback", "abb59f572874d3b4": "Meddelanden läses in", "9c353040cc3010c4": "Förbereder worktree", + "f624d18fa6181f60": "Stoppa", "536ad0c3529ef1b3": "Urklipps-API:t är inte tillgängligt vid kopiering av kommandot.", "7e06782c1ee65b02": "Kunde inte kopiera kommandot till urklipp.", "61bc68e834fb83af": "Kopiera kommando", @@ -6198,6 +6200,10 @@ "cd312dae87fc794f": "Anteckningen behölls utan skärmbilden.", "4616fb6552fd8875": "Sidan lästes inte in. Välj är inte tillgängligt förrän sidan har renderats", "770d6036de8dbcb7": "Den här fliken är öppen i skrivbordsappen T3 Code.", + "5511e975ba69f726": "Dator", + "1ef44b8f78119bba": "Svävande förhandsvisning av datoranvändning", + "e60b3936c5e2190b": "Förhandsvisning är inte tillgänglig", + "65ba9047454a5170": "Väntar på agenten…", "b252602c8f71d6af": "Det gick inte att bryta ut förhandsvisningen", "0fc0a2ff438851b5": "Svävande webbläsarförhandsvisning", "74892fefe58df8e3": "Stäng utbruten förhandsvisning", @@ -8347,7 +8353,6 @@ "a6a6dc235b108747": "Låt agenter använda den delade webbläsaren. Projekt kan åsidosätta det.", "ea5fed973bfc1aca": "Återställ standardåtkomst för webbläsaren till standard", "19e1f74805f4a1fb": "Agenters webbläsaråtkomst", - "5511e975ba69f726": "Dator", "72cb818f86f74f1d": "Anslut den valda miljön för att konfigurera datoranvändning.", "3a989eeb48af4c84": "Välj en miljö för att konfigurera datoranvändning på dess värd.", "c97c0f969ce80c8c": "Det gick inte att kontrollera datoranvändning: {error}", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index d6db16b98275d..2056f2d76c083 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -1641,6 +1641,7 @@ "86a59f2432768c7f": "输入框正忙,请在就绪后重试。", "ddbd48554168bc6e": "来自应用的消息需要已开始的会话。", "881cec6c80bb6477": "无法发送应用的消息。", + "77069ea78dc20ef2": "正在使用你的计算机", "94d640e2a0d2e849": "侧聊中不能再开始侧聊。", "3208297e5c0ed324": "子智能体会话不能开始侧聊。", "cbf94e4eba3e039f": "侧聊尚未就绪,请稍后重试。", @@ -1655,6 +1656,7 @@ "0e974f4d7d582b12": "正在发送反馈", "abb59f572874d3b4": "正在加载消息", "9c353040cc3010c4": "正在准备工作树", + "f624d18fa6181f60": "停止", "536ad0c3529ef1b3": "复制命令时剪贴板 API 不可用。", "7e06782c1ee65b02": "无法将命令复制到剪贴板。", "61bc68e834fb83af": "复制命令", @@ -6204,6 +6206,10 @@ "cd312dae87fc794f": "标注已保留,但不含截图。", "4616fb6552fd8875": "页面未加载。在页面渲染前无法选取元素", "770d6036de8dbcb7": "此标签页已在 T3 Code 桌面应用中打开。", + "5511e975ba69f726": "计算机", + "1ef44b8f78119bba": "悬浮计算机操控预览", + "e60b3936c5e2190b": "预览不可用", + "65ba9047454a5170": "正在等待智能体…", "b252602c8f71d6af": "无法弹出预览", "0fc0a2ff438851b5": "悬浮浏览器预览", "74892fefe58df8e3": "关闭已弹出的预览", @@ -8357,7 +8363,6 @@ "a6a6dc235b108747": "允许智能体使用共享浏览器。项目可以覆盖此设置。", "ea5fed973bfc1aca": "重置默认浏览器访问权限为默认值", "19e1f74805f4a1fb": "智能体浏览器访问", - "5511e975ba69f726": "计算机", "72cb818f86f74f1d": "连接所选环境以配置计算机操控。", "3a989eeb48af4c84": "选择一个环境,以便在其主机上配置计算机操控。", "c97c0f969ce80c8c": "无法检查计算机操控:{error}", diff --git a/apps/web/src/previewMiniPlayerStore.ts b/apps/web/src/previewMiniPlayerStore.ts index bdbb9b1ca876f..38b22bf1318f8 100644 --- a/apps/web/src/previewMiniPlayerStore.ts +++ b/apps/web/src/previewMiniPlayerStore.ts @@ -20,7 +20,8 @@ export type PreviewMiniPlayerSource = readonly deviceId: string; readonly platform: DevicePlatform; readonly name: string; - }; + } + | { readonly kind: "computer" }; export interface PreviewMiniPlayerState { readonly source: PreviewMiniPlayerSource; @@ -49,11 +50,18 @@ interface PreviewMiniPlayerStoreState { } export function previewMiniPlayerSourceKey(source: PreviewMiniPlayerSource): string { - return source.kind === "browser" - ? `browser:${source.tabId}` - : `device:${encodeURIComponent(source.hostId)}:${encodeURIComponent(source.deviceId)}`; + switch (source.kind) { + case "browser": + return `browser:${source.tabId}`; + case "device": + return `device:${encodeURIComponent(source.hostId)}:${encodeURIComponent(source.deviceId)}`; + case "computer": + return "computer"; + } } +export const COMPUTER_MINI_PLAYER_SOURCE: PreviewMiniPlayerSource = { kind: "computer" }; + export const browserMiniPlayerSource = (tabId: string): PreviewMiniPlayerSource => ({ kind: "browser", tabId, diff --git a/apps/web/src/state/cua.ts b/apps/web/src/state/cua.ts new file mode 100644 index 0000000000000..7ebe5dbd6b519 --- /dev/null +++ b/apps/web/src/state/cua.ts @@ -0,0 +1,22 @@ +import { createCuaEnvironmentAtoms } from "@t3tools/client-runtime/state/cua"; +import type { CuaWindowPreviewState, ScopedThreadRef } from "@t3tools/contracts"; + +import { connectionAtomRuntime } from "../connection/runtime"; +import { useEnvironmentQuery } from "./query"; + +const cuaEnvironment = createCuaEnvironmentAtoms(connectionAtomRuntime); + +const IDLE: CuaWindowPreviewState = { status: "idle" }; + +/** Subscribes while mounted; the server captures only for mounted subscribers. */ +export function useCuaWindowPreview(threadRef: ScopedThreadRef | null): CuaWindowPreviewState { + const query = useEnvironmentQuery( + threadRef === null + ? null + : cuaEnvironment.windowPreview({ + environmentId: threadRef.environmentId, + input: { threadId: threadRef.threadId }, + }), + ); + return query.data ?? IDLE; +} diff --git a/docs/user/computer-use.md b/docs/user/computer-use.md index 991e3b27a2c88..f5214239fbc4d 100644 --- a/docs/user/computer-use.md +++ b/docs/user/computer-use.md @@ -35,7 +35,14 @@ before starting the server. If you already configured a `cua-driver` MCP server for Codex yourself, Codex keeps yours and T3 Code does not add a second one. -## What you see +## Watch the agent work Each action an agent takes shows in the thread with the app's icon and a plain title, such as **Clicked in Safari**. + +On the web and desktop, a floating card shows the window the agent is driving +and refreshes while the turn runs, then keeps the last frame. The card follows +**Auto-show floating preview** under **Settings → Browser**. Closing it +stops the capture until the agent's next action. If the host cannot capture +its screen, for example because Screen Recording is off on a Mac, the card +says why. diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index 736abada9a390..44eed70c29f9b 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -263,6 +263,10 @@ "types": "./src/state/device.ts", "default": "./src/state/device.ts" }, + "./state/cua": { + "types": "./src/state/cua.ts", + "default": "./src/state/cua.ts" + }, "./state/deviceHubAccess": { "types": "./src/state/deviceHubAccess.ts", "default": "./src/state/deviceHubAccess.ts" diff --git a/packages/client-runtime/src/rpc/client.ts b/packages/client-runtime/src/rpc/client.ts index 7c8f06cb1f083..47728fedec82f 100644 --- a/packages/client-runtime/src/rpc/client.ts +++ b/packages/client-runtime/src/rpc/client.ts @@ -76,6 +76,7 @@ export type EnvironmentSubscriptionRpcTag = | typeof WS_METHODS.subscribePreviewEvents | typeof WS_METHODS.subscribeDiscoveredLocalServers | typeof WS_METHODS.subscribeDeviceState + | typeof WS_METHODS.subscribeCuaWindowPreview | typeof WS_METHODS.subscribeResourceTelemetry | typeof WS_METHODS.pullRequestsSubscribeRefreshes | typeof WS_METHODS.pullRequestsSubscribeLinkedThreadRefreshes diff --git a/packages/client-runtime/src/state/cua.ts b/packages/client-runtime/src/state/cua.ts new file mode 100644 index 0000000000000..8ac30275f63ac --- /dev/null +++ b/packages/client-runtime/src/state/cua.ts @@ -0,0 +1,18 @@ +import { WS_METHODS } from "@t3tools/contracts"; +import { Atom } from "effect/reactivity"; + +import type { EnvironmentRegistry } from "../connection/registry.ts"; +import { createEnvironmentRpcSubscriptionAtomFamily } from "./runtime.ts"; + +export function createCuaEnvironmentAtoms( + runtime: Atom.AtomRuntime, +) { + return { + /** Live frames of the window the agent is driving; the server captures only while subscribed. */ + windowPreview: createEnvironmentRpcSubscriptionAtomFamily(runtime, { + label: "environment-data:cua:window-preview", + tag: WS_METHODS.subscribeCuaWindowPreview, + idleTtlMs: 1_000, + }), + }; +} diff --git a/packages/contracts/src/cua.ts b/packages/contracts/src/cua.ts index c0b97a7bd75b5..6d6f20535140f 100644 --- a/packages/contracts/src/cua.ts +++ b/packages/contracts/src/cua.ts @@ -1,6 +1,6 @@ import * as Schema from "effect/Schema"; -import { TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts"; /** Native host descriptor, confined to the desktop/server control pipe. */ export const CuaDriverMcpConfiguration = Schema.Struct({ @@ -12,6 +12,31 @@ export const CuaDriverMcpConfiguration = Schema.Struct({ }); export type CuaDriverMcpConfiguration = typeof CuaDriverMcpConfiguration.Type; +/** A window the agent is driving, refreshed for the user while a client watches. */ +export const CuaWindowPreviewFrame = Schema.Struct({ + appName: Schema.optionalKey(Schema.String), + windowTitle: Schema.optionalKey(Schema.String), + width: Schema.Number, + height: Schema.Number, + mimeType: Schema.String, + dataBase64: Schema.String, + capturedAt: Schema.String, +}); +export type CuaWindowPreviewFrame = typeof CuaWindowPreviewFrame.Type; + +export const CuaWindowPreviewState = Schema.Struct({ + status: Schema.Literals(["idle", "live", "unavailable"]), + /** Why no frame can be captured, for the client to show instead of a stale card. */ + detail: Schema.optionalKey(Schema.String), + frame: Schema.optionalKey(CuaWindowPreviewFrame), +}); +export type CuaWindowPreviewState = typeof CuaWindowPreviewState.Type; + +export const CuaWindowPreviewSubscribeInput = Schema.Struct({ + threadId: ThreadId, +}); +export type CuaWindowPreviewSubscribeInput = typeof CuaWindowPreviewSubscribeInput.Type; + export const DesktopCuaDriverRequest = Schema.Struct({ version: Schema.Literal(1), type: Schema.Literal("cuaDriverRequest"), diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index b2e446ba5fc19..0b14cea10a9c7 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -337,7 +337,7 @@ import { DeviceSession, DeviceShutdownInput, } from "./device.ts"; -import { CuaHostStatus } from "./cua.ts"; +import { CuaHostStatus, CuaWindowPreviewState, CuaWindowPreviewSubscribeInput } from "./cua.ts"; import { ServerConfigStreamEvent, DesktopUpdateCommitInput, @@ -666,6 +666,7 @@ export const WS_METHODS = { subscribePreviewEvents: "subscribePreviewEvents", subscribeDiscoveredLocalServers: "subscribeDiscoveredLocalServers", subscribeDeviceState: "subscribeDeviceState", + subscribeCuaWindowPreview: "subscribeCuaWindowPreview", subscribeServerConfig: "subscribeServerConfig", subscribeServerLifecycle: "subscribeServerLifecycle", subscribeAuthAccess: "subscribeAuthAccess", @@ -1951,6 +1952,13 @@ const WsSubscribeDeviceStateRpc = Rpc.make(WS_METHODS.subscribeDeviceState, { stream: true, }); +const WsSubscribeCuaWindowPreviewRpc = Rpc.make(WS_METHODS.subscribeCuaWindowPreview, { + payload: CuaWindowPreviewSubscribeInput, + success: CuaWindowPreviewState, + error: EnvironmentAuthorizationError, + stream: true, +}); + const WsOrchestrationV2DispatchCommandRpc = Rpc.make(ORCHESTRATION_V2_WS_METHODS.dispatchCommand, { payload: OrchestrationV2RpcSchemas.dispatchCommand.input, success: OrchestrationV2RpcSchemas.dispatchCommand.output, @@ -2462,6 +2470,7 @@ export const WsRpcGroup = RpcGroup.make( WsDeviceDetailRpc, WsDeviceActionRpc, WsSubscribeDeviceStateRpc, + WsSubscribeCuaWindowPreviewRpc, WsSubscribeServerConfigRpc, WsSubscribeServerLifecycleRpc, WsSubscribeAuthAccessRpc,