mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-16 05:01:03 +03:00
fix(app): track declared session-store retention in an explicit state machine (#61919)
This commit is contained in:
committed by
GitHub
Unverified
parent
795ffefd85
commit
aa048bcb89
@@ -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<string>[], state = createSessionStoreState<string>()) {
|
||||
return events.reduce<{ state: SessionStoreState<string>; 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<string> => ({
|
||||
type: "opened",
|
||||
key,
|
||||
value: key,
|
||||
listed: input.listed ?? false,
|
||||
routed: input.routed,
|
||||
})
|
||||
|
||||
const sync = (listed: readonly string[], routed?: string): SessionStoreEvent<string> => ({
|
||||
type: "sync",
|
||||
listed: new Set(listed),
|
||||
routed,
|
||||
})
|
||||
|
||||
const open = (state: SessionStoreState<string>) => (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,
|
||||
})
|
||||
})
|
||||
@@ -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<E> = {
|
||||
/**
|
||||
* `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<E> =
|
||||
| {
|
||||
readonly status: "active"
|
||||
readonly issued: number
|
||||
readonly entries: Readonly<Record<string, SessionStoreEntry<E>>>
|
||||
}
|
||||
| { readonly status: "disposed" }
|
||||
|
||||
export type SessionStoreEvent<E> =
|
||||
/** 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<string>; readonly routed: string | undefined }
|
||||
| { readonly type: "disposed" }
|
||||
|
||||
export type SessionStoreEffect<E> = { readonly type: "dispose"; readonly value: E }
|
||||
|
||||
export type SessionStoreTransition<E> = {
|
||||
readonly state: SessionStoreState<E>
|
||||
readonly effects: readonly SessionStoreEffect<E>[]
|
||||
}
|
||||
|
||||
export function createSessionStoreState<E>(): SessionStoreState<E> {
|
||||
return { status: "active", issued: 0, entries: {} }
|
||||
}
|
||||
|
||||
export function transitionSessionStore<E>(
|
||||
state: SessionStoreState<E>,
|
||||
event: SessionStoreEvent<E>,
|
||||
): SessionStoreTransition<E> {
|
||||
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<E> = {
|
||||
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<E>(state: SessionStoreState<E>, 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<E>(
|
||||
state: Extract<SessionStoreState<E>, { status: "active" }>,
|
||||
routed: string | undefined,
|
||||
effects: readonly SessionStoreEffect<E>[],
|
||||
): SessionStoreTransition<E> {
|
||||
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<E>(value: E): SessionStoreEffect<E> {
|
||||
return { type: "dispose", value }
|
||||
}
|
||||
|
||||
function step<E>(
|
||||
state: SessionStoreState<E>,
|
||||
effects: readonly SessionStoreEffect<E>[] = [],
|
||||
): SessionStoreTransition<E> {
|
||||
return { state, effects }
|
||||
}
|
||||
@@ -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<T>(session: SessionRef, open: () => Persisted<T>)
|
||||
|
||||
/**
|
||||
* 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<T extends object>(input: {
|
||||
readonly open: (session: SessionRef) => Persisted<T>
|
||||
@@ -260,26 +267,25 @@ export function createSessionStore<T extends object>(input: {
|
||||
*/
|
||||
readonly sessions: { list(): readonly SessionRef[]; current(): SessionRef | undefined }
|
||||
}) {
|
||||
const entries = new Map<string, { readonly handle: Persisted<T>; readonly dispose: () => void }>()
|
||||
// Keys a tab has listed while their store was open; only these can close.
|
||||
const listed = new Set<string>()
|
||||
type Opened = { readonly handle: Persisted<T>; readonly dispose: () => void }
|
||||
|
||||
// A plain variable: readers hold the handles, and nothing renders the table itself.
|
||||
const machine = { state: createSessionStoreState<Opened>() }
|
||||
|
||||
const dispatch = (event: SessionStoreEvent<Opened>) => {
|
||||
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<T extends object>(input: {
|
||||
}
|
||||
|
||||
return {
|
||||
get(session: SessionRef) {
|
||||
const existing = entries.get(session.key)
|
||||
get(session: SessionRef): Persisted<T> {
|
||||
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" }),
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user