From d1da4264a90525c0c89b777d286b64c8bc187af8 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Wed, 4 Nov 2026 21:07:21 -0600 Subject: [PATCH] fix(desktop): serialize force focus and fix the debug bar toggle (#61885) --- packages/desktop/src/main/native/debug.ts | 214 ++++++++++------ .../main/native/force-focus-machine.test.ts | 220 ++++++++++++++++ .../src/main/native/force-focus-machine.ts | 241 ++++++++++++++++++ packages/gui-plugins/src/debug/bar.tsx | 41 ++- .../src/debug/focus-machine.test.ts | 105 ++++++++ .../gui-plugins/src/debug/focus-machine.ts | 84 ++++++ 6 files changed, 813 insertions(+), 92 deletions(-) create mode 100644 packages/desktop/src/main/native/force-focus-machine.test.ts create mode 100644 packages/desktop/src/main/native/force-focus-machine.ts create mode 100644 packages/gui-plugins/src/debug/focus-machine.test.ts create mode 100644 packages/gui-plugins/src/debug/focus-machine.ts diff --git a/packages/desktop/src/main/native/debug.ts b/packages/desktop/src/main/native/debug.ts index f481577dfc3..245d463d61a 100644 --- a/packages/desktop/src/main/native/debug.ts +++ b/packages/desktop/src/main/native/debug.ts @@ -1,8 +1,13 @@ import type { WebContents } from "electron" - -const focusDebuggerOwners = new WeakSet() - -const forcedFocusNodes = new WeakMap() +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 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((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 | 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) => { + 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 } diff --git a/packages/desktop/src/main/native/force-focus-machine.test.ts b/packages/desktop/src/main/native/force-focus-machine.test.ts new file mode 100644 index 00000000000..2ee294770d1 --- /dev/null +++ b/packages/desktop/src/main/native/force-focus-machine.test.ts @@ -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() + +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[][] }>( + (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) + }) +}) diff --git a/packages/desktop/src/main/native/force-focus-machine.ts b/packages/desktop/src/main/native/force-focus-machine.ts new file mode 100644 index 00000000000..8d0f87650d5 --- /dev/null +++ b/packages/desktop/src/main/native/force-focus-machine.ts @@ -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: [] } +} diff --git a/packages/gui-plugins/src/debug/bar.tsx b/packages/gui-plugins/src/debug/bar.tsx index 746dbc5ce1d..34c08353b39 100644 --- a/packages/gui-plugins/src/debug/bar.tsx +++ b/packages/gui-plugins/src/debug/bar.tsx @@ -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 (