diff --git a/packages/app/src/runtime/plugin/session-store-machine.test.ts b/packages/app/src/runtime/plugin/session-store-machine.test.ts new file mode 100644 index 00000000000..bc942106ae3 --- /dev/null +++ b/packages/app/src/runtime/plugin/session-store-machine.test.ts @@ -0,0 +1,82 @@ +import { expect, test } from "bun:test" +import { + createSessionStoreState, + selectSessionStoreEntry, + SESSION_STORE_MAX_UNLISTED, + transitionSessionStore, + type SessionStoreEvent, + type SessionStoreState, +} from "./session-store-machine" + +/** Folds events from an empty table, collecting the stores each one closed. */ +function replay(events: readonly SessionStoreEvent[], state = createSessionStoreState()) { + return events.reduce<{ state: SessionStoreState; closed: string[] }>( + (current, event) => { + const next = transitionSessionStore(current.state, event) + + return { state: next.state, closed: [...current.closed, ...next.effects.map((effect) => effect.value)] } + }, + { state, closed: [] }, + ) +} + +const opened = (key: string, input: { listed?: boolean; routed?: string } = {}): SessionStoreEvent => ({ + type: "opened", + key, + value: key, + listed: input.listed ?? false, + routed: input.routed, +}) + +const sync = (listed: readonly string[], routed?: string): SessionStoreEvent => ({ + type: "sync", + listed: new Set(listed), + routed, +}) + +const open = (state: SessionStoreState) => (state.status === "active" ? Object.keys(state.entries).sort() : []) + +// Before, a store no tab ever listed stayed open until the plugin went away. +test("stores no tab lists close oldest first past the cap, except the routed session's", () => { + const keys = Array.from({ length: SESSION_STORE_MAX_UNLISTED + 3 }, (_, index) => `s${index}`) + const run = replay(keys.map((key) => opened(key, { routed: "s0" }))) + + expect({ closed: run.closed, routed: open(run.state).includes("s0") }).toEqual({ closed: ["s1", "s2"], routed: true }) + + // Once the route leaves it, the routed store counts against the cap too. + expect(replay([sync([])], run.state).closed).toEqual(["s0"]) +}) + +test("an unlisted store survives until a tab lists it, then closes with that tab once the route leaves it", () => { + const steps = [ + { event: opened("a", { routed: "a" }), open: ["a"] }, + { event: sync([], "a"), open: ["a"] }, + { event: sync(["a"], "a"), open: ["a"] }, + { event: sync([], "a"), open: ["a"] }, + { event: sync([], undefined), open: [] }, + ] + + const states = steps.map((_, index) => replay(steps.slice(0, index + 1).map((item) => item.event)).state) + + expect(states.map(open)).toEqual(steps.map((item) => item.open)) +}) + +test("a store opened for a listed session closes with its tab", () => { + expect(replay([opened("a", { listed: true }), sync(["b"])]).closed).toEqual(["a"]) +}) + +test("a sync that changes nothing keeps the same state", () => { + const run = replay([opened("a"), opened("b", { listed: true })]) + + expect(transitionSessionStore(run.state, sync(["b"])).state).toBe(run.state) +}) + +test("disposal closes every store once and closes a store opened afterwards at once", () => { + const run = replay([opened("a"), opened("b", { listed: true }), { type: "disposed" }, opened("c"), sync([])]) + + expect({ closed: run.closed, status: run.state.status, read: selectSessionStoreEntry(run.state, "a") }).toEqual({ + closed: ["a", "b", "c"], + status: "disposed", + read: undefined, + }) +}) diff --git a/packages/app/src/runtime/plugin/session-store-machine.ts b/packages/app/src/runtime/plugin/session-store-machine.ts new file mode 100644 index 00000000000..87d0aee7cd6 --- /dev/null +++ b/packages/app/src/runtime/plugin/session-store-machine.ts @@ -0,0 +1,140 @@ +/** Stores of sessions no tab has listed beyond this close, oldest first, so preloads without a tab stay bounded. */ +export const SESSION_STORE_MAX_UNLISTED = 16 + +export type SessionStoreEntry = { + /** + * `unlisted` until a tab lists the session: a deep link or a new session routes and preloads before the titlebar + * adds its tab. Only a `listed` store closes with its tab. + */ + readonly retention: "unlisted" | "listed" + /** When the store opened, which picks the oldest unlisted store to close. */ + readonly order: number + readonly value: E +} + +/** The open stores of one declared session store, by session key. */ +export type SessionStoreState = + | { + readonly status: "active" + readonly issued: number + readonly entries: Readonly>> + } + | { readonly status: "disposed" } + +export type SessionStoreEvent = + /** A store opened for a session that had none; `listed`: a tab lists the session already. */ + | { + readonly type: "opened" + readonly key: string + readonly value: E + readonly listed: boolean + readonly routed: string | undefined + } + /** The sessions open tabs list, and the routed one. */ + | { readonly type: "sync"; readonly listed: ReadonlySet; readonly routed: string | undefined } + | { readonly type: "disposed" } + +export type SessionStoreEffect = { readonly type: "dispose"; readonly value: E } + +export type SessionStoreTransition = { + readonly state: SessionStoreState + readonly effects: readonly SessionStoreEffect[] +} + +export function createSessionStoreState(): SessionStoreState { + return { status: "active", issued: 0, entries: {} } +} + +export function transitionSessionStore( + state: SessionStoreState, + event: SessionStoreEvent, +): SessionStoreTransition { + if (state.status === "disposed") { + if (event.type === "opened") return step(state, [dispose(event.value)]) + + return step(state) + } + + if (event.type === "disposed") + return step( + { status: "disposed" }, + Object.values(state.entries).map((entry) => dispose(entry.value)), + ) + + if (event.type === "opened") { + if (state.entries[event.key]) return step(state, [dispose(event.value)]) + + const issued = state.issued + 1 + + const entry: SessionStoreEntry = { + retention: event.listed ? "listed" : "unlisted", + order: issued, + value: event.value, + } + + return bounded({ status: "active", issued, entries: { ...state.entries, [event.key]: entry } }, event.routed, []) + } + + const listed = event.listed + const all = Object.entries(state.entries) + // A listed store closes once its tab has: the routed session keeps its store until the route leaves it. + const closed = all.filter(([key, entry]) => entry.retention === "listed" && !listed.has(key) && key !== event.routed) + const changed = closed.length > 0 || all.some(([key, entry]) => entry.retention === "unlisted" && listed.has(key)) + + if (!changed) return bounded(state, event.routed, []) + + const entries = Object.fromEntries( + all.flatMap(([key, entry]) => { + if (closed.some((item) => item[0] === key)) return [] + + return [[key, listed.has(key) ? { ...entry, retention: "listed" as const } : entry] as const] + }), + ) + + return bounded( + { ...state, entries }, + event.routed, + closed.map(([, entry]) => dispose(entry.value)), + ) +} + +/** The value of a session's open store. */ +export function selectSessionStoreEntry(state: SessionStoreState, key: string) { + return state.status === "active" ? state.entries[key]?.value : undefined +} + +/** Closes the oldest unlisted stores past the cap; the routed session keeps its store. */ +function bounded( + state: Extract, { status: "active" }>, + routed: string | undefined, + effects: readonly SessionStoreEffect[], +): SessionStoreTransition { + const unlisted = Object.entries(state.entries) + .filter(([key, entry]) => entry.retention === "unlisted" && key !== routed) + .sort((a, b) => a[1].order - b[1].order) + + const evicted = unlisted.slice(0, Math.max(0, unlisted.length - SESSION_STORE_MAX_UNLISTED)) + + if (evicted.length === 0) return step(state, effects) + + return step( + { + ...state, + entries: Object.fromEntries( + Object.entries(state.entries).filter(([key]) => !evicted.some((item) => item[0] === key)), + ), + }, + [...effects, ...evicted.map(([, entry]) => dispose(entry.value))], + ) +} + +function dispose(value: E): SessionStoreEffect { + return { type: "dispose", value } +} + +function step( + state: SessionStoreState, + effects: readonly SessionStoreEffect[] = [], +): SessionStoreTransition { + return { state, effects } +} diff --git a/packages/app/src/runtime/plugin/stores.ts b/packages/app/src/runtime/plugin/stores.ts index 71375129a10..437a048fc36 100644 --- a/packages/app/src/runtime/plugin/stores.ts +++ b/packages/app/src/runtime/plugin/stores.ts @@ -17,6 +17,12 @@ import type { Mutable, Persisted, SessionRef } from "@opencode/plugin/gui" import type { BuiltinStoreFrom } from "@opencode/plugin/gui/builtin" import { Persist, type persisted } from "@/runtime/persistence/storage" import type { SessionStateKey } from "@/runtime/server/scope" +import { + createSessionStoreState, + selectSessionStoreEntry, + transitionSessionStore, + type SessionStoreEvent, +} from "./session-store-machine" import { createDeferredStoreState, createStoreLoadState, @@ -248,7 +254,8 @@ export function locatedHandle(session: SessionRef, open: () => Persisted) /** * A declared session store: one handle per session, opened through `locatedHandle`. Call it under an owner: an effect - * drops the store of a session whose tab closed. + * drops the store of a session whose tab closed, and the oldest stores past `SESSION_STORE_MAX_UNLISTED` that no tab + * lists. */ export function createSessionStore(input: { readonly open: (session: SessionRef) => Persisted @@ -260,26 +267,25 @@ export function createSessionStore(input: { */ readonly sessions: { list(): readonly SessionRef[]; current(): SessionRef | undefined } }) { - const entries = new Map; readonly dispose: () => void }>() - // Keys a tab has listed while their store was open; only these can close. - const listed = new Set() + type Opened = { readonly handle: Persisted; readonly dispose: () => void } + + // A plain variable: readers hold the handles, and nothing renders the table itself. + const machine = { state: createSessionStoreState() } + + const dispatch = (event: SessionStoreEvent) => { + const next = transitionSessionStore(machine.state, event) + + machine.state = next.state + next.effects.forEach((effect) => effect.value.dispose()) + } // Drops the stores of sessions whose tabs closed. The routed session keeps its store, and so does one no tab has - // listed yet: a deep link or a new session routes and preloads before the titlebar adds its tab. + // listed yet, up to a bound: a deep link or a new session routes and preloads before the titlebar adds its tab. createRenderEffect(() => { - const keys = new Set(input.sessions.list().map((session) => session.key)) + const listed = new Set(input.sessions.list().map((session) => session.key)) const routed = input.sessions.current()?.key - untrack(() => - entries.forEach((entry, key) => { - if (keys.has(key)) return void listed.add(key) - - if (key === routed || !listed.has(key)) return - entry.dispose() - entries.delete(key) - listed.delete(key) - }), - ) + untrack(() => dispatch({ type: "sync", listed, routed })) }) const create = (session: SessionRef) => { @@ -307,22 +313,27 @@ export function createSessionStore(input: { } return { - get(session: SessionRef) { - const existing = entries.get(session.key) + get(session: SessionRef): Persisted { + const existing = selectSessionStoreEntry(machine.state, session.key) if (existing) return existing.handle - const created = create(session) - entries.set(session.key, created) - // Listed already, it closes with its tab. - if (untrack(input.sessions.list).some((item) => item.key === session.key)) listed.add(session.key) + // A plugin's code that runs on after it went away reads nothing and writes nowhere. + if (machine.state.status === "disposed") + return { value: undefined, ready: () => false, update: () => undefined, set: () => undefined } + const created = create(session) + + dispatch({ + type: "opened", + key: session.key, + value: created, + // Listed already, it closes with its tab. + listed: untrack(input.sessions.list).some((item) => item.key === session.key), + routed: untrack(input.sessions.current)?.key, + }) return created.handle }, - dispose() { - entries.forEach((entry) => entry.dispose()) - entries.clear() - listed.clear() - }, + dispose: () => dispatch({ type: "disposed" }), } }