fix(app): make settings account holds, worktree delete check, extension lists and picker cache explicit machines (#62103)

This commit is contained in:
Luke Parker
2026-11-05 09:54:53 -06:00
committed by GitHub
Unverified
parent 3a58140e92
commit 47cace689a
19 changed files with 1859 additions and 379 deletions
@@ -710,6 +710,42 @@ test("a project whose folder is gone opens its settings with a notice", async ({
await expect(notice).toContainText(directory)
})
test("a project plugin list that fails to load offers Retry instead of an empty list", async ({ page }) => {
const { settings } = await open(page)
await openProject(page)
const lists = { failing: true }
// Only the project's list carries a location; the server-wide list still loads.
await page.route(/\/api\/plugin\?.*location/, (route) =>
route.fulfill(
lists.failing
? {
status: 500,
json: { name: "UnknownError", data: { message: "config is invalid" } },
headers: { "access-control-allow-origin": "*" },
}
: {
json: {
location: { directory },
data: [{ id: "project-plugin", source: { type: "package", target: "project-plugin" } }],
},
headers: { "access-control-allow-origin": "*" },
},
),
)
await settings.getByRole("tab", { name: "Extensions", exact: true }).click()
await settings.getByRole("tab", { name: "Plugins", exact: true }).click()
const panel = settings.getByRole("tabpanel", { name: "Plugins", exact: true })
await expect(panel.getByRole("status")).toContainText("Could not load plugins")
await expect(panel.getByText("No plugins yet", { exact: true })).toHaveCount(0)
lists.failing = false
await panel.getByRole("button", { name: "Try again", exact: true }).click()
await expect(panel.getByText("project-plugin", { exact: true })).toBeVisible()
await expect(panel.getByRole("status")).toHaveCount(0)
})
for (const field of [
{
name: "color",
@@ -1229,6 +1265,52 @@ test("a failed worktree delete restores its row, and the next confirmation still
expect(removals.requests).toBe(2)
})
test("a failed worktree check offers Retry, and the passing retry enables Delete", async ({ page }) => {
const inventory: WorktreeDirectory[] = [
{ directory },
...sandboxes.map((item) => ({ directory: item, strategy: "git" })),
]
const { settings } = await open(page, {
worktrees: () => inventory,
onWorktreeRemove: (body) => {
inventory.splice(
inventory.findIndex((item) => item.directory === body.directory),
1,
)
},
})
const checks = { failing: true }
await page.route(/\/api\/vcs\/status(\?|$)/, (route) =>
checks.failing
? route.fulfill({
status: 500,
json: { name: "UnknownError", data: { message: "git is busy" } },
headers: { "access-control-allow-origin": "*" },
})
: route.fallback(),
)
await settings.getByRole("tab", { name: "Worktrees", exact: true }).click()
await expect(settings.getByText("12 worktrees", { exact: true })).toBeVisible()
await settings.getByRole("button", { name: "Delete “workspace-1”?", exact: true }).click()
const dialog = page.getByRole("dialog", { name: "Delete “workspace-1”?", exact: true })
const remove = dialog.getByRole("button", { name: "Delete worktree", exact: true })
const retry = dialog.getByRole("button", { name: "Try again", exact: true })
await expect(dialog.getByText("Unable to verify git status.", { exact: true })).toBeVisible()
await expect(remove).toBeDisabled()
checks.failing = false
await retry.click()
await expect(remove).toBeEnabled()
await expect(retry).toHaveCount(0)
await expect(dialog.getByText("Unable to verify git status.", { exact: true })).toHaveCount(0)
await remove.click()
await expect(settings.getByText("11 worktrees", { exact: true })).toBeVisible()
})
test.describe("worktrees prefetch", () => {
const other = project({ id: "proj_other", directory: "/repo/other", name: "Other project" })
+1
View File
@@ -944,6 +944,7 @@ export const dict = {
"settings.extensions.availableAll": "Available to all projects",
"settings.extensions.manageConfig": "Manage in opencode.json",
"settings.extensions.addSkills": "How to add skills",
"settings.extensions.plugins.loadFailed": "Could not load plugins",
"project.settings.title": "Edit project",
"project.settings.autoAccept.description": "Approve this project's permission requests without asking",
"project.settings.autoAccept.default.on": "Use default (On)",
+6 -2
View File
@@ -1,8 +1,12 @@
import type { SessionApi, SessionInfo, SessionListInput } from "@opencode/client/promise"
export async function listAllSessions(api: Pick<SessionApi, "list">, input: Omit<SessionListInput, "cursor">) {
export async function listAllSessions(
api: Pick<SessionApi, "list">,
input: Omit<SessionListInput, "cursor">,
options?: Parameters<SessionApi["list"]>[1],
) {
const load = async (cursor?: string): Promise<SessionInfo[]> => {
const result = await api.list({ ...input, limit: input.limit ?? 100, cursor })
const result = await api.list({ ...input, limit: input.limit ?? 100, cursor }, options)
const sessions = result.data
if (result.data.length === 0 || !result.cursor.next) return sessions
@@ -0,0 +1,117 @@
import { expect, test } from "bun:test"
import {
createExtensionLoadState,
EXTENSION_LOAD_TIMEOUT_MS,
extensionLoadView,
transitionExtensionLoad,
type ExtensionLoadEffect,
type ExtensionLoadEvent,
type ExtensionLoadState,
} from "./extension-load-machine"
type State = ExtensionLoadState<string[], string>
type Event = ExtensionLoadEvent<string[], string>
function replay(events: Event[], state: State = createExtensionLoadState()) {
return events.reduce<{ state: State; effects: ExtensionLoadEffect<string>[] }>(
(current, event) => {
const result = transitionExtensionLoad(current.state, event)
return { state: result.state, effects: [...current.effects, ...result.effects] }
},
{ state, effects: [] },
)
}
const run = (attempt: number, key: string): ExtensionLoadEffect<string> => ({
type: "run",
attempt,
key,
timeoutMs: EXTENSION_LOAD_TIMEOUT_MS,
})
test("a failed list shows an error with Retry instead of an empty list", () => {
const failed = replay([
{ type: "target.synced", key: "/a" },
{ type: "load.failed", attempt: 1 },
])
expect(extensionLoadView(failed.state, "/a")).toEqual({ status: "error" })
const timedOut = replay([
{ type: "target.synced", key: "/a" },
{ type: "load.timed-out", attempt: 1 },
])
expect(extensionLoadView(timedOut.state, "/a")).toEqual({ status: "error" })
})
test("switching projects drops the previous project's list at once and ignores its late result", () => {
const ready = replay([
{ type: "target.synced", key: "/a" },
{ type: "load.succeeded", attempt: 1, value: ["plugin-a"] },
]).state
// The page renders the next project before the driver syncs its key.
expect(extensionLoadView(ready, "/b")).toEqual({ status: "loading" })
const switched = replay([{ type: "target.synced", key: "/b" }], ready)
expect(switched.effects).toEqual([run(2, "/b")])
expect(extensionLoadView(switched.state, "/b")).toEqual({ status: "loading" })
const again = replay([{ type: "target.synced", key: "/a" }], switched.state)
expect(again.effects).toEqual([{ type: "abort", attempt: 2 }, run(3, "/a")])
expect(transitionExtensionLoad(again.state, { type: "load.succeeded", attempt: 2, value: ["plugin-b"] }).state).toBe(
again.state,
)
})
test("Retry reads once and shows loading while it runs", () => {
const failed = replay([
{ type: "target.synced", key: "/a" },
{ type: "load.failed", attempt: 1 },
]).state
const retried = replay([{ type: "retry.requested" }], failed)
expect(retried.effects).toEqual([run(2, "/a")])
expect(extensionLoadView(retried.state, "/a")).toEqual({ status: "loading" })
expect(transitionExtensionLoad(retried.state, { type: "retry.requested" }).state).toBe(retried.state)
const done = transitionExtensionLoad(retried.state, { type: "load.succeeded", attempt: 2, value: [] })
expect(done.effects).toEqual([{ type: "abort", attempt: 2 }])
expect(extensionLoadView(done.state, "/a")).toEqual({ status: "ready", value: [] })
})
test("a change during a read reads once more, and a failed refresh keeps the list", () => {
const queued = replay([
{ type: "target.synced", key: "/a" },
{ type: "invalidated" },
{ type: "invalidated" },
{ type: "load.succeeded", attempt: 1, value: ["old"] },
])
expect(queued.effects).toEqual([run(1, "/a"), { type: "abort", attempt: 1 }, run(2, "/a")])
expect(extensionLoadView(queued.state, "/a")).toEqual({ status: "ready", value: ["old"] })
const kept = transitionExtensionLoad(queued.state, { type: "load.timed-out", attempt: 2 }).state
expect(extensionLoadView(kept, "/a")).toEqual({ status: "ready", value: ["old"] })
// A reconnect reads a failed list again without Retry.
const failed = replay([
{ type: "target.synced", key: "/a" },
{ type: "load.failed", attempt: 1 },
{ type: "invalidated" },
])
expect(failed.effects.at(-1)).toEqual(run(2, "/a"))
})
test("closing the page aborts the running read and ignores its result", () => {
const disposed = replay([{ type: "target.synced", key: "/a" }, { type: "disposed" }])
expect(disposed.effects).toEqual([run(1, "/a"), { type: "abort", attempt: 1 }])
expect(transitionExtensionLoad(disposed.state, { type: "load.succeeded", attempt: 1, value: [] }).state).toBe(
disposed.state,
)
})
@@ -0,0 +1,158 @@
/** How long one list read may run before the section offers Retry. */
export const EXTENSION_LOAD_TIMEOUT_MS = 15_000
/**
* One keyed read for a Settings › Extensions list: the server's plugins, a project's plugins, or a project's language
* server config. `key` is what the list belongs to (a server or a project folder); a new key drops the previous key's
* value and aborts its read. `queued` marks a change (a config or plugin event, a reconnect) that arrived during a
* read, so one more read follows it. A failed refresh keeps the value it already shows.
*/
export type ExtensionLoadState<T, K> =
| { readonly status: "idle"; readonly issued: number }
| {
readonly status: "loading"
readonly issued: number
readonly attempt: number
readonly key: K
readonly queued: boolean
}
| { readonly status: "ready"; readonly issued: number; readonly key: K; readonly value: T }
| {
readonly status: "refreshing"
readonly issued: number
readonly attempt: number
readonly key: K
readonly value: T
readonly queued: boolean
}
| { readonly status: "error"; readonly issued: number; readonly key: K }
| { readonly status: "disposed" }
export type ExtensionLoadEvent<T, K> =
| { readonly type: "target.synced"; readonly key: K }
/** A config or plugin event for this list, or the event stream reconnected. */
| { readonly type: "invalidated" }
| { readonly type: "retry.requested" }
| { readonly type: "load.succeeded"; readonly attempt: number; readonly value: T }
| { readonly type: "load.failed"; readonly attempt: number }
| { readonly type: "load.timed-out"; readonly attempt: number }
| { readonly type: "disposed" }
export type ExtensionLoadEffect<K> =
| { readonly type: "run"; readonly attempt: number; readonly key: K; readonly timeoutMs: number }
| { readonly type: "abort"; readonly attempt: number }
export type ExtensionLoadTransition<T, K> = {
readonly state: ExtensionLoadState<T, K>
readonly effects: readonly ExtensionLoadEffect<K>[]
}
export function createExtensionLoadState<T, K>(): ExtensionLoadState<T, K> {
return { status: "idle", issued: 0 }
}
export function transitionExtensionLoad<T, K>(
state: ExtensionLoadState<T, K>,
event: ExtensionLoadEvent<T, K>,
): ExtensionLoadTransition<T, K> {
if (state.status === "disposed") return { state, effects: [] }
if (event.type === "disposed")
return {
state: { status: "disposed" },
effects: state.status === "loading" || state.status === "refreshing" ? [abort(state.attempt)] : [],
}
if (event.type === "target.synced") {
if (state.status !== "idle" && Object.is(state.key, event.key)) return { state, effects: [] }
const next = load<T, K>(state.issued, event.key)
if (state.status === "loading" || state.status === "refreshing")
return { state: next.state, effects: [abort(state.attempt), ...next.effects] }
return next
}
if (state.status === "idle") return { state, effects: [] }
if (event.type === "invalidated") {
if (state.status === "ready") return refresh(state.issued, state.key, state.value)
if (state.status === "error") return load<T, K>(state.issued, state.key)
if (state.queued) return { state, effects: [] }
return { state: { ...state, queued: true }, effects: [] }
}
if (event.type === "retry.requested") {
if (state.status !== "error") return { state, effects: [] }
return load<T, K>(state.issued, state.key)
}
if ((state.status !== "loading" && state.status !== "refreshing") || state.attempt !== event.attempt)
return { state, effects: [] }
const settle = abort(state.attempt)
if (event.type === "load.succeeded") {
const next = state.queued
? refresh(state.issued, state.key, event.value)
: { state: { status: "ready", issued: state.issued, key: state.key, value: event.value } as const, effects: [] }
return { state: next.state, effects: [settle, ...next.effects] }
}
if (state.queued) {
const next =
state.status === "refreshing"
? refresh(state.issued, state.key, state.value)
: load<T, K>(state.issued, state.key)
return { state: next.state, effects: [settle, ...next.effects] }
}
return {
state:
state.status === "refreshing"
? { status: "ready", issued: state.issued, key: state.key, value: state.value }
: { status: "error", issued: state.issued, key: state.key },
effects: [settle],
}
}
/** What a list shows for `key`, the key it renders now; a state for another key reads as loading. */
export function extensionLoadView<T, K>(
state: ExtensionLoadState<T, K>,
key: K,
): { readonly status: "loading" } | { readonly status: "ready"; readonly value: T } | { readonly status: "error" } {
if (state.status === "idle" || state.status === "disposed" || !Object.is(state.key, key)) return { status: "loading" }
if (state.status === "ready" || state.status === "refreshing") return { status: "ready", value: state.value }
if (state.status === "error") return { status: "error" }
return { status: "loading" }
}
function load<T, K>(issued: number, key: K): ExtensionLoadTransition<T, K> {
const attempt = issued + 1
return {
state: { status: "loading", issued: attempt, attempt, key, queued: false },
effects: [{ type: "run", attempt, key, timeoutMs: EXTENSION_LOAD_TIMEOUT_MS }],
}
}
function refresh<T, K>(issued: number, key: K, value: T): ExtensionLoadTransition<T, K> {
const attempt = issued + 1
return {
state: { status: "refreshing", issued: attempt, attempt, key, value, queued: false },
effects: [{ type: "run", attempt, key, timeoutMs: EXTENSION_LOAD_TIMEOUT_MS }],
}
}
function abort(attempt: number): ExtensionLoadEffect<never> {
return { type: "abort", attempt }
}
@@ -0,0 +1,85 @@
import { Button } from "@opencode/ui/button"
import { createEffect, createMemo, createSignal, on, onCleanup, untrack } from "solid-js"
import { useServerSDK } from "@/runtime/server/client"
import {
createExtensionLoadState,
extensionLoadView,
transitionExtensionLoad,
type ExtensionLoadEffect,
type ExtensionLoadEvent,
} from "./extension-load-machine"
import "./workspaces/project.css"
/**
* Reads one Settings › Extensions list for the current `key`. The read does not wait for the event stream, so a
* server that answers HTTP while its stream reconnects still lists; the stream's reconnect reads the list again.
*/
export function createExtensionLoad<T, K>(input: { key: () => K; task: (key: K, signal: AbortSignal) => Promise<T> }) {
const server = useServerSDK()
const [loadState, setLoadState] = createSignal(createExtensionLoadState<T, K>())
const runs = new Map<number, { controller: AbortController; timer: ReturnType<typeof setTimeout> }>()
const dispatch = (event: ExtensionLoadEvent<T, K>) => {
const previous = untrack(loadState)
const result = transitionExtensionLoad(previous, event)
if (result.state !== previous) setLoadState(() => result.state)
result.effects.forEach(run)
}
const run = (effect: ExtensionLoadEffect<K>) => {
if (effect.type === "abort") {
const current = runs.get(effect.attempt)
runs.delete(effect.attempt)
clearTimeout(current?.timer)
current?.controller.abort()
return
}
const attempt = effect.attempt
const controller = new AbortController()
runs.set(attempt, {
controller,
timer: setTimeout(() => dispatch({ type: "load.timed-out", attempt }), effect.timeoutMs),
})
void Promise.try(() => input.task(effect.key, controller.signal)).then(
(value) => dispatch({ type: "load.succeeded", attempt, value }),
() => dispatch({ type: "load.failed", attempt }),
)
}
createEffect(() => {
const key = input.key()
untrack(() => dispatch({ type: "target.synced", key }))
})
createEffect(
on(
() => server.connection.status() === "connected",
(connected, previous) => {
if (connected && previous === false) dispatch({ type: "invalidated" })
},
),
)
onCleanup(() => dispatch({ type: "disposed" }))
return {
view: createMemo(() => extensionLoadView(loadState(), input.key())),
retry: () => dispatch({ type: "retry.requested" }),
invalidate: () => dispatch({ type: "invalidated" }),
}
}
/** A list that failed to load, with Retry. */
export function ExtensionLoadFailed(props: { message: string; retry: string; onRetry: () => void }) {
return (
<div class="project-settings-extension-section-copy" role="status">
<span class="project-settings-extension-empty-description">{props.message}</span>
<Button variant="ghost-muted" onClick={() => props.onRetry()}>
{props.retry}
</Button>
</div>
)
}
@@ -1,5 +1,5 @@
import type { McpServer } from "@opencode/client/promise"
import { Component, For, Show, createEffect, createMemo, createResource, type JSX } from "solid-js"
import { Component, For, Show, createEffect, createMemo, onCleanup, type JSX } from "solid-js"
import { useDialog } from "@opencode/ui/context/dialog"
import { Icon } from "@opencode/ui/icon"
import { Button } from "@opencode/ui/button"
@@ -17,6 +17,7 @@ import { ExtensionPlugins } from "@/runtime/plugin/extension-plugins"
import { ExternalLink } from "@/runtime/platform/external-link"
import { usePlatform } from "@/runtime/platform/platform"
import { SettingsList } from "@/settings/list"
import { createExtensionLoad, ExtensionLoadFailed } from "@/settings/extension-load"
import type { SettingsView } from "@/settings/surface"
import "@/settings/settings.css"
import "@/shell/search-list.css"
@@ -63,16 +64,23 @@ export const SettingsExtensions: Component<{
const toggle = (item: McpServer, enabled: boolean) =>
mcp.dispatch({ type: "toggle.requested", name: item.name, enabled, status: item.status.status })
const [pluginList] = createResource(
() => serverSdk.connection.status() === "connected",
() =>
serverSdk.api.plugin
.list()
.then((result) => result.data)
.catch(() => []),
{ initialValue: [] },
const plugins = createExtensionLoad({
key: () => serverSdk.scope,
task: (_, signal) => serverSdk.api.plugin.list(undefined, { signal }).then((result) => result.data),
})
onCleanup(
serverSdk.event.on("plugin.updated", (event) => {
if (!event.location) plugins.invalidate()
}),
)
const pluginList = createMemo(() => {
const current = plugins.view()
return current.status === "ready" ? current.value : undefined
})
// The desktop window runs the GUIs of its own server's plugins, so only that server's rows control them.
const own = () => !!platform.plugins && ServerConnection.builtin(serverSdk.server)
@@ -196,7 +204,20 @@ export const SettingsExtensions: Component<{
{language.t("settings.extensions.manageConfig")}
</span>
</div>
<ExtensionPlugins plugins={pluginList.latest ?? []} own={own()} />
{/* The desktop's own server also lists the plugins main runs, so its rows stay while the list loads. */}
<Show when={own() || pluginList()}>
<ExtensionPlugins plugins={pluginList() ?? []} own={own()} />
</Show>
<Show when={plugins.view().status === "loading" && !own()}>
<p class="project-settings-extension-empty-description">{language.t("common.loading")}</p>
</Show>
<Show when={plugins.view().status === "error"}>
<ExtensionLoadFailed
message={language.t("settings.extensions.plugins.loadFailed")}
retry={language.t("common.retry")}
onRetry={plugins.retry}
/>
</Show>
</div>
</Tabs.Content>
@@ -1,42 +1,74 @@
import { expect, test } from "bun:test"
import type { ProviderAccount } from "./accounts"
import {
availableProviders,
connectedProviders,
createProviderDisconnectState,
createSettingsProvidersState,
providerAccountView,
providerRow,
transitionProviderDisconnect,
type ProviderDisconnectEffect,
type ProviderDisconnectEvent,
type ProviderDisconnectState,
transitionSettingsProviders,
type SettingsProvidersEffect,
type SettingsProvidersEvent,
type SettingsProvidersState,
} from "./machine"
type Item = { readonly id: string }
const openai = { id: "openai" }
const opencode = { id: "opencode" }
const consoleGoogle = { id: "console-google" }
const disconnectOpenAI: ProviderDisconnectEvent = {
const disconnectOpenAI: SettingsProvidersEvent<Item> = {
type: "disconnect.requested",
providerIDs: ["openai"],
integrationID: "openai",
providerName: "OpenAI",
}
const disconnectConsole: ProviderDisconnectEvent = {
const disconnectConsole: SettingsProvidersEvent<Item> = {
type: "disconnect.requested",
providerIDs: ["opencode", "console-google"],
integrationID: "opencode",
providerName: "OpenCode",
}
function replay(events: ProviderDisconnectEvent[]) {
return events.reduce<{ state: ProviderDisconnectState; effects: ProviderDisconnectEffect[] }>(
const work: ProviderAccount = { type: "credential", id: "cred_work", label: "Work", method: "oauth" }
const personal: ProviderAccount = { type: "credential", id: "cred_personal", label: "Personal", method: "oauth" }
// The Console list before a switch, and the transient catalog in which the workspace providers dropped.
const before = [opencode, consoleGoogle, openai]
const transient = [openai]
const activate = (catalog: readonly Item[], account = personal): SettingsProvidersEvent<Item> => ({
type: "account.activate.requested",
integrationID: "opencode",
providerName: "OpenCode",
account,
activeCredentialID: work.id,
catalog,
})
const remove = (catalog: readonly Item[]): SettingsProvidersEvent<Item> => ({
type: "account.remove.requested",
integrationID: "opencode",
providerName: "OpenCode",
account: work,
final: false,
catalog,
})
function replay(events: SettingsProvidersEvent<Item>[], state = createSettingsProvidersState<Item>()) {
return events.reduce<{ state: SettingsProvidersState<Item>; effects: SettingsProvidersEffect[] }>(
(current, event) => {
const result = transitionProviderDisconnect(current.state, event)
const result = transitionSettingsProviders(current.state, event)
return { state: result.state, effects: [...current.effects, ...result.effects] }
},
{ state: createProviderDisconnectState(), effects: [] },
{ state, effects: [] },
)
}
@@ -81,7 +113,7 @@ test("a removed provider stays hidden until the catalog drops it, then shows aga
expect(connectedProviders(removed.state, [openai])).toEqual([])
expect(removed.effects.at(-1)).toEqual({ type: "toast.disconnected", providerName: "OpenAI" })
const dropped = transitionProviderDisconnect(removed.state, { type: "catalog.synced", providerIDs: [] }).state
const dropped = transitionSettingsProviders(removed.state, { type: "catalog.synced", providerIDs: [] }).state
expect(connectedProviders(dropped, [openai])).toEqual([openai])
})
@@ -100,12 +132,12 @@ test("a removal confirmed after the catalog already dropped the provider leaves
test("a result for a disconnect that a reconnect superseded is ignored", () => {
const reconnected = replay([disconnectOpenAI, { type: "provider.reconnected", providerID: "openai" }]).state
expect(transitionProviderDisconnect(reconnected, { type: "disconnect.succeeded", attempt: 1 })).toEqual({
expect(transitionSettingsProviders(reconnected, { type: "disconnect.succeeded", attempt: 1 })).toEqual({
state: reconnected,
effects: [],
})
expect(
transitionProviderDisconnect(reconnected, {
transitionSettingsProviders(reconnected, {
type: "disconnect.failed",
attempt: 1,
reason: { kind: "no-credentials" },
@@ -128,5 +160,111 @@ test("reconnecting the Console clears its providers only", () => {
test("a second disconnect while one is running starts no request", () => {
const removing = replay([disconnectOpenAI]).state
expect(transitionProviderDisconnect(removing, disconnectOpenAI)).toEqual({ state: removing, effects: [] })
expect(transitionSettingsProviders(removing, disconnectOpenAI)).toEqual({ state: removing, effects: [] })
})
test("the dialog's late catalog refresh does not unfreeze the list while an account switch runs", () => {
const switching = replay([
{ type: "dialog.opened", catalog: before },
{ type: "dialog.closed", attempt: 1 },
activate(transient),
{ type: "dialog.refresh.settled", attempt: 1 },
])
expect(switching.effects).toEqual([
{ type: "dialog.open", attempt: 1, provider: undefined },
{ type: "catalog.refresh", attempt: 1 },
{
type: "account.activate.run",
attempt: 2,
integrationID: "opencode",
providerName: "OpenCode",
account: personal,
},
])
expect(availableProviders(switching.state, transient)).toEqual(before)
expect(providerAccountView(switching.state).busy).toBe(true)
const settled = transitionSettingsProviders(switching.state, { type: "account.settled", attempt: 2 }).state
expect(availableProviders(settled, transient)).toEqual(transient)
expect(providerAccountView(settled).busy).toBe(false)
})
test("a finished account action does not unfreeze the list behind an open connect dialog", () => {
const open = replay([activate(before), { type: "dialog.opened", provider: "anthropic", catalog: transient }])
expect(open.effects.at(-1)).toEqual({ type: "dialog.open", attempt: 2, provider: "anthropic" })
const settled = replay([{ type: "account.settled", attempt: 1 }], open.state)
expect(availableProviders(settled.state, transient)).toEqual(before)
expect(providerAccountView(settled.state).busy).toBe(false)
const closed = replay(
[
{ type: "dialog.closed", attempt: 2 },
{ type: "dialog.refresh.settled", attempt: 2 },
],
settled.state,
)
expect(closed.state.status).toBe("live")
expect(availableProviders(closed.state, transient)).toEqual(transient)
})
test("a closed dialog's refresh does not release a dialog opened after it", () => {
const second = replay([
{ type: "dialog.opened", catalog: before },
{ type: "dialog.closed", attempt: 1 },
{ type: "dialog.opened", catalog: transient },
]).state
expect(transitionSettingsProviders(second, { type: "dialog.refresh.settled", attempt: 1 }).state).toBe(second)
expect(transitionSettingsProviders(second, { type: "dialog.closed", attempt: 1 }).state).toBe(second)
expect(availableProviders(second, transient)).toEqual(before)
})
test("an account action closes a rename and blocks renames and other account actions until it settles", () => {
const renaming = replay([{ type: "account.rename.started", credentialID: work.id }]).state
expect(providerAccountView(renaming)).toEqual({ busy: false, renaming: work.id })
const busy = transitionSettingsProviders(renaming, activate(before)).state
expect(providerAccountView(busy)).toEqual({ busy: true, renaming: undefined })
for (const event of [
{ type: "account.rename.started", credentialID: work.id },
activate(before),
remove(before),
{ type: "account.settled", attempt: 99 },
] satisfies SettingsProvidersEvent<Item>[])
expect(transitionSettingsProviders(busy, event)).toEqual({ state: busy, effects: [] })
const done = transitionSettingsProviders(busy, { type: "account.settled", attempt: 1 }).state
expect(done).toEqual({ status: "live", rows: {}, nextAttempt: 2, renaming: undefined })
expect(transitionSettingsProviders(done, remove(before)).effects).toEqual([
{
type: "account.remove.run",
attempt: 2,
integrationID: "opencode",
providerName: "OpenCode",
account: work,
final: false,
},
])
})
test("switching to the account that is already active starts nothing", () => {
const live = createSettingsProvidersState<Item>()
expect(transitionSettingsProviders(live, activate(before, work))).toEqual({ state: live, effects: [] })
})
test("a disconnect toast still reports while the list is held", () => {
const result = replay([
{ type: "dialog.opened", catalog: before },
disconnectOpenAI,
{ type: "disconnect.succeeded", attempt: 2 },
])
expect(result.state.status).toBe("holding")
expect(result.effects.at(-1)).toEqual({ type: "toast.disconnected", providerName: "OpenAI" })
})
+222 -30
View File
@@ -1,3 +1,5 @@
import type { ProviderAccount } from "./accounts"
export type DisconnectFailure =
| { readonly kind: "no-credentials" }
| { readonly kind: "request"; readonly error: unknown }
@@ -15,13 +17,75 @@ export type ProviderRowState =
// The server confirmed the removal but its catalog still lists the provider.
| { readonly status: "removed"; readonly integrationID: string }
export type ProviderDisconnectState = {
/** Holds only rows that are not "connected"; a missing ID is a connected row. */
readonly rows: Readonly<Record<string, Exclude<ProviderRowState, { status: "connected" }>>>
/** Holds only rows that are not "connected"; a missing ID is a connected row. */
export type ProviderRows = Readonly<Record<string, Exclude<ProviderRowState, { status: "connected" }>>>
/** The connect dialog is open, or closed and refreshing the catalog it may have changed. */
export type ProviderDialogHold = {
readonly phase: "open" | "refreshing"
readonly attempt: number
}
/** An account switch or removal that waits for the server and, for the Console, for the new workspace catalog. */
export type ProviderAccountBusy = {
readonly phase: "activating" | "removing"
readonly attempt: number
readonly credentialID: string
}
type ProvidersBase = {
readonly rows: ProviderRows
readonly nextAttempt: number
}
export type ProviderDisconnectEvent =
/**
* Settings › Providers.
* - `live`: the list follows the catalog; an inline account rename may be open.
* - `holding`: the connect dialog or an account action is running, so the Connected list stays on `held`, the list
* as it was when the first of them started. It goes live again only when both have finished.
* An account action closes any rename and disables every account menu until it settles.
*/
export type SettingsProvidersState<T = unknown> =
| (ProvidersBase & { readonly status: "live"; readonly account?: undefined; readonly renaming?: string })
| (ProvidersBase & {
readonly status: "holding"
readonly held: readonly T[]
readonly dialog: ProviderDialogHold
readonly account?: undefined
readonly renaming?: string
})
| (ProvidersBase & {
readonly status: "holding"
readonly held: readonly T[]
readonly dialog?: ProviderDialogHold
readonly account: ProviderAccountBusy
readonly renaming?: undefined
})
export type SettingsProvidersEvent<T = unknown> =
/** `catalog` is the live Connected list, which the list holds if nothing holds it yet. */
| { readonly type: "dialog.opened"; readonly provider?: string; readonly catalog: readonly T[] }
| { readonly type: "dialog.closed"; readonly attempt: number }
| { readonly type: "dialog.refresh.settled"; readonly attempt: number }
| { readonly type: "account.rename.started"; readonly credentialID: string }
| { readonly type: "account.rename.closed" }
| {
readonly type: "account.activate.requested"
readonly integrationID: string
readonly providerName: string
readonly account: ProviderAccount
readonly activeCredentialID: string | undefined
readonly catalog: readonly T[]
}
| {
readonly type: "account.remove.requested"
readonly integrationID: string
readonly providerName: string
readonly account: ProviderAccount
readonly final: boolean
readonly catalog: readonly T[]
}
| { readonly type: "account.settled"; readonly attempt: number }
| {
readonly type: "disconnect.requested"
/** The clicked provider, plus its Console workspace providers when it is the Console root. */
@@ -34,26 +98,130 @@ export type ProviderDisconnectEvent =
| { readonly type: "provider.reconnected"; readonly providerID: string }
| { readonly type: "catalog.synced"; readonly providerIDs: readonly string[] }
export type ProviderDisconnectEffect =
export type SettingsProvidersEffect =
| { readonly type: "dialog.open"; readonly attempt: number; readonly provider?: string }
| { readonly type: "catalog.refresh"; readonly attempt: number }
| {
readonly type: "account.activate.run"
readonly attempt: number
readonly integrationID: string
readonly providerName: string
readonly account: ProviderAccount
}
| {
readonly type: "account.remove.run"
readonly attempt: number
readonly integrationID: string
readonly providerName: string
readonly account: ProviderAccount
readonly final: boolean
}
| { readonly type: "disconnect.run"; readonly attempt: number; readonly integrationID: string }
| { readonly type: "toast.disconnected"; readonly providerName: string }
| { readonly type: "toast.failed"; readonly providerName: string; readonly reason: DisconnectFailure }
export type ProviderDisconnectTransition = {
readonly state: ProviderDisconnectState
readonly effects: readonly ProviderDisconnectEffect[]
export type SettingsProvidersTransition<T = unknown> = {
readonly state: SettingsProvidersState<T>
readonly effects: readonly SettingsProvidersEffect[]
}
const CONNECTED: ProviderRowState = { status: "connected" }
export function createProviderDisconnectState(): ProviderDisconnectState {
return { rows: {}, nextAttempt: 1 }
export function createSettingsProvidersState<T>(): SettingsProvidersState<T> {
return { status: "live", rows: {}, nextAttempt: 1 }
}
export function transitionProviderDisconnect(
state: ProviderDisconnectState,
event: ProviderDisconnectEvent,
): ProviderDisconnectTransition {
export function transitionSettingsProviders<T>(
state: SettingsProvidersState<T>,
event: SettingsProvidersEvent<T>,
): SettingsProvidersTransition<T> {
if (event.type === "dialog.opened") {
const attempt = state.nextAttempt
return {
state: hold(
{ ...state, nextAttempt: attempt + 1 },
state.status === "holding" ? state.held : event.catalog,
{ phase: "open", attempt },
state.account,
state.renaming,
),
effects: [{ type: "dialog.open", attempt, provider: event.provider }],
}
}
if (event.type === "dialog.closed") {
if (state.status !== "holding" || state.dialog?.phase !== "open" || state.dialog.attempt !== event.attempt)
return { state, effects: [] }
return {
state: hold(state, state.held, { phase: "refreshing", attempt: event.attempt }, state.account, state.renaming),
effects: [{ type: "catalog.refresh", attempt: event.attempt }],
}
}
if (event.type === "dialog.refresh.settled") {
if (state.status !== "holding" || state.dialog?.phase !== "refreshing" || state.dialog.attempt !== event.attempt)
return { state, effects: [] }
return { state: hold(state, state.held, undefined, state.account, state.renaming), effects: [] }
}
if (event.type === "account.rename.started") {
if (state.account || state.renaming === event.credentialID) return { state, effects: [] }
return { state: { ...state, renaming: event.credentialID }, effects: [] }
}
if (event.type === "account.rename.closed") {
if (state.account || state.renaming === undefined) return { state, effects: [] }
return { state: { ...state, renaming: undefined }, effects: [] }
}
if (event.type === "account.activate.requested" || event.type === "account.remove.requested") {
if (state.account) return { state, effects: [] }
if (event.type === "account.activate.requested" && event.account.id === event.activeCredentialID)
return { state, effects: [] }
const attempt = state.nextAttempt
const phase = event.type === "account.activate.requested" ? "activating" : "removing"
return {
state: hold(
{ ...state, nextAttempt: attempt + 1 },
state.status === "holding" ? state.held : event.catalog,
state.status === "holding" ? state.dialog : undefined,
{ phase, attempt, credentialID: event.account.id },
undefined,
),
effects: [
event.type === "account.activate.requested"
? {
type: "account.activate.run",
attempt,
integrationID: event.integrationID,
providerName: event.providerName,
account: event.account,
}
: {
type: "account.remove.run",
attempt,
integrationID: event.integrationID,
providerName: event.providerName,
account: event.account,
final: event.final,
},
],
}
}
if (event.type === "account.settled") {
if (state.account?.attempt !== event.attempt || state.status !== "holding") return { state, effects: [] }
return { state: hold(state, state.held, state.dialog, undefined, undefined), effects: [] }
}
if (event.type === "disconnect.requested") return requested(state, event)
if (event.type === "disconnect.succeeded") return settled(state, event.attempt, undefined)
@@ -80,27 +248,51 @@ export function transitionProviderDisconnect(
}
}
export function providerRow(state: ProviderDisconnectState, providerID: string): ProviderRowState {
/** The Connected list to show: the held one while the dialog or an account action runs, otherwise the live one. */
export function availableProviders<T>(state: SettingsProvidersState<T>, live: readonly T[]) {
return state.status === "holding" ? state.held : live
}
export function providerAccountView(state: SettingsProvidersState) {
return { busy: state.account !== undefined, renaming: state.renaming }
}
export function providerRow(state: ProvidersBase, providerID: string): ProviderRowState {
return state.rows[providerID] ?? CONNECTED
}
/** A row leaves the Connected list while its removal runs and after the server confirms it, and returns on failure. */
export function connectedProviders<T extends { readonly id: string }>(
state: ProviderDisconnectState,
available: readonly T[],
) {
export function connectedProviders<T extends { readonly id: string }>(state: ProvidersBase, available: readonly T[]) {
return available.filter((item) => providerRow(state, item.id).status === "connected")
}
function requested(
state: ProviderDisconnectState,
event: Extract<ProviderDisconnectEvent, { type: "disconnect.requested" }>,
): ProviderDisconnectTransition {
function hold<T>(
base: ProvidersBase,
held: readonly T[],
dialog: ProviderDialogHold | undefined,
account: ProviderAccountBusy | undefined,
renaming: string | undefined,
): SettingsProvidersState<T> {
const rows = base.rows
const nextAttempt = base.nextAttempt
if (account) return { status: "holding", rows, nextAttempt, held, dialog, account }
if (dialog) return { status: "holding", rows, nextAttempt, held, dialog, renaming }
return { status: "live", rows, nextAttempt, renaming }
}
function requested<T>(
state: SettingsProvidersState<T>,
event: Extract<SettingsProvidersEvent<T>, { type: "disconnect.requested" }>,
): SettingsProvidersTransition<T> {
if (event.providerIDs.some((id) => providerRow(state, id).status !== "connected")) return { state, effects: [] }
const attempt = state.nextAttempt
return {
state: {
...state,
rows: {
...state.rows,
...Object.fromEntries(
@@ -122,11 +314,11 @@ function requested(
}
}
function settled(
state: ProviderDisconnectState,
function settled<T>(
state: SettingsProvidersState<T>,
attempt: number,
failure: DisconnectFailure | undefined,
): ProviderDisconnectTransition {
): SettingsProvidersTransition<T> {
const current = Object.values(state.rows).find((row) => row.status === "removing" && row.attempt === attempt)
if (current?.status !== "removing") return { state, effects: [] }
@@ -148,10 +340,10 @@ function settled(
}
// Returns the same state object when no row changes, so the signal holding it does not notify.
function update(
state: ProviderDisconnectState,
next: (id: string, row: ProviderDisconnectState["rows"][string]) => ProviderRowState,
): ProviderDisconnectState {
function update<T>(
state: SettingsProvidersState<T>,
next: (id: string, row: ProviderRows[string]) => ProviderRowState,
): SettingsProvidersState<T> {
const entries = Object.entries(state.rows).map(([id, row]) => [id, row, next(id, row)] as const)
if (entries.every(([, row, result]) => row === result)) return state
+101 -76
View File
@@ -10,7 +10,6 @@ import { popularProviders, useProviders } from "@/providers/catalog/providers"
import { consoleProviderGroup } from "@/providers/catalog/console"
import { useIntegrations } from "@/providers/catalog/integrations"
import { createEffect, createMemo, createSignal, on, untrack, type Component, For, type JSX, Show } from "solid-js"
import { createStore } from "solid-js/store"
import { useLanguage } from "@/runtime/i18n/language"
import { useServerSDK } from "@/runtime/server/client"
import { formatServerError } from "@/runtime/server/errors"
@@ -22,11 +21,13 @@ import { activeProviderAccount, providerAccounts, type ProviderAccount } from ".
import { AccountNameInput } from "./account-name"
import { useProviderAccountActions } from "./account-actions"
import {
availableProviders,
connectedProviders,
createProviderDisconnectState,
transitionProviderDisconnect,
type ProviderDisconnectEffect,
type ProviderDisconnectEvent,
createSettingsProvidersState,
providerAccountView,
transitionSettingsProviders,
type SettingsProvidersEffect,
type SettingsProvidersEvent,
} from "./machine"
import "@/settings/settings.css"
@@ -59,25 +60,62 @@ export const SettingsProviders: Component<{
const providerConnect = useProviderConnectController()
const accountActions = useProviderAccountActions(() => props.directory)
const [state, setState] = createStore<{
consoleExpanded: boolean
credentialID?: string
renaming?: string
held?: ProviderItem[]
}>({
consoleExpanded: false,
})
const [consoleExpanded, setConsoleExpanded] = createSignal(false)
const [pageState, setPageState] = createSignal(createSettingsProvidersState<ProviderItem>())
const accountView = createMemo(() => providerAccountView(pageState()))
const [disconnects, setDisconnects] = createSignal(createProviderDisconnectState())
const dispatch = (event: ProviderDisconnectEvent) => {
const result = transitionProviderDisconnect(untrack(disconnects), event)
setDisconnects(result.state)
result.effects.forEach(run)
const dispatch = (event: SettingsProvidersEvent<ProviderItem>) => {
const result = transitionSettingsProviders(untrack(pageState), event)
setPageState(result.state)
result.effects.forEach(
(effect) => void Promise.try(() => run(effect)).catch((cause: unknown) => console.error(cause)),
)
}
// Results that arrive after Settings closes still report through a toast, as the user asked for the change.
const run = (effect: ProviderDisconnectEffect) => {
const run = (effect: SettingsProvidersEffect) => {
if (effect.type === "dialog.open") {
providerConnect.select(effect.provider)
void dialog.show(
() => (
<DialogConnectProvider
directory={props.directory}
defaultLocation={props.directory === undefined}
controller={providerConnect}
onConnected={(providerID) => dispatch({ type: "provider.reconnected", providerID })}
/>
),
() => dispatch({ type: "dialog.closed", attempt: effect.attempt }),
)
return
}
if (effect.type === "catalog.refresh") {
void accountActions
.refresh()
.catch(() => undefined)
.finally(() => dispatch({ type: "dialog.refresh.settled", attempt: effect.attempt }))
return
}
// The actions toast their own request failures; anything else they throw still settles the menus.
if (effect.type === "account.activate.run" || effect.type === "account.remove.run") {
const input = { integrationID: effect.integrationID, provider: effect.providerName, account: effect.account }
void Promise.try(() =>
effect.type === "account.activate.run"
? accountActions.activate(input)
: accountActions.remove({ ...input, final: effect.final }),
)
.catch((error) =>
showToast({ title: language.t("common.requestFailed"), description: formatServerError(error, language.t) }),
)
.finally(() => dispatch({ type: "account.settled", attempt: effect.attempt }))
return
}
if (effect.type === "disconnect.run") {
void serverSdk.api.integration
.get({
@@ -139,30 +177,11 @@ export const SettingsProviders: Component<{
return integrations.list().find((entry) => entry.id === id)
}
const connect = (provider?: string) => {
// The list stays as it was while the dialog connects, so a new sign-in that briefly drops the
// Console workspace providers from the catalog can't flash rows behind the dialog.
setState("held", available())
providerConnect.select(provider)
void dialog.show(
() => (
<DialogConnectProvider
directory={props.directory}
defaultLocation={props.directory === undefined}
controller={providerConnect}
onConnected={(providerID) => dispatch({ type: "provider.reconnected", providerID })}
/>
),
() =>
void accountActions
.refresh()
.catch(() => undefined)
.finally(() => setState("held", undefined)),
)
}
// The list stays as it was while the dialog connects, so a new sign-in that briefly drops the
// Console workspace providers from the catalog can't flash rows behind the dialog.
const connect = (provider?: string) => dispatch({ type: "dialog.opened", provider, catalog: untrack(available) })
const available = createMemo(() => {
if (state.held) return state.held
const liveAvailable = createMemo(() => {
const connected = providers.connected()
const managedConsole = consoleProviderGroup(connected)
@@ -182,6 +201,8 @@ export const SettingsProviders: Component<{
.toSorted((a, b) => Number(b.id === "opencode-go") - Number(a.id === "opencode-go"))
})
const available = createMemo(() => availableProviders(pageState(), liveAvailable()))
// Tells the machine which providers the server catalog lists, so a confirmed removal stops hiding a
// provider once the server drops it and shows it again if it is later reconnected.
createEffect(
@@ -191,7 +212,7 @@ export const SettingsProviders: Component<{
),
)
const connected = createMemo(() => connectedProviders(disconnects(), available()))
const connected = createMemo(() => connectedProviders(pageState(), available()))
const consoleGroup = createMemo(() => consoleProviderGroup(available()))
@@ -286,29 +307,31 @@ export const SettingsProviders: Component<{
})
}
const activate = async (provider: ProviderItem, providerName: string, account: ProviderAccount) => {
if (activeProviderAccount(integration(provider))?.id === account.id) return
setState({ credentialID: account.id, held: available() })
await accountActions.activate({ integrationID: provider.integrationID ?? provider.id, provider: providerName, account })
setState({ credentialID: undefined, held: undefined })
}
const remove = async (provider: ProviderItem, providerName: string, account: ProviderAccount) => {
setState({ credentialID: account.id, held: available() })
await accountActions.remove({
const activate = (provider: ProviderItem, providerName: string, account: ProviderAccount) =>
dispatch({
type: "account.activate.requested",
integrationID: provider.integrationID ?? provider.id,
provider: providerName,
providerName,
account,
activeCredentialID: activeProviderAccount(integration(provider))?.id,
catalog: untrack(available),
})
const remove = (provider: ProviderItem, providerName: string, account: ProviderAccount) =>
dispatch({
type: "account.remove.requested",
integrationID: provider.integrationID ?? provider.id,
providerName,
account,
final: providerAccounts(integration(provider)).length === 1,
catalog: untrack(available),
})
setState({ credentialID: undefined, held: undefined })
}
function AccountMenu(menuProps: { provider: ProviderItem; name?: string }) {
const accounts = () => providerAccounts(integration(menuProps.provider))
const active = () => activeProviderAccount(integration(menuProps.provider))
const name = () => menuProps.name ?? menuProps.provider.name
const renaming = () => accounts().find((account) => account.id === state.renaming)
const renaming = () => accounts().find((account) => account.id === accountView().renaming)
return (
<Show
@@ -322,7 +345,7 @@ export const SettingsProviders: Component<{
value={account().label}
class="settings-provider-account-input"
onSave={(label) => accountActions.rename(account(), label)}
onClose={() => setState("renaming", undefined)}
onClose={() => dispatch({ type: "account.rename.closed" })}
/>
)}
</Show>
@@ -362,12 +385,12 @@ export const SettingsProviders: Component<{
onChange={(credentialID) => {
const account = accounts().find((item) => item.id === credentialID)
if (account) void activate(menuProps.provider, name(), account)
if (account) activate(menuProps.provider, name(), account)
}}
>
<For each={accounts()}>
{(account) => (
<Menu.RadioItem value={account.id} closeOnSelect disabled={state.credentialID !== undefined}>
<Menu.RadioItem value={account.id} closeOnSelect disabled={accountView().busy}>
<span class="settings-provider-account-label">{account.label}</span>
</Menu.RadioItem>
)}
@@ -375,7 +398,7 @@ export const SettingsProviders: Component<{
</Menu.RadioGroup>
</Menu.Group>
<Menu.Separator />
<Menu.Item disabled={state.credentialID !== undefined} onSelect={() => connect(menuProps.provider.id)}>
<Menu.Item disabled={accountView().busy} onSelect={() => connect(menuProps.provider.id)}>
<Icon name="plus" size="small" class="shrink-0" />
{language.t("settings.providers.account.add")}
</Menu.Item>
@@ -388,19 +411,25 @@ export const SettingsProviders: Component<{
variant="ghost-muted"
size="large"
icon={<Icon name="outline-dots" />}
disabled={state.credentialID !== undefined || !active()}
disabled={accountView().busy || !active()}
aria-label={language.t("dialog.provider.accounts.options", { account: active()?.label ?? "" })}
/>
<Menu.Portal>
<Menu.Content onCloseAutoFocus={(event) => state.renaming && event.preventDefault()}>
<Menu.Item onSelect={() => setState("renaming", active()?.id)}>
<Menu.Content onCloseAutoFocus={(event) => accountView().renaming && event.preventDefault()}>
<Menu.Item
onSelect={() => {
const account = active()
if (account) dispatch({ type: "account.rename.started", credentialID: account.id })
}}
>
{language.t("common.rename")}
</Menu.Item>
<Menu.Item
onSelect={() => {
const account = active()
if (account) void remove(menuProps.provider, name(), account)
if (account) remove(menuProps.provider, name(), account)
}}
>
{language.t("dialog.provider.accounts.remove")}
@@ -445,9 +474,7 @@ export const SettingsProviders: Component<{
<ProviderModelIcon provider={item} class="settings-provider-icon shrink-0" />
<div class="settings-provider-main">
<span class="settings-provider-name truncate">
{item.name}
</span>
<span class="settings-provider-name truncate">{item.name}</span>
<Badge>{type(item)}</Badge>
</div>
</div>
@@ -502,8 +529,8 @@ export const SettingsProviders: Component<{
<button
type="button"
class="settings-provider-console-toggle"
aria-expanded={state.consoleExpanded}
onClick={() => setState("consoleExpanded", (value) => !value)}
aria-expanded={consoleExpanded()}
onClick={() => setConsoleExpanded((value) => !value)}
>
<span>
{language.plural(
@@ -517,7 +544,7 @@ export const SettingsProviders: Component<{
size="small"
classList={{
"settings-provider-console-chevron": true,
open: state.consoleExpanded,
open: consoleExpanded(),
}}
/>
</button>
@@ -539,7 +566,7 @@ export const SettingsProviders: Component<{
<AccountMenu provider={item} name={language.t("provider.connect.opencode.name")} />
</Show>
</div>
<Show when={state.consoleExpanded}>
<Show when={consoleExpanded()}>
<div class="settings-provider-console-list">
<div class="settings-provider-console-separator" aria-hidden="true" />
<For each={group().providers}>
@@ -581,9 +608,7 @@ export const SettingsProviders: Component<{
<div class="settings-provider-copy">
<div class="settings-provider-main">
<span class="settings-provider-name">
{item.name}
</span>
<span class="settings-provider-name">{item.name}</span>
<Show when={item.id === "opencode" || item.id === "opencode-go"}>
<Badge>{language.t("dialog.provider.tag.recommended")}</Badge>
</Show>
@@ -6,6 +6,8 @@ import {
visibleWorkspaces,
WORKSPACE_COLLAPSE_MS,
WORKSPACE_DELETE_TIMEOUT_MS,
WORKSPACE_INSPECT_TIMEOUT_MS,
workspaceConfirmView,
workspaceRowView,
type WorkspaceDeleteEffect,
type WorkspaceDeleteEvent,
@@ -42,41 +44,150 @@ const run = (attempt: number, item: WorkspaceTarget, force: boolean, active?: st
timeoutMs: WORKSPACE_DELETE_TIMEOUT_MS,
})
const clean = { active: false, linked: false, dirty: false }
const dirty = { active: false, linked: false, dirty: true }
const inspect = (attempt: number, item: WorkspaceTarget, active?: string): WorkspaceDeleteEffect => ({
type: "inspect.run",
attempt,
directory: item.directory,
active,
timeoutMs: WORKSPACE_INSPECT_TIMEOUT_MS,
})
// Opens the single-worktree confirmation (attempt 1), passes its check (attempt 2) and accepts it.
const acceptOne = (item: WorkspaceTarget): WorkspaceDeleteEvent[] => [
{ type: "confirm.opened", scope: "one", active: undefined, targets: [item] },
{ type: "inspect.succeeded", attempt: 2, inspection: clean },
{ type: "confirm.accepted", attempt: 1 },
]
describe("workspace delete machine", () => {
test("a closing dialog's late cancel does not cancel the next confirmation", () => {
const next = replay([
{ type: "confirm.opened", scope: "one", active: undefined, targets: [a] },
{ type: "confirm.accepted", attempt: 1 },
{ type: "delete.skipped", attempt: 2, reason: { kind: "failed", message: "busy" } },
...acceptOne(a),
{ type: "delete.skipped", attempt: 3, reason: { kind: "failed", message: "busy" } },
{ type: "confirm.opened", scope: "one", active: undefined, targets: [b] },
{ type: "inspect.succeeded", attempt: 5, inspection: clean },
])
expect(next.state).toMatchObject({ status: "confirming", attempt: 3 })
expect(next.state).toMatchObject({ status: "confirming", attempt: 4 })
// The first dialog's exit animation ends now and reports its close.
const late = transitionWorkspaceDelete(next.state, { type: "confirm.cancelled", attempt: 1 })
expect(late.state).toBe(next.state)
expect(isWorkspaceDeleteBusy(late.state)).toBe(true)
expect(transitionWorkspaceDelete(late.state, { type: "confirm.accepted", attempt: 3 }).effects).toEqual([
run(4, b, true),
expect(transitionWorkspaceDelete(late.state, { type: "confirm.accepted", attempt: 4 }).effects).toEqual([
run(6, b, true),
])
})
test("a collapsed row stays hidden until the inventory drops it", () => {
const collapsing = replay([
{ type: "confirm.opened", scope: "one", active: undefined, targets: [a] },
{ type: "confirm.accepted", attempt: 1 },
{ type: "delete.succeeded", attempt: 2, target: a },
test("a failed check offers Retry instead of stranding the confirmation", () => {
const opened = replay([{ type: "confirm.opened", scope: "one", active: "/repo", targets: [a] }])
expect(opened.effects).toEqual([
{ type: "open.confirm", attempt: 1, scope: "one", active: "/repo", targets: [a] },
inspect(2, a, "/repo"),
])
expect(workspaceConfirmView(opened.state, 1)).toEqual({
checking: true,
failed: false,
canDelete: false,
inspection: undefined,
})
for (const type of ["inspect.failed", "inspect.timed-out"] as const) {
const failed = transitionWorkspaceDelete(opened.state, { type, attempt: 2 })
expect(failed.effects).toEqual([{ type: "inspect.stop", attempt: 2 }])
expect(workspaceConfirmView(failed.state, 1)).toEqual({
checking: false,
failed: true,
canDelete: false,
inspection: undefined,
})
expect(transitionWorkspaceDelete(failed.state, { type: "confirm.accepted", attempt: 1 }).state).toBe(failed.state)
const retried = transitionWorkspaceDelete(failed.state, { type: "inspect.retried", attempt: 1 })
expect(retried.effects).toEqual([inspect(3, a, "/repo")])
expect(workspaceConfirmView(retried.state, 1).checking).toBe(true)
// A second click while the retry runs starts nothing.
expect(transitionWorkspaceDelete(retried.state, { type: "inspect.retried", attempt: 1 }).state).toBe(
retried.state,
)
const ready = replay(
[
{ type: "inspect.succeeded", attempt: 3, inspection: dirty },
{ type: "confirm.accepted", attempt: 1 },
],
retried.state,
)
expect(ready.effects).toEqual([run(4, a, true, "/repo")])
}
})
test("Delete does nothing until the check passes, and the dialog keeps its warnings while it closes", () => {
const checking = replay([{ type: "confirm.opened", scope: "one", active: undefined, targets: [a] }]).state
expect(transitionWorkspaceDelete(checking, { type: "confirm.accepted", attempt: 1 }).state).toBe(checking)
const deleting = replay(
[
{ type: "inspect.succeeded", attempt: 2, inspection: dirty },
{ type: "confirm.accepted", attempt: 1 },
],
checking,
).state
expect(workspaceConfirmView(deleting, 1)).toEqual({
checking: false,
failed: false,
canDelete: false,
inspection: dirty,
})
})
test("closing or leaving a confirmation stops its check, and a late check result is ignored", () => {
const checking = replay([{ type: "confirm.opened", scope: "one", active: undefined, targets: [a] }]).state
const cancelled = transitionWorkspaceDelete(checking, { type: "confirm.cancelled", attempt: 1 })
expect(cancelled).toEqual({
state: { status: "idle", issued: 2, removed: {} },
effects: [{ type: "inspect.stop", attempt: 2 }],
})
expect(
transitionWorkspaceDelete(cancelled.state, { type: "inspect.succeeded", attempt: 2, inspection: clean }).state,
).toBe(cancelled.state)
expect(transitionWorkspaceDelete(checking, { type: "disposed" })).toEqual({
state: { status: "disposed" },
effects: [{ type: "inspect.stop", attempt: 2 }],
})
const retried = replay(
[
{ type: "inspect.failed", attempt: 2 },
{ type: "inspect.retried", attempt: 1 },
],
checking,
).state
expect(transitionWorkspaceDelete(retried, { type: "inspect.succeeded", attempt: 2, inspection: clean }).state).toBe(
retried,
)
})
test("a collapsed row stays hidden until the inventory drops it", () => {
const collapsing = replay([...acceptOne(a), { type: "delete.succeeded", attempt: 3, target: a }])
expect(collapsing.effects).toEqual([
{ type: "delete.timer.stop", attempt: 2 },
{ type: "collapse.start", attempt: 2, delayMs: WORKSPACE_COLLAPSE_MS },
{ type: "delete.timer.stop", attempt: 3 },
{ type: "collapse.start", attempt: 3, delayMs: WORKSPACE_COLLAPSE_MS },
])
expect(workspaceRowView(collapsing.state, a.key)).toEqual({ deleting: true, collapsing: true })
expect(visibleWorkspaces(collapsing.state, [a, b], (item) => item.key)).toEqual([a, b])
const collapsed = transitionWorkspaceDelete(collapsing.state, { type: "collapse.completed", attempt: 2 })
const collapsed = transitionWorkspaceDelete(collapsing.state, { type: "collapse.completed", attempt: 3 })
expect(collapsed.effects).toEqual([{ type: "finalize.removed", target: a }])
expect(collapsed.state).toMatchObject({ status: "idle" })
// The inventory still lists it while it refetches, and the row must not come back.
@@ -85,7 +196,7 @@ describe("workspace delete machine", () => {
expect(stale.state).toBe(collapsed.state)
const synced = transitionWorkspaceDelete(collapsed.state, { type: "inventory.synced", keys: [b.key] })
expect(synced.state).toEqual({ status: "idle", issued: 2, removed: {} })
expect(synced.state).toEqual({ status: "idle", issued: 3, removed: {} })
})
test("a bulk delete moves past blocked, failed and timed-out worktrees", () => {
@@ -139,26 +250,18 @@ describe("workspace delete machine", () => {
})
test("closing the list mid-delete still reconciles what the server removed", () => {
const collapsing = replay([
{ type: "confirm.opened", scope: "one", active: undefined, targets: [a] },
{ type: "confirm.accepted", attempt: 1 },
{ type: "delete.succeeded", attempt: 2, target: a },
])
const collapsing = replay([...acceptOne(a), { type: "delete.succeeded", attempt: 3, target: a }])
expect(transitionWorkspaceDelete(collapsing.state, { type: "disposed" }).effects).toEqual([
{ type: "collapse.cancel" },
{ type: "finalize.removed", target: a },
])
const deleting = replay([
{ type: "confirm.opened", scope: "one", active: undefined, targets: [a] },
{ type: "confirm.accepted", attempt: 1 },
{ type: "disposed" },
])
const deleting = replay([...acceptOne(a), { type: "disposed" }])
expect(deleting.effects).toEqual([{ type: "delete.timer.stop", attempt: 2 }])
expect(deleting.effects).toEqual([{ type: "delete.timer.stop", attempt: 3 }])
expect(
transitionWorkspaceDelete(deleting.state, { type: "delete.succeeded", attempt: 2, target: a }).effects,
transitionWorkspaceDelete(deleting.state, { type: "delete.succeeded", attempt: 3, target: a }).effects,
).toEqual([{ type: "finalize.removed", target: a }])
expect(
transitionWorkspaceDelete(deleting.state, {
@@ -188,7 +291,7 @@ describe("workspace delete machine", () => {
).toBe(confirming.state)
expect(transitionWorkspaceDelete(confirming.state, { type: "confirm.cancelled", attempt: 1 }).state).toEqual({
status: "idle",
issued: 1,
issued: 2,
removed: {},
})
})
@@ -6,6 +6,9 @@ export const WORKSPACE_COLLAPSE_MS = 150
/** How long one worktree's check and removal may run before the list moves on. */
export const WORKSPACE_DELETE_TIMEOUT_MS = 60_000
/** How long the single-worktree confirmation checks git status and sessions before it offers Retry. */
export const WORKSPACE_INSPECT_TIMEOUT_MS = 15_000
export type WorkspaceTarget = {
readonly key: string
readonly directory: string
@@ -21,6 +24,12 @@ export type WorkspaceSkipReason =
| { readonly kind: "failed"; readonly message: string | undefined }
| { readonly kind: "timed-out" }
/** The single-worktree confirmation's check of git status and linked sessions, which must pass before Delete. */
export type WorkspaceConfirmPreflight =
| { readonly status: "checking"; readonly checkAttempt: number }
| { readonly status: "ready"; readonly inspection: WorkspaceDeleteInspection }
| { readonly status: "failed" }
type Run = {
readonly issued: number
readonly attempt: number
@@ -29,14 +38,16 @@ type Run = {
readonly active: string | undefined
readonly current: WorkspaceTarget
readonly queue: readonly WorkspaceTarget[]
/** The accepted single-worktree check, so its dialog keeps its warnings while it animates closed. */
readonly confirmed?: { readonly attempt: number; readonly inspection: WorkspaceDeleteInspection }
readonly removed: Readonly<Record<string, true>>
}
/**
* Deleting worktrees from Settings › Worktrees. One confirmation or one sequential batch at a time. `removed` holds
* rows that finished collapsing until the inventory drops them, so they never reappear in between. Attempts come from
* `issued`: a confirmation and each worktree's removal take one, and a result whose attempt the state no longer holds
* is stale.
* `issued`: a confirmation, each check and each worktree's removal take one, and a result whose attempt the state no
* longer holds is stale.
*/
export type WorkspaceDeleteState =
| { readonly status: "idle"; readonly issued: number; readonly removed: Readonly<Record<string, true>> }
@@ -44,11 +55,21 @@ export type WorkspaceDeleteState =
readonly status: "confirming"
readonly issued: number
readonly attempt: number
readonly scope: WorkspaceDeleteScope
readonly scope: "all" | "unused"
readonly active: string | undefined
readonly targets: readonly WorkspaceTarget[]
readonly removed: Readonly<Record<string, true>>
}
| {
readonly status: "confirming"
readonly issued: number
readonly attempt: number
readonly scope: "one"
readonly active: string | undefined
readonly target: WorkspaceTarget
readonly preflight: WorkspaceConfirmPreflight
readonly removed: Readonly<Record<string, true>>
}
| ({ readonly status: "deleting" } & Run)
| ({ readonly status: "collapsing" } & Run)
| { readonly status: "disposed" }
@@ -60,6 +81,11 @@ export type WorkspaceDeleteEvent =
readonly active: string | undefined
readonly targets: readonly WorkspaceTarget[]
}
| { readonly type: "inspect.succeeded"; readonly attempt: number; readonly inspection: WorkspaceDeleteInspection }
| { readonly type: "inspect.failed"; readonly attempt: number }
| { readonly type: "inspect.timed-out"; readonly attempt: number }
/** Retry in the single-worktree confirmation; `attempt` is the confirmation's. */
| { readonly type: "inspect.retried"; readonly attempt: number }
/** The confirmation closed. Its dialog reports this after its exit animation, possibly after another one opened. */
| { readonly type: "confirm.cancelled"; readonly attempt: number }
| { readonly type: "confirm.accepted"; readonly attempt: number }
@@ -79,6 +105,15 @@ export type WorkspaceDeleteEffect =
readonly active: string | undefined
readonly targets: readonly WorkspaceTarget[]
}
/** Starts the check's timeout and reads git status and sessions with a signal that `inspect.stop` aborts. */
| {
readonly type: "inspect.run"
readonly attempt: number
readonly directory: string
readonly active: string | undefined
readonly timeoutMs: number
}
| { readonly type: "inspect.stop"; readonly attempt: number }
/** Starts the attempt's timeout, then checks (unless forced) and removes the worktree. */
| {
readonly type: "delete.run"
@@ -128,7 +163,7 @@ export function transitionWorkspaceDelete(
effects: [{ type: "collapse.cancel" }, { type: "finalize.removed", target: state.current }],
}
return { state: { status: "disposed" }, effects: NONE }
return { state: { status: "disposed" }, effects: state.status === "confirming" ? stopCheck(state) : NONE }
}
if (event.type === "inventory.synced") {
@@ -148,43 +183,50 @@ export function transitionWorkspaceDelete(
}
if (state.status === "idle") {
if (event.type !== "confirm.opened" || event.targets.length === 0) return { state, effects: NONE }
const [target] = event.type === "confirm.opened" ? event.targets : []
if (event.type !== "confirm.opened" || !target) return { state, effects: NONE }
const attempt = state.issued + 1
const open: WorkspaceDeleteEffect = {
type: "open.confirm",
attempt,
scope: event.scope,
active: event.active,
targets: event.targets,
}
if (event.scope !== "one")
return {
state: {
status: "confirming",
issued: attempt,
attempt,
scope: event.scope,
active: event.active,
targets: event.targets,
removed: state.removed,
},
effects: [open],
}
const check = attempt + 1
return {
state: {
status: "confirming",
issued: attempt,
issued: check,
attempt,
scope: event.scope,
scope: "one",
active: event.active,
targets: event.targets,
target,
preflight: { status: "checking", checkAttempt: check },
removed: state.removed,
},
effects: [{ type: "open.confirm", attempt, scope: event.scope, active: event.active, targets: event.targets }],
effects: [open, inspectRun(check, target, event.active)],
}
}
if (state.status === "confirming") {
if ((event.type !== "confirm.cancelled" && event.type !== "confirm.accepted") || event.attempt !== state.attempt)
return { state, effects: NONE }
if (event.type === "confirm.cancelled")
return { state: { status: "idle", issued: state.issued, removed: state.removed }, effects: NONE }
const [current, ...queue] = state.targets
if (!current) return { state: { status: "idle", issued: state.issued, removed: state.removed }, effects: NONE }
return start({
issued: state.issued,
force: state.scope === "one",
active: state.active,
current,
queue,
removed: state.removed,
})
}
if (state.status === "confirming") return confirming(state, event)
if (!("attempt" in event) || event.attempt !== state.attempt) return { state, effects: NONE }
@@ -231,6 +273,88 @@ export function workspaceRowView(state: WorkspaceDeleteState, key: string) {
return { deleting: false, collapsing: false }
}
/** What the single-worktree dialog for confirmation `attempt` shows. */
export function workspaceConfirmView(state: WorkspaceDeleteState, attempt: number) {
if (state.status === "confirming" && state.scope === "one" && state.attempt === attempt)
return {
checking: state.preflight.status === "checking",
failed: state.preflight.status === "failed",
canDelete: state.preflight.status === "ready",
inspection: state.preflight.status === "ready" ? state.preflight.inspection : undefined,
}
if ((state.status === "deleting" || state.status === "collapsing") && state.confirmed?.attempt === attempt)
return { checking: false, failed: false, canDelete: false, inspection: state.confirmed.inspection }
return { checking: false, failed: false, canDelete: false, inspection: undefined }
}
type Confirming = Extract<WorkspaceDeleteState, { status: "confirming" }>
function confirming(state: Confirming, event: WorkspaceDeleteEvent): WorkspaceDeleteTransition {
if (state.scope === "one" && state.preflight.status === "checking" && "attempt" in event) {
const check = state.preflight.checkAttempt
if (event.type === "inspect.succeeded" && event.attempt === check)
return {
state: { ...state, preflight: { status: "ready", inspection: event.inspection } },
effects: [{ type: "inspect.stop", attempt: check }],
}
if ((event.type === "inspect.failed" || event.type === "inspect.timed-out") && event.attempt === check)
return {
state: { ...state, preflight: { status: "failed" } },
effects: [{ type: "inspect.stop", attempt: check }],
}
}
if (!("attempt" in event) || event.attempt !== state.attempt) return { state, effects: NONE }
if (event.type === "confirm.cancelled")
return { state: { status: "idle", issued: state.issued, removed: state.removed }, effects: stopCheck(state) }
if (state.scope !== "one") {
if (event.type !== "confirm.accepted") return { state, effects: NONE }
const [current, ...queue] = state.targets
if (!current) return { state: { status: "idle", issued: state.issued, removed: state.removed }, effects: NONE }
return start({ issued: state.issued, force: false, active: state.active, current, queue, removed: state.removed })
}
if (event.type === "inspect.retried" && state.preflight.status === "failed") {
const check = state.issued + 1
return {
state: { ...state, issued: check, preflight: { status: "checking", checkAttempt: check } },
effects: [inspectRun(check, state.target, state.active)],
}
}
// The dialog disables Delete until the check passes; the machine holds the same rule for any other caller.
if (event.type !== "confirm.accepted" || state.preflight.status !== "ready") return { state, effects: NONE }
return start({
issued: state.issued,
force: true,
active: state.active,
current: state.target,
queue: [],
confirmed: { attempt: state.attempt, inspection: state.preflight.inspection },
removed: state.removed,
})
}
function stopCheck(state: Confirming): readonly WorkspaceDeleteEffect[] {
if (state.scope !== "one" || state.preflight.status !== "checking") return NONE
return [{ type: "inspect.stop", attempt: state.preflight.checkAttempt }]
}
function inspectRun(attempt: number, target: WorkspaceTarget, active: string | undefined): WorkspaceDeleteEffect {
return { type: "inspect.run", attempt, directory: target.directory, active, timeoutMs: WORKSPACE_INSPECT_TIMEOUT_MS }
}
function start(run: Omit<Run, "attempt">): WorkspaceDeleteTransition {
const attempt = run.issued + 1
@@ -243,6 +367,7 @@ function start(run: Omit<Run, "attempt">): WorkspaceDeleteTransition {
active: run.active,
current: run.current,
queue: run.queue,
confirmed: run.confirmed,
removed: run.removed,
},
effects: [
@@ -1,15 +1,13 @@
import { Icon } from "@opencode/ui/icon"
import { Switch } from "@opencode/ui/switch"
import { Tabs } from "@opencode/ui/tabs"
import { Button } from "@opencode/ui/button"
import { useQuery } from "@tanstack/solid-query"
import { isLocationNotFoundError } from "@opencode/client/promise"
import {
type Component,
For,
Show,
createEffect,
createMemo,
createResource,
createSignal,
onCleanup,
type JSX,
@@ -26,6 +24,7 @@ import { ExternalLink } from "@/runtime/platform/external-link"
import { ProjectFolderMissing } from "./project-folder-missing"
import { configuredLanguageServers } from "./project-lsp"
import { SettingsList } from "@/settings/list"
import { createExtensionLoad, ExtensionLoadFailed } from "@/settings/extension-load"
import "./project.css"
type SkillItem = {
@@ -126,21 +125,24 @@ const ProjectLanguageServers: Component = () => {
const server = useServerSDK()
const location = useWorkspaceLocation()
const config = useQuery(() => ({
queryKey: [server.scope, "settings-project-language-servers", location().directory],
enabled: server.connection.status() === "connected",
queryFn: () => server.api.config.get({ location: { directory: location().directory } }),
}))
const config = createExtensionLoad({
key: () => location().directory,
task: (directory, signal) => server.api.config.get({ location: { directory } }, { signal }),
})
const configured = createMemo(() =>
configuredLanguageServers(config.isPending || config.isError ? [] : (config.data ?? [])),
)
const view = config.view
const empty = () => !config.isPending && !config.isError && configured().servers.length === 0
const configured = createMemo(() => {
const current = view()
return configuredLanguageServers(current.status === "ready" ? current.value : [])
})
const empty = () => view().status === "ready" && configured().servers.length === 0
onCleanup(
server.event.on("config.updated", (event) => {
if (event.location && event.location.directory !== location().directory) return
void config.refetch()
config.invalidate()
}),
)
@@ -170,20 +172,17 @@ const ProjectLanguageServers: Component = () => {
<span>{language.t("project.settings.extensions.lsp.description")}</span>
</div>
<Show
when={!config.isPending}
when={view().status !== "loading"}
fallback={<p class="project-settings-extension-empty-description">{language.t("common.loading")}</p>}
>
<Show
when={!config.isError}
when={view().status !== "error"}
fallback={
<div class="project-settings-extension-section-copy" role="status">
<span class="project-settings-extension-empty-description">
{language.t("project.settings.extensions.lsp.loadFailed")}
</span>
<Button variant="ghost-muted" onClick={() => void config.refetch()}>
{language.t("project.settings.extensions.lsp.retry")}
</Button>
</div>
<ExtensionLoadFailed
message={language.t("project.settings.extensions.lsp.loadFailed")}
retry={language.t("project.settings.extensions.lsp.retry")}
onRetry={config.retry}
/>
}
>
<Show when={configured().servers.length > 0}>
@@ -251,34 +250,42 @@ export const ProjectSettingsExtensions: Component<{
data.location.mcp.server.list({ directory: directorySDK().directory })?.find((server) => server.name === name)
?.status.status
// Reading `.latest` rethrows a failed fetch, such as the project's plugin list after its folder is deleted, so these
// lists fall back to empty instead of crashing the page.
const [globalPluginList] = createResource(
() => serverSDK.connection.status() === "connected",
() =>
serverSDK.api.plugin
.list()
.then((result) => result.data)
.catch(() => []),
{ initialValue: [] },
// Both lists load as one, so a project list that answers first never shows shared plugins as the project's own. A
// deleted project folder has no plugins of its own; `ProjectFolderMissing` explains why.
const plugins = createExtensionLoad({
key: () => directorySDK().directory,
task: (directory, signal) =>
Promise.all([
serverSDK.api.plugin.list(undefined, { signal }).then((result) => result.data),
serverSDK.api.plugin
.list({ location: { directory } }, { signal })
.then((result) => result.data)
.catch((error) => {
if (isLocationNotFoundError(error)) return []
throw error
}),
]),
})
onCleanup(
serverSDK.event.on("plugin.updated", (event) => {
if (event.location && event.location.directory !== directorySDK().directory) return
plugins.invalidate()
}),
)
const [projectPluginList] = createResource(
() => (serverSDK.connection.status() === "connected" ? directorySDK().directory : undefined),
(directory) =>
serverSDK.api.plugin
.list({ location: { directory } })
.then((result) => result.data)
.catch(() => []),
{ initialValue: [] },
)
const pluginLists = createMemo(() => {
const current = plugins.view()
const globalPlugins = createMemo(() => pluginLabels(globalPluginList.latest ?? []))
return current.status === "ready" ? current.value : undefined
})
const globalPlugins = createMemo(() => pluginLabels(pluginLists()?.[0] ?? []))
const projectPlugins = createMemo(() => {
const shared = new Set(globalPlugins())
return pluginLabels(projectPluginList.latest ?? []).filter((name) => !shared.has(name))
return pluginLabels(pluginLists()?.[1] ?? []).filter((name) => !shared.has(name))
})
const serverSkills = createMemo(() => data.location.skill.list() ?? [])
@@ -364,9 +371,19 @@ export const ProjectSettingsExtensions: Component<{
<div class="project-settings-extension-section">
<ProjectSectionHeader
kind="plugins"
empty={projectPlugins().length === 0}
empty={pluginLists() !== undefined && projectPlugins().length === 0}
action={<span>{language.t("settings.extensions.manageConfig")}</span>}
/>
<Show when={plugins.view().status === "loading"}>
<p class="project-settings-extension-empty-description">{language.t("common.loading")}</p>
</Show>
<Show when={plugins.view().status === "error"}>
<ExtensionLoadFailed
message={language.t("settings.extensions.plugins.loadFailed")}
retry={language.t("common.retry")}
onRetry={plugins.retry}
/>
</Show>
<Show when={projectPlugins().length > 0}>
<ExtensionCard>{pluginRows(projectPlugins())}</ExtensionCard>
</Show>
@@ -34,12 +34,12 @@ import {
workspaceInventory,
} from "@/workspaces/paths"
import { listAllSessions } from "@/session/list"
import type { ServerScope } from "@/runtime/server/scope"
import {
createWorkspaceDeleteState,
isWorkspaceDeleteBusy,
transitionWorkspaceDelete,
visibleWorkspaces,
workspaceConfirmView,
workspaceRowView,
type WorkspaceDeleteEffect,
type WorkspaceDeleteEvent,
@@ -116,9 +116,9 @@ export const SettingsWorkspaces: Component<{
)
// Fetch sessions per workspace directory instead of paging through every session on the server.
const loadSessions = async (directories: readonly string[]) => {
const loadSessions = async (directories: readonly string[], signal?: AbortSignal) => {
const fetched = await Promise.all(
directories.map((directory) => listAllSessions(serverSDK.api.session, { order: "desc", directory })),
directories.map((directory) => listAllSessions(serverSDK.api.session, { order: "desc", directory }, { signal })),
)
const sessions = fetched.flat()
@@ -205,21 +205,19 @@ export const SettingsWorkspaces: Component<{
return getRelativeTime(new Date(session.time.updated).toISOString(), language.t)
}
const inspect = async (directory: string, active: string | undefined) => {
const inspect = async (directory: string, active: string | undefined, signal?: AbortSignal) => {
const [working, branch, sessions] = await Promise.all([
serverSDK.api.vcs.status({ location: { directory } }),
serverSDK.api.vcs.diff({ location: { directory }, mode: "branch" }),
loadSessions([directory]),
serverSDK.api.vcs.status({ location: { directory } }, { signal }),
serverSDK.api.vcs.diff({ location: { directory }, mode: "branch" }, { signal }),
loadSessions([directory], signal),
])
const result = inspectWorkspaceDeletion({
return inspectWorkspaceDeletion({
workspace: directory,
activeDirectory: active,
sessions,
status: working.data.length > 0 || branch.data.length > 0 ? "dirty" : "clean",
})
return { result, sessions }
}
const inspectionMessages = (result: WorkspaceDeleteInspection) => {
@@ -249,11 +247,11 @@ export const SettingsWorkspaces: Component<{
if (!effect.force) {
const preflight = await inspect(target.directory, effect.active)
if (preflight.result.active || preflight.result.linked || preflight.result.dirty)
if (preflight.active || preflight.linked || preflight.dirty)
return dispatch({
type: "delete.skipped",
attempt: effect.attempt,
reason: { kind: "blocked", inspection: preflight.result },
reason: { kind: "blocked", inspection: preflight },
})
}
@@ -266,6 +264,7 @@ export const SettingsWorkspaces: Component<{
}
const deleteTimers = new Map<number, ReturnType<typeof setTimeout>>()
const checks = new Map<number, { controller: AbortController; timer: ReturnType<typeof setTimeout> }>()
let collapseTimer: ReturnType<typeof setTimeout> | undefined
const serverKey = ServerConnection.key(serverSDK.server)
@@ -280,6 +279,30 @@ export const SettingsWorkspaces: Component<{
const run = (effect: WorkspaceDeleteEffect) => {
if (effect.type === "open.confirm") return openConfirm(effect)
if (effect.type === "inspect.run") {
const attempt = effect.attempt
const controller = new AbortController()
checks.set(attempt, {
controller,
timer: setTimeout(() => dispatch({ type: "inspect.timed-out", attempt }), effect.timeoutMs),
})
void inspect(effect.directory, effect.active, controller.signal).then(
(inspection) => dispatch({ type: "inspect.succeeded", attempt, inspection }),
() => dispatch({ type: "inspect.failed", attempt }),
)
return
}
if (effect.type === "inspect.stop") {
const check = checks.get(effect.attempt)
checks.delete(effect.attempt)
clearTimeout(check?.timer)
check?.controller.abort()
return
}
if (effect.type === "delete.run") {
const attempt = effect.attempt
deleteTimers.set(
@@ -345,15 +368,13 @@ export const SettingsWorkspaces: Component<{
const target = effect.targets[0]
if (effect.scope === "one" && target) {
const active = effect.active
void dialog.push(
() => (
<DialogDeleteWorkspace
directory={target.directory}
scope={serverSDK.scope}
attempt={attempt}
inspect={() => inspect(target.directory, active)}
view={workspaceConfirmView(deleteState(), attempt)}
inspectionMessages={inspectionMessages}
onRetry={() => dispatch({ type: "inspect.retried", attempt })}
onDelete={accept}
/>
),
@@ -624,29 +645,20 @@ function DialogDeleteWorkspaces(props: { title: string; confirmation: string; wa
function DialogDeleteWorkspace(props: {
directory: string
scope: ServerScope
attempt: number
inspect: () => Promise<{ result: WorkspaceDeleteInspection; sessions: SessionInfo[] }>
view: ReturnType<typeof workspaceConfirmView>
inspectionMessages: (result: WorkspaceDeleteInspection) => string[]
onRetry: () => void
onDelete: () => void
}) {
const dialog = useDialog()
const language = useLanguage()
const status = useQuery(() => ({
queryKey: [props.scope, pathKey(props.directory), "workspace-delete-status", props.attempt] as const,
queryFn: props.inspect,
staleTime: 0,
}))
const descriptions = () => {
if (status.isPending) return []
if (props.view.failed) return [language.t("workspace.status.error")]
if (status.isError) return [language.t("workspace.status.error")]
if (!props.view.inspection) return []
if (!status.data) return []
return props.inspectionMessages(status.data.result)
return props.inspectionMessages(props.view.inspection)
}
const remove = () => {
@@ -663,7 +675,7 @@ function DialogDeleteWorkspace(props: {
<div class="flex flex-col gap-2">
<div class="flex flex-col gap-1">
<span class="text-11-regular text-v2-text-text-faint">
{language.t(status.isPending ? "workspace.status.checking" : "workspace.delete.location")}
{language.t(props.view.checking ? "workspace.status.checking" : "workspace.delete.location")}
</span>
<code class="block w-fit max-w-full rounded-[4px] bg-[color-mix(in_oklch,var(--v2-text-text-base)_8%,transparent)] px-1 py-0.5 font-mono text-xs font-medium leading-4 text-v2-text-text-base break-all">
{props.directory}
@@ -679,7 +691,12 @@ function DialogDeleteWorkspace(props: {
<Button type="button" variant="neutral" autofocus onClick={() => dialog.close()}>
{language.t("common.cancel")}
</Button>
<Button type="button" variant="danger" disabled={status.isPending || status.isError} onClick={remove}>
<Show when={props.view.failed}>
<Button type="button" variant="neutral" onClick={() => props.onRetry()}>
{language.t("common.retry")}
</Button>
</Show>
<Button type="button" variant="danger" disabled={!props.view.canDelete} onClick={remove}>
{language.t("workspace.delete.button")}
</Button>
</DialogFooter>
@@ -118,10 +118,7 @@ export function DirectoryPickerDialog(props: DirectoryPickerDialogProps) {
return keys
})
const home = createMemo(
() =>
sync.data.path.home || inferHomeDirectory(props.location?.directory ?? ""),
)
const home = createMemo(() => sync.data.path.home || inferHomeDirectory(props.location?.directory ?? ""))
const subtitle = createMemo(() => (servers.local(props.server) ? undefined : serverName(props.server)))
@@ -375,12 +372,15 @@ export function DirectoryPickerDialog(props: DirectoryPickerDialogProps) {
if (query === undefined || signal.aborted) return directories.slice(0, 5)
const files = await sdk.api.file
.find({
location: current,
query,
type: "file",
limit: 20,
})
.find(
{
location: current,
query,
type: "file",
limit: 20,
},
{ signal },
)
.then((result) => result.data)
.catch(() => [])
@@ -567,6 +567,7 @@ export function DirectoryPickerDialog(props: DirectoryPickerDialogProps) {
onCleanup(() => {
dispatchTree({ type: "disposed" })
dispatchCombobox({ type: "disposed" })
search.dispose()
tree?.cleanUp()
})
@@ -19,7 +19,10 @@ import {
type Sdk = Parameters<typeof listPickerDirectory>[0]
type FileApi = { find?: (input: never) => Promise<object>; list?: (input: never, options: never) => Promise<object> }
type FileApi = {
find?: (input: never, options: never) => Promise<object>
list?: (input: never, options: never) => Promise<object>
}
// SAFETY: the picker only reads `api.file.find` and `api.file.list`, which every fake here provides.
// oxlint-disable-next-line anti-slop/no-chained-type-assertions -- a partial fake stands in for the generated SDK client
@@ -489,6 +492,57 @@ test("aborting one running task frees its slot for the next", async () => {
expect(await next).toBe("next")
})
test("a folder listing that failed once is read again by the next search", async () => {
const location = { directory: "/repo" }
const listed: unknown[] = []
const api = sdk({
find: async () => ({ location, data: [] }),
list: async (input: { path: string }) => {
listed.push(input.path)
if (listed.length === 1) throw new Error("server is starting")
return { location, data: [{ path: "components/", type: "directory" }] }
},
})
const search = createDirectorySearch({ sdk: api, home: () => "", base: () => "/repo", location: () => location })
expect(await search("comp")).toEqual([])
expect(await search("comp")).toEqual(["/repo/components"])
expect(listed).toEqual(["/repo", "/repo"])
})
test("a search passes its signal to the server search, and closing the picker aborts its folder reads", async () => {
const location = { directory: "/repo" }
const signals: Array<AbortSignal | undefined> = []
const listing = Promise.withResolvers<AbortSignal>()
const api = sdk({
find: async (_input: never, options: { signal?: AbortSignal }) => {
signals.push(options.signal)
return { location, data: [] }
},
list: (_input: never, options: { signal: AbortSignal }) => {
listing.resolve(options.signal)
return new Promise<object>(() => {})
},
})
const search = createDirectorySearch({ sdk: api, home: () => "", base: () => "/repo", location: () => location })
const controller = new AbortController()
const pending = search("comp", { signal: controller.signal })
const read = await listing.promise
expect(signals).toEqual([controller.signal])
search.dispose()
expect(read.aborted).toBe(true)
expect(await pending).toEqual([])
})
test("listing a folder passes the abort signal to the request", async () => {
const controller = new AbortController()
const signals: unknown[] = []
+122 -101
View File
@@ -138,113 +138,79 @@ export function displayInputDirectory(path: string, home: string) {
}
// `abort(key)` and `clear()` abort the task's signal and resolve its promise with undefined at once, so a task that
// never settles cannot keep its slot.
// never settles cannot keep its slot. The queue order lives in `PriorityQueueState`; this map holds only the I/O.
export function createPriorityTaskQueue<T>(concurrency: number) {
type Job = {
key: string
priority: "user" | "background"
promise: Promise<T | undefined>
type Entry = {
controller: AbortController
run: () => void
settle: (outcome: { value: T | undefined } | { error: unknown }) => void
task: (signal: AbortSignal) => Promise<T>
deferred: PromiseWithResolvers<T | undefined>
}
const jobs = new Map<string, Job>()
const user: Job[] = []
const background: Job[] = []
let active = 0
const entries = new Map<string, Entry>()
let queue: PriorityQueueState = { status: "idle" }
const drain = () => {
while (active < concurrency) {
const job = user.pop() ?? background.shift()
const dispatch = (event: PriorityQueueEvent) => {
const result = transitionPriorityQueue(queue, event, concurrency)
queue = result.state
result.effects.forEach((effect) => {
if (effect.type === "start") return start(effect.key)
if (!job) return
active++
job.run()
effect.keys.forEach((key) => {
const entry = entries.get(key)
if (!entry) return
entries.delete(key)
entry.controller.abort()
entry.deferred.resolve(undefined)
})
})
}
// A task that settles after it was aborted, or after another task took its key, reports nothing.
const start = (key: string) => {
const entry = entries.get(key)
if (!entry) return
const settle = (outcome: { value: T | undefined } | { error: unknown }) => {
if (entries.get(key) !== entry) return
entries.delete(key)
if ("error" in outcome) entry.deferred.reject(outcome.error)
else entry.deferred.resolve(outcome.value)
dispatch({ type: "settled", key })
}
void Promise.resolve()
.then(() => (entry.controller.signal.aborted ? undefined : entry.task(entry.controller.signal)))
.then(
(value) => settle({ value }),
(error) => settle({ error }),
)
}
const schedule = (key: string, priority: Job["priority"], task: (signal: AbortSignal) => Promise<T>) => {
const existing = jobs.get(key)
const schedule = (key: string, priority: TaskPriority, task: (signal: AbortSignal) => Promise<T>) => {
const existing = entries.get(key)
if (existing) {
if (priority === "user") promote(key)
dispatch({ type: "scheduled", key, priority })
return existing.promise
return existing.deferred.promise
}
const deferred = Promise.withResolvers<T | undefined>()
const controller = new AbortController()
const state = { running: false, settled: false }
const entry: Entry = { controller: new AbortController(), task, deferred: Promise.withResolvers() }
entries.set(key, entry)
dispatch({ type: "scheduled", key, priority })
const job: Job = {
key,
priority,
promise: deferred.promise,
controller,
run: () => {
state.running = true
Promise.resolve()
.then(() => (controller.signal.aborted ? undefined : task(controller.signal)))
.then(
(value) => job.settle({ value }),
(error) => job.settle({ error }),
)
},
settle: (outcome) => {
if (state.settled) return
state.settled = true
jobs.delete(key)
dequeue(job)
if (state.running) active--
if ("error" in outcome) deferred.reject(outcome.error)
else deferred.resolve(outcome.value)
drain()
},
}
jobs.set(key, job)
;(priority === "user" ? user : background).push(job)
drain()
return job.promise
return entry.deferred.promise
}
const dequeue = (job: Job) => {
const queue = job.priority === "user" ? user : background
const index = queue.indexOf(job)
if (index !== -1) queue.splice(index, 1)
return {
schedule,
promote: (key: string) => dispatch({ type: "promoted", key }),
abort: (key: string) => dispatch({ type: "aborted", key }),
clear: () => dispatch({ type: "cleared" }),
}
const abort = (key: string) => {
const job = jobs.get(key)
if (!job) return
job.controller.abort()
job.settle({ value: undefined })
}
const promote = (key: string) => {
const job = jobs.get(key)
if (!job || job.priority === "user") return
const index = background.indexOf(job)
if (index === -1) return
background.splice(index, 1)
job.priority = "user"
user.push(job)
}
// Queued jobs go first, so aborting a running one never starts a job that is about to be dropped.
const clear = () => {
;[...user, ...background, ...jobs.values()].forEach((job) => abort(job.key))
}
return { schedule, promote, abort, clear }
}
export function nextSuggestionIndex(current: number, delta: -1 | 1, count: number) {
@@ -292,6 +258,16 @@ function nativePickerPath(path: string) {
import { getFilename } from "@opencode/util/path"
import fuzzysort from "fuzzysort"
import { ServerSDK } from "@/runtime/server/client"
import {
createDirectoryCacheState,
directoryCacheEntry,
transitionDirectoryCache,
transitionPriorityQueue,
type DirectoryCacheEvent,
type PriorityQueueEvent,
type PriorityQueueState,
type TaskPriority,
} from "./queue-machine"
export function cleanPickerInput(value: string) {
const first = (value ?? "").split(/\r?\n/)[0] ?? ""
@@ -446,7 +422,48 @@ export function createDirectorySearch(args: {
base: () => string | undefined
home: () => string
}) {
const cache = new Map<string, Promise<Array<{ name: string; absolute: string }>>>()
type Item = { name: string; absolute: string }
// Reads end with the dialog, not with one search, since later searches reuse what they cached.
const lifetime = new AbortController()
const waiters = new Map<number, Array<(items: readonly Item[]) => void>>()
let cache = createDirectoryCacheState<Item>()
const dispatch = (event: DirectoryCacheEvent<Item>) => {
const result = transitionDirectoryCache(cache, event)
cache = result.state
result.effects.forEach((effect) => {
if (effect.type === "fetch") {
const attempt = effect.attempt
const key = effect.key
void listPickerDirectory(args.sdk, effect.location, effect.directory, lifetime.signal).then(
(nodes) =>
dispatch({
type: "lookup.succeeded",
key,
attempt,
items: nodes.filter((node) => node.type === "directory"),
}),
() => dispatch({ type: "lookup.failed", key, attempt }),
)
return
}
if (effect.type === "resolve") {
const resolve = waiters.get(effect.attempt) ?? []
waiters.delete(effect.attempt)
resolve.forEach((answer) => answer(effect.items))
return
}
lifetime.abort()
const pending = [...waiters.values()].flat()
waiters.clear()
pending.forEach((answer) => answer([]))
})
}
const scoped = (value: string) => {
const raw = normalizePickerDrive(value)
@@ -467,22 +484,21 @@ export function createDirectorySearch(args: {
return { directory: trimPickerPath(base), path: raw }
}
const directories = async (directory: string) => {
const directories = async (directory: string): Promise<readonly Item[]> => {
const location = args.location()
if (!location) return []
const key = JSON.stringify([location, trimPickerPath(directory)])
const existing = cache.get(key)
dispatch({ type: "lookup.requested", key, location, directory })
const entry = directoryCacheEntry(cache, key)
if (existing) return existing
if (!entry) return []
const request = listPickerDirectory(args.sdk, location, directory)
.catch(() => [])
.then((nodes) => nodes.filter((node) => node.type === "directory"))
if (entry.status === "ready") return entry.items
const answer = Promise.withResolvers<readonly Item[]>()
waiters.set(entry.attempt, [...(waiters.get(entry.attempt) ?? []), answer.resolve])
cache.set(key, request)
return request
return answer.promise
}
const match = async (directory: string, query: string, limit: number) => {
@@ -493,7 +509,7 @@ export function createDirectorySearch(args: {
return fuzzysort.go(query, items, { key: "name", limit }).map((item) => item.obj.absolute)
}
return async (filter: string, options?: { signal?: AbortSignal }): Promise<string[]> => {
const search = async (filter: string, options?: { signal?: AbortSignal }): Promise<string[]> => {
const active = () => !options?.signal?.aborted
const value = cleanPickerInput(filter)
const input = scoped(value)
@@ -511,7 +527,10 @@ export function createDirectorySearch(args: {
relative === undefined
? []
: await args.sdk.api.file
.find({ location, query: joinPickerPath(relative, query), type: "directory", limit: 50 })
.find(
{ location, query: joinPickerPath(relative, query), type: "directory", limit: 50 },
{ signal: options?.signal },
)
.then((result) =>
result.data
.map((entry) => pickerAbsolutePath(entry.path, result.location.directory))
@@ -567,4 +586,6 @@ export function createDirectorySearch(args: {
return Array.from(new Set([base, ...matches, ...children].filter(Boolean))).slice(0, 50)
}
return Object.assign(search, { dispose: () => dispatch({ type: "disposed" }) })
}
@@ -0,0 +1,116 @@
import { expect, test } from "bun:test"
import {
createDirectoryCacheState,
directoryCacheEntry,
transitionDirectoryCache,
transitionPriorityQueue,
type DirectoryCacheEvent,
type DirectoryCacheState,
type PriorityQueueEvent,
type PriorityQueueState,
} from "./queue-machine"
const location = { directory: "/repo" }
const lookup = (key: string): DirectoryCacheEvent<string> => ({
type: "lookup.requested",
key,
location,
directory: key,
})
function cache(events: DirectoryCacheEvent<string>[], state = createDirectoryCacheState<string>()) {
return events.reduce<{ state: DirectoryCacheState<string>; effects: unknown[] }>(
(current, event) => {
const result = transitionDirectoryCache(current.state, event)
return { state: result.state, effects: [...current.effects, ...result.effects] }
},
{ state, effects: [] },
)
}
function queue(events: PriorityQueueEvent[], concurrency: number) {
return events.reduce<{ state: PriorityQueueState; effects: unknown[] }>(
(current, event) => {
const result = transitionPriorityQueue(current.state, event, concurrency)
return { state: result.state, effects: [...current.effects, ...result.effects] }
},
{ state: { status: "idle" }, effects: [] },
)
}
test("a failed folder read leaves the cache, so the next lookup reads it again", () => {
const failed = cache([lookup("/repo/src"), { type: "lookup.failed", key: "/repo/src", attempt: 1 }])
expect(failed.effects.at(-1)).toEqual({ type: "resolve", attempt: 1, items: [] })
expect(directoryCacheEntry(failed.state, "/repo/src")).toBeUndefined()
expect(transitionDirectoryCache(failed.state, lookup("/repo/src")).effects).toEqual([
{ type: "fetch", key: "/repo/src", attempt: 2, location, directory: "/repo/src" },
])
})
test("lookups of one folder share a read, and a late or stale result changes nothing", () => {
const loading = cache([lookup("/repo/src"), lookup("/repo/src")])
expect(loading.effects).toEqual([{ type: "fetch", key: "/repo/src", attempt: 1, location, directory: "/repo/src" }])
const ready = transitionDirectoryCache(loading.state, {
type: "lookup.succeeded",
key: "/repo/src",
attempt: 1,
items: ["components"],
}).state
expect(directoryCacheEntry(ready, "/repo/src")).toEqual({ status: "ready", items: ["components"] })
expect(transitionDirectoryCache(ready, { type: "lookup.failed", key: "/repo/src", attempt: 1 }).state).toBe(ready)
expect(transitionDirectoryCache(ready, lookup("/repo/src")).state).toBe(ready)
})
test("closing the dialog aborts every read and ignores what arrives after", () => {
const disposed = cache([lookup("/repo/src"), { type: "disposed" }])
expect(disposed.effects.at(-1)).toEqual({ type: "abort-all" })
expect(
transitionDirectoryCache(disposed.state, { type: "lookup.succeeded", key: "/repo/src", attempt: 1, items: [] })
.effects,
).toEqual([])
expect(transitionDirectoryCache(disposed.state, lookup("/repo/lib")).effects).toEqual([])
})
test("clearing the queue cancels queued and running tasks at once without starting a queued one", () => {
const cleared = queue(
[
{ type: "scheduled", key: "a", priority: "background" },
{ type: "scheduled", key: "b", priority: "background" },
{ type: "scheduled", key: "c", priority: "user" },
{ type: "cleared" },
],
1,
)
expect(cleared.state).toEqual({ status: "idle" })
expect(cleared.effects).toEqual([
{ type: "start", key: "a" },
{ type: "cancel", keys: ["c", "b", "a"] },
])
})
test("an aborted task's slot goes to the newest user task, and its late settle starts nothing", () => {
const aborted = queue(
[
{ type: "scheduled", key: "a", priority: "user" },
{ type: "scheduled", key: "b", priority: "background" },
{ type: "scheduled", key: "c", priority: "background" },
{ type: "promoted", key: "c" },
{ type: "aborted", key: "a" },
],
1,
)
expect(aborted.effects.slice(1)).toEqual([
{ type: "cancel", keys: ["a"] },
{ type: "start", key: "c" },
])
expect(transitionPriorityQueue(aborted.state, { type: "settled", key: "a" }, 1).state).toBe(aborted.state)
})
@@ -0,0 +1,203 @@
export type TaskPriority = "user" | "background"
/**
* The directory picker's listing queue: at most `concurrency` tasks run, and a free slot takes the newest `user` task
* before the oldest `background` one. `busy` always has a running task.
*/
export type PriorityQueueState =
| { readonly status: "idle" }
| {
readonly status: "busy"
readonly running: readonly string[]
readonly user: readonly string[]
readonly background: readonly string[]
}
export type PriorityQueueEvent =
| { readonly type: "scheduled"; readonly key: string; readonly priority: TaskPriority }
| { readonly type: "promoted"; readonly key: string }
| { readonly type: "settled"; readonly key: string }
| { readonly type: "aborted"; readonly key: string }
| { readonly type: "cleared" }
export type PriorityQueueEffect =
| { readonly type: "start"; readonly key: string }
/** Aborts the tasks and resolves their promises with undefined at once, so a task that never settles frees its slot. */
| { readonly type: "cancel"; readonly keys: readonly string[] }
export type PriorityQueueTransition = {
readonly state: PriorityQueueState
readonly effects: readonly PriorityQueueEffect[]
}
const IDLE: PriorityQueueState = { status: "idle" }
export function transitionPriorityQueue(
state: PriorityQueueState,
event: PriorityQueueEvent,
concurrency: number,
): PriorityQueueTransition {
if (event.type === "scheduled" && state.status === "idle")
return {
state: { status: "busy", running: [event.key], user: [], background: [] },
effects: [{ type: "start", key: event.key }],
}
if (state.status === "idle") return { state, effects: [] }
if (event.type === "cleared")
return { state: IDLE, effects: [{ type: "cancel", keys: [...state.user, ...state.background, ...state.running] }] }
if (event.type === "scheduled" || event.type === "promoted") {
const priority = event.type === "promoted" ? "user" : event.priority
if (state.background.includes(event.key)) {
if (priority !== "user") return { state, effects: [] }
return {
state: {
...state,
user: [...state.user, event.key],
background: state.background.filter((key) => key !== event.key),
},
effects: [],
}
}
if (event.type === "promoted" || state.running.includes(event.key) || state.user.includes(event.key))
return { state, effects: [] }
if (state.running.length < concurrency)
return {
state: { ...state, running: [...state.running, event.key] },
effects: [{ type: "start", key: event.key }],
}
return {
state:
priority === "user"
? { ...state, user: [...state.user, event.key] }
: { ...state, background: [...state.background, event.key] },
effects: [],
}
}
if (event.type === "aborted" && (state.user.includes(event.key) || state.background.includes(event.key)))
return {
state: {
...state,
user: state.user.filter((key) => key !== event.key),
background: state.background.filter((key) => key !== event.key),
},
effects: [{ type: "cancel", keys: [event.key] }],
}
if (!state.running.includes(event.key)) return { state, effects: [] }
const running = state.running.filter((key) => key !== event.key)
const next = state.user.at(-1) ?? state.background[0]
const cancel: readonly PriorityQueueEffect[] = event.type === "aborted" ? [{ type: "cancel", keys: [event.key] }] : []
if (next === undefined) return { state: running.length === 0 ? IDLE : { ...state, running }, effects: cancel }
return {
state: {
status: "busy",
running: [...running, next],
user: state.user.filter((key) => key !== next),
background: state.background.filter((key) => key !== next),
},
effects: [...cancel, { type: "start", key: next }],
}
}
export type DirectoryCacheEntry<T> =
| { readonly status: "loading"; readonly attempt: number }
| { readonly status: "ready"; readonly items: readonly T[] }
export type PickerLocation = { readonly directory: string; readonly workspace?: string }
/**
* The picker dialog's cache of folder listings for path autocomplete. Concurrent lookups of one folder share a read.
* A failed read answers its lookups with no folders and leaves the cache, so the next keystroke reads it again.
*/
export type DirectoryCacheState<T> =
| {
readonly status: "active"
readonly issued: number
readonly entries: Readonly<Record<string, DirectoryCacheEntry<T>>>
}
| { readonly status: "disposed" }
export type DirectoryCacheEvent<T> =
| {
readonly type: "lookup.requested"
readonly key: string
readonly location: PickerLocation
readonly directory: string
}
| { readonly type: "lookup.succeeded"; readonly key: string; readonly attempt: number; readonly items: readonly T[] }
| { readonly type: "lookup.failed"; readonly key: string; readonly attempt: number }
| { readonly type: "disposed" }
export type DirectoryCacheEffect<T> =
| {
readonly type: "fetch"
readonly key: string
readonly attempt: number
readonly location: PickerLocation
readonly directory: string
}
/** Answers every lookup waiting on `attempt`. */
| { readonly type: "resolve"; readonly attempt: number; readonly items: readonly T[] }
/** Aborts every read and answers every waiting lookup with no folders. */
| { readonly type: "abort-all" }
export type DirectoryCacheTransition<T> = {
readonly state: DirectoryCacheState<T>
readonly effects: readonly DirectoryCacheEffect<T>[]
}
export function createDirectoryCacheState<T>(): DirectoryCacheState<T> {
return { status: "active", issued: 0, entries: {} }
}
export function transitionDirectoryCache<T>(
state: DirectoryCacheState<T>,
event: DirectoryCacheEvent<T>,
): DirectoryCacheTransition<T> {
if (state.status === "disposed") return { state, effects: [] }
if (event.type === "disposed") return { state: { status: "disposed" }, effects: [{ type: "abort-all" }] }
if (event.type === "lookup.requested") {
if (state.entries[event.key]) return { state, effects: [] }
const attempt = state.issued + 1
return {
state: { ...state, issued: attempt, entries: { ...state.entries, [event.key]: { status: "loading", attempt } } },
effects: [{ type: "fetch", key: event.key, attempt, location: event.location, directory: event.directory }],
}
}
const entry = state.entries[event.key]
if (entry?.status !== "loading" || entry.attempt !== event.attempt) return { state, effects: [] }
if (event.type === "lookup.succeeded")
return {
state: { ...state, entries: { ...state.entries, [event.key]: { status: "ready", items: event.items } } },
effects: [{ type: "resolve", attempt: event.attempt, items: event.items }],
}
return {
state: {
...state,
entries: Object.fromEntries(Object.entries(state.entries).filter(([key]) => key !== event.key)),
},
effects: [{ type: "resolve", attempt: event.attempt, items: [] }],
}
}
export function directoryCacheEntry<T>(state: DirectoryCacheState<T>, key: string) {
return state.status === "active" ? state.entries[key] : undefined
}