diff --git a/packages/app/test-browser/browser-pane-model.test.ts b/packages/app/test-browser/browser-pane-model.test.ts index 6949f115d29..3fed0690658 100644 --- a/packages/app/test-browser/browser-pane-model.test.ts +++ b/packages/app/test-browser/browser-pane-model.test.ts @@ -1,4 +1,4 @@ -import { expect, spyOn, test } from "bun:test" +import { afterEach, expect, jest, spyOn, test } from "bun:test" import { createRoot, createSignal } from "solid-js" import type { IpcClient, SessionRef, SetupContext } from "@opencode/plugin/gui" import { liveAccessor } from "@opencode/plugin/gui/host" @@ -20,12 +20,31 @@ const tab = (digit: string, url = `https://${digit}.example/`): Browser.Tab => ( }) // The real model over the pane's main-process Ipc, faked at its boundary, with two shell sessions on one server. -function fixture() { +// `given` is what the window knows of that server, the sessions' location and the pane's Ipc as the model starts. +// With `slow`, main takes a registration only once the test calls `answer`, as while it attaches to the server. +function fixture( + given: { connected?: boolean; compatible?: boolean; local?: boolean; located?: boolean; ipc?: "active" | "pending" | "inactive"; slow?: boolean } = {}, +) { const bindings = new Map() const listeners = new Set<(value: { binding: string; event: PaneEvent }) => void>() // What main rejects the next commands with, first in, first out. const rejections: string[] = [] - const server = { id: "browser-test", compatible: true, builtin: true, data: { on: () => () => undefined, session: { status: () => "idle" } } } + const [connected, setConnected] = createSignal(given.connected ?? true) + const [ipc, setIpc] = createSignal(given.ipc ?? "active") + const answered = Promise.withResolvers() + + if (!given.slow) answered.resolve() + + const server = { + id: "browser-test", + compatible: given.compatible ?? true, + get connected() { + return connected() + }, + local: given.local ?? true, + builtin: true, + data: { on: () => () => undefined, session: { status: () => "idle" } }, + } const refs = ["ses_alpha", "ses_beta"].map((id) => ({ key: `${server.id}\n${id}`, @@ -33,7 +52,7 @@ function fixture() { tab: id, server, pending: false, - location: { directory: "/repo" }, + location: given.located === false ? undefined : { directory: "/repo" }, })) const [current, setCurrent] = createSignal(refs[0]) @@ -41,6 +60,7 @@ function fixture() { const pane: PaneClient = { register: async (input) => { bindings.set(input.session, input.binding) + await answered.promise }, load: async () => undefined, command: async () => { @@ -66,7 +86,11 @@ function fixture() { }, } - const live = liveAccessor(() => ({ status: "active" as const, generation: 1, value: pane })) + const live = liveAccessor(() => { + const status = ipc() + + return status === "active" ? { status, generation: 1, value: pane } : { status } + }) const history = { value: { visits: [] }, set: () => undefined } const fake = { @@ -97,9 +121,133 @@ function fixture() { // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above const sessions = refs.map((ref) => ref as unknown as SessionRef) - return { ...owned, sessions, route: setCurrent, refs, emit, send, rejections } + return { ...owned, sessions, route: setCurrent, refs, emit, send, rejections, setConnected, setIpc, answer: answered.resolve, registered: () => Array.from(bindings.keys()) } } +// Runs the promise jobs queued so far, which the fake clock does not: more turns than a registration takes. +const turns = async () => { + for (const _ of Array.from({ length: 32 })) await Promise.resolve() +} + +// Whether the promise is still pending once every queued job ran. +const waits = async (promise: Promise) => { + const state = { done: false } + + void promise.then(() => (state.done = true)) + await turns() + + return !state.done +} + +afterEach(() => void jest.useRealTimers()) + +// What the system says of the network, which nothing but the navigator's own property can change. Returns the undo. +const network = (online: boolean) => { + const own = Object.getOwnPropertyDescriptor(navigator, "onLine") + + Object.defineProperty(navigator, "onLine", { configurable: true, get: () => online }) + + return () => (own ? Object.defineProperty(navigator, "onLine", own) : Reflect.deleteProperty(navigator, "onLine")) +} + +// A prompt waits for the desktop's attachment only while one is in flight on a server that can answer it. In every +// other state the gate resolves in the same tick: no timer runs, and nothing is asked of a server that cannot answer. +test.each([ + { state: "the server is not connected, or is reconnecting", given: { connected: false } }, + { state: "the server is one this app cannot talk to", given: { compatible: false } }, + { state: "the session has no location yet", given: { located: false } }, + { state: "the window is offline and the server is on another computer", given: { local: false }, offline: true }, + { state: "the pane's plugin is disabled or failed", given: { ipc: "inactive" as const } }, + { state: "another desktop owns the session", error: "browser.pane.replaced" }, + { state: "the server has no browser for the session", error: "browser.pane.unsupported" }, + { state: "the server does not have the session", error: "browser.pane.missing" }, + { state: "the desktop is attached already", attached: true }, + { state: "the plugin was disposed", disposed: true }, +])("a prompt does not wait when $state", async (row) => { + jest.useFakeTimers() + const restore = network(!row.offline) + const app = fixture(row.given) + const session = app.sessions[1] + const never = new AbortController().signal + + try { + // An earlier prompt met the state: what main answered it with is how the session stands now. + if (row.error || row.attached) { + const first = app.model.ready(session, never) + await turns() + app.send(session.id, row.error ? { type: "state", state: null, error: row.error } : { type: "state", state: { tabs: [tab("b")], focusedTabID: tab("b").id } }) + expect(await waits(first)).toBe(false) + } + + if (row.disposed) app.dispose() + const registered = app.registered().length + expect(await waits(app.model.ready(session, never))).toBe(false) + + // Nothing was started that could not answer. + if (!row.attached) expect(app.registered().length).toBe(registered) + } finally { + restore() + app.dispose() + } +}) + +test.each([ + { name: "the desktop has attached", end: "answer" }, + { name: "the server goes away", end: "disconnect" }, + { name: "the plugin is disposed", end: "dispose" }, + { name: "the host stops waiting", end: "abort" }, + { name: "the pane's plugin stops", end: "ipc" }, +] as const)("a prompt waits while the attachment is in flight, until $name", async (row) => { + jest.useFakeTimers() + const app = fixture({ slow: true }) + const session = app.sessions[1] + const host = new AbortController() + + try { + const waiting = app.model.ready(session, host.signal) + + expect(await waits(waiting)).toBe(true) + expect(app.registered()).toContain(session.id) + // No timer of the gate's own ends the wait: the host's does. + jest.advanceTimersByTime(900) + expect(await waits(waiting)).toBe(true) + + if (row.end === "answer") app.answer() + + if (row.end === "disconnect") app.setConnected(false) + + if (row.end === "dispose") app.dispose() + + if (row.end === "abort") host.abort() + + if (row.end === "ipc") app.setIpc("inactive") + expect(await waits(waiting)).toBe(false) + } finally { + app.dispose() + } +}) + +test("a prompt waits for a pane that is still starting, and for one whose server is on this computer while offline", async () => { + jest.useFakeTimers() + const restore = network(false) + const starting = fixture({ ipc: "pending" }) + const local = fixture({ local: true, slow: true }) + const never = new AbortController().signal + + try { + const first = starting.model.ready(starting.sessions[1], never) + expect(await waits(first)).toBe(true) + starting.setIpc("inactive") + expect(await waits(first)).toBe(false) + + expect(await waits(local.model.ready(local.sessions[1], never))).toBe(true) + } finally { + restore() + starting.dispose() + local.dispose() + } +}) + test("drops page details when a tab closes or its binding is suspended", () => { const app = fixture() diff --git a/packages/gui-plugins/src/browser/machine.test.ts b/packages/gui-plugins/src/browser/machine.test.ts index df590c428fb..edffe7c8a0d 100644 --- a/packages/gui-plugins/src/browser/machine.test.ts +++ b/packages/gui-plugins/src/browser/machine.test.ts @@ -156,6 +156,8 @@ describe("browser pane machine", () => { expect(sessionSettled(starting, key)).toBe(false) expect(sessionSettled(transition(starting, { type: "ipc.changed", ipc: active }).state, key)).toBe(false) expect(sessionSettled(replay(attach(), createInitialState({ status: "inactive" })).state, key)).toBe(true) + // One that was starting and then failed to start: the prompt that waited for it goes. + expect(sessionSettled(transition(starting, { type: "ipc.changed", ipc: { status: "inactive" } }).state, key)).toBe(true) // The server evicted the idle attachment: the prompt's wake registers it again, and the prompt waits for that. const evicted = transition(ready(), paneState(ready(), inventory(tab(tabA)), "browser.pane.suspended")).state diff --git a/packages/gui-plugins/src/browser/machine.ts b/packages/gui-plugins/src/browser/machine.ts index 298ff6d5056..ef924f824ef 100644 --- a/packages/gui-plugins/src/browser/machine.ts +++ b/packages/gui-plugins/src/browser/machine.ts @@ -438,6 +438,14 @@ export function sessionSettled(state: State, sessionKey: string) { return phase.reason === "unlisted" || (phase.reason === "ipc" && state.ipc.status !== "pending") } +/** + * Whether a prompt to the session waits for its attachment: only while one is in flight and can still succeed, on a + * session whose server could answer it (`reachable`, see `attachable`). In every other state the prompt goes at once. + */ +export function sessionAttaching(state: State, sessionKey: string, reachable: boolean) { + return reachable && !sessionSettled(state, sessionKey) +} + export function sessionSuspended(state: State, sessionKey: string) { return attachmentOf(state, sessionKey)?.phase.status === "suspended" } diff --git a/packages/gui-plugins/src/browser/model.ts b/packages/gui-plugins/src/browser/model.ts index 9fd1ea94623..06b9116e0cb 100644 --- a/packages/gui-plugins/src/browser/model.ts +++ b/packages/gui-plugins/src/browser/model.ts @@ -2,6 +2,7 @@ import { FileVerificationError } from "@opencode/util/file-verification" import { builtinContext } from "@opencode/plugin/gui/builtin" import { FileSource } from "../file/contract" import { ACTIVATION_DELAY_MS } from "./activation-delay" +import { attachable } from "./prompt-gate" import { batch, createRoot, createSignal, getOwner, onCleanup, untrack } from "solid-js" import { createStore, reconcile, unwrap } from "solid-js/store" import { makeEventListener } from "@solid-primitives/event-listener" @@ -43,7 +44,7 @@ import { sessionFailure, sessionPending, sessionRegistration, - sessionSettled, + sessionAttaching, sessionSuspended, sessionTab, sessionTabs, @@ -518,7 +519,15 @@ export function createModel(ctx: SetupContext) { dispatch({ type: "ipc.changed", ipc: untrack(ipc) }) wakeCurrent() }, - { otherwise: () => dispatch({ type: "ipc.changed", ipc: untrack(ipc) }) }, + { + // A pane that is starting and one that does not run are both no pane here, and they differ: a starting one + // attaches by itself, so a prompt waits for it, and one that failed to start never does. + otherwise: () => + createKeyed( + () => ipc().status, + () => dispatch({ type: "ipc.changed", ipc: untrack(ipc) }), + ), + }, ) const attach = (ref: SessionRef) => { @@ -690,22 +699,36 @@ export function createModel(ctx: SetupContext) { if (current) openURL(session, workspaceFileURL(current.root, path, session.server.builtin ? undefined : session.id)) } + // The window has a network connection, as far as the system knows. + const [online, setOnline] = createSignal(navigator.onLine) + makeEventListener(window, "online", () => setOnline(true)) + makeEventListener(window, "offline", () => setOnline(false)) + + // A prompt waits only while an attachment for its session is in flight on a server that can answer it. + const attaching = (session: SessionRef) => sessionAttaching(machine(), session.key, attachable(session, online())) + // A prompt is about to go to the session. Its first step lists the browser tools only if the server already holds - // this desktop's attachment, so the session attaches now, routed or not, and the send waits until the desktop took - // it or cannot. The host stops waiting through `signal`. + // this desktop's attachment, so the session attaches now, routed or not, and the send waits while that is in flight + // and can still succeed. In every other state it resolves at once: a server that is not connected or not compatible, + // a window that is offline, a session another desktop owns, one the server lacks or has no browser for, one with no + // location, a pane that does not run. The server going away, this plugin being disposed and the host's `signal` each + // end a wait at once. const ready = (session: SessionRef, signal: AbortSignal) => { - if (!session.server.compatible) return Promise.resolve() + if (!untrack(() => attachable(session, online()))) return Promise.resolve() attach(session) dispatch({ type: "session.wake", sessionKey: session.key }) - if (sessionSettled(untrack(machine), session.key) || signal.aborted) return Promise.resolve() + if (!untrack(() => attaching(session)) || signal.aborted) return Promise.resolve() const settled = Promise.withResolvers() const dispose = createRoot((dispose) => { createKeyed( - () => sessionSettled(machine(), session.key), + () => !attaching(session), () => settled.resolve(), ) + // The plugin's owner disposes this root before the machine hears of it, which would leave the wait to the host's + // timeout. + onCleanup(() => settled.resolve()) return dispose }, owner) diff --git a/packages/gui-plugins/src/browser/prompt-gate.test.ts b/packages/gui-plugins/src/browser/prompt-gate.test.ts new file mode 100644 index 00000000000..1818b279375 --- /dev/null +++ b/packages/gui-plugins/src/browser/prompt-gate.test.ts @@ -0,0 +1,21 @@ +import { expect, test } from "bun:test" +import type { SessionRef } from "@opencode/plugin/gui" +import { attachable } from "./prompt-gate" + +// SAFETY: `attachable` reads only these fields of a session and its server. +const session = (server: { connected?: boolean; compatible?: boolean; local?: boolean }, located = true) => + ({ + location: located ? { directory: "/repo" } : undefined, + server: { connected: true, compatible: true, local: false, ...server }, + }) as SessionRef + +test.each([ + ["a connected, compatible server and a located session", session({}), true, true], + ["a server that is not connected, or is reconnecting", session({ connected: false }), true, false], + ["a server this app cannot talk to", session({ compatible: false }), true, false], + ["a session with no location yet", session({}, false), true, false], + ["a window that is offline, with the server on another computer", session({}), false, false], + ["a window that is offline, with the server on this computer", session({ local: true }), false, true], +] as const)("a prompt can gain from waiting for the attachment only with %s", (_label, ref, online, expected) => { + expect(attachable(ref, online)).toBe(expected) +}) diff --git a/packages/gui-plugins/src/browser/prompt-gate.ts b/packages/gui-plugins/src/browser/prompt-gate.ts new file mode 100644 index 00000000000..ea2c31d9733 --- /dev/null +++ b/packages/gui-plugins/src/browser/prompt-gate.ts @@ -0,0 +1,11 @@ +import type { SessionRef } from "@opencode/plugin/gui" + +/** + * Whether a prompt to the session could gain anything by waiting for this desktop to attach to it. It could not when + * the session's server is not connected or is one this app cannot talk to, when the session has no location yet, or + * when the window is offline and the server is not on this computer: an attachment started then answers nothing in + * time, so the prompt goes at once. + */ +export function attachable(session: SessionRef, online: boolean) { + return session.server.connected && session.server.compatible && session.location !== undefined && (online || session.server.local) +} diff --git a/packages/gui-plugins/src/browser/renderer.tsx b/packages/gui-plugins/src/browser/renderer.tsx index e96b8f819dc..3267b7a3f22 100644 --- a/packages/gui-plugins/src/browser/renderer.tsx +++ b/packages/gui-plugins/src/browser/renderer.tsx @@ -30,6 +30,7 @@ import { } from "./model-machine" import { PageIcon } from "./page-icon" import { artifactLink, artifactWebURL } from "./artifact-link" +import { attachable } from "./prompt-gate" import { remotePath, workspacePrefix } from "./remote-address" import { viewportToolbarAvailable } from "./viewport-toolbar-machine" import barStyles from "./bar.css?inline" @@ -162,14 +163,18 @@ const setup: Plugin.Setup = (ctx) => { // The agent's first step lists the browser tools only when this desktop attached to the session before the prompt // reached the server. A draft's session is created by the send itself, so the send waits here for the attachment. ctx.add(BuiltinPromptGate, { - async ready(input) { + ready(input) { + // A prompt that cannot gain from an attachment waits for nothing, not even for the model's chunk. + if (!attachable(input.session, navigator.onLine)) return dispatchModel({ type: "load.requested" }) const loading = untrack(modelState) + const loaded = loading.status === "loading" ? loads.get(loading.attempt) : undefined - if (loading.status === "loading") await loads.get(loading.attempt) + if (!loaded) return untrack(model)?.ready(input.session, input.signal) - if (input.signal.aborted || ctx.signal.aborted) return - await untrack(model)?.ready(input.session, input.signal) + return loaded.then(() => { + if (!input.signal.aborted && !ctx.signal.aborted) return untrack(model)?.ready(input.session, input.signal) + }) }, })