diff --git a/packages/app/e2e/regression/settings.spec.ts b/packages/app/e2e/regression/settings.spec.ts index 5f9434b6687..51f5589bed2 100644 --- a/packages/app/e2e/regression/settings.spec.ts +++ b/packages/app/e2e/regression/settings.spec.ts @@ -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" }) diff --git a/packages/app/src/runtime/i18n/en.ts b/packages/app/src/runtime/i18n/en.ts index ae68c7b8f43..a7476df2a47 100644 --- a/packages/app/src/runtime/i18n/en.ts +++ b/packages/app/src/runtime/i18n/en.ts @@ -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)", diff --git a/packages/app/src/session/list.ts b/packages/app/src/session/list.ts index e4d000ff20a..d1e46a27c3d 100644 --- a/packages/app/src/session/list.ts +++ b/packages/app/src/session/list.ts @@ -1,8 +1,12 @@ import type { SessionApi, SessionInfo, SessionListInput } from "@opencode/client/promise" -export async function listAllSessions(api: Pick, input: Omit) { +export async function listAllSessions( + api: Pick, + input: Omit, + options?: Parameters[1], +) { const load = async (cursor?: string): Promise => { - 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 diff --git a/packages/app/src/settings/extension-load-machine.test.ts b/packages/app/src/settings/extension-load-machine.test.ts new file mode 100644 index 00000000000..a75425000d2 --- /dev/null +++ b/packages/app/src/settings/extension-load-machine.test.ts @@ -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 + +type Event = ExtensionLoadEvent + +function replay(events: Event[], state: State = createExtensionLoadState()) { + return events.reduce<{ state: State; effects: ExtensionLoadEffect[] }>( + (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 => ({ + 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, + ) +}) diff --git a/packages/app/src/settings/extension-load-machine.ts b/packages/app/src/settings/extension-load-machine.ts new file mode 100644 index 00000000000..d97c03e4d81 --- /dev/null +++ b/packages/app/src/settings/extension-load-machine.ts @@ -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 = + | { 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 = + | { 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 = + | { readonly type: "run"; readonly attempt: number; readonly key: K; readonly timeoutMs: number } + | { readonly type: "abort"; readonly attempt: number } + +export type ExtensionLoadTransition = { + readonly state: ExtensionLoadState + readonly effects: readonly ExtensionLoadEffect[] +} + +export function createExtensionLoadState(): ExtensionLoadState { + return { status: "idle", issued: 0 } +} + +export function transitionExtensionLoad( + state: ExtensionLoadState, + event: ExtensionLoadEvent, +): ExtensionLoadTransition { + 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(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(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(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(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( + state: ExtensionLoadState, + 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(issued: number, key: K): ExtensionLoadTransition { + 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(issued: number, key: K, value: T): ExtensionLoadTransition { + 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 { + return { type: "abort", attempt } +} diff --git a/packages/app/src/settings/extension-load.tsx b/packages/app/src/settings/extension-load.tsx new file mode 100644 index 00000000000..a4f21b7289d --- /dev/null +++ b/packages/app/src/settings/extension-load.tsx @@ -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(input: { key: () => K; task: (key: K, signal: AbortSignal) => Promise }) { + const server = useServerSDK() + const [loadState, setLoadState] = createSignal(createExtensionLoadState()) + const runs = new Map }>() + + const dispatch = (event: ExtensionLoadEvent) => { + const previous = untrack(loadState) + const result = transitionExtensionLoad(previous, event) + + if (result.state !== previous) setLoadState(() => result.state) + result.effects.forEach(run) + } + + const run = (effect: ExtensionLoadEffect) => { + 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 ( +
+ {props.message} + +
+ ) +} diff --git a/packages/app/src/settings/providers/extensions.tsx b/packages/app/src/settings/providers/extensions.tsx index 74b438437d9..47a570ce6c9 100644 --- a/packages/app/src/settings/providers/extensions.tsx +++ b/packages/app/src/settings/providers/extensions.tsx @@ -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")} - + {/* The desktop's own server also lists the plugins main runs, so its rows stay while the list loads. */} + + + + +

{language.t("common.loading")}

+
+ + + diff --git a/packages/app/src/settings/providers/machine.test.ts b/packages/app/src/settings/providers/machine.test.ts index 6bc142e7199..e6bb87e3ede 100644 --- a/packages/app/src/settings/providers/machine.test.ts +++ b/packages/app/src/settings/providers/machine.test.ts @@ -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 = { type: "disconnect.requested", providerIDs: ["openai"], integrationID: "openai", providerName: "OpenAI", } -const disconnectConsole: ProviderDisconnectEvent = { +const disconnectConsole: SettingsProvidersEvent = { 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 => ({ + type: "account.activate.requested", + integrationID: "opencode", + providerName: "OpenCode", + account, + activeCredentialID: work.id, + catalog, +}) + +const remove = (catalog: readonly Item[]): SettingsProvidersEvent => ({ + type: "account.remove.requested", + integrationID: "opencode", + providerName: "OpenCode", + account: work, + final: false, + catalog, +}) + +function replay(events: SettingsProvidersEvent[], state = createSettingsProvidersState()) { + return events.reduce<{ state: SettingsProvidersState; 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[]) + 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() + + 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" }) }) diff --git a/packages/app/src/settings/providers/machine.ts b/packages/app/src/settings/providers/machine.ts index 2e8cfe82108..04ece2a9d4c 100644 --- a/packages/app/src/settings/providers/machine.ts +++ b/packages/app/src/settings/providers/machine.ts @@ -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>> +/** Holds only rows that are not "connected"; a missing ID is a connected row. */ +export type ProviderRows = Readonly>> + +/** 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 = + | (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 = + /** `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 = { + readonly state: SettingsProvidersState + readonly effects: readonly SettingsProvidersEffect[] } const CONNECTED: ProviderRowState = { status: "connected" } -export function createProviderDisconnectState(): ProviderDisconnectState { - return { rows: {}, nextAttempt: 1 } +export function createSettingsProvidersState(): SettingsProvidersState { + return { status: "live", rows: {}, nextAttempt: 1 } } -export function transitionProviderDisconnect( - state: ProviderDisconnectState, - event: ProviderDisconnectEvent, -): ProviderDisconnectTransition { +export function transitionSettingsProviders( + state: SettingsProvidersState, + event: SettingsProvidersEvent, +): SettingsProvidersTransition { + 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(state: SettingsProvidersState, 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( - state: ProviderDisconnectState, - available: readonly T[], -) { +export function connectedProviders(state: ProvidersBase, available: readonly T[]) { return available.filter((item) => providerRow(state, item.id).status === "connected") } -function requested( - state: ProviderDisconnectState, - event: Extract, -): ProviderDisconnectTransition { +function hold( + base: ProvidersBase, + held: readonly T[], + dialog: ProviderDialogHold | undefined, + account: ProviderAccountBusy | undefined, + renaming: string | undefined, +): SettingsProvidersState { + 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( + state: SettingsProvidersState, + event: Extract, { type: "disconnect.requested" }>, +): SettingsProvidersTransition { 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( + state: SettingsProvidersState, attempt: number, failure: DisconnectFailure | undefined, -): ProviderDisconnectTransition { +): SettingsProvidersTransition { 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( + state: SettingsProvidersState, + next: (id: string, row: ProviderRows[string]) => ProviderRowState, +): SettingsProvidersState { 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 diff --git a/packages/app/src/settings/providers/providers.tsx b/packages/app/src/settings/providers/providers.tsx index 33d9f6adea5..6bc7d59aa58 100644 --- a/packages/app/src/settings/providers/providers.tsx +++ b/packages/app/src/settings/providers/providers.tsx @@ -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()) + 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) => { + 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( + () => ( + 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( - () => ( - 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 ( @@ -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) }} > {(account) => ( - + )} @@ -375,7 +398,7 @@ export const SettingsProviders: Component<{ - connect(menuProps.provider.id)}> + connect(menuProps.provider.id)}> {language.t("settings.providers.account.add")} @@ -388,19 +411,25 @@ export const SettingsProviders: Component<{ variant="ghost-muted" size="large" icon={} - disabled={state.credentialID !== undefined || !active()} + disabled={accountView().busy || !active()} aria-label={language.t("dialog.provider.accounts.options", { account: active()?.label ?? "" })} /> - state.renaming && event.preventDefault()}> - setState("renaming", active()?.id)}> + accountView().renaming && event.preventDefault()}> + { + const account = active() + + if (account) dispatch({ type: "account.rename.started", credentialID: account.id }) + }} + > {language.t("common.rename")} { 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<{
- - {item.name} - + {item.name} {type(item)}
@@ -502,8 +529,8 @@ export const SettingsProviders: Component<{ @@ -539,7 +566,7 @@ export const SettingsProviders: Component<{ - +