fix(plugin-browser): drive browser attachments through one state machine (#61985)

This commit is contained in:
Luke Parker
2026-11-05 00:56:59 -06:00
committed by GitHub
Unverified
parent 1a1993e4eb
commit dd39237ddf
4 changed files with 1466 additions and 175 deletions
+150
View File
@@ -0,0 +1,150 @@
import { expect } from "bun:test"
import { Context, Deferred, Effect, Fiber, Layer, Stream } from "effect"
import { Browser } from "@opencode/plugin-browser/rpc"
import type { Permission } from "@opencode/schema/permission"
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
import { LayerNode } from "@opencode/util/effect/layer-node"
import { Global } from "@opencode/util/global"
import { Bus } from "@opencode/core/bus"
import { Database } from "@opencode/core/database/database"
import { Location } from "@opencode/core/location"
import { LocationServiceMap } from "@opencode/core/location-services"
import { Plugin } from "@opencode/core/plugin"
import { Rpc } from "@opencode/core/rpc"
import { AbsolutePath } from "@opencode/core/schema"
import { Session } from "@opencode/core/session"
import { tempGlobalLayer } from "./fixture/global"
import { offlineModels } from "./fixture/models"
import { tmpdirScoped } from "./fixture/tmpdir"
import { testEffect } from "./lib/effect"
// The browser plugin's `session.permissions` writes, as the test orders them.
const writes: {
/**
* While set, a revoke reads the session, then waits until a grant has written; that grant waits until the revoke has
* read. This is the interleaving that loses a replacement's grant to its predecessor's stale revoke.
*/
race?: { readonly revokeRead: Deferred.Deferred<void>; readonly granted: Deferred.Deferred<void> }
/** Completes when a revoke write finishes. */
revoked: Deferred.Deferred<void>
} = { revoked: Deferred.makeUnsafe() }
const isGrant = (permissions: Permission.Ruleset) =>
permissions.some((rule) => rule.action === "browser" && rule.effect === "allow")
const orderedWrites = Session.node.replace(
Session.node.mapLayer((base) =>
Layer.effect(
Session.Service,
Effect.map(Session.Service, (sessions) =>
Session.Service.of({
...sessions,
setPermissions: (input) => {
const race = writes.race
if (isGrant(input.permissions))
return race
? Deferred.await(race.revokeRead).pipe(
Effect.andThen(sessions.setPermissions(input)),
Effect.ensuring(Deferred.succeed(race.granted, undefined)),
)
: sessions.setPermissions(input)
const revoked = writes.revoked
return (
race
? Deferred.succeed(race.revokeRead, undefined).pipe(
Effect.andThen(Deferred.await(race.granted)),
Effect.andThen(sessions.setPermissions(input)),
)
: sessions.setPermissions(input)
).pipe(Effect.ensuring(Deferred.succeed(revoked, undefined)))
},
}),
),
).pipe(Layer.provide(base)),
),
)
const it = testEffect(
AppNodeBuilder.build(LayerNode.group([Database.node, Bus.node, Session.node, LocationServiceMap.node]), [
Global.node.replace(tempGlobalLayer),
offlineModels,
orderedWrites,
]),
)
const user = { action: "bash", resource: "*", effect: "ask" } as const
const allows = [
{ action: "browser", resource: "*", effect: "allow" },
{ action: "skill", resource: "browser", effect: "allow" },
] as const
const setup = Effect.gen(function* () {
writes.race = undefined
writes.revoked = Deferred.makeUnsafe()
const dir = yield* tmpdirScoped()
const ref = Location.Ref.make({ directory: AbsolutePath.make(dir.path) })
const locations = yield* LocationServiceMap.Service
const context = yield* locations.contextEffect(ref).pipe(Effect.scoped)
yield* Plugin.awaitActivation.pipe(Effect.provideContext(context))
const sessions = yield* Session.Service
const session = yield* sessions.create({ location: ref, permissions: [user] })
const rpc = Context.get(context, Rpc.Service).client(Browser.Definition)
const handshakes = new Map<string, Deferred.Deferred<void>>()
const handshake = (connectionID: string) => {
const existing = handshakes.get(connectionID)
if (existing) return existing
const created = Deferred.makeUnsafe<void>()
handshakes.set(connectionID, created)
return created
}
yield* rpc.events.subscribe("control").pipe(
Stream.runForEach((event) =>
event.data.type === "attached" ? Deferred.succeed(handshake(event.data.connectionID), undefined) : Effect.void,
),
Effect.forkScoped({ startImmediately: true }),
)
return {
ref,
locations,
attach: (connectionID: string) =>
rpc.attach({ sessionID: session.id, connectionID, version: 4 }).pipe(Effect.forkScoped),
attached: (connectionID: string) => Deferred.await(handshake(connectionID)).pipe(Effect.timeout("10 seconds")),
permissions: Effect.map(sessions.get(session.id), (info) => info.permissions ?? []),
}
})
it.live("a replaced attachment's revoke never removes its replacement's grant", () =>
Effect.gen(function* () {
const browser = yield* setup
const first = yield* browser.attach("conn_1")
yield* browser.attached("conn_1")
expect(yield* browser.permissions).toEqual([user, ...allows])
const race = { revokeRead: Deferred.makeUnsafe<void>(), granted: Deferred.makeUnsafe<void>() }
writes.race = race
const second = yield* browser.attach("conn_2")
expect(yield* Fiber.join(first)).toBe("replaced")
yield* browser.attached("conn_2")
// A revoke for conn_1, if one ran, was held until conn_2's grant wrote; let it land before reading.
if (yield* Deferred.isDone(race.revokeRead)) yield* Deferred.await(writes.revoked)
expect(yield* browser.permissions).toEqual([user, ...allows])
writes.race = undefined
writes.revoked = Deferred.makeUnsafe()
yield* Fiber.interrupt(second)
yield* Deferred.await(writes.revoked).pipe(Effect.timeout("10 seconds"))
expect(yield* browser.permissions).toEqual([user])
}),
)
it.live("disposing the plugin revokes the browser rules before the location finishes closing", () =>
Effect.gen(function* () {
const browser = yield* setup
yield* browser.attach("conn_1")
yield* browser.attached("conn_1")
expect(yield* browser.permissions).toEqual([user, ...allows])
yield* browser.locations.invalidate(browser.ref)
expect(yield* browser.permissions).toEqual([user])
}),
)
+191 -175
View File
@@ -4,17 +4,14 @@ import type { Context } from "@opencode/plugin/effect/plugin"
import type { RpcRegistration } from "@opencode/plugin/effect/rpc"
import type { Session } from "@opencode/schema/session"
import { Tool } from "@opencode/schema/tool"
import { Deferred, Effect, Schema, Stream } from "effect"
import { Cause, Deferred, Duration, Effect, Exit, Option, Schema, Scope, Semaphore, Stream } from "effect"
import { BrowserMachine } from "./machine.js"
import { Browser } from "./rpc.js"
import { BrowserSkill } from "./skill.js"
import { BrowserTunnel } from "./tunnel.js"
type Attachment = {
connectionID: string
state: Browser.State
closed: Deferred.Deferred<"closed" | "replaced">
pending: Map<string, { command: Browser.Command; result: Deferred.Deferred<Browser.Result, Tool.Error> }>
tunnels: BrowserTunnel.Tunnels
readonly closed: Deferred.Deferred<"closed" | "replaced", "unavailable">
readonly tunnels: BrowserTunnel.Tunnels
}
export type Connection = Effect.Success<ReturnType<typeof make>>
@@ -22,69 +19,101 @@ export type Connection = Effect.Success<ReturnType<typeof make>>
export const make = Effect.fn("BrowserConnection.make")(function* (
ctx: Pick<Context, "agent" | "rpc" | "session" | "location" | "event">,
) {
const browsers = new Map<Session.ID, Attachment>()
// The browser tools and their skill, which an attachment allows together.
const access = [
{ action: "browser", resource: "*" },
{ action: "skill", resource: BrowserSkill.id },
] as const
// Appended after config, so every agent hides the browser until an attachment allows it.
yield* ctx.agent.transform((editor) =>
editor
.list()
.forEach((agent) => agent.permissions.push(...access.map((rule) => ({ ...rule, effect: "deny" as const })))),
)
// Each attachment adds and removes its own allows, so a replaced attachment keeps the new one's.
const grant = (sessionID: Session.ID) =>
Effect.acquireRelease(
ctx.session.get({ sessionID }).pipe(
Effect.flatMap((session) =>
ctx.session.update({
sessionID,
permissions: [
...(session.permissions ?? []),
...access.map((rule) => ({ ...rule, effect: "allow" as const })),
],
}),
),
Effect.orDie,
.forEach((agent) =>
agent.permissions.push(...BrowserMachine.ACCESS.map((rule) => ({ ...rule, effect: "deny" as const }))),
),
() =>
ctx.session.get({ sessionID }).pipe(
Effect.flatMap((session) => {
const current = session.permissions ?? []
const permissions = access.reduce((rules, allow) => {
const index = rules.findIndex(
(rule) => rule.action === allow.action && rule.resource === allow.resource && rule.effect === "allow",
)
return index === -1 ? rules : rules.toSpliced(index, 1)
}, current)
if (permissions.length === current.length) return Effect.void
return ctx.session.update({ sessionID, permissions })
}),
Effect.ignore,
),
)
let active = true
const close = (sessionID: Session.ID, reason: "closed" | "replaced" = "closed") =>
Effect.gen(function* () {
const browser = browsers.get(sessionID)
if (!browser) return
browsers.delete(sessionID)
browser.tunnels.dispose()
yield* Deferred.succeed(browser.closed, reason)
)
// Permission syncs run here. Registered first, so it closes last: after disposal has drained the revokes.
const work = yield* Scope.make()
yield* Effect.addFinalizer((exit) => Scope.close(work, exit))
const machine = { state: BrowserMachine.createConnectionState() }
const attachments = new Map<number, Attachment>()
const requests = new Map<string, Deferred.Deferred<Browser.Result, Tool.Error>>()
const drained = Deferred.makeUnsafe<void>()
// One event at a time, effects included, so controls reach the bus in transition order: `attached` before any
// `command` of that attachment.
const lock = Semaphore.makeUnsafe(1)
const step = (event: BrowserMachine.ConnectionEvent): Effect.Effect<void> =>
Effect.suspend(() => {
const next = BrowserMachine.transitionConnection(machine.state, event)
machine.state = next.state
return Effect.forEach(
next.effects,
(effect) =>
perform(effect).pipe(Effect.catchCause((cause) => Effect.logWarning("Browser effect failed", cause))),
{ discard: true },
)
})
yield* Effect.addFinalizer(() => {
active = false
return Effect.forEach(browsers.keys(), (id) => close(id), { discard: true })
})
const dispatch = (event: BrowserMachine.ConnectionEvent) => lock.withPermit(step(event))
const perform = (effect: BrowserMachine.ConnectionEffect): Effect.Effect<void, unknown> => {
if (effect.type === "sync-permissions") return Effect.asVoid(Effect.forkIn(syncPermissions(effect), work))
if (effect.type === "close-attachment")
return Effect.suspend(() => {
const attachment = attachments.get(effect.attempt)
if (!attachment) return Effect.void
attachments.delete(effect.attempt)
attachment.tunnels.dispose()
return Deferred.done(
attachment.closed,
effect.outcome === "unavailable" ? Exit.fail(effect.outcome) : Exit.succeed(effect.outcome),
).pipe(Effect.asVoid)
})
if (effect.type === "emit-control") return rpc.events.emit("control", effect.control)
if (effect.type === "dispatch-command")
return (
rpc.events
.emit("control", { type: "command", connectionID: effect.connectionID, requestID: effect.requestID })
// Already inside the lock, so the failure steps directly.
.pipe(Effect.catch((error) => step({ ...effect, type: "request.dispatch-failed", error })))
)
if (effect.type === "settle-request")
return Effect.suspend(() => {
const result = requests.get(effect.requestID)
if (!result) return Effect.void
requests.delete(effect.requestID)
return Deferred.done(
result,
effect.settlement.ok ? Exit.succeed(effect.settlement.result) : Exit.fail(effect.settlement.error),
).pipe(Effect.asVoid)
})
if (effect.type === "warn") return Effect.logWarning(effect.message, effect.error)
return Deferred.done(drained, Exit.void).pipe(Effect.asVoid)
}
const syncPermissions = (effect: Extract<BrowserMachine.ConnectionEffect, { readonly type: "sync-permissions" }>) =>
ctx.session.get({ sessionID: effect.sessionID }).pipe(
Effect.flatMap((session) => {
const permissions = BrowserMachine.reconcileBrowserPermissions(session.permissions, effect.allow)
return permissions ? ctx.session.update({ sessionID: effect.sessionID, permissions }) : Effect.void
}),
Effect.timeoutOption(Duration.millis(BrowserMachine.PERMISSION_SYNC_TIMEOUT_MS)),
Effect.matchCauseEffect({
onSuccess: (done) =>
dispatch({
type: Option.isSome(done) ? "permissions.synced" : "permissions.timed-out",
sessionID: effect.sessionID,
attempt: effect.attempt,
}),
onFailure: (cause) =>
dispatch({
type: "permissions.failed",
sessionID: effect.sessionID,
attempt: effect.attempt,
error: Cause.squash(cause),
}),
}),
)
const tunnels = (input: {
sessionID: Session.ID
connectionID: string
}): Effect.Effect<BrowserTunnel.Tunnels, Error> => {
const browser = browsers.get(input.sessionID)
return browser?.connectionID === input.connectionID
? Effect.succeed(browser.tunnels)
const attempt = BrowserMachine.selectAttachment(machine.state, input.sessionID, input.connectionID)
const attachment = attempt === undefined ? undefined : attachments.get(attempt)
return attachment
? Effect.succeed(attachment.tunnels)
: Effect.fail(new Error("Browser attachment is unavailable; its network connections were closed."))
}
const rpc: RpcRegistration<typeof Browser.Definition> = yield* ctx.rpc
@@ -96,58 +125,58 @@ export const make = Effect.fn("BrowserConnection.make")(function* (
.pipe(Effect.mapError(() => call.error("unavailable", "Session not found.", {})))
if (session.location.directory !== ctx.location.directory)
return yield* Effect.fail(call.error("unavailable", "Session belongs to another location.", {}))
const browser = yield* Effect.acquireRelease(
Effect.gen(function* () {
if (!active) return yield* Effect.fail(call.error("unavailable", "Browser is unavailable.", {}))
yield* close(input.sessionID, "replaced")
const browser: Attachment = {
connectionID: input.connectionID,
state: { tabs: [], focusedTabID: null },
closed: yield* Deferred.make<"closed" | "replaced">(),
pending: new Map(),
tunnels: BrowserTunnel.make(),
}
browsers.set(input.sessionID, browser)
return browser
}),
(browser) => (browsers.get(input.sessionID) === browser ? close(input.sessionID) : Effect.void),
return yield* Effect.acquireUseRelease(
lock.withPermit(
Effect.suspend(() => {
if (BrowserMachine.isConnectionDisposed(machine.state))
return Effect.fail(call.error("unavailable", "Browser is unavailable.", {}))
const attempt = BrowserMachine.selectNextAttempt(machine.state)
const attachment: Attachment = { closed: Deferred.makeUnsafe(), tunnels: BrowserTunnel.make() }
attachments.set(attempt, attachment)
return step({
type: "attach.started",
sessionID: input.sessionID,
attempt,
connectionID: input.connectionID,
}).pipe(Effect.as({ attempt, attachment }))
}),
),
(attached) =>
Deferred.await(attached.attachment.closed).pipe(
Effect.mapError(() => call.error("unavailable", "Browser permissions could not be granted.", {})),
),
(attached) => dispatch({ type: "attach.closed", sessionID: input.sessionID, attempt: attached.attempt }),
)
yield* grant(input.sessionID)
yield* rpc.events
.emit("control", { type: "attached", connectionID: input.connectionID, version: 4 })
.pipe(Effect.orDie)
return yield* Deferred.await(browser.closed)
}).pipe(Effect.scoped),
state: (input, call) =>
Effect.gen(function* () {
const browser = browsers.get(input.sessionID)
if (!browser || browser.connectionID !== input.connectionID)
return yield* Effect.fail(call.error("unavailable", "Browser is unavailable.", {}))
browser.state = input.state
}),
state: (input, call) =>
Effect.suspend(() =>
BrowserMachine.isAttachedConnection(machine.state, input.sessionID, input.connectionID)
? dispatch({
type: "state.updated",
sessionID: input.sessionID,
connectionID: input.connectionID,
browserState: input.state,
})
: Effect.fail(call.error("unavailable", "Browser is unavailable.", {})),
),
command: (input, call) =>
Effect.gen(function* () {
const browser = browsers.get(input.sessionID)
const pending =
browser?.connectionID === input.connectionID ? browser.pending.get(input.requestID) : undefined
if (!pending)
return yield* Effect.fail(call.error("unavailable", "Browser request is no longer available.", {}))
return pending.command
Effect.suspend(() => {
const command = BrowserMachine.selectPendingCommand(
machine.state,
input.sessionID,
input.connectionID,
input.requestID,
)
return command
? Effect.succeed(command)
: Effect.fail(call.error("unavailable", "Browser request is no longer available.", {}))
}),
result: (input, call) =>
Effect.gen(function* () {
const browser = browsers.get(input.sessionID)
if (!browser || browser.connectionID !== input.connectionID)
return yield* Effect.fail(call.error("unavailable", "Browser is unavailable.", {}))
const pending = browser.pending.get(input.requestID)
if (!pending) return
if (input.outcome.type === "failure")
return yield* Deferred.fail(
pending.result,
new Tool.Error({ message: `[browser.${input.outcome.code}] ${input.outcome.message}` }),
).pipe(Effect.asVoid)
yield* Deferred.succeed(pending.result, input.outcome.result)
}).pipe(Effect.asVoid),
Effect.suspend(() =>
BrowserMachine.isAttachedConnection(machine.state, input.sessionID, input.connectionID)
? dispatch({ type: "request.settled", ...input })
: Effect.fail(call.error("unavailable", "Browser is unavailable.", {})),
),
"tunnel.open": (input, call) =>
tunnels(input).pipe(
Effect.flatMap((network) => network.open(input.target)),
@@ -171,29 +200,67 @@ export const make = Effect.fn("BrowserConnection.make")(function* (
})
.pipe(Effect.orDie)
yield* ctx.event.subscribe({ types: ["session.deleted", "session.moved"] }).pipe(
Stream.runForEach((event) => close(event.data.sessionID)),
Stream.runForEach((event) =>
dispatch({
type: event.type === "session.deleted" ? "session.deleted" : "session.moved",
sessionID: event.data.sessionID,
}),
),
Effect.forkScoped({ startImmediately: true }),
)
// Registered last, so it runs first: attachments close and revokes drain while the RPC and `work` are still open.
yield* Effect.addFinalizer(() => dispatch({ type: "disposed" }).pipe(Effect.andThen(Deferred.await(drained))))
const request = Effect.fn("BrowserConnection.request")(function* (
sessionID: Session.ID,
connectionID: string,
action: Browser.Action,
tab: Browser.Tab | undefined,
files: readonly Browser.File[],
inspection: Pick<Browser.Command, "inspect" | "target">,
) {
const requestID = crypto.randomUUID()
const target = { sessionID, connectionID, requestID }
const result = yield* Deferred.make<Browser.Result, Tool.Error>()
const command = {
action:
(action.type === "files.upload" || action.type === "files.drop") && !inspection.inspect
? { ...action, paths: files.map((file) => file.name) }
: action,
...(tab ? { generation: tab.generation } : {}),
files,
...inspection,
}
// Once started, the request always reaches the machine's exit: a settlement, a timeout or a cancel.
return yield* Effect.uninterruptibleMask((restore) =>
Effect.sync(() => requests.set(requestID, result)).pipe(
Effect.andThen(dispatch({ type: "request.started", ...target, command })),
Effect.andThen(
restore(
Deferred.await(result).pipe(
Effect.timeoutOrElse({
duration: Duration.millis(BrowserMachine.REQUEST_TIMEOUT_MS),
orElse: () =>
dispatch({ type: "request.timed-out", ...target }).pipe(Effect.andThen(Deferred.await(result))),
}),
),
),
),
Effect.onInterrupt(() => dispatch({ type: "request.cancelled", ...target })),
Effect.ensuring(Effect.sync(() => requests.delete(requestID))),
),
)
})
return {
target: Effect.fn("BrowserConnection.target")(function* (sessionID: Session.ID, action: Browser.Action) {
const browser = browsers.get(sessionID)
if (!browser)
return yield* new Tool.Error({
message:
"[browser.disconnected] No desktop browser is connected to this session. Open this session in the desktop app and wait for it to connect. Then call browser.tabs.list({}). Repeating browser actions while disconnected will not help.",
})
const tab = "tabID" in action ? browser.state.tabs.find((tab) => tab.id === action.tabID) : undefined
if ("tabID" in action && !tab)
return yield* new Tool.Error({
message:
"[browser.tab_unavailable] This tab is closed or does not belong to the connected session. Call browser.tabs.list({}) and use an exact returned tabID. If no tabs exist, use browser.tabs.open({}). Never substitute a request ID, file ID, or element ref for tabID.",
})
// Keep the selected attachment and document, even while permissions or file IO wait.
const selected = BrowserMachine.selectTarget(machine.state, sessionID, action)
if (!selected.ok) return yield* selected.error
// Requests go to the attachment selected here. One that closes first, even while file IO waits, runs nothing.
return {
tab,
tab: selected.tab,
inspect: () =>
request(rpc, browser, action, tab, [], { inspect: true }).pipe(
request(sessionID, selected.connectionID, action, selected.tab, [], { inspect: true }).pipe(
Effect.flatMap((result) => Schema.decodeUnknownEffect(Browser.Target)(result.value)),
Effect.mapError(
(error) =>
@@ -207,59 +274,8 @@ export const make = Effect.fn("BrowserConnection.make")(function* (
),
),
request: (files: readonly Browser.File[], target?: Browser.Target) =>
request(rpc, browser, action, tab, files, { target }),
request(sessionID, selected.connectionID, action, selected.tab, files, { target }),
}
}),
}
})
const request = Effect.fn("BrowserConnection.request")(function* (
rpc: RpcRegistration<typeof Browser.Definition>,
browser: Attachment,
action: Browser.Action,
tab: Browser.Tab | undefined,
files: readonly Browser.File[],
inspection: Pick<Browser.Command, "inspect" | "target">,
) {
const requestID = crypto.randomUUID()
const pending = yield* Deferred.make<Browser.Result, Tool.Error>()
const command =
(action.type === "files.upload" || action.type === "files.drop") && !inspection.inspect
? { ...action, paths: files.map((file) => file.name) }
: action
browser.pending.set(requestID, {
command: { action: command, ...(tab ? { generation: tab.generation } : {}), files, ...inspection },
result: pending,
})
return yield* rpc.events.emit("control", { type: "command", connectionID: browser.connectionID, requestID }).pipe(
Effect.mapError(
(error) =>
new Tool.Error({
message: `Could not dispatch browser.${action.type}. Check the desktop connection and call browser.tabs.list({}) before deciding whether to retry.`,
error,
}),
),
Effect.andThen(Deferred.await(pending)),
Effect.raceFirst(
Deferred.await(browser.closed).pipe(
Effect.andThen(
new Tool.Error({
message:
"[browser.disconnected] Browser connection closed; the action may already have run. Reconnect this session in the desktop app, call browser.tabs.list({}), and inspect the target tab with browser.snapshot({tabID}). Do not repeat clicks, submissions, uploads, or evaluations until their outcome is known.",
}),
),
),
),
Effect.onInterrupt(() =>
rpc.events.emit("control", { type: "cancel", connectionID: browser.connectionID, requestID }).pipe(Effect.ignore),
),
Effect.timeoutOrElse({
duration: "60 seconds",
orElse: () =>
new Tool.Error({
message: `[browser.timeout] browser.${action.type} did not finish within 60 seconds; its outcome is unknown. Check the desktop connection, call browser.tabs.list({}), and inspect the tab or browser.files.list({tabID}) for completed work. Do not blindly repeat a mutating action or start another recording.`,
}),
}),
Effect.ensuring(Effect.sync(() => browser.pending.delete(requestID))),
)
})
+675
View File
@@ -0,0 +1,675 @@
export * as BrowserMachine from "./machine.js"
import type { Permission } from "@opencode/schema/permission"
import type { Session } from "@opencode/schema/session"
import { Tool } from "@opencode/schema/tool"
import type { Browser } from "./rpc.js"
import { BrowserSkill } from "./skill.js"
/** How long one permission sync (`session.get` and, when needed, `session.update`) may take. The desktop waits 15 s. */
export const PERMISSION_SYNC_TIMEOUT_MS = 10_000
/** How long a dispatched browser command may run before it times out and is cancelled on the desktop. */
export const REQUEST_TIMEOUT_MS = 60_000
/** The browser tools and their skill, which an attachment allows together. */
export const ACCESS = [
{ action: "browser", resource: "*" },
{ action: "skill", resource: BrowserSkill.id },
] as const
/** The one `session.permissions` sync in flight for a session: grant (`allow`) or revoke the browser rules. */
export type PermissionSync = { readonly attempt: number; readonly allow: boolean }
/**
* One session's attachment. A session absent from `sessions` has no attachment and no sync in flight.
*
* - `attaching`: the desktop called `attach` as `attempt`. Its grant runs after any revoke in flight (`sync`); until it
* succeeds, no `attached` handshake is sent and no command is dispatched.
* - `attached`: the session allows the browser and the desktop received `attached`; commands run.
* - `revoking`: no attachment; `sync` settles, then a revoke follows unless the session was `deleted`.
*/
export type SessionState =
| {
readonly status: "attaching"
readonly attempt: number
readonly connectionID: string
readonly sync: PermissionSync
}
| {
readonly status: "attached"
readonly attempt: number
readonly connectionID: string
readonly browserState: Browser.State
readonly pending: ReadonlyMap<string, Browser.Command>
}
| { readonly status: "revoking"; readonly sync: PermissionSync; readonly deleted: boolean }
export type RevokingSession = Extract<SessionState, { readonly status: "revoking" }>
type AttachingSession = Extract<SessionState, { readonly status: "attaching" }>
type AttachedSession = Extract<SessionState, { readonly status: "attached" }>
/** Every attachment of the plugin. Once `disposed`, only revokes still draining remain. */
export type ConnectionState =
| {
readonly status: "active"
readonly nextAttempt: number
readonly sessions: ReadonlyMap<Session.ID, SessionState>
}
| {
readonly status: "disposed"
readonly nextAttempt: number
readonly sessions: ReadonlyMap<Session.ID, RevokingSession>
}
/** How an `attach` call ends: its result, or `unavailable` when the grant failed. */
export type AttachmentOutcome = "closed" | "replaced" | "unavailable"
export type RequestSettlement =
| { readonly ok: true; readonly result: Browser.Result }
| { readonly ok: false; readonly error: Tool.Error }
export type ConnectionEvent =
/** `attempt` is the state's `nextAttempt`, read when the driver registered the attachment's handle. */
| {
readonly type: "attach.started"
readonly sessionID: Session.ID
readonly attempt: number
readonly connectionID: string
}
/** The `attach` call ended on the desktop's side (disconnect or interrupt). */
| { readonly type: "attach.closed"; readonly sessionID: Session.ID; readonly attempt: number }
| { readonly type: "permissions.synced"; readonly sessionID: Session.ID; readonly attempt: number }
| {
readonly type: "permissions.failed"
readonly sessionID: Session.ID
readonly attempt: number
readonly error: unknown
}
| { readonly type: "permissions.timed-out"; readonly sessionID: Session.ID; readonly attempt: number }
| {
readonly type: "state.updated"
readonly sessionID: Session.ID
readonly connectionID: string
readonly browserState: Browser.State
}
| {
readonly type: "request.started"
readonly sessionID: Session.ID
readonly connectionID: string
readonly requestID: string
readonly command: Browser.Command
}
| {
readonly type: "request.dispatch-failed"
readonly sessionID: Session.ID
readonly connectionID: string
readonly requestID: string
readonly error: unknown
}
| {
readonly type: "request.settled"
readonly sessionID: Session.ID
readonly connectionID: string
readonly requestID: string
readonly outcome: Browser.Outcome
}
| {
readonly type: "request.timed-out"
readonly sessionID: Session.ID
readonly connectionID: string
readonly requestID: string
}
/** The tool call that started the request was interrupted. */
| {
readonly type: "request.cancelled"
readonly sessionID: Session.ID
readonly connectionID: string
readonly requestID: string
}
| { readonly type: "session.moved"; readonly sessionID: Session.ID }
| { readonly type: "session.deleted"; readonly sessionID: Session.ID }
| { readonly type: "disposed" }
export type ConnectionEffect =
| {
readonly type: "sync-permissions"
readonly sessionID: Session.ID
readonly attempt: number
readonly allow: boolean
}
/** Disposes the attachment's tunnels and ends its `attach` call with `outcome`. */
| { readonly type: "close-attachment"; readonly attempt: number; readonly outcome: AttachmentOutcome }
| { readonly type: "emit-control"; readonly control: Browser.Control }
/** Emits the `command` control; a failure comes back as `request.dispatch-failed`. */
| {
readonly type: "dispatch-command"
readonly sessionID: Session.ID
readonly connectionID: string
readonly requestID: string
}
| { readonly type: "settle-request"; readonly requestID: string; readonly settlement: RequestSettlement }
| { readonly type: "warn"; readonly message: string; readonly error: unknown }
/** The disposed plugin has no revoke left in flight. */
| { readonly type: "notify-drained" }
export type ConnectionTransition = { readonly state: ConnectionState; readonly effects: readonly ConnectionEffect[] }
type SessionEvent = Exclude<ConnectionEvent, { readonly type: "disposed" }>
type Step<S extends SessionState> = {
readonly entry: S | undefined
readonly nextAttempt: number
readonly effects: readonly ConnectionEffect[]
}
export function createConnectionState(): ConnectionState {
return { status: "active", nextAttempt: 1, sessions: new Map() }
}
export function transitionConnection(state: ConnectionState, event: ConnectionEvent): ConnectionTransition {
if (event.type === "disposed") return dispose(state)
// A request whose attachment closed or was replaced after the tool picked it was never sent.
if (event.type === "request.started" && !isAttachedConnection(state, event.sessionID, event.connectionID))
return {
state,
effects: [
{
type: "settle-request",
requestID: event.requestID,
settlement: { ok: false, error: disconnectedBeforeDispatch() },
},
],
}
const entry = state.sessions.get(event.sessionID)
if (state.status === "disposed") {
if (!entry || entry.status !== "revoking") return { state, effects: [] }
const step = transitionRevoking(entry, event, state.nextAttempt)
if (!step) return { state, effects: [] }
const sessions = new Map(state.sessions)
if (step.entry) sessions.set(event.sessionID, step.entry)
if (!step.entry) sessions.delete(event.sessionID)
return {
state: { status: "disposed", nextAttempt: step.nextAttempt, sessions },
effects: sessions.size ? step.effects : [...step.effects, { type: "notify-drained" }],
}
}
const step = transitionSession(entry, event, state.nextAttempt)
if (!step) return { state, effects: [] }
const sessions = new Map(state.sessions)
if (step.entry) sessions.set(event.sessionID, step.entry)
if (!step.entry) sessions.delete(event.sessionID)
return { state: { status: "active", nextAttempt: step.nextAttempt, sessions }, effects: step.effects }
}
function transitionSession(
entry: SessionState | undefined,
event: SessionEvent,
nextAttempt: number,
): Step<SessionState> | undefined {
if (event.type === "attach.started") return attach(entry, event, nextAttempt)
if (!entry) return undefined
if (entry.status === "revoking") return transitionRevoking(entry, event, nextAttempt)
if (entry.status === "attaching") return transitionAttaching(entry, event, nextAttempt)
return transitionAttached(entry, event, nextAttempt)
}
function attach(
entry: SessionState | undefined,
event: Extract<SessionEvent, { readonly type: "attach.started" }>,
nextAttempt: number,
): Step<SessionState> | undefined {
if (event.attempt !== nextAttempt) return undefined
const attaching = (sync: PermissionSync): AttachingSession => ({
status: "attaching",
attempt: event.attempt,
connectionID: event.connectionID,
sync,
})
// A sync already in flight finishes first; the grant waits for it, so two writes never interleave.
if (entry?.status === "attaching")
return {
entry: attaching(entry.sync),
nextAttempt: nextAttempt + 1,
effects: [{ type: "close-attachment", attempt: entry.attempt, outcome: "replaced" }],
}
if (entry?.status === "revoking") return { entry: attaching(entry.sync), nextAttempt: nextAttempt + 1, effects: [] }
const sync = { attempt: nextAttempt + 1, allow: true }
const effects: ConnectionEffect[] =
entry?.status === "attached"
? [...failPending(entry), { type: "close-attachment", attempt: entry.attempt, outcome: "replaced" }]
: []
return {
entry: attaching(sync),
nextAttempt: nextAttempt + 2,
effects: [...effects, { type: "sync-permissions", sessionID: event.sessionID, ...sync }],
}
}
function transitionAttaching(
entry: AttachingSession,
event: SessionEvent,
nextAttempt: number,
): Step<SessionState> | undefined {
if (
event.type === "permissions.synced" ||
event.type === "permissions.failed" ||
event.type === "permissions.timed-out"
) {
if (event.attempt !== entry.sync.attempt) return undefined
const warning = syncWarning(event, entry.sync)
// The revoke that ran before this attachment settled; now grant.
if (!entry.sync.allow) {
const sync = { attempt: nextAttempt, allow: true }
return {
entry: { ...entry, sync },
nextAttempt: nextAttempt + 1,
effects: [...warning, { type: "sync-permissions", sessionID: event.sessionID, ...sync }],
}
}
if (event.type === "permissions.synced")
return {
entry: {
status: "attached",
attempt: entry.attempt,
connectionID: entry.connectionID,
browserState: { tabs: [], focusedTabID: null },
pending: new Map(),
},
nextAttempt,
effects: [
{ type: "emit-control", control: { type: "attached", connectionID: entry.connectionID, version: 4 } },
],
}
// A grant that timed out may still have written its rules; revoke them.
const sync = { attempt: nextAttempt, allow: false }
return {
entry: { status: "revoking", sync, deleted: false },
nextAttempt: nextAttempt + 1,
effects: [
...warning,
{ type: "close-attachment", attempt: entry.attempt, outcome: "unavailable" },
{ type: "sync-permissions", sessionID: event.sessionID, ...sync },
],
}
}
if (
(event.type === "attach.closed" && event.attempt === entry.attempt) ||
event.type === "session.moved" ||
event.type === "session.deleted"
)
return {
entry: { status: "revoking", sync: entry.sync, deleted: event.type === "session.deleted" },
nextAttempt,
effects: [{ type: "close-attachment", attempt: entry.attempt, outcome: "closed" }],
}
return undefined
}
function transitionAttached(
entry: AttachedSession,
event: SessionEvent,
nextAttempt: number,
): Step<SessionState> | undefined {
if (event.type === "state.updated") return updateBrowserState(entry, event, nextAttempt)
if (event.type === "request.started") {
if (entry.pending.has(event.requestID)) return undefined
return {
entry: { ...entry, pending: new Map(entry.pending).set(event.requestID, event.command) },
nextAttempt,
effects: [
{
type: "dispatch-command",
sessionID: event.sessionID,
connectionID: entry.connectionID,
requestID: event.requestID,
},
],
}
}
if (
event.type === "request.dispatch-failed" ||
event.type === "request.settled" ||
event.type === "request.timed-out" ||
event.type === "request.cancelled"
) {
const command = entry.connectionID === event.connectionID ? entry.pending.get(event.requestID) : undefined
if (!command) return undefined
const pending = new Map(entry.pending)
pending.delete(event.requestID)
return { entry: { ...entry, pending }, nextAttempt, effects: settleRequest(entry, event, command) }
}
if (event.type === "session.deleted")
return {
entry: undefined,
nextAttempt,
effects: [...failPending(entry), { type: "close-attachment", attempt: entry.attempt, outcome: "closed" }],
}
if ((event.type === "attach.closed" && event.attempt === entry.attempt) || event.type === "session.moved")
return revokeAttached(entry, event.sessionID, nextAttempt)
return undefined
}
function transitionRevoking(
entry: RevokingSession,
event: SessionEvent,
nextAttempt: number,
): Step<RevokingSession> | undefined {
if (event.type === "session.deleted")
return entry.deleted ? undefined : { entry: { ...entry, deleted: true }, nextAttempt, effects: [] }
if (
event.type !== "permissions.synced" &&
event.type !== "permissions.failed" &&
event.type !== "permissions.timed-out"
)
return undefined
if (event.attempt !== entry.sync.attempt) return undefined
const warning = syncWarning(event, entry.sync)
// A grant settled after its attachment closed, or timed out and may still have written: revoke it.
if (entry.sync.allow && !entry.deleted) {
const sync = { attempt: nextAttempt, allow: false }
return {
entry: { status: "revoking", sync, deleted: false },
nextAttempt: nextAttempt + 1,
effects: [...warning, { type: "sync-permissions", sessionID: event.sessionID, ...sync }],
}
}
return { entry: undefined, nextAttempt, effects: warning }
}
function dispose(state: ConnectionState): ConnectionTransition {
if (state.status === "disposed") return { state, effects: [] }
const effects: ConnectionEffect[] = []
const sessions = new Map<Session.ID, RevokingSession>()
const nextAttempt = Array.from(state.sessions).reduce((attempt, [sessionID, entry]) => {
if (entry.status === "revoking") {
sessions.set(sessionID, entry)
return attempt
}
if (entry.status === "attaching") {
sessions.set(sessionID, { status: "revoking", sync: entry.sync, deleted: false })
effects.push({ type: "close-attachment", attempt: entry.attempt, outcome: "closed" })
return attempt
}
const step = revokeAttached(entry, sessionID, attempt)
if (step.entry) sessions.set(sessionID, step.entry)
effects.push(...step.effects)
return step.nextAttempt
}, state.nextAttempt)
if (!sessions.size) effects.push({ type: "notify-drained" })
return { state: { status: "disposed", nextAttempt, sessions }, effects }
}
function revokeAttached(entry: AttachedSession, sessionID: Session.ID, nextAttempt: number): Step<RevokingSession> {
const sync = { attempt: nextAttempt, allow: false }
return {
entry: { status: "revoking", sync, deleted: false },
nextAttempt: nextAttempt + 1,
effects: [
...failPending(entry),
{ type: "close-attachment", attempt: entry.attempt, outcome: "closed" },
{ type: "sync-permissions", sessionID, ...sync },
],
}
}
function updateBrowserState(
entry: AttachedSession,
event: Extract<SessionEvent, { readonly type: "state.updated" }>,
nextAttempt: number,
): Step<SessionState> | undefined {
if (entry.connectionID !== event.connectionID || entry.browserState === event.browserState) return undefined
return { entry: { ...entry, browserState: event.browserState }, nextAttempt, effects: [] }
}
function settleRequest(
entry: AttachedSession,
event: Extract<
SessionEvent,
{ readonly type: "request.dispatch-failed" | "request.settled" | "request.timed-out" | "request.cancelled" }
>,
command: Browser.Command,
): ConnectionEffect[] {
const cancel: ConnectionEffect = {
type: "emit-control",
control: { type: "cancel", connectionID: entry.connectionID, requestID: event.requestID },
}
// The interrupted caller no longer waits; only the desktop needs to stop.
if (event.type === "request.cancelled") return [cancel]
const settle = (settlement: RequestSettlement): ConnectionEffect => ({
type: "settle-request",
requestID: event.requestID,
settlement,
})
if (event.type === "request.timed-out") return [settle({ ok: false, error: timedOut(command.action.type) }), cancel]
if (event.type === "request.dispatch-failed")
return [settle({ ok: false, error: dispatchFailed(command.action.type, event.error) })]
if (event.outcome.type === "success") return [settle({ ok: true, result: event.outcome.result })]
return [
settle({
ok: false,
error: new Tool.Error({ message: `[browser.${event.outcome.code}] ${event.outcome.message}` }),
}),
]
}
function failPending(entry: AttachedSession): ConnectionEffect[] {
return Array.from(entry.pending.keys(), (requestID) => ({
type: "settle-request",
requestID,
settlement: { ok: false, error: disconnectedAfterDispatch() },
}))
}
function syncWarning(
event: Extract<
SessionEvent,
{ readonly type: "permissions.synced" | "permissions.failed" | "permissions.timed-out" }
>,
sync: PermissionSync,
): ConnectionEffect[] {
const action = sync.allow ? "grant" : "revoke"
if (event.type === "permissions.failed")
return [{ type: "warn", message: `Browser permission ${action} failed`, error: event.error }]
if (event.type === "permissions.timed-out")
return [
{
type: "warn",
message: `Browser permission ${action} timed out after ${PERMISSION_SYNC_TIMEOUT_MS} ms`,
error: undefined,
},
]
return []
}
/**
* The session's permissions with exactly one set of browser allows (`allow`) or none, every other rule kept in order.
* Undefined when they already are, so a replace writes nothing.
*/
export function reconcileBrowserPermissions(
current: readonly Permission.Rule[] | undefined,
allow: boolean,
): Permission.Rule[] | undefined {
const rules = current ?? []
const kept = rules.filter(
(rule) =>
rule.effect !== "allow" ||
!ACCESS.some((access) => access.action === rule.action && access.resource === rule.resource),
)
const next = allow ? [...kept, ...ACCESS.map((rule) => ({ ...rule, effect: "allow" as const }))] : kept
const unchanged =
next.length === rules.length &&
next.every(
(rule, index) =>
rule.action === rules[index]?.action &&
rule.resource === rules[index]?.resource &&
rule.effect === rules[index]?.effect,
)
return unchanged ? undefined : next
}
export function isConnectionDisposed(state: ConnectionState) {
return state.status === "disposed"
}
/** The attempt the next `attach` gets; the driver keys its handle by it before dispatching `attach.started`. */
export function selectNextAttempt(state: ConnectionState) {
return state.nextAttempt
}
/** The attempt of the session's attachment with `connectionID`, attaching or attached. */
export function selectAttachment(state: ConnectionState, sessionID: Session.ID, connectionID: string) {
if (state.status === "disposed") return undefined
const entry = state.sessions.get(sessionID)
if (entry?.status === "revoking" || entry?.connectionID !== connectionID) return undefined
return entry.attempt
}
export function isAttachedConnection(state: ConnectionState, sessionID: Session.ID, connectionID: string) {
if (state.status === "disposed") return false
const entry = state.sessions.get(sessionID)
return entry?.status === "attached" && entry.connectionID === connectionID
}
export function selectPendingCommand(
state: ConnectionState,
sessionID: Session.ID,
connectionID: string,
requestID: string,
) {
if (state.status === "disposed") return undefined
const entry = state.sessions.get(sessionID)
if (entry?.status !== "attached" || entry.connectionID !== connectionID) return undefined
return entry.pending.get(requestID)
}
/** The attachment and tab a browser tool call targets, or the error the tool returns. */
export function selectTarget(
state: ConnectionState,
sessionID: Session.ID,
action: Browser.Action,
):
| { readonly ok: true; readonly connectionID: string; readonly tab: Browser.Tab | undefined }
| { readonly ok: false; readonly error: Tool.Error } {
const entry = state.status === "active" ? state.sessions.get(sessionID) : undefined
if (!entry || entry.status === "revoking")
return {
ok: false,
error: new Tool.Error({
message:
"[browser.disconnected] No desktop browser is connected to this session. Open this session in the desktop app and wait for it to connect. Then call browser.tabs.list({}). Repeating browser actions while disconnected will not help.",
}),
}
if (entry.status === "attaching")
return {
ok: false,
error: new Tool.Error({
message:
"[browser.disconnected] The desktop browser is still connecting to this session; no action ran. Call browser.tabs.list({}) once it finishes connecting.",
}),
}
const tab = "tabID" in action ? entry.browserState.tabs.find((tab) => tab.id === action.tabID) : undefined
if ("tabID" in action && !tab)
return {
ok: false,
error: new Tool.Error({
message:
"[browser.tab_unavailable] This tab is closed or does not belong to the connected session. Call browser.tabs.list({}) and use an exact returned tabID. If no tabs exist, use browser.tabs.open({}). Never substitute a request ID, file ID, or element ref for tabID.",
}),
}
return { ok: true, connectionID: entry.connectionID, tab }
}
function disconnectedBeforeDispatch() {
return new Tool.Error({
message:
"[browser.disconnected] The desktop browser disconnected before this action was sent; no action ran. Reconnect this session in the desktop app, then call browser.tabs.list({}).",
})
}
function disconnectedAfterDispatch() {
return new Tool.Error({
message:
"[browser.disconnected] Browser connection closed; the action may already have run. Reconnect this session in the desktop app, call browser.tabs.list({}), and inspect the target tab with browser.snapshot({tabID}). Do not repeat clicks, submissions, uploads, or evaluations until their outcome is known.",
})
}
function dispatchFailed(action: Browser.Method, error: unknown) {
return new Tool.Error({
message: `Could not dispatch browser.${action}. Check the desktop connection and call browser.tabs.list({}) before deciding whether to retry.`,
error,
})
}
function timedOut(action: Browser.Method) {
return new Tool.Error({
message: `[browser.timeout] browser.${action} did not finish within ${REQUEST_TIMEOUT_MS / 1000} seconds; its outcome is unknown. Check the desktop connection, call browser.tabs.list({}), and inspect the tab or browser.files.list({tabID}) for completed work. Do not blindly repeat a mutating action or start another recording.`,
})
}
@@ -0,0 +1,450 @@
import { describe, expect, test } from "bun:test"
import { Session } from "@opencode/schema/session"
import { Schema } from "effect"
import { BrowserMachine } from "../src/machine.js"
import { Browser } from "../src/rpc.js"
const sessionID = Session.ID.make("ses_browser")
const other = Session.ID.make("ses_other")
const tabID = Browser.TabID.make(`tab_${crypto.randomUUID()}`)
const tab = {
id: tabID,
url: "https://example.com/",
title: "Example",
loading: false,
canGoBack: false,
canGoForward: false,
generation: 1,
}
const command: Browser.Command = { action: { type: "tabs.list" }, files: [] }
const success = Schema.decodeUnknownSync(Browser.Outcome)({
type: "success",
result: { value: { ok: true }, files: [] },
})
const failure = Schema.decodeUnknownSync(Browser.Outcome)({ type: "failure", code: "navigation", message: "Blocked" })
type Event = BrowserMachine.ConnectionEvent
function run(state: BrowserMachine.ConnectionState, ...events: Event[]) {
return events.reduce(
(result, event) => {
const next = BrowserMachine.transitionConnection(result.state, event)
return { state: next.state, effects: [...result.effects, ...next.effects] }
},
{ state, effects: [] as BrowserMachine.ConnectionEffect[] },
)
}
/** `attach.started` with the attempt the driver reads from `selectNextAttempt` at that moment. */
function attach(state: BrowserMachine.ConnectionState, connectionID: string, id = sessionID): Event {
return { type: "attach.started", sessionID: id, attempt: BrowserMachine.selectNextAttempt(state), connectionID }
}
function entry(state: BrowserMachine.ConnectionState, id = sessionID) {
return state.sessions.get(id)
}
function syncs(effects: readonly BrowserMachine.ConnectionEffect[]) {
return effects.flatMap((effect) => (effect.type === "sync-permissions" ? [effect] : []))
}
function lastSync(effects: readonly BrowserMachine.ConnectionEffect[]) {
const sync = syncs(effects).at(-1)
if (!sync) throw new Error("expected a permission sync")
return sync
}
function synced(attempt: number, id = sessionID): Event {
return { type: "permissions.synced", sessionID: id, attempt }
}
function controls(effects: readonly BrowserMachine.ConnectionEffect[]) {
return effects.flatMap((effect) => (effect.type === "emit-control" ? [effect.control] : []))
}
function settlements(effects: readonly BrowserMachine.ConnectionEffect[]) {
return effects.flatMap((effect) => (effect.type === "settle-request" ? [effect] : []))
}
function message(settlement: BrowserMachine.RequestSettlement) {
return settlement.ok ? undefined : settlement.error.message
}
/** An attached `conn_1`, as the desktop sees it once its grant succeeded. */
function attached(connectionID = "conn_1") {
const initial = BrowserMachine.createConnectionState()
const started = run(initial, attach(initial, connectionID))
return run(started.state, synced(lastSync(started.effects).attempt)).state
}
function started(requestID: string, connectionID = "conn_1"): Event {
return { type: "request.started", sessionID, connectionID, requestID, command }
}
describe("attachment replace", () => {
test("a replaced attachment never revokes its replacement's grant", () => {
const first = attached()
const replace = run(first, attach(first, "conn_2"))
expect(replace.effects).toContainEqual({ type: "close-attachment", attempt: 1, outcome: "replaced" })
expect(entry(replace.state)?.status).toBe("attaching")
// conn_1's RPC scope ends after the replace; that must not touch the session.
const closed = BrowserMachine.transitionConnection(replace.state, {
type: "attach.closed",
sessionID,
attempt: 1,
})
expect(closed.state).toBe(replace.state)
expect(closed.effects).toEqual([])
const done = run(replace.state, synced(lastSync(replace.effects).attempt))
expect(controls(done.effects)).toEqual([{ type: "attached", connectionID: "conn_2", version: 4 }])
expect(syncs([...replace.effects, ...done.effects]).every((sync) => sync.allow)).toBe(true)
expect(entry(done.state)).toMatchObject({ status: "attached", connectionID: "conn_2" })
})
test("a re-attach waits for the revoke in flight, then grants", () => {
const closed = run(attached(), { type: "attach.closed", sessionID, attempt: 1 })
const revoke = lastSync(closed.effects)
expect(revoke).toMatchObject({ allow: false })
const reattach = run(closed.state, attach(closed.state, "conn_2"))
expect(reattach.effects).toEqual([])
expect(entry(reattach.state)).toMatchObject({
status: "attaching",
sync: { attempt: revoke.attempt, allow: false },
})
const revoked = run(reattach.state, synced(revoke.attempt))
const grant = lastSync(revoked.effects)
expect(grant).toMatchObject({ allow: true })
expect(controls(revoked.effects)).toEqual([])
const done = run(revoked.state, synced(grant.attempt))
expect(controls(done.effects)).toEqual([{ type: "attached", connectionID: "conn_2", version: 4 }])
})
test("a replace while attaching reuses the grant in flight and hands `attached` only to the replacement", () => {
const initial = BrowserMachine.createConnectionState()
const first = run(initial, attach(initial, "conn_1"))
const grant = lastSync(first.effects)
const replace = run(first.state, attach(first.state, "conn_2"))
expect(replace.effects).toEqual([{ type: "close-attachment", attempt: 1, outcome: "replaced" }])
const done = run(replace.state, synced(grant.attempt))
expect(controls(done.effects)).toEqual([{ type: "attached", connectionID: "conn_2", version: 4 }])
})
})
describe("handshake", () => {
test("no tool reaches an attachment before its grant succeeds", () => {
const initial = BrowserMachine.createConnectionState()
const first = run(initial, attach(initial, "conn_1"))
expect(controls(first.effects)).toEqual([])
expect(BrowserMachine.selectTarget(first.state, sessionID, { type: "tabs.list" })).toMatchObject({
ok: false,
error: { message: expect.stringContaining("still connecting") },
})
const early = BrowserMachine.transitionConnection(first.state, started("req_1"))
expect(early.state).toBe(first.state)
expect(early.effects).toEqual([
{ type: "settle-request", requestID: "req_1", settlement: { ok: false, error: expect.anything() } },
])
const report = BrowserMachine.transitionConnection(first.state, {
type: "state.updated",
sessionID,
connectionID: "conn_1",
browserState: { tabs: [tab], focusedTabID: tabID },
})
expect(report.state).toBe(first.state)
const done = run(first.state, synced(lastSync(first.effects).attempt))
expect(controls(done.effects)).toEqual([{ type: "attached", connectionID: "conn_1", version: 4 }])
expect(BrowserMachine.selectTarget(done.state, sessionID, { type: "tabs.list" })).toMatchObject({
ok: true,
connectionID: "conn_1",
})
})
test.each(["attach.closed", "session.moved"] as const)(
"%s while attaching never sends `attached` and revokes after the grant settles",
(type) => {
const initial = BrowserMachine.createConnectionState()
const first = run(initial, attach(initial, "conn_1"))
const grant = lastSync(first.effects)
const closed = run(first.state, type === "attach.closed" ? { type, sessionID, attempt: 1 } : { type, sessionID })
expect(closed.effects).toEqual([{ type: "close-attachment", attempt: 1, outcome: "closed" }])
const settled = run(closed.state, synced(grant.attempt))
expect(controls(settled.effects)).toEqual([])
const revoke = lastSync(settled.effects)
expect(revoke).toMatchObject({ allow: false })
const done = run(settled.state, synced(revoke.attempt))
expect(entry(done.state)).toBeUndefined()
expect(done.effects).toEqual([])
},
)
test("a request for an attachment that closed after the tool selected it is never sent", () => {
const first = attached()
expect(BrowserMachine.selectTarget(first, sessionID, { type: "tabs.list" })).toMatchObject({
ok: true,
connectionID: "conn_1",
})
const replaced = run(first, attach(first, "conn_2"))
const synced2 = run(replaced.state, synced(lastSync(replaced.effects).attempt)).state
const late = BrowserMachine.transitionConnection(synced2, started("req_1", "conn_1"))
expect(late.state).toBe(synced2)
expect(late.effects).toHaveLength(1)
expect(message(settlements(late.effects)[0]!.settlement)).toContain("no action ran")
})
})
describe("permission syncs", () => {
test.each([
{ type: "permissions.failed" as const, error: new Error("session gone") },
{ type: "permissions.timed-out" as const },
])("a grant that ends with $type fails the attach and revokes what it may have written", (failed) => {
const initial = BrowserMachine.createConnectionState()
const first = run(initial, attach(initial, "conn_1"))
const grant = lastSync(first.effects)
const next = run(first.state, { ...failed, sessionID, attempt: grant.attempt })
expect(next.effects).toContainEqual({ type: "close-attachment", attempt: 1, outcome: "unavailable" })
expect(next.effects.some((effect) => effect.type === "warn")).toBe(true)
expect(controls(next.effects)).toEqual([])
const revoke = lastSync(next.effects)
expect(revoke).toMatchObject({ allow: false })
const done = run(next.state, { type: "permissions.failed", sessionID, attempt: revoke.attempt, error: undefined })
expect(entry(done.state)).toBeUndefined()
expect(syncs(done.effects)).toEqual([])
})
test("a failed revoke before a re-attach still grants the new attachment", () => {
const closed = run(attached(), { type: "attach.closed", sessionID, attempt: 1 })
const reattach = run(closed.state, attach(closed.state, "conn_2"))
const next = run(reattach.state, {
type: "permissions.timed-out",
sessionID,
attempt: lastSync(closed.effects).attempt,
})
expect(lastSync(next.effects)).toMatchObject({ allow: true })
expect(entry(next.state)).toMatchObject({ status: "attaching", connectionID: "conn_2" })
})
test("stale sync results and stale attach events change nothing", () => {
const initial = BrowserMachine.createConnectionState()
const first = run(initial, attach(initial, "conn_1"))
for (const event of [
synced(99),
{ type: "permissions.failed", sessionID, attempt: 99, error: undefined },
{ type: "permissions.timed-out", sessionID, attempt: 99 },
synced(lastSync(first.effects).attempt, other),
{ type: "attach.closed", sessionID, attempt: 99 },
{ type: "attach.started", sessionID, attempt: 1, connectionID: "conn_9" },
] satisfies Event[]) {
const next = BrowserMachine.transitionConnection(first.state, event)
expect(next.state).toBe(first.state)
expect(next.effects).toEqual([])
}
})
})
describe("reconcileBrowserPermissions", () => {
const user = { action: "bash", resource: "*", effect: "ask" } as const
const allows = BrowserMachine.ACCESS.map((rule) => ({ ...rule, effect: "allow" as const }))
test("granting what is already granted writes nothing", () => {
expect(BrowserMachine.reconcileBrowserPermissions([user, ...allows], true)).toBeUndefined()
expect(BrowserMachine.reconcileBrowserPermissions([user], false)).toBeUndefined()
expect(BrowserMachine.reconcileBrowserPermissions(undefined, false)).toBeUndefined()
})
test("revoking removes every duplicate and keeps the user's rules in order", () => {
expect(BrowserMachine.reconcileBrowserPermissions([...allows, user, ...allows], false)).toEqual([user])
expect(BrowserMachine.reconcileBrowserPermissions([...allows, user, ...allows], true)).toEqual([user, ...allows])
expect(BrowserMachine.reconcileBrowserPermissions(undefined, true)).toEqual(allows)
})
test("browser denies are not browser allows", () => {
const deny = { action: "browser", resource: "*", effect: "deny" } as const
expect(BrowserMachine.reconcileBrowserPermissions([deny], false)).toBeUndefined()
})
})
describe("requests", () => {
const live = () => {
const state = attached()
return run(state, started("req_1"))
}
test("a started request dispatches once and keeps its command for the desktop", () => {
const next = live()
expect(next.effects).toEqual([{ type: "dispatch-command", sessionID, connectionID: "conn_1", requestID: "req_1" }])
expect(BrowserMachine.selectPendingCommand(next.state, sessionID, "conn_1", "req_1")).toBe(command)
expect(BrowserMachine.selectPendingCommand(next.state, sessionID, "conn_2", "req_1")).toBeUndefined()
})
test.each([
{ outcome: success, expected: { ok: true, result: { value: { ok: true }, files: [] } } },
{
outcome: failure,
expected: { ok: false, error: expect.objectContaining({ message: "[browser.navigation] Blocked" }) },
},
])("a result settles the request ($outcome.type)", ({ outcome, expected }) => {
const next = run(live().state, {
type: "request.settled",
sessionID,
connectionID: "conn_1",
requestID: "req_1",
outcome,
})
expect(next.effects).toEqual([{ type: "settle-request", requestID: "req_1", settlement: expected }])
expect(BrowserMachine.selectPendingCommand(next.state, sessionID, "conn_1", "req_1")).toBeUndefined()
})
test("a failed dispatch settles without a cancel", () => {
const next = run(live().state, {
type: "request.dispatch-failed",
sessionID,
connectionID: "conn_1",
requestID: "req_1",
error: new Error("bus closed"),
})
expect(controls(next.effects)).toEqual([])
expect(message(settlements(next.effects)[0]!.settlement)).toContain("Could not dispatch browser.tabs.list")
})
test("a timeout settles and cancels on the desktop", () => {
const next = run(live().state, { type: "request.timed-out", sessionID, connectionID: "conn_1", requestID: "req_1" })
expect(message(settlements(next.effects)[0]!.settlement)).toContain("[browser.timeout]")
expect(controls(next.effects)).toEqual([{ type: "cancel", connectionID: "conn_1", requestID: "req_1" }])
})
test("an interrupted caller cancels on the desktop without a settlement", () => {
const next = run(live().state, { type: "request.cancelled", sessionID, connectionID: "conn_1", requestID: "req_1" })
expect(next.effects).toEqual([
{ type: "emit-control", control: { type: "cancel", connectionID: "conn_1", requestID: "req_1" } },
])
})
test("a close fails pending requests as possibly run, without a cancel", () => {
const next = run(live().state, { type: "attach.closed", sessionID, attempt: 1 })
expect(controls(next.effects)).toEqual([])
expect(message(settlements(next.effects)[0]!.settlement)).toContain("the action may already have run")
})
test("late results after a settlement change nothing", () => {
const settled = run(live().state, {
type: "request.settled",
sessionID,
connectionID: "conn_1",
requestID: "req_1",
outcome: success,
}).state
for (const event of [
{ type: "request.settled", sessionID, connectionID: "conn_1", requestID: "req_1", outcome: success },
{ type: "request.timed-out", sessionID, connectionID: "conn_1", requestID: "req_1" },
{ type: "request.cancelled", sessionID, connectionID: "conn_1", requestID: "req_1" },
{ type: "request.dispatch-failed", sessionID, connectionID: "conn_1", requestID: "req_1", error: undefined },
] satisfies Event[]) {
const next = BrowserMachine.transitionConnection(settled, event)
expect(next.state).toBe(settled)
expect(next.effects).toEqual([])
}
})
})
describe("browser state", () => {
test("the reported inventory resolves tab targets; another connection's report is ignored", () => {
const state = attached()
const browserState = { tabs: [tab], focusedTabID: tabID }
const stale = BrowserMachine.transitionConnection(state, {
type: "state.updated",
sessionID,
connectionID: "conn_2",
browserState,
})
expect(stale.state).toBe(state)
expect(BrowserMachine.selectTarget(state, sessionID, { type: "back", tabID })).toMatchObject({
ok: false,
error: { message: expect.stringContaining("[browser.tab_unavailable]") },
})
const next = run(state, { type: "state.updated", sessionID, connectionID: "conn_1", browserState })
expect(BrowserMachine.selectTarget(next.state, sessionID, { type: "back", tabID })).toMatchObject({ ok: true, tab })
})
})
describe("session lifecycle", () => {
test("deleting an attached session closes it without a revoke", () => {
const next = run(attached(), { type: "session.deleted", sessionID })
expect(next.effects).toEqual([{ type: "close-attachment", attempt: 1, outcome: "closed" }])
expect(entry(next.state)).toBeUndefined()
})
test("deleting an attaching session ends after its grant settles, without a revoke", () => {
const initial = BrowserMachine.createConnectionState()
const first = run(initial, attach(initial, "conn_1"))
const deleted = run(first.state, { type: "session.deleted", sessionID })
expect(entry(deleted.state)).toMatchObject({ status: "revoking", deleted: true })
const done = run(deleted.state, synced(lastSync(first.effects).attempt))
expect(entry(done.state)).toBeUndefined()
expect(done.effects).toEqual([])
})
test("moving an attached session revokes its grant", () => {
const next = run(attached(), { type: "session.moved", sessionID })
expect(next.effects).toContainEqual({ type: "close-attachment", attempt: 1, outcome: "closed" })
expect(lastSync(next.effects)).toMatchObject({ allow: false })
})
})
describe("disposal", () => {
test("an idle plugin drains at once", () => {
const next = run(BrowserMachine.createConnectionState(), { type: "disposed" })
expect(next.effects).toEqual([{ type: "notify-drained" }])
expect(BrowserMachine.isConnectionDisposed(next.state)).toBe(true)
})
test("disposal closes every attachment at once and drains only when the last revoke settles", () => {
const first = attached()
const withOther = run(first, attach(first, "conn_other", other))
const otherGrant = lastSync(withOther.effects)
const disposed = run(withOther.state, { type: "disposed" })
expect(disposed.effects).toContainEqual({ type: "close-attachment", attempt: 1, outcome: "closed" })
expect(disposed.effects).toContainEqual({ type: "close-attachment", attempt: 3, outcome: "closed" })
expect(disposed.effects).not.toContainEqual({ type: "notify-drained" })
expect(BrowserMachine.selectTarget(disposed.state, sessionID, { type: "tabs.list" }).ok).toBe(false)
expect(BrowserMachine.selectAttachment(disposed.state, sessionID, "conn_1")).toBeUndefined()
const revoke = lastSync(disposed.effects)
const firstDone = run(disposed.state, synced(revoke.attempt))
expect(firstDone.effects).toEqual([])
// The other session's grant was still in flight; it is revoked before the plugin drains.
const otherSettled = run(firstDone.state, synced(otherGrant.attempt, other))
const otherRevoke = lastSync(otherSettled.effects)
expect(otherRevoke).toMatchObject({ sessionID: other, allow: false })
expect(otherSettled.effects).not.toContainEqual({ type: "notify-drained" })
const drained = run(otherSettled.state, synced(otherRevoke.attempt, other))
expect(drained.effects).toEqual([{ type: "notify-drained" }])
expect(drained.state.sessions.size).toBe(0)
})
test("a disposed plugin rejects requests and ignores attachments", () => {
const disposed = run(BrowserMachine.createConnectionState(), { type: "disposed" }).state
const request = BrowserMachine.transitionConnection(disposed, started("req_1"))
expect(request.state).toBe(disposed)
expect(message(settlements(request.effects)[0]!.settlement)).toContain("no action ran")
const late = BrowserMachine.transitionConnection(disposed, attach(disposed, "conn_1"))
expect(late.state).toBe(disposed)
expect(late.effects).toEqual([])
})
})