From c579f9ab7c21fa059fd58c7720a5747f4f8883c2 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Wed, 4 Nov 2026 21:31:11 -0600 Subject: [PATCH] fix(app): model the Extensions flyout, MCP toggles and config actions as state machines (#61886) --- .../regression/mcp-workspace-toggle.spec.ts | 75 +- .../e2e/regression/session-summary.spec.ts | 2 + .../src/details/config-action-machine.test.ts | 117 +++ .../src/details/config-action-machine.ts | 107 +++ .../src/details/flyout-machine.test.ts | 218 +++++ .../gui-plugins/src/details/flyout-machine.ts | 252 +++++ packages/gui-plugins/src/details/i18n/en.ts | 2 + .../src/details/mcp-machine.test.ts | 315 +++++++ .../gui-plugins/src/details/mcp-machine.ts | 278 ++++++ packages/gui-plugins/src/details/panel.tsx | 5 +- packages/gui-plugins/src/details/popover.tsx | 4 +- packages/gui-plugins/src/details/renderer.tsx | 7 +- .../gui-plugins/src/details/server-panel.tsx | 886 +++++++++++------- 13 files changed, 1944 insertions(+), 324 deletions(-) create mode 100644 packages/gui-plugins/src/details/config-action-machine.test.ts create mode 100644 packages/gui-plugins/src/details/config-action-machine.ts create mode 100644 packages/gui-plugins/src/details/flyout-machine.test.ts create mode 100644 packages/gui-plugins/src/details/flyout-machine.ts create mode 100644 packages/gui-plugins/src/details/mcp-machine.test.ts create mode 100644 packages/gui-plugins/src/details/mcp-machine.ts diff --git a/packages/app/e2e/regression/mcp-workspace-toggle.spec.ts b/packages/app/e2e/regression/mcp-workspace-toggle.spec.ts index cb8ef2fc047..3c3f6dd846c 100644 --- a/packages/app/e2e/regression/mcp-workspace-toggle.spec.ts +++ b/packages/app/e2e/regression/mcp-workspace-toggle.spec.ts @@ -147,12 +147,29 @@ for (const surface of ["popover", "dialog"] as const) { test("the MCP popover shows a failed server and reconnects it from its details", async ({ page }) => { const error = "Streamable HTTP error: Error POSTing to endpoint: 404 Not Found" + const again = "Streamable HTTP error: Error POSTing to endpoint: 503 Service Unavailable" + const retries = { connecting: false, failing: true } const view = await open(page, { surface: "popover", mcp: (target) => [ - { name: "figma-desktop", status: target !== workspace ? { status: "connected" } : { status: "failed", error } }, + { + name: "figma-desktop", + status: + target !== workspace + ? { status: "connected" } + : retries.connecting + ? { status: "pending" } + : { status: "failed", error }, + }, ], + // The first retry fails again with another error, reported by the refreshed status; the second connects. + onMcpAction: (input) => { + if (input.action !== "connect" || !retries.failing) return + retries.failing = false + + return { status: "failed", error: again } + }, }) const row = view.panel.locator(".session-mcp-row").filter({ hasText: "figma-desktop" }) @@ -164,14 +181,62 @@ test("the MCP popover shows a failed server and reconnects it from its details", const details = page.getByRole("dialog", { name: "figma-desktop", exact: true }) await expect(details).toHaveAccessibleDescription("Connection failed") await expect(details.getByText(error, { exact: true })).toBeVisible() - await details.getByRole("button", { name: "Try again", exact: true }).click() + const retry = details.getByRole("button", { name: "Try again", exact: true }) + const connect = await holdRoute(page, /\/api\/experimental\/mcp\/figma-desktop\/connect(?:\?|$)/, { method: "POST" }) + await retry.click() + await connect.arrived + // The server reports that it is connecting; the details stay open while the retry runs, and take no second retry. + retries.connecting = true + + const listed = page.waitForResponse((response) => { + const url = new URL(response.url()) + + return ( + response.request().method() === "GET" && + url.pathname === "/api/mcp" && + url.searchParams.get("location[directory]") === workspace + ) + }) + + await view.push([ + { + id: "evt_mcp_connecting", + created: 1, + type: "mcp.status.changed", + location: { directory: workspace }, + data: { server: "figma-desktop" }, + }, + ]) + await listed + await expect(details.getByText(error, { exact: true })).toBeVisible() + await expect(retry).toBeDisabled() + await expect(details.getByRole("button", { name: "Disable", exact: true })).toBeDisabled() + connect.release() + // A retry that fails again shows its new error in place. + await expect(details.getByText(again, { exact: true })).toBeVisible() + await expect(retry).toBeEnabled() + + const reconnect = await holdRoute(page, /\/api\/experimental\/mcp\/figma-desktop\/connect(?:\?|$)/, { + method: "POST", + }) + + await retry.click() + await reconnect.arrived + await page.keyboard.press("Escape") await expect(details).toBeHidden() + + // The details closed and opened again still show the retry the dialog started, and take no second connect. + if (await view.panel.isVisible()) await page.getByRole("button", { name: "Session details", exact: true }).click() + await expect(view.panel).toBeHidden() + await view.show() + await expect(view.toggle).toBeDisabled() + reconnect.release() + await expect(view.toggle).toHaveAccessibleDescription("Connected") + await expect(view.toggle).toBeEnabled() expect(view.requests.filter((request) => request.path.endsWith("/connect"))).toEqual([ { path: "/api/experimental/mcp/figma-desktop/connect", directory: workspace }, + { path: "/api/experimental/mcp/figma-desktop/connect", directory: workspace }, ]) - - if (!(await view.panel.isVisible())) await view.show() - await expect(view.toggle).toHaveAccessibleDescription("Connected") }) for (const surface of ["dialog"] as const) { diff --git a/packages/app/e2e/regression/session-summary.spec.ts b/packages/app/e2e/regression/session-summary.spec.ts index 39e08332fc7..55a909baf42 100644 --- a/packages/app/e2e/regression/session-summary.spec.ts +++ b/packages/app/e2e/regression/session-summary.spec.ts @@ -563,6 +563,8 @@ test("MCP rows toggle once per action and keep sign-in, errors, and management a if (pending) { await pending.arrived await expect(connected).toBeDisabled() + // Each row toggles its own server: the others stay free meanwhile. + await expect(disabled).toBeEnabled() pending.release() } diff --git a/packages/gui-plugins/src/details/config-action-machine.test.ts b/packages/gui-plugins/src/details/config-action-machine.test.ts new file mode 100644 index 00000000000..0c8177825cf --- /dev/null +++ b/packages/gui-plugins/src/details/config-action-machine.test.ts @@ -0,0 +1,117 @@ +import { describe, expect, test } from "bun:test" +import { + CONFIG_ACTION_TIMEOUT_MS, + CONFIG_COPIED_MS, + configActionView, + initialConfigActionState, + transitionConfigAction, + type ConfigActionEvent, + type ConfigActionState, + type ConfigActionTransition, +} from "./config-action-machine" + +// Folds the events in order and returns the last transition. +const replay = (events: readonly ConfigActionEvent[], state: ConfigActionState = initialConfigActionState) => + events.reduce((last, event) => transitionConfigAction(last.state, event), { + state, + effects: [], + }) + +describe("transitionConfigAction", () => { + test("a copy moves from opening to copied in one step and expires", () => { + const opening = transitionConfigAction(initialConfigActionState, { type: "activate" }) + + expect(opening.effects).toEqual([{ type: "run", attempt: 1, timeoutMs: CONFIG_ACTION_TIMEOUT_MS }]) + expect(configActionView(opening.state)).toEqual({ disabled: true, copied: false }) + + const copied = transitionConfigAction(opening.state, { type: "copied", attempt: 1 }) + + expect(copied.effects).toEqual([ + { type: "abort", attempt: 1 }, + { type: "schedule-reset", attempt: 1, delayMs: CONFIG_COPIED_MS }, + ]) + expect(configActionView(copied.state)).toEqual({ disabled: false, copied: true }) + + const expired = transitionConfigAction(copied.state, { type: "copied.expired", attempt: 1 }) + + expect(expired.state).toEqual({ status: "idle", issued: 1 }) + }) + + test("copying again restarts and ignores the first copy's reset", () => { + const again = replay([{ type: "activate" }, { type: "copied", attempt: 1 }, { type: "activate" }]) + + expect(again.state).toEqual({ status: "opening", attempt: 2 }) + expect(again.effects).toEqual([ + { type: "cancel-reset" }, + { type: "run", attempt: 2, timeoutMs: CONFIG_ACTION_TIMEOUT_MS }, + ]) + expect(transitionConfigAction(again.state, { type: "copied.expired", attempt: 1 }).state).toBe(again.state) + }) + + test("a second click while the action runs starts nothing", () => { + const opening = transitionConfigAction(initialConfigActionState, { type: "activate" }).state + + expect(transitionConfigAction(opening, { type: "activate" })).toEqual({ state: opening, effects: [] }) + }) + + test("hiding the popover drops the copied mark", () => { + const copied = replay([{ type: "activate" }, { type: "copied", attempt: 1 }]).state + const hidden = transitionConfigAction(copied, { type: "hidden" }) + + expect(hidden).toEqual({ state: { status: "idle", issued: 1 }, effects: [{ type: "cancel-reset" }] }) + + const opening = transitionConfigAction(initialConfigActionState, { type: "activate" }).state + + expect(transitionConfigAction(opening, { type: "hidden" }).state).toBe(opening) + }) + + test("an opened file closes the popover only when a side tab replaced it", () => { + const tab = replay([{ type: "activate" }, { type: "opened", attempt: 1, close: true }]) + + expect(tab).toEqual({ + state: { status: "idle", issued: 1 }, + effects: [{ type: "abort", attempt: 1 }, { type: "close-owner" }], + }) + + const revealed = replay([{ type: "activate" }, { type: "opened", attempt: 1, close: false }]) + + expect(revealed.effects).toEqual([{ type: "abort", attempt: 1 }]) + }) + + test("a failure or a timeout ends the action with a toast", () => { + const failed = replay([{ type: "activate" }, { type: "failed", attempt: 1, error: "No configuration file found" }]) + + expect(failed).toEqual({ + state: { status: "idle", issued: 1 }, + effects: [ + { type: "abort", attempt: 1 }, + { type: "toast-failed", error: "No configuration file found" }, + ], + }) + + const timedOut = replay([{ type: "activate" }, { type: "timed-out", attempt: 1 }]) + + expect(timedOut.effects).toEqual([{ type: "abort", attempt: 1 }, { type: "toast-timed-out" }]) + + // The request that hung settles later and changes nothing. + expect(transitionConfigAction(timedOut.state, { type: "copied", attempt: 1 }).state).toBe(timedOut.state) + }) + + test("disposal aborts the running action and ignores its result", () => { + const disposed = replay([{ type: "activate" }, { type: "disposed" }]) + + expect(disposed).toEqual({ state: { status: "disposed" }, effects: [{ type: "abort", attempt: 1 }] }) + + for (const event of [ + { type: "opened", attempt: 1, close: true }, + { type: "copied", attempt: 1 }, + { type: "failed", attempt: 1, error: "late" }, + { type: "activate" }, + ] satisfies ConfigActionEvent[]) + expect(transitionConfigAction(disposed.state, event).state).toBe(disposed.state) + + const copied = replay([{ type: "activate" }, { type: "copied", attempt: 1 }, { type: "disposed" }]) + + expect(copied.effects).toEqual([{ type: "cancel-reset" }]) + }) +}) diff --git a/packages/gui-plugins/src/details/config-action-machine.ts b/packages/gui-plugins/src/details/config-action-machine.ts new file mode 100644 index 00000000000..c2e0002068b --- /dev/null +++ b/packages/gui-plugins/src/details/config-action-machine.ts @@ -0,0 +1,107 @@ +/** How long reading the configuration and opening, revealing or copying its file may take before it gives up. */ +export const CONFIG_ACTION_TIMEOUT_MS = 15_000 + +/** How long a copied path keeps its mark. */ +export const CONFIG_COPIED_MS = 2_000 + +/** + * A footer action that reads the server's configuration: the configuration file link or a setup button. Each click + * takes the next attempt number, so a result whose attempt the state no longer holds is stale; `issued` is the last + * one handed out. + */ +export type ConfigActionState = + | { readonly status: "idle"; readonly issued: number } + | { readonly status: "opening"; readonly attempt: number } + /** A remote server's configuration path is on the clipboard. */ + | { readonly status: "copied"; readonly attempt: number } + | { readonly status: "disposed" } + +export type ConfigActionEvent = + | { readonly type: "activate" } + /** The file or draft opened; `close` closes the popover, which a side tab or a draft replaces. */ + | { readonly type: "opened"; readonly attempt: number; readonly close: boolean } + | { readonly type: "copied"; readonly attempt: number } + | { readonly type: "failed"; readonly attempt: number; readonly error: string } + | { readonly type: "timed-out"; readonly attempt: number } + | { readonly type: "copied.expired"; readonly attempt: number } + /** The popover or drawer that shows the action hid. */ + | { readonly type: "hidden" } + | { readonly type: "disposed" } + +export type ConfigActionEffect = + /** Starts the attempt's controller and timeout, then runs the action. */ + | { readonly type: "run"; readonly attempt: number; readonly timeoutMs: number } + /** Ends the attempt's controller and timeout. */ + | { readonly type: "abort"; readonly attempt: number } + | { readonly type: "schedule-reset"; readonly attempt: number; readonly delayMs: number } + | { readonly type: "cancel-reset" } + | { readonly type: "close-owner" } + | { readonly type: "toast-failed"; readonly error: string } + | { readonly type: "toast-timed-out" } + +export type ConfigActionTransition = { + readonly state: ConfigActionState + readonly effects: readonly ConfigActionEffect[] +} + +export const initialConfigActionState: ConfigActionState = { status: "idle", issued: 0 } + +const NONE: readonly ConfigActionEffect[] = [] + +const CANCEL_RESET: readonly ConfigActionEffect[] = [{ type: "cancel-reset" }] + +export function transitionConfigAction(state: ConfigActionState, event: ConfigActionEvent): ConfigActionTransition { + if (state.status === "disposed") return { state, effects: NONE } + + if (event.type === "disposed") { + if (state.status === "opening") + return { state: { status: "disposed" }, effects: [{ type: "abort", attempt: state.attempt }] } + + return { state: { status: "disposed" }, effects: state.status === "copied" ? CANCEL_RESET : NONE } + } + + if (event.type === "hidden") { + if (state.status !== "copied") return { state, effects: NONE } + + return { state: { status: "idle", issued: state.attempt }, effects: CANCEL_RESET } + } + + if (event.type === "activate") { + if (state.status === "opening") return { state, effects: NONE } + const attempt = (state.status === "idle" ? state.issued : state.attempt) + 1 + + return { + state: { status: "opening", attempt }, + effects: [ + ...(state.status === "copied" ? CANCEL_RESET : NONE), + { type: "run", attempt, timeoutMs: CONFIG_ACTION_TIMEOUT_MS }, + ], + } + } + + if (event.type === "copied.expired") { + if (state.status !== "copied" || state.attempt !== event.attempt) return { state, effects: NONE } + + return { state: { status: "idle", issued: state.attempt }, effects: NONE } + } + + if (state.status !== "opening" || state.attempt !== event.attempt) return { state, effects: NONE } + const abort: ConfigActionEffect = { type: "abort", attempt: state.attempt } + const idle: ConfigActionState = { status: "idle", issued: state.attempt } + + if (event.type === "opened") return { state: idle, effects: event.close ? [abort, { type: "close-owner" }] : [abort] } + + if (event.type === "copied") + return { + state: { status: "copied", attempt: state.attempt }, + effects: [abort, { type: "schedule-reset", attempt: state.attempt, delayMs: CONFIG_COPIED_MS }], + } + + if (event.type === "failed") return { state: idle, effects: [abort, { type: "toast-failed", error: event.error }] } + + return { state: idle, effects: [abort, { type: "toast-timed-out" }] } +} + +export function configActionView(state: ConfigActionState) { + return { disabled: state.status === "opening", copied: state.status === "copied" } +} diff --git a/packages/gui-plugins/src/details/flyout-machine.test.ts b/packages/gui-plugins/src/details/flyout-machine.test.ts new file mode 100644 index 00000000000..f9e19975605 --- /dev/null +++ b/packages/gui-plugins/src/details/flyout-machine.test.ts @@ -0,0 +1,218 @@ +import { describe, expect, test } from "bun:test" +import { + AIM_TIMEOUT_MS, + flyoutActive, + flyoutPane, + initialFlyoutState, + transitionFlyout, + type FlyoutAnchor, + type FlyoutEvent, + type FlyoutState, + type FlyoutTransition, +} from "./flyout-machine" + +const mcpRow: FlyoutAnchor = { row: 40, above: 100, below: 600 } + +const pluginsRow: FlyoutAnchor = { row: 72, above: 100, below: 600 } + +// Folds the events in order and returns the last transition. +const replay = (events: readonly FlyoutEvent[], state: FlyoutState = initialFlyoutState) => + events.reduce((last, event) => transitionFlyout(last.state, event), { state, effects: [] }) + +const enterMcp: FlyoutEvent = { type: "row.entered", service: "mcp", shown: true, anchor: mcpRow } + +const aimPlugins: FlyoutEvent = { type: "row.moved", service: "plugins", aiming: true, anchor: undefined } + +describe("transitionFlyout", () => { + test("a row that cannot be measured leaves the flyout closed, so the next open still snaps and refreshes", () => { + const failed = transitionFlyout(initialFlyoutState, { ...enterMcp, anchor: undefined }) + + expect(failed.state).toBe(initialFlyoutState) + expect(failed.effects).toEqual([]) + + const opened = transitionFlyout(failed.state, enterMcp) + + expect(opened.state).toEqual({ status: "open", service: "mcp", anchor: mcpRow, refreshed: ["mcp"], issued: 0 }) + expect(opened.effects).toEqual([{ type: "refresh", service: "mcp" }, { type: "snap-open" }]) + + // A later switch glides: it does not snap again. + const switched = transitionFlyout(opened.state, { + type: "row.moved", + service: "plugins", + aiming: false, + anchor: pluginsRow, + }) + + expect(switched.state).toMatchObject({ status: "open", service: "plugins", refreshed: ["mcp", "plugins"] }) + expect(switched.effects).toEqual([{ type: "refresh", service: "plugins" }]) + }) + + test("hiding the details cancels a pending aim, fences its timer and refreshes each list on the next open", () => { + const aimed = replay([enterMcp, aimPlugins]) + + expect(aimed.state).toMatchObject({ status: "aiming", service: "mcp", target: "plugins", attempt: 1 }) + expect(aimed.effects).toEqual([{ type: "schedule-aim", attempt: 1, target: "plugins", delayMs: AIM_TIMEOUT_MS }]) + + const hidden = transitionFlyout(aimed.state, { type: "hidden" }) + + expect(hidden.state).toEqual({ status: "closed", pane: "mcp", anchor: mcpRow, issued: 1 }) + expect(hidden.effects).toEqual([{ type: "cancel-aim" }]) + + // The aim timer of before the hide cannot open the flyout. + const late = transitionFlyout(hidden.state, { type: "aim.due", attempt: 1, anchor: pluginsRow }) + + expect(late.state).toBe(hidden.state) + expect(late.effects).toEqual([]) + + const reopened = transitionFlyout(hidden.state, enterMcp) + + expect(reopened.effects).toEqual([{ type: "refresh", service: "mcp" }, { type: "snap-open" }]) + }) + + test("a pointer resting inside the safe triangle hands over to the row it aimed across", () => { + const aimed = replay([enterMcp, aimPlugins]) + const due = transitionFlyout(aimed.state, { type: "aim.due", attempt: 1, anchor: pluginsRow }) + + expect(due.state).toEqual({ + status: "open", + service: "plugins", + anchor: pluginsRow, + refreshed: ["mcp", "plugins"], + issued: 1, + }) + expect(flyoutActive(due.state)).toBe("plugins") + }) + + test("each move across the same row restarts the aim timer without replacing the state", () => { + const aimed = replay([enterMcp, aimPlugins]) + const again = transitionFlyout(aimed.state, aimPlugins) + + expect(again.state).toBe(aimed.state) + expect(again.effects).toEqual([{ type: "schedule-aim", attempt: 1, target: "plugins", delayMs: AIM_TIMEOUT_MS }]) + + const other = transitionFlyout(aimed.state, { ...aimPlugins, service: "skills" }) + + expect(other.state).toMatchObject({ status: "aiming", target: "skills", attempt: 2 }) + + // The first target's timer is stale. + const stale = transitionFlyout(other.state, { type: "aim.due", attempt: 1, anchor: pluginsRow }) + + expect(stale.state).toBe(other.state) + }) + + test("leaving the rows or reaching the flyout keeps the list on show", () => { + const aimed = replay([enterMcp, aimPlugins]) + + for (const event of [ + { type: "aim.cancelled" }, + { type: "row.moved", service: "mcp", aiming: false, anchor: undefined }, + { type: "row.moved", service: undefined, aiming: false, anchor: undefined }, + ] satisfies FlyoutEvent[]) { + const result = transitionFlyout(aimed.state, event) + + expect(result.state).toEqual({ status: "open", service: "mcp", anchor: mcpRow, refreshed: ["mcp"], issued: 1 }) + expect(result.effects).toEqual([{ type: "cancel-aim" }]) + } + }) + + test("pointer moves that change nothing keep the same state", () => { + const opened = transitionFlyout(initialFlyoutState, enterMcp).state + + for (const event of [ + { type: "row.moved", service: "mcp", aiming: false, anchor: undefined }, + { type: "row.moved", service: undefined, aiming: false, anchor: undefined }, + { type: "aim.cancelled" }, + { type: "row.entered", service: "plugins", shown: true, anchor: pluginsRow }, + { type: "remeasured", anchor: { ...mcpRow } }, + { type: "remeasured", anchor: undefined }, + { type: "aim.due", attempt: 7, anchor: pluginsRow }, + ] satisfies FlyoutEvent[]) + expect(transitionFlyout(opened, event)).toEqual({ state: opened, effects: [] }) + + for (const event of [ + { type: "row.moved", service: "plugins", aiming: false, anchor: pluginsRow }, + { type: "aim.cancelled" }, + { type: "close", focusRow: true }, + { type: "hidden" }, + ] satisfies FlyoutEvent[]) + expect(transitionFlyout(initialFlyoutState, event).state).toBe(initialFlyoutState) + }) + + test("a row that cannot be measured during a switch keeps the current list", () => { + const opened = transitionFlyout(initialFlyoutState, enterMcp).state + const moved = transitionFlyout(opened, { type: "row.moved", service: "plugins", aiming: false, anchor: undefined }) + + expect(moved.state).toBe(opened) + + const clicked = transitionFlyout(opened, { + type: "row.activated", + service: "plugins", + focus: false, + shown: true, + anchor: undefined, + }) + + expect(clicked.state).toBe(opened) + }) + + test("activating a row by keyboard opens it and moves focus into its list", () => { + const result = transitionFlyout(initialFlyoutState, { + type: "row.activated", + service: "skills", + focus: true, + shown: true, + anchor: mcpRow, + }) + + expect(result.effects).toEqual([ + { type: "refresh", service: "skills" }, + { type: "snap-open" }, + { type: "focus-pane", service: "skills" }, + ]) + + // Activating it again only moves focus: the list already refreshed. + const again = transitionFlyout(result.state, { + type: "row.activated", + service: "skills", + focus: true, + shown: true, + anchor: mcpRow, + }) + + expect(again.state).toBe(result.state) + expect(again.effects).toEqual([{ type: "focus-pane", service: "skills" }]) + }) + + test("rows of hidden details do not open the flyout", () => { + const result = transitionFlyout(initialFlyoutState, { ...enterMcp, shown: false }) + + expect(result.state).toBe(initialFlyoutState) + }) + + test("closing keeps the pane for the exit fade and returns focus to the row only when asked", () => { + const opened = transitionFlyout(initialFlyoutState, enterMcp).state + const back = transitionFlyout(opened, { type: "close", focusRow: true }) + + expect(back.state).toEqual({ status: "closed", pane: "mcp", anchor: mcpRow, issued: 0 }) + expect(back.effects).toEqual([{ type: "focus-row", service: "mcp" }]) + expect(flyoutActive(back.state)).toBeUndefined() + expect(flyoutPane(back.state)).toBe("mcp") + expect(transitionFlyout(opened, { type: "close", focusRow: false }).effects).toEqual([]) + }) + + test("scrolling moves the anchor of the open list", () => { + const opened = transitionFlyout(initialFlyoutState, enterMcp).state + const moved = transitionFlyout(opened, { type: "remeasured", anchor: pluginsRow }) + + expect(moved.state).toMatchObject({ status: "open", service: "mcp", anchor: pluginsRow }) + }) + + test("disposal cancels a pending aim and ignores everything after", () => { + const aimed = replay([enterMcp, aimPlugins]) + const disposed = transitionFlyout(aimed.state, { type: "disposed" }) + + expect(disposed).toEqual({ state: { status: "disposed" }, effects: [{ type: "cancel-aim" }] }) + expect(transitionFlyout(disposed.state, enterMcp).state).toBe(disposed.state) + expect(transitionFlyout(initialFlyoutState, { type: "disposed" }).effects).toEqual([]) + }) +}) diff --git a/packages/gui-plugins/src/details/flyout-machine.ts b/packages/gui-plugins/src/details/flyout-machine.ts new file mode 100644 index 00000000000..01328174702 --- /dev/null +++ b/packages/gui-plugins/src/details/flyout-machine.ts @@ -0,0 +1,252 @@ +/** How long a pointer may rest inside the safe triangle before the row under it takes over. */ +export const AIM_TIMEOUT_MS = 100 + +export type Service = "mcp" | "plugins" | "skills" + +/** Where the trigger row sits in the flyout's containing block, and the room around it in the viewport. */ +export type FlyoutAnchor = { readonly row: number; readonly above: number; readonly below: number } + +/** + * The Extensions flyout beside the details popover. Each aim at another row takes the next attempt number, so an aim + * timer whose attempt the state no longer holds is stale; `issued` is the last one handed out. + */ +export type FlyoutState = + /** No list shows. `pane` is the last list, kept through the exit so it fades out with its content. */ + | { + readonly status: "closed" + readonly pane: Service | undefined + readonly anchor: FlyoutAnchor + readonly issued: number + } + /** `refreshed` lists the lists refreshed since the flyout opened, each the first time it showed. */ + | { + readonly status: "open" + readonly service: Service + readonly anchor: FlyoutAnchor + readonly refreshed: readonly Service[] + readonly issued: number + } + /** The pointer heads for the open list across another row; `target` takes over once the pointer rests. */ + | { + readonly status: "aiming" + readonly service: Service + readonly target: Service + readonly attempt: number + readonly anchor: FlyoutAnchor + readonly refreshed: readonly Service[] + } + | { readonly status: "disposed" } + +export type FlyoutEvent = + /** The pointer entered a row: opens a closed flyout. `anchor` is undefined when the row could not be measured. */ + | { + readonly type: "row.entered" + readonly service: Service + readonly shown: boolean + readonly anchor: FlyoutAnchor | undefined + } + /** A click or the inline-end arrow key on a row opens its list; `focus` moves focus into it. */ + | { + readonly type: "row.activated" + readonly service: Service + readonly focus: boolean + readonly shown: boolean + readonly anchor: FlyoutAnchor | undefined + } + /** + * The pointer moved over the rows, or focus moved to another row: switches an open flyout. `service` is undefined + * between rows; `aiming` is whether the pointer heads for the open list. `anchor` is only measured for a switch. + */ + | { + readonly type: "row.moved" + readonly service: Service | undefined + readonly aiming: boolean + readonly anchor: FlyoutAnchor | undefined + } + /** The pointer left the rows or reached the flyout. */ + | { readonly type: "aim.cancelled" } + | { readonly type: "aim.due"; readonly attempt: number; readonly anchor: FlyoutAnchor | undefined } + /** Scrolling or resizing measured the open row again. */ + | { readonly type: "remeasured"; readonly anchor: FlyoutAnchor | undefined } + /** Escape, the inline-start arrow key or a footer action; `focusRow` returns focus from the list to its row. */ + | { readonly type: "close"; readonly focusRow: boolean } + /** The details popover or drawer hid. */ + | { readonly type: "hidden" } + | { readonly type: "disposed" } + +export type FlyoutEffect = + /** Starts the aim timer again; it reports `aim.due` with the target row measured. */ + | { readonly type: "schedule-aim"; readonly attempt: number; readonly target: Service; readonly delayMs: number } + | { readonly type: "cancel-aim" } + /** The first open lands beside its row at its list's height without a transition; later switches glide. */ + | { readonly type: "snap-open" } + | { readonly type: "refresh"; readonly service: Service } + | { readonly type: "focus-pane"; readonly service: Service } + /** Runs before the state commits, so focus leaves the list before it goes inert. */ + | { readonly type: "focus-row"; readonly service: Service } + +export type FlyoutTransition = { readonly state: FlyoutState; readonly effects: readonly FlyoutEffect[] } + +const NO_ANCHOR: FlyoutAnchor = { row: 0, above: 0, below: 0 } + +export const initialFlyoutState: FlyoutState = { status: "closed", pane: undefined, anchor: NO_ANCHOR, issued: 0 } + +const NONE: readonly FlyoutEffect[] = [] + +const CANCEL_AIM: readonly FlyoutEffect[] = [{ type: "cancel-aim" }] + +type Opened = Extract + +export function transitionFlyout(state: FlyoutState, event: FlyoutEvent): FlyoutTransition { + if (state.status === "disposed") return { state, effects: NONE } + + if (event.type === "disposed") + return { state: { status: "disposed" }, effects: state.status === "aiming" ? CANCEL_AIM : NONE } + + if (state.status === "closed") return opening(state, event) + + if (event.type === "hidden") return close(state, NONE) + + if (event.type === "close") + return close(state, event.focusRow ? [{ type: "focus-row", service: state.service }] : NONE) + + if (event.type === "aim.cancelled") return settle(state) + + if (event.type === "remeasured") { + if (!event.anchor || sameAnchor(state.anchor, event.anchor)) return { state, effects: NONE } + + return { state: { ...state, anchor: event.anchor }, effects: NONE } + } + + if (event.type === "aim.due") { + if (state.status !== "aiming" || event.attempt !== state.attempt) return { state, effects: NONE } + + return event.anchor ? show(state, state.target, event.anchor, false) : settle(state) + } + + if (event.type === "row.entered") return { state, effects: NONE } + + if (event.type === "row.activated") { + if (!event.shown || !event.anchor) return settle(state) + + return show(state, event.service, event.anchor, event.focus) + } + + if (!event.service || event.service === state.service) return settle(state) + + if (event.aiming) return aim(state, event.service) + + return event.anchor ? show(state, event.service, event.anchor, false) : settle(state) +} + +/** The open flyout, or undefined while it is closed. */ +export function flyoutActive(state: FlyoutState) { + return state.status === "open" || state.status === "aiming" ? state.service : undefined +} + +/** The list on show, kept while the flyout fades out. */ +export function flyoutPane(state: FlyoutState) { + if (state.status === "disposed") return undefined + + return state.status === "closed" ? state.pane : state.service +} + +export function flyoutAnchor(state: FlyoutState) { + return state.status === "disposed" ? NO_ANCHOR : state.anchor +} + +export function sameAnchor(a: FlyoutAnchor, b: FlyoutAnchor) { + return a.row === b.row && a.above === b.above && a.below === b.below +} + +function opening(state: Extract, event: FlyoutEvent): FlyoutTransition { + if (event.type !== "row.entered" && event.type !== "row.activated") return { state, effects: NONE } + + if (!event.shown || !event.anchor) return { state, effects: NONE } + const focus = event.type === "row.activated" && event.focus + + return { + state: { + status: "open", + service: event.service, + anchor: event.anchor, + refreshed: [event.service], + issued: state.issued, + }, + effects: [ + { type: "refresh", service: event.service }, + { type: "snap-open" }, + ...(focus ? [{ type: "focus-pane", service: event.service } as const] : []), + ], + } +} + +function show(state: Opened, service: Service, anchor: FlyoutAnchor, focus: boolean): FlyoutTransition { + const fresh = !state.refreshed.includes(service) + + const effects: readonly FlyoutEffect[] = [ + ...(state.status === "aiming" ? CANCEL_AIM : NONE), + ...(fresh ? [{ type: "refresh", service } as const] : []), + ...(focus ? [{ type: "focus-pane", service } as const] : []), + ] + + if (state.status === "open" && state.service === service && sameAnchor(state.anchor, anchor)) + return { state, effects } + + return { + state: { + status: "open", + service, + anchor, + refreshed: fresh ? [...state.refreshed, service] : state.refreshed, + issued: issued(state), + }, + effects, + } +} + +// Each move keeps the pointer's aim alive for another timeout; a new target takes a new attempt. +function aim(state: Opened, target: Service): FlyoutTransition { + if (state.status === "aiming" && state.target === target) + return { state, effects: [{ type: "schedule-aim", attempt: state.attempt, target, delayMs: AIM_TIMEOUT_MS }] } + const attempt = issued(state) + 1 + + return { + state: { + status: "aiming", + service: state.service, + target, + attempt, + anchor: state.anchor, + refreshed: state.refreshed, + }, + effects: [{ type: "schedule-aim", attempt, target, delayMs: AIM_TIMEOUT_MS }], + } +} + +// The pointer gave up its aim: the list on show stays. +function settle(state: Opened): FlyoutTransition { + if (state.status === "open") return { state, effects: NONE } + + return { + state: { + status: "open", + service: state.service, + anchor: state.anchor, + refreshed: state.refreshed, + issued: state.attempt, + }, + effects: CANCEL_AIM, + } +} + +function close(state: Opened, effects: readonly FlyoutEffect[]): FlyoutTransition { + return { + state: { status: "closed", pane: state.service, anchor: state.anchor, issued: issued(state) }, + effects: [...(state.status === "aiming" ? CANCEL_AIM : NONE), ...effects], + } +} + +function issued(state: Opened) { + return state.status === "aiming" ? state.attempt : state.issued +} diff --git a/packages/gui-plugins/src/details/i18n/en.ts b/packages/gui-plugins/src/details/i18n/en.ts index d32faad7644..9b2969a4746 100644 --- a/packages/gui-plugins/src/details/i18n/en.ts +++ b/packages/gui-plugins/src/details/i18n/en.ts @@ -21,6 +21,7 @@ export default { configure: "Configuration file", copyConfigPath: "Copy configuration file path", configFileMissing: "No configuration file found", + timedOut: "The server took too long to respond", "setup.mcp": "Add a server with OpenCode", "setup.mcp.prompt": "Help me add an MCP server to my global OpenCode config. Ask me which service I want to connect, then set it up and check that it connects.", @@ -59,5 +60,6 @@ export default { "mcp.error.copy": "Copy details", "mcp.error.copyFailed": "Couldn't copy error details", "mcp.error.disable": "Disable", + "mcp.timedOut": "{{name}} took too long to respond", "mcp.error.details": "MCP server: {{name}}\nStatus: failed\nConfiguration: mcp.servers.{{name}}\nError: {{error}}", } diff --git a/packages/gui-plugins/src/details/mcp-machine.test.ts b/packages/gui-plugins/src/details/mcp-machine.test.ts new file mode 100644 index 00000000000..851e236380f --- /dev/null +++ b/packages/gui-plugins/src/details/mcp-machine.test.ts @@ -0,0 +1,315 @@ +import { describe, expect, test } from "bun:test" +import { + MCP_TOGGLE_TIMEOUT_MS, + initialMcpState, + mcpDialogView, + mcpRowView, + transitionMcp, + type McpEvent, + type McpState, + type McpTransition, +} from "./mcp-machine" + +// The state once a popover lists the servers, as every controller starts. +const mounted = transitionMcp(initialMcpState, { type: "mounted" }).state + +// Folds the events in order and returns the last transition. +const replay = (events: readonly McpEvent[], state: McpState = mounted) => + events.reduce((last, event) => transitionMcp(last.state, event), { state, effects: [] }) + +const toggle = ( + name: string, + enabled: boolean, + status: "connected" | "disabled" | "failed" = "connected", +): McpEvent => ({ + type: "toggle.requested", + name, + enabled, + status, +}) + +const opened: McpEvent = { type: "error.opened", name: "playwright", error: "Connection refused" } + +describe("transitionMcp", () => { + test("toggling one server leaves every other row free to toggle", () => { + const figma = transitionMcp(mounted, toggle("figma", false)) + + expect(figma.effects).toEqual([ + { type: "run-toggle", name: "figma", attempt: 1, enabled: false, timeoutMs: MCP_TOGGLE_TIMEOUT_MS }, + ]) + expect(mcpRowView(figma.state, "figma", "connected")).toEqual({ busy: true, pending: true }) + expect(mcpRowView(figma.state, "off", "disabled")).toEqual({ busy: false, pending: false }) + + const off = transitionMcp(figma.state, toggle("off", true, "disabled")) + + expect(off.effects).toEqual([ + { type: "run-toggle", name: "off", attempt: 2, enabled: true, timeoutMs: MCP_TOGGLE_TIMEOUT_MS }, + ]) + + const settled = transitionMcp(off.state, { type: "toggle.succeeded", name: "off", attempt: 2 }) + + expect(settled.effects).toEqual([{ type: "abort-toggle", attempt: 2 }]) + expect(mcpRowView(settled.state, "off", "connected").busy).toBe(false) + expect(mcpRowView(settled.state, "figma", "connected").busy).toBe(true) + }) + + test("the row and the error dialog share one toggle per server", () => { + const retrying = replay([opened, toggle("playwright", true, "failed")]) + + expect(retrying.effects).toEqual([ + { type: "run-toggle", name: "playwright", attempt: 2, enabled: true, timeoutMs: MCP_TOGGLE_TIMEOUT_MS }, + ]) + + const disable = transitionMcp(retrying.state, toggle("playwright", false, "failed")) + + expect(disable).toEqual({ state: retrying.state, effects: [] }) + }) + + test("a server that is still connecting takes no toggle", () => { + const result = transitionMcp(mounted, { + type: "toggle.requested", + name: "waiting", + enabled: false, + status: "pending", + }) + + expect(result).toEqual({ state: mounted, effects: [] }) + expect(mcpRowView(mounted, "waiting", "pending")).toEqual({ busy: false, pending: true }) + }) + + test("the error dialog stays open while a retry connects and shows the retry's new failure", () => { + const retrying = replay([opened, toggle("playwright", true, "failed")]) + + const pending = transitionMcp(retrying.state, { + type: "server.synced", + attempt: 1, + loaded: true, + status: { status: "pending" }, + }) + + expect(pending.effects).toEqual([]) + expect(mcpDialogView(pending.state, 1, "pending")).toEqual({ + name: "playwright", + error: "Connection refused", + copied: false, + busy: true, + }) + + const failed = replay( + [ + { + type: "server.synced", + attempt: 1, + loaded: true, + status: { status: "failed", error: "Port 9222 unreachable" }, + }, + { type: "toggle.failed", name: "playwright", attempt: 2, error: "Port 9222 unreachable", server: true }, + ], + pending.state, + ) + + // The dialog shows the failure, so no toast repeats it. + expect(failed.effects).toEqual([{ type: "abort-toggle", attempt: 2 }]) + expect(mcpDialogView(failed.state, 1, "failed")).toEqual({ + name: "playwright", + error: "Port 9222 unreachable", + copied: false, + busy: false, + }) + + const connected = replay( + [ + toggle("playwright", true, "failed"), + { type: "server.synced", attempt: 1, loaded: true, status: { status: "connected" } }, + ], + failed.state, + ) + + expect(connected.effects).toEqual([{ type: "close-dialog", attempt: 1 }]) + expect(mcpDialogView(connected.state, 1, "connected")).toBeUndefined() + }) + + test("a retry that succeeds closes the dialog even when the server list did not change", () => { + const result = replay([ + opened, + toggle("playwright", true, "failed"), + { type: "toggle.succeeded", name: "playwright", attempt: 2 }, + ]) + + expect(result.effects).toEqual([ + { type: "abort-toggle", attempt: 2 }, + { type: "close-dialog", attempt: 1 }, + ]) + }) + + test("a request that throws shows a toast and keeps the dialog's server error", () => { + const result = replay([ + opened, + toggle("playwright", true, "failed"), + { type: "toggle.failed", name: "playwright", attempt: 2, error: "Network error", server: false }, + ]) + + expect(result.effects).toEqual([ + { type: "abort-toggle", attempt: 2 }, + { type: "toast-failed", message: "Network error" }, + ]) + expect(mcpDialogView(result.state, 1, "failed")?.error).toBe("Connection refused") + }) + + test("a failed status without a dialog shows a toast that names the server", () => { + const result = replay([ + toggle("figma", true, "disabled"), + { type: "toggle.failed", name: "figma", attempt: 1, error: "404 Not Found", server: true }, + ]) + + expect(result.effects).toEqual([ + { type: "abort-toggle", attempt: 1 }, + { type: "toast-failed", message: "figma: 404 Not Found" }, + ]) + }) + + test("the server list decides when the dialog closes", () => { + const open = transitionMcp(mounted, opened).state + + expect(open).toMatchObject({ dialog: { status: "open", attempt: 1 } }) + + for (const status of [ + { status: "needs_auth", error: "Sign in" }, + { status: "failed", error: "Connection refused" }, + ] as const) + expect(transitionMcp(open, { type: "server.synced", attempt: 1, loaded: true, status }).state).toBe(open) + + expect(transitionMcp(open, { type: "server.synced", attempt: 1, loaded: false, status: undefined }).state).toBe( + open, + ) + + for (const status of [{ status: "disabled" }, undefined] as const) { + const result = transitionMcp(open, { type: "server.synced", attempt: 1, loaded: true, status }) + + expect(result.effects).toEqual([{ type: "close-dialog", attempt: 1 }]) + expect(mcpDialogView(result.state, 1, status?.status)).toBeUndefined() + } + }) + + test("a sign-in hands over from the dialog to the browser before the resources refresh", () => { + const result = replay([ + opened, + toggle("playwright", true, "failed"), + { + type: "toggle.authorizing", + name: "playwright", + attempt: 2, + url: "https://auth.example/authorize", + signIn: { integrationID: "oauth", attemptID: "a1", url: "https://auth.example/authorize", lifetime: 60_000 }, + }, + ]) + + expect(result.effects).toEqual([ + { type: "close-dialog", attempt: 1 }, + { type: "open-external", url: "https://auth.example/authorize" }, + { + type: "open-sign-in", + name: "playwright", + signIn: { integrationID: "oauth", attemptID: "a1", url: "https://auth.example/authorize", lifetime: 60_000 }, + }, + ]) + expect(mcpRowView(result.state, "playwright", "needs_auth").busy).toBe(true) + }) + + test("results of an attempt that ended change nothing", () => { + const timedOut = replay([toggle("figma", false), { type: "toggle.timed-out", name: "figma", attempt: 1 }]) + + expect(timedOut.effects).toEqual([ + { type: "abort-toggle", attempt: 1 }, + { type: "toast-timed-out", name: "figma" }, + ]) + + for (const event of [ + { type: "toggle.succeeded", name: "figma", attempt: 1 }, + { type: "toggle.failed", name: "figma", attempt: 1, error: "late", server: false }, + { type: "toggle.authorizing", name: "figma", attempt: 1, url: "https://auth.example", signIn: undefined }, + ] satisfies McpEvent[]) + expect(transitionMcp(timedOut.state, event)).toEqual({ state: timedOut.state, effects: [] }) + }) + + test("a closed or replaced dialog ignores its late events", () => { + const first = transitionMcp(mounted, opened).state + const second = transitionMcp(first, { type: "error.opened", name: "figma", error: "Timeout" }) + + expect(second.effects).toEqual([ + { type: "close-dialog", attempt: 1 }, + { type: "open-dialog", attempt: 2, name: "figma" }, + ]) + + for (const event of [ + { type: "error.dismissed", attempt: 1 }, + { type: "error.copied", attempt: 1, error: "Connection refused" }, + { type: "server.synced", attempt: 1, loaded: true, status: { status: "connected" } }, + ] satisfies McpEvent[]) + expect(transitionMcp(second.state, event).state).toBe(second.state) + }) + + test("the copied mark follows the error text it copied", () => { + const copied = replay([opened, { type: "error.copied", attempt: 1, error: "Connection refused" }]) + + expect(mcpDialogView(copied.state, 1, "failed")?.copied).toBe(true) + + const changed = transitionMcp(copied.state, { + type: "server.synced", + attempt: 1, + loaded: true, + status: { status: "failed", error: "Port 9222 unreachable" }, + }) + + expect(mcpDialogView(changed.state, 1, "failed")).toMatchObject({ error: "Port 9222 unreachable", copied: false }) + }) + + test("a popover that closes and reopens keeps the toggle its dialog's retry started", () => { + const retrying = replay([opened, toggle("playwright", true, "failed"), { type: "error.dismissed", attempt: 1 }]) + const reopened = replay([{ type: "unmounted" }, { type: "mounted" }], retrying.state) + + expect(reopened.state).toMatchObject({ status: "active", mounts: 1, toggles: [{ name: "playwright", attempt: 2 }] }) + expect(mcpRowView(reopened.state, "playwright", "failed")).toEqual({ busy: true, pending: true }) + + // The reopened row and a dialog opened again cannot start a second connect for the same server. + const again = replay([opened, toggle("playwright", true, "failed")], reopened.state) + + expect(again.effects).toEqual([]) + expect(mcpDialogView(again.state, 3, "failed")?.busy).toBe(true) + expect(transitionMcp(reopened.state, toggle("playwright", false, "failed")).state).toBe(reopened.state) + }) + + test("a list ends once no popover lists it, no toggle runs and no dialog shows", () => { + const closed = replay([toggle("figma", false), opened, { type: "unmounted" }]) + + expect(closed.state).toMatchObject({ status: "active", mounts: 0 }) + + const settled = transitionMcp(closed.state, { type: "toggle.succeeded", name: "figma", attempt: 1 }) + + expect(settled.state).toMatchObject({ status: "active", mounts: 0 }) + + const dismissed = transitionMcp(settled.state, { type: "error.dismissed", attempt: 2 }) + + expect(dismissed.state).toEqual({ status: "disposed" }) + expect(transitionMcp(mounted, { type: "unmounted" }).state).toEqual({ status: "disposed" }) + + // A second popover or drawer keeps it while the first one closes. + const both = transitionMcp(mounted, { type: "mounted" }).state + + expect(transitionMcp(both, { type: "unmounted" }).state).toMatchObject({ status: "active", mounts: 1 }) + }) + + test("disposal aborts every toggle and closes the dialog", () => { + const result = replay([toggle("figma", false), toggle("off", true, "disabled"), opened, { type: "disposed" }]) + + expect(result).toEqual({ + state: { status: "disposed" }, + effects: [ + { type: "abort-toggle", attempt: 1 }, + { type: "abort-toggle", attempt: 2 }, + { type: "close-dialog", attempt: 3 }, + ], + }) + expect(transitionMcp(result.state, toggle("figma", true)).state).toBe(result.state) + }) +}) diff --git a/packages/gui-plugins/src/details/mcp-machine.ts b/packages/gui-plugins/src/details/mcp-machine.ts new file mode 100644 index 00000000000..9c29cb78520 --- /dev/null +++ b/packages/gui-plugins/src/details/mcp-machine.ts @@ -0,0 +1,278 @@ +/** How long one connect, disconnect or sign-in may run before it gives up with an error. */ +export const MCP_TOGGLE_TIMEOUT_MS = 60_000 + +/** An MCP server's status, as the server lists it. */ +export type McpServerStatus = + | { readonly status: "connected" | "pending" | "disabled" } + | { readonly status: "failed" | "needs_auth"; readonly error: string } + +/** A sign-in that also accepts the redirect URL pasted from the browser. */ +export type McpSignIn = { + readonly integrationID: string + readonly attemptID: string + readonly url: string + /** The attempt's lifetime in milliseconds. */ + readonly lifetime: number +} + +/** One server's connect, disconnect or sign-in in flight. */ +export type McpToggle = { readonly name: string; readonly attempt: number } + +export type McpErrorDialog = + | { readonly status: "closed" } + /** + * One server's failure. `error` is its latest failure, kept while a retry runs; `copied` is the error text the user + * last copied. + */ + | { + readonly status: "open" + readonly attempt: number + readonly name: string + readonly error: string + readonly copied: string | undefined + } + +/** + * The MCP list of one server and directory: its toggles in flight and its error dialog, shared by every popover or + * drawer that lists it. It lives while one is mounted, a toggle runs or the dialog shows. Toggles and dialogs take + * attempt numbers from `issued`, so a result whose attempt the state no longer holds is stale. + */ +export type McpState = + | { + readonly status: "active" + /** The popovers and drawers that list the servers. */ + readonly mounts: number + readonly issued: number + readonly toggles: readonly McpToggle[] + readonly dialog: McpErrorDialog + } + | { readonly status: "disposed" } + +export type McpEvent = + /** A row's switch or sign-in button, or the error dialog's Disable or Try again. */ + | { + readonly type: "toggle.requested" + readonly name: string + readonly enabled: boolean + readonly status: McpServerStatus["status"] | undefined + } + /** The server started an OAuth sign-in; the toggle goes on to refresh the server's resources. */ + | { + readonly type: "toggle.authorizing" + readonly name: string + readonly attempt: number + readonly url: string + readonly signIn: McpSignIn | undefined + } + | { readonly type: "toggle.succeeded"; readonly name: string; readonly attempt: number } + /** `server` is true when the refreshed status failed, false when a request threw. */ + | { + readonly type: "toggle.failed" + readonly name: string + readonly attempt: number + readonly error: string + readonly server: boolean + } + | { readonly type: "toggle.timed-out"; readonly name: string; readonly attempt: number } + | { readonly type: "error.opened"; readonly name: string; readonly error: string } + /** The dialog closed, by the user or by the machine. */ + | { readonly type: "error.dismissed"; readonly attempt: number } + | { readonly type: "error.copied"; readonly attempt: number; readonly error: string } + /** The dialog's server changed in the server's list. `loaded` is false while the list is not known. */ + | { + readonly type: "server.synced" + readonly attempt: number + readonly loaded: boolean + readonly status: McpServerStatus | undefined + } + /** A popover or drawer that lists the servers mounted or unmounted. */ + | { readonly type: "mounted" } + | { readonly type: "unmounted" } + | { readonly type: "disposed" } + +export type McpEffect = + /** Starts the attempt's controller and timeout, then runs the toggle. */ + | { + readonly type: "run-toggle" + readonly name: string + readonly attempt: number + readonly enabled: boolean + readonly timeoutMs: number + } + /** Ends the attempt's controller and timeout. */ + | { readonly type: "abort-toggle"; readonly attempt: number } + | { readonly type: "open-external"; readonly url: string } + | { readonly type: "open-sign-in"; readonly name: string; readonly signIn: McpSignIn } + | { readonly type: "open-dialog"; readonly attempt: number; readonly name: string } + | { readonly type: "close-dialog"; readonly attempt: number } + | { readonly type: "toast-failed"; readonly message: string } + | { readonly type: "toast-timed-out"; readonly name: string } + +export type McpTransition = { readonly state: McpState; readonly effects: readonly McpEffect[] } + +export const initialMcpState: McpState = { + status: "active", + mounts: 0, + issued: 0, + toggles: [], + dialog: { status: "closed" }, +} + +const NONE: readonly McpEffect[] = [] + +const CLOSED: McpErrorDialog = { status: "closed" } + +type Live = Exclude + +export function transitionMcp(state: McpState, event: McpEvent): McpTransition { + if (state.status === "disposed") return { state, effects: NONE } + + if (event.type === "disposed") + return { + state: { status: "disposed" }, + effects: [ + ...state.toggles.map((toggle): McpEffect => ({ type: "abort-toggle", attempt: toggle.attempt })), + ...closeDialog(state.dialog), + ], + } + + return release(step(state, event)) +} + +/** What a row shows: `busy` while its own toggle runs, `pending` while it takes no new toggle. */ +export function mcpRowView(state: McpState, name: string, status: McpServerStatus["status"]) { + const busy = toggling(state, name) + + return { busy, pending: busy || status === "pending" } +} + +/** What an open error dialog shows, or undefined once it closed. */ +export function mcpDialogView(state: McpState, attempt: number, status: McpServerStatus["status"] | undefined) { + if (state.status === "disposed" || state.dialog.status !== "open" || state.dialog.attempt !== attempt) return + + return { + name: state.dialog.name, + error: state.dialog.error, + copied: state.dialog.copied === state.dialog.error, + busy: toggling(state, state.dialog.name) || status === "pending", + } +} + +function step(state: Live, event: Exclude): McpTransition { + if (event.type === "mounted") return { state: { ...state, mounts: state.mounts + 1 }, effects: NONE } + + if (event.type === "unmounted") return { state: { ...state, mounts: Math.max(0, state.mounts - 1) }, effects: NONE } + + if (event.type === "toggle.requested") { + // One toggle per server at a time, from its row and its dialog alike. + if (toggling(state, event.name) || event.status === "pending") return { state, effects: NONE } + const attempt = state.issued + 1 + + return { + state: { ...state, issued: attempt, toggles: [...state.toggles, { name: event.name, attempt }] }, + effects: [ + { type: "run-toggle", name: event.name, attempt, enabled: event.enabled, timeoutMs: MCP_TOGGLE_TIMEOUT_MS }, + ], + } + } + + if ( + event.type === "toggle.authorizing" || + event.type === "toggle.succeeded" || + event.type === "toggle.failed" || + event.type === "toggle.timed-out" + ) + return settled(state, event) + + if (event.type === "error.opened") { + const attempt = state.issued + 1 + + return { + state: { + ...state, + issued: attempt, + dialog: { status: "open", attempt, name: event.name, error: event.error, copied: undefined }, + }, + effects: [...closeDialog(state.dialog), { type: "open-dialog", attempt, name: event.name }], + } + } + + const dialog = state.dialog + + if (dialog.status !== "open" || dialog.attempt !== event.attempt) return { state, effects: NONE } + + if (event.type === "error.dismissed") return { state: { ...state, dialog: CLOSED }, effects: NONE } + + if (event.type === "error.copied") + return { state: { ...state, dialog: { ...dialog, copied: event.error } }, effects: NONE } + + if (!event.loaded) return { state, effects: NONE } + const status = event.status + + // A reconnect, a disable or a removal, here or elsewhere, leaves nothing to show. + if (!status || status.status === "connected" || status.status === "disabled") + return { state: { ...state, dialog: CLOSED }, effects: closeDialog(dialog) } + + // A retry stays open while it connects, and a new failure replaces the error in place. + if (status.status !== "failed" || status.error === dialog.error) return { state, effects: NONE } + + return { state: { ...state, dialog: { ...dialog, error: status.error } }, effects: NONE } +} + +function settled( + state: Live, + event: Extract, +): McpTransition { + if (!state.toggles.some((toggle) => toggle.name === event.name && toggle.attempt === event.attempt)) + return { state, effects: NONE } + const dialog = state.dialog + const shown = dialog.status === "open" && dialog.name === event.name + + // The browser takes over from the dialog; the toggle still refreshes the server's resources. + if (event.type === "toggle.authorizing") + return { + state: shown ? { ...state, dialog: CLOSED } : state, + effects: [ + ...(shown ? closeDialog(dialog) : NONE), + { type: "open-external", url: event.url }, + ...(event.signIn ? [{ type: "open-sign-in", name: event.name, signIn: event.signIn } as const] : []), + ], + } + + const next = { ...state, toggles: state.toggles.filter((toggle) => toggle.attempt !== event.attempt) } + const abort: McpEffect = { type: "abort-toggle", attempt: event.attempt } + + if (event.type === "toggle.succeeded") + return shown + ? { state: { ...next, dialog: CLOSED }, effects: [abort, ...closeDialog(dialog)] } + : { state: next, effects: [abort] } + + if (event.type === "toggle.timed-out") + return { state: next, effects: [abort, { type: "toast-timed-out", name: event.name }] } + + // The open dialog shows the server's new failure itself. + if (shown && event.server) return { state: { ...next, dialog: { ...dialog, error: event.error } }, effects: [abort] } + + return { + state: next, + effects: [abort, { type: "toast-failed", message: event.server ? `${event.name}: ${event.error}` : event.error }], + } +} + +// The list ends once nothing uses it: no popover or drawer lists it, no toggle runs and no dialog shows. +function release(transition: McpTransition): McpTransition { + const state = transition.state + + if (state.status !== "active" || state.mounts > 0 || state.toggles.length > 0 || state.dialog.status === "open") + return transition + + return { state: { status: "disposed" }, effects: transition.effects } +} + +function closeDialog(dialog: McpErrorDialog): readonly McpEffect[] { + return dialog.status === "open" ? [{ type: "close-dialog", attempt: dialog.attempt }] : NONE +} + +function toggling(state: McpState, name: string) { + return state.status !== "disposed" && state.toggles.some((toggle) => toggle.name === name) +} diff --git a/packages/gui-plugins/src/details/panel.tsx b/packages/gui-plugins/src/details/panel.tsx index 44015fca50e..67bb9458963 100644 --- a/packages/gui-plugins/src/details/panel.tsx +++ b/packages/gui-plugins/src/details/panel.tsx @@ -1,10 +1,12 @@ import type { MountedSession } from "@opencode/plugin/gui" -import { SessionServerPanel } from "./server-panel" +import { SessionServerPanel, type McpControllers } from "./server-panel" export type DetailsPanelProps = { session: MountedSession shown?: boolean mobile?: boolean + /** The plugin instance's MCP controllers, which outlive each panel. */ + mcp: McpControllers /** Closes the popover that shows the panel, once an action opened something beside it. */ onClose?: () => void } @@ -17,6 +19,7 @@ export default function SessionDetailsPanel(props: DetailsPanelProps) { directory={props.session.directory} shown={props.shown !== false} mobile={props.mobile} + mcp={props.mcp} onClose={props.onClose} /> diff --git a/packages/gui-plugins/src/details/popover.tsx b/packages/gui-plugins/src/details/popover.tsx index 2caea956d56..77df13a0411 100644 --- a/packages/gui-plugins/src/details/popover.tsx +++ b/packages/gui-plugins/src/details/popover.tsx @@ -6,6 +6,7 @@ import { Tooltip } from "@opencode/ui/tooltip" import { onCleanup, Show, Suspense, type Component, type ParentProps } from "solid-js" import { Command, createVisitState, usePlugin, type MountedSession } from "@opencode/plugin/gui" import type { DetailsPanelProps } from "./panel" +import type { McpControllers } from "./server-panel" /** Every mounted details popover, so a shortcut finds the one on screen. */ export type DetailsMenus = Set<{ trigger: () => HTMLButtonElement | undefined; toggle: () => void }> @@ -16,6 +17,7 @@ export function DetailsHeader(props: { session: MountedSession active: boolean panel: Component + mcp: McpControllers }) { const Panel = props.panel // Cached timelines stay mounted while hidden; routing away from the session closes its details. @@ -25,7 +27,7 @@ export function DetailsHeader(props: { - setOpen(false)} /> + setOpen(false)} /> diff --git a/packages/gui-plugins/src/details/renderer.tsx b/packages/gui-plugins/src/details/renderer.tsx index c673533ac3d..cd6aaf353c7 100644 --- a/packages/gui-plugins/src/details/renderer.tsx +++ b/packages/gui-plugins/src/details/renderer.tsx @@ -3,11 +3,14 @@ import { Panel, Slot, Style, usePanel, type Plugin } from "@opencode/plugin/gui" import type Details from "./index" import { DetailsHeader, type DetailsMenus } from "./popover" import { BuiltinSlot, onIdle } from "@opencode/plugin/gui/builtin" +import type { McpControllers } from "./server-panel" const setup: Plugin.Setup = (ctx) => { const sessions = ctx.sessions const menus: DetailsMenus = new Set() + // MCP toggles and error dialogs outlive the popover or drawer that started them. + const mcp: McpControllers = new Map() const DetailsPanel = lazy(() => Promise.all([import("./panel"), import("./details.css?inline")]).then(([panel, css]) => { @@ -33,7 +36,7 @@ const setup: Plugin.Setup = (ctx) => { at: "session.header", order: 20, render: (input) => ( - + ), }) @@ -74,7 +77,7 @@ const setup: Plugin.Setup = (ctx) => { return ( - + ) diff --git a/packages/gui-plugins/src/details/server-panel.tsx b/packages/gui-plugins/src/details/server-panel.tsx index b900b924d2c..55e1bf9fdd3 100644 --- a/packages/gui-plugins/src/details/server-panel.tsx +++ b/packages/gui-plugins/src/details/server-panel.tsx @@ -10,7 +10,6 @@ import { TextInput } from "@opencode/ui/text-input" import { showToast } from "@opencode/ui/toast" import { Tooltip } from "@opencode/ui/tooltip" import { TruncatedText } from "@opencode/ui/truncated-text" -import { useMutation } from "@tanstack/solid-query" import { children, createMemo, @@ -19,26 +18,54 @@ import { createUniqueId, For, Index, - on, onCleanup, onMount, Show, + untrack, type Component, type JSX, } from "solid-js" import { createStore } from "solid-js/store" -import { createKeyed, useDrawer, usePlugin, type MountedSession } from "@opencode/plugin/gui" +import { createKeyed, useDrawer, usePlugin, type MountedSession, type ServerRef } from "@opencode/plugin/gui" import { globalConfigDirectory, serviceConfigFile } from "./config-file" import { builtinContext } from "@opencode/plugin/gui/builtin" import { createFlyoutMotion } from "./flyout-motion" +import { + configActionView, + initialConfigActionState, + transitionConfigAction, + type ConfigActionEffect, + type ConfigActionEvent, + type ConfigActionState, +} from "./config-action-machine" +import { + flyoutActive, + flyoutAnchor, + flyoutPane, + initialFlyoutState, + sameAnchor, + transitionFlyout, + type FlyoutAnchor, + type FlyoutEvent, + type FlyoutState, + type Service, +} from "./flyout-machine" +import { + initialMcpState, + mcpDialogView, + mcpRowView, + transitionMcp, + type McpEffect, + type McpEvent, + type McpServerStatus, + type McpState, +} from "./mcp-machine" const services = [ { type: "mcp", icon: "mcp", label: "mcp" }, { type: "plugins", icon: "cube", label: "plugins" }, { type: "skills", icon: "graduation-cap", label: "skills" }, -] as const - -type Service = (typeof services)[number]["type"] +] as const satisfies readonly { type: Service; icon: string; label: string }[] type ServiceProps = { session: MountedSession @@ -61,10 +88,7 @@ type ServiceSource = { Footer: Component } -// How long a pointer may rest inside the safe triangle before the row under it takes over. -const AIM_TIMEOUT = 100 - -export function SessionServerPanel(props: ServiceProps & { mobile?: boolean }) { +export function SessionServerPanel(props: ServiceProps & { mobile?: boolean; mcp: McpControllers }) { const ctx = usePlugin() const name = () => (ctx.servers.list().length < 2 ? ctx.t("server") : props.session.server.name) @@ -79,14 +103,18 @@ export function SessionServerPanel(props: ServiceProps & { mobile?: boolean }) { } > {(directory) => ( - + // Another server starts its lists and flyout afresh. + + + )} ) @@ -102,47 +130,39 @@ function ServerHeading(props: { name: string }) { ) } -function ServiceMenu(props: ServiceProps & { mobile?: boolean; name: string }) { +function ServiceMenu(props: ServiceProps & { mobile?: boolean; name: string; mcp: McpControllers }) { const ctx = usePlugin() const drawer = useDrawer() const id = createUniqueId() const motion = createFlyoutMotion() - // A new scope whenever visibility changes closes the flyout. - const scope = createMemo( - on( - () => props.shown, - () => ({}), - ), - ) + const [flyoutState, setFlyoutState] = createSignal(initialFlyoutState) - // A signal, not a store field: a store would wrap the scope object and never match it. - const [open, setOpen] = createSignal<{ readonly scope: object; readonly service: Service }>() - - const [menu, setMenu] = createStore<{ - // The pane on show, kept through the flyout's exit so it fades out with its list. - pane: Service | undefined - // Where the trigger row sits in the flyout's containing block, and the room around it in the viewport. - anchor: { row: number; above: number; below: number } + // Each list's measured height, and whether it scrolls. + const [sizes, setSizes] = createStore<{ heights: Partial> overflow: Partial> - }>({ pane: undefined, anchor: { row: 0, above: 0, below: 0 }, heights: {}, overflow: {} }) + }>({ heights: {}, overflow: {} }) const sources: Record = { - mcp: useMcp(props, () => close()), + mcp: useMcp(props, props.mcp, () => dispatch({ type: "close", focusRow: false })), plugins: useCatalog(props, "plugins"), skills: useCatalog(props, "skills"), } - const active = () => { - const current = open() + // Memos, so a pointer aiming across rows, which replaces the state on each new target, rewrites nothing on screen. + const active = createMemo(() => flyoutActive(flyoutState())) + const pane = createMemo(() => flyoutPane(flyoutState())) + const anchor = createMemo(() => flyoutAnchor(flyoutState()), undefined, { equals: sameAnchor }) - return current?.scope === scope() ? current.service : undefined + const height = () => { + const current = pane() + + return (current ? (sizes.heights[current] ?? 0) : 0) + 4 } - const height = () => (menu.pane ? (menu.heights[menu.pane] ?? 0) : 0) + 4 // Beside its row, kept inside the viewport. - const offset = () => Math.max(-menu.anchor.above, Math.min(menu.anchor.row - 2, menu.anchor.below - height())) + const offset = () => Math.max(-anchor().above, Math.min(anchor().row - 2, anchor().below - height())) const rows: Partial> = {} const panes: Partial> = {} @@ -152,76 +172,75 @@ function ServiceMenu(props: ServiceProps & { mobile?: boolean; name: string }) { // The flyout's containing block in the viewport, measured when a list opens and on scroll or resize, so pointer // moves never read layout. const bounds = { left: 0, right: 0, top: 0 } - // Each list refreshes the first time it shows after the flyout opens. - const refreshed = new Set() // The two latest pointer positions at least 2px apart, which give the pointer's heading. const trail = { x: 0, y: 0, px: 0, py: 0 } - let pending: ReturnType | undefined - onCleanup(() => clearTimeout(pending)) + let aimTimer: ReturnType | undefined - // Places the flyout beside a row: where the row sits in the containing block, and the room around it. - const measure = (service: Service) => { + // Places the flyout beside a row: where the row sits in the containing block, and the room around it. Undefined + // while the flyout or the row is not laid out. + const measure = (service: Service): FlyoutAnchor | undefined => { const row = rows[service] const box = flyout?.offsetParent - if (!row || !box) return false + if (!row || !box || !surface) return const base = box.getBoundingClientRect() bounds.left = base.left bounds.right = base.right bounds.top = base.top - setMenu("anchor", { + + return { row: row.getBoundingClientRect().top - base.top, above: base.top - 16, below: window.innerHeight - 16 - base.top, - }) - - return true - } - - const activate = (service: Service, focus = false) => { - clearTimeout(pending) - - if (!flyout || !surface) return - const opening = active() === undefined - - if (!refreshed.has(service)) { - refreshed.add(service) - - if (!sources[service].loading) sources[service].retry() - } - - // The first open lands beside its row at its list's height; later switches glide and resize. - if (opening) { - flyout.style.transition = "none" - surface.style.transition = "none" - } - - if (!measure(service)) return - setOpen({ scope: scope(), service }) - setMenu("pane", service) - - if (opening) { - void flyout.offsetHeight - flyout.style.removeProperty("transition") - surface.style.removeProperty("transition") - } - - if (focus) { - const pane = panes[service] - - if (pane) (focusables(pane)[0] ?? pane).focus() } } - const close = (focus = false) => { - clearTimeout(pending) - const service = active() + const dispatch = (event: FlyoutEvent) => { + const previous = untrack(flyoutState) + const next = transitionFlyout(previous, event) // Focus returns to the row before the list goes inert, so it never falls to the document. - if (focus && service) rows[service]?.focus() - refreshed.clear() - setOpen(undefined) + next.effects.forEach((effect) => { + if (effect.type === "focus-row") rows[effect.service]?.focus() + }) + + if (next.state !== previous) + commit( + next.state, + next.effects.some((effect) => effect.type === "snap-open"), + ) + + next.effects.forEach((effect) => { + if (effect.type === "schedule-aim") { + clearTimeout(aimTimer) + aimTimer = setTimeout( + () => dispatch({ type: "aim.due", attempt: effect.attempt, anchor: measure(effect.target) }), + effect.delayMs, + ) + } + + if (effect.type === "cancel-aim") clearTimeout(aimTimer) + + if (effect.type === "refresh" && !sources[effect.service].loading) sources[effect.service].retry() + + if (effect.type === "focus-pane") { + const element = panes[effect.service] + + if (element) (focusables(element)[0] ?? element).focus() + } + }) + } + + // The first open lands beside its row at its list's height; later switches glide and resize. + const commit = (state: FlyoutState, snap: boolean) => { + if (!snap || !flyout || !surface) return void setFlyoutState(state) + flyout.style.transition = "none" + surface.style.transition = "none" + setFlyoutState(state) + void flyout.offsetHeight + flyout.style.removeProperty("transition") + surface.style.removeProperty("transition") } // Moving between rows switches at once, except while the pointer heads for the open flyout across other rows. @@ -235,24 +254,28 @@ function ServiceMenu(props: ServiceProps & { mobile?: boolean; name: string }) { trail.y = event.clientY } + const current = active() + // A closed flyout opens when the pointer enters a row, so a pointer resting where Escape closed it stays put. - if (!active()) return + if (!current) return const target = event.target const service = target instanceof Node ? services.find((item) => rows[item.type]?.contains(target))?.type : undefined - if (!service || service === active()) return clearTimeout(pending) + const heading = !!service && service !== current && aiming(event) - if (!aiming(event)) return activate(service) - clearTimeout(pending) - pending = setTimeout(() => activate(service), AIM_TIMEOUT) + dispatch({ + type: "row.moved", + service, + aiming: heading, + anchor: service && service !== current && !heading ? measure(service) : undefined, + }) } // Whether the pointer's last step points into the open flyout: inside the triangle from its previous position to // the flyout's near edge. const aiming = (event: PointerEvent) => { - if (!active()) return false // The flyout sits against the containing block's inline start, where it is heading rather than where it is. const edge = ctx.locale.direction() === "rtl" ? bounds.right : bounds.left const top = bounds.top + offset() @@ -277,38 +300,48 @@ function ServiceMenu(props: ServiceProps & { mobile?: boolean; name: string }) { if (row !== -1) { if (event.key === into) { event.preventDefault() - activate(services[row].type, true) + const service = services[row].type + dispatch({ type: "row.activated", service, focus: true, shown: props.shown, anchor: measure(service) }) } if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return event.preventDefault() const next = services[(row + (event.key === "ArrowDown" ? 1 : services.length - 1)) % services.length].type rows[next]?.focus() - - if (active()) activate(next) + // An open flyout follows the focused row. + dispatch({ type: "row.moved", service: next, aiming: false, anchor: active() ? measure(next) : undefined }) return } - const pane = menu.pane ? panes[menu.pane] : undefined + const current = pane() + const element = current ? panes[current] : undefined - if (!pane?.contains(target)) return + if (!element?.contains(target)) return if (event.key === back) { event.preventDefault() - close(true) + dispatch({ type: "close", focusRow: true }) return } if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return event.preventDefault() - const items = focusables(pane) + const items = focusables(element) const index = items.findIndex((item) => item === target || item.contains(target)) const step = event.key === "ArrowDown" ? 1 : -1 items[index === -1 ? 0 : (index + step + items.length) % items.length]?.focus() } + // Hiding the details closes the flyout, so a pending aim cannot reopen it and each list refreshes on the next open. + createKeyed( + () => props.shown, + () => undefined, + { otherwise: () => dispatch({ type: "hidden" }) }, + ) + onCleanup(() => dispatch({ type: "disposed" })) + // While a list is open: Escape closes only the flyout, before the details popover's own Escape handling sees it, // and scrolling or resizing measures the flyout's place again. createKeyed( @@ -317,7 +350,7 @@ function ServiceMenu(props: ServiceProps & { mobile?: boolean; name: string }) { const remeasure = () => { const service = active() - if (service) measure(service) + if (service) dispatch({ type: "remeasured", anchor: measure(service) }) } const escape = (event: KeyboardEvent) => { @@ -326,7 +359,7 @@ function ServiceMenu(props: ServiceProps & { mobile?: boolean; name: string }) { if (event.key !== "Escape" || !focused || !flyout?.offsetParent?.contains(focused)) return event.preventDefault() event.stopPropagation() - close(!!flyout?.contains(focused)) + dispatch({ type: "close", focusRow: !!flyout?.contains(focused) }) } document.addEventListener("keydown", escape, true) @@ -344,12 +377,12 @@ function ServiceMenu(props: ServiceProps & { mobile?: boolean; name: string }) { const observer = new ResizeObserver((entries) => entries.forEach((entry) => { const service = services.find((item) => panes[item.type]?.contains(entry.target))?.type - const pane = service ? panes[service] : undefined + const element = service ? panes[service] : undefined const scroller = service ? scrollers[service] : undefined - if (!service || !pane || !scroller) return - setMenu("heights", service, pane.offsetHeight) - setMenu("overflow", service, scroller.scrollHeight > scroller.clientHeight + 1) + if (!service || !element || !scroller) return + setSizes("heights", service, element.offsetHeight) + setSizes("overflow", service, scroller.scrollHeight > scroller.clientHeight + 1) }), ) @@ -399,7 +432,11 @@ function ServiceMenu(props: ServiceProps & { mobile?: boolean; name: string }) { <>
-
clearTimeout(pending)}> +
dispatch({ type: "aim.cancelled" })} + > {(service) => { const source = sources[service.type] @@ -413,9 +450,23 @@ function ServiceMenu(props: ServiceProps & { mobile?: boolean; name: string }) { aria-expanded={active() === service.type} aria-controls={`${id}-${service.type}`} onPointerEnter={(event) => { - if (event.pointerType !== "touch" && active() === undefined) activate(service.type) + if (event.pointerType === "touch" || active() !== undefined) return + dispatch({ + type: "row.entered", + service: service.type, + shown: props.shown, + anchor: measure(service.type), + }) }} - onClick={(event) => activate(service.type, event.detail === 0)} + onClick={(event) => + dispatch({ + type: "row.activated", + service: service.type, + focus: event.detail === 0, + shown: props.shown, + anchor: measure(service.type), + }) + } > {ctx.t(service.label)} @@ -447,7 +498,7 @@ function ServiceMenu(props: ServiceProps & { mobile?: boolean; name: string }) { inert={active() === undefined || undefined} style={{ transform: `translateY(${offset()}px)` }} onKeyDown={keydown} - onPointerEnter={() => clearTimeout(pending)} + onPointerEnter={() => dispatch({ type: "aim.cancelled" })} >
@@ -468,9 +519,9 @@ function ServiceMenu(props: ServiceProps & { mobile?: boolean; name: string }) { aria-label={ctx.t(service.label)} aria-busy={source.loading} data-service={service.type} - data-active={menu.pane === service.type || undefined} - data-overflow={menu.overflow[service.type] || undefined} - inert={menu.pane !== service.type || undefined} + data-active={pane() === service.type || undefined} + data-overflow={sizes.overflow[service.type] || undefined} + inert={pane() !== service.type || undefined} > void): ServiceSource { +function useMcp(props: ServiceProps, controllers: McpControllers, close: () => void): ServiceSource { const ctx = usePlugin() const data = () => props.session.server.data - - const toggle = useMcpToggle(props.session, () => props.directory) + const mcp = useMcpController(controllers, props.session.server, props.directory) const [load, { refetch }] = createResource( () => props.shown && data(), @@ -517,11 +567,6 @@ function useMcp(props: ServiceProps, close: () => void): ServiceSource { ), ) - const showError = (name: string) => - ctx.dialogs.open((dialog) => ( - - )) - return { get loading() { return load.loading @@ -544,7 +589,9 @@ function useMcp(props: ServiceProps, close: () => void): ServiceSource { {(server) => { const enabled = () => server().status.status !== "disabled" - const pending = () => toggle.isPending || server().status.status === "pending" + const view = createMemo(() => mcpRowView(mcp.state(), server().name, server().status.status)) + const pending = () => view().pending + const busy = () => view().busy const failure = () => { const status = server().status @@ -553,7 +600,6 @@ function useMcp(props: ServiceProps, close: () => void): ServiceSource { } const signIn = () => server().status.status === "needs_auth" && !!server().integrationID - const busy = () => toggle.isPending && toggle.variables?.name === server().name // The dot shows the status; the words stay for assistive technology. const label = () => { @@ -568,13 +614,22 @@ function useMcp(props: ServiceProps, close: () => void): ServiceSource { return ctx.t(status === "connected" ? "mcp.connected" : "mcp.disabled") } - const change = (value: boolean) => { - if (pending()) return - toggle.mutate({ name: server().name, enabled: value }) + const change = (value: boolean) => + mcp.dispatch({ + type: "toggle.requested", + name: server().name, + enabled: value, + status: server().status.status, + }) + + const showError = () => { + const error = failure() + + if (error) mcp.dispatch({ type: "error.opened", name: server().name, error }) } const follow = () => { - if (failure()) return showError(server().name) + if (failure()) return showError() change(server().status.status === "needs_auth" || !enabled()) } @@ -590,7 +645,7 @@ function useMcp(props: ServiceProps, close: () => void): ServiceSource { status={server().status.status} error={failure()} label={ctx.t("mcp.error.actionLabel", { name: server().name })} - onClick={() => showError(server().name)} + onClick={showError} /> @@ -728,9 +783,7 @@ function useCatalog(props: ServiceProps, service: "plugins" | "skills"): Service Body: () => ( - } + fallback={} > {(item) => ( @@ -861,67 +914,54 @@ function ServiceConfigLink(props: { owner: ServiceProps; service: Service }) { const ctx = usePlugin() const system = ctx.system const local = () => props.owner.session.server.local - const [store, setStore] = createStore({ opening: false, copied: false }) const label = () => ctx.t(local() ? "configure" : "copyConfigPath") - // Clears the copied mark two seconds after the latest copy. - let reset: ReturnType | undefined - onCleanup(() => clearTimeout(reset)) - - const activate = async () => { - if (store.opening) return - setStore({ opening: true, copied: false }) + const action = useConfigAction(props.owner, async (signal) => { const session = props.owner.session - await session.server.client.config - .get({ location: { directory: props.owner.directory } }) - .then(async (entries) => { - const path = serviceConfigFile(entries, props.service) - if (!path) throw new Error(ctx.t("configFileMissing")) + const entries = await session.server.client.config.get( + { location: { directory: props.owner.directory } }, + { signal }, + ) - // A local file opens in a side tab beside the session, inside the workspace or not. - if (local()) { - if (ctx.links.open({ href: path, session })) return props.owner.onClose?.() - await ctx.desktop?.reveal(path) + const path = serviceConfigFile(entries, props.service) - return - } + if (!path) throw new Error(ctx.t("configFileMissing")) + signal.throwIfAborted() - await system.copy(path) - setStore("copied", true) - clearTimeout(reset) - reset = setTimeout(() => setStore("copied", false), 2000) - }) - .catch((error) => - showToast({ - variant: "error", - title: ctx.t("common.requestFailed"), - description: error instanceof Error ? error.message : String(error), - }), - ) - .finally(() => setStore("opening", false)) - } + // A local file opens in a side tab beside the session, inside the workspace or not. + if (local()) { + if (ctx.links.open({ href: path, session })) return { type: "opened", close: true } + await ctx.desktop?.reveal(path) + + return { type: "opened", close: false } + } + + await system.copy(path) + + return { type: "copied" } + }) return ( anchor?.querySelector("svg")?.getBoundingClientRect()} - forceOpen={store.copied ? true : undefined} + forceOpen={action.view().copied ? true : undefined} class="w-full" > ) } +type ConfigActionResult = { readonly type: "opened"; readonly close: boolean } | { readonly type: "copied" } + +// Runs a footer action through its machine: one run at a time, bounded by a timeout, and ended with the popover. +function useConfigAction(owner: ServiceProps, task: (signal: AbortSignal) => Promise) { + const ctx = usePlugin() + const [actionState, setActionState] = createSignal(initialConfigActionState) + const runs = new Map }>() + let reset: ReturnType | undefined + + const dispatch = (event: ConfigActionEvent) => { + const previous = untrack(actionState) + const next = transitionConfigAction(previous, event) + + if (next.state !== previous) setActionState(next.state) + next.effects.forEach(run) + } + + const run = (effect: ConfigActionEffect) => { + if (effect.type === "run") { + const attempt = effect.attempt + const controller = new AbortController() + + runs.set(attempt, { + controller, + timer: setTimeout(() => dispatch({ type: "timed-out", attempt }), effect.timeoutMs), + }) + void task(AbortSignal.any([ctx.signal, controller.signal])).then( + (result) => dispatch({ ...result, attempt }), + (error) => dispatch({ type: "failed", attempt, error: error instanceof Error ? error.message : String(error) }), + ) + + return + } + + if (effect.type === "abort") { + const handle = runs.get(effect.attempt) + runs.delete(effect.attempt) + clearTimeout(handle?.timer) + handle?.controller.abort() + + return + } + + if (effect.type === "schedule-reset") { + const attempt = effect.attempt + clearTimeout(reset) + reset = setTimeout(() => dispatch({ type: "copied.expired", attempt }), effect.delayMs) + + return + } + + if (effect.type === "cancel-reset") return clearTimeout(reset) + + if (effect.type === "close-owner") return owner.onClose?.() + + showToast({ + variant: "error", + title: ctx.t("common.requestFailed"), + description: effect.type === "toast-failed" ? effect.error : ctx.t("timedOut"), + }) + } + + // Hiding the popover or drawer drops the copied mark, so its tooltip does not stay open over nothing. + createKeyed( + () => owner.shown, + () => undefined, + { otherwise: () => dispatch({ type: "hidden" }) }, + ) + onCleanup(() => dispatch({ type: "disposed" })) + + return { view: () => configActionView(actionState()), activate: () => dispatch({ type: "activate" }) } +} + function ServiceEmpty(props: { title: string }) { return (
@@ -1012,105 +1118,269 @@ function insideTriangle(point: Point, a: Point, b: Point, c: Point) { return sides.every((value) => value >= 0) || sides.every((value) => value <= 0) } -// Connects, disconnects, or starts sign-in for one of the session server's MCPs, like the app's MCP toggle. -function useMcpToggle(session: MountedSession, directory: () => string) { - const ctx = usePlugin() - const system = ctx.system - const data = () => session.server.data - - return useMutation(() => ({ - mutationFn: async (input: { name: string; enabled: boolean }) => { - const client = session.server.client - const source = data() - const ref = { directory: directory() } - const server = (await client.mcp.list({ location: ref })).data.find((item) => item.name === input.name) - - if (!server) return - - if (!input.enabled) { - await client.experimental.mcp.disconnect({ server: input.name, location: ref }) - } - - if (input.enabled && server.status.status !== "needs_auth") { - await client.experimental.mcp.connect({ server: input.name, location: ref }) - } - - source.location.mcp.server.invalidate(ref) - await source.location.mcp.server.sync(ref) - const current = source.location.mcp.server.list(ref)?.find((item) => item.name === input.name) - - if (input.enabled && current?.status.status === "needs_auth" && current.integrationID) { - const integration = await client.integration.get({ integrationID: current.integrationID, location: ref }) - const method = integration.data?.methods.find((item) => item.type === "oauth" && !item.form?.length) - - if (!method || method.type !== "oauth") throw new Error(ctx.t("mcp.interactiveAuth", { name: input.name })) - - const integrationID = current.integrationID - const attempt = await client.integration.oauth.connect({ integrationID, methodID: method.id, location: ref }) - - system.openExternal(attempt.data.url) - - if (attempt.data.paste) - ctx.dialogs.open((dialog) => ( - { - const latest = data() - latest.location.mcp.server.invalidate(ref) - latest.location.mcp.resource.invalidate(ref) - await Promise.all([latest.location.mcp.server.sync(ref), latest.location.mcp.resource.sync(ref)]) - dialog.close() - }} - /> - )) - } - - source.location.mcp.resource.invalidate(ref) - await source.location.mcp.resource.sync(ref) - // A successful HTTP response can still leave the MCP connection in a failed state. - const status = current?.status - - if (status?.status === "failed") throw new Error(`${input.name}: ${status.error}`) - }, - onError: (error) => - showToast({ - variant: "error", - title: ctx.t("common.requestFailed"), - description: error instanceof Error ? error.message : String(error), - }), - })) +type McpController = { + readonly state: () => McpState + dispatch: (event: McpEvent) => void + /** Reports that an error dialog closed, by the user or by the controller. */ + dismiss: (attempt: number) => void } -// The MCPs dialog's error view, for a server the popover lists. It reads the server's own data, so it outlives the -// popover that opened it. -function McpErrorDialog(props: { session: MountedSession; directory: string; name: string; onClose: () => void }) { +/** + * The plugin instance's MCP controllers, by server and directory, so a popover or drawer that mounts again finds the + * toggles and the error dialog the previous one left running. + */ +export type McpControllers = Map + +// The controller for the server and directory, shared with every other mount and the error dialog, for as long as +// this mount lives. +function useMcpController(controllers: McpControllers, server: ServerRef, directory: string) { + const key = JSON.stringify([server.id, directory]) + const current = controllers.get(key) + + const mcp = + current && untrack(current.state).status !== "disposed" + ? current + : createMcpController(server, directory, () => { + if (controllers.get(key) === mcp) controllers.delete(key) + }) + + controllers.set(key, mcp) + mcp.dispatch({ type: "mounted" }) + onCleanup(() => mcp.dispatch({ type: "unmounted" })) + + return mcp +} + +// Connects, disconnects, or starts sign-in for one server's MCPs in one directory, like the app's MCP toggle, and shows +// their errors. It ends once no popover lists it, no toggle runs and no error dialog shows, or with the plugin. +function createMcpController(server: ServerRef, directory: string, release: () => void): McpController { const ctx = usePlugin() - const toggle = useMcpToggle(props.session, () => props.directory) - const [copied, setCopied] = createSignal(false) + const [mcpState, setMcpState] = createSignal(initialMcpState) + const runs = new Map }>() + const dialogs = new Map void }>() + const dispose = () => dispatch({ type: "disposed" }) - const failure = () => { - const server = props.session.server.data.location.mcp.server - .list({ directory: props.directory }) - ?.find((item) => item.name === props.name) + const dispatch = (event: McpEvent) => { + const previous = untrack(mcpState) + const next = transitionMcp(previous, event) - return server?.status.status === "failed" ? { name: server.name, error: server.status.error } : undefined + if (next.state !== previous) setMcpState(next.state) + + if (next.state.status === "disposed" && previous.status !== "disposed") { + ctx.signal.removeEventListener("abort", dispose) + release() + } + + next.effects.forEach(run) } - // A successful retry, disabling, or a removed server leaves nothing to show. + const mcp: McpController = { + state: mcpState, + dispatch, + dismiss: (attempt) => { + dialogs.delete(attempt) + dispatch({ type: "error.dismissed", attempt }) + }, + } + + const run = (effect: McpEffect) => { + if (effect.type === "run-toggle") { + const name = effect.name + const attempt = effect.attempt + const controller = new AbortController() + + runs.set(attempt, { + controller, + timer: setTimeout(() => dispatch({ type: "toggle.timed-out", name, attempt }), effect.timeoutMs), + }) + void toggle(effect, controller.signal).then(dispatch, (error) => + dispatch({ + type: "toggle.failed", + name, + attempt, + error: error instanceof Error ? error.message : String(error), + server: false, + }), + ) + + return + } + + if (effect.type === "abort-toggle") { + const handle = runs.get(effect.attempt) + runs.delete(effect.attempt) + clearTimeout(handle?.timer) + handle?.controller.abort() + + return + } + + if (effect.type === "open-external") return ctx.system.openExternal(effect.url) + + if (effect.type === "open-sign-in") { + const signIn = effect.signIn + const ref = { directory } + + ctx.dialogs.open((dialog) => ( + { + const latest = server.data + latest.location.mcp.server.invalidate(ref) + latest.location.mcp.resource.invalidate(ref) + await Promise.all([latest.location.mcp.server.sync(ref), latest.location.mcp.resource.sync(ref)]) + dialog.close() + }} + /> + )) + + return + } + + if (effect.type === "open-dialog") { + dialogs.set( + effect.attempt, + ctx.dialogs.open(() => ( + + )), + ) + + return + } + + if (effect.type === "close-dialog") { + const handle = dialogs.get(effect.attempt) + dialogs.delete(effect.attempt) + handle?.close() + + return + } + + showToast({ + variant: "error", + title: ctx.t("common.requestFailed"), + description: effect.type === "toast-failed" ? effect.message : ctx.t("mcp.timedOut", { name: effect.name }), + }) + } + + const toggle = async (effect: Extract, signal: AbortSignal): Promise => { + const client = server.client + const source = server.data + const ref = { directory } + const name = effect.name + const attempt = effect.attempt + const found = (await client.mcp.list({ location: ref }, { signal })).data.find((item) => item.name === name) + + if (!found) return { type: "toggle.succeeded", name, attempt } + + if (!effect.enabled) await client.experimental.mcp.disconnect({ server: name, location: ref }, { signal }) + + if (effect.enabled && found.status.status !== "needs_auth") + await client.experimental.mcp.connect({ server: name, location: ref }, { signal }) + + source.location.mcp.server.invalidate(ref) + await source.location.mcp.server.sync(ref) + const current = source.location.mcp.server.list(ref)?.find((item) => item.name === name) + const integrationID = current?.integrationID + + if (effect.enabled && current?.status.status === "needs_auth" && integrationID) { + const integration = await client.integration.get({ integrationID, location: ref }, { signal }) + const method = integration.data?.methods.find((item) => item.type === "oauth" && !item.form?.length) + + if (!method || method.type !== "oauth") throw new Error(ctx.t("mcp.interactiveAuth", { name })) + + const started = await client.integration.oauth.connect( + { integrationID, methodID: method.id, location: ref }, + { signal }, + ) + + dispatch({ + type: "toggle.authorizing", + name, + attempt, + url: started.data.url, + signIn: started.data.paste + ? { + integrationID, + attemptID: started.data.attemptID, + url: started.data.url, + lifetime: started.data.time.expires - started.data.time.created, + } + : undefined, + }) + } + + source.location.mcp.resource.invalidate(ref) + await source.location.mcp.resource.sync(ref) + // A successful HTTP response can still leave the MCP connection in a failed state. + const status = current?.status + + if (status?.status === "failed") return { type: "toggle.failed", name, attempt, error: status.error, server: true } + + return { type: "toggle.succeeded", name, attempt } + } + + // The plugin's end ends the toggles and dialogs that outlived the popover. + ctx.signal.addEventListener("abort", dispose, { once: true }) + + return mcp +} + +// The MCPs dialog's error view, for a server the popover lists. Its controller outlives the popover that opened it. +function McpErrorDialog(props: { + mcp: McpController + attempt: number + name: string + server: ServerRef + directory: string +}) { + const ctx = usePlugin() + const list = () => props.server.data.location.mcp.server.list({ directory: props.directory }) + const status = () => list()?.find((item) => item.name === props.name)?.status + const view = createMemo(() => mcpDialogView(props.mcp.state(), props.attempt, status()?.status)) + + // Follows the server's status, which changes here and anywhere else: a reconnect or a removal closes the dialog, and + // a new failure replaces its error. createKeyed( - () => !!failure(), - () => undefined, - { otherwise: props.onClose }, + () => ({ loaded: list() !== undefined, status: status() }), + (synced) => + props.mcp.dispatch({ + type: "server.synced", + attempt: props.attempt, + loaded: synced.loaded, + status: synced.status, + }), + { + equals: (previous, next) => + previous.loaded === next.loaded && + previous.status?.status === next.status?.status && + statusError(previous.status) === statusError(next.status), + }, ) + onCleanup(() => props.mcp.dismiss(props.attempt)) + + const toggle = (enabled: boolean) => + props.mcp.dispatch({ type: "toggle.requested", name: props.name, enabled, status: status()?.status }) + + const copy = (name: string, error: string) => + void ctx.system.copy(ctx.t("mcp.error.details", { name, error })).then( + () => props.mcp.dispatch({ type: "error.copied", attempt: props.attempt, error }), + (cause) => + showToast({ + variant: "error", + title: ctx.t("mcp.error.copyFailed"), + description: cause instanceof Error ? cause.message : String(cause), + }), + ) return ( - + {(current) => ( @@ -1128,34 +1398,15 @@ function McpErrorDialog(props: { session: MountedSession; directory: string; nam - - @@ -1166,10 +1417,14 @@ function McpErrorDialog(props: { session: MountedSession; directory: string; nam ) } +function statusError(status: McpServerStatus | undefined) { + return status?.status === "failed" || status?.status === "needs_auth" ? status.error : undefined +} + // Waits for an MCP sign-in that also accepts the redirect URL pasted from the browser, for when the browser cannot // reach the machine running the server (SSH, a remote desktop connection, a container). Like the app's MCPs dialog. function McpSignInDialog(props: { - session: MountedSession + server: ServerRef name: string integrationID: string attemptID: string @@ -1206,7 +1461,7 @@ function McpSignInDialog(props: { } const poll = async () => { - const result = await props.session.server.client.integration.oauth + const result = await props.server.client.integration.oauth .status(attempt()) .then((response) => ({ ok: true as const, status: response.data })) .catch((error) => ({ ok: false as const, error })) @@ -1215,7 +1470,8 @@ function McpSignInDialog(props: { // A failed request says nothing about the attempt, which may still be pending, so keep polling until it expires. if (!result.ok) { - if (Date.now() >= deadline) return fail(result.error instanceof Error ? result.error.message : String(result.error)) + if (Date.now() >= deadline) + return fail(result.error instanceof Error ? result.error.message : String(result.error)) timer = setTimeout(() => void poll(), 1_000) return @@ -1241,7 +1497,7 @@ function McpSignInDialog(props: { if (!code) return setStore("error", ctx.t("mcp.signIn.paste.required")) setStore({ error: undefined, submitting: true }) - const error = await props.session.server.client.integration.oauth + const error = await props.server.client.integration.oauth .complete({ ...attempt(), code }) .then(() => undefined) .catch((error) => (error instanceof Error ? error.message : String(error))) @@ -1259,7 +1515,7 @@ function McpSignInDialog(props: { clearTimeout(timer) if (settled) return - void props.session.server.client.integration.oauth.cancel(attempt()).catch(() => undefined) + void props.server.client.integration.oauth.cancel(attempt()).catch(() => undefined) }) return (