mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-21 04:12:08 +03:00
fix(desktop): serialize force focus and fix the debug bar toggle (#61885)
This commit is contained in:
committed by
GitHub
Unverified
parent
6540d9b01c
commit
d1da4264a9
@@ -1,8 +1,13 @@
|
||||
import type { WebContents } from "electron"
|
||||
|
||||
const focusDebuggerOwners = new WeakSet<WebContents>()
|
||||
|
||||
const forcedFocusNodes = new WeakMap<WebContents, number[]>()
|
||||
import { Schema } from "effect"
|
||||
import {
|
||||
initialForceFocusState,
|
||||
isCurrentForceFocusAttempt,
|
||||
transitionForceFocus,
|
||||
type ForceFocusCommand,
|
||||
type ForceFocusEvent,
|
||||
type ForceFocusState,
|
||||
} from "./force-focus-machine"
|
||||
|
||||
const focusableSelector = `
|
||||
a[href],
|
||||
@@ -15,93 +20,142 @@ const focusableSelector = `
|
||||
[tabindex]:not([tabindex="-1"])
|
||||
`
|
||||
|
||||
export async function setForceFocus(contents: WebContents, enabled: boolean) {
|
||||
const debuggerApi = contents.debugger
|
||||
// Bounds each CDP command, so a hung one cannot hold the window's later requests forever.
|
||||
const COMMAND_TIMEOUT_MS = 10_000
|
||||
|
||||
if (!debuggerApi.isAttached()) {
|
||||
if (!enabled) {
|
||||
focusDebuggerOwners.delete(contents)
|
||||
forcedFocusNodes.delete(contents)
|
||||
const DocumentResult = Schema.Struct({ root: Schema.Struct({ nodeId: Schema.Number }) })
|
||||
|
||||
return
|
||||
}
|
||||
const QuerySelectorAllResult = Schema.Struct({ nodeIds: Schema.Array(Schema.Number) })
|
||||
|
||||
debuggerApi.attach("1.3")
|
||||
focusDebuggerOwners.add(contents)
|
||||
debuggerApi.once("detach", () => {
|
||||
focusDebuggerOwners.delete(contents)
|
||||
forcedFocusNodes.delete(contents)
|
||||
})
|
||||
}
|
||||
const drivers = new WeakMap<WebContents, (event: ForceFocusEvent) => void>()
|
||||
|
||||
if (!enabled) {
|
||||
await Promise.allSettled(
|
||||
(forcedFocusNodes.get(contents) ?? []).map((nodeId) =>
|
||||
debuggerApi.sendCommand("CSS.forcePseudoState", {
|
||||
nodeId,
|
||||
forcedPseudoClasses: [],
|
||||
}),
|
||||
),
|
||||
)
|
||||
forcedFocusNodes.delete(contents)
|
||||
export function setForceFocus(contents: WebContents, enabled: boolean) {
|
||||
if (contents.isDestroyed()) return enabled ? Promise.reject(new Error("Window closed")) : Promise.resolve()
|
||||
const dispatch = drivers.get(contents) ?? createDriver(contents)
|
||||
|
||||
if (!focusDebuggerOwners.delete(contents)) return
|
||||
debuggerApi.detach()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
await debuggerApi.sendCommand("DOM.enable")
|
||||
await debuggerApi.sendCommand("CSS.enable")
|
||||
|
||||
const document: unknown = await debuggerApi.sendCommand("DOM.getDocument", {
|
||||
depth: -1,
|
||||
pierce: true,
|
||||
})
|
||||
|
||||
const nodes: unknown = await debuggerApi.sendCommand("DOM.querySelectorAll", {
|
||||
nodeId: readDocumentNodeId(document),
|
||||
selector: focusableSelector,
|
||||
})
|
||||
|
||||
const nodeIds = readNodeIds(nodes)
|
||||
forcedFocusNodes.set(contents, [...new Set([...(forcedFocusNodes.get(contents) ?? []), ...nodeIds])])
|
||||
await Promise.allSettled(
|
||||
nodeIds.map((nodeId) =>
|
||||
debuggerApi.sendCommand("CSS.forcePseudoState", {
|
||||
nodeId,
|
||||
forcedPseudoClasses: ["focus", "focus-visible"],
|
||||
}),
|
||||
),
|
||||
return new Promise<void>((resolve, reject) =>
|
||||
dispatch({ type: "request", request: { enabled, reply: { resolve, reject } } }),
|
||||
)
|
||||
}
|
||||
|
||||
function readDocumentNodeId(value: unknown) {
|
||||
if (
|
||||
!value ||
|
||||
typeof value !== "object" ||
|
||||
!("root" in value) ||
|
||||
!value.root ||
|
||||
typeof value.root !== "object" ||
|
||||
!("nodeId" in value.root) ||
|
||||
typeof value.root.nodeId !== "number"
|
||||
) {
|
||||
throw new Error("Invalid DOM.getDocument response")
|
||||
// Runs one window's force focus machine. Events queue while a transition runs its commands, so an event a command
|
||||
// raises synchronously sees the state that command belongs to.
|
||||
function createDriver(contents: WebContents) {
|
||||
const debuggerApi = contents.debugger
|
||||
const queue: ForceFocusEvent[] = []
|
||||
let state: ForceFocusState = initialForceFocusState
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
let draining = false
|
||||
|
||||
const dispatch = (event: ForceFocusEvent) => {
|
||||
queue.push(event)
|
||||
|
||||
if (draining) return
|
||||
|
||||
draining = true
|
||||
|
||||
for (let next = queue.shift(); next; next = queue.shift()) {
|
||||
const result = transitionForceFocus(state, next)
|
||||
state = result.state
|
||||
result.commands.forEach(run)
|
||||
}
|
||||
|
||||
draining = false
|
||||
}
|
||||
|
||||
return value.root.nodeId
|
||||
}
|
||||
const onDetach = () => dispatch({ type: "debugger.detached" })
|
||||
|
||||
function readNodeIds(value: unknown) {
|
||||
if (
|
||||
!value ||
|
||||
typeof value !== "object" ||
|
||||
!("nodeIds" in value) ||
|
||||
!Array.isArray(value.nodeIds) ||
|
||||
!value.nodeIds.every((nodeId) => typeof nodeId === "number")
|
||||
) {
|
||||
throw new Error("Invalid DOM.querySelectorAll response")
|
||||
// The machine already counts its own detach; only another client's detach is an event.
|
||||
const detach = () => {
|
||||
if (!debuggerApi.isAttached()) return
|
||||
debuggerApi.off("detach", onDetach)
|
||||
debuggerApi.detach()
|
||||
debuggerApi.on("detach", onDetach)
|
||||
}
|
||||
|
||||
return value.nodeIds
|
||||
const arm = (attempt: number) => {
|
||||
clearTimeout(timer)
|
||||
timer = setTimeout(() => dispatch({ type: "timed-out", attempt }), COMMAND_TIMEOUT_MS)
|
||||
}
|
||||
|
||||
const enable = async (attempt: number) => {
|
||||
if (!debuggerApi.isAttached()) {
|
||||
debuggerApi.attach("1.3")
|
||||
dispatch({ type: "debugger.attached", attempt })
|
||||
}
|
||||
|
||||
await debuggerApi.sendCommand("DOM.enable")
|
||||
await debuggerApi.sendCommand("CSS.enable")
|
||||
|
||||
const document = Schema.decodeUnknownSync(DocumentResult)(
|
||||
await debuggerApi.sendCommand("DOM.getDocument", { depth: -1, pierce: true }),
|
||||
)
|
||||
|
||||
const nodes = Schema.decodeUnknownSync(QuerySelectorAllResult)(
|
||||
await debuggerApi.sendCommand("DOM.querySelectorAll", {
|
||||
nodeId: document.root.nodeId,
|
||||
selector: focusableSelector,
|
||||
}),
|
||||
)
|
||||
|
||||
// A timed-out or superseded attempt must not force styles the machine no longer tracks.
|
||||
if (!isCurrentForceFocusAttempt(state, attempt)) return nodes.nodeIds
|
||||
await Promise.allSettled(
|
||||
nodes.nodeIds.map((nodeId) =>
|
||||
debuggerApi.sendCommand("CSS.forcePseudoState", { nodeId, forcedPseudoClasses: ["focus", "focus-visible"] }),
|
||||
),
|
||||
)
|
||||
|
||||
return nodes.nodeIds
|
||||
}
|
||||
|
||||
const disable = async (command: Extract<ForceFocusCommand, { type: "disable" }>) => {
|
||||
await Promise.allSettled(
|
||||
command.nodeIds.map((nodeId) =>
|
||||
debuggerApi.sendCommand("CSS.forcePseudoState", { nodeId, forcedPseudoClasses: [] }),
|
||||
),
|
||||
)
|
||||
|
||||
// A later attempt may have attached the debugger again by now.
|
||||
if (command.owned && isCurrentForceFocusAttempt(state, command.attempt)) detach()
|
||||
}
|
||||
|
||||
const run = (command: ForceFocusCommand) => {
|
||||
switch (command.type) {
|
||||
case "enable":
|
||||
arm(command.attempt)
|
||||
|
||||
return void enable(command.attempt).then(
|
||||
(nodeIds) => dispatch({ type: "enable.succeeded", attempt: command.attempt, nodeIds }),
|
||||
(cause) =>
|
||||
dispatch({
|
||||
type: "enable.failed",
|
||||
attempt: command.attempt,
|
||||
error: cause instanceof Error ? cause : new Error(String(cause)),
|
||||
}),
|
||||
)
|
||||
case "disable":
|
||||
arm(command.attempt)
|
||||
|
||||
return void disable(command).then(() => dispatch({ type: "disable.settled", attempt: command.attempt }))
|
||||
case "detach":
|
||||
return detach()
|
||||
case "cancel-timer":
|
||||
clearTimeout(timer)
|
||||
timer = undefined
|
||||
|
||||
return
|
||||
case "settle":
|
||||
return command.replies.forEach((reply) => (command.error ? reply.reject(command.error) : reply.resolve()))
|
||||
}
|
||||
}
|
||||
|
||||
debuggerApi.on("detach", onDetach)
|
||||
contents.once("destroyed", () => {
|
||||
debuggerApi.off("detach", onDetach)
|
||||
dispatch({ type: "destroyed" })
|
||||
})
|
||||
drivers.set(contents, dispatch)
|
||||
|
||||
return dispatch
|
||||
}
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
initialForceFocusState,
|
||||
transitionForceFocus,
|
||||
type ForceFocusCommand,
|
||||
type ForceFocusEvent,
|
||||
type ForceFocusReply,
|
||||
type ForceFocusState,
|
||||
} from "./force-focus-machine"
|
||||
|
||||
const names = new Map<ForceFocusReply, string>()
|
||||
|
||||
function request(name: string, enabled: boolean): ForceFocusEvent {
|
||||
const reply = { resolve: () => undefined, reject: () => undefined }
|
||||
names.set(reply, name)
|
||||
|
||||
return { type: "request", request: { enabled, reply } }
|
||||
}
|
||||
|
||||
// Names each reply so a step reads as which requests resolved and which were rejected, and why.
|
||||
function readable(command: ForceFocusCommand) {
|
||||
if (command.type !== "settle") return command
|
||||
const replies = command.replies.map((reply) => names.get(reply))
|
||||
|
||||
if (!command.error) return { type: "resolve", replies }
|
||||
|
||||
return { type: "reject", replies, error: command.error.message }
|
||||
}
|
||||
|
||||
// Folds events through the machine and keeps the readable commands of each step.
|
||||
function replay(events: readonly ForceFocusEvent[], from = initialForceFocusState) {
|
||||
return events.reduce<{ state: ForceFocusState; commands: ReturnType<typeof readable>[][] }>(
|
||||
(result, event) => {
|
||||
const next = transitionForceFocus(result.state, event)
|
||||
|
||||
return { state: next.state, commands: [...result.commands, next.commands.map(readable)] }
|
||||
},
|
||||
{ state: from, commands: [] },
|
||||
)
|
||||
}
|
||||
|
||||
const failure = new Error("DOM.enable failed")
|
||||
|
||||
describe("force focus debugger", () => {
|
||||
test("turning off while turning on waits for the enable instead of detaching under it", () => {
|
||||
// On dev the second call found no forced nodes yet and detached the debugger under the running enable.
|
||||
const run = replay([
|
||||
request("on", true),
|
||||
{ type: "debugger.attached", attempt: 1 },
|
||||
request("off", false),
|
||||
{ type: "enable.succeeded", attempt: 1, nodeIds: [10, 11] },
|
||||
{ type: "disable.settled", attempt: 2 },
|
||||
])
|
||||
|
||||
expect(run.commands).toEqual([
|
||||
[{ type: "enable", attempt: 1 }],
|
||||
[],
|
||||
[],
|
||||
[
|
||||
{ type: "resolve", replies: ["on"] },
|
||||
{ type: "disable", attempt: 2, owned: true, nodeIds: [10, 11] },
|
||||
],
|
||||
[{ type: "cancel-timer" }, { type: "resolve", replies: ["off"] }],
|
||||
])
|
||||
expect(run.state).toEqual({ status: "off", attempt: 2 })
|
||||
})
|
||||
|
||||
test("a failed enable detaches the debugger it attached", () => {
|
||||
// On dev a CDP failure after attach left the debugger attached.
|
||||
const owned = replay([
|
||||
request("on", true),
|
||||
{ type: "debugger.attached", attempt: 1 },
|
||||
{ type: "enable.failed", attempt: 1, error: failure },
|
||||
])
|
||||
|
||||
expect(owned.commands.at(-1)).toEqual([
|
||||
{ type: "cancel-timer" },
|
||||
{ type: "detach" },
|
||||
{ type: "reject", replies: ["on"], error: failure.message },
|
||||
])
|
||||
expect(owned.state).toEqual({ status: "off", attempt: 1 })
|
||||
|
||||
// Another client attached the debugger first, so it stays attached.
|
||||
const external = replay([request("on", true), { type: "enable.failed", attempt: 1, error: failure }])
|
||||
|
||||
expect(external.commands.at(-1)).toEqual([
|
||||
{ type: "cancel-timer" },
|
||||
{ type: "reject", replies: ["on"], error: failure.message },
|
||||
])
|
||||
})
|
||||
|
||||
test("a failed enable clears the nodes an earlier enable forced on a debugger it does not own", () => {
|
||||
const on = replay([request("first", true), { type: "enable.succeeded", attempt: 1, nodeIds: [4] }]).state
|
||||
const run = replay([request("again", true), { type: "enable.failed", attempt: 2, error: failure }], on)
|
||||
|
||||
expect(run.commands.at(-1)).toEqual([
|
||||
{ type: "reject", replies: ["again"], error: failure.message },
|
||||
{ type: "disable", attempt: 3, owned: false, nodeIds: [4] },
|
||||
])
|
||||
expect(replay([{ type: "disable.settled", attempt: 3 }], run.state).state).toEqual({ status: "off", attempt: 3 })
|
||||
})
|
||||
|
||||
test("on, off and on again while enabling settles on without another command", () => {
|
||||
const requests = [request("a", true), request("b", false), request("c", true)]
|
||||
const succeeded = replay([...requests, { type: "enable.succeeded", attempt: 1, nodeIds: [5] }])
|
||||
|
||||
expect(succeeded.commands.at(-1)).toEqual([{ type: "cancel-timer" }, { type: "resolve", replies: ["a", "b", "c"] }])
|
||||
expect(succeeded.state).toEqual({ status: "on", attempt: 1, owned: false, nodeIds: [5] })
|
||||
|
||||
const failed = replay([...requests, { type: "enable.failed", attempt: 1, error: failure }])
|
||||
|
||||
expect(failed.commands.at(-1)).toEqual([
|
||||
{ type: "cancel-timer" },
|
||||
{ type: "resolve", replies: ["b"] },
|
||||
{ type: "reject", replies: ["a", "c"], error: failure.message },
|
||||
])
|
||||
})
|
||||
|
||||
test("turning on while turning off enables again once the disable settles", () => {
|
||||
const on = replay([request("on", true), { type: "enable.succeeded", attempt: 1, nodeIds: [1] }]).state
|
||||
const run = replay([request("off", false), request("back", true), { type: "disable.settled", attempt: 2 }], on)
|
||||
|
||||
expect(run.commands).toEqual([
|
||||
[{ type: "disable", attempt: 2, owned: false, nodeIds: [1] }],
|
||||
[],
|
||||
[
|
||||
{ type: "resolve", replies: ["off"] },
|
||||
{ type: "enable", attempt: 3 },
|
||||
],
|
||||
])
|
||||
expect(run.state).toMatchObject({ status: "enabling", attempt: 3, owned: false, nodeIds: [], desired: true })
|
||||
})
|
||||
|
||||
test("a timed out command rolls back and answers every request", () => {
|
||||
const enabling = replay([request("on", true), { type: "debugger.attached", attempt: 1 }, request("off", false)])
|
||||
const timedOut = replay([{ type: "timed-out", attempt: 1 }], enabling.state)
|
||||
|
||||
expect(timedOut.commands).toEqual([
|
||||
[
|
||||
{ type: "cancel-timer" },
|
||||
{ type: "detach" },
|
||||
{ type: "resolve", replies: ["off"] },
|
||||
{ type: "reject", replies: ["on"], error: "Timed out forcing focus styles" },
|
||||
],
|
||||
])
|
||||
expect(timedOut.state).toEqual({ status: "off", attempt: 1 })
|
||||
|
||||
const on = replay([
|
||||
request("on", true),
|
||||
{ type: "debugger.attached", attempt: 1 },
|
||||
{ type: "enable.succeeded", attempt: 1, nodeIds: [] },
|
||||
])
|
||||
|
||||
const disabling = replay([request("off", false), { type: "timed-out", attempt: 2 }], on.state)
|
||||
|
||||
expect(disabling.commands.at(-1)).toEqual([
|
||||
{ type: "cancel-timer" },
|
||||
{ type: "detach" },
|
||||
{ type: "resolve", replies: ["off"] },
|
||||
])
|
||||
})
|
||||
|
||||
test("ignores results of other attempts", () => {
|
||||
const enabling = replay([request("on", true)]).state
|
||||
|
||||
const events: ForceFocusEvent[] = [
|
||||
{ type: "debugger.attached", attempt: 2 },
|
||||
{ type: "enable.succeeded", attempt: 0, nodeIds: [1] },
|
||||
{ type: "enable.failed", attempt: 2, error: failure },
|
||||
{ type: "disable.settled", attempt: 1 },
|
||||
{ type: "timed-out", attempt: 2 },
|
||||
]
|
||||
|
||||
events.forEach((event) => expect(transitionForceFocus(enabling, event)).toEqual({ state: enabling, commands: [] }))
|
||||
expect(transitionForceFocus(initialForceFocusState, { type: "timed-out", attempt: 0 }).state).toBe(
|
||||
initialForceFocusState,
|
||||
)
|
||||
})
|
||||
|
||||
test("an external detach ends force focus", () => {
|
||||
const on = replay([request("on", true), { type: "enable.succeeded", attempt: 1, nodeIds: [1] }]).state
|
||||
|
||||
expect(replay([{ type: "debugger.detached" }], on).state).toEqual({ status: "off", attempt: 1 })
|
||||
|
||||
const enabling = replay([request("on", true), request("off", false), { type: "debugger.detached" }])
|
||||
|
||||
expect(enabling.commands.at(-1)).toEqual([
|
||||
{ type: "cancel-timer" },
|
||||
{ type: "resolve", replies: ["off"] },
|
||||
{ type: "reject", replies: ["on"], error: "Debugger detached" },
|
||||
])
|
||||
|
||||
// The detach finishes the running disable; its own late result changes nothing.
|
||||
const disabling = replay(
|
||||
[request("off", false), { type: "debugger.detached" }, { type: "disable.settled", attempt: 2 }],
|
||||
on,
|
||||
)
|
||||
|
||||
expect(disabling.commands.slice(1)).toEqual([[{ type: "cancel-timer" }, { type: "resolve", replies: ["off"] }], []])
|
||||
})
|
||||
|
||||
test("a closed window answers pending and later requests", () => {
|
||||
const closed = replay([request("on", true), request("off", false), { type: "destroyed" }])
|
||||
|
||||
expect(closed.commands.at(-1)).toEqual([
|
||||
{ type: "cancel-timer" },
|
||||
{ type: "resolve", replies: ["off"] },
|
||||
{ type: "reject", replies: ["on"], error: "Window closed" },
|
||||
])
|
||||
expect(closed.state).toEqual({ status: "disposed" })
|
||||
|
||||
const late = replay([request("late on", true), request("late off", false)], closed.state)
|
||||
|
||||
expect(late.commands).toEqual([
|
||||
[{ type: "reject", replies: ["late on"], error: "Window closed" }],
|
||||
[{ type: "resolve", replies: ["late off"] }],
|
||||
])
|
||||
expect(late.state).toBe(closed.state)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,241 @@
|
||||
export type ForceFocusReply = {
|
||||
readonly resolve: () => void
|
||||
readonly reject: (error: Error) => void
|
||||
}
|
||||
|
||||
export type ForceFocusRequest = {
|
||||
readonly enabled: boolean
|
||||
readonly reply: ForceFocusReply
|
||||
}
|
||||
|
||||
type Busy = {
|
||||
readonly attempt: number
|
||||
readonly owned: boolean
|
||||
readonly nodeIds: readonly number[]
|
||||
readonly desired: boolean
|
||||
readonly requests: readonly ForceFocusRequest[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Forced `:focus` styles on one window's WebContents. One CDP command runs at a time: `enabling` and `disabling` hold
|
||||
* the requests that arrive meanwhile, and `desired` is the latest of them, applied once the running command settles.
|
||||
* `owned` is true when force focus attached the debugger itself and must detach it; false when another client had
|
||||
* attached it first. `nodeIds` are the nodes forced so far.
|
||||
*/
|
||||
export type ForceFocusState =
|
||||
| { readonly status: "off"; readonly attempt: number }
|
||||
| { readonly status: "on"; readonly attempt: number; readonly owned: boolean; readonly nodeIds: readonly number[] }
|
||||
| (Busy & { readonly status: "enabling" })
|
||||
| (Busy & { readonly status: "disabling" })
|
||||
| { readonly status: "disposed" }
|
||||
|
||||
export type ForceFocusEvent =
|
||||
| { readonly type: "request"; readonly request: ForceFocusRequest }
|
||||
| { readonly type: "debugger.attached"; readonly attempt: number }
|
||||
| { readonly type: "enable.succeeded"; readonly attempt: number; readonly nodeIds: readonly number[] }
|
||||
| { readonly type: "enable.failed"; readonly attempt: number; readonly error: Error }
|
||||
| { readonly type: "disable.settled"; readonly attempt: number }
|
||||
| { readonly type: "timed-out"; readonly attempt: number }
|
||||
| { readonly type: "debugger.detached" }
|
||||
| { readonly type: "destroyed" }
|
||||
|
||||
export type ForceFocusCommand =
|
||||
| { readonly type: "enable"; readonly attempt: number }
|
||||
| { readonly type: "disable"; readonly attempt: number; readonly owned: boolean; readonly nodeIds: readonly number[] }
|
||||
| { readonly type: "detach" }
|
||||
| { readonly type: "cancel-timer" }
|
||||
| { readonly type: "settle"; readonly replies: readonly ForceFocusReply[]; readonly error?: Error }
|
||||
|
||||
export type ForceFocusTransition = {
|
||||
readonly state: ForceFocusState
|
||||
readonly commands: readonly ForceFocusCommand[]
|
||||
}
|
||||
|
||||
export const initialForceFocusState: ForceFocusState = Object.freeze({ status: "off", attempt: 0 })
|
||||
|
||||
export function transitionForceFocus(state: ForceFocusState, event: ForceFocusEvent): ForceFocusTransition {
|
||||
if (state.status === "disposed") {
|
||||
if (event.type !== "request") return unchanged(state)
|
||||
|
||||
return { state, commands: settleSplit([event.request], new Error("Window closed")) }
|
||||
}
|
||||
|
||||
switch (event.type) {
|
||||
case "request": {
|
||||
const request = event.request
|
||||
const attempt = state.attempt + 1
|
||||
|
||||
if (state.status === "enabling" || state.status === "disabling") {
|
||||
return {
|
||||
state: { ...state, desired: request.enabled, requests: [...state.requests, request] },
|
||||
commands: [],
|
||||
}
|
||||
}
|
||||
|
||||
if (state.status === "off" && !request.enabled) return { state, commands: settle([request]) }
|
||||
|
||||
const owned = state.status === "on" && state.owned
|
||||
const nodeIds = state.status === "on" ? state.nodeIds : []
|
||||
|
||||
// Turning on again from `on` forces the nodes rendered since.
|
||||
if (request.enabled) {
|
||||
return {
|
||||
state: { status: "enabling", attempt, owned, nodeIds, desired: true, requests: [request] },
|
||||
commands: [{ type: "enable", attempt }],
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
state: { status: "disabling", attempt, owned, nodeIds, desired: false, requests: [request] },
|
||||
commands: [{ type: "disable", attempt, owned, nodeIds }],
|
||||
}
|
||||
}
|
||||
|
||||
case "debugger.attached": {
|
||||
if (state.status !== "enabling" || state.attempt !== event.attempt || state.owned) return unchanged(state)
|
||||
|
||||
return { state: { ...state, owned: true }, commands: [] }
|
||||
}
|
||||
|
||||
case "enable.succeeded": {
|
||||
if (state.status !== "enabling" || state.attempt !== event.attempt) return unchanged(state)
|
||||
const nodeIds = [...new Set([...state.nodeIds, ...event.nodeIds])]
|
||||
|
||||
if (state.desired) {
|
||||
return {
|
||||
state: { status: "on", attempt: state.attempt, owned: state.owned, nodeIds },
|
||||
commands: [{ type: "cancel-timer" }, ...settle(state.requests)],
|
||||
}
|
||||
}
|
||||
|
||||
// Turned off while turning on: the requests to turn on are done, the ones to turn off wait for the reset.
|
||||
const attempt = state.attempt + 1
|
||||
|
||||
return {
|
||||
state: { ...state, status: "disabling", attempt, nodeIds, requests: wanting(state.requests, false) },
|
||||
commands: [...settle(wanting(state.requests, true)), { type: "disable", attempt, owned: state.owned, nodeIds }],
|
||||
}
|
||||
}
|
||||
|
||||
case "enable.failed": {
|
||||
if (state.status !== "enabling" || state.attempt !== event.attempt) return unchanged(state)
|
||||
|
||||
return failEnable(state, event.error)
|
||||
}
|
||||
|
||||
case "disable.settled": {
|
||||
if (state.status !== "disabling" || state.attempt !== event.attempt) return unchanged(state)
|
||||
|
||||
return finishDisable(state, [])
|
||||
}
|
||||
|
||||
case "timed-out": {
|
||||
if (state.status === "enabling" && state.attempt === event.attempt) {
|
||||
return failEnable(state, new Error("Timed out forcing focus styles"))
|
||||
}
|
||||
|
||||
if (state.status !== "disabling" || state.attempt !== event.attempt) return unchanged(state)
|
||||
|
||||
return finishDisable(state, state.owned ? [{ type: "detach" }] : [])
|
||||
}
|
||||
|
||||
case "debugger.detached": {
|
||||
// Another client detached the debugger, which drops every forced style with it.
|
||||
if (state.status === "off") return unchanged(state)
|
||||
|
||||
if (state.status === "on") return { state: { status: "off", attempt: state.attempt }, commands: [] }
|
||||
|
||||
if (state.status === "disabling") return finishDisable(state, [])
|
||||
|
||||
return {
|
||||
state: { status: "off", attempt: state.attempt },
|
||||
commands: [{ type: "cancel-timer" }, ...settleSplit(state.requests, new Error("Debugger detached"))],
|
||||
}
|
||||
}
|
||||
|
||||
case "destroyed": {
|
||||
if (state.status === "off" || state.status === "on") return { state: { status: "disposed" }, commands: [] }
|
||||
|
||||
return {
|
||||
state: { status: "disposed" },
|
||||
commands: [{ type: "cancel-timer" }, ...settleSplit(state.requests, new Error("Window closed"))],
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a CDP command for `attempt` still belongs to the live state. */
|
||||
export function isCurrentForceFocusAttempt(state: ForceFocusState, attempt: number) {
|
||||
return (state.status === "enabling" || state.status === "disabling") && state.attempt === attempt
|
||||
}
|
||||
|
||||
// A failed enable rolls back: detach a debugger it attached, else clear the nodes it forced before.
|
||||
function failEnable(state: Busy, error: Error): ForceFocusTransition {
|
||||
const settled = settleSplit(state.requests, error)
|
||||
|
||||
if (state.owned) {
|
||||
return {
|
||||
state: { status: "off", attempt: state.attempt },
|
||||
commands: [{ type: "cancel-timer" }, { type: "detach" }, ...settled],
|
||||
}
|
||||
}
|
||||
|
||||
if (state.nodeIds.length === 0) {
|
||||
return { state: { status: "off", attempt: state.attempt }, commands: [{ type: "cancel-timer" }, ...settled] }
|
||||
}
|
||||
|
||||
const attempt = state.attempt + 1
|
||||
|
||||
return {
|
||||
state: { status: "disabling", attempt, owned: false, nodeIds: state.nodeIds, desired: false, requests: [] },
|
||||
commands: [...settled, { type: "disable", attempt, owned: false, nodeIds: state.nodeIds }],
|
||||
}
|
||||
}
|
||||
|
||||
// Every forced style is cleared and an owned debugger detached; turn on again if a request asked for it meanwhile.
|
||||
function finishDisable(state: Busy, commands: readonly ForceFocusCommand[]): ForceFocusTransition {
|
||||
if (!state.desired) {
|
||||
return {
|
||||
state: { status: "off", attempt: state.attempt },
|
||||
commands: [{ type: "cancel-timer" }, ...commands, ...settle(state.requests)],
|
||||
}
|
||||
}
|
||||
|
||||
const attempt = state.attempt + 1
|
||||
|
||||
return {
|
||||
state: {
|
||||
status: "enabling",
|
||||
attempt,
|
||||
owned: false,
|
||||
nodeIds: [],
|
||||
desired: true,
|
||||
requests: wanting(state.requests, true),
|
||||
},
|
||||
commands: [...commands, ...settle(wanting(state.requests, false)), { type: "enable", attempt }],
|
||||
}
|
||||
}
|
||||
|
||||
function wanting(requests: readonly ForceFocusRequest[], enabled: boolean) {
|
||||
return requests.filter((request) => request.enabled === enabled)
|
||||
}
|
||||
|
||||
// Requests to turn off are met when force focus ends up off; requests to turn on fail with `error`.
|
||||
function settleSplit(requests: readonly ForceFocusRequest[], error: Error) {
|
||||
return [...settle(wanting(requests, false)), ...settle(wanting(requests, true), error)]
|
||||
}
|
||||
|
||||
// Resolves the requests' replies, or rejects them with `error`.
|
||||
function settle(requests: readonly ForceFocusRequest[], error?: Error): ForceFocusCommand[] {
|
||||
const replies = requests.map((request) => request.reply)
|
||||
|
||||
if (replies.length === 0) return []
|
||||
|
||||
if (!error) return [{ type: "settle", replies }]
|
||||
|
||||
return [{ type: "settle", replies, error }]
|
||||
}
|
||||
|
||||
function unchanged(state: ForceFocusState): ForceFocusTransition {
|
||||
return { state, commands: [] }
|
||||
}
|
||||
@@ -1,12 +1,19 @@
|
||||
import { createMemo, createSignal, onCleanup, Show } from "solid-js"
|
||||
import { createMemo, createSignal, onCleanup, Show, untrack } from "solid-js"
|
||||
import { Icon } from "@opencode/ui/icon"
|
||||
import { IconButton } from "@opencode/ui/icon-button"
|
||||
import { showToast } from "@opencode/ui/toast"
|
||||
import { Tooltip } from "@opencode/ui/tooltip"
|
||||
import { usePlugin } from "@opencode/plugin/gui"
|
||||
import { motionGlobals, motionTuning } from "@opencode/ui/motion-tuning"
|
||||
import { duration } from "@opencode/util/duration"
|
||||
import { SessionTurn } from "@opencode/util/session-turn"
|
||||
import { builtinContext } from "@opencode/plugin/gui/builtin"
|
||||
import {
|
||||
initialFocusToggleState,
|
||||
isFocusToggleActive,
|
||||
transitionFocusToggle,
|
||||
type FocusToggleEvent,
|
||||
} from "./focus-machine"
|
||||
|
||||
const fixed = (n?: number, digits = 0) => {
|
||||
if (n === undefined || Number.isNaN(n)) return
|
||||
@@ -119,7 +126,7 @@ export default function DebugBar(props: {
|
||||
const locale = ctx.locale
|
||||
const desktop = ctx.desktop
|
||||
const sessions = ctx.sessions
|
||||
const [focus, setFocus] = createSignal(false)
|
||||
const [focus, setFocus] = createSignal(initialFocusToggleState)
|
||||
|
||||
const target = createMemo(
|
||||
() => {
|
||||
@@ -167,16 +174,26 @@ export default function DebugBar(props: {
|
||||
|
||||
const na = () => ctx.t("na").toUpperCase()
|
||||
|
||||
const toggleFocus = async () => {
|
||||
const dispatchFocus = (event: FocusToggleEvent) => {
|
||||
if (!desktop) return
|
||||
const enabled = !focus()
|
||||
await desktop.forceFocus(enabled)
|
||||
setFocus(enabled)
|
||||
const next = transitionFocusToggle(untrack(focus), event)
|
||||
setFocus(next.state)
|
||||
next.effects.forEach((effect) => {
|
||||
switch (effect.type) {
|
||||
case "set":
|
||||
return void desktop.forceFocus(effect.enabled).then(
|
||||
() => dispatchFocus({ type: "set.succeeded", attempt: effect.attempt }),
|
||||
() => dispatchFocus({ type: "set.failed", attempt: effect.attempt }),
|
||||
)
|
||||
case "reset":
|
||||
return void desktop.forceFocus(false).catch(() => undefined)
|
||||
case "notify-failed":
|
||||
return void showToast({ title: ctx.t("common.requestFailed") })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
onCleanup(() => {
|
||||
if (focus()) void desktop?.forceFocus(false).catch(() => undefined)
|
||||
})
|
||||
onCleanup(() => dispatchFocus({ type: "disposed" }))
|
||||
|
||||
return (
|
||||
<aside
|
||||
@@ -234,12 +251,12 @@ export default function DebugBar(props: {
|
||||
/>
|
||||
<Show when={desktop}>
|
||||
<ToggleCell
|
||||
active={focus()}
|
||||
active={isFocusToggleActive(focus())}
|
||||
inline={props.inline}
|
||||
label={ctx.t("focus.label")}
|
||||
tip={ctx.t("focus.tip")}
|
||||
value={ctx.t(focus() ? "focus.on" : "focus.off")}
|
||||
onClick={() => void toggleFocus()}
|
||||
value={ctx.t(isFocusToggleActive(focus()) ? "focus.on" : "focus.off")}
|
||||
onClick={() => dispatchFocus({ type: "toggle" })}
|
||||
/>
|
||||
</Show>
|
||||
</Show>
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
initialFocusToggleState,
|
||||
isFocusToggleActive,
|
||||
transitionFocusToggle,
|
||||
type FocusToggleEffect,
|
||||
type FocusToggleEvent,
|
||||
type FocusToggleState,
|
||||
} from "./focus-machine"
|
||||
|
||||
// Folds events through the machine and keeps the effects of each step.
|
||||
function replay(events: readonly FocusToggleEvent[], from = initialFocusToggleState) {
|
||||
return events.reduce<{ state: FocusToggleState; effects: (readonly FocusToggleEffect[])[] }>(
|
||||
(result, event) => {
|
||||
const next = transitionFocusToggle(result.state, event)
|
||||
|
||||
return { state: next.state, effects: [...result.effects, next.effects] }
|
||||
},
|
||||
{ state: from, effects: [] },
|
||||
)
|
||||
}
|
||||
|
||||
const toggle: FocusToggleEvent = { type: "toggle" }
|
||||
|
||||
describe("debug bar force focus toggle", () => {
|
||||
test("closing the bar while turning on still turns force focus off", () => {
|
||||
// On dev the cleanup read `focus() === false` and skipped the reset, and main forced focus once the call landed.
|
||||
const closed = replay([toggle, { type: "disposed" }])
|
||||
|
||||
expect(closed.state).toEqual({ status: "disposed" })
|
||||
expect(closed.effects).toEqual([[{ type: "set", attempt: 1, enabled: true }], [{ type: "reset" }]])
|
||||
expect(transitionFocusToggle(closed.state, { type: "set.succeeded", attempt: 1 }).state).toBe(closed.state)
|
||||
})
|
||||
|
||||
test("a second click while turning on turns force focus back off", () => {
|
||||
// On dev both clicks read `!focus()` before the first call resolved, so both sent `true`.
|
||||
const twice = replay([toggle, toggle])
|
||||
|
||||
expect(twice.effects).toEqual([[{ type: "set", attempt: 1, enabled: true }], []])
|
||||
expect(isFocusToggleActive(twice.state)).toBe(false)
|
||||
|
||||
const settled = replay(
|
||||
[
|
||||
{ type: "set.succeeded", attempt: 1 },
|
||||
{ type: "set.succeeded", attempt: 2 },
|
||||
],
|
||||
twice.state,
|
||||
)
|
||||
|
||||
expect(settled.effects).toEqual([[{ type: "set", attempt: 2, enabled: false }], []])
|
||||
expect(settled.state).toEqual({ status: "idle", attempt: 2, enabled: false })
|
||||
})
|
||||
|
||||
test("a third click before the call settles keeps force focus on without another call", () => {
|
||||
const thrice = replay([toggle, toggle, toggle, { type: "set.succeeded", attempt: 1 }])
|
||||
|
||||
expect(thrice.effects.flat()).toEqual([{ type: "set", attempt: 1, enabled: true }])
|
||||
expect(thrice.state).toEqual({ status: "idle", attempt: 1, enabled: true })
|
||||
})
|
||||
|
||||
test("a failed call reverts the cell and reports it", () => {
|
||||
// On dev the rejection was unhandled and the cell kept its value with no feedback.
|
||||
const failed = replay([toggle, { type: "set.failed", attempt: 1 }])
|
||||
|
||||
expect(failed.state).toEqual({ status: "idle", attempt: 1, enabled: false })
|
||||
expect(failed.effects.at(-1)).toEqual([{ type: "notify-failed" }])
|
||||
expect(isFocusToggleActive(failed.state)).toBe(false)
|
||||
|
||||
const retried = replay([toggle], failed.state)
|
||||
|
||||
expect(retried.effects).toEqual([[{ type: "set", attempt: 2, enabled: true }]])
|
||||
})
|
||||
|
||||
test("a failed call the user already clicked back from settles quietly", () => {
|
||||
const failed = replay([toggle, toggle, { type: "set.failed", attempt: 1 }])
|
||||
|
||||
expect(failed.state).toEqual({ status: "idle", attempt: 1, enabled: false })
|
||||
expect(failed.effects.at(-1)).toEqual([])
|
||||
})
|
||||
|
||||
test("ignores results of other attempts", () => {
|
||||
const changing = replay([toggle]).state
|
||||
|
||||
expect(transitionFocusToggle(changing, { type: "set.succeeded", attempt: 2 }).state).toBe(changing)
|
||||
expect(transitionFocusToggle(changing, { type: "set.failed", attempt: 0 }).state).toBe(changing)
|
||||
expect(transitionFocusToggle(initialFocusToggleState, { type: "set.succeeded", attempt: 0 }).state).toBe(
|
||||
initialFocusToggleState,
|
||||
)
|
||||
})
|
||||
|
||||
test("closing the bar resets force focus only when it may be on", () => {
|
||||
const on = replay([toggle, { type: "set.succeeded", attempt: 1 }]).state
|
||||
const turningOff = replay([toggle], on).state
|
||||
|
||||
expect(transitionFocusToggle(initialFocusToggleState, { type: "disposed" }).effects).toEqual([])
|
||||
expect(transitionFocusToggle(on, { type: "disposed" }).effects).toEqual([{ type: "reset" }])
|
||||
// The call in flight already turns it off.
|
||||
expect(transitionFocusToggle(turningOff, { type: "disposed" }).effects).toEqual([])
|
||||
|
||||
const disposed = transitionFocusToggle(on, { type: "disposed" }).state
|
||||
|
||||
expect(transitionFocusToggle(disposed, toggle).state).toBe(disposed)
|
||||
expect(isFocusToggleActive(disposed)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* The debug bar's FOCUS toggle. `changing` waits for main to apply `target`; main held `!target` before that call.
|
||||
* `desired` is the user's latest click, so a click while the call is in flight flips it, and the follow-up call starts
|
||||
* once this one settles. `attempt` fences call results; `idle` keeps the last one issued.
|
||||
*/
|
||||
export type FocusToggleState =
|
||||
| { readonly status: "idle"; readonly attempt: number; readonly enabled: boolean }
|
||||
| { readonly status: "changing"; readonly attempt: number; readonly target: boolean; readonly desired: boolean }
|
||||
| { readonly status: "disposed" }
|
||||
|
||||
export type FocusToggleEvent =
|
||||
| { readonly type: "toggle" }
|
||||
| { readonly type: "set.succeeded"; readonly attempt: number }
|
||||
| { readonly type: "set.failed"; readonly attempt: number }
|
||||
| { readonly type: "disposed" }
|
||||
|
||||
export type FocusToggleEffect =
|
||||
| { readonly type: "set"; readonly attempt: number; readonly enabled: boolean }
|
||||
| { readonly type: "reset" }
|
||||
| { readonly type: "notify-failed" }
|
||||
|
||||
export type FocusToggleTransition = {
|
||||
readonly state: FocusToggleState
|
||||
readonly effects: readonly FocusToggleEffect[]
|
||||
}
|
||||
|
||||
export const initialFocusToggleState: FocusToggleState = Object.freeze({ status: "idle", attempt: 0, enabled: false })
|
||||
|
||||
export function transitionFocusToggle(state: FocusToggleState, event: FocusToggleEvent): FocusToggleTransition {
|
||||
if (state.status === "disposed") return unchanged(state)
|
||||
|
||||
switch (event.type) {
|
||||
case "toggle": {
|
||||
if (state.status === "idle") return start(state.attempt + 1, !state.enabled)
|
||||
|
||||
return { state: { ...state, desired: !state.desired }, effects: [] }
|
||||
}
|
||||
|
||||
case "set.succeeded": {
|
||||
if (state.status !== "changing" || state.attempt !== event.attempt) return unchanged(state)
|
||||
|
||||
if (state.desired !== state.target) return start(state.attempt + 1, state.desired)
|
||||
|
||||
return { state: { status: "idle", attempt: state.attempt, enabled: state.target }, effects: [] }
|
||||
}
|
||||
|
||||
case "set.failed": {
|
||||
if (state.status !== "changing" || state.attempt !== event.attempt) return unchanged(state)
|
||||
|
||||
return {
|
||||
state: { status: "idle", attempt: state.attempt, enabled: !state.target },
|
||||
// A user who already clicked back has what they asked for.
|
||||
effects: state.desired === state.target ? [{ type: "notify-failed" }] : [],
|
||||
}
|
||||
}
|
||||
|
||||
case "disposed": {
|
||||
// Main may still turn force focus on for a call in flight, so a closing bar always asks to turn it off after.
|
||||
const on = state.status === "idle" ? state.enabled : state.target
|
||||
|
||||
return { state: { status: "disposed" }, effects: on ? [{ type: "reset" }] : [] }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the FOCUS cell shows on: the user's latest choice, ahead of main confirming it. */
|
||||
export function isFocusToggleActive(state: FocusToggleState) {
|
||||
if (state.status === "changing") return state.desired
|
||||
|
||||
if (state.status === "idle") return state.enabled
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
function start(attempt: number, enabled: boolean): FocusToggleTransition {
|
||||
return {
|
||||
state: { status: "changing", attempt, target: enabled, desired: enabled },
|
||||
effects: [{ type: "set", attempt, enabled }],
|
||||
}
|
||||
}
|
||||
|
||||
function unchanged(state: FocusToggleState): FocusToggleTransition {
|
||||
return { state, effects: [] }
|
||||
}
|
||||
Reference in New Issue
Block a user