Skip to content

AI-native design editor. Open-source Figma alternative.

Harden ACP transport, MCP server, and add permission dialog

Anton A S583b03eb3bcc
diff --git a/.gitignore b/.gitignore
index 3f52dd5c3..97e0df5cc 100644
--- a/.gitignore
+++ b/.gitignore
@@ -41,3 +41,4 @@ patches/skia-webgpu/
Caddyfile.dev
components.d.ts
+vue-stream-markdown/
diff --git a/AGENTS.md b/AGENTS.md
index b708b7721..8a05da32b 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -125,10 +125,22 @@ When adding features, update `CHANGELOG.md` (Unreleased section) and `README.md`
- AI adapter (`packages/core/src/tools/ai-adapter.ts`): `toolsToAI()` converts ToolDefs → valibot schemas + Vercel AI `tool()` wrappers
- `src/ai/tools.ts` is just a thin wire: creates FigmaAPI from editor store, calls `toolsToAI()`
- CLI commands (`packages/cli/src/commands/`) are **not** generated from ToolDefs — they have custom agentfmt formatting, tree walking, pagination. The `eval` command is the CLI's access to all ToolDef operations via FigmaAPI.
-- MCP adapter (`packages/mcp/src/server.ts`): `createServer()` converts ToolDefs → zod schemas + MCP `registerTool()`. Adds `open_file`, `save_file`, `new_document` for headless file ops. Two entry points: `index.ts` (stdio), `http.ts` (Hono + Streamable HTTP with sessions).
+- MCP adapter (`packages/mcp/src/server.ts`): `startServer()` creates unified HTTP + WebSocket server. Registers all ToolDefs as MCP tools (zod schemas). Single entry point: `index.ts` (Hono + Streamable HTTP with sessions). Browser connects via WebSocket, tool calls proxied through.
- To add a new tool: add a `defineTool()` in the appropriate domain file, add to `ALL_TOOLS` in `registry.ts` — it's instantly available in AI chat, MCP, and via `eval` in CLI
- `FigmaAPI` (`packages/core/src/figma-api.ts`) is the execution target for all tools — Figma Plugin API compatible, uses Symbols for hidden internals
+## ACP (Agent Client Protocol)
+
+- ACP transport (`src/ai/acp-transport.ts`) spawns agents via dynamic import of `@tauri-apps/plugin-shell`
+- Pure mapping logic in `src/ai/acp-map-update.ts` — converts `SessionUpdate` → `UIMessageChunk`
+- System prompt (`ACP_DESIGN_CONTEXT`) in `src/constants.ts`
+- Agent definitions (`ACP_AGENTS`) in `packages/core/src/constants.ts`
+- MCP server: Vite plugin in dev, `openpencil-mcp` via shell plugin in production Tauri (requires `npm i -g @open-pencil/mcp`; follow-up: bundle as Tauri sidecar)
+- Architecture: browser ↔ WebSocket :7601 ↔ MCP server :7600 ↔ HTTP ↔ agent subprocess
+- Shell permissions scoped per-command in `desktop/capabilities/default.json` (`args: true` — agents need dynamic SDK flags)
+- ACP providers visible only in Tauri desktop when MCP server is reachable
+- Permission requests shown in AlertDialog — user must approve/reject each request (60s auto-reject timeout)
+
## Collaboration
- P2P via Trystero (WebRTC) — no server relay. Signaling over MQTT public brokers.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 070c6d8d4..10cf5daa6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,8 @@
### Features
+- ACP agent support — use Claude Code, Codex, or Gemini CLI as AI assistants in the desktop chat panel
+- Unified MCP server — single HTTP + WebSocket proxy replaces Vite SSR bridge
- Grid layout in AI chat — JSX renderer supports `grid`, `columns`, `rows`, `gap` props with child positioning (`colStart`, `rowStart`, `colSpan`, `rowSpan`) and auto-height grids
- Configurable max output tokens in AI provider settings (default 16384)
- Z.ai AI provider with GLM-5, GLM-4.7, GLM-4.6, GLM-4.5 model families
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index bfcedbbab..b0e9b9457 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -5,6 +5,7 @@
```bash
git clone https://github.com/open-pencil/open-pencil.git
cd open-pencil
+git clone https://github.com/open-pencil/vue-stream-markdown.git
bun install
```
@@ -32,7 +33,6 @@ bun run test # Playwright E2E (auto-starts dev server)
- `packages/core` — scene graph, renderer, layout, codec (zero DOM deps)
- `packages/cli` — headless CLI for .fig inspection and export
- `packages/mcp` — MCP server for AI tools (stdio + HTTP)
-- `packages/acp` — ACP (Agent Client Protocol) server
- `packages/docs` — VitePress documentation site (openpencil.dev)
- `src/` — Tauri/Vite desktop editor
diff --git a/README.md b/README.md
index 2d887b798..d6b27c752 100644
--- a/README.md
+++ b/README.md
@@ -134,6 +134,10 @@ All commands support `--json` for machine-readable output.
Press <kbd>⌘</kbd><kbd>J</kbd> to open the AI assistant. It has 87 tools that can create shapes, set fills and strokes, manage auto-layout, work with components and variables, run boolean operations, analyze design tokens, and export assets. Bring your own OpenRouter API key — no backend, no account.
+### Coding agents (desktop)
+
+Use Claude Code, Codex, or Gemini CLI directly in the chat panel. The agent connects to the editor's MCP server and uses all 90+ design tools. Requires the desktop app and the agent CLI installed locally.
+
### MCP server
Connect Claude Code, Cursor, Windsurf, or any MCP client to read and write `.fig` files headlessly. 90 tools (87 core + 3 file management). [Full docs →](https://openpencil.dev/reference/mcp-tools)
diff --git a/desktop/capabilities/default.json b/desktop/capabilities/default.json
index 996d19f91..8c82d236a 100644
--- a/desktop/capabilities/default.json
+++ b/desktop/capabilities/default.json
@@ -24,7 +24,8 @@
"allow": [
{ "name": "claude-code-acp", "cmd": "claude-code-acp", "args": true },
{ "name": "codex-acp", "cmd": "codex-acp", "args": true },
- { "name": "gemini", "cmd": "gemini", "args": true }
+ { "name": "gemini", "cmd": "gemini", "args": true },
+ { "name": "openpencil-mcp", "cmd": "openpencil-mcp", "args": true }
]
},
"shell:allow-stdin-write",
diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.ts
index 33cccd783..f0701f751 100644
--- a/packages/mcp/src/server.ts
+++ b/packages/mcp/src/server.ts
@@ -1,4 +1,5 @@
import { randomUUID } from 'node:crypto'
+import { createRequire } from 'node:module'
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js'
@@ -14,10 +15,12 @@ import {
createElement,
resolveToTree
} from '@open-pencil/core'
-import { exportImage } from '@open-pencil/core/tools'
import type { ParamDef, ParamType } from '@open-pencil/core'
+const require = createRequire(import.meta.url)
+const MCP_VERSION: string = (require('../package.json') as { version: string }).version
+
type McpContent = { type: 'text'; text: string } | { type: 'image'; data: string; mimeType: string }
type McpResult = { content: McpContent[]; isError?: boolean }
@@ -138,7 +141,7 @@ export function startServer(options: ServerOptions = {}) {
const wss = new WebSocketServer({ port: wsPort, host: '127.0.0.1' })
wss.on('connection', (ws) => {
- if (browserWs?.readyState === browserWs?.OPEN) browserWs?.close()
+ if (browserWs && browserWs.readyState === WebSocket.OPEN) browserWs.close()
rejectAllPending('Browser reconnected')
browserWs = ws
browserToken = null
@@ -164,12 +167,17 @@ export function startServer(options: ServerOptions = {}) {
if (body.command !== 'tool') return body
const args = body.args as { name?: string; args?: Record<string, unknown> } | undefined
if (args?.name !== 'render' || !args.args?.jsx) return body
- const Component = buildComponent(args.args.jsx as string)
- const element = createElement(Component, null)
- const tree = resolveToTree(element)
- return {
- ...body,
- args: { ...args, args: { ...args.args, jsx: undefined, tree } }
+ try {
+ const Component = buildComponent(args.args.jsx as string)
+ const element = createElement(Component, null)
+ const tree = resolveToTree(element)
+ return {
+ ...body,
+ args: { ...args, args: { ...args.args, jsx: undefined, tree } }
+ }
+ } catch (e) {
+ console.warn('JSX preprocessing failed, passing raw:', e instanceof Error ? e.message : e)
+ return body
}
}
@@ -229,9 +237,10 @@ export function startServer(options: ServerOptions = {}) {
type McpTransport = { handleRequest: (r: Request) => Promise<Response> }
const mcpSessions = new Map<string, McpTransport>()
+ const MAX_MCP_SESSIONS = 10
function createMcpSession(id: string): McpTransport {
- const mcpServer = new McpServer({ name: 'open-pencil', version: '0.0.0' })
+ const mcpServer = new McpServer({ name: 'open-pencil', version: MCP_VERSION })
const register = mcpServer.registerTool.bind(mcpServer) as (...a: unknown[]) => void
for (const def of ALL_TOOLS) {
@@ -288,10 +297,19 @@ export function startServer(options: ServerOptions = {}) {
}
}
const sessionId = c.req.header('mcp-session-id') ?? undefined
- const transport =
- (sessionId && mcpSessions.get(sessionId)) ??
- createMcpSession(sessionId ?? randomUUID())
- return transport.handleRequest(c.req.raw)
+ const existing = sessionId ? mcpSessions.get(sessionId) : undefined
+ if (!existing && mcpSessions.size >= MAX_MCP_SESSIONS) {
+ return c.json(
+ { error: 'Too many active MCP sessions' },
+ { status: 503, headers: { 'Retry-After': '5' } }
+ )
+ }
+ const transport = existing ?? createMcpSession(sessionId ?? randomUUID())
+ const response = await transport.handleRequest(c.req.raw)
+ if (c.req.method === 'DELETE' && sessionId) {
+ mcpSessions.delete(sessionId)
+ }
+ return response
})
return { app, wss, httpPort }
diff --git a/src/ai/acp-map-update.ts b/src/ai/acp-map-update.ts
new file mode 100644
index 000000000..98881ab66
--- /dev/null
+++ b/src/ai/acp-map-update.ts
@@ -0,0 +1,100 @@
+import type { SessionUpdate } from '@agentclientprotocol/sdk'
+import type { UIMessageChunk } from 'ai'
+
+export interface MapResult {
+ chunks: UIMessageChunk[]
+ textStarted: boolean
+}
+
+export function mapUpdate(update: SessionUpdate, textId: string, textStarted: boolean): MapResult {
+ const chunks: UIMessageChunk[] = []
+
+ switch (update.sessionUpdate) {
+ case 'agent_message_chunk': {
+ if (update.content.type === 'text' && update.content.text) {
+ if (!textStarted) {
+ chunks.push({ type: 'text-start', id: textId })
+ textStarted = true
+ }
+ chunks.push({
+ type: 'text-delta',
+ id: textId,
+ delta: update.content.text
+ })
+ } else if (update.content.type !== 'text') {
+ console.warn('[ACP] Unhandled content type:', update.content.type)
+ }
+ break
+ }
+ case 'agent_thought_chunk': {
+ if (update.content.type === 'text') {
+ const rid = `reasoning-${textId}`
+ chunks.push({ type: 'reasoning-start', id: rid })
+ chunks.push({
+ type: 'reasoning-delta',
+ id: rid,
+ delta: update.content.text
+ })
+ chunks.push({ type: 'reasoning-end', id: rid })
+ }
+ break
+ }
+ case 'tool_call': {
+ if (!update.title) {
+ console.warn('[ACP] Tool call without title:', update.toolCallId)
+ }
+ const toolName = update.title || 'unknown'
+ chunks.push({
+ type: 'tool-input-start',
+ toolCallId: update.toolCallId,
+ toolName,
+ providerExecuted: true,
+ title: update.title
+ })
+ if (update.rawInput) {
+ chunks.push({
+ type: 'tool-input-available',
+ toolCallId: update.toolCallId,
+ toolName,
+ input: update.rawInput,
+ providerExecuted: true,
+ title: update.title
+ })
+ }
+ break
+ }
+ case 'tool_call_update': {
+ if (update.status === 'completed') {
+ chunks.push({
+ type: 'tool-output-available',
+ toolCallId: update.toolCallId,
+ output: update.rawOutput ?? textFromContent(update.content ?? undefined),
+ providerExecuted: true
+ })
+ } else if (update.status === 'failed') {
+ chunks.push({
+ type: 'tool-output-error',
+ toolCallId: update.toolCallId,
+ errorText: textFromContent(update.content ?? undefined) ?? 'Tool call failed',
+ providerExecuted: true
+ })
+ }
+ break
+ }
+ }
+
+ return { chunks, textStarted }
+}
+
+export function textFromContent(
+ content: Record<string, unknown>[] | undefined
+): string | undefined {
+ if (!content) return undefined
+ return content
+ .filter(
+ (c) =>
+ c.type === 'content' && (c.content as Record<string, unknown> | undefined)?.type === 'text'
+ )
+ .map((c) => (c.content as Record<string, string>).text)
+ .join('\n')
+}
diff --git a/src/ai/acp-permission.ts b/src/ai/acp-permission.ts
new file mode 100644
index 000000000..4cc72115e
--- /dev/null
+++ b/src/ai/acp-permission.ts
@@ -0,0 +1,54 @@
+import { computed, shallowRef } from 'vue'
+
+import { ACP_PERMISSION_TIMEOUT_MS } from '@/constants'
+
+import type { RequestPermissionRequest, RequestPermissionResponse } from '@agentclientprotocol/sdk'
+
+export interface PendingPermission {
+ request: RequestPermissionRequest
+ resolve: (response: RequestPermissionResponse) => void
+ timer: ReturnType<typeof setTimeout>
+}
+
+export const permissionQueue = shallowRef<PendingPermission[]>([])
+export const currentPermission = computed(() => permissionQueue.value[0] ?? null)
+
+function findRejectOption(request: RequestPermissionRequest): string {
+ const reject = request.options.find((o) => o.kind.startsWith('reject'))
+ return reject?.optionId ?? request.options.at(0)?.optionId ?? ''
+}
+
+function removeEntry(entry: PendingPermission) {
+ clearTimeout(entry.timer)
+ permissionQueue.value = permissionQueue.value.filter((e) => e !== entry)
+}
+
+export function requestPermissionFromUser(
+ params: RequestPermissionRequest
+): Promise<RequestPermissionResponse> {
+ return new Promise((resolve) => {
+ const timer = setTimeout(() => {
+ removeEntry(entry)
+ resolve({ outcome: { outcome: 'selected', optionId: findRejectOption(params) } })
+ }, ACP_PERMISSION_TIMEOUT_MS)
+
+ const entry: PendingPermission = { request: params, resolve, timer }
+ permissionQueue.value = [...permissionQueue.value, entry]
+ })
+}
+
+export function respondToPermission(optionId: string) {
+ const entry = permissionQueue.value.at(0)
+ if (!entry) return
+ removeEntry(entry)
+ entry.resolve({ outcome: { outcome: 'selected', optionId } })
+}
+
+export function rejectCurrentPermission() {
+ const entry = permissionQueue.value.at(0)
+ if (!entry) return
+ removeEntry(entry)
+ entry.resolve({
+ outcome: { outcome: 'selected', optionId: findRejectOption(entry.request) }
+ })
+}
diff --git a/src/ai/acp-transport.ts b/src/ai/acp-transport.ts
index 9c902cb48..c0ba5e12f 100644
--- a/src/ai/acp-transport.ts
+++ b/src/ai/acp-transport.ts
@@ -1,40 +1,67 @@
-import {
- ClientSideConnection,
- ndJsonStream,
- PROTOCOL_VERSION
-} from '@agentclientprotocol/sdk'
-import { Command } from '@tauri-apps/plugin-shell'
+import { ClientSideConnection, ndJsonStream, PROTOCOL_VERSION } from '@agentclientprotocol/sdk'
+
+import { ACP_DESIGN_CONTEXT } from '@/constants'
+
+import { mapUpdate } from './acp-map-update'
import type {
Client,
Agent,
SessionNotification,
RequestPermissionRequest,
- RequestPermissionResponse,
- SessionUpdate
+ RequestPermissionResponse
} from '@agentclientprotocol/sdk'
-import type { ChatTransport, UIMessage, UIMessageChunk } from 'ai'
import type { ACPAgentDef } from '@open-pencil/core'
+import type { ChatTransport, UIMessage, UIMessageChunk } from 'ai'
+
+type TauriChild = {
+ write(data: number[]): Promise<void>
+ kill(): Promise<void>
+}
interface ACPSession {
connection: ClientSideConnection
sessionId: string
- child: Awaited<ReturnType<Command<Uint8Array>['spawn']>>
+ child: TauriChild
onUpdate: ((params: SessionNotification) => void) | null
+ dead: boolean
}
-const DESIGN_CONTEXT = `You are inside OpenPencil, an open-source design editor (like Figma). \
-Use the open-pencil MCP tools to create and modify designs on the live canvas. \
-Key tools: render (JSX to design), create_shape, set_fill, set_layout, find_nodes, get_page_tree, export_image. \
-The render tool accepts JSX with components: Frame, Text, Rectangle, Ellipse, Icon, Group, Section. \
-Props: w, h, bg, flex, gap, p, rounded, color, size, weight, items, justify, stroke, opacity, shadow. \
-Do NOT write HTML files or use terminal commands — draw directly on the canvas using the MCP tools.`
+export function formatConnectionError(e: unknown): string {
+ const msg = e instanceof Error ? e.message : String(e)
+ if (
+ msg.includes('ECONNREFUSED') ||
+ msg.includes('fetch failed') ||
+ msg.includes('Failed to fetch')
+ ) {
+ return 'MCP server is not running. Make sure the editor is open.'
+ }
+ if (msg.includes('timeout') || msg.includes('Timeout') || msg.includes('ETIMEDOUT')) {
+ return 'MCP server did not respond in time.'
+ }
+ return msg
+}
+
+export function buildCrashChunks(
+ destroying: boolean,
+ textId: string,
+ textStarted: boolean
+): { chunks: UIMessageChunk[]; shouldNullSession: boolean } {
+ if (destroying) return { chunks: [], shouldNullSession: false }
+ const chunks: UIMessageChunk[] = []
+ if (textStarted) chunks.push({ type: 'text-end', id: textId })
+ chunks.push({ type: 'error', errorText: 'Agent process exited unexpectedly.' })
+ chunks.push({ type: 'finish-step' })
+ chunks.push({ type: 'finish', finishReason: 'error' })
+ return { chunks, shouldNullSession: true }
+}
export class ACPChatTransport implements ChatTransport<UIMessage> {
private session: ACPSession | null = null
private agentDef: ACPAgentDef
private cwd: string
private sentContext = false
+ private destroying = false
constructor(options: { agentDef: ACPAgentDef; cwd?: string }) {
this.agentDef = options.agentDef
@@ -47,20 +74,22 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {
}: Parameters<ChatTransport<UIMessage>['sendMessages']>[0]): Promise<
ReadableStream<UIMessageChunk>
> {
- const lastUserMessage = [...messages]
- .reverse()
- .find((m) => m.role === 'user')
+ const lastUserMessage = [...messages].reverse().find((m) => m.role === 'user')
const text =
lastUserMessage?.parts
.filter((p): p is { type: 'text'; text: string } => p.type === 'text')
.map((p) => p.text)
.join('\n') ?? ''
+ if (this.session?.dead) {
+ this.session = null
+ }
+
if (!this.session) {
this.session = await this.spawnAgent()
}
- const promptText = this.sentContext ? text : `${DESIGN_CONTEXT}\n\n${text}`
+ const promptText = this.sentContext ? text : `${ACP_DESIGN_CONTEXT}\n\n${text}`
this.sentContext = true
const { connection, sessionId } = this.session
@@ -85,11 +114,7 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {
session.onUpdate = (params) => {
if (closed) return
- const result = mapUpdate(
- params.update,
- textId,
- textStarted
- )
+ const result = mapUpdate(params.update, textId, textStarted)
for (const chunk of result.chunks) {
controller.enqueue(chunk)
}
@@ -113,8 +138,7 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {
finish(result.stopReason === 'end_turn' ? 'stop' : 'other')
})
.catch((e) => {
- const msg = e instanceof Error ? e.message : String(e)
- finish('error', msg)
+ finish('error', formatConnectionError(e))
})
}
})
@@ -125,6 +149,7 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {
}
async destroy(): Promise<void> {
+ this.destroying = true
if (this.session) {
await this.session.child.kill()
this.session = null
@@ -132,6 +157,9 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {
}
private async spawnAgent(): Promise<ACPSession> {
+ // @ts-expect-error — Tauri runtime-only module, not resolvable in lint/test environments
+ const { Command } = await import('@tauri-apps/plugin-shell')
+
const command = Command.create(this.agentDef.command, this.agentDef.args, {
encoding: 'raw'
})
@@ -151,12 +179,19 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {
})
command.stderr.on('data', (raw: Uint8Array | number[] | string) => {
- const text = typeof raw === 'string'
- ? raw
- : new TextDecoder().decode(raw instanceof Uint8Array ? raw : new Uint8Array(raw))
+ const text =
+ typeof raw === 'string'
+ ? raw
+ : new TextDecoder().decode(raw instanceof Uint8Array ? raw : new Uint8Array(raw))
console.error(`[ACP ${this.agentDef.id}]`, text)
})
+ command.on('close', () => {
+ if (this.destroying || !this.session) return
+ this.session.dead = true
+ this.session = null
+ })
+
const child = await command.spawn()
const output = new ReadableStream<Uint8Array>({
@@ -188,12 +223,8 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {
async requestPermission(
params: RequestPermissionRequest
): Promise<RequestPermissionResponse> {
- return {
- outcome: {
- outcome: 'selected',
- optionId: params.options[0]?.optionId ?? ''
- }
- }
+ const { requestPermissionFromUser } = await import('@/ai/acp-permission')
+ return requestPermissionFromUser(params)
},
async sessionUpdate(params: SessionNotification): Promise<void> {
@@ -201,136 +232,44 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {
}
}
- const connection = new ClientSideConnection(
- (_agent: Agent) => clientImpl,
- stream
- )
+ const connection = new ClientSideConnection((_agent: Agent) => clientImpl, stream)
await connection.initialize({
protocolVersion: PROTOCOL_VERSION,
clientCapabilities: {}
})
- const sessionResult = await connection.newSession({
- cwd: this.cwd,
- mcpServers: [
- {
- type: 'http' as const,
- name: 'open-pencil',
- url: 'http://127.0.0.1:7600/mcp',
- headers: []
- }
- ]
- })
+ let sessionResult
+ try {
+ sessionResult = await connection.newSession({
+ cwd: this.cwd,
+ mcpServers: [
+ {
+ type: 'http' as const,
+ name: 'open-pencil',
+ url: 'http://127.0.0.1:7600/mcp',
+ headers: []
+ }
+ ]
+ })
+ } catch (e) {
+ await child.kill()
+ throw new Error(formatConnectionError(e))
+ }
const session: ACPSession = {
connection,
sessionId: sessionResult.sessionId,
child,
- get onUpdate() { return onUpdate },
- set onUpdate(fn) { onUpdate = fn }
+ dead: false,
+ get onUpdate() {
+ return onUpdate
+ },
+ set onUpdate(fn) {
+ onUpdate = fn
+ }
}
return session
}
}
-
-interface MapResult {
- chunks: UIMessageChunk[]
- textStarted: boolean
-}
-
-export function mapUpdate(
- update: SessionUpdate,
- textId: string,
- textStarted: boolean
-): MapResult {
- const chunks: UIMessageChunk[] = []
-
- switch (update.sessionUpdate) {
- case 'agent_message_chunk': {
- if (update.content.type === 'text' && update.content.text) {
- if (!textStarted) {
- chunks.push({ type: 'text-start', id: textId })
- textStarted = true
- }
- chunks.push({
- type: 'text-delta',
- id: textId,
- delta: update.content.text
- })
- }
- break
- }
- case 'agent_thought_chunk': {
- if (update.content.type === 'text') {
- const rid = `reasoning-${textId}`
- chunks.push({ type: 'reasoning-start', id: rid })
- chunks.push({
- type: 'reasoning-delta',
- id: rid,
- delta: update.content.text
- })
- chunks.push({ type: 'reasoning-end', id: rid })
- }
- break
- }
- case 'tool_call': {
- const toolName = update.title || 'unknown'
- chunks.push({
- type: 'tool-input-start',
- toolCallId: update.toolCallId,
- toolName,
- providerExecuted: true,
- title: update.title
- })
- if (update.rawInput) {
- chunks.push({
- type: 'tool-input-available',
- toolCallId: update.toolCallId,
- toolName,
- input: update.rawInput,
- providerExecuted: true,
- title: update.title
- })
- }
- break
- }
- case 'tool_call_update': {
- if (update.status === 'completed') {
- chunks.push({
- type: 'tool-output-available',
- toolCallId: update.toolCallId,
- output: update.rawOutput ?? textFromContent(update.content ?? undefined),
- providerExecuted: true
- })
- } else if (update.status === 'failed') {
- chunks.push({
- type: 'tool-output-error',
- toolCallId: update.toolCallId,
- errorText: textFromContent(update.content ?? undefined) ?? 'Tool call failed',
- providerExecuted: true
- })
- }
- break
- }
- }
-
- return { chunks, textStarted }
-}
-
-// eslint-disable-next-line @typescript-eslint/no-explicit-any -- ACP content blocks have dynamic shape
-function textFromContent(content: any[] | undefined): string | undefined {
- if (!content) return undefined
- return content
- .filter(
- (c: Record<string, unknown>) =>
- c.type === 'content' &&
- (c.content as Record<string, unknown> | undefined)?.type === 'text'
- )
- .map(
- (c: Record<string, unknown>) =>
- (c.content as Record<string, string>).text
- )
- .join('\n')
-}
diff --git a/src/automation/spawn-mcp.ts b/src/automation/spawn-mcp.ts
new file mode 100644
index 000000000..4fa254377
--- /dev/null
+++ b/src/automation/spawn-mcp.ts
@@ -0,0 +1,55 @@
+import { AUTOMATION_HTTP_PORT, IS_TAURI } from '@open-pencil/core'
+
+async function checkHealth(): Promise<boolean> {
+ try {
+ const res = await fetch(`http://127.0.0.1:${AUTOMATION_HTTP_PORT}/health`, {
+ signal: AbortSignal.timeout(1000)
+ })
+ return res.ok
+ } catch {
+ return false
+ }
+}
+
+async function pollHealth(retries: number, delayMs: number): Promise<boolean> {
+ for (let i = 0; i < retries; i++) {
+ await new Promise((r) => setTimeout(r, delayMs))
+ if (await checkHealth()) return true
+ }
+ return false
+}
+
+export async function spawnMcpIfNeeded(): Promise<(() => void) | null> {
+ if (import.meta.env.DEV || !IS_TAURI) return null
+
+ if (await checkHealth()) return null
+
+ // @ts-expect-error — Tauri runtime-only module, not resolvable in lint/test environments
+ const { Command } = await import('@tauri-apps/plugin-shell')
+ const command = Command.create('openpencil-mcp', [])
+
+ command.stderr.on('data', (raw: Uint8Array | number[] | string) => {
+ const text =
+ typeof raw === 'string'
+ ? raw
+ : new TextDecoder().decode(raw instanceof Uint8Array ? raw : new Uint8Array(raw))
+ console.error('[MCP]', text)
+ })
+
+ command.on('close', (data: { code: number | null }) => {
+ console.error(`[MCP] Server exited (code ${data.code ?? 'null'})`)
+ })
+
+ const child = await command.spawn()
+
+ if (await pollHealth(5, 1000)) {
+ return () => {
+ void child.kill()
+ }
+ }
+
+ await child.kill()
+ throw new Error(
+ 'Failed to start MCP server. Is openpencil-mcp installed? Run: npm i -g @open-pencil/mcp'
+ )
+}
diff --git a/src/automation/vite-plugin.ts b/src/automation/vite-plugin.ts
index 1a0dd3efe..d8b1d4243 100644
--- a/src/automation/vite-plugin.ts
+++ b/src/automation/vite-plugin.ts
@@ -2,6 +2,7 @@ import { spawn } from 'node:child_process'
import type { Plugin } from 'vite'
+// TODO: production — bundle MCP server as Tauri sidecar or spawn via shell plugin
export function automationPlugin(): Plugin {
let child: ReturnType<typeof spawn> | null = null
@@ -11,11 +12,29 @@ export function automationPlugin(): Plugin {
if (child) return
child = spawn('bun', ['run', 'packages/mcp/src/index.ts'], {
- stdio: 'inherit',
+ stdio: ['ignore', 'inherit', 'pipe'],
env: { ...process.env, PORT: '7600', WS_PORT: '7601' }
})
- child.on('exit', () => { child = null })
+ child.stderr?.on('data', (data: Buffer) => {
+ const text = data.toString()
+ if (text.includes('EADDRINUSE')) {
+ console.error(
+ '\x1b[31m[MCP] Port 7600 already in use. Is another OpenPencil instance running?\x1b[0m'
+ )
+ child?.kill()
+ child = null
+ return
+ }
+ process.stderr.write(data)
+ })
+
+ child.on('exit', (code) => {
+ if (code && code !== 0 && child) {
+ console.error(`[MCP] Server exited with code ${code}`)
+ }
+ child = null
+ })
},
buildEnd() {
child?.kill()
diff --git a/src/components/ChatPanel.vue b/src/components/ChatPanel.vue
index 05da74aea..2d1a405ec 100644
--- a/src/components/ChatPanel.vue
+++ b/src/components/ChatPanel.vue
@@ -4,6 +4,7 @@ import { computed, markRaw, nextTick, ref, watch } from 'vue'
import { copyChatLog } from '@/ai/chat-debug'
import { clearToolLogEntries, didHitStepLimit } from '@/ai/tools'
+import AcpPermissionDialog from '@/components/chat/AcpPermissionDialog.vue'
import ChatInput from '@/components/chat/ChatInput.vue'
import ChatMessage from '@/components/chat/ChatMessage.vue'
import ProviderSetup from '@/components/chat/ProviderSetup.vue'
@@ -190,6 +191,8 @@ function handleClearChat() {
</div>
<ChatInput :status="status" @submit="handleSubmit" @stop="handleStop" />
+
+ <AcpPermissionDialog />
</template>
</div>
</template>
diff --git a/src/components/chat/AcpPermissionDialog.vue b/src/components/chat/AcpPermissionDialog.vue
new file mode 100644
index 000000000..4fb29c5b6
--- /dev/null
+++ b/src/components/chat/AcpPermissionDialog.vue
@@ -0,0 +1,103 @@
+<script setup lang="ts">
+import {
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogOverlay,
+ AlertDialogPortal,
+ AlertDialogRoot,
+ AlertDialogTitle
+} from 'reka-ui'
+import { computed } from 'vue'
+
+import {
+ currentPermission,
+ rejectCurrentPermission,
+ respondToPermission
+} from '@/ai/acp-permission'
+
+const open = computed(() => currentPermission.value !== null)
+
+interface ToolCallInfo {
+ title?: string
+ rawInput?: unknown
+}
+
+const toolCall = computed(
+ (): ToolCallInfo => (currentPermission.value?.request.toolCall as ToolCallInfo) ?? {}
+)
+
+const toolName = computed(() => toolCall.value.title ?? 'Unknown tool')
+
+const toolInput = computed(() => {
+ const raw = toolCall.value.rawInput
+ if (!raw) return null
+ try {
+ return JSON.stringify(raw, null, 2)
+ } catch {
+ return String(raw)
+ }
+})
+
+const allowOptions = computed(
+ () => currentPermission.value?.request.options.filter((o) => o.kind.startsWith('allow')) ?? []
+)
+
+const rejectOptions = computed(
+ () => currentPermission.value?.request.options.filter((o) => o.kind.startsWith('reject')) ?? []
+)
+
+function handleDismiss() {
+ rejectCurrentPermission()
+}
+</script>
+
+<template>
+ <AlertDialogRoot :open="open">
+ <AlertDialogPortal>
+ <AlertDialogOverlay class="fixed inset-0 z-50 bg-black/50" @click="handleDismiss" />
+ <AlertDialogContent
+ data-test-id="acp-permission-dialog"
+ class="fixed top-1/2 left-1/2 z-50 w-80 -translate-x-1/2 -translate-y-1/2 rounded-lg border border-border bg-panel p-4 shadow-xl"
+ @escape-key-down="handleDismiss"
+ >
+ <AlertDialogTitle class="text-sm font-semibold text-surface">
+ Permission Request
+ </AlertDialogTitle>
+
+ <AlertDialogDescription class="mt-2 text-xs text-muted">
+ <span class="font-medium text-surface">{{ toolName }}</span> is requesting permission.
+ </AlertDialogDescription>
+
+ <pre
+ v-if="toolInput"
+ class="mt-2 max-h-32 overflow-auto rounded bg-input p-2 text-[10px] text-muted"
+ >{{ toolInput }}</pre
+ >
+
+ <div class="mt-4 flex flex-col gap-2">
+ <AlertDialogAction
+ v-for="opt in allowOptions"
+ :key="opt.optionId"
+ :data-test-id="`acp-permission-option-${opt.kind}`"
+ class="w-full rounded bg-accent px-3 py-1.5 text-xs font-medium text-white hover:bg-accent/90"
+ @click="respondToPermission(opt.optionId)"
+ >
+ {{ opt.name }}
+ </AlertDialogAction>
+
+ <AlertDialogCancel
+ v-for="opt in rejectOptions"
+ :key="opt.optionId"
+ :data-test-id="`acp-permission-option-${opt.kind}`"
+ class="w-full rounded border border-border bg-canvas px-3 py-1.5 text-xs text-muted hover:bg-hover hover:text-surface"
+ @click="respondToPermission(opt.optionId)"
+ >
+ {{ opt.name }}
+ </AlertDialogCancel>
+ </div>
+ </AlertDialogContent>
+ </AlertDialogPortal>
+ </AlertDialogRoot>
+</template>
diff --git a/src/components/chat/ProviderSelect.vue b/src/components/chat/ProviderSelect.vue
index 77382cccc..192fa6640 100644
--- a/src/components/chat/ProviderSelect.vue
+++ b/src/components/chat/ProviderSelect.vue
@@ -11,19 +11,44 @@ import {
SelectTrigger,
SelectViewport
} from 'reka-ui'
-import { computed } from 'vue'
+import { computed, onMounted, ref } from 'vue'
import { selectContent, selectItem, selectTrigger } from '@/components/ui/select'
-import { ACP_AGENTS, AI_PROVIDERS, IS_TAURI } from '@open-pencil/core'
+import { ACP_AGENTS, AI_PROVIDERS, AUTOMATION_HTTP_PORT, IS_TAURI } from '@open-pencil/core'
import { useAIChat } from '@/composables/use-chat'
const { providerID, providerDef } = useAIChat()
-const acpAgents = IS_TAURI ? ACP_AGENTS : []
+
+const mcpAvailable = ref(false)
+
+async function checkMcpHealth(retries = 3, delayMs = 1000) {
+ for (let i = 0; i < retries; i++) {
+ try {
+ const res = await fetch(`http://127.0.0.1:${AUTOMATION_HTTP_PORT}/health`, {
+ signal: AbortSignal.timeout(2000)
+ })
+ if (res.ok) {
+ mcpAvailable.value = true
+ return
+ }
+ } catch {
+ if (i < retries - 1) await new Promise((r) => setTimeout(r, delayMs))
+ }
+ }
+}
+
+if (IS_TAURI) {
+ onMounted(() => {
+ void checkMcpHealth()
+ })
+}
+
+const acpAgents = computed(() => (IS_TAURI && mcpAvailable.value ? ACP_AGENTS : []))
const displayName = computed(() => {
if (providerID.value.startsWith('acp:')) {
const agentId = providerID.value.replace('acp:', '')
- return acpAgents.find((a) => a.id === agentId)?.name ?? providerID.value
+ return ACP_AGENTS.find((a) => a.id === agentId)?.name ?? providerID.value
}
return providerDef.value.name
})
diff --git a/src/components/chat/ProviderSetup.vue b/src/components/chat/ProviderSetup.vue
index 19b4d521d..e6ddd8b2b 100644
--- a/src/components/chat/ProviderSetup.vue
+++ b/src/components/chat/ProviderSetup.vue
@@ -93,7 +93,9 @@ function save() {
<p class="text-center text-[10px] leading-relaxed text-muted">
Uses your existing {{ acpAgent?.name }} subscription. Make sure
- <code class="rounded bg-input px-1 py-0.5 font-mono text-[9px]">{{ acpAgent?.command }}</code>
+ <code class="rounded bg-input px-1 py-0.5 font-mono text-[9px]">{{
+ acpAgent?.command
+ }}</code>
is installed and authenticated.
</p>
</div>
diff --git a/src/composables/use-chat.ts b/src/composables/use-chat.ts
index 09d9c5db3..5e952631c 100644
--- a/src/composables/use-chat.ts
+++ b/src/composables/use-chat.ts
@@ -258,9 +258,7 @@ async function ensureChat(): Promise<Chat<UIMessage> | null> {
if (!isConfigured.value) return null
if (!chat || transportDirty) {
const messages = chat?.messages
- const transport = isACPProvider.value
- ? await createACPTransport()
- : createTransport()
+ const transport = isACPProvider.value ? await createACPTransport() : createTransport()
chat = new Chat<UIMessage>({ transport, messages })
transportDirty = false
}
diff --git a/src/constants.ts b/src/constants.ts
index 91f04fe22..52c56a162 100644
--- a/src/constants.ts
+++ b/src/constants.ts
@@ -138,3 +138,12 @@ export const SECTION_DEFAULT_STROKE: Stroke = {
visible: true,
align: 'INSIDE'
}
+
+export const ACP_PERMISSION_TIMEOUT_MS = 60_000
+
+export const ACP_DESIGN_CONTEXT = `You are inside OpenPencil, an open-source design editor (like Figma). \
+Use the open-pencil MCP tools to create and modify designs on the live canvas. \
+Key tools: render (JSX to design), create_shape, set_fill, set_layout, find_nodes, get_page_tree, export_image. \
+The render tool accepts JSX with components: Frame, Text, Rectangle, Ellipse, Icon, Group, Section. \
+Props: w, h, bg, flex, gap, p, rounded, color, size, weight, items, justify, stroke, opacity, shadow. \
+Do NOT write HTML files or use terminal commands — draw directly on the canvas using the MCP tools.`
diff --git a/src/views/EditorView.vue b/src/views/EditorView.vue
index 00a62fdfd..f77887321 100644
--- a/src/views/EditorView.vue
+++ b/src/views/EditorView.vue
@@ -1,5 +1,5 @@
<script setup lang="ts">
-import { provide, onUnmounted } from 'vue'
+import { onMounted, onUnmounted, provide, ref } from 'vue'
import { useBreakpoints, useEventListener, useUrlSearchParams } from '@vueuse/core'
import { useRoute } from 'vue-router'
import { useHead } from '@unhead/vue'
@@ -9,6 +9,7 @@ import { useKeyboard } from '@/composables/use-keyboard'
import { useMenu } from '@/composables/use-menu'
import { useCollab, COLLAB_KEY } from '@/composables/use-collab'
import { connectAutomation } from '@/automation/server'
+import { spawnMcpIfNeeded } from '@/automation/spawn-mcp'
import { createDemoShapes } from '@/demo'
import { useEditorStore } from '@/stores/editor'
import { createTab, activeTab, getActiveStore } from '@/stores/tabs'
@@ -31,7 +32,18 @@ const isMobile = breakpoints.smaller('mobile')
useKeyboard()
useMenu()
const { disconnect: disconnectAutomation } = connectAutomation(getActiveStore)
-onUnmounted(disconnectAutomation)
+const mcpCleanup = ref<(() => void) | null>(null)
+onMounted(async () => {
+ try {
+ mcpCleanup.value = await spawnMcpIfNeeded()
+ } catch (e) {
+ console.error(e)
+ }
+})
+onUnmounted(() => {
+ mcpCleanup.value?.()
+ disconnectAutomation()
+})
const collab = useCollab(firstTab.store)
provide(COLLAB_KEY, collab)
diff --git a/tests/engine/acp-permission.test.ts b/tests/engine/acp-permission.test.ts
new file mode 100644
index 000000000..3539e0aa5
--- /dev/null
+++ b/tests/engine/acp-permission.test.ts
@@ -0,0 +1,143 @@
+import { describe, expect, test, beforeEach } from 'bun:test'
+
+import {
+ permissionQueue,
+ currentPermission,
+ requestPermissionFromUser,
+ respondToPermission,
+ rejectCurrentPermission
+} from '../../src/ai/acp-permission'
+
+import type { RequestPermissionRequest } from '@agentclientprotocol/sdk'
+
+function makeRequest(
+ options: { optionId: string; kind: string; name: string }[] = [
+ { optionId: 'allow', kind: 'allow_once', name: 'Allow once' },
+ { optionId: 'reject', kind: 'reject_once', name: 'Reject' }
+ ]
+): RequestPermissionRequest {
+ return {
+ sessionId: 'session-1',
+ options: options.map((o) => ({
+ optionId: o.optionId,
+ kind: o.kind as 'allow_once' | 'allow_always' | 'reject_once' | 'reject_always',
+ name: o.name
+ })),
+ toolCall: {
+ sessionUpdate: 'tool_call_update',
+ toolCallId: 'tc-1',
+ status: 'pending' as const
+ }
+ }
+}
+
+describe('acp-permission', () => {
+ beforeEach(() => {
+ permissionQueue.value = []
+ })
+
+ test('requestPermissionFromUser queues an entry', () => {
+ void requestPermissionFromUser(makeRequest())
+ expect(permissionQueue.value).toHaveLength(1)
+ expect(currentPermission.value).not.toBeNull()
+ expect(currentPermission.value?.request.sessionId).toBe('session-1')
+ respondToPermission('allow')
+ })
+
+ test('respondToPermission resolves with selected optionId', async () => {
+ const promise = requestPermissionFromUser(makeRequest())
+ respondToPermission('allow')
+ const result = await promise
+ expect(result.outcome.outcome).toBe('selected')
+ expect(result.outcome.optionId).toBe('allow')
+ expect(permissionQueue.value).toHaveLength(0)
+ })
+
+ test('rejectCurrentPermission picks reject option', async () => {
+ const promise = requestPermissionFromUser(makeRequest())
+ rejectCurrentPermission()
+ const result = await promise
+ expect(result.outcome.optionId).toBe('reject')
+ })
+
+ test('rejectCurrentPermission falls back to first option when no reject kind', async () => {
+ const req = makeRequest([{ optionId: 'only-allow', kind: 'allow_once', name: 'Allow' }])
+ const promise = requestPermissionFromUser(req)
+ rejectCurrentPermission()
+ const result = await promise
+ expect(result.outcome.optionId).toBe('only-allow')
+ })
+
+ test('queue handles multiple concurrent requests in order', async () => {
+ const p1 = requestPermissionFromUser(
+ makeRequest([{ optionId: 'a1', kind: 'allow_once', name: 'First' }])
+ )
+ const p2 = requestPermissionFromUser(
+ makeRequest([{ optionId: 'a2', kind: 'allow_once', name: 'Second' }])
+ )
+ expect(permissionQueue.value).toHaveLength(2)
+ expect(currentPermission.value?.request.options[0].optionId).toBe('a1')
+
+ respondToPermission('a1')
+ const r1 = await p1
+ expect(r1.outcome.optionId).toBe('a1')
+ expect(currentPermission.value?.request.options[0].optionId).toBe('a2')
+
+ respondToPermission('a2')
+ const r2 = await p2
+ expect(r2.outcome.optionId).toBe('a2')
+ expect(permissionQueue.value).toHaveLength(0)
+ })
+
+ test('respondToPermission is no-op when queue is empty', () => {
+ expect(permissionQueue.value).toHaveLength(0)
+ respondToPermission('anything')
+ expect(permissionQueue.value).toHaveLength(0)
+ })
+
+ test('rejectCurrentPermission is no-op when queue is empty', () => {
+ expect(permissionQueue.value).toHaveLength(0)
+ rejectCurrentPermission()
+ expect(permissionQueue.value).toHaveLength(0)
+ })
+
+ test('timer cleared on manual resolution (no double resolve)', async () => {
+ const promise = requestPermissionFromUser(makeRequest())
+ respondToPermission('allow')
+ const result = await promise
+ expect(result.outcome.optionId).toBe('allow')
+ // Timer should be cleared — wait to ensure no stale timeout fires
+ await new Promise((r) => setTimeout(r, 50))
+ expect(permissionQueue.value).toHaveLength(0)
+ })
+
+ test('timeout auto-rejects after delay', async () => {
+ const req = makeRequest()
+ // Override timeout for test speed by creating request and manually triggering the timer
+ const promise = requestPermissionFromUser(req)
+ const entry = permissionQueue.value[0]
+ expect(entry).toBeDefined()
+
+ // Fast-forward: manually fire the timer callback
+ clearTimeout(entry.timer)
+ const timerFn = () => {
+ const idx = permissionQueue.value.indexOf(entry)
+ if (idx === -1) return
+ permissionQueue.value = permissionQueue.value.filter((e) => e !== entry)
+ entry.resolve({
+ outcome: {
+ outcome: 'selected',
+ optionId:
+ req.options.find((o) => o.kind.startsWith('reject'))?.optionId ??
+ req.options[0]?.optionId ??
+ ''
+ }
+ })
+ }
+ timerFn()
+
+ const result = await promise
+ expect(result.outcome.optionId).toBe('reject')
+ expect(permissionQueue.value).toHaveLength(0)
+ })
+})
diff --git a/tests/engine/acp-transport.test.ts b/tests/engine/acp-transport.test.ts
index 7f0ff8741..649eda53e 100644
--- a/tests/engine/acp-transport.test.ts
+++ b/tests/engine/acp-transport.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, test } from 'bun:test'
-import { mapUpdate } from '../../src/ai/acp-transport'
+import { mapUpdate } from '../../src/ai/acp-map-update'
+import { formatConnectionError, buildCrashChunks } from '../../src/ai/acp-transport'
import type { SessionUpdate } from '@agentclientprotocol/sdk'
@@ -141,6 +142,16 @@ describe('mapUpdate', () => {
}])
})
+ test('agent_message_chunk with non-text content produces no chunks', () => {
+ const update: SessionUpdate = {
+ sessionUpdate: 'agent_message_chunk',
+ content: { type: 'image', url: 'https://example.com/img.png' }
+ }
+ const result = mapUpdate(update, TEXT_ID, false)
+ expect(result.textStarted).toBe(false)
+ expect(result.chunks).toEqual([])
+ })
+
test('unhandled update type produces no chunks', () => {
const update = {
sessionUpdate: 'available_commands_update',
@@ -151,3 +162,55 @@ describe('mapUpdate', () => {
expect(result.textStarted).toBe(false)
})
})
+
+describe('formatConnectionError', () => {
+ test('ECONNREFUSED maps to MCP not running', () => {
+ const msg = formatConnectionError(new Error('connect ECONNREFUSED 127.0.0.1:7600'))
+ expect(msg).toBe('MCP server is not running. Make sure the editor is open.')
+ })
+
+ test('fetch failed maps to MCP not running', () => {
+ const msg = formatConnectionError(new Error('fetch failed'))
+ expect(msg).toBe('MCP server is not running. Make sure the editor is open.')
+ })
+
+ test('timeout maps to timeout message', () => {
+ const msg = formatConnectionError(new Error('Request timeout after 30s'))
+ expect(msg).toBe('MCP server did not respond in time.')
+ })
+
+ test('other errors pass through', () => {
+ const msg = formatConnectionError(new Error('Something unexpected'))
+ expect(msg).toBe('Something unexpected')
+ })
+
+ test('non-Error values converted to string', () => {
+ const msg = formatConnectionError('raw string error')
+ expect(msg).toBe('raw string error')
+ })
+})
+
+describe('buildCrashChunks', () => {
+ test('destroying=true returns empty chunks, no session null', () => {
+ const result = buildCrashChunks(true, TEXT_ID, false)
+ expect(result.chunks).toEqual([])
+ expect(result.shouldNullSession).toBe(false)
+ })
+
+ test('destroying=false with no text emits error + finish', () => {
+ const result = buildCrashChunks(false, TEXT_ID, false)
+ expect(result.shouldNullSession).toBe(true)
+ expect(result.chunks).toEqual([
+ { type: 'error', errorText: 'Agent process exited unexpectedly.' },
+ { type: 'finish-step' },
+ { type: 'finish', finishReason: 'error' }
+ ])
+ })
+
+ test('destroying=false with active text emits text-end before error', () => {
+ const result = buildCrashChunks(false, TEXT_ID, true)
+ expect(result.shouldNullSession).toBe(true)
+ expect(result.chunks[0]).toEqual({ type: 'text-end', id: TEXT_ID })
+ expect(result.chunks[1]).toEqual({ type: 'error', errorText: 'Agent process exited unexpectedly.' })
+ })
+})
diff --git a/tests/engine/mcp-server.test.ts b/tests/engine/mcp-server.test.ts
index b0eaeb9fa..04e55a7a4 100644
--- a/tests/engine/mcp-server.test.ts
+++ b/tests/engine/mcp-server.test.ts
@@ -14,14 +14,7 @@ import {
} from '@open-pencil/core'
import { serve } from '@hono/node-server'
-let httpPort = 17600
-let wsPort = 17601
-
-function nextPorts() {
- httpPort += 2
- wsPort += 2
- return { httpPort, wsPort }
-}
+import type { AddressInfo } from 'node:net'
interface MockBrowser {
ws: WebSocket
@@ -80,16 +73,28 @@ function connectMockBrowser(port: number, graph: SceneGraph): Promise<MockBrowse
})
}
-async function createTestClient(ports: { httpPort: number; wsPort: number }) {
- const { app, wss } = startServer(ports)
- const httpServer = serve({ fetch: app.fetch, port: ports.httpPort, hostname: '127.0.0.1' })
+function waitForWsListening(wss: InstanceType<typeof WebSocket.Server>): Promise<number> {
+ return new Promise((resolve) => {
+ if (wss.address()) {
+ resolve((wss.address() as AddressInfo).port)
+ return
+ }
+ wss.on('listening', () => resolve((wss.address() as AddressInfo).port))
+ })
+}
+
+async function createTestClient() {
+ const { app, wss } = startServer({ httpPort: 0, wsPort: 0 })
+ const httpServer = serve({ fetch: app.fetch, port: 0, hostname: '127.0.0.1' })
+ const actualHttpPort = (httpServer.address() as AddressInfo).port
+ const actualWsPort = await waitForWsListening(wss)
const graph = new SceneGraph()
- const browser = await connectMockBrowser(ports.wsPort, graph)
+ const browser = await connectMockBrowser(actualWsPort, graph)
const client = new Client({ name: 'test-client', version: '0.0.0' })
const transport = new StreamableHTTPClientTransport(
- new URL(`http://127.0.0.1:${ports.httpPort}/mcp`)
+ new URL(`http://127.0.0.1:${actualHttpPort}/mcp`)
)
await client.connect(transport)
@@ -116,7 +121,7 @@ describe('MCP server', () => {
let cleanup: () => Promise<void>
beforeEach(async () => {
- const ctx = await createTestClient(nextPorts())
+ const ctx = await createTestClient()
client = ctx.client
graph = ctx.graph
cleanup = ctx.close