mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 11:42:17 +00:00
fix(browser): a prompt waits for the attachment only while one is in flight and can succeed
The gate woke the attachment whatever the server's state, so with the server restarting or the window offline a registration that could not answer held every prompt for the host's whole timeout, and a plugin disposed mid-wait left the wait to that timeout too. It now resolves in the same tick unless the server is connected and compatible, the session has a location, the window is online or the server local, and a registration is in flight. The server going away, the plugin being disposed and the pane's plugin failing to start each end a wait at once. The machine never heard of a pane that went from starting to not running, so a prompt kept waiting for it.
This commit is contained in:
parent
43a5b7f629
commit
466af8091b
7 changed files with 235 additions and 17 deletions
|
|
@ -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<string, string>()
|
||||
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<void>()
|
||||
|
||||
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<void>) => {
|
||||
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()
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<typeof definition>) {
|
|||
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<typeof definition>) {
|
|||
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<void>()
|
||||
|
||||
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)
|
||||
|
|
|
|||
21
packages/gui-plugins/src/browser/prompt-gate.test.ts
Normal file
21
packages/gui-plugins/src/browser/prompt-gate.test.ts
Normal file
|
|
@ -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)
|
||||
})
|
||||
11
packages/gui-plugins/src/browser/prompt-gate.ts
Normal file
11
packages/gui-plugins/src/browser/prompt-gate.ts
Normal file
|
|
@ -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)
|
||||
}
|
||||
|
|
@ -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<typeof definition> = (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)
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue