mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-16 05:01:03 +03:00
fix(app): retry inbox branch loads and lease keybind suspension per caller (#61956)
This commit is contained in:
committed by
GitHub
Unverified
parent
b6cfbec4cc
commit
75e5879d90
@@ -1,6 +1,6 @@
|
||||
import { createSimpleContext } from "@opencode/ui/context"
|
||||
import { useDialog } from "@opencode/ui/context/dialog"
|
||||
import { type Accessor, batch, createEffect, createMemo, onCleanup, onMount, untrack } from "solid-js"
|
||||
import { type Accessor, batch, createEffect, createMemo, createSignal, onCleanup, onMount, untrack } from "solid-js"
|
||||
import { createStore, produce, reconcile } from "solid-js/store"
|
||||
import { Predicate, Schema } from "effect"
|
||||
import { Persistence } from "@/runtime/persistence/schema"
|
||||
@@ -10,6 +10,7 @@ import { useSettings } from "@/settings/model"
|
||||
import { keybindRenames } from "@/settings/keybinds/migration"
|
||||
import en from "@/runtime/i18n/en"
|
||||
import { Persist, persisted } from "@/runtime/persistence/storage"
|
||||
import { INITIAL_KEYBIND_SUSPEND_STATE, selectKeybindsSuspended, transitionKeybindSuspend } from "./suspend-machine"
|
||||
|
||||
const IS_MAC = typeof navigator !== "undefined" && /(Mac|iPod|iPhone|iPad)/.test(navigator.platform)
|
||||
|
||||
@@ -386,11 +387,12 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex
|
||||
const settings = useSettings()
|
||||
const language = useLanguage()
|
||||
|
||||
const [store, setStore] = createStore<{ registrations: CommandRegistration[]; suspendCount: number }>({
|
||||
const [store, setStore] = createStore<{ registrations: CommandRegistration[] }>({
|
||||
registrations: [],
|
||||
suspendCount: 0,
|
||||
})
|
||||
|
||||
const [suspendState, setSuspendState] = createSignal(INITIAL_KEYBIND_SUSPEND_STATE)
|
||||
|
||||
const warnedDuplicates = new Set<string>()
|
||||
|
||||
const [catalog, setCatalog, _, catalogReady] = persisted(Persist.global("command.catalog.v1"), CommandCatalog, {})
|
||||
@@ -479,7 +481,7 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex
|
||||
]
|
||||
})
|
||||
|
||||
const suspended = () => store.suspendCount > 0
|
||||
const suspended = () => selectKeybindsSuspended(suspendState())
|
||||
|
||||
const palette = createMemo(() => {
|
||||
const config = settings.keybinds.get(PALETTE_ID) ?? DEFAULT_PALETTE_KEYBIND
|
||||
@@ -601,8 +603,17 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex
|
||||
return !!config && matchKeybind(parseKeybind(config), event)
|
||||
},
|
||||
show: showPalette,
|
||||
/** Suspends command keybinds until the returned release runs. Each caller holds its own lease. */
|
||||
suspend() {
|
||||
const next = transitionKeybindSuspend(untrack(suspendState), { type: "suspend" })
|
||||
setSuspendState(next)
|
||||
|
||||
return () =>
|
||||
setSuspendState((current) => transitionKeybindSuspend(current, { type: "resume", hold: next.issued }))
|
||||
},
|
||||
/** One shared idempotent hold: `false` suspends keybinds and `true` releases only that hold. */
|
||||
keybinds(enabled: boolean) {
|
||||
setStore("suspendCount", (count) => Math.max(0, count + (enabled ? -1 : 1)))
|
||||
setSuspendState((current) => transitionKeybindSuspend(current, { type: "keybinds", enabled }))
|
||||
},
|
||||
suspended,
|
||||
get catalog() {
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import {
|
||||
INITIAL_KEYBIND_SUSPEND_STATE,
|
||||
selectKeybindsSuspended,
|
||||
transitionKeybindSuspend,
|
||||
type KeybindSuspendEvent,
|
||||
type KeybindSuspendState,
|
||||
} from "./suspend-machine"
|
||||
|
||||
const run = (state: KeybindSuspendState, ...events: KeybindSuspendEvent[]) =>
|
||||
events.reduce(transitionKeybindSuspend, state)
|
||||
|
||||
test("a caller releasing twice keeps another caller's suspension", () => {
|
||||
const both = run(INITIAL_KEYBIND_SUSPEND_STATE, { type: "suspend" }, { type: "suspend" })
|
||||
|
||||
expect(both).toEqual({ status: "suspended", issued: 2, holds: [1, 2] })
|
||||
|
||||
const released = run(both, { type: "resume", hold: 1 })
|
||||
|
||||
expect(run(released, { type: "resume", hold: 1 }, { type: "keybinds", enabled: true })).toBe(released)
|
||||
expect(selectKeybindsSuspended(released)).toBe(true)
|
||||
|
||||
const active = run(released, { type: "resume", hold: 2 })
|
||||
|
||||
expect(active).toEqual({ status: "active", issued: 2 })
|
||||
expect(selectKeybindsSuspended(active)).toBe(false)
|
||||
expect(run(active, { type: "resume", hold: 2 })).toBe(active)
|
||||
expect(run(active, { type: "suspend" })).toEqual({ status: "suspended", issued: 3, holds: [3] })
|
||||
})
|
||||
|
||||
test("a repeated keybinds(false) resumes on one keybinds(true)", () => {
|
||||
const off = run(INITIAL_KEYBIND_SUSPEND_STATE, { type: "keybinds", enabled: false })
|
||||
|
||||
expect(run(off, { type: "keybinds", enabled: false })).toBe(off)
|
||||
expect(selectKeybindsSuspended(run(off, { type: "keybinds", enabled: true }))).toBe(false)
|
||||
})
|
||||
|
||||
test.each([
|
||||
[
|
||||
"the lease outlives the toggle",
|
||||
[
|
||||
{ type: "keybinds", enabled: true },
|
||||
{ type: "resume", hold: 1 },
|
||||
],
|
||||
],
|
||||
[
|
||||
"the toggle outlives the lease",
|
||||
[
|
||||
{ type: "resume", hold: 1 },
|
||||
{ type: "keybinds", enabled: true },
|
||||
],
|
||||
],
|
||||
] satisfies [string, KeybindSuspendEvent[]][])("keybinds stay suspended until every hold ends: %s", (_, releases) => {
|
||||
const held = run(INITIAL_KEYBIND_SUSPEND_STATE, { type: "suspend" }, { type: "keybinds", enabled: false })
|
||||
const partial = run(held, releases[0])
|
||||
|
||||
expect(selectKeybindsSuspended(partial)).toBe(true)
|
||||
expect(selectKeybindsSuspended(run(partial, releases[1]))).toBe(false)
|
||||
})
|
||||
@@ -0,0 +1,46 @@
|
||||
// The hold behind `keybinds(false)`. `suspend()` leases start at 1, so they never collide with it.
|
||||
const TOGGLE_HOLD = 0
|
||||
|
||||
/**
|
||||
* Global command keybind suspension. `holds` is never empty: `0` is the idempotent `keybinds(false)` hold, and
|
||||
* `1..issued` are `suspend()` leases, so a caller can only release its own hold.
|
||||
*/
|
||||
export type KeybindSuspendState =
|
||||
| { readonly status: "active"; readonly issued: number }
|
||||
| { readonly status: "suspended"; readonly issued: number; readonly holds: readonly number[] }
|
||||
|
||||
export type KeybindSuspendEvent =
|
||||
| { readonly type: "suspend" }
|
||||
| { readonly type: "resume"; readonly hold: number }
|
||||
| { readonly type: "keybinds"; readonly enabled: boolean }
|
||||
|
||||
export const INITIAL_KEYBIND_SUSPEND_STATE: KeybindSuspendState = Object.freeze({ status: "active", issued: 0 })
|
||||
|
||||
export function transitionKeybindSuspend(state: KeybindSuspendState, event: KeybindSuspendEvent): KeybindSuspendState {
|
||||
const holds = state.status === "suspended" ? state.holds : []
|
||||
|
||||
if (event.type === "suspend") {
|
||||
const hold = state.issued + 1
|
||||
|
||||
return { status: "suspended", issued: hold, holds: [...holds, hold] }
|
||||
}
|
||||
|
||||
if (event.type === "keybinds" && !event.enabled) {
|
||||
if (holds.includes(TOGGLE_HOLD)) return state
|
||||
|
||||
return { status: "suspended", issued: state.issued, holds: [...holds, TOGGLE_HOLD] }
|
||||
}
|
||||
|
||||
const hold = event.type === "resume" ? event.hold : TOGGLE_HOLD
|
||||
|
||||
if (!holds.includes(hold)) return state
|
||||
const rest = holds.filter((id) => id !== hold)
|
||||
|
||||
if (rest.length === 0) return { status: "active", issued: state.issued }
|
||||
|
||||
return { status: "suspended", issued: state.issued, holds: rest }
|
||||
}
|
||||
|
||||
export function selectKeybindsSuspended(state: KeybindSuspendState) {
|
||||
return state.status === "suspended"
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
BRANCH_LOAD_TIMEOUT_MS,
|
||||
INITIAL_INBOX_BRANCH_STATE,
|
||||
selectBranchLoading,
|
||||
transitionInboxBranch,
|
||||
type InboxBranchEvent,
|
||||
type InboxBranchState,
|
||||
} from "./inbox-branch-machine"
|
||||
|
||||
const target = (key: string, server = "srv") => ({ key, server })
|
||||
|
||||
const run = (state: InboxBranchState, ...events: InboxBranchEvent[]) =>
|
||||
events.reduce((current, event) => transitionInboxBranch(current, event).state, state)
|
||||
|
||||
const entry = (state: InboxBranchState, key: string) => (state.status === "active" ? state.entries[key] : undefined)
|
||||
|
||||
describe("inbox branch machine", () => {
|
||||
test("retries a failed lookup instead of settling it for good", () => {
|
||||
const queued = transitionInboxBranch(INITIAL_INBOX_BRANCH_STATE, { type: "enqueue", targets: [target("a")] })
|
||||
|
||||
expect(queued.effects).toEqual([{ type: "load.start", key: "a", attempt: 1, timeoutMs: BRANCH_LOAD_TIMEOUT_MS }])
|
||||
expect(selectBranchLoading(queued.state, "a")).toBe(true)
|
||||
|
||||
const failed = transitionInboxBranch(queued.state, { type: "load.failed", key: "a", attempt: 1 })
|
||||
|
||||
expect(failed.effects).toEqual([
|
||||
{ type: "timer.clear", attempt: 1 },
|
||||
{ type: "retry.schedule", key: "a", attempt: 2, delayMs: 1_000 },
|
||||
])
|
||||
expect(selectBranchLoading(failed.state, "a")).toBe(false)
|
||||
|
||||
// The view re-enqueues shown rows on every change; that must not count as a fresh lookup or a settled one.
|
||||
expect(transitionInboxBranch(failed.state, { type: "enqueue", targets: [target("a")] }).state).toBe(failed.state)
|
||||
|
||||
const retried = transitionInboxBranch(failed.state, { type: "retry.due", key: "a", attempt: 2 })
|
||||
|
||||
expect(retried.effects).toEqual([{ type: "load.start", key: "a", attempt: 3, timeoutMs: BRANCH_LOAD_TIMEOUT_MS }])
|
||||
expect(selectBranchLoading(retried.state, "a")).toBe(false)
|
||||
|
||||
const ok = run(retried.state, { type: "load.succeeded", key: "a", attempt: 3 })
|
||||
|
||||
expect(entry(ok, "a")).toEqual({ phase: "ok", server: "srv" })
|
||||
})
|
||||
|
||||
test("starts the next lookup as soon as one slot frees, even when another hangs", () => {
|
||||
const keys = ["k1", "k2", "k3", "k4", "k5", "k6"]
|
||||
|
||||
const started = transitionInboxBranch(INITIAL_INBOX_BRANCH_STATE, {
|
||||
type: "enqueue",
|
||||
targets: keys.map((key) => target(key)),
|
||||
})
|
||||
|
||||
expect(started.effects.map((effect) => (effect.type === "load.start" ? effect.key : effect.type))).toEqual([
|
||||
"k1",
|
||||
"k2",
|
||||
"k3",
|
||||
"k4",
|
||||
])
|
||||
|
||||
const failed = transitionInboxBranch(started.state, { type: "load.failed", key: "k1", attempt: 1 })
|
||||
|
||||
expect(failed.effects).toContainEqual({
|
||||
type: "load.start",
|
||||
key: "k5",
|
||||
attempt: 6,
|
||||
timeoutMs: BRANCH_LOAD_TIMEOUT_MS,
|
||||
})
|
||||
|
||||
const hung = transitionInboxBranch(failed.state, { type: "load.timed-out", key: "k2", attempt: 2 })
|
||||
|
||||
expect(hung.effects).toEqual([
|
||||
{ type: "retry.schedule", key: "k2", attempt: 7, delayMs: 1_000 },
|
||||
{ type: "load.start", key: "k6", attempt: 8, timeoutMs: BRANCH_LOAD_TIMEOUT_MS },
|
||||
])
|
||||
expect(selectBranchLoading(hung.state, "k2")).toBe(false)
|
||||
|
||||
// The hung request answering late belongs to an attempt that is no longer current.
|
||||
expect(transitionInboxBranch(hung.state, { type: "load.succeeded", key: "k2", attempt: 2 }).state).toBe(hung.state)
|
||||
})
|
||||
|
||||
test("rests a location after its retries and wakes it when its server reconnects", () => {
|
||||
const connected = run(INITIAL_INBOX_BRANCH_STATE, { type: "connections.changed", connected: ["srv", "other"] })
|
||||
|
||||
const failed = run(
|
||||
connected,
|
||||
{ type: "enqueue", targets: [target("a"), target("b"), target("c", "other")] },
|
||||
{ type: "load.failed", key: "a", attempt: 1 },
|
||||
{ type: "retry.due", key: "a", attempt: 4 },
|
||||
{ type: "load.failed", key: "a", attempt: 5 },
|
||||
{ type: "retry.due", key: "a", attempt: 6 },
|
||||
{ type: "load.failed", key: "a", attempt: 7 },
|
||||
{ type: "load.failed", key: "b", attempt: 2 },
|
||||
{ type: "load.failed", key: "c", attempt: 3 },
|
||||
)
|
||||
|
||||
expect(entry(failed, "a")).toEqual({ phase: "failed", server: "srv" })
|
||||
expect(entry(failed, "b")).toEqual({ phase: "retrying", server: "srv", attempt: 8, failures: 1 })
|
||||
expect(selectBranchLoading(failed, "a")).toBe(false)
|
||||
expect(transitionInboxBranch(failed, { type: "enqueue", targets: [target("a")] }).state).toBe(failed)
|
||||
|
||||
const dropped = run(failed, { type: "connections.changed", connected: ["other"] })
|
||||
const woken = transitionInboxBranch(dropped, { type: "connections.changed", connected: ["other", "srv"] })
|
||||
|
||||
expect(woken.effects).toEqual([
|
||||
{ type: "timer.clear", attempt: 8 },
|
||||
{ type: "load.start", key: "a", attempt: 10, timeoutMs: BRANCH_LOAD_TIMEOUT_MS },
|
||||
{ type: "load.start", key: "b", attempt: 11, timeoutMs: BRANCH_LOAD_TIMEOUT_MS },
|
||||
])
|
||||
expect(entry(woken.state, "c")).toEqual(entry(failed, "c"))
|
||||
expect(selectBranchLoading(woken.state, "a")).toBe(false)
|
||||
expect(transitionInboxBranch(woken.state, { type: "retry.due", key: "b", attempt: 8 }).state).toBe(woken.state)
|
||||
expect(transitionInboxBranch(woken.state, { type: "connections.changed", connected: ["srv", "other"] }).state).toBe(
|
||||
woken.state,
|
||||
)
|
||||
})
|
||||
|
||||
test("enqueues each location once", () => {
|
||||
const state = run(INITIAL_INBOX_BRANCH_STATE, { type: "enqueue", targets: [target("a"), target("a")] })
|
||||
|
||||
expect(state.status === "active" && state.issued).toBe(1)
|
||||
expect(transitionInboxBranch(state, { type: "enqueue", targets: [target("a")] }).state).toBe(state)
|
||||
})
|
||||
|
||||
test("ignores every event after disposal", () => {
|
||||
const loading = run(INITIAL_INBOX_BRANCH_STATE, { type: "enqueue", targets: [target("a")] })
|
||||
const disposed = transitionInboxBranch(loading, { type: "disposed" })
|
||||
|
||||
expect(disposed.effects).toEqual([{ type: "timers.clear" }])
|
||||
expect(selectBranchLoading(disposed.state, "a")).toBe(false)
|
||||
|
||||
const events: InboxBranchEvent[] = [
|
||||
{ type: "enqueue", targets: [target("b")] },
|
||||
{ type: "load.succeeded", key: "a", attempt: 1 },
|
||||
{ type: "load.failed", key: "a", attempt: 1 },
|
||||
{ type: "load.timed-out", key: "a", attempt: 1 },
|
||||
{ type: "retry.due", key: "a", attempt: 1 },
|
||||
{ type: "connections.changed", connected: ["srv"] },
|
||||
{ type: "disposed" },
|
||||
]
|
||||
|
||||
events.forEach((event) =>
|
||||
expect(transitionInboxBranch(disposed.state, event)).toEqual({ state: disposed.state, effects: [] }),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,265 @@
|
||||
// Branch lookups each run git on the server, so load them a few at a time.
|
||||
export const BRANCH_BATCH = 4
|
||||
|
||||
// A lookup that never settles frees its slot after this long, so one hung server cannot stall the rest.
|
||||
export const BRANCH_LOAD_TIMEOUT_MS = 15_000
|
||||
|
||||
export const BRANCH_RETRY_DELAY_MS = 1_000
|
||||
|
||||
export const BRANCH_RETRY_MAX_DELAY_MS = 4_000
|
||||
|
||||
// Retries after the first failed lookup, before the location rests as failed until its server reconnects.
|
||||
export const BRANCH_RETRY_LIMIT = 2
|
||||
|
||||
export type InboxBranchTarget = {
|
||||
readonly key: string
|
||||
readonly server: string
|
||||
}
|
||||
|
||||
/**
|
||||
* One location's git branch load. `initial` is true until the first attempt settles, so only that attempt shows a
|
||||
* loader. `failures` counts failed attempts since the location was enqueued or its server reconnected.
|
||||
* - `queued`: waiting in `queue` for one of the `BRANCH_BATCH` slots.
|
||||
* - `loading`: holding a slot with `attempt` in flight.
|
||||
* - `retrying`: waiting off-queue for backoff `attempt`, holding no slot.
|
||||
* - `ok`: loaded; live updates arrive through `vcs.branch.updated`.
|
||||
* - `failed`: retries exhausted; rests until `server` reconnects.
|
||||
*/
|
||||
export type InboxBranchEntry =
|
||||
| { readonly phase: "queued"; readonly server: string; readonly initial: boolean; readonly failures: number }
|
||||
| {
|
||||
readonly phase: "loading"
|
||||
readonly server: string
|
||||
readonly attempt: number
|
||||
readonly initial: boolean
|
||||
readonly failures: number
|
||||
}
|
||||
| { readonly phase: "retrying"; readonly server: string; readonly attempt: number; readonly failures: number }
|
||||
| { readonly phase: "ok"; readonly server: string }
|
||||
| { readonly phase: "failed"; readonly server: string }
|
||||
|
||||
export type InboxBranchState =
|
||||
| {
|
||||
readonly status: "active"
|
||||
readonly issued: number
|
||||
readonly connected: ReadonlySet<string>
|
||||
readonly queue: readonly string[]
|
||||
readonly entries: Readonly<Record<string, InboxBranchEntry>>
|
||||
}
|
||||
| { readonly status: "disposed" }
|
||||
|
||||
export type InboxBranchEvent =
|
||||
| { readonly type: "enqueue"; readonly targets: readonly InboxBranchTarget[] }
|
||||
| { readonly type: "load.succeeded"; readonly key: string; readonly attempt: number }
|
||||
| { readonly type: "load.failed"; readonly key: string; readonly attempt: number }
|
||||
| { readonly type: "load.timed-out"; readonly key: string; readonly attempt: number }
|
||||
| { readonly type: "retry.due"; readonly key: string; readonly attempt: number }
|
||||
| { readonly type: "connections.changed"; readonly connected: readonly string[] }
|
||||
| { readonly type: "disposed" }
|
||||
|
||||
export type InboxBranchEffect =
|
||||
| { readonly type: "load.start"; readonly key: string; readonly attempt: number; readonly timeoutMs: number }
|
||||
| { readonly type: "retry.schedule"; readonly key: string; readonly attempt: number; readonly delayMs: number }
|
||||
| { readonly type: "timer.clear"; readonly attempt: number }
|
||||
| { readonly type: "timers.clear" }
|
||||
|
||||
export type InboxBranchTransition = {
|
||||
readonly state: InboxBranchState
|
||||
readonly effects: readonly InboxBranchEffect[]
|
||||
}
|
||||
|
||||
type ActiveState = Extract<InboxBranchState, { status: "active" }>
|
||||
|
||||
const NONE: readonly InboxBranchEffect[] = Object.freeze([])
|
||||
|
||||
export const INITIAL_INBOX_BRANCH_STATE: InboxBranchState = Object.freeze({
|
||||
status: "active",
|
||||
issued: 0,
|
||||
connected: new Set<string>(),
|
||||
queue: Object.freeze([]),
|
||||
entries: Object.freeze({}),
|
||||
})
|
||||
|
||||
const DISPOSED_INBOX_BRANCH_STATE: InboxBranchState = Object.freeze({ status: "disposed" })
|
||||
|
||||
export function branchRetryDelay(failures: number) {
|
||||
return Math.min(BRANCH_RETRY_DELAY_MS * 2 ** (failures - 1), BRANCH_RETRY_MAX_DELAY_MS)
|
||||
}
|
||||
|
||||
export function transitionInboxBranch(state: InboxBranchState, event: InboxBranchEvent): InboxBranchTransition {
|
||||
if (state.status === "disposed") return { state, effects: NONE }
|
||||
|
||||
if (event.type === "disposed") return { state: DISPOSED_INBOX_BRANCH_STATE, effects: [{ type: "timers.clear" }] }
|
||||
|
||||
if (event.type === "enqueue") {
|
||||
const added = [
|
||||
...new Map(
|
||||
event.targets.filter((target) => !state.entries[target.key]).map((target) => [target.key, target] as const),
|
||||
).values(),
|
||||
]
|
||||
|
||||
if (added.length === 0) return { state, effects: NONE }
|
||||
|
||||
return pump(
|
||||
{
|
||||
...state,
|
||||
queue: [...state.queue, ...added.map((target) => target.key)],
|
||||
entries: {
|
||||
...state.entries,
|
||||
...Object.fromEntries(
|
||||
added.map((target) => [
|
||||
target.key,
|
||||
{ phase: "queued", server: target.server, initial: true, failures: 0 } satisfies InboxBranchEntry,
|
||||
]),
|
||||
),
|
||||
},
|
||||
},
|
||||
NONE,
|
||||
)
|
||||
}
|
||||
|
||||
if (event.type === "connections.changed") return reconnect(state, new Set(event.connected))
|
||||
|
||||
if (event.type === "retry.due") {
|
||||
const entry = state.entries[event.key]
|
||||
|
||||
if (entry?.phase !== "retrying" || entry.attempt !== event.attempt) return { state, effects: NONE }
|
||||
|
||||
return pump(
|
||||
{
|
||||
...state,
|
||||
queue: [...state.queue, event.key],
|
||||
entries: {
|
||||
...state.entries,
|
||||
[event.key]: { phase: "queued", server: entry.server, initial: false, failures: entry.failures },
|
||||
},
|
||||
},
|
||||
NONE,
|
||||
)
|
||||
}
|
||||
|
||||
const entry = state.entries[event.key]
|
||||
|
||||
if (entry?.phase !== "loading" || entry.attempt !== event.attempt) return { state, effects: NONE }
|
||||
|
||||
// A timeout fires from the attempt's own timer, so only the other results clear it.
|
||||
const cleared: readonly InboxBranchEffect[] =
|
||||
event.type === "load.timed-out" ? NONE : [{ type: "timer.clear", attempt: entry.attempt }]
|
||||
|
||||
if (event.type === "load.succeeded") {
|
||||
return pump(
|
||||
{ ...state, entries: { ...state.entries, [event.key]: { phase: "ok", server: entry.server } } },
|
||||
cleared,
|
||||
)
|
||||
}
|
||||
|
||||
if (entry.failures >= BRANCH_RETRY_LIMIT) {
|
||||
return pump(
|
||||
{ ...state, entries: { ...state.entries, [event.key]: { phase: "failed", server: entry.server } } },
|
||||
cleared,
|
||||
)
|
||||
}
|
||||
|
||||
const failures = entry.failures + 1
|
||||
const attempt = state.issued + 1
|
||||
|
||||
return pump(
|
||||
{
|
||||
...state,
|
||||
issued: attempt,
|
||||
entries: { ...state.entries, [event.key]: { phase: "retrying", server: entry.server, attempt, failures } },
|
||||
},
|
||||
[...cleared, { type: "retry.schedule", key: event.key, attempt, delayMs: branchRetryDelay(failures) }],
|
||||
)
|
||||
}
|
||||
|
||||
/** True while a location's first lookup has not settled. Background retries do not show a loader. */
|
||||
export function selectBranchLoading(state: InboxBranchState, key: string) {
|
||||
if (state.status === "disposed") return false
|
||||
const entry = state.entries[key]
|
||||
|
||||
if (!entry) return true
|
||||
|
||||
return (entry.phase === "queued" || entry.phase === "loading") && entry.initial
|
||||
}
|
||||
|
||||
// A server that connects again wakes its failed and backing-off locations with a fresh retry budget.
|
||||
function reconnect(state: ActiveState, connected: ReadonlySet<string>): InboxBranchTransition {
|
||||
if (connected.size === state.connected.size && [...connected].every((server) => state.connected.has(server))) {
|
||||
return { state, effects: NONE }
|
||||
}
|
||||
|
||||
const woken = Object.entries(state.entries).filter(
|
||||
([, entry]) =>
|
||||
(entry.phase === "failed" || entry.phase === "retrying") &&
|
||||
connected.has(entry.server) &&
|
||||
!state.connected.has(entry.server),
|
||||
)
|
||||
|
||||
if (woken.length === 0) return { state: { ...state, connected }, effects: NONE }
|
||||
|
||||
return pump(
|
||||
{
|
||||
...state,
|
||||
connected,
|
||||
queue: [...state.queue, ...woken.map(([key]) => key)],
|
||||
entries: {
|
||||
...state.entries,
|
||||
...Object.fromEntries(
|
||||
woken.map(([key, entry]) => [
|
||||
key,
|
||||
{ phase: "queued", server: entry.server, initial: false, failures: 0 } satisfies InboxBranchEntry,
|
||||
]),
|
||||
),
|
||||
},
|
||||
},
|
||||
woken.flatMap(([, entry]) =>
|
||||
entry.phase === "retrying" ? [{ type: "timer.clear", attempt: entry.attempt } satisfies InboxBranchEffect] : [],
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
// Fill free slots from the head of the queue, so each settled lookup starts the next one.
|
||||
function pump(state: ActiveState, prior: readonly InboxBranchEffect[]): InboxBranchTransition {
|
||||
const slots = BRANCH_BATCH - Object.values(state.entries).filter((entry) => entry.phase === "loading").length
|
||||
|
||||
if (slots <= 0 || state.queue.length === 0) return { state, effects: prior }
|
||||
|
||||
const starting = state.queue.slice(0, slots).flatMap((key, index) => {
|
||||
const entry = state.entries[key]
|
||||
|
||||
return entry?.phase === "queued" ? [{ key, entry, attempt: state.issued + index + 1 }] : []
|
||||
})
|
||||
|
||||
return {
|
||||
state: {
|
||||
...state,
|
||||
issued: state.issued + Math.min(slots, state.queue.length),
|
||||
queue: state.queue.slice(slots),
|
||||
entries: {
|
||||
...state.entries,
|
||||
...Object.fromEntries(
|
||||
starting.map((item) => [
|
||||
item.key,
|
||||
{
|
||||
phase: "loading",
|
||||
server: item.entry.server,
|
||||
attempt: item.attempt,
|
||||
initial: item.entry.initial,
|
||||
failures: item.entry.failures,
|
||||
} satisfies InboxBranchEntry,
|
||||
]),
|
||||
),
|
||||
},
|
||||
},
|
||||
effects: [
|
||||
...prior,
|
||||
...starting.map((item): InboxBranchEffect => ({
|
||||
type: "load.start",
|
||||
key: item.key,
|
||||
attempt: item.attempt,
|
||||
timeoutMs: BRANCH_LOAD_TIMEOUT_MS,
|
||||
})),
|
||||
],
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { isSessionNotFoundError, type SessionInfo } from "@opencode/client/promise"
|
||||
import { useQueries, useQueryClient } from "@tanstack/solid-query"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { createEffect, createMemo, onCleanup, startTransition } from "solid-js"
|
||||
import { createEffect, createMemo, createSignal, onCleanup, startTransition, untrack } from "solid-js"
|
||||
import { useGlobal, type ServerCtx } from "@/runtime/server/runtime"
|
||||
import { ServerConnection, useServers } from "@/runtime/server/registry"
|
||||
import { canUseServer } from "@/runtime/server/health-machine"
|
||||
@@ -17,13 +17,17 @@ import { notifySessionTabsRemoved } from "./session-events"
|
||||
import { errorMessage } from "@/shell/layout/helpers"
|
||||
import { showToast } from "@/shell/notifications/toast"
|
||||
import { workingSince } from "./inbox-working"
|
||||
import {
|
||||
INITIAL_INBOX_BRANCH_STATE,
|
||||
selectBranchLoading,
|
||||
transitionInboxBranch,
|
||||
type InboxBranchEffect,
|
||||
type InboxBranchEvent,
|
||||
} from "./inbox-branch-machine"
|
||||
|
||||
// Keep the immutable result opaque so Solid Query does not recursively unwrap every session.
|
||||
const selectSessions = (sessions: SessionInfo[]) => () => sessions
|
||||
|
||||
// Branch lookups each run git on the server, so load them a few at a time.
|
||||
const BRANCH_BATCH = 4
|
||||
|
||||
// Root sessions fetched per server.
|
||||
const INDEX_LIMIT = 50
|
||||
|
||||
@@ -262,43 +266,89 @@ export function createSessionInbox(options: { archived?: boolean } = {}) {
|
||||
return route.sessionId === entry.session.id || entry.ctx.data.session.root(route.sessionId) === entry.session.id
|
||||
}
|
||||
|
||||
// Git info is not stored on the session, so load it for the rows a view shows and mark each location settled once
|
||||
// its load ends.
|
||||
const [vcs, setVcs] = createStore<{ settled: Record<string, true> }>({ settled: {} })
|
||||
const queued = new Set<string>()
|
||||
const queue: InboxEntry[] = []
|
||||
const drain = { running: false }
|
||||
// Git info is not stored on the session, so load it for the rows a view shows. `branchTargets` keeps the latest row
|
||||
// per location for the lookup; the machine owns each location's phase.
|
||||
const [branchState, setBranchState] = createSignal(INITIAL_INBOX_BRANCH_STATE)
|
||||
const branchTargets = new Map<string, InboxEntry>()
|
||||
const branchTimers = new Map<number, ReturnType<typeof setTimeout>>()
|
||||
|
||||
const run = async () => {
|
||||
if (drain.running) return
|
||||
drain.running = true
|
||||
const dispatchBranch = (event: InboxBranchEvent) =>
|
||||
untrack(() => {
|
||||
const previous = branchState()
|
||||
const next = transitionInboxBranch(previous, event)
|
||||
|
||||
while (queue.length) {
|
||||
await Promise.all(
|
||||
queue.splice(0, BRANCH_BATCH).map((entry) => {
|
||||
const location = entry.ctx.data.location
|
||||
if (next.state !== previous) setBranchState(next.state)
|
||||
next.effects.forEach(runBranchEffect)
|
||||
})
|
||||
|
||||
return (location.info(entry.session.location) ? Promise.resolve() : location.syncInfo(entry.session.location))
|
||||
.then(() => location.vcs.sync(entry.session.location))
|
||||
.catch(() => undefined)
|
||||
.then(() => setVcs("settled", locationKey(entry), true))
|
||||
}),
|
||||
)
|
||||
const runBranchEffect = (effect: InboxBranchEffect) => {
|
||||
if (effect.type === "timers.clear") {
|
||||
branchTimers.forEach(clearTimeout)
|
||||
branchTimers.clear()
|
||||
branchTargets.clear()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
drain.running = false
|
||||
if (effect.type === "timer.clear") {
|
||||
clearTimeout(branchTimers.get(effect.attempt))
|
||||
branchTimers.delete(effect.attempt)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (effect.type === "retry.schedule") {
|
||||
branchTimers.set(
|
||||
effect.attempt,
|
||||
setTimeout(() => {
|
||||
branchTimers.delete(effect.attempt)
|
||||
dispatchBranch({ type: "retry.due", key: effect.key, attempt: effect.attempt })
|
||||
}, effect.delayMs),
|
||||
)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
branchTimers.set(
|
||||
effect.attempt,
|
||||
setTimeout(() => {
|
||||
branchTimers.delete(effect.attempt)
|
||||
dispatchBranch({ type: "load.timed-out", key: effect.key, attempt: effect.attempt })
|
||||
}, effect.timeoutMs),
|
||||
)
|
||||
// A synchronous throw rejects too, so every attempt settles into an event.
|
||||
void Promise.try(() => {
|
||||
const entry = branchTargets.get(effect.key)
|
||||
|
||||
if (!entry) throw new Error(`No inbox row for location ${effect.key}`)
|
||||
const location = entry.ctx.data.location
|
||||
|
||||
return (
|
||||
location.info(entry.session.location) ? Promise.resolve() : location.syncInfo(entry.session.location)
|
||||
).then(() => location.vcs.sync(entry.session.location))
|
||||
}).then(
|
||||
() => dispatchBranch({ type: "load.succeeded", key: effect.key, attempt: effect.attempt }),
|
||||
() => dispatchBranch({ type: "load.failed", key: effect.key, attempt: effect.attempt }),
|
||||
)
|
||||
}
|
||||
|
||||
createEffect(() =>
|
||||
dispatchBranch({
|
||||
type: "connections.changed",
|
||||
connected: connections().flatMap((item) =>
|
||||
item.ctx.sdk.connection.status() === "connected" ? [ServerConnection.key(item.conn)] : [],
|
||||
),
|
||||
}),
|
||||
)
|
||||
|
||||
onCleanup(() => dispatchBranch({ type: "disposed" }))
|
||||
|
||||
const loadBranches = (list: InboxEntry[]) => {
|
||||
list.forEach((entry) => {
|
||||
const key = locationKey(entry)
|
||||
|
||||
if (queued.has(key)) return
|
||||
|
||||
queued.add(key)
|
||||
queue.push(entry)
|
||||
list.forEach((entry) => branchTargets.set(locationKey(entry), entry))
|
||||
dispatchBranch({
|
||||
type: "enqueue",
|
||||
targets: list.map((entry) => ({ key: locationKey(entry), server: entry.server })),
|
||||
})
|
||||
void run()
|
||||
}
|
||||
|
||||
const open = (entry: InboxEntry) => {
|
||||
@@ -348,7 +398,8 @@ export function createSessionInbox(options: { archived?: boolean } = {}) {
|
||||
open,
|
||||
loadBranches,
|
||||
branchLoading: (entry: InboxEntry) =>
|
||||
!vcs.settled[locationKey(entry)] && !entry.ctx.data.location.vcs.info(entry.session.location),
|
||||
!entry.ctx.data.location.vcs.info(entry.session.location) &&
|
||||
selectBranchLoading(branchState(), locationKey(entry)),
|
||||
branch: (entry: InboxEntry) =>
|
||||
entry.ctx.data.location.vcs.info(entry.session.location)?.branch.current ?? undefined,
|
||||
inWorktree: inboxInWorktree,
|
||||
|
||||
Reference in New Issue
Block a user