import * as Clock from "effect/Clock" import * as Context from "effect/Context" import * as Effect from "effect/Effect" import * as Option from "effect/Option" import * as Schema from "effect/Schema" import type { RpcClientError } from "effect/rpc" import { supportsCapability, type UiConnection, } from "../simulation/connector.js" import { Frontend } from "../client/protocol.js" import type { SimulationRequestError } from "../simulation/rpc.js" import { mediaDirectory } from "../instance/media.js" import { renderScreenshot } from "./screenshot.js" import { appendKeypress, formatArrow, formatPress, loadRecentKeypresses, } from "../recording/keypresses.js" export interface WaitOptions { /** Maximum wait in milliseconds. Defaults to 5,000. */ readonly timeout?: number /** Poll interval in milliseconds. Defaults to 50. */ readonly interval?: number } export interface ElementQuery { readonly id?: string readonly num?: number readonly focusable?: boolean readonly focused?: boolean readonly clickable?: boolean readonly editor?: boolean } export type SemanticQuery = Partial export type Position = Pick export type Predicate = (state: Frontend.State) => boolean export type EffectPredicate = ( state: Frontend.State, ) => Effect.Effect /** * A UI RPC did not answer within the request timeout: the control plane is * unresponsive. Script runs treat this as fatal. */ export class UiTimeoutError extends Schema.TaggedError()( "UiTimeoutError", { operation: Schema.String, milliseconds: Schema.Number, message: Schema.String, frame: Schema.optionalKey(Frontend.CapturedFrame), }, ) {} /** * A wait (`waitFor`, `getElement`, `getNode`) reached its deadline without the * UI matching. The control plane stayed responsive; scripts may catch this to * branch on "did X appear in time?". */ export class UiWaitTimeoutError extends Schema.TaggedError()( "UiWaitTimeoutError", { operation: Schema.String, milliseconds: Schema.Number, message: Schema.String, frame: Schema.optionalKey(Frontend.CapturedFrame), }, ) {} export class UiElementAmbiguousError extends Schema.TaggedError()( "UiElementAmbiguousError", { count: Schema.Number, }, ) { override get message() { return `ui.getElement matched ${this.count} elements` } } export class UiNodeAmbiguousError extends Schema.TaggedError()( "UiNodeAmbiguousError", { count: Schema.Number, }, ) { override get message() { return `ui.getNode matched ${this.count} semantic nodes` } } export class UiCapabilityError extends Schema.TaggedError()( "UiCapabilityError", { capability: Schema.Literals(["ui.snapshot", "ui.click.semantic", "ui.mouse"]), message: Schema.String, }, ) {} export class UiWaitOptionsError extends Schema.TaggedError()( "UiWaitOptionsError", { field: Schema.Literals(["timeout", "interval"]), value: Schema.Number, message: Schema.String, }, ) {} export class UiPredicateError extends Schema.TaggedError()( "UiPredicateError", { cause: Schema.Defect(), message: Schema.String, }, ) {} export class UiScreenshotError extends Schema.TaggedError()( "UiScreenshotError", { cause: Schema.Defect(), message: Schema.String, }, ) {} export class UiPressError extends Schema.TaggedError()( "UiPressError", { key: Schema.String, message: Schema.String, }, ) {} export interface Options { /** Per-RPC timeout in milliseconds. Defaults to 30,000. */ readonly requestTimeout?: number /** Directory where Drive writes locally rendered screenshots. */ readonly screenshotDirectory?: string /** Recording timeline used for the optional KeyCastr-style overlay. */ readonly keypressTimeline?: string } const RequestTimeout = Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0)) export type WaitError = UiWaitTimeoutError | UiWaitOptionsError type RpcError = SimulationRequestError | RpcClientError.RpcClientError export type OperationError = RpcError | UiTimeoutError export type PressError = OperationError | UiPressError export type ScreenshotError = OperationError | UiScreenshotError export type SemanticOperationError = OperationError | UiCapabilityError export interface Ui { readonly state: () => Effect.Effect readonly snapshot: () => Effect.Effect readonly capture: () => Effect.Effect readonly matches: (text: string) => Effect.Effect readonly screenshot: ( name?: string, ) => Effect.Effect readonly type: (text: string) => Effect.Effect readonly press: ( key: string, modifiers?: Frontend.KeyModifiers, ) => Effect.Effect readonly enter: () => Effect.Effect readonly arrow: ( direction: Frontend.ArrowParams["direction"], ) => Effect.Effect readonly focus: ( target: number | Frontend.Element, ) => Effect.Effect /** Send real terminal mouse input at zero-based absolute cell coordinates. */ readonly mouse: ( params: Frontend.MouseParams, ) => Effect.Effect readonly click: ( target: number | Frontend.Element | Frontend.SemanticNode, position?: Position, ) => Effect.Effect< Frontend.State, OperationError | UiCapabilityError | UiElementAmbiguousError | WaitError > readonly resize: ( viewport: Frontend.ResizeParams, ) => Effect.Effect readonly submit: ( text: string, ) => Effect.Effect readonly waitFor: ( target: string | Predicate | EffectPredicate, options?: WaitOptions, ) => Effect.Effect< Frontend.State, OperationError | WaitError | UiPredicateError | E > readonly getElement: ( target: number | string | ElementQuery, options?: WaitOptions, ) => Effect.Effect< Frontend.Element, OperationError | WaitError | UiElementAmbiguousError > readonly getNode: ( target: string | SemanticQuery, options?: WaitOptions, ) => Effect.Effect< Frontend.SemanticNode, SemanticOperationError | WaitError | UiNodeAmbiguousError > } interface Control extends Ui { readonly finishRecording: () => Effect.Effect } export interface Transform { (effect: Effect.Effect): Effect.Effect } /** Applies one Effect transformation to every operation without changing the UI interface. */ export const transform = (ui: Ui, apply: Transform): Ui => ({ state: () => apply(ui.state()), snapshot: () => apply(ui.snapshot()), capture: () => apply(ui.capture()), matches: (text) => apply(ui.matches(text)), screenshot: (name) => apply(ui.screenshot(name)), type: (text) => apply(ui.type(text)), press: (key, modifiers) => apply(ui.press(key, modifiers)), enter: () => apply(ui.enter()), arrow: (direction) => apply(ui.arrow(direction)), focus: (target) => apply(ui.focus(target)), mouse: (params) => apply(ui.mouse(params)), click: (target, position) => apply(ui.click(target, position)), resize: (viewport) => apply(ui.resize(viewport)), submit: (text) => apply(ui.submit(text)), waitFor: (target, options) => apply(ui.waitFor(target, options)), getElement: (target, options) => apply(ui.getElement(target, options)), getNode: (target, options) => apply(ui.getNode(target, options)), }) interface ActivePoll { readonly connection: UiConnection readonly attempt: ( operation: string, effect: Effect.Effect, ) => Effect.Effect, E | UiTimeoutError> readonly sleep: () => Effect.Effect } const CurrentPoll = Context.Reference( "opencode-drive/UiPoll", { defaultValue: () => undefined }, ) export const make = (connection: UiConnection, options?: Options): Control => { const requestTimeout = RequestTimeout.make(options?.requestTimeout ?? 30_000) const evidenceTimeout = Math.min(requestTimeout, 1_000) const { rpc } = connection const timeoutError = (operation: string) => new UiTimeoutError({ operation, milliseconds: requestTimeout, message: `ui.${operation} timed out after ${requestTimeout}ms`, }) const call = ( operation: string, effect: Effect.Effect, ): Effect.Effect => Effect.timeoutOrElse(effect, { duration: requestTimeout, orElse: () => Effect.fail(timeoutError(operation)), }) // OpenCode can drop a screen-read reply (for example when reading the buffer // races a render), so inside a poll we bound and retry read-only RPCs while // keeping consecutive unanswered time bounded by requestTimeout. const read = ( operation: string, effect: Effect.Effect, ): Effect.Effect => Effect.flatMap(CurrentPoll, (active) => { if (active === undefined || active.connection !== connection) { return call(operation, effect) } return Effect.gen(function* () { while (true) { const result = yield* active.attempt(operation, effect) if (Option.isSome(result)) return result.value yield* active.sleep() } }) }) const ensureSnapshot = Effect.suspend(() => supportsCapability(connection.compatibility, "ui.snapshot") ? Effect.void : Effect.fail( new UiCapabilityError({ capability: "ui.snapshot", message: "ui.snapshot is not available on this OpenCode endpoint", }), ), ) const state = Effect.fn("Ui.state")(() => read("state", rpc["ui.state"]())) const snapshot = Effect.fn("Ui.snapshot")(() => Effect.andThen(ensureSnapshot, read("snapshot", rpc["ui.snapshot"]())), ) const capture = Effect.fn("Ui.capture")(() => call("capture", rpc["ui.capture"]()), ) const matches = Effect.fn("Ui.matches")((text: string) => read("matches", rpc["ui.matches"]({ text })), ) const screenshot = Effect.fn("Ui.screenshot")(function* (name?: string) { const frame = yield* capture() const keys = options?.keypressTimeline ? yield* Effect.promise(() => loadRecentKeypresses(options.keypressTimeline!)) : [] return yield* Effect.tryPromise({ try: () => renderScreenshot(frame, options?.screenshotDirectory ?? mediaDirectory(), name, keys), catch: (cause) => new UiScreenshotError({ cause, message: cause instanceof Error ? cause.message : String(cause), }), }) }) const finishRecording = Effect.fn("Ui.finishRecording")(() => call("finishRecording", rpc["ui.recording.finish"]()), ) const type = Effect.fn("Ui.type")((text: string) => call("type", rpc["ui.type"]({ text })), ) const recordKeypress = (label: string) => options?.keypressTimeline ? Effect.promise(() => appendKeypress(options.keypressTimeline!, label)) : Effect.void const press = Effect.fn("Ui.press")(function* ( key: string, modifiers?: Frontend.KeyModifiers, ) { if (/^(?:alt|cmd|ctrl|meta|mod|shift)\+/i.test(key)) return yield* Effect.fail(new UiPressError({ key, message: `ui.press key must not contain chord syntax; pass modifiers separately (for example, ui.press("u", { ctrl: true }))`, })) const result = yield* call("press", rpc["ui.press"](Frontend.pressParams(key, modifiers))) yield* recordKeypress(formatPress(key, modifiers)) return result }) const enter = Effect.fn("Ui.enter")(() => call("enter", rpc["ui.enter"]()).pipe( Effect.tap(() => recordKeypress("Enter")), ), ) const arrow = Effect.fn("Ui.arrow")( (direction: Frontend.ArrowParams["direction"]) => call("arrow", rpc["ui.arrow"]({ direction })).pipe( Effect.tap(() => recordKeypress(formatArrow(direction))), ), ) const focus = Effect.fn("Ui.focus")((target: number | Frontend.Element) => call( "focus", rpc["ui.focus"]({ target: typeof target === "number" ? target : target.num, }), ), ) const resize = Effect.fn("Ui.resize")((viewport: Frontend.ResizeParams) => call("resize", rpc["ui.resize"](viewport)), ) const mouse = Effect.fn("Ui.mouse")(function* (params: Frontend.MouseParams) { if (!supportsCapability(connection.compatibility, "ui.mouse")) return yield* Effect.fail(new UiCapabilityError({ capability: "ui.mouse", message: "ui.mouse is not available on this OpenCode endpoint", })) return yield* call("mouse", rpc["ui.mouse"](params)) }) const submit = Effect.fn("Ui.submit")(function* (text: string) { yield* type(text) return yield* enter() }) const pollingTimeout = ( operation: string, milliseconds: number, message: string, ) => rpc["ui.capture"]().pipe( Effect.timeoutOrElse({ duration: evidenceTimeout, orElse: () => Effect.succeed(undefined), }), Effect.catchCause(() => Effect.succeed(undefined)), Effect.flatMap((frame) => Effect.fail( new UiWaitTimeoutError({ operation, milliseconds, message, ...(frame === undefined ? {} : { frame }), }), ), ), ) const poll = ( operation: string, step: (active: ActivePoll) => Effect.Effect, options: WaitOptions | undefined, message: string, ): Effect.Effect => { const timeout = options?.timeout ?? 5_000 const interval = options?.interval ?? 50 const validate = Effect.gen(function* () { if (!Number.isFinite(timeout) || timeout < 0) { yield* Effect.fail( new UiWaitOptionsError({ field: "timeout", value: timeout, message: "ui wait timeout must be a finite non-negative number", }), ) } if (!Number.isFinite(interval) || interval <= 0) { yield* Effect.fail( new UiWaitOptionsError({ field: "interval", value: interval, message: "ui wait interval must be a finite positive number", }), ) } }) return Effect.gen(function* () { yield* validate const clock = yield* Clock.Clock const now = () => Number(clock.monotonicTimeNanosUnsafe()) / 1_000_000 const startedAt = now() const baseAttemptTimeout = requestTimeout === 0 ? 0 : Math.min( requestTimeout, Math.max( 1, Math.min( requestTimeout / 2, timeout > 0 ? timeout / 2 : 250, 250, ), ), ) let nextAttemptTimeout = baseAttemptTimeout let unansweredSince: number | undefined let unansweredOperation = operation const onReply = () => { unansweredSince = undefined nextAttemptTimeout = baseAttemptTimeout } const active: ActivePoll = { connection, attempt: (rpcOperation, effect) => Effect.gen(function* () { if (requestTimeout === 0) { return yield* Effect.fail(timeoutError(rpcOperation)) } const attemptStart = now() const remainingRequest = unansweredSince === undefined ? requestTimeout : requestTimeout - (attemptStart - unansweredSince) if (remainingRequest <= 0) { return yield* Effect.fail(timeoutError(rpcOperation)) } const remainingWait = timeout - (attemptStart - startedAt) if (remainingWait <= 0) { return Option.none() } const duration = Math.min( nextAttemptTimeout, remainingRequest, remainingWait, ) const exhaustsRequest = duration >= remainingRequest && remainingRequest <= remainingWait const outcome = yield* effect.pipe( Effect.tap(() => Effect.sync(onReply)), Effect.tapError(() => Effect.sync(onReply)), Effect.timeoutOption(duration), ) if (Option.isSome(outcome)) { return outcome } unansweredSince = unansweredSince === undefined ? attemptStart : Math.min(unansweredSince, attemptStart) unansweredOperation = rpcOperation nextAttemptTimeout = Math.min(requestTimeout, nextAttemptTimeout * 2) if (exhaustsRequest || now() - unansweredSince >= requestTimeout) { return yield* Effect.fail(timeoutError(rpcOperation)) } return Option.none() }), sleep: () => Effect.suspend(() => { if (unansweredSince === undefined) { return Effect.sleep(interval) } const remainingRequest = requestTimeout - (now() - unansweredSince) if (remainingRequest <= 0) { return Effect.fail(timeoutError(unansweredOperation)) } return Effect.sleep( Math.min(interval, Math.max(1, remainingRequest / 2)), ) }), } return yield* Effect.gen(function* () { while (true) { const value = yield* step(active) if (value !== undefined) return value yield* active.sleep() } }).pipe( Effect.timeoutOrElse({ duration: timeout, orElse: () => pollingTimeout(operation, timeout, message), }), ) }) } const waitFor = Effect.fn("Ui.waitFor")( ( target: string | Predicate | EffectPredicate, options?: WaitOptions, ) => poll( "waitFor", (active) => typeof target === "string" ? Effect.gen(function* () { const matched = yield* active.attempt( "matches", rpc["ui.matches"]({ text: target }), ) if (Option.isNone(matched) || !matched.value) return undefined return Option.getOrUndefined( yield* active.attempt("state", rpc["ui.state"]()), ) }) : Effect.gen(function* () { const current = yield* active.attempt( "state", rpc["ui.state"](), ) if (Option.isNone(current)) return undefined const matched = yield* Effect.provideService( predicateEffect(target, current.value), CurrentPoll, active, ) return matched ? current.value : undefined }), options, typeof target === "string" ? `timed out waiting for the UI to match ${JSON.stringify(target)}` : "timed out waiting for the UI to match", ), ) const getElement = Effect.fn("Ui.getElement")( (target: number | string | ElementQuery, options?: WaitOptions) => poll( "getElement", (active) => Effect.flatMap( active.attempt("state", rpc["ui.state"]()), (current) => { if (Option.isNone(current)) return Effect.succeed(undefined) const elements = current.value.elements.filter((element) => typeof target === "number" ? element.num === target : typeof target === "string" ? element.id === target : matchesQuery(element, target), ) if (elements.length > 1) return Effect.fail( new UiElementAmbiguousError({ count: elements.length }), ) return Effect.succeed(elements[0]) }, ), options, "timed out waiting for the UI element", ), ) const getNode = Effect.fn("Ui.getNode")( (target: string | SemanticQuery, options?: WaitOptions) => poll( "getNode", (active) => Effect.andThen( ensureSnapshot, Effect.flatMap( active.attempt("snapshot", rpc["ui.snapshot"]()), (current) => { if (Option.isNone(current)) return Effect.succeed(undefined) const nodes = current.value.nodes.filter((node) => typeof target === "string" ? node.id === target : matchesQuery(node, target), ) if (nodes.length > 1) return Effect.fail( new UiNodeAmbiguousError({ count: nodes.length }), ) return Effect.succeed(nodes[0]) }, ), ), options, "timed out waiting for the semantic UI node", ), ) const click = Effect.fn("Ui.click")(function* ( target: number | Frontend.Element | Frontend.SemanticNode, position?: Position, ) { if (typeof target !== "number" && "element" in target) { if (!supportsCapability(connection.compatibility, "ui.click.semantic")) return yield* Effect.fail( new UiCapabilityError({ capability: "ui.click.semantic", message: "semantic ui.click is not available on this OpenCode endpoint", }), ) const element = position === undefined ? (yield* state()).elements.find((candidate) => candidate.num === target.element) : undefined return yield* call( "click", rpc["ui.click"]({ target: target.element, x: position?.x ?? (element === undefined ? 0 : Math.floor(element.width / 2)), y: position?.y ?? (element === undefined ? 0 : Math.floor(element.height / 2)), semantic: { id: target.id, ...(target.instance === undefined ? {} : { instance: target.instance }), element: target.element, }, }), ) } const element = typeof target === "number" ? yield* getElement(target) : target return yield* call( "click", rpc["ui.click"]({ target: element.num, x: position?.x ?? Math.floor(element.width / 2), y: position?.y ?? Math.floor(element.height / 2), }), ) }) return { state, snapshot, capture, matches, screenshot, finishRecording, type, press, enter, arrow, focus, mouse, click, resize, submit, waitFor, getElement, getNode, } } function predicateEffect( predicate: Predicate | EffectPredicate, state: Frontend.State, ): Effect.Effect { return Effect.gen(function* () { const result = yield* Effect.try({ try: () => predicate(state), catch: (cause) => new UiPredicateError({ cause, message: `ui.waitFor predicate failed: ${cause instanceof Error ? cause.message : String(cause)}`, }), }) const value: unknown = Effect.isEffect(result) ? yield* result : result if (typeof value === "boolean") return value return yield* Effect.fail( new UiPredicateError({ cause: value, message: "ui.waitFor predicate must return a boolean or Effect", }), ) }) } function matchesQuery(value: Value, query: Partial) { return Object.entries(query).every( ([key, expected]) => expected === undefined || Reflect.get(value, key) === expected, ) } export * as OpenCodeUi from "./ui.js"