AI-native design editor. Open-source Figma alternative.
refactor(app): make MCP runtime lifecycle explicit
Danila Poyarkov25d7889ab2b1
diff --git a/src/app/automation/mcp/preferences.ts b/src/app/automation/mcp/preferences.tsindex 841d621d7..014663353 100644--- a/src/app/automation/mcp/preferences.ts+++ b/src/app/automation/mcp/preferences.ts@@ -1,19 +1,19 @@import { useLocalStorage } from '@vueuse/core'import { ref } from 'vue'-import type { MCPToolCatalogEntry } from '@open-pencil/mcp/tools'+import type { ToolDescriptor, ToolEffect } from '@open-pencil/mcp/tools'const DISABLED_TOOLS_STORAGE_KEY = 'open-pencil:mcp:disabled-tools'const ROOT_DIRECTORY_STORAGE_KEY = 'open-pencil:mcp:root-directory'const AUTHENTICATION_ENABLED_STORAGE_KEY = 'open-pencil:mcp:authentication-enabled'-export const configurableMCPTools = ref<MCPToolCatalogEntry[]>([])+export const configurableMCPTools = ref<ToolDescriptor[]>([])export const disabledMCPTools = useLocalStorage<string[]>(DISABLED_TOOLS_STORAGE_KEY, [])export const mcpRootDirectory = useLocalStorage(ROOT_DIRECTORY_STORAGE_KEY, '')export const mcpAuthenticationEnabled = useLocalStorage(AUTHENTICATION_ENABLED_STORAGE_KEY, true)-export function setMCPToolCatalog(tools: MCPToolCatalogEntry[]): void {+export function setMCPToolDescriptors(tools: ToolDescriptor[]): void {configurableMCPTools.value = tools.filter((tool) => tool.availability !== 'eval')}@@ -24,13 +24,10 @@ export function setMCPToolEnabled(name: string, enabled: boolean): void {disabledMCPTools.value = [...disabled]}-export function setMCPToolCategoryEnabled(- documentAccess: MCPToolCatalogEntry['documentAccess'],- enabled: boolean-): void {+export function setMCPToolCategoryEnabled(effect: ToolEffect, enabled: boolean): void {const disabled = new Set(disabledMCPTools.value)for (const tool of configurableMCPTools.value) {- if (tool.documentAccess !== documentAccess) continue+ if (tool.effect !== effect) continueif (enabled) disabled.delete(tool.name)else disabled.add(tool.name)}diff --git a/src/app/automation/mcp/runtime.ts b/src/app/automation/mcp/runtime.tsindex 4ccfc4701..13ce60376 100644--- a/src/app/automation/mcp/runtime.ts+++ b/src/app/automation/mcp/runtime.ts@@ -6,104 +6,174 @@ import { connectAutomation } from '@/app/automation/bridge/server'import type { EditorStore } from '@/app/editor/active-store'import { isTauri } from '@/app/tauri/env'-import { setMCPToolCatalog } from './preferences'-import { readAutomationHealth, spawnMCPIfNeeded, type AutomationServerHandle } from './spawn'+import { setMCPToolDescriptors } from './preferences'+import {+ type AutomationHealth,+ type AutomationServerHandle,+ readAutomationHealth,+ spawnMCPIfNeeded+} from './spawn'export type MCPRuntimeStatus = 'idle' | 'starting' | 'running' | 'stopped' | 'error'-export const mcpRuntime = reactive({- status: 'idle' as MCPRuntimeStatus,- port: AUTOMATION_HTTP_PORT,- version: null as string | null,- error: null as string | null,- checking: false,- externallyManaged: false-})+export interface MCPRuntimeState {+ status: MCPRuntimeStatus+ port: number+ version: string | null+ error: string | null+ checking: boolean+ externallyManaged: boolean+}-let server: AutomationServerHandle | null = null-let disconnectAutomation: (() => void) | null = null-let activeStore: (() => EditorStore) | null = null-let lifecycle = Promise.resolve()+export type MCPRuntimeResult = { ok: true } | { ok: false; error: Error }-function enqueueLifecycle(operation: () => Promise<void>): Promise<void> {- const next = lifecycle.then(operation, operation)- lifecycle = next.catch(() => undefined)- return next+export interface MCPRuntimeDependencies {+ connect: (getStore: () => EditorStore, authToken: string | null) => () => void+ canConnect: () => boolean+ readHealth: (authToken?: string | null) => Promise<AutomationHealth | null>+ setToolDescriptors: (tools: NonNullable<AutomationHealth['tools']>) => void+ spawn: () => Promise<AutomationServerHandle | null>}-export async function refreshMCPRuntime(): Promise<void> {- mcpRuntime.checking = true- try {- const health = await readAutomationHealth()- mcpRuntime.version = health?.version ?? null- setMCPToolCatalog(health?.tools ?? [])- if (health) {- mcpRuntime.status = 'running'- mcpRuntime.error = null- } else if (mcpRuntime.status !== 'starting' && mcpRuntime.status !== 'error') {- mcpRuntime.status = 'stopped'- }- } finally {- mcpRuntime.checking = false- }+function toError(error: unknown): Error {+ return error instanceof Error ? error : new Error(String(error))}-async function start(): Promise<void> {- mcpRuntime.status = 'starting'- mcpRuntime.error = null- mcpRuntime.externallyManaged = false- try {- server = await spawnMCPIfNeeded()- const health = await readAutomationHealth()- if (!health) throw new Error('MCP server did not become healthy')- mcpRuntime.externallyManaged = server?.managed === false- if (activeStore && (import.meta.env.DEV || isTauri())) {- disconnectAutomation = connectAutomation(activeStore, server?.authToken ?? null).disconnect+export function createMCPRuntimeService(dependencies: MCPRuntimeDependencies) {+ const state = reactive<MCPRuntimeState>({+ status: 'idle',+ port: AUTOMATION_HTTP_PORT,+ version: null,+ error: null,+ checking: false,+ externallyManaged: false+ })++ let server: AutomationServerHandle | null = null+ let disconnectAutomation: (() => void) | null = null+ let activeStore: (() => EditorStore) | null = null+ let lifecycle: Promise<void> = Promise.resolve()++ function enqueue<T>(operation: () => Promise<T>): Promise<T> {+ const next = lifecycle.then(operation, operation)+ lifecycle = next.then(+ () => undefined,+ () => undefined+ )+ return next+ }++ function applyHealth(health: AutomationHealth): void {+ state.version = health.version ?? null+ dependencies.setToolDescriptors(health.tools ?? [])+ state.status = 'running'+ state.error = null+ }++ async function refreshOperation(): Promise<MCPRuntimeResult> {+ state.checking = true+ try {+ const health = await dependencies.readHealth(server?.authToken)+ if (health) {+ applyHealth(health)+ return { ok: true }+ }+ state.version = null+ dependencies.setToolDescriptors([])+ if (state.status !== 'error') state.status = 'stopped'+ return { ok: true }+ } catch (error) {+ const runtimeError = toError(error)+ state.status = 'error'+ state.error = runtimeError.message+ return { ok: false, error: runtimeError }+ } finally {+ state.checking = false}- mcpRuntime.version = health.version ?? null- setMCPToolCatalog(health.tools ?? [])- mcpRuntime.status = 'running'- } catch (error) {+ }++ async function disconnectCurrentServer(): Promise<Error | null> {disconnectAutomation?.()disconnectAutomation = null- if (server) {- try {- await server.disconnect()- } catch (disconnectError) {- console.warn('[MCP] Failed to stop server after startup error:', disconnectError)+ const currentServer = server+ server = null+ try {+ await currentServer?.disconnect()+ return null+ } catch (error) {+ return toError(error)+ }+ }++ async function startOperation(): Promise<MCPRuntimeResult> {+ state.status = 'starting'+ state.error = null+ state.externallyManaged = false+ try {+ server = await dependencies.spawn()+ const health = await dependencies.readHealth(server?.authToken)+ if (!health) throw new Error('MCP server did not become healthy')+ state.externallyManaged = server?.managed === false+ if (activeStore && dependencies.canConnect()) {+ disconnectAutomation = dependencies.connect(activeStore, server?.authToken ?? null)}+ applyHealth(health)+ return { ok: true }+ } catch (error) {+ const runtimeError = toError(error)+ const disconnectError = await disconnectCurrentServer()+ state.status = 'error'+ state.error = disconnectError+ ? `${runtimeError.message}. Cleanup failed: ${disconnectError.message}`+ : runtimeError.message+ console.warn('[MCP]', runtimeError)+ return { ok: false, error: runtimeError }}- server = null- mcpRuntime.status = 'error'- mcpRuntime.error = error instanceof Error ? error.message : String(error)- console.warn('[MCP]', error)}-}-export function startMCPRuntime(getStore: () => EditorStore): Promise<void> {- activeStore = getStore- return enqueueLifecycle(start)-}+ async function stopOperation(releaseStore: boolean): Promise<MCPRuntimeResult> {+ const disconnectError = await disconnectCurrentServer()+ if (releaseStore) activeStore = null+ state.status = disconnectError ? 'error' : 'stopped'+ state.version = null+ state.error = disconnectError?.message ?? null+ state.externallyManaged = false+ dependencies.setToolDescriptors([])+ return disconnectError ? { ok: false, error: disconnectError } : { ok: true }+ }-async function stop(): Promise<void> {- disconnectAutomation?.()- disconnectAutomation = null- await server?.disconnect()- server = null- mcpRuntime.status = 'stopped'- mcpRuntime.version = null- mcpRuntime.externallyManaged = false- setMCPToolCatalog([])+ return {+ state,+ refresh: () => enqueue(refreshOperation),+ start(getStore: () => EditorStore): Promise<MCPRuntimeResult> {+ activeStore = getStore+ return enqueue(startOperation)+ },+ stop: () => enqueue(() => stopOperation(true)),+ restart: () =>+ enqueue(async () => {+ await stopOperation(false)+ if (!activeStore) {+ const error = new Error('Editor is not ready')+ state.status = 'error'+ state.error = error.message+ return { ok: false, error } as MCPRuntimeResult+ }+ return startOperation()+ })+ }}-export function stopMCPRuntime(): Promise<void> {- return enqueueLifecycle(stop)-}+const appMCPRuntime = createMCPRuntimeService({+ connect: (getStore, authToken) => connectAutomation(getStore, authToken).disconnect,+ canConnect: () => import.meta.env.DEV || isTauri(),+ readHealth: readAutomationHealth,+ setToolDescriptors: setMCPToolDescriptors,+ spawn: spawnMCPIfNeeded+})-export function restartMCPRuntime(): Promise<void> {- return enqueueLifecycle(async () => {- await stop()- if (!activeStore) throw new Error('Editor is not ready')- await start()- })-}+export const mcpRuntime = appMCPRuntime.state+export const refreshMCPRuntime = appMCPRuntime.refresh+export const restartMCPRuntime = () => appMCPRuntime.restart()+export const startMCPRuntime = (getStore: () => EditorStore) => appMCPRuntime.start(getStore)+export const stopMCPRuntime = () => appMCPRuntime.stop()diff --git a/src/app/automation/mcp/spawn.ts b/src/app/automation/mcp/spawn.tsindex f84879ad0..859e61784 100644--- a/src/app/automation/mcp/spawn.ts+++ b/src/app/automation/mcp/spawn.ts@@ -3,7 +3,8 @@ import { promiseTimeout } from '@vueuse/core'import { AUTOMATION_HTTP_PORT } from '@open-pencil/core/constants'import { randomHex } from '@open-pencil/core/random'import type { DiscoveryInfo } from '@open-pencil/mcp/discovery'-import type { MCPToolCatalogEntry } from '@open-pencil/mcp/tools'+import type { ToolDescriptor } from '@open-pencil/mcp/tools'+import { parseToolDescriptor } from '@open-pencil/mcp/tools'import { decodeTauriStderr } from '@/app/shell/ui'import { resolvePlatformCommand } from '@/app/tauri/command'@@ -18,7 +19,7 @@ export interface AutomationHealth {installCommand?: stringauthRequired?: booleandiscoveryPath?: string- tools?: MCPToolCatalogEntry[]+ tools?: ToolDescriptor[]}export interface AutomationServerHandle {@@ -160,13 +161,79 @@ async function resolveDiscoveryPath(healthDiscoveryPath?: string): Promise<strinreturn expected}-export async function readAutomationHealth(): Promise<AutomationHealth | null> {+interface AutomationHealthRecord {+ status?: unknown+ version?: unknown+ installCommand?: unknown+ authRequired?: unknown+ discoveryPath?: unknown+ tools?: unknown+}++function isAutomationHealthRecord(value: unknown): value is AutomationHealthRecord {+ return typeof value === 'object' && value !== null && !Array.isArray(value)+}++function optionalString(value: unknown): string | null | undefined {+ if (value === undefined) return undefined+ return typeof value === 'string' ? value : null+}++function optionalBoolean(value: unknown): boolean | null | undefined {+ if (value === undefined) return undefined+ return typeof value === 'boolean' ? value : null+}++function parseToolDescriptors(value: unknown): ToolDescriptor[] | null | undefined {+ if (value === undefined) return undefined+ if (!Array.isArray(value)) return null+ const descriptors: ToolDescriptor[] = []+ for (const candidate of value) {+ const descriptor = parseToolDescriptor(candidate)+ if (!descriptor) return null+ descriptors.push(descriptor)+ }+ return descriptors+}++function parseAutomationHealth(value: unknown): AutomationHealth | null {+ if (!isAutomationHealthRecord(value)) return null+ if (value.status !== 'ok' && value.status !== 'no_app') return null+ const version = optionalString(value.version)+ const installCommand = optionalString(value.installCommand)+ const authRequired = optionalBoolean(value.authRequired)+ const discoveryPath = optionalString(value.discoveryPath)+ const tools = parseToolDescriptors(value.tools)+ if (+ version === null ||+ installCommand === null ||+ authRequired === null ||+ discoveryPath === null ||+ tools === null+ ) {+ return null+ }+ return {+ status: value.status,+ ...(version !== undefined ? { version } : {}),+ ...(installCommand !== undefined ? { installCommand } : {}),+ ...(authRequired !== undefined ? { authRequired } : {}),+ ...(discoveryPath !== undefined ? { discoveryPath } : {}),+ ...(tools !== undefined ? { tools } : {})+ }+}++export async function readAutomationHealth(+ authToken: string | null = runtimeAutomationAuthToken+): Promise<AutomationHealth | null> {try {+ const headers = authToken ? { Authorization: `Bearer ${authToken}` } : undefinedconst res = await fetch(`http://127.0.0.1:${AUTOMATION_HTTP_PORT}/health`, {+ headers,signal: AbortSignal.timeout(1000)})if (!res.ok) return null- return (await res.json()) as AutomationHealth+ return parseAutomationHealth(await res.json())} catch {return null}@@ -196,10 +263,14 @@ function assertCompatibleMCPVersion(health: AutomationHealth): void {)}-async function pollHealth(retries: number, delayMs: number): Promise<AutomationHealth | null> {- for (let i = 0; i < retries; i++) {+async function pollHealth(+ attempts: number,+ delayMs: number,+ authToken: string | null = runtimeAutomationAuthToken+): Promise<AutomationHealth | null> {+ for (let attempt = 0; attempt < attempts; attempt++) {await promiseTimeout(delayMs)- const health = await readAutomationHealth()+ const health = await readAutomationHealth(authToken)if (health) return health}return null@@ -278,9 +349,9 @@ async function configureDevMCP(): Promise<AutomationServerHandle> {if (!response.ok) {throw new Error(`Failed to configure development MCP server (${response.status})`)}- const health = await pollHealth(10, 250)- if (!health) throw new Error('Development MCP server did not become healthy')const authToken = configuration.authenticationEnabled ? DEV_AUTOMATION_AUTH_TOKEN : null+ const health = await pollHealth(10, 250, authToken)+ if (!health) throw new Error('Development MCP server did not become healthy')runtimeAutomationAuthToken = authTokenreturn { disconnect: noop, authToken, managed: true }}@@ -354,7 +425,7 @@ async function startMCPIfNeeded(): Promise<AutomationServerHandle | null> {))}- const health = await pollHealth(5, 1000)+ const health = await pollHealth(5, 1000, authToken)if (health) {try {diff --git a/tests/engine/app/automation/mcp-runtime.test.ts b/tests/engine/app/automation/mcp-runtime.test.tsnew file mode 100644index 000000000..1a0c85936--- /dev/null+++ b/tests/engine/app/automation/mcp-runtime.test.ts@@ -0,0 +1,115 @@+import { describe, expect, test } from 'bun:test'++import type { ToolDescriptor } from '@open-pencil/mcp/tools'++import { createMCPRuntimeService, type MCPRuntimeDependencies } from '@/app/automation/mcp/runtime'++function descriptor(name = 'get_page_tree'): ToolDescriptor {+ return {+ name,+ description: name,+ effect: 'read',+ availability: 'default',+ capabilities: ['document:read']+ }+}++function setup(overrides: Partial<MCPRuntimeDependencies> = {}) {+ const calls: string[] = []+ const catalogs: ToolDescriptor[][] = []+ const dependencies: MCPRuntimeDependencies = {+ canConnect: () => true,+ connect: () => {+ calls.push('connect')+ return () => calls.push('disconnect-bridge')+ },+ readHealth: async () => ({ status: 'ok', version: '0.14.0', tools: [descriptor()] }),+ setToolDescriptors: (tools) => catalogs.push(tools),+ spawn: async () => ({+ authToken: 'token',+ managed: true,+ disconnect: () => {+ calls.push('disconnect-server')+ }+ }),+ ...overrides+ }+ return { calls, catalogs, service: createMCPRuntimeService(dependencies) }+}++const getStore = () => ({}) as never++describe('MCP runtime service', () => {+ test('starts only after a healthy server response', async () => {+ const { calls, catalogs, service } = setup()++ expect(await service.start(getStore)).toEqual({ ok: true })+ expect(service.state.status).toBe('running')+ expect(service.state.version).toBe('0.14.0')+ expect(calls).toEqual(['connect'])+ expect(catalogs.at(-1)?.map((tool) => tool.name)).toEqual(['get_page_tree'])+ })++ test('serializes refresh behind stop so stale health cannot restore running state', async () => {+ let releaseHealth: (() => void) | undefined+ const blockedHealth = new Promise<void>((resolve) => {+ releaseHealth = resolve+ })+ let healthCalls = 0+ const { service } = setup({+ readHealth: async () => {+ healthCalls+++ if (healthCalls === 2) await blockedHealth+ return { status: 'ok', tools: [descriptor()] }+ }+ })+ await service.start(getStore)++ const refresh = service.refresh()+ const stop = service.stop()+ releaseHealth?.()+ await Promise.all([refresh, stop])++ expect(service.state.status).toBe('stopped')+ })++ test('reports startup failure and cleans up the spawned server', async () => {+ const { calls, service } = setup({ readHealth: async () => null })++ const result = await service.start(getStore)++ expect(result.ok).toBe(false)+ expect(service.state.status).toBe('error')+ expect(service.state.error).toContain('did not become healthy')+ expect(calls).toEqual(['disconnect-server'])+ })++ test('clears local runtime state even when server shutdown fails', async () => {+ const { catalogs, service } = setup({+ spawn: async () => ({+ authToken: 'token',+ managed: true,+ disconnect: () => {+ throw new Error('shutdown failed')+ }+ })+ })+ await service.start(getStore)++ const result = await service.stop()++ expect(result.ok).toBe(false)+ expect(service.state.status).toBe('error')+ expect(service.state.version).toBeNull()+ expect(catalogs.at(-1)).toEqual([])+ })++ test('restarts with the retained editor store inside one lifecycle operation', async () => {+ const { calls, service } = setup()+ await service.start(getStore)++ expect(await service.restart()).toEqual({ ok: true })+ expect(service.state.status).toBe('running')+ expect(calls).toEqual(['connect', 'disconnect-bridge', 'disconnect-server', 'connect'])+ })+})