fix(app): keep each screen's review model while anything holds it (#61866)

This commit is contained in:
Luke Parker
2026-11-04 20:10:44 -06:00
committed by GitHub
Unverified
parent 1d7b8425f8
commit 94bb890d27
3 changed files with 494 additions and 56 deletions
+129 -56
View File
@@ -10,7 +10,6 @@ import {
Suspense,
untrack,
} from "solid-js"
import { createStore } from "solid-js/store"
import { Icon } from "@opencode/ui/icon"
import type { FileDiffInfo } from "@opencode/client/promise"
import {
@@ -30,6 +29,15 @@ import { BuiltinPanel, onIdle, type BuiltinPanelTab } from "@opencode/plugin/gui
import { Changes, type ChangeKind } from "@opencode/plugin/gui/review"
import type Review from "./index"
import { createReviewModel, type Demand, type ReviewModel } from "./model"
import {
INITIAL_REVIEW_SCREEN_STATE,
reviewScreenDemand,
reviewScreenModel,
reviewScreenModels,
transitionReviewScreen,
type ReviewScreenEvent,
type ReviewScreenState,
} from "./screen-machine"
const TAB = "changes"
@@ -42,79 +50,130 @@ const setup: Plugin.Setup<typeof Review> = (ctx) => {
const diff = ctx.stores.diff
const panel = ctx.stores.panel
// Who shows a screen's changes: the review render, the file tree, and file tabs. Keyed by the session screen, which
// stays while it routes another session, so a session switch keeps the demand.
const demands = new WeakMap<SessionScreen, ReturnType<typeof createStore<Demand>>>()
// One review model per session screen, like the review the screen created before plugins. The screen keeps it while
// it is routed, a review panel renders it, or a view watches its changes; it follows the routed session through `view`.
const [screens, setScreens] = createSignal<ReviewScreenState>(INITIAL_REVIEW_SCREEN_STATE)
const screenIDs = new WeakMap<SessionScreen, number>()
const runtimes = new Map<number, { attempt: number; model: ReviewModel; dispose: () => void }>()
const ids = { screen: 0, lease: 0 }
const demand = (screen: SessionScreen) => {
const existing = demands.get(screen)
const screenID = (screen: SessionScreen) => {
const existing = screenIDs.get(screen)
if (existing) return existing
if (existing !== undefined) return existing
ids.screen += 1
screenIDs.set(screen, ids.screen)
const created = createStore<Demand>({ tree: 0, files: 0, panel: 0, details: 0 })
return ids.screen
}
demands.set(screen, created)
/** `origin` is the screen and session of the event, which a model the event creates starts from. */
const dispatchScreen = (event: ReviewScreenEvent, origin?: { screen: SessionScreen; session: MountedSession }) => {
const next = transitionReviewScreen(untrack(screens), event)
return created
// One batch, so readers of the state find the models its effects created.
batch(() => {
setScreens(next.state)
next.effects.forEach((effect) => {
if (effect.type === "model.dispose") {
const runtime = runtimes.get(effect.screenID)
if (runtime?.attempt !== effect.attempt) return
runtimes.delete(effect.screenID)
runtime.dispose()
return
}
if (!origin) return
const screen = origin.screen
const id = effect.screenID
runtimes.set(
id,
createRoot((dispose) => {
// The routed session of this screen; the last one stays while it routes none.
const view = createMemo<MountedSession>(
(last) => (ctx.screen.current() === screen ? sessions.current() : undefined) ?? last,
origin.session,
)
const demand = createMemo(() => reviewScreenDemand(screens(), id), undefined, { equals: sameDemand })
const model = createReviewModel({
ctx,
screen,
view,
demand: {
get tree() {
return demand().tree
},
get files() {
return demand().files
},
get panel() {
return demand().panel
},
get details() {
return demand().details
},
},
})
return { attempt: effect.attempt, model, dispose }
}, owner),
)
})
})
}
// Views receive their screen before the public attachment is published, so initial render effects can watch it.
const watch = (screen: SessionScreen, source: keyof Demand) => {
const set = demand(screen)[1]
ids.lease += 1
const watchID = ids.lease
const id = screenID(screen)
set(source, (count) => count + 1)
dispatchScreen({ type: "watch.added", screenID: id, watchID, source })
return () => set(source, (count) => Math.max(0, count - 1))
return () => dispatchScreen({ type: "watch.removed", screenID: id, watchID })
}
// One review model per session screen, like the review the screen created before plugins, created once the
// screen routes a session. It follows the routed session, a new object on each switch, through `view`.
const [entry, setEntry] = createSignal<{ screen: SessionScreen; model: ReviewModel; dispose: () => void }>()
createKeyed(
ctx.screen.current,
(screen) => {
const current = untrack(entry)
const initial = untrack(sessions.current)
() => {
const screen = ctx.screen.current()
const session = sessions.current()
if (current?.screen === screen || !initial) return
current?.dispose()
setEntry(
createRoot((dispose) => {
// The routed session of this screen; the last one stays while none is routed for a moment.
const view = createMemo<MountedSession>(
(last) => (ctx.screen.current() === screen ? sessions.current() : undefined) ?? last,
initial,
)
return { screen, model: createReviewModel({ ctx, screen, view, demand: demand(screen)[0] }), dispose }
}, owner),
)
return screen && session ? { screen, session } : undefined
},
(current) => dispatchScreen({ type: "route.entered", screenID: screenID(current.screen) }, current),
{
// A screen that unmounts and remounts in one update keeps its model.
otherwise: () => {
const current = untrack(entry)
queueMicrotask(() => {
if (sessions.current() || untrack(entry) !== current) return
current?.dispose()
setEntry(undefined)
})
},
// The model follows a session switch on the same screen through `view`.
equals: (previous, next) => previous.screen === next.screen,
otherwise: () => dispatchScreen({ type: "route.left" }),
},
)
onCleanup(() => untrack(entry)?.dispose())
onCleanup(() => dispatchScreen({ type: "disposed" }))
const modelFor = (session: SessionRef) => {
const model = entry()?.model
const liveModel = (state: ReviewScreenState, id: number) => {
const attempt = reviewScreenModel(state, id)
const runtime = runtimes.get(id)
return model && model.view().key === session.key ? model : undefined
return attempt !== undefined && runtime?.attempt === attempt ? runtime.model : undefined
}
const count = () => entry()?.model.count() ?? 0
const modelFor = (session: SessionRef) => {
const state = screens()
return reviewScreenModels(state)
.map((id) => liveModel(state, id))
.find((model) => model?.view().key === session.key)
}
const count = () => {
const session = sessions.current()
return session ? (modelFor(session)?.count() ?? 0) : 0
}
// One tab object for every session, so a session switch never renders its trigger again.
const tab: BuiltinPanelTab = {
@@ -161,13 +220,18 @@ const setup: Plugin.Setup<typeof Review> = (ctx) => {
closed: (): ClosedPanelTab => ({ title: ctx.t("tab.title"), icon: "review" }),
render: (props) => {
const frame = usePanel()
const id = screenID(props.screen)
ids.lease += 1
const panelID = ids.lease
// A server switch mounts a new screen before the owned model effect runs. Never render the old screen's model.
const model = () => {
const current = entry()
// The panel holds its screen's model, so a screen it renders before the route publishes it has one at once.
dispatchScreen(
{ type: "panel.mounted", screenID: id, panelID },
{ screen: props.screen, session: untrack(() => props.session) },
)
onCleanup(() => dispatchScreen({ type: "panel.unmounted", screenID: id, panelID }))
return current?.screen === props.screen ? current.model : undefined
}
const model = () => liveModel(screens(), id)
return (
<Show when={model()} keyed>
@@ -313,4 +377,13 @@ const setup: Plugin.Setup<typeof Review> = (ctx) => {
})
}
function sameDemand(previous: Demand, next: Demand) {
return (
previous.tree === next.tree &&
previous.files === next.files &&
previous.panel === next.panel &&
previous.details === next.details
)
}
export default setup
@@ -0,0 +1,166 @@
import { describe, expect, test } from "bun:test"
import {
INITIAL_REVIEW_SCREEN_STATE,
reviewScreenDemand,
reviewScreenModel,
reviewScreenModels,
transitionReviewScreen,
type ReviewScreenEffect,
type ReviewScreenEvent,
type ReviewScreenState,
} from "./screen-machine"
// Replays events through the pure machine and collects every effect it asked for, in order.
function play(state: ReviewScreenState, ...events: ReviewScreenEvent[]) {
return events.reduce<{ state: ReviewScreenState; effects: readonly ReviewScreenEffect[] }>(
(result, event) => {
const next = transitionReviewScreen(result.state, event)
return { state: next.state, effects: [...result.effects, ...next.effects] }
},
{ state, effects: [] },
)
}
// Screen 1 routes a session and renders the review panel (panel 10), as a session with the side region open does.
function shown() {
return play(
INITIAL_REVIEW_SCREEN_STATE,
{ type: "route.entered", screenID: 1 },
{ type: "panel.mounted", screenID: 1, panelID: 10 },
)
}
describe("a server switch", () => {
test("gives the new screen's panel its own model before the route publishes the screen", () => {
const mounted = play(shown().state, { type: "panel.mounted", screenID: 2, panelID: 20 })
expect(mounted.effects).toEqual([{ type: "model.create", screenID: 2, attempt: 2 }])
expect(reviewScreenModel(mounted.state, 2)).toBe(2)
expect(reviewScreenModel(mounted.state, 1)).toBe(1)
expect(reviewScreenModels(mounted.state)).toEqual([1, 2])
})
test("disposes only the old screen's model, whichever of route and unmount comes first", () => {
const mounted = play(shown().state, { type: "panel.mounted", screenID: 2, panelID: 20 }).state
const routedFirst = play(
mounted,
{ type: "route.entered", screenID: 2 },
{ type: "panel.unmounted", screenID: 1, panelID: 10 },
)
const unmountedFirst = play(
mounted,
{ type: "panel.unmounted", screenID: 1, panelID: 10 },
{ type: "route.entered", screenID: 2 },
)
expect(routedFirst.effects).toEqual([{ type: "model.dispose", screenID: 1, attempt: 1 }])
expect(unmountedFirst.effects).toEqual([{ type: "model.dispose", screenID: 1, attempt: 1 }])
expect(reviewScreenModels(routedFirst.state)).toEqual([2])
expect(routedFirst.state).toEqual(unmountedFirst.state)
})
})
describe("a moment without a route", () => {
test("keeps the model while its panel renders, however long the moment lasts", () => {
const left = play(shown().state, { type: "route.left" })
expect(left.effects).toEqual([])
expect(reviewScreenModel(left.state, 1)).toBe(1)
const back = play(left.state, { type: "route.entered", screenID: 1 })
expect(back.effects).toEqual([])
expect(reviewScreenModel(back.state, 1)).toBe(1)
})
test("disposes the model once nothing holds the screen", () => {
const left = play(
INITIAL_REVIEW_SCREEN_STATE,
{ type: "route.entered", screenID: 1 },
{ type: "route.left" },
{ type: "route.left" },
)
expect(left.effects).toEqual([
{ type: "model.create", screenID: 1, attempt: 1 },
{ type: "model.dispose", screenID: 1, attempt: 1 },
])
expect(reviewScreenModel(left.state, 1)).toBeUndefined()
})
})
describe("watches", () => {
test("a released watch releases only its own hold, once", () => {
const watched = play(
shown().state,
{ type: "watch.added", screenID: 1, watchID: 30, source: "files" },
{ type: "watch.added", screenID: 1, watchID: 31, source: "files" },
).state
expect(reviewScreenDemand(watched, 1).files).toBe(2)
const released = transitionReviewScreen(watched, { type: "watch.removed", screenID: 1, watchID: 30 }).state
expect(reviewScreenDemand(released, 1).files).toBe(1)
expect(transitionReviewScreen(released, { type: "watch.removed", screenID: 1, watchID: 30 }).state).toBe(released)
})
test("hold their demand before the screen routes, and keep a model nothing else holds", () => {
const watching = play(INITIAL_REVIEW_SCREEN_STATE, {
type: "watch.added",
screenID: 1,
watchID: 30,
source: "details",
})
expect(watching.effects).toEqual([])
expect(reviewScreenModel(watching.state, 1)).toBeUndefined()
expect(reviewScreenDemand(watching.state, 1)).toEqual({ tree: 0, files: 0, panel: 0, details: 1 })
const routed = play(watching.state, { type: "route.entered", screenID: 1 }, { type: "route.left" })
expect(routed.effects).toEqual([{ type: "model.create", screenID: 1, attempt: 1 }])
expect(reviewScreenDemand(routed.state, 1).details).toBe(1)
const released = play(routed.state, { type: "watch.removed", screenID: 1, watchID: 30 })
expect(released.effects).toEqual([{ type: "model.dispose", screenID: 1, attempt: 1 }])
})
test("a watch released before the screen routes leaves nothing behind", () => {
const state = play(
INITIAL_REVIEW_SCREEN_STATE,
{ type: "watch.added", screenID: 1, watchID: 30, source: "files" },
{ type: "watch.removed", screenID: 1, watchID: 30 },
)
expect(state.effects).toEqual([])
expect(state.state).toEqual(INITIAL_REVIEW_SCREEN_STATE)
})
})
test("disposal disposes every model and ignores later events", () => {
const disposed = play(
shown().state,
{ type: "panel.mounted", screenID: 2, panelID: 20 },
{ type: "watch.added", screenID: 3, watchID: 30, source: "files" },
{ type: "disposed" },
)
expect(disposed.effects.filter((effect) => effect.type === "model.dispose")).toEqual([
{ type: "model.dispose", screenID: 1, attempt: 1 },
{ type: "model.dispose", screenID: 2, attempt: 2 },
])
const late = play(
disposed.state,
{ type: "route.entered", screenID: 1 },
{ type: "panel.unmounted", screenID: 1, panelID: 10 },
)
expect(late.state).toBe(disposed.state)
expect(late.effects).toEqual([])
})
@@ -0,0 +1,199 @@
import type { Demand } from "./model"
/** One `Changes.watch` hold: which view shows the screen's changes. */
export type ReviewScreenWatch = { readonly id: number; readonly source: keyof Demand }
export type ReviewScreenEntry =
/** Views watch the screen's changes before it routes a session or renders the review panel. */
| { readonly phase: "watching"; readonly watches: readonly ReviewScreenWatch[] }
/** The screen has a review model, kept while it is routed, a review panel renders it, or a view watches it. */
| {
readonly phase: "ready"
/** The model's number; a dispose for another number is stale. */
readonly attempt: number
readonly panels: readonly number[]
readonly watches: readonly ReviewScreenWatch[]
}
/** The review model of each session screen. Screens and leases are numbered by the driver. */
export type ReviewScreenState =
| {
readonly status: "active"
/** The last model number handed out. */
readonly issued: number
/** The screen the route shows. */
readonly routed: number | undefined
readonly entries: Readonly<Record<number, ReviewScreenEntry>>
}
| { readonly status: "disposed" }
export type ReviewScreenEvent =
| { readonly type: "route.entered"; readonly screenID: number }
| { readonly type: "route.left" }
| { readonly type: "panel.mounted"; readonly screenID: number; readonly panelID: number }
| { readonly type: "panel.unmounted"; readonly screenID: number; readonly panelID: number }
| { readonly type: "watch.added"; readonly screenID: number; readonly watchID: number; readonly source: keyof Demand }
| { readonly type: "watch.removed"; readonly screenID: number; readonly watchID: number }
| { readonly type: "disposed" }
export type ReviewScreenEffect =
| { readonly type: "model.create"; readonly screenID: number; readonly attempt: number }
| { readonly type: "model.dispose"; readonly screenID: number; readonly attempt: number }
export type ReviewScreenTransition = {
readonly state: ReviewScreenState
readonly effects: readonly ReviewScreenEffect[]
}
type Active = Extract<ReviewScreenState, { status: "active" }>
export const INITIAL_REVIEW_SCREEN_STATE: ReviewScreenState = {
status: "active",
issued: 0,
routed: undefined,
entries: {},
}
const NONE: readonly ReviewScreenEffect[] = []
export function transitionReviewScreen(state: ReviewScreenState, event: ReviewScreenEvent): ReviewScreenTransition {
if (state.status === "disposed") return unchanged(state)
if (event.type === "disposed")
return {
state: { status: "disposed" },
effects: Object.entries(state.entries).flatMap(([id, entry]): ReviewScreenEffect[] =>
entry.phase === "ready" ? [{ type: "model.dispose", screenID: Number(id), attempt: entry.attempt }] : [],
),
}
if (event.type === "route.entered") {
if (state.routed === event.screenID) return unchanged(state)
const routed = { ...state, routed: event.screenID }
const entered =
routed.entries[event.screenID]?.phase === "ready" ? changed(routed) : create(routed, event.screenID, [])
return state.routed === undefined ? entered : settle(entered, state.routed)
}
if (event.type === "route.left")
return state.routed === undefined
? unchanged(state)
: settle(changed({ ...state, routed: undefined }), state.routed)
const entry = state.entries[event.screenID]
// A panel can render its screen before the route publishes it, as on a server switch: it gets the model at once.
if (event.type === "panel.mounted") {
if (entry?.phase !== "ready") return create(state, event.screenID, [event.panelID])
if (entry.panels.includes(event.panelID)) return unchanged(state)
return changed(put(state, event.screenID, { ...entry, panels: [...entry.panels, event.panelID] }))
}
if (event.type === "panel.unmounted") {
if (entry?.phase !== "ready" || !entry.panels.includes(event.panelID)) return unchanged(state)
return settle(
changed(put(state, event.screenID, { ...entry, panels: entry.panels.filter((id) => id !== event.panelID) })),
event.screenID,
)
}
if (event.type === "watch.added") {
if (entry?.watches.some((watch) => watch.id === event.watchID)) return unchanged(state)
const watch: ReviewScreenWatch = { id: event.watchID, source: event.source }
return changed(
put(
state,
event.screenID,
entry ? { ...entry, watches: [...entry.watches, watch] } : { phase: "watching", watches: [watch] },
),
)
}
// A released watch releases only its own hold, once.
if (!entry?.watches.some((watch) => watch.id === event.watchID)) return unchanged(state)
return settle(
changed(
put(state, event.screenID, { ...entry, watches: entry.watches.filter((watch) => watch.id !== event.watchID) }),
),
event.screenID,
)
}
/** The number of the screen's live model, if it has one. */
export function reviewScreenModel(state: ReviewScreenState, screenID: number) {
if (state.status !== "active") return undefined
const entry = state.entries[screenID]
return entry?.phase === "ready" ? entry.attempt : undefined
}
/** The screens with a model, the routed one first. */
export function reviewScreenModels(state: ReviewScreenState) {
if (state.status !== "active") return []
const ids = Object.keys(state.entries).map(Number)
return (state.routed === undefined ? ids : [state.routed, ...ids.filter((id) => id !== state.routed)]).filter(
(id) => state.entries[id]?.phase === "ready",
)
}
/** How many views of each kind show the screen's changes. */
export function reviewScreenDemand(state: ReviewScreenState, screenID: number): Demand {
const watches = state.status === "active" ? (state.entries[screenID]?.watches ?? []) : []
const count = (source: keyof Demand) => watches.filter((watch) => watch.source === source).length
return { tree: count("tree"), files: count("files"), panel: count("panel"), details: count("details") }
}
/** Gives a screen without a model one, keeping the watches it already holds. */
function create(state: Active, screenID: number, panels: readonly number[]): ReviewScreenTransition {
const attempt = state.issued + 1
return {
state: put({ ...state, issued: attempt }, screenID, {
phase: "ready",
attempt,
panels,
watches: state.entries[screenID]?.watches ?? [],
}),
effects: [{ type: "model.create", screenID, attempt }],
}
}
/** Forgets a screen nothing holds anymore, disposing its model. */
function settle(transition: ReviewScreenTransition, screenID: number): ReviewScreenTransition {
const state = transition.state
if (state.status !== "active" || state.routed === screenID) return transition
const entry = state.entries[screenID]
if (!entry || entry.watches.length > 0 || (entry.phase === "ready" && entry.panels.length > 0)) return transition
const entries = Object.fromEntries(Object.entries(state.entries).filter(([id]) => Number(id) !== screenID))
return {
state: { ...state, entries },
effects:
entry.phase === "ready"
? [...transition.effects, { type: "model.dispose", screenID, attempt: entry.attempt }]
: transition.effects,
}
}
function put(state: Active, screenID: number, entry: ReviewScreenEntry): Active {
return { ...state, entries: { ...state.entries, [screenID]: entry } }
}
function changed(state: ReviewScreenState): ReviewScreenTransition {
return { state, effects: NONE }
}
function unchanged(state: ReviewScreenState): ReviewScreenTransition {
return { state, effects: NONE }
}