fix(app): show failed and offline review diffs instead of a clean tree (#61862)

This commit is contained in:
Luke Parker
2026-11-04 20:26:57 -06:00
committed by GitHub
Unverified
parent 9dc81059ee
commit 6469454d35
8 changed files with 898 additions and 105 deletions
@@ -1786,6 +1786,29 @@ test("desktop review waits for the session's stored mode before it loads changes
expect(working).toEqual([])
})
// A failed request used to settle like an empty one, so the review claimed the working tree was clean.
test("a failed diff request offers a retry instead of a clean working tree", async ({ page }) => {
await openSession(page, { name: "ReviewDiffFailure", vcsDiff: [fileDiff("src/alpha.ts")] })
const changes = { failing: true }
await page.route(/\/api\/vcs\/diff\?/, (route) => {
if (!changes.failing || new URL(route.request().url()).searchParams.get("untracked") !== "folders")
return route.fallback()
return route.fulfill({ status: 500, headers: { "access-control-allow-origin": "*" }, json: {} })
})
const panel = page.locator("#review-panel")
const failure = panel.getByRole("alert")
await page.getByRole("button", { name: "Toggle review", exact: true }).click()
await openReviewLauncher(panel)
await expect(failure.getByText("Couldn't load changes", { exact: true })).toBeVisible()
await expect(panel.locator('[data-slot="session-review-v2-empty-changes"]')).toHaveCount(0)
changes.failing = false
await failure.getByRole("button", { name: "Try again", exact: true }).click()
await expect(panel.locator('[data-slot="session-review-v2-file-name"]')).toHaveText("alpha.ts")
await expect(failure).toHaveCount(0)
})
test("a chosen mode the session stops offering shows as Git, and comes back when it is offered again", async ({
page,
}) => {
@@ -14,6 +14,9 @@ export default {
"git.description": "Track, review, and undo changes in this project",
loadingChanges: "Loading changes…",
noChanges: "No changes",
"load.failed": "Couldn't load changes",
"load.timeout": "The server took too long to answer",
offline: "Can't reach this server",
"settings.wrapLines.title": "Wrap lines",
"settings.wrapLines.description": "Wrap long lines in mobile diffs instead of scrolling horizontally",
}
@@ -0,0 +1,319 @@
import { describe, expect, test } from "bun:test"
import type { FileDiffInfo } from "@opencode/client/promise"
import {
INITIAL_REVIEW_DIFF_STATE,
reviewDiffReady,
reviewDiffView,
transitionReviewDiff,
type ReviewDiffContext,
type ReviewDiffEffect,
type ReviewDiffEvent,
type ReviewDiffState,
type ReviewDiffTarget,
} from "./machine"
const git: ReviewDiffTarget = {
kind: "vcs",
serverID: "local",
directory: "C:/repo",
mode: "git",
branch: "feature",
defaultBranch: "dev",
}
const branch: ReviewDiffTarget = { ...git, mode: "branch" }
const turn: ReviewDiffTarget = { kind: "turn", serverID: "local", sessionID: "ses_1" }
const alpha: FileDiffInfo[] = [{ file: "src/alpha.ts", patch: "", additions: 1, deletions: 0, status: "modified" }]
const beta: FileDiffInfo[] = [{ file: "src/beta.ts", patch: "", additions: 2, deletions: 1, status: "modified" }]
function ready(target: ReviewDiffTarget, input: { connected?: boolean; demanded?: boolean } = {}): ReviewDiffEvent {
const context: ReviewDiffContext = {
kind: "ready",
target,
connected: input.connected ?? true,
demanded: input.demanded ?? true,
}
return { type: "context.changed", context }
}
// Replays events through the pure machine and collects every effect it asked for, in order.
function play(state: ReviewDiffState, ...events: ReviewDiffEvent[]) {
return events.reduce<{ state: ReviewDiffState; effects: readonly ReviewDiffEffect[] }>(
(result, event) => {
const next = transitionReviewDiff(result.state, event)
return { state: next.state, effects: [...result.effects, ...next.effects] }
},
{ state, effects: [] },
)
}
// The review panel shows Git changes that loaded as attempt 1.
function loaded() {
return play(INITIAL_REVIEW_DIFF_STATE, ready(git), {
type: "fetch.succeeded",
attempt: 1,
rows: { rows: alpha, version: 10 },
}).state
}
describe("a request that fails", () => {
test("shows the failure with a retry instead of a clean working tree", () => {
const failed = play(INITIAL_REVIEW_DIFF_STATE, ready(git), {
type: "fetch.failed",
attempt: 1,
message: "git failed",
})
expect(failed.effects).toEqual([{ type: "fetch", target: git, attempt: 1 }])
expect(reviewDiffView(failed.state)).toEqual({
status: "error",
failure: { type: "rejected", message: "git failed" },
})
expect(reviewDiffReady(failed.state)).toBe(false)
const retried = play(
failed.state,
{ type: "retry" },
{
type: "fetch.succeeded",
attempt: 2,
rows: { rows: alpha, version: 20 },
},
)
expect(retried.effects).toEqual([{ type: "fetch", target: git, attempt: 2 }])
expect(reviewDiffView(retried.state)).toEqual({ status: "ready", rows: alpha, version: 20 })
expect(reviewDiffReady(retried.state)).toBe(true)
})
test("times out instead of loading forever, and a timed-out refresh keeps the diffs shown", () => {
const timedOut = play(INITIAL_REVIEW_DIFF_STATE, ready(git), { type: "fetch.timed-out", attempt: 1 }).state
expect(reviewDiffView(timedOut)).toEqual({ status: "error", failure: { type: "timeout" } })
const refreshed = play(loaded(), { type: "refresh", source: "vcs" }, { type: "fetch.timed-out", attempt: 2 })
expect(refreshed.effects).toEqual([{ type: "fetch", target: git, attempt: 2 }])
expect(reviewDiffView(refreshed.state)).toEqual({ status: "ready", rows: alpha, version: 10 })
})
test("a failed refresh keeps the diffs shown", () => {
const state = play(
loaded(),
{ type: "window.focused" },
{ type: "fetch.failed", attempt: 2, message: "boom" },
).state
expect(reviewDiffView(state)).toEqual({ status: "ready", rows: alpha, version: 10 })
})
test("a retry outside a failure does nothing", () => {
const state = loaded()
expect(transitionReviewDiff(state, { type: "retry" }).state).toBe(state)
})
})
describe("a disconnected server", () => {
test("shows offline instead of loading forever, and loads once it reconnects", () => {
const unresolved = play(INITIAL_REVIEW_DIFF_STATE, { type: "context.changed", context: { kind: "offline" } })
expect(reviewDiffView(unresolved.state)).toEqual({ status: "offline" })
expect(unresolved.effects).toEqual([])
const offline = play(unresolved.state, ready(git, { connected: false }))
expect(reviewDiffView(offline.state)).toEqual({ status: "offline" })
expect(offline.effects).toEqual([])
const reconnected = play(offline.state, ready(git))
expect(reviewDiffView(reconnected.state)).toEqual({ status: "loading" })
expect(reconnected.effects).toEqual([{ type: "fetch", target: git, attempt: 1 }])
})
test("a disconnect ends the request and drops its late answer", () => {
const state = play(INITIAL_REVIEW_DIFF_STATE, ready(git), ready(git, { connected: false }), {
type: "fetch.succeeded",
attempt: 1,
rows: { rows: alpha, version: 10 },
})
expect(state.effects).toEqual([{ type: "fetch", target: git, attempt: 1 }, { type: "abort" }])
expect(reviewDiffView(state.state)).toEqual({ status: "offline" })
})
test("keeps loaded diffs while disconnected and refreshes them on reconnect", () => {
const disconnected = play(loaded(), ready(git, { connected: false }))
expect(reviewDiffView(disconnected.state)).toEqual({ status: "ready", rows: alpha, version: 10 })
expect(transitionReviewDiff(disconnected.state, { type: "side.opened" }).state).toBe(disconnected.state)
const reconnected = play(disconnected.state, ready(git))
expect(reconnected.effects).toEqual([{ type: "fetch", target: git, attempt: 2 }])
expect(reviewDiffView(reconnected.state)).toEqual({ status: "ready", rows: alpha, version: 10 })
})
})
describe("the side region opening", () => {
test("waits for the session store before it requests the stored mode", () => {
const waiting = play(INITIAL_REVIEW_DIFF_STATE, { type: "context.changed", context: { kind: "waiting" } }).state
const opened = transitionReviewDiff(waiting, { type: "side.opened" })
expect(opened.state).toBe(waiting)
expect(opened.effects).toEqual([])
const idle = play(waiting, ready(branch, { demanded: false }), { type: "side.opened" })
expect(idle.effects).toEqual([{ type: "fetch", target: branch, attempt: 1 }])
})
test("does not request again while a request runs", () => {
const loading = play(INITIAL_REVIEW_DIFF_STATE, ready(git)).state
expect(transitionReviewDiff(loading, { type: "side.opened" }).state).toBe(loading)
})
})
describe("another target", () => {
test("aborts the running request and drops its answers", () => {
const switched = play(
INITIAL_REVIEW_DIFF_STATE,
ready(git),
ready(branch),
{ type: "fetch.succeeded", attempt: 1, rows: { rows: alpha, version: 10 } },
{ type: "fetch.failed", attempt: 1, message: "aborted" },
)
expect(switched.effects).toEqual([
{ type: "fetch", target: git, attempt: 1 },
{ type: "abort" },
{ type: "fetch", target: branch, attempt: 2 },
])
expect(reviewDiffView(switched.state)).toEqual({ status: "loading" })
const settled = play(switched.state, { type: "fetch.succeeded", attempt: 2, rows: { rows: beta, version: 20 } })
expect(reviewDiffView(settled.state)).toEqual({ status: "ready", rows: beta, version: 20 })
})
test("shows what an earlier request loaded for it while it loads again", () => {
const state = play(loaded(), {
type: "context.changed",
context: { kind: "ready", target: branch, connected: true, demanded: true, cached: { rows: beta, version: 5 } },
})
expect(state.effects).toEqual([{ type: "fetch", target: branch, attempt: 2 }])
expect(reviewDiffView(state.state)).toEqual({ status: "ready", rows: beta, version: 5 })
})
test("never carries the previous target's failure", () => {
const failed = play(INITIAL_REVIEW_DIFF_STATE, ready(git), { type: "fetch.failed", attempt: 1, message: "boom" })
const switched = play(failed.state, ready(turn))
expect(reviewDiffView(switched.state)).toEqual({ status: "loading" })
})
})
describe("background refreshes", () => {
test("follow the source that changed while something shows the changes", () => {
const state = loaded()
expect(play(state, { type: "refresh", source: "vcs" }).effects).toEqual([
{ type: "fetch", target: git, attempt: 2 },
])
expect(transitionReviewDiff(state, { type: "refresh", source: "turn" }).state).toBe(state)
const hidden = play(state, ready(git, { demanded: false })).state
expect(transitionReviewDiff(hidden, { type: "refresh", source: "vcs" }).state).toBe(hidden)
expect(transitionReviewDiff(hidden, { type: "window.focused" }).state).toBe(hidden)
expect(play(hidden, ready(git)).effects).toEqual([{ type: "fetch", target: git, attempt: 2 }])
})
test("a focused window refreshes Git changes but not a finished turn", () => {
const changes = play(INITIAL_REVIEW_DIFF_STATE, ready(turn), {
type: "fetch.succeeded",
attempt: 1,
rows: { rows: alpha, version: 10 },
}).state
expect(transitionReviewDiff(changes, { type: "window.focused" }).state).toBe(changes)
expect(play(changes, { type: "refresh", source: "turn" }).effects).toEqual([
{ type: "fetch", target: turn, attempt: 2 },
])
})
test("files that keep changing during the first load cannot hold it off: it keeps its request, then loads once more", () => {
const changing = play(
INITIAL_REVIEW_DIFF_STATE,
ready(git),
...Array.from({ length: 5 }, (): ReviewDiffEvent => ({ type: "refresh", source: "vcs" })),
)
expect(changing.effects).toEqual([{ type: "fetch", target: git, attempt: 1 }])
const settled = play(changing.state, { type: "fetch.succeeded", attempt: 1, rows: { rows: alpha, version: 10 } })
expect(settled.effects).toEqual([{ type: "fetch", target: git, attempt: 2 }])
expect(reviewDiffView(settled.state)).toEqual({ status: "ready", rows: alpha, version: 10 })
const final = play(settled.state, { type: "fetch.succeeded", attempt: 2, rows: { rows: beta, version: 20 } })
expect(final.effects).toEqual([])
expect(reviewDiffView(final.state)).toEqual({ status: "ready", rows: beta, version: 20 })
})
test("the first load still times out while files keep changing", () => {
const state = play(
INITIAL_REVIEW_DIFF_STATE,
ready(git),
{ type: "refresh", source: "vcs" },
{ type: "refresh", source: "vcs" },
{ type: "fetch.timed-out", attempt: 1 },
)
expect(state.effects).toEqual([{ type: "fetch", target: git, attempt: 1 }])
expect(reviewDiffView(state.state)).toEqual({ status: "error", failure: { type: "timeout" } })
})
test("a change while shown diffs refresh restarts the refresh", () => {
const state = play(loaded(), { type: "refresh", source: "vcs" }, { type: "refresh", source: "vcs" })
expect(state.effects).toEqual([
{ type: "fetch", target: git, attempt: 2 },
{ type: "abort" },
{ type: "fetch", target: git, attempt: 3 },
])
})
})
test("disposal aborts the running request and ignores every later event", () => {
const disposed = play(INITIAL_REVIEW_DIFF_STATE, ready(git), { type: "disposed" })
expect(disposed.effects).toEqual([{ type: "fetch", target: git, attempt: 1 }, { type: "abort" }])
const late = play(
disposed.state,
{ type: "fetch.succeeded", attempt: 1, rows: { rows: alpha, version: 10 } },
ready(branch),
{ type: "retry" },
)
expect(late.state).toBe(disposed.state)
expect(late.effects).toEqual([])
})
test("a project without a repository is ready without a request", () => {
const state = play(loaded(), { type: "context.changed", context: { kind: "no-vcs" } })
expect(state.effects).toEqual([])
expect(reviewDiffView(state.state)).toEqual({ status: "no-vcs" })
expect(reviewDiffReady(state.state)).toBe(true)
})
+274
View File
@@ -0,0 +1,274 @@
import type { FileDiffInfo } from "@opencode/client/promise"
/** How long a diff request may run before the review shows it failed, so a wedged server never loads forever. */
export const REVIEW_DIFF_TIMEOUT_MS = 30_000
/** What one diff request reads: a directory's changes against the working tree or branch, or a session's last turn. */
export type ReviewDiffTarget =
| {
readonly kind: "vcs"
readonly serverID: string
readonly directory: string
readonly mode: "git" | "branch"
readonly branch: string
readonly defaultBranch: string
}
| { readonly kind: "turn"; readonly serverID: string; readonly sessionID: string }
/** Diffs loaded once for a target, with the version that tells their detail requests apart. */
export type ReviewDiffRows = { readonly rows: readonly FileDiffInfo[]; readonly version: number }
/** What the routed session lets the review request. */
export type ReviewDiffContext =
/** The session store has not loaded, or the connected server has not sent the project: the mode is not known yet. */
| { readonly kind: "waiting" }
/** The project has no repository. */
| { readonly kind: "no-vcs" }
/** The server is disconnected before it sent the project. */
| { readonly kind: "offline" }
| {
readonly kind: "ready"
readonly target: ReviewDiffTarget
readonly connected: boolean
/** Something shows the changes: the review panel, a change tree or file markers. */
readonly demanded: boolean
/** Diffs an earlier request loaded for this target, shown while they load again. */
readonly cached?: ReviewDiffRows
}
export type ReviewDiffFailure = { readonly type: "rejected"; readonly message: string } | { readonly type: "timeout" }
type Link = {
readonly target: ReviewDiffTarget
readonly connected: boolean
readonly demanded: boolean
/** The last request's number; a result for any other number is stale. */
readonly attempt: number
}
export type ReviewDiffState =
| { readonly status: "waiting"; readonly attempt: number }
| { readonly status: "no-vcs"; readonly attempt: number }
| { readonly status: "offline"; readonly attempt: number }
/** Nothing loaded and no request running: the server is disconnected, or nothing shows the changes. */
| (Link & { readonly status: "idle" })
/** `stale`: files changed while it loads; one more request follows its answer. */
| (Link & { readonly status: "loading"; readonly stale: boolean })
| (Link & { readonly status: "ready" } & ReviewDiffRows)
/** Loads again while the diffs already loaded stay shown. */
| (Link & { readonly status: "refreshing" } & ReviewDiffRows)
| (Link & { readonly status: "error"; readonly failure: ReviewDiffFailure })
| { readonly status: "disposed"; readonly attempt: number }
export type ReviewDiffEvent =
| { readonly type: "context.changed"; readonly context: ReviewDiffContext }
/** The side region opened on a wide screen; loads the changes once so the review tab can count them. */
| { readonly type: "side.opened" }
| { readonly type: "window.focused" }
/** Files changed in the directory (`vcs`), or the session finished a turn (`turn`). */
| { readonly type: "refresh"; readonly source: ReviewDiffTarget["kind"] }
| { readonly type: "retry" }
| { readonly type: "fetch.succeeded"; readonly attempt: number; readonly rows: ReviewDiffRows }
| { readonly type: "fetch.failed"; readonly attempt: number; readonly message: string }
| { readonly type: "fetch.timed-out"; readonly attempt: number }
| { readonly type: "disposed" }
export type ReviewDiffEffect =
/** Starts a request, replacing any running one. */
{ readonly type: "fetch"; readonly target: ReviewDiffTarget; readonly attempt: number } | { readonly type: "abort" }
export type ReviewDiffTransition = { readonly state: ReviewDiffState; readonly effects: readonly ReviewDiffEffect[] }
/** What the review panel shows. */
export type ReviewDiffView =
| { readonly status: "loading" }
| { readonly status: "offline" }
| { readonly status: "no-vcs" }
| { readonly status: "error"; readonly failure: ReviewDiffFailure }
| ({ readonly status: "ready" } & ReviewDiffRows)
type Linked = Extract<ReviewDiffState, Link>
export const INITIAL_REVIEW_DIFF_STATE: ReviewDiffState = { status: "waiting", attempt: 0 }
const LOADING: ReviewDiffView = { status: "loading" }
const OFFLINE: ReviewDiffView = { status: "offline" }
const NO_VCS: ReviewDiffView = { status: "no-vcs" }
const NONE: readonly ReviewDiffEffect[] = []
const ABORT: readonly ReviewDiffEffect[] = [{ type: "abort" }]
export function transitionReviewDiff(state: ReviewDiffState, event: ReviewDiffEvent): ReviewDiffTransition {
if (state.status === "disposed") return unchanged(state)
if (event.type === "disposed") return leave(state, { status: "disposed", attempt: state.attempt })
if (event.type === "context.changed") return contextChanged(state, event.context)
if (!linked(state)) return unchanged(state)
const enabled = state.connected && state.demanded
// Loads even while nothing shows the changes, so the review tab can count them.
if (event.type === "side.opened")
return state.connected && !inFlight(state) ? fetch(state, state, rowsOf(state)) : unchanged(state)
if (event.type === "window.focused")
return enabled && state.target.kind === "vcs" && (state.status === "ready" || state.status === "error")
? fetch(state, state, rowsOf(state))
: unchanged(state)
if (event.type === "refresh") {
if (!enabled || state.target.kind !== event.source) return unchanged(state)
// The first load keeps its request and deadline, so files that keep changing cannot hold it off forever.
if (state.status === "loading") return state.stale ? unchanged(state) : changed({ ...state, stale: true })
// Shown diffs refresh at once, so the answer cannot predate the change.
return fetch(state, state, rowsOf(state))
}
if (event.type === "retry")
return state.status === "error" && state.connected ? fetch(state, state, undefined) : unchanged(state)
if (!inFlight(state) || event.attempt !== state.attempt) return unchanged(state)
if (event.type === "fetch.succeeded") {
if (state.status !== "loading" || !state.stale) return changed({ ...link(state), status: "ready", ...event.rows })
const attempt = state.attempt + 1
// The changes that arrived meanwhile load once more, with the first answer shown.
return {
state: { ...link(state), attempt, status: "refreshing", ...event.rows },
effects: [{ type: "fetch", target: state.target, attempt }],
}
}
// A failed refresh keeps the diffs already shown. A failed first load shows the failure; Try again loads the changes
// that arrived meanwhile too.
if (state.status === "refreshing")
return changed({ ...link(state), status: "ready", rows: state.rows, version: state.version })
return changed({
...link(state),
status: "error",
failure: event.type === "fetch.timed-out" ? { type: "timeout" } : { type: "rejected", message: event.message },
})
}
export function reviewDiffView(state: ReviewDiffState): ReviewDiffView {
if (state.status === "offline") return OFFLINE
if (state.status === "no-vcs") return NO_VCS
if (state.status === "idle") return state.connected ? LOADING : OFFLINE
if (state.status === "error") return { status: "error", failure: state.failure }
if (state.status === "ready" || state.status === "refreshing")
return { status: "ready", rows: state.rows, version: state.version }
return LOADING
}
/** Whether the review knows what to show: diffs, or that the project has no repository. */
export function reviewDiffReady(state: ReviewDiffState) {
return state.status === "ready" || state.status === "refreshing" || state.status === "no-vcs"
}
export function sameReviewDiffTarget(a: ReviewDiffTarget, b: ReviewDiffTarget) {
if (a.kind === "turn") return b.kind === "turn" && a.serverID === b.serverID && a.sessionID === b.sessionID
if (b.kind === "turn") return false
return (
a.serverID === b.serverID &&
a.directory === b.directory &&
a.mode === b.mode &&
a.branch === b.branch &&
a.defaultBranch === b.defaultBranch
)
}
function contextChanged(state: Exclude<ReviewDiffState, { status: "disposed" }>, context: ReviewDiffContext) {
if (context.kind !== "ready")
return state.status === context.kind
? unchanged(state)
: leave(state, { status: context.kind, attempt: state.attempt })
const next: Link = {
target: context.target,
connected: context.connected,
demanded: context.demanded,
attempt: state.attempt,
}
const enabled = next.connected && next.demanded
// Another target starts over from what an earlier request loaded for it, if anything.
if (!linked(state) || !sameReviewDiffTarget(state.target, next.target)) {
if (enabled) return fetch(state, next, context.cached)
return leave(state, context.cached ? { ...next, status: "ready", ...context.cached } : { ...next, status: "idle" })
}
if (state.connected === next.connected && state.demanded === next.demanded) return unchanged(state)
// A disconnect ends the request; what loaded stays shown.
if (!next.connected) {
const rows = rowsOf(state)
return leave(state, rows ? { ...next, status: "ready", ...rows } : { ...next, status: "idle" })
}
// Becoming shown, or reconnecting while shown, loads again.
if (enabled && !(state.connected && state.demanded) && !inFlight(state)) return fetch(state, next, rowsOf(state))
return changed({ ...state, connected: next.connected, demanded: next.demanded })
}
function fetch(state: ReviewDiffState, next: Link, rows: ReviewDiffRows | undefined): ReviewDiffTransition {
const attempt = state.attempt + 1
const start: ReviewDiffEffect = { type: "fetch", target: next.target, attempt }
return {
state: rows
? { ...link(next), attempt, status: "refreshing", ...rows }
: { ...link(next), attempt, status: "loading", stale: false },
effects: inFlight(state) ? [...ABORT, start] : [start],
}
}
/** Moves to a state that runs no request, ending the running one. */
function leave(state: ReviewDiffState, next: ReviewDiffState): ReviewDiffTransition {
return { state: next, effects: inFlight(state) ? ABORT : NONE }
}
function link(state: Link): Link {
return { target: state.target, connected: state.connected, demanded: state.demanded, attempt: state.attempt }
}
function linked(state: ReviewDiffState): state is Linked {
return "target" in state
}
function inFlight(state: ReviewDiffState) {
return state.status === "loading" || state.status === "refreshing"
}
function rowsOf(state: ReviewDiffState): ReviewDiffRows | undefined {
if (state.status !== "ready" && state.status !== "refreshing") return undefined
return { rows: state.rows, version: state.version }
}
function changed(state: ReviewDiffState): ReviewDiffTransition {
return { state, effects: NONE }
}
function unchanged(state: ReviewDiffState): ReviewDiffTransition {
return { state, effects: NONE }
}
+172 -49
View File
@@ -5,7 +5,7 @@ import { artifactMime } from "@opencode/util/artifact"
import { bytesToBase64 } from "@opencode/util/base64"
import { checksum } from "@opencode/util/encode"
import { showToast } from "@opencode/ui/toast"
import { createQuery, useQueries, useQueryClient } from "@tanstack/solid-query"
import { createQuery, focusManager, useQueries, useQueryClient } from "@tanstack/solid-query"
import { debounce } from "@solid-primitives/scheduled"
import { createMemo, createSignal, on, onCleanup, untrack, type Accessor } from "solid-js"
import { createStore } from "solid-js/store"
@@ -36,6 +36,21 @@ import {
type ReviewScrollEvent,
type ReviewScrollState,
} from "./scroll-machine"
import {
INITIAL_REVIEW_DIFF_STATE,
REVIEW_DIFF_TIMEOUT_MS,
reviewDiffReady,
reviewDiffView,
sameReviewDiffTarget,
transitionReviewDiff,
type ReviewDiffContext,
type ReviewDiffEffect,
type ReviewDiffEvent,
type ReviewDiffRows,
type ReviewDiffState,
type ReviewDiffTarget,
type ReviewDiffView,
} from "./machine"
export type ChangeMode = "git" | "branch" | "turn"
@@ -46,6 +61,9 @@ export type Demand = { tree: number; files: number; panel: number; details: numb
/** The narrow review's list and the animation frame that scrolls it to a focused file. */
type ScrollTarget = { element?: HTMLDivElement; frame?: number }
/** The diff request the driver runs: its abort controller and its timeout. */
type DiffRequest = { controller?: AbortController; timer?: ReturnType<typeof setTimeout> }
const selectionFromLines = (range: LineRange): FileSelection => ({
startLine: Math.min(range.start, range.end),
endLine: Math.max(range.start, range.end),
@@ -161,29 +179,122 @@ export function createReviewModel(input: {
const turnKey = () => [ctx.id, view().server.id, "session-turn", view().id] as const
const diffQuery = createQuery(() => {
const value = mode()
const turn = value === "turn"
const diffContext = createMemo(
(): ReviewDiffContext => {
const project = view().project
if (project && !project.vcs) return { kind: "no-vcs" }
return {
queryKey: turn ? turnKey() : ([...vcsKey(), value] as const),
// Desktop storage loads asynchronously; until this session's mode is known, a request would use the default.
enabled: !!stored() && view().server.connected && wantsReview() && !!view().project?.vcs,
refetchOnMount: "always" as const,
// A finished turn does not change on focus or filesystem events; refresh it when the session goes idle.
refetchOnWindowFocus: !turn,
queryFn: turn
? () => view().server.client.session.diff({ sessionID: view().id })
: () =>
view()
.server.client.vcs.diff({
location: { directory: directory() },
mode: value === "git" ? "working" : value,
untracked: "folders",
})
.then((result) => result.data),
}
})
if (!stored()) return { kind: "waiting" }
const connected = view().server.connected
if (!project) return connected ? { kind: "waiting" } : { kind: "offline" }
const value = mode()
const serverID = view().server.id
const target: ReviewDiffTarget =
value === "turn"
? { kind: "turn", serverID, sessionID: view().id }
: {
kind: "vcs",
serverID,
directory: directory(),
mode: value,
branch: vcs()?.branch.current ?? "",
defaultBranch: vcs()?.branch.default ?? "",
}
return { kind: "ready", target, connected, demanded: wantsReview() }
},
undefined,
{ equals: sameDiffContext },
)
const [diffState, setDiffState] = createSignal<ReviewDiffState>(INITIAL_REVIEW_DIFF_STATE)
const diffRequest: DiffRequest = {}
// The diffs a target last loaded stay in the query cache, so returning to a mode or directory shows them at once.
const diffKey = (target: ReviewDiffTarget) =>
target.kind === "turn"
? [ctx.id, target.serverID, "session-turn", target.sessionID]
: [ctx.id, target.serverID, "session-vcs", target.directory, target.branch, target.defaultBranch, target.mode]
const dispatchDiff = (event: ReviewDiffEvent) => {
const next = transitionReviewDiff(untrack(diffState), event)
setDiffState(next.state)
next.effects.forEach(runDiffEffect)
}
const runDiffEffect = (effect: ReviewDiffEffect) => {
clearTimeout(diffRequest.timer)
diffRequest.controller?.abort()
if (effect.type === "abort") return
const attempt = effect.attempt
const controller = new AbortController()
const timer = setTimeout(() => {
controller.abort()
dispatchDiff({ type: "fetch.timed-out", attempt })
}, REVIEW_DIFF_TIMEOUT_MS)
diffRequest.controller = controller
diffRequest.timer = timer
// The machine drops the answer of a request it no longer waits for, aborted or not.
void requestDiff(effect.target, AbortSignal.any([ctx.signal, controller.signal])).then(
(rows) => {
clearTimeout(timer)
const loaded: ReviewDiffRows = { rows, version: Date.now() }
queryClient.setQueryData(diffKey(effect.target), loaded)
dispatchDiff({ type: "fetch.succeeded", attempt, rows: loaded })
},
(cause: unknown) => {
clearTimeout(timer)
dispatchDiff({ type: "fetch.failed", attempt, message: cause instanceof Error ? cause.message : String(cause) })
},
)
}
const requestDiff = (target: ReviewDiffTarget, signal: AbortSignal) => {
const client = view().server.client
if (target.kind === "turn") return client.session.diff({ sessionID: target.sessionID }, { signal })
return client.vcs
.diff(
{
location: { directory: target.directory },
mode: target.mode === "git" ? "working" : target.mode,
untracked: "folders",
},
{ signal },
)
.then((result) => result.data)
}
createKeyed(diffContext, (context) =>
dispatchDiff({
type: "context.changed",
context:
context.kind === "ready"
? { ...context, cached: queryClient.getQueryData<ReviewDiffRows>(diffKey(context.target)) }
: context,
}),
)
// A finished turn does not change on focus or filesystem events; the machine refreshes only Git changes then.
onCleanup(
focusManager.subscribe((focused) => {
if (focused) dispatchDiff({ type: "window.focused" })
}),
)
onCleanup(() => dispatchDiff({ type: "disposed" }))
// A connection or demand change alone keeps the view, so the diffs it shows are not computed again.
const diffView = createMemo(() => reviewDiffView(diffState()), undefined, { equals: sameDiffView })
// The session details' changes row: the session directory's working tree, loaded only while the details show.
const detailsKey = () => [ctx.id, view().server.id, "session-details", view().directory] as const
@@ -203,6 +314,7 @@ export function createReviewModel(input: {
}))
const refresh = debounce(() => {
dispatchDiff({ type: "refresh", source: "vcs" })
void queryClient.invalidateQueries({ queryKey: vcsKey() })
void queryClient.invalidateQueries({ queryKey: detailsKey() })
}, 100)
@@ -232,18 +344,22 @@ export function createReviewModel(input: {
)
createKeyed(opened, () => {
if (diffQuery.isFetching) return
if (input.demand.tree > 0) {
refresh()
return
}
if (view().server.connected && view().project?.vcs) void diffQuery.refetch()
dispatchDiff({ type: "side.opened" })
})
const rows = (): FileDiffInfo[] => (diffQuery.isFetched ? (diffQuery.data ?? []) : [])
const noRows: readonly FileDiffInfo[] = []
const rows = () => {
const current = diffView()
return current.status === "ready" ? current.rows : noRows
}
// Git lists an untracked folder as one row. Once the change tree opens it, the folder lists its entries one level
// deep; they stay loaded while it is closed again, until the changes' source changes.
@@ -323,24 +439,9 @@ export function createReviewModel(input: {
const count = () => rows().length
const hasChanges = () => count() > 0
const ready = () => {
// A project without VCS never enables diffQuery, so its status stays "pending" forever.
const project = view().project
const ready = () => reviewDiffReady(diffState())
if (project && !project.vcs) return true
if (!stored()) return false
return !diffQuery.isPending
}
const lifetime = { disposed: false }
onCleanup(() => {
lifetime.disposed = true
})
const alive = () => !lifetime.disposed && !ctx.signal.aborted
const alive = () => untrack(diffState).status !== "disposed" && !ctx.signal.aborted
// Initializes Git for the routed session. The request keeps that session's object, so its server and location stay
// its own. Cache refresh follows the request's session; only error feedback depends on which session is routed.
@@ -641,6 +742,7 @@ export function createReviewModel(input: {
// A session that goes idle has finished its turn, which may have changed files.
createKeyed(idled, () => {
refresh()
dispatchDiff({ type: "refresh", source: "turn" })
void queryClient.invalidateQueries({ queryKey: turnKey() })
})
@@ -675,7 +777,13 @@ export function createReviewModel(input: {
count,
deferRender,
details: (): FileDiffInfo[] | undefined => (detailsQuery.isFetched ? (detailsQuery.data ?? []) : undefined),
diffVersion: () => diffQuery.dataUpdatedAt,
/** What the review shows: diffs, or why there are none yet. */
diff: diffView,
diffVersion: () => {
const current = diffView()
return current.status === "ready" ? current.version : 0
},
diffs,
folderLabels,
renderable,
@@ -687,11 +795,6 @@ export function createReviewModel(input: {
loadDiff,
readFile,
mode,
noGit: createMemo(() => {
const project = view().project
return !!project && !project.vcs
}),
filter: () => state.filter,
setFilter: (value: string) => setState("filter", value),
open: () => stored()?.open ?? [],
@@ -706,6 +809,7 @@ export function createReviewModel(input: {
options,
panelRendered,
ready,
retry: () => dispatchDiff({ type: "retry" }),
setMode: (value: ChangeMode) =>
update((draft) => {
draft.mode = value
@@ -721,3 +825,22 @@ export function createReviewModel(input: {
}
export type ReviewModel = ReturnType<typeof createReviewModel>
function sameDiffContext(previous: ReviewDiffContext, next: ReviewDiffContext) {
if (previous.kind !== "ready" || next.kind !== "ready") return previous.kind === next.kind
return (
previous.connected === next.connected &&
previous.demanded === next.demanded &&
sameReviewDiffTarget(previous.target, next.target)
)
}
function sameDiffView(previous: ReviewDiffView, next: ReviewDiffView) {
if (previous.status === "ready" && next.status === "ready")
return previous.rows === next.rows && previous.version === next.version
if (previous.status === "error" && next.status === "error") return previous.failure === next.failure
return previous.status === next.status
}
+56 -49
View File
@@ -1,4 +1,4 @@
import { createMemo, createResource, createSignal, Show, type JSX } from "solid-js"
import { createMemo, createResource, createSignal, Match, Show, Switch, type JSX } from "solid-js"
import { Dynamic } from "solid-js/web"
import type { FileDiffInfo } from "@opencode/client/promise"
import {
@@ -32,6 +32,7 @@ import {
sortReviewPaths,
type RenderDiff,
} from "./kinds"
import type { ReviewDiffView } from "./machine"
import type { ReviewModel } from "./model"
import { ReviewPanelEmpty, ReviewTitle } from "./parts"
@@ -54,7 +55,7 @@ type ReviewPanelProps = {
kinds: ReturnType<typeof reviewDiffKinds>
/** Labels for opened untracked folders in the change tree. */
folderLabels?: ReadonlyMap<string, string>
diffsReady: boolean
status: ReviewDiffView["status"]
diffVersion?: number
loadDiff?: (path: string, version?: number) => Promise<RenderDiff | undefined>
readFile: ReviewModel["readFile"]
@@ -92,7 +93,7 @@ export default function ReviewPanelContent(props: {
diffs={props.review.renderable()}
kinds={props.review.kinds()}
folderLabels={props.review.folderLabels()}
diffsReady={props.review.ready()}
status={props.review.diff().status}
diffVersion={props.review.diffVersion()}
loadDiff={props.review.loadDiff}
readFile={props.review.readFile}
@@ -219,7 +220,7 @@ function ReviewPanel(props: ReviewPanelProps) {
session={props.session}
title={props.title}
state={props.state}
diffsReady={props.diffsReady}
status={props.status}
onSelectFile={props.onSelectFile}
diffs={diffs()}
filteredFiles={filteredFiles()}
@@ -272,7 +273,7 @@ function ReviewPanelSidebar(props: {
session: MountedSession
title?: JSX.Element
state: ReviewPanelState
diffsReady: boolean
status: ReviewDiffView["status"]
onSelectFile: (path: string) => void
diffs: RenderDiff[]
filteredFiles: string[]
@@ -326,58 +327,64 @@ function ReviewPanelSidebar(props: {
minWidth={SESSION_REVIEW_V2_SIDEBAR_WIDTH_MIN}
maxWidth={SESSION_REVIEW_V2_SIDEBAR_WIDTH_MAX}
>
<Show
when={props.diffsReady}
fallback={
<Switch>
<Match when={props.status === "loading"}>
<div class="px-2 py-2 text-12-regular text-text-weak">
{ctx.t("common.loading")}
{ctx.t("common.loading.ellipsis")}
</div>
}
>
<Show
when={props.searching}
fallback={
<Show when={views()}>
{(views) => (
<Dynamic
component={views().Tree}
screen={props.screen}
session={props.session}
allowed={props.filteredFiles}
kinds={props.kinds}
labels={props.folderLabels}
active={props.activeDiff}
onFileClick={props.onSelectFile}
/>
)}
</Show>
}
>
</Match>
<Match when={props.status === "offline"}>
<div class="px-2 py-2 text-12-regular text-text-weak">{ctx.t("offline")}</div>
</Match>
<Match when={props.status === "error"}>
<div class="px-2 py-2 text-12-regular text-text-weak">{ctx.t("load.failed")}</div>
</Match>
<Match when={true}>
<Show
when={props.filteredFiles.length > 0}
fallback={<div class="px-2 py-2 text-12-regular text-text-weak">{ctx.t("palette.empty")}</div>}
when={props.searching}
fallback={
<Show when={views()}>
{(views) => (
<Dynamic
component={views().Tree}
screen={props.screen}
session={props.session}
allowed={props.filteredFiles}
kinds={props.kinds}
labels={props.folderLabels}
active={props.activeDiff}
onFileClick={props.onSelectFile}
/>
)}
</Show>
}
>
<Show when={views()}>
{(views) => (
<Dynamic
component={views().List}
screen={props.screen}
session={props.session}
files={props.filteredFiles}
kinds={props.kinds}
active={props.activeDiff}
highlighted={highlightedPath()}
onFileClick={(path: string) => {
setExplicitHighlight(path)
props.onSelectFile(path)
}}
/>
)}
<Show
when={props.filteredFiles.length > 0}
fallback={<div class="px-2 py-2 text-12-regular text-text-weak">{ctx.t("palette.empty")}</div>}
>
<Show when={views()}>
{(views) => (
<Dynamic
component={views().List}
screen={props.screen}
session={props.session}
files={props.filteredFiles}
kinds={props.kinds}
active={props.activeDiff}
highlighted={highlightedPath()}
onFileClick={(path: string) => {
setExplicitHighlight(path)
props.onSelectFile(path)
}}
/>
)}
</Show>
</Show>
</Show>
</Show>
</Show>
</Match>
</Switch>
</SessionReviewV2Sidebar>
)
}
+49 -6
View File
@@ -1,8 +1,10 @@
import { Match, Show, Switch } from "solid-js"
import { SessionReviewEmptyChangesV2 } from "@opencode/session-ui/v2/session-review-empty-changes-v2"
import { SessionReviewEmptyNoGitV2 } from "@opencode/session-ui/v2/session-review-empty-no-git-v2"
import { Button } from "@opencode/ui/button"
import { Select } from "@opencode/ui/select"
import { usePlugin } from "@opencode/plugin/gui"
import type Review from "./index"
import type { ChangeMode, ReviewModel } from "./model"
export function ReviewTitle(props: { review: ReviewModel }) {
@@ -43,7 +45,6 @@ export function ReviewTitle(props: { review: ReviewModel }) {
export function ReviewEmpty(props: { review: ReviewModel; loadingClass: string }) {
const ctx = usePlugin()
const loading = () => !props.review.ready()
const text = () => {
if (props.review.mode() === "git") return ctx.t("empty.git")
@@ -55,14 +56,19 @@ export function ReviewEmpty(props: { review: ReviewModel; loadingClass: string }
return (
<Switch>
<Match when={loading()}>
<Match when={props.review.diff().status === "loading"}>
<div class={props.loadingClass}>{ctx.t("loadingChanges")}</div>
</Match>
<Match when={props.review.noGit()}>
<Match when={props.review.diff().status === "no-vcs"}>
<div class="h-full flex flex-col">
<SessionReviewEmptyNoGitV2 pending={props.review.initializingGit()} onInitGit={props.review.initializeGit} />
</div>
</Match>
<Match when={props.review.diff().status === "offline" || props.review.diff().status === "error"}>
<div class="h-full pb-64 -mt-4 flex flex-col items-center justify-center">
<ReviewUnavailable review={props.review} />
</div>
</Match>
<Match when={true}>
<div class="h-full pb-64 -mt-4 flex flex-col items-center justify-center text-center gap-6">
<div class="text-14-regular text-text-weak max-w-56">{text()}</div>
@@ -74,19 +80,56 @@ export function ReviewEmpty(props: { review: ReviewModel; loadingClass: string }
export function ReviewPanelEmpty(props: { review: ReviewModel }) {
const ctx = usePlugin()
const loading = () => !props.review.ready()
return (
<Switch>
<Match when={loading()}>
<Match when={props.review.diff().status === "loading"}>
<div class="px-6 py-4 text-text-weak">{ctx.t("loadingChanges")}</div>
</Match>
<Match when={props.review.noGit()}>
<Match when={props.review.diff().status === "no-vcs"}>
<SessionReviewEmptyNoGitV2 pending={props.review.initializingGit()} onInitGit={props.review.initializeGit} />
</Match>
<Match when={props.review.diff().status === "offline" || props.review.diff().status === "error"}>
<div class="h-full flex flex-col items-center justify-center">
<ReviewUnavailable review={props.review} />
</div>
</Match>
<Match when={true}>
<SessionReviewEmptyChangesV2 />
</Match>
</Switch>
)
}
/** Why the changes cannot show: the server is unreachable, or their request failed and can be retried. */
function ReviewUnavailable(props: { review: ReviewModel }) {
const ctx = usePlugin<typeof Review>()
const failure = () => {
const current = props.review.diff()
return current.status === "error" ? current.failure : undefined
}
return (
<Show
when={failure()}
keyed
fallback={<div class="px-4 text-center text-14-regular text-text-weak max-w-56">{ctx.t("offline")}</div>}
>
{(failure) => (
<div role="alert" class="flex flex-col items-center gap-3 px-4 text-center">
<div class="flex flex-col gap-1">
<div class="text-13-regular text-text-strong">{ctx.t("load.failed")}</div>
<div class="text-12-regular text-text-weak break-words">
{failure.type === "timeout" ? ctx.t("load.timeout") : failure.message}
</div>
</div>
<Button size="small" variant="outline" onClick={() => props.review.retry()}>
{ctx.t("common.retry")}
</Button>
</div>
)}
</Show>
)
}
+2 -1
View File
@@ -20,7 +20,8 @@ export interface Changes {
*/
diffs(session: SessionRef): readonly FileDiffInfo[]
/**
* False while the current mode's diffs load.
* True once the current mode's diffs loaded, or the project has no repository. False while they load, after their
* request failed or timed out, while the server is unreachable, and before anything requested them.
*
* @param session - The session to read.
* @returns Whether the diffs loaded.