fix(client): evict missing sessions on 404 instead of retrying or toasting (#60459)

This commit is contained in:
Luke Parker
2026-10-30 14:35:52 +10:00
committed by GitHub
Unverified
parent f807ffeccb
commit 2e64b9fc3b
10 changed files with 329 additions and 29 deletions
+17 -1
View File
@@ -2,7 +2,14 @@ import { expect, test } from "bun:test"
import type { SessionInfo } from "@opencode/client/promise"
import { createSessionMutations } from "./data"
const session = { id: "ses_test" } as SessionInfo
const session: SessionInfo = {
id: "ses_test",
projectID: "project",
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
time: { created: 0, updated: 0 },
location: { directory: "/project" },
}
test("keeps a removed session hidden after its deletion event, for lists cached before it", async () => {
const release = Promise.withResolvers<void>()
@@ -38,3 +45,12 @@ test("rolls back a failed removal", async () => {
await expect(request).rejects.toThrow("offline")
expect(mutation.apply([session])).toEqual([session])
})
test("treats SessionNotFoundError on removal as already deleted", async () => {
const mutation = createSessionMutations(async () => {
throw JSON.parse('{"_tag":"SessionNotFoundError","sessionID":"ses_test","message":"Session not found: ses_test"}')
})
await expect(mutation.remove(session.id)).resolves.toBeUndefined()
expect(mutation.apply([session])).toEqual([])
})
+22 -9
View File
@@ -1,11 +1,13 @@
import type { Data } from "@opencode/client/solid"
import type { OpenCodeEvent, SessionInfo } from "@opencode/client/promise"
import { isSessionNotFoundError, type OpenCodeEvent, type SessionInfo } from "@opencode/client/promise"
import { onCleanup } from "solid-js"
import { createStore } from "solid-js/store"
import { uuid } from "@/runtime/persistence/uuid"
type SessionMutation = { readonly id: string; readonly type: "remove"; readonly sessionID: string }
const REMOVED_SESSION_LIMIT = 512
// The events on which the server advances a session's `time.updated` to the event's time.
const SESSION_ACTIVITY = [
"session.inbox.enqueued",
@@ -27,8 +29,13 @@ const SESSION_ACTIVITY = [
export function createDesktopData(input: { data: Data; remove: (sessionID: string) => Promise<void> }) {
const mutation = createSessionMutations(input.remove)
const [activity, setActivity] = createStore<Record<string, number>>({})
onCleanup(input.data.on("session.deleted", (event) => mutation.deleted(event.data.sessionID)))
const [activity, setActivity] = createStore<Record<string, number | undefined>>({})
onCleanup(
input.data.on("session.deleted", (event) => {
setActivity(event.data.sessionID, undefined)
mutation.deleted(event.data.sessionID)
}),
)
// Lists loaded earlier (the Home index, the live store, search results) learn each session's newer
// `time.updated` from its events, so they rank sessions in the server's order without reloading.
@@ -53,7 +60,11 @@ export function createDesktopData(input: { data: Data; remove: (sessionID: strin
...input.data.session,
list: () => apply(input.data.session.list()),
apply,
remove: mutation.remove,
remove: (sessionID: string) =>
mutation.remove(sessionID).then(() => {
setActivity(sessionID, undefined)
input.data.session.forget(sessionID)
}),
},
}
}
@@ -65,6 +76,9 @@ export function createSessionMutations(remove: (sessionID: string) => Promise<vo
setStore("session", (current) => current.filter((mutation) => mutation.id !== id))
}
const append = (current: readonly SessionMutation[], next: SessionMutation) =>
[...current.filter((mutation) => mutation.sessionID !== next.sessionID), next].slice(-REMOVED_SESSION_LIMIT)
return {
apply(sessions: readonly SessionInfo[]) {
const removed = new Set(
@@ -75,21 +89,20 @@ export function createSessionMutations(remove: (sessionID: string) => Promise<vo
},
remove(sessionID: string) {
const mutation = { id: uuid(), type: "remove" as const, sessionID }
setStore("session", (current) => [...current, mutation])
setStore("session", (current) => append(current, mutation))
return Promise.resolve()
.then(() => remove(sessionID))
.catch((error) => {
if (isSessionNotFoundError(error)) return
clear(mutation.id)
throw error
})
},
// Keep the deleted session hidden: cached lists such as the Home index still hold it until they refetch.
deleted(sessionID: string) {
setStore("session", (current) => [
...current.filter((mutation) => mutation.sessionID !== sessionID),
{ id: uuid(), type: "remove", sessionID },
])
setStore("session", (current) => append(current, { id: uuid(), type: "remove", sessionID }))
},
}
}
@@ -1,7 +1,7 @@
import { createEffect, createMemo, onCleanup, untrack } from "solid-js"
import { createStore } from "solid-js/store"
import { Schema } from "effect"
import type { SessionInfo } from "@opencode/client/promise"
import { isSessionNotFoundError, type SessionInfo } from "@opencode/client/promise"
import type { ServerSDK } from "@/runtime/server/client"
import type { Data } from "@opencode/client/solid"
import { usePlatform } from "@/runtime/platform/platform"
@@ -208,7 +208,14 @@ export function createServerNotificationState(input: {
viewRetryTimer = undefined
viewRetryAttempt = 0
},
() => {
(error) => {
if (isSessionNotFoundError(error)) {
acknowledged.delete(root)
input.data.session.forget(root)
return
}
if (acknowledged.get(root) !== idle) return
acknowledged.delete(root)
@@ -229,6 +229,7 @@ function SessionTabEntry(props: {
pending() ||
!ctx ||
props.active ||
ctx.data.session.missing(id) ||
(!session() && !persisted()?.title) ||
ctx.sdk.connection.status() !== "connected"
)
+74 -11
View File
@@ -47,7 +47,9 @@ import { SessionMessage } from "@opencode/schema/session-message"
import {
isFormAlreadySettledError,
isFormNotFoundError,
isMessageNotFoundError,
isPermissionNotFoundError,
isSessionNotFoundError,
type SessionPromptInput,
} from "../promise"
import { createStore, produce, reconcile } from "solid-js/store"
@@ -122,6 +124,7 @@ type LocationData = {
type Store = {
session: {
info: Record<string, SessionInfo>
missing: Record<string, true | undefined>
// Family index keyed by a family's root (or furthest-known-ancestor when the
// true root is not yet loaded). The value is a flat deduplicated list of every
// session ID in that family, including the key itself once its info arrives.
@@ -256,6 +259,7 @@ function createSync() {
}
const CHILD_PAGE = 200
const DELETED_SESSION_LIMIT = 512
export function createData(config: CreateDataInput) {
const api = config.api
@@ -266,6 +270,11 @@ export function createData(config: CreateDataInput) {
if (disposed || (config.connection && config.connection.status() !== "connected")) return
void load().catch((error) => {
if (disposed || (config.connection && config.connection.status() !== "connected")) return
if (isSessionNotFoundError(error)) {
markDeleted(error.sessionID)
return
}
if (isMessageNotFoundError(error)) return
if (config.onError) return config.onError(error)
console.error("Failed to refresh client data", error)
})
@@ -288,6 +297,7 @@ export function createData(config: CreateDataInput) {
const [store, setStore] = createStore<Store>({
session: {
info: {},
missing: {},
family: {},
active: {},
message: {},
@@ -631,6 +641,36 @@ export function createData(config: CreateDataInput) {
)
}
let deletionEpoch = 0
const deletedAt = new Map<string, number>()
function clearDeleted(sessionID: string) {
deletedAt.delete(sessionID)
if (store.session.missing[sessionID]) setStore("session", "missing", sessionID, undefined)
}
function markDeleted(sessionID: string) {
if (sessionOutbox.has(sessionID)) return
batch(() => {
deletedAt.delete(sessionID)
deletedAt.set(sessionID, ++deletionEpoch)
if (deletedAt.size > DELETED_SESSION_LIMIT) {
const oldest = deletedAt.keys().next().value
if (oldest !== undefined) {
deletedAt.delete(oldest)
setStore("session", "missing", oldest, undefined)
}
}
setStore("session", "missing", sessionID, true)
removeSession(sessionID)
})
}
function evictMissing(error: unknown): never {
if (isSessionNotFoundError(error)) markDeleted(error.sessionID)
throw error
}
function removeSession(sessionID: string) {
activeUpdates?.set(sessionID, undefined)
store.session.pending[sessionID]?.forEach((item) => outbox.delete(item.id))
@@ -705,6 +745,7 @@ export function createData(config: CreateDataInput) {
setStore("project", "info", event.data.id, reconcile(event.data))
return
case "session.created":
clearDeleted(event.data.sessionID)
sessionOutbox.delete(event.data.sessionID)
result.session.invalidate(event.data.sessionID)
refresh(() => result.session.sync(event.data.sessionID))
@@ -716,7 +757,7 @@ export function createData(config: CreateDataInput) {
sync.complete(`session.message:${event.data.sessionID}`)
return
case "session.deleted":
removeSession(event.data.sessionID)
markDeleted(event.data.sessionID)
return
case "session.usage.updated":
if (store.session.info[event.data.sessionID])
@@ -1462,11 +1503,18 @@ export function createData(config: CreateDataInput) {
get(sessionID: string) {
return store.session.info[sessionID]
},
missing(sessionID: string) {
return Boolean(store.session.missing[sessionID])
},
forget(sessionID: string) {
markDeleted(sessionID)
},
creating(sessionID: string) {
return creating.has(sessionID)
},
remember(info: SessionInfo) {
batch(() => {
clearDeleted(info.id)
setStore("session", "info", info.id, reconcile(info))
sync.complete(`session:${info.id}`)
registerSession(info.id)
@@ -1541,10 +1589,12 @@ export function createData(config: CreateDataInput) {
},
sync(sessionID: string) {
return sync.run(`session.pending:${sessionID}`, async () => {
const started = deletionEpoch
const updates = new Map<string, SessionInboxInfo | SessionInbox.Delivery | undefined>()
pendingUpdates.set(sessionID, updates)
try {
const snapshot = await api().session.inbox.list({ sessionID })
const snapshot = await api().session.inbox.list({ sessionID }).catch(evictMissing)
if ((deletedAt.get(sessionID) ?? 0) > started) return
// Events can overtake this HTTP response on a remote connection.
// Reconcile them before an older snapshot can resurrect delivered input.
const current = new Map(snapshot.map((item) => [item.id, item]))
@@ -1600,6 +1650,7 @@ export function createData(config: CreateDataInput) {
const id = payload.id ?? SessionID.create()
const location = payload.location ?? defaultLocation()
const fresh = !store.session.info[id]
clearDeleted(id)
if (fresh) {
const now = Date.now()
sessionOutbox.add(id)
@@ -1732,11 +1783,12 @@ export function createData(config: CreateDataInput) {
},
sync(sessionID: string, options?: { children?: boolean }) {
return sync.run(options?.children ? `session.family:${sessionID}` : `session:${sessionID}`, async () => {
const started = deletionEpoch
const [info, children] = await Promise.all([
api().session.get({ sessionID }),
api().session.get({ sessionID }).catch(evictMissing),
options?.children ? listChildren({ parentID: sessionID, order: "desc", limit: CHILD_PAGE }) : [],
])
const sessions = [info, ...children]
const sessions = [info, ...children].filter((session) => (deletedAt.get(session.id) ?? 0) <= started)
batch(() => {
setStore(
"session",
@@ -1746,6 +1798,7 @@ export function createData(config: CreateDataInput) {
}),
)
for (const session of sessions) {
clearDeleted(session.id)
sync.complete(`session:${session.id}`)
registerSession(session.id)
}
@@ -1766,11 +1819,15 @@ export function createData(config: CreateDataInput) {
},
sync(sessionID: string) {
return sync.run(`session.message:${sessionID}`, async () => {
const response = await api().message.list({
sessionID,
limit: config.initialMessageLimit?.() ?? messagePageLimit,
order: "desc",
})
const started = deletionEpoch
const response = await api()
.message.list({
sessionID,
limit: config.initialMessageLimit?.() ?? messagePageLimit,
order: "desc",
})
.catch(evictMissing)
if ((deletedAt.get(sessionID) ?? 0) > started) return
const fetched = response.data.toReversed().map(stored)
// Same protection as the pending sync: a re-fetch racing an
// admission must not wipe its local transcript row.
@@ -1877,7 +1934,10 @@ export function createData(config: CreateDataInput) {
},
sync(sessionID: string) {
return sync.run(`session.permission:${sessionID}`, async () => {
setStore("session", "permission", sessionID, await api().permission.list({ sessionID }))
const started = deletionEpoch
const list = await api().permission.list({ sessionID }).catch(evictMissing)
if ((deletedAt.get(sessionID) ?? 0) > started) return
setStore("session", "permission", sessionID, list)
})
},
invalidate(sessionID: string) {
@@ -1924,7 +1984,10 @@ export function createData(config: CreateDataInput) {
])
return
}
setStore("session", "form", sessionID, await api().session.form.list({ sessionID }))
const started = deletionEpoch
const list = await api().session.form.list({ sessionID }).catch(evictMissing)
if ((deletedAt.get(sessionID) ?? 0) > started) return
setStore("session", "form", sessionID, list)
})
},
invalidate(sessionID: string, ref?: LocationRef) {
+162
View File
@@ -249,4 +249,166 @@ test("invalidations that land before a queued reload starts are absorbed by it",
} finally {
setup.dispose()
}
})
test("event-driven session reads evict missing sessions without reporting an error, while explicit reads still reject", async () => {
const listeners = new Set<Parameters<CreateDataInput["event"]["listen"]>[0]>()
const errors: unknown[] = []
const session: SessionInfo = {
id: "ses_ephemeral",
projectID: "project",
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
time: { created: 0, updated: 0, idle: 1 },
location: { directory: "/project" },
}
const api = OpenCode.make({
baseUrl: "http://opencode.local",
fetch: async () =>
Response.json(
{ _tag: "SessionNotFoundError", sessionID: session.id, message: `Session not found: ${session.id}` },
{ status: 404 },
),
})
const setup = createRoot((dispose) => ({
data: createData({
api: () => api,
directory: "/project",
event: {
on: () => () => {},
listen(handler) {
listeners.add(handler)
return () => listeners.delete(handler)
},
},
onError: (error) => errors.push(error),
}),
dispose,
}))
const viewed: OpenCodeEvent = {
id: "evt_ephemeral_viewed",
created: 2,
type: "session.viewed",
durable: { aggregateID: session.id, seq: 1, version: 1 },
data: { sessionID: session.id, idle: 2 },
}
try {
setup.data.session.remember(session)
expect(setup.data.session.get(session.id)).toBeDefined()
listeners.forEach((listener) => listener({ name: viewed.type, details: viewed }))
const deadline = Date.now() + 2_000
while (!setup.data.session.missing(session.id)) {
if (Date.now() > deadline) throw new Error("Timed out waiting for missing-session eviction")
await Bun.sleep(5)
}
expect(errors).toEqual([])
expect(setup.data.session.get(session.id)).toBeUndefined()
expect(setup.data.session.missing(session.id)).toBe(true)
await expect(setup.data.session.sync(session.id)).rejects.toMatchObject({
_tag: "SessionNotFoundError",
sessionID: session.id,
})
expect(errors).toEqual([])
} finally {
setup.dispose()
}
})
test("delayed metadata and family reads do not resurrect sessions deleted while in flight", async () => {
const listeners = new Set<Parameters<CreateDataInput["event"]["listen"]>[0]>()
const makeSession = (id: string, parentID?: string): SessionInfo => ({
id,
projectID: "project",
...(parentID ? { parentID } : {}),
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
time: { created: 0, updated: 0 },
location: { directory: "/project" },
})
const root = makeSession("ses_root")
const child = makeSession("ses_child", root.id)
const ownStarted = Promise.withResolvers<void>()
const ownRelease = Promise.withResolvers<void>()
const familyStarted = Promise.withResolvers<void>()
const familyRelease = Promise.withResolvers<void>()
const requests: string[] = []
const api = OpenCode.make({
baseUrl: "http://opencode.local",
fetch: async (input, init) => {
const url = new URL((input instanceof Request ? input : new Request(input, init)).url)
requests.push(`${url.pathname}${url.search}`)
if (url.pathname === `/api/session/${root.id}`) return Response.json({ data: root })
if (url.pathname === "/api/session" && url.searchParams.get("parentID") === root.id) {
familyStarted.resolve()
await familyRelease.promise
return Response.json({ data: [child], cursor: {} })
}
if (url.pathname === `/api/session/${child.id}` && requests.filter((item) => item === `/api/session/${child.id}`).length === 1) {
ownStarted.resolve()
await ownRelease.promise
return Response.json({ data: child })
}
return Response.json(
{ _tag: "SessionNotFoundError", sessionID: child.id, message: `Session not found: ${child.id}` },
{ status: 404 },
)
},
})
const setup = createRoot((dispose) => ({
data: createData({
api: () => api,
directory: "/project",
event: {
on: () => () => {},
listen(handler) {
listeners.add(handler)
return () => listeners.delete(handler)
},
},
}),
dispose,
}))
const emitDeleted = (sessionID: string, seq: number) => {
const event: OpenCodeEvent = {
id: `evt_del_${seq}`,
created: seq,
type: "session.deleted",
durable: { aggregateID: sessionID, seq, version: 1 },
data: { sessionID },
}
listeners.forEach((listener) => listener({ name: event.type, details: event }))
}
try {
// Own metadata read started before deletion must not republish.
setup.data.session.remember(child)
setup.data.session.invalidate(child.id)
const ownSync = setup.data.session.sync(child.id)
await ownStarted.promise
emitDeleted(child.id, 1)
expect(setup.data.session.get(child.id)).toBeUndefined()
ownRelease.resolve()
await ownSync
expect(setup.data.session.get(child.id)).toBeUndefined()
// Parent family read started before child deletion must not republish or mark child synced.
setup.data.session.remember(root)
setup.data.session.remember(child)
const familySync = setup.data.session.sync(root.id, { children: true })
await familyStarted.promise
emitDeleted(child.id, 2)
expect(setup.data.session.get(child.id)).toBeUndefined()
familyRelease.resolve()
await familySync
expect(setup.data.session.get(child.id)).toBeUndefined()
expect(setup.data.session.family(root.id)).toEqual([root.id])
await expect(setup.data.session.sync(child.id)).rejects.toMatchObject({
_tag: "SessionNotFoundError",
sessionID: child.id,
})
} finally {
ownRelease.resolve()
familyRelease.resolve()
setup.dispose()
}
})
@@ -350,3 +350,21 @@ test.each([
app.connection.dispose()
}
})
test("browser.pane.missing stops retry backoff without surfacing an error and wakes only when created", () => {
jest.useFakeTimers()
const app = fixture()
try {
app.emit(0, { type: "state", state: null, error: "browser.pane.missing" })
jest.advanceTimersByTime(60_000)
app.connection.wake()
expect(app.calls).toHaveLength(1)
expect(app.states.at(-1)?.error).toBeUndefined()
app.connection.wake(true)
expect(app.calls).toHaveLength(2)
} finally {
app.connection.dispose()
}
})
@@ -192,14 +192,18 @@ export function createConnection(input: {
return publish()
}
if (event.error === "browser.pane.unsupported" || event.error === "browser.pane.replaced") {
if (
event.error === "browser.pane.unsupported" ||
event.error === "browser.pane.replaced" ||
event.error === "browser.pane.missing"
) {
blocked = true
registration.close()
state.registration = undefined
state.ready = false
state.embeds = {}
state.browser = null
state.error = event.error
state.error = event.error === "browser.pane.missing" ? undefined : event.error
publish()
return
@@ -246,7 +250,9 @@ export function createConnection(input: {
}
return {
wake() {
wake(unblock = false) {
if (unblock) blocked = false
// Passive focus, pointer, and key edges wake an idle-evicted pane without bypassing transport backoff.
if (retry === undefined) register()
},
+1 -1
View File
@@ -278,7 +278,7 @@ export function createModel(ctx: SetupContext<typeof definition>) {
(data) => {
onCleanup(
data.on("session.created", (event) => {
if (event.data.sessionID === ref.id) entry.connection.wake()
if (event.data.sessionID === ref.id) entry.connection.wake(true)
}),
)
onCleanup(
+16 -2
View File
@@ -3,7 +3,7 @@ import { Browser } from "@opencode/plugin-browser/rpc"
import { OpenCode } from "@opencode/client/effect"
import { SessionID } from "@opencode/schema/session-id"
import electron, { type BrowserWindow } from "electron"
import { Deferred, Effect, ManagedRuntime, Queue, Schedule, Schema, Stream } from "effect"
import { Deferred, Effect, ManagedRuntime, Predicate, Queue, Schedule, Schema, Stream } from "effect"
import { HttpClient, HttpClientRequest } from "effect/http"
import type { BuiltinMainStorage } from "@opencode/plugin/gui/builtin"
import type { Embeds, Persisted, ServerEndpoints, Windows } from "@opencode/plugin/gui/main"
@@ -118,8 +118,15 @@ export function createBrowserPane(input: {
.webRequest.onBeforeRequest({ urls: ["file://*/*"] }, (details, callback) =>
callback({ cancel: !fileURLWithin(details.url, entry.fileRoots) }),
)
// "unsupported" means the server has no browser plugin; the renderer stops retrying.
let reason: "browser.pane.unsupported" | "browser.pane.replaced" | "browser.pane.suspended" | undefined
let reason:
| "browser.pane.unsupported"
| "browser.pane.replaced"
| "browser.pane.suspended"
| "browser.pane.missing"
| undefined
let attached = false
const stop = () => close(entry, reason)
@@ -293,6 +300,13 @@ export function createBrowserPane(input: {
Effect.scoped,
Effect.tapError((error) =>
Effect.sync(() => {
if (Predicate.isTagged(error, "SessionNotFoundError")) {
reason = "browser.pane.missing"
restore.remove(entry.storageKey)
return
}
const type = error instanceof Object && "type" in error ? error.type : undefined
if (type === "rpc.unavailable" && attached) {