Skip to content

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

feat: detect, sign in, and connect coding agents to OpenPencil's tools (#1366)

Danila Poyarkov4820c8947518
diff --git a/changes/1366/added.md b/changes/1366/added.md
new file mode 100644
index 000000000..c41d8029d
--- /dev/null
+++ b/changes/1366/added.md
@@ -0,0 +1,2 @@
+- On desktop, AI setup shows whether Claude Code, Codex, and Pi are installed and signed in, names the account Claude Code and Codex use, and signs them in from the setup screen.
+- Coding agent chats send your message only once the agent has connected to OpenPencil's tools, and otherwise say why it could not.
diff --git a/changes/1366/fixed.md b/changes/1366/fixed.md
new file mode 100644
index 000000000..dad30aca6
--- /dev/null
+++ b/changes/1366/fixed.md
@@ -0,0 +1,2 @@
+- Claude Code, Codex, and Gemini CLI chats end when the agent finishes its turn, instead of staying busy until the agent exits; their OpenPencil tool calls show under the tools' names with their results instead of as failed, a run of thoughts shows as one, and an MCP server that fails to start shows its error instead of spinning.
+- Coding agent chats start the agent in a folder of OpenPencil's own instead of your home folder, so it no longer reads project settings kept there or may write across it.
diff --git a/desktop/capabilities/default.json b/desktop/capabilities/default.json
index 94e27a561..600827e2a 100644
--- a/desktop/capabilities/default.json
+++ b/desktop/capabilities/default.json
@@ -128,6 +128,11 @@
"identifier": "shell:allow-spawn",
"allow": [
{ "name": "claude-agent-acp", "cmd": "claude-agent-acp", "args": false },
+ {
+ "name": "claude-agent-acp-sign-in",
+ "cmd": "claude-agent-acp",
+ "args": ["--cli", "auth", "login", "--claudeai"]
+ },
{ "name": "codex-acp", "cmd": "codex-acp", "args": false },
{ "name": "gemini", "cmd": "gemini", "args": ["--acp"] },
{
@@ -157,6 +162,11 @@
{ "name": "openpencil-mcp-http", "cmd": "openpencil-mcp-http", "args": false },
{ "name": "openpencil-harness", "cmd": "openpencil-harness", "args": false },
{ "name": "cmd-claude-agent-acp", "cmd": "cmd", "args": ["/c", "claude-agent-acp"] },
+ {
+ "name": "cmd-claude-agent-acp-sign-in",
+ "cmd": "cmd",
+ "args": ["/c", "claude-agent-acp", "--cli", "auth", "login", "--claudeai"]
+ },
{ "name": "cmd-codex-acp", "cmd": "cmd", "args": ["/c", "codex-acp"] },
{ "name": "cmd-gemini", "cmd": "cmd", "args": ["/c", "gemini", "--acp"] },
{
diff --git a/desktop/src/agents.rs b/desktop/src/agents.rs
index c8f96106b..0a86f29e2 100644
--- a/desktop/src/agents.rs
+++ b/desktop/src/agents.rs
@@ -198,6 +198,21 @@ pub async fn agent_lookup() -> Result<AgentLookup, String> {
.map_err(|_| "Could not discover local agents.".to_owned())
}
+/// The folder coding agents start in. Starting them in the home folder lets them read its
+/// project settings (Codex reads `.codex` there) and, sandboxed, write anywhere in it.
+#[tauri::command]
+pub fn agent_workspace(app: tauri::AppHandle) -> Result<String, String> {
+ use tauri::Manager;
+ let dir = app
+ .path()
+ .app_data_dir()
+ .map_err(|e| format!("Could not find the app data folder: {e}"))?
+ .join("agent-workspace");
+ std::fs::create_dir_all(&dir)
+ .map_err(|e| format!("Could not create the agent workspace: {e}"))?;
+ Ok(dir.to_string_lossy().into_owned())
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/desktop/src/lib.rs b/desktop/src/lib.rs
index 650a2e8f7..1c6e08226 100644
--- a/desktop/src/lib.rs
+++ b/desktop/src/lib.rs
@@ -417,6 +417,7 @@ pub fn run() {
.manage(PendingCloudLinks(Mutex::new(Vec::new())))
.invoke_handler(tauri::generate_handler![
agents::agent_lookup,
+ agents::agent_workspace,
build_fig_file,
credential_read,
credential_access_paused,
diff --git a/packages/core/src/ai/providers.ts b/packages/core/src/ai/providers.ts
index c20a06320..6ea2dda17 100644
--- a/packages/core/src/ai/providers.ts
+++ b/packages/core/src/ai/providers.ts
@@ -14,6 +14,12 @@ export interface ACPAgentDef {
/** The vendor's installation guide for the agent itself. */
setupURL?: string
installCommand?: string
+ /**
+ * The ACP auth method setup signs in with, once the agent offers it. `acp` methods run inside
+ * the agent through `authenticate`; `terminal` methods run the agent's command with `args`,
+ * which the desktop shell scope pins under `<command>-sign-in`.
+ */
+ signIn?: { via: 'acp'; method: string } | { via: 'terminal'; method: string; args: string[] }
}
export const ACP_AGENTS: ACPAgentDef[] = [
@@ -25,7 +31,12 @@ export const ACP_AGENTS: ACPAgentDef[] = [
cliCommand: 'claude',
adapterPackage: '@agentclientprotocol/claude-agent-acp',
setupURL: 'https://code.claude.com/docs/en/setup',
- installCommand: 'npm i -g @agentclientprotocol/claude-agent-acp'
+ installCommand: 'npm i -g @agentclientprotocol/claude-agent-acp',
+ signIn: {
+ via: 'terminal',
+ method: 'claude-ai-login',
+ args: ['--cli', 'auth', 'login', '--claudeai']
+ }
},
{
id: 'codex',
@@ -35,7 +46,8 @@ export const ACP_AGENTS: ACPAgentDef[] = [
cliCommand: 'codex',
adapterPackage: '@agentclientprotocol/codex-acp',
setupURL: 'https://developers.openai.com/codex/cli',
- installCommand: 'npm i -g @agentclientprotocol/codex-acp'
+ installCommand: 'npm i -g @agentclientprotocol/codex-acp',
+ signIn: { via: 'acp', method: 'chat-gpt' }
},
{
id: 'gemini-cli',
diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.ts
index c93aca754..9d6256be2 100644
--- a/packages/core/src/constants.ts
+++ b/packages/core/src/constants.ts
@@ -179,6 +179,15 @@ export const AUTOMATION_HTTP_PORT = 7600
*/
export const MCP_AGENT_HEADER = 'x-openpencil-agent'
+/** The name the app's chats give OpenPencil's MCP server in an agent's session. */
+export const OPEN_PENCIL_MCP_SERVER = 'open-pencil'
+
+/**
+ * Request header naming the app chat whose agent opens an MCP session, so the app can tell that
+ * this chat's agent reached its tools before it sends the prompt.
+ */
+export const MCP_CHAT_HEADER = 'x-openpencil-chat'
+
export const GOOGLE_FONTS_API_KEY = 'AIzaSyD1tYDR_dUEiV-Tw1vksEhZbUytgKW5pc8'
export const CJK_FALLBACK_FAMILIES_MACOS = [
diff --git a/packages/docs/programmable/coding-agents.md b/packages/docs/programmable/coding-agents.md
index b609552b1..620590543 100644
--- a/packages/docs/programmable/coding-agents.md
+++ b/packages/docs/programmable/coding-agents.md
@@ -7,16 +7,16 @@ Coding agents need the desktop app; the browser cannot start programs on your co
## What you need
1. The [OpenPencil desktop app](/download).
-2. The agent's ACP program, installed globally (see each agent below).
+2. The agent's ACP program, installed globally (see each agent below). Claude Code's and Codex's ACP programs include the agent, so their own command-line tools are optional.
3. OpenPencil's MCP server, installed globally. Use the version that matches your app:
```sh
npm install -g @open-pencil/mcp
```
-4. The agent signed in to your account with its own command-line tool.
+4. The agent signed in to your account. Pi can use an AI Gateway key instead (see [Pi](#pi)).
-Then open **Settings → AI & agents → Run guided setup**, choose the agent under **Coding agents on this computer**, and check that both the agent and the MCP server show as installed. **Check again** looks again after you install something.
+Then open **Settings → AI & agents → Run guided setup**, choose the agent under **Coding agents on this computer**, and check that both the agent and the MCP server show as installed. **Install adapter** runs the npm command shown under it. Once the ACP program is installed, guided setup asks the agent which account it uses and shows what it reports, such as the plan and email; when it is not signed in, **Sign in** opens the agent's own login in your browser. For a signed-in agent, **OpenPencil tools** shows whether a session reaches OpenPencil's MCP server, checked the way a chat starts, without sending a message. **Check again** repeats the check after you install something or sign in elsewhere.
### Let your agent set itself up
@@ -28,7 +28,7 @@ If you already use one of these agents in a terminal, guided setup can do the ty
npm install -g @agentclientprotocol/claude-agent-acp
```
-Sign in by running `claude` and using `/login`. The ACP program uses the same account as Claude Code.
+Sign in from guided setup, or by running `claude` and using `/login`. The ACP program uses the same account as Claude Code. If the browser cannot hand the sign-in back, the sign-in page shows a code to paste into guided setup.
## Codex
@@ -36,7 +36,9 @@ Sign in by running `claude` and using `/login`. The ACP program uses the same ac
npm install -g @agentclientprotocol/codex-acp
```
-Sign in with `codex login`.
+Sign in with ChatGPT from guided setup, or with `codex login`; both use the same account.
+
+An older adapter from the `@zed-industries/codex-acp` package also installs a `codex-acp` program. It neither reports nor signs in to your account, so guided setup asks you to install the supported one and to remove the older one or put it later on your `PATH`.
## Gemini CLI
@@ -62,5 +64,7 @@ OpenPencil reads only Pi's `settings.json` for the default model; your credentia
- **Shown as not found after installing.** Apps started from the Dock or Start menu do not see every folder your terminal adds to `PATH`. OpenPencil also looks in common global folders for npm, Bun, Volta, mise, and Homebrew; if your package manager installs elsewhere, add that folder to your login shell's `PATH` and restart OpenPencil.
- **Shown as update needed.** The MCP server or Pi's companion does not match the app version. Press the update button, or run the command guided setup shows with the package manager that installed it, then press **Check again**. A chat that needs it says so and offers **Run guided setup**.
+- **The agent couldn't reach OpenPencil's tools.** Before sending your message, OpenPencil waits for the agent to connect to its MCP server and stops if it does not, quoting the agent's reason when it gives one. Check that the MCP server shows as installed in guided setup and is running in **Settings → MCP**. Codex skips OpenPencil's server when its own `config.toml` defines a server named `open-pencil`; remove that entry.
- **The agent starts but cannot edit the canvas.** The MCP server is missing or not running. Install the matching `@open-pencil/mcp` version and restart OpenPencil.
-- **The agent asks you to sign in.** Sign in with the agent's own command-line tool as described above, then send your message again.
+- **Where the agent works.** Chats start the agent in a folder of its own inside OpenPencil's app data, not your home folder, so it does not pick up project settings kept there. The agent still uses its own configuration, such as the MCP servers and rules in `~/.codex` or `~/.claude`.
+- **The agent asks you to sign in.** Press **Sign in** in guided setup, or sign in with the agent's own command-line tool as described above, then send your message again.
diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.ts
index 06ed63892..f058c9f98 100644
--- a/packages/mcp/src/server.ts
+++ b/packages/mcp/src/server.ts
@@ -9,23 +9,18 @@ import { resolveCommand } from 'package-manager-detector/commands'
import { detect, getUserAgent } from 'package-manager-detector/detect'
import { WebSocketServer, type WebSocket } from 'ws'
-import { MCP_AGENT_HEADER } from '@open-pencil/core/constants'
+import { MCP_AGENT_HEADER, MCP_CHAT_HEADER } from '@open-pencil/core/constants'
import { bearerToken, isAuthorized, mcpRequestToken } from '#mcp/auth'
import { createBrowserRPCBridge } from '#mcp/browser-rpc'
import { MCP_CORS_HEADERS, MCP_CORS_METHODS, MCP_EXPOSED_HEADERS } from '#mcp/http-options'
import type { RPCJSONObject } from '#mcp/json'
import { registerFileRoutes } from '#mcp/server/files'
-import { createMCPSessionManager } from '#mcp/server/sessions'
+import { createMCPSessionManager, sessionOpener } from '#mcp/server/sessions'
import { createToolDescriptors } from '#mcp/tool/manifest'
import type { ToolDescriptor, ToolPolicy } from '#mcp/tool/metadata'
import { applyToolPolicy } from '#mcp/tool/policy'
-import {
- MCP_AGENT_KINDS,
- registerTools,
- type MCPAgentKind,
- type MCPAgentSession
-} from '#mcp/tool/registration'
+import { registerTools, type MCPAgentSession } from '#mcp/tool/registration'
import { scopeRPC, type MCPToolScope } from '#mcp/tool/scope'
import packageJSON from '../package.json' with { type: 'json' }
@@ -77,10 +72,6 @@ export {
type RPCSender
} from '#mcp/tool/registration'
-function agentKindFromHeader(value: string | undefined): MCPAgentKind {
- return MCP_AGENT_KINDS.find((kind) => kind === value) ?? 'mcp'
-}
-
export interface ServerOptions {
/** TCP port for the HTTP + WebSocket server. Ignored when `withTcp` is false. When set to 0 with `withTcp: true`, binds to an ephemeral port. Defaults to 7600. */
httpPort?: number
@@ -171,6 +162,8 @@ function createHonoApp(options: {
version: MCP_VERSION,
installCommand: await mcpInstallCommand(),
authRequired: authToken !== null,
+ // Tells the app it reports agent_session_opened, so a chat may wait for its agent.
+ agentSessionEvents: true,
...(canInspectConfiguration ? { tools: toolDescriptors } : {})
})
})
@@ -249,7 +242,7 @@ function createHonoApp(options: {
}
const transport = await mcpSessions.resolveTransport(
undefined,
- agentKindFromHeader(c.req.header(MCP_AGENT_HEADER))
+ sessionOpener(c.req.header(MCP_AGENT_HEADER), c.req.header(MCP_CHAT_HEADER))
)
if ('error' in transport) {
if (transport.error === 'closed') {
@@ -357,6 +350,11 @@ function buildServerContext(options: ServerOptions) {
agentSession,
onToolSettled
}),
+ onSessionOpened: ({ id, kind, chat }) => {
+ sendToBrowser({ command: 'agent_session_opened', args: { session: id, kind, chat } }).catch(
+ () => undefined
+ )
+ },
onSessionClosed: (sessionId) => {
// Best-effort: the app may be gone already, and then it shows no agents anyway.
sendToBrowser({ command: 'agent_session_closed', args: { session: sessionId } }).catch(
diff --git a/packages/mcp/src/server/sessions.ts b/packages/mcp/src/server/sessions.ts
index f725dfd94..59624344d 100644
--- a/packages/mcp/src/server/sessions.ts
+++ b/packages/mcp/src/server/sessions.ts
@@ -8,7 +8,7 @@ import {
import { withTimeout } from 'es-toolkit/promise'
import { createPendingRequests } from '#mcp/server/pending-requests'
-import type { MCPAgentKind, MCPAgentSession, MCPToolSettled } from '#mcp/tool/registration'
+import { MCP_AGENT_KINDS, type MCPAgentSession, type MCPToolSettled } from '#mcp/tool/registration'
export type MCPTransport = {
handleRequest: (request: Request) => Promise<Response>
@@ -22,8 +22,12 @@ type MCPSession = {
lastSeen: number
activeRequests: number
initialized: boolean
+ agent: MCPAgentSession
}
+/** Who opens a session, as its first request's headers say. */
+export type MCPSessionOpener = Omit<MCPAgentSession, 'id'>
+
type MCPSessionManagerOptions = {
serverVersion: string
registerTools: (
@@ -31,6 +35,8 @@ type MCPSessionManagerOptions = {
session: MCPAgentSession,
onToolSettled: MCPToolSettled
) => void
+ /** Told when a client's initialize succeeds, so an app chat knows its agent reached the tools. */
+ onSessionOpened?: (session: MCPAgentSession) => void
/** Told when a session ends, so the app stops showing its agent. */
onSessionClosed?: (sessionId: string) => void
/** Idle lifetime in ms; 0 disables expiration. Defaults to 15 minutes. */
@@ -38,6 +44,19 @@ type MCPSessionManagerOptions = {
}
const MAX_MCP_SESSIONS = 10
+/** App chat ids are random hex; anything else is ignored rather than forwarded. */
+const CHAT_ID = /^[0-9a-f]{16,64}$/
+
+/** The opener a session's first request names through the app's agent and chat headers. */
+export function sessionOpener(
+ kind: string | undefined,
+ chat: string | undefined
+): MCPSessionOpener {
+ return {
+ kind: MCP_AGENT_KINDS.find((candidate) => candidate === kind) ?? 'mcp',
+ ...(chat && CHAT_ID.test(chat) ? { chat } : {})
+ }
+}
const MCP_SESSION_IDLE_TIMEOUT_MS = 15 * 60_000
const MAX_SWEEP_INTERVAL_MS = 60_000
// The MCP SDK's close() does not enforce a timeout internally.
@@ -78,6 +97,7 @@ async function isInitializeResult(response: Response, id: string): Promise<boole
export function createMCPSessionManager({
serverVersion,
registerTools,
+ onSessionOpened,
onSessionClosed,
sessionIdleTimeoutMs = MCP_SESSION_IDLE_TIMEOUT_MS
}: MCPSessionManagerOptions) {
@@ -96,6 +116,15 @@ export function createMCPSessionManager({
return task
}
+ function notifyOpened(agent: MCPAgentSession) {
+ try {
+ onSessionOpened?.(agent)
+ } catch (e) {
+ // Application notification must not fail the client's initialize.
+ process.stderr.write(` MCP session: open notification warning (${describeError(e)})\n`)
+ }
+ }
+
function notifyToolsChanged() {
for (const session of sessions.values()) {
try {
@@ -125,13 +154,14 @@ export function createMCPSessionManager({
const creating = new Map<string, Promise<MCPTransport>>()
let closed = false
- async function createSession(id: string, kind: MCPAgentKind): Promise<MCPTransport> {
+ async function createSession(id: string, opener: MCPSessionOpener): Promise<MCPTransport> {
if (closed) throw new Error('Session manager is closed')
const inFlight = creating.get(id)
if (inFlight) return inFlight
const promise = (async () => {
const server = new McpServer({ name: 'open-pencil', version: serverVersion })
+ const agent: MCPAgentSession = { id, ...opener }
const transport = new WebStandardStreamableHTTPServerTransport({
sessionIdGenerator: () => id,
@@ -142,7 +172,7 @@ export function createMCPSessionManager({
// InitializeRequest is processed later by handleRequest; connect() alone
// does not establish a valid MCP session.
try {
- registerTools(server, { id, kind }, requests.releaseCancelled)
+ registerTools(server, agent, requests.releaseCancelled)
await server.connect(transport)
} catch (e) {
await closeSession({ transport, server })
@@ -162,6 +192,7 @@ export function createMCPSessionManager({
lastSeen: Date.now(),
activeRequests: 0,
initialized: false,
+ agent,
transport: {
close: () => transport.close(),
handleRequest: (request) => handleSessionRequest(id, session, request)
@@ -203,6 +234,7 @@ export function createMCPSessionManager({
if (!session.initialized) {
session.initialized = await isInitializeResult(response, id)
if (!session.initialized) await deleteSession(id)
+ else notifyOpened(session.agent)
}
return response
} catch (error) {
@@ -216,7 +248,7 @@ export function createMCPSessionManager({
function resolveTransport(
sessionId: string | undefined,
- kind: MCPAgentKind = 'mcp'
+ opener: MCPSessionOpener = { kind: 'mcp' }
): Promise<MCPTransport | { error: 'too_many' | 'closed' }> {
if (closed) return Promise.resolve({ error: 'closed' })
cleanupExpired()
@@ -237,7 +269,7 @@ export function createMCPSessionManager({
if (sessions.size + creating.size + closing.size >= MAX_MCP_SESSIONS) {
return Promise.resolve({ error: 'too_many' })
}
- return createSession(sessionId ?? randomUUID(), kind).catch((e) => {
+ return createSession(sessionId ?? randomUUID(), opener).catch((e) => {
// If the manager was closed during session creation, return the structured
// error instead of letting the throw escape as a route-level 500.
if (closed) return { error: 'closed' as const }
diff --git a/packages/mcp/src/tool/registration.ts b/packages/mcp/src/tool/registration.ts
index e6a603d3a..c73ed588a 100644
--- a/packages/mcp/src/tool/registration.ts
+++ b/packages/mcp/src/tool/registration.ts
@@ -73,6 +73,8 @@ export type MCPAgentKind = (typeof MCP_AGENT_KINDS)[number]
export interface MCPAgentSession {
id: string
kind: MCPAgentKind
+ /** The app chat the session belongs to, from its `x-openpencil-chat` header. */
+ chat?: string
}
export interface RegisterToolsOptions {
diff --git a/packages/vue/src/i18n/locales/de/ai.json b/packages/vue/src/i18n/locales/de/ai.json
index 766a9347a..37151068a 100644
--- a/packages/vue/src/i18n/locales/de/ai.json
+++ b/packages/vue/src/i18n/locales/de/ai.json
@@ -221,8 +221,9 @@
"aiSetupAccessServerDescription": "Jeder Server, der die OpenAI-API spricht, etwa Ollama oder LM Studio.",
"aiSetupConnectTitle": "KI verbinden",
"aiSetupNothingDescription": "Geh zurück, um etwas anderes zu wählen, oder richte die KI in den erweiterten Einstellungen ein.",
- "aiSetupAgentDescription": "OpenPencil startet {agent}, sobald du eine Nachricht sendest. Melde dich vorher mit dessen eigenem Kommandozeilen-Tool an.",
+ "aiSetupAgentDescription": "OpenPencil startet {agent}, sobald du eine Nachricht sendest, mit dem Konto, bei dem {agent} angemeldet ist.",
"aiSetupAgentInstall": "Falls es noch nicht installiert ist, führe Folgendes aus:",
+ "aiSetupAgentInstallSupported": "Installiere den unterstützten Adapter:",
"aiSetupMeteredNote": "OpenRouter bietet Modelle mehrerer Anbieter mit einem Konto und einem Schlüssel.",
"aiSetupReviewTitle": "Einrichtung prüfen",
"aiSetupAgentModel": "Vom Agenten gewähltes Modell",
@@ -267,6 +268,29 @@
"aiSetupAgentPromptHint": "Nutzt du schon {agent} oder einen anderen Coding-Agenten? Kopiere den Einrichtungs-Prompt und füge ihn dort ein; er installiert, was OpenPencil braucht.",
"aiSetupAgentCopyPrompt": "Einrichtungs-Prompt kopieren",
"aiSetupAgentCheckAgain": "Erneut prüfen",
+ "aiSetupAgentInstallRuns": "Die Installation führt {command} aus.",
+ "aiSetupDetectNotFound": "Auf diesem Computer nicht gefunden",
+ "aiSetupDetectFound": "Auf diesem Computer gefunden",
+ "aiSetupDetectSignedOut": "Gefunden · nicht angemeldet",
+ "aiSetupDetectSignedIn": "Angemeldet",
+ "aiSetupDetectSignedInAs": "Angemeldet · {account}",
+ "aiSetupAgentAccount": "Konto",
+ "aiSetupAgentAccountChecking": "wird geprüft…",
+ "aiSetupAgentAccountUnknown": "konnte nicht geprüft werden",
+ "aiSetupAgentNotSignedIn": "nicht angemeldet",
+ "aiSetupAgentSigningIn": "Anmeldung läuft…",
+ "aiSetupAgentSignIn": "Anmelden",
+ "aiSetupAgentSignInBrowser": "Schließe die Anmeldung in deinem Browser ab.",
+ "aiSetupAgentSignInOpenPage": "Anmeldeseite öffnen",
+ "aiSetupAgentSignInCode": "Code von der Anmeldeseite, falls sie einen zeigt",
+ "aiSetupAgentSignInSubmitCode": "Code senden",
+ "aiSetupAgentSignInFailed": "Anmeldung bei {agent} fehlgeschlagen. Versuche es erneut.",
+ "aiSetupAgentTools": "OpenPencil-Werkzeuge",
+ "aiSetupAgentToolsConnected": "verbunden",
+ "aiSetupAgentToolsUnreachable": "nicht erreichbar",
+ "aiSetupAgentToolsFailed": "{agent} erreicht die Werkzeuge von OpenPencil nicht, daher starten Chats damit nicht.",
+ "aiSetupAgentToolsHint": "Prüfe unter Einstellungen → MCP, ob der MCP-Server von OpenPencil läuft, und drücke dann Erneut prüfen.",
+ "aiSetupAgentAdapterMismatch": "OpenPencil hat {path} gefunden, einen anderen Adapter, den es nicht unterstützt. Installiere den unterstützten und entferne diesen oder setze ihn in deinem PATH weiter nach hinten.",
"aiSetupPiDescription": "OpenPencil führt Pi über seinen Harness-Begleiter aus und nutzt die Anbieter, bei denen du dich in Pi angemeldet hast.",
"aiSetupPiCompanion": "Harness-Begleiter",
"aiSetupPiInstallCompanion": "Begleiter installieren",
diff --git a/packages/vue/src/i18n/locales/es/ai.json b/packages/vue/src/i18n/locales/es/ai.json
index 45e39f523..de7d326c9 100644
--- a/packages/vue/src/i18n/locales/es/ai.json
+++ b/packages/vue/src/i18n/locales/es/ai.json
@@ -221,8 +221,9 @@
"aiSetupAccessServerDescription": "Cualquier servidor compatible con la API de OpenAI, como Ollama o LM Studio.",
"aiSetupConnectTitle": "Conecta tu IA",
"aiSetupNothingDescription": "Vuelve atrás para elegir otro acceso o configura la IA en los ajustes avanzados.",
- "aiSetupAgentDescription": "OpenPencil inicia {agent} cuando envías un mensaje. Antes, inicia sesión con su propia herramienta de línea de comandos.",
+ "aiSetupAgentDescription": "OpenPencil inicia {agent} cuando envías un mensaje, con la cuenta en la que {agent} tiene la sesión iniciada.",
"aiSetupAgentInstall": "Si aún no está instalado, ejecuta:",
+ "aiSetupAgentInstallSupported": "Instala el adaptador compatible:",
"aiSetupMeteredNote": "OpenRouter te da modelos de varios proveedores con una sola cuenta y una sola clave.",
"aiSetupReviewTitle": "Revisa tu configuración",
"aiSetupAgentModel": "Modelo elegido por el agente",
@@ -267,6 +268,29 @@
"aiSetupAgentPromptHint": "¿Ya usas {agent} u otro agente de programación? Copia el prompt de configuración y pégalo allí; instalará lo que OpenPencil necesita.",
"aiSetupAgentCopyPrompt": "Copiar prompt de configuración",
"aiSetupAgentCheckAgain": "Comprobar de nuevo",
+ "aiSetupAgentInstallRuns": "La instalación ejecuta {command}.",
+ "aiSetupDetectNotFound": "No se encontró en este equipo",
+ "aiSetupDetectFound": "Encontrado en este equipo",
+ "aiSetupDetectSignedOut": "Encontrado · sesión no iniciada",
+ "aiSetupDetectSignedIn": "Sesión iniciada",
+ "aiSetupDetectSignedInAs": "Sesión iniciada · {account}",
+ "aiSetupAgentAccount": "Cuenta",
+ "aiSetupAgentAccountChecking": "comprobando…",
+ "aiSetupAgentAccountUnknown": "no se pudo comprobar",
+ "aiSetupAgentNotSignedIn": "sesión no iniciada",
+ "aiSetupAgentSigningIn": "iniciando sesión…",
+ "aiSetupAgentSignIn": "Iniciar sesión",
+ "aiSetupAgentSignInBrowser": "Termina de iniciar sesión en tu navegador.",
+ "aiSetupAgentSignInOpenPage": "Abrir la página de inicio de sesión",
+ "aiSetupAgentSignInCode": "Código de la página de inicio de sesión, si muestra uno",
+ "aiSetupAgentSignInSubmitCode": "Enviar código",
+ "aiSetupAgentSignInFailed": "No se pudo iniciar sesión en {agent}. Inténtalo de nuevo.",
+ "aiSetupAgentTools": "Herramientas de OpenPencil",
+ "aiSetupAgentToolsConnected": "conectadas",
+ "aiSetupAgentToolsUnreachable": "no accesibles",
+ "aiSetupAgentToolsFailed": "{agent} no puede acceder a las herramientas de OpenPencil, así que los chats con él no se iniciarán.",
+ "aiSetupAgentToolsHint": "Comprueba en Ajustes → MCP que el servidor MCP de OpenPencil esté en marcha y pulsa Comprobar de nuevo.",
+ "aiSetupAgentAdapterMismatch": "OpenPencil encontró {path}, otro adaptador que no admite. Instala el compatible y elimina este o ponlo más atrás en tu PATH.",
"aiSetupPiDescription": "OpenPencil ejecuta Pi mediante su complemento Harness y usa los proveedores en los que iniciaste sesión en Pi.",
"aiSetupPiCompanion": "Complemento Harness",
"aiSetupPiInstallCompanion": "Instalar complemento",
diff --git a/packages/vue/src/i18n/locales/fr/ai.json b/packages/vue/src/i18n/locales/fr/ai.json
index 857e14126..e7531cea0 100644
--- a/packages/vue/src/i18n/locales/fr/ai.json
+++ b/packages/vue/src/i18n/locales/fr/ai.json
@@ -221,8 +221,9 @@
"aiSetupAccessServerDescription": "Tout serveur compatible avec l’API OpenAI, comme Ollama ou LM Studio.",
"aiSetupConnectTitle": "Connectez votre IA",
"aiSetupNothingDescription": "Revenez en arrière pour choisir un autre accès, ou configurez l’IA dans les réglages avancés.",
- "aiSetupAgentDescription": "OpenPencil lance {agent} quand vous envoyez un message. Connectez-vous d’abord avec son propre outil en ligne de commande.",
+ "aiSetupAgentDescription": "OpenPencil lance {agent} quand vous envoyez un message, avec le compte auquel {agent} est connecté.",
"aiSetupAgentInstall": "S’il n’est pas encore installé, exécutez :",
+ "aiSetupAgentInstallSupported": "Installez l’adaptateur pris en charge :",
"aiSetupMeteredNote": "OpenRouter donne accès aux modèles de plusieurs fournisseurs avec un seul compte et une seule clé.",
"aiSetupReviewTitle": "Vérifiez votre configuration",
"aiSetupAgentModel": "Modèle choisi par l’agent",
@@ -267,6 +268,29 @@
"aiSetupAgentPromptHint": "Vous utilisez déjà {agent} ou un autre agent de code ? Copiez le prompt de configuration et collez-le dedans ; il installe ce dont OpenPencil a besoin.",
"aiSetupAgentCopyPrompt": "Copier le prompt de configuration",
"aiSetupAgentCheckAgain": "Vérifier à nouveau",
+ "aiSetupAgentInstallRuns": "L’installation exécute {command}.",
+ "aiSetupDetectNotFound": "Introuvable sur cet ordinateur",
+ "aiSetupDetectFound": "Trouvé sur cet ordinateur",
+ "aiSetupDetectSignedOut": "Trouvé · non connecté",
+ "aiSetupDetectSignedIn": "Connecté",
+ "aiSetupDetectSignedInAs": "Connecté · {account}",
+ "aiSetupAgentAccount": "Compte",
+ "aiSetupAgentAccountChecking": "vérification…",
+ "aiSetupAgentAccountUnknown": "vérification impossible",
+ "aiSetupAgentNotSignedIn": "non connecté",
+ "aiSetupAgentSigningIn": "connexion…",
+ "aiSetupAgentSignIn": "Se connecter",
+ "aiSetupAgentSignInBrowser": "Terminez la connexion dans votre navigateur.",
+ "aiSetupAgentSignInOpenPage": "Ouvrir la page de connexion",
+ "aiSetupAgentSignInCode": "Code de la page de connexion, si elle en affiche un",
+ "aiSetupAgentSignInSubmitCode": "Envoyer le code",
+ "aiSetupAgentSignInFailed": "Impossible de se connecter à {agent}. Réessayez.",
+ "aiSetupAgentTools": "Outils d’OpenPencil",
+ "aiSetupAgentToolsConnected": "connectés",
+ "aiSetupAgentToolsUnreachable": "inaccessibles",
+ "aiSetupAgentToolsFailed": "{agent} n’atteint pas les outils d’OpenPencil : les discussions avec lui ne démarreront pas.",
+ "aiSetupAgentToolsHint": "Vérifiez dans Paramètres → MCP que le serveur MCP d’OpenPencil est lancé, puis appuyez sur Vérifier à nouveau.",
+ "aiSetupAgentAdapterMismatch": "OpenPencil a trouvé {path}, un autre adaptateur qu’il ne prend pas en charge. Installez celui qui est pris en charge, puis supprimez celui-ci ou placez-le plus loin dans votre PATH.",
"aiSetupPiDescription": "OpenPencil exécute Pi via son compagnon Harness et utilise les fournisseurs auxquels vous êtes connecté dans Pi.",
"aiSetupPiCompanion": "Compagnon Harness",
"aiSetupPiInstallCompanion": "Installer le compagnon",
diff --git a/packages/vue/src/i18n/locales/it/ai.json b/packages/vue/src/i18n/locales/it/ai.json
index e2999a05c..dc92cf21b 100644
--- a/packages/vue/src/i18n/locales/it/ai.json
+++ b/packages/vue/src/i18n/locales/it/ai.json
@@ -221,8 +221,9 @@
"aiSetupAccessServerDescription": "Qualsiasi server compatibile con l’API di OpenAI, come Ollama o LM Studio.",
"aiSetupConnectTitle": "Collega la tua IA",
"aiSetupNothingDescription": "Torna indietro per scegliere un altro accesso o configura l’IA nelle impostazioni avanzate.",
- "aiSetupAgentDescription": "OpenPencil avvia {agent} quando invii un messaggio. Prima accedi con il suo strumento da riga di comando.",
+ "aiSetupAgentDescription": "OpenPencil avvia {agent} quando invii un messaggio, con l’account a cui {agent} ha effettuato l’accesso.",
"aiSetupAgentInstall": "Se non è ancora installato, esegui:",
+ "aiSetupAgentInstallSupported": "Installa l’adattatore supportato:",
"aiSetupMeteredNote": "OpenRouter offre modelli di più fornitori con un solo account e una sola chiave.",
"aiSetupReviewTitle": "Controlla la configurazione",
"aiSetupAgentModel": "Modello scelto dall’agente",
@@ -267,6 +268,29 @@
"aiSetupAgentPromptHint": "Usi già {agent} o un altro agente di programmazione? Copia il prompt di configurazione e incollalo lì: installerà ciò che serve a OpenPencil.",
"aiSetupAgentCopyPrompt": "Copia il prompt di configurazione",
"aiSetupAgentCheckAgain": "Controlla di nuovo",
+ "aiSetupAgentInstallRuns": "L’installazione esegue {command}.",
+ "aiSetupDetectNotFound": "Non trovato su questo computer",
+ "aiSetupDetectFound": "Trovato su questo computer",
+ "aiSetupDetectSignedOut": "Trovato · accesso non effettuato",
+ "aiSetupDetectSignedIn": "Accesso effettuato",
+ "aiSetupDetectSignedInAs": "Accesso effettuato · {account}",
+ "aiSetupAgentAccount": "Account",
+ "aiSetupAgentAccountChecking": "verifica…",
+ "aiSetupAgentAccountUnknown": "impossibile verificare",
+ "aiSetupAgentNotSignedIn": "accesso non effettuato",
+ "aiSetupAgentSigningIn": "accesso in corso…",
+ "aiSetupAgentSignIn": "Accedi",
+ "aiSetupAgentSignInBrowser": "Completa l’accesso nel browser.",
+ "aiSetupAgentSignInOpenPage": "Apri la pagina di accesso",
+ "aiSetupAgentSignInCode": "Codice della pagina di accesso, se ne mostra uno",
+ "aiSetupAgentSignInSubmitCode": "Invia codice",
+ "aiSetupAgentSignInFailed": "Impossibile accedere a {agent}. Riprova.",
+ "aiSetupAgentTools": "Strumenti di OpenPencil",
+ "aiSetupAgentToolsConnected": "collegati",
+ "aiSetupAgentToolsUnreachable": "non raggiungibili",
+ "aiSetupAgentToolsFailed": "{agent} non raggiunge gli strumenti di OpenPencil, quindi le chat con lui non partiranno.",
+ "aiSetupAgentToolsHint": "Verifica in Impostazioni → MCP che il server MCP di OpenPencil sia in esecuzione, poi premi Controlla di nuovo.",
+ "aiSetupAgentAdapterMismatch": "OpenPencil ha trovato {path}, un altro adattatore che non supporta. Installa quello supportato e rimuovi questo o spostalo più avanti nel tuo PATH.",
"aiSetupPiDescription": "OpenPencil esegue Pi tramite il suo companion Harness e usa i provider a cui hai effettuato l’accesso in Pi.",
"aiSetupPiCompanion": "Companion Harness",
"aiSetupPiInstallCompanion": "Installa companion",
diff --git a/packages/vue/src/i18n/locales/ja/ai.json b/packages/vue/src/i18n/locales/ja/ai.json
index 2f5b16392..d7afeaf8b 100644
--- a/packages/vue/src/i18n/locales/ja/ai.json
+++ b/packages/vue/src/i18n/locales/ja/ai.json
@@ -221,8 +221,9 @@
"aiSetupAccessServerDescription": "Ollama や LM Studio など、OpenAI API 互換のサーバー。",
"aiSetupConnectTitle": "AI を接続",
"aiSetupNothingDescription": "戻って別のものを選ぶか、詳細設定で AI を設定してください。",
- "aiSetupAgentDescription": "メッセージを送ると OpenPencil が {agent} を起動します。先にエージェント自身のコマンドラインツールでサインインしてください。",
+ "aiSetupAgentDescription": "メッセージを送ると、OpenPencil は {agent} がサインインしているアカウントで {agent} を起動します。",
"aiSetupAgentInstall": "まだインストールしていない場合は、次を実行してください:",
+ "aiSetupAgentInstallSupported": "対応しているアダプターをインストールします:",
"aiSetupMeteredNote": "OpenRouter なら、1 つのアカウントと 1 つのキーで複数ベンダーのモデルを使えます。",
"aiSetupReviewTitle": "設定を確認",
"aiSetupAgentModel": "モデルはエージェントが選択",
@@ -267,6 +268,29 @@
"aiSetupAgentPromptHint": "{agent} などのコーディングエージェントをすでに使っていますか?セットアップ用プロンプトをコピーして貼り付けると、OpenPencil に必要なものをインストールします。",
"aiSetupAgentCopyPrompt": "セットアップ用プロンプトをコピー",
"aiSetupAgentCheckAgain": "もう一度確認",
+ "aiSetupAgentInstallRuns": "インストールでは {command} を実行します。",
+ "aiSetupDetectNotFound": "このコンピューターには見つかりません",
+ "aiSetupDetectFound": "このコンピューターで見つかりました",
+ "aiSetupDetectSignedOut": "見つかりました · 未サインイン",
+ "aiSetupDetectSignedIn": "サインイン済み",
+ "aiSetupDetectSignedInAs": "サインイン済み · {account}",
+ "aiSetupAgentAccount": "アカウント",
+ "aiSetupAgentAccountChecking": "確認中…",
+ "aiSetupAgentAccountUnknown": "確認できません",
+ "aiSetupAgentNotSignedIn": "未サインイン",
+ "aiSetupAgentSigningIn": "サインイン中…",
+ "aiSetupAgentSignIn": "サインイン",
+ "aiSetupAgentSignInBrowser": "ブラウザでサインインを完了してください。",
+ "aiSetupAgentSignInOpenPage": "サインインページを開く",
+ "aiSetupAgentSignInCode": "サインインページに表示されたコード(表示された場合)",
+ "aiSetupAgentSignInSubmitCode": "コードを送信",
+ "aiSetupAgentSignInFailed": "{agent} にサインインできませんでした。もう一度お試しください。",
+ "aiSetupAgentTools": "OpenPencil のツール",
+ "aiSetupAgentToolsConnected": "接続済み",
+ "aiSetupAgentToolsUnreachable": "接続できません",
+ "aiSetupAgentToolsFailed": "{agent} が OpenPencil のツールに接続できないため、このエージェントとのチャットは開始されません。",
+ "aiSetupAgentToolsHint": "設定 → MCP で OpenPencil の MCP サーバーが動作しているか確認し、もう一度確認を押してください。",
+ "aiSetupAgentAdapterMismatch": "OpenPencil が見つけた {path} は、対応していない別のアダプターです。対応版をインストールし、これを削除するか PATH の後ろに移してください。",
"aiSetupPiDescription": "OpenPencil は Harness コンパニオンを通じて Pi を実行し、Pi でサインインしたプロバイダーを使います。",
"aiSetupPiCompanion": "Harness コンパニオン",
"aiSetupPiInstallCompanion": "コンパニオンをインストール",
diff --git a/packages/vue/src/i18n/locales/pl/ai.json b/packages/vue/src/i18n/locales/pl/ai.json
index 8328210f5..624160183 100644
--- a/packages/vue/src/i18n/locales/pl/ai.json
+++ b/packages/vue/src/i18n/locales/pl/ai.json
@@ -221,8 +221,9 @@
"aiSetupAccessServerDescription": "Dowolny serwer zgodny z API OpenAI, np. Ollama lub LM Studio.",
"aiSetupConnectTitle": "Połącz AI",
"aiSetupNothingDescription": "Wróć, aby wybrać inny dostęp, albo skonfiguruj AI w ustawieniach zaawansowanych.",
- "aiSetupAgentDescription": "OpenPencil uruchamia {agent}, gdy wyślesz wiadomość. Najpierw zaloguj się za pomocą jego narzędzia wiersza poleceń.",
+ "aiSetupAgentDescription": "OpenPencil uruchamia {agent}, gdy wyślesz wiadomość, z kontem, na którym {agent} jest zalogowany.",
"aiSetupAgentInstall": "Jeśli nie jest jeszcze zainstalowany, uruchom:",
+ "aiSetupAgentInstallSupported": "Zainstaluj obsługiwany adapter:",
"aiSetupMeteredNote": "OpenRouter daje dostęp do modeli wielu dostawców z jednym kontem i jednym kluczem.",
"aiSetupReviewTitle": "Sprawdź konfigurację",
"aiSetupAgentModel": "Model wybrany przez agenta",
@@ -267,6 +268,29 @@
"aiSetupAgentPromptHint": "Korzystasz już z {agent} lub innego agenta programistycznego? Skopiuj prompt konfiguracji i wklej go tam — zainstaluje to, czego potrzebuje OpenPencil.",
"aiSetupAgentCopyPrompt": "Kopiuj prompt konfiguracji",
"aiSetupAgentCheckAgain": "Sprawdź ponownie",
+ "aiSetupAgentInstallRuns": "Instalacja uruchamia {command}.",
+ "aiSetupDetectNotFound": "Nie znaleziono na tym komputerze",
+ "aiSetupDetectFound": "Znaleziono na tym komputerze",
+ "aiSetupDetectSignedOut": "Znaleziono · niezalogowany",
+ "aiSetupDetectSignedIn": "Zalogowano",
+ "aiSetupDetectSignedInAs": "Zalogowano · {account}",
+ "aiSetupAgentAccount": "Konto",
+ "aiSetupAgentAccountChecking": "sprawdzanie…",
+ "aiSetupAgentAccountUnknown": "nie udało się sprawdzić",
+ "aiSetupAgentNotSignedIn": "niezalogowany",
+ "aiSetupAgentSigningIn": "logowanie…",
+ "aiSetupAgentSignIn": "Zaloguj się",
+ "aiSetupAgentSignInBrowser": "Dokończ logowanie w przeglądarce.",
+ "aiSetupAgentSignInOpenPage": "Otwórz stronę logowania",
+ "aiSetupAgentSignInCode": "Kod ze strony logowania, jeśli go wyświetla",
+ "aiSetupAgentSignInSubmitCode": "Wyślij kod",
+ "aiSetupAgentSignInFailed": "Nie udało się zalogować do {agent}. Spróbuj ponownie.",
+ "aiSetupAgentTools": "Narzędzia OpenPencil",
+ "aiSetupAgentToolsConnected": "połączone",
+ "aiSetupAgentToolsUnreachable": "niedostępne",
+ "aiSetupAgentToolsFailed": "{agent} nie łączy się z narzędziami OpenPencil, więc czaty z nim się nie rozpoczną.",
+ "aiSetupAgentToolsHint": "Sprawdź w Ustawienia → MCP, czy serwer MCP OpenPencil działa, a potem naciśnij Sprawdź ponownie.",
+ "aiSetupAgentAdapterMismatch": "OpenPencil znalazł {path}, inny adapter, którego nie obsługuje. Zainstaluj obsługiwany, a ten usuń lub przesuń dalej w PATH.",
"aiSetupPiDescription": "OpenPencil uruchamia Pi przez towarzyszący program Harness i korzysta z dostawców, do których zalogowano się w Pi.",
"aiSetupPiCompanion": "Program towarzyszący Harness",
"aiSetupPiInstallCompanion": "Zainstaluj program towarzyszący",
diff --git a/packages/vue/src/i18n/locales/ru/ai.json b/packages/vue/src/i18n/locales/ru/ai.json
index 9739738ef..a5a20fe6c 100644
--- a/packages/vue/src/i18n/locales/ru/ai.json
+++ b/packages/vue/src/i18n/locales/ru/ai.json
@@ -221,8 +221,9 @@
"aiSetupAccessServerDescription": "Любой сервер с API, совместимым с OpenAI, например Ollama или LM Studio.",
"aiSetupConnectTitle": "Подключите ИИ",
"aiSetupNothingDescription": "Вернитесь и выберите другой доступ или настройте ИИ в расширенных настройках.",
- "aiSetupAgentDescription": "OpenPencil запускает {agent}, когда вы отправляете сообщение. Сначала войдите в аккаунт через его собственную консольную утилиту.",
+ "aiSetupAgentDescription": "OpenPencil запускает {agent}, когда вы отправляете сообщение, с аккаунтом, в который вошёл {agent}.",
"aiSetupAgentInstall": "Если он ещё не установлен, выполните:",
+ "aiSetupAgentInstallSupported": "Установите поддерживаемый адаптер:",
"aiSetupMeteredNote": "OpenRouter даёт доступ к моделям разных компаний с одним аккаунтом и одним ключом.",
"aiSetupReviewTitle": "Проверьте настройку",
"aiSetupAgentModel": "Модель выбирает агент",
@@ -267,6 +268,29 @@
"aiSetupAgentPromptHint": "Уже пользуетесь {agent} или другим агентом для программирования? Скопируйте промпт настройки и вставьте его туда — он установит всё нужное OpenPencil.",
"aiSetupAgentCopyPrompt": "Скопировать промпт настройки",
"aiSetupAgentCheckAgain": "Проверить снова",
+ "aiSetupAgentInstallRuns": "Установка выполнит {command}.",
+ "aiSetupDetectNotFound": "Не найден на этом компьютере",
+ "aiSetupDetectFound": "Найден на этом компьютере",
+ "aiSetupDetectSignedOut": "Найден · вход не выполнен",
+ "aiSetupDetectSignedIn": "Вход выполнен",
+ "aiSetupDetectSignedInAs": "Вход выполнен · {account}",
+ "aiSetupAgentAccount": "Аккаунт",
+ "aiSetupAgentAccountChecking": "проверка…",
+ "aiSetupAgentAccountUnknown": "не удалось проверить",
+ "aiSetupAgentNotSignedIn": "вход не выполнен",
+ "aiSetupAgentSigningIn": "вход…",
+ "aiSetupAgentSignIn": "Войти",
+ "aiSetupAgentSignInBrowser": "Завершите вход в браузере.",
+ "aiSetupAgentSignInOpenPage": "Открыть страницу входа",
+ "aiSetupAgentSignInCode": "Код со страницы входа, если она его показывает",
+ "aiSetupAgentSignInSubmitCode": "Отправить код",
+ "aiSetupAgentSignInFailed": "Не удалось войти в {agent}. Попробуйте ещё раз.",
+ "aiSetupAgentTools": "Инструменты OpenPencil",
+ "aiSetupAgentToolsConnected": "подключены",
+ "aiSetupAgentToolsUnreachable": "недоступны",
+ "aiSetupAgentToolsFailed": "{agent} не может подключиться к инструментам OpenPencil, поэтому чаты с ним не начнутся.",
+ "aiSetupAgentToolsHint": "Проверьте в разделе Настройки → MCP, что MCP-сервер OpenPencil запущен, затем нажмите «Проверить снова».",
+ "aiSetupAgentAdapterMismatch": "OpenPencil нашёл {path} — другой адаптер, который он не поддерживает. Установите поддерживаемый, а этот удалите или переместите дальше в PATH.",
"aiSetupPiDescription": "OpenPencil запускает Pi через компаньон Harness и использует провайдеров, в которые вы вошли в Pi.",
"aiSetupPiCompanion": "Компаньон Harness",
"aiSetupPiInstallCompanion": "Установить компаньон",
diff --git a/packages/vue/src/i18n/locales/zh-cn/ai.json b/packages/vue/src/i18n/locales/zh-cn/ai.json
index 8d17abfa8..8c8269c75 100644
--- a/packages/vue/src/i18n/locales/zh-cn/ai.json
+++ b/packages/vue/src/i18n/locales/zh-cn/ai.json
@@ -221,8 +221,9 @@
"aiSetupAccessServerDescription": "任何兼容 OpenAI API 的服务器,例如 Ollama 或 LM Studio。",
"aiSetupConnectTitle": "连接你的 AI",
"aiSetupNothingDescription": "返回选择其他服务,或在高级设置中配置 AI。",
- "aiSetupAgentDescription": "发送消息时,OpenPencil 会启动 {agent}。请先使用它自带的命令行工具登录。",
+ "aiSetupAgentDescription": "发送消息时,OpenPencil 会使用 {agent} 已登录的账户启动 {agent}。",
"aiSetupAgentInstall": "如果尚未安装,请运行:",
+ "aiSetupAgentInstallSupported": "安装受支持的适配器:",
"aiSetupMeteredNote": "OpenRouter 让你用一个账户和一个密钥使用多家厂商的模型。",
"aiSetupReviewTitle": "检查你的设置",
"aiSetupAgentModel": "模型由智能体选择",
@@ -267,6 +268,29 @@
"aiSetupAgentPromptHint": "已经在用 {agent} 或其他编程智能体?复制设置提示词并粘贴进去,它会安装 OpenPencil 所需的内容。",
"aiSetupAgentCopyPrompt": "复制设置提示词",
"aiSetupAgentCheckAgain": "重新检查",
+ "aiSetupAgentInstallRuns": "安装将运行 {command}。",
+ "aiSetupDetectNotFound": "在这台电脑上未找到",
+ "aiSetupDetectFound": "已在这台电脑上找到",
+ "aiSetupDetectSignedOut": "已找到 · 未登录",
+ "aiSetupDetectSignedIn": "已登录",
+ "aiSetupDetectSignedInAs": "已登录 · {account}",
+ "aiSetupAgentAccount": "账户",
+ "aiSetupAgentAccountChecking": "检查中…",
+ "aiSetupAgentAccountUnknown": "无法检查",
+ "aiSetupAgentNotSignedIn": "未登录",
+ "aiSetupAgentSigningIn": "正在登录…",
+ "aiSetupAgentSignIn": "登录",
+ "aiSetupAgentSignInBrowser": "请在浏览器中完成登录。",
+ "aiSetupAgentSignInOpenPage": "打开登录页面",
+ "aiSetupAgentSignInCode": "登录页面显示的代码(如有)",
+ "aiSetupAgentSignInSubmitCode": "提交代码",
+ "aiSetupAgentSignInFailed": "无法登录 {agent}。请重试。",
+ "aiSetupAgentTools": "OpenPencil 工具",
+ "aiSetupAgentToolsConnected": "已连接",
+ "aiSetupAgentToolsUnreachable": "无法连接",
+ "aiSetupAgentToolsFailed": "{agent} 无法连接到 OpenPencil 的工具,因此无法开始与它的对话。",
+ "aiSetupAgentToolsHint": "请在设置 → MCP 中确认 OpenPencil 的 MCP 服务器正在运行,然后点击重新检查。",
+ "aiSetupAgentAdapterMismatch": "OpenPencil 找到的 {path} 是它不支持的另一个适配器。请安装受支持的版本,并删除这个或将其在 PATH 中后移。",
"aiSetupPiDescription": "OpenPencil 通过 Harness 配套程序运行 Pi,并使用你在 Pi 中登录的提供商。",
"aiSetupPiCompanion": "Harness 配套程序",
"aiSetupPiInstallCompanion": "安装配套程序",
diff --git a/packages/vue/src/i18n/messages/ai.ts b/packages/vue/src/i18n/messages/ai.ts
index da03334c0..bfdf63846 100644
--- a/packages/vue/src/i18n/messages/ai.ts
+++ b/packages/vue/src/i18n/messages/ai.ts
@@ -253,9 +253,10 @@ export const aiMessageDefaults = {
aiSetupConnectTitle: 'Connect your AI',
aiSetupNothingDescription: 'Go back to choose other access, or set up AI in advanced settings.',
aiSetupAgentDescription: params(
- 'OpenPencil starts {agent} when you send a message. Sign in with its own command-line tool first.'
+ 'OpenPencil starts {agent} when you send a message, with the account {agent} is signed in to.'
),
aiSetupAgentInstall: 'If it is not installed yet, run:',
+ aiSetupAgentInstallSupported: 'Install the supported adapter:',
aiSetupAgentChecking: 'Checking this computer…',
aiSetupAgentInstalled: 'installed',
aiSetupAgentNotFound: 'not found',
@@ -283,6 +284,34 @@ export const aiMessageDefaults = {
aiSetupAgentLookupFailed: 'Couldn’t check this computer. Try again.',
aiSetupAgentCopyPrompt: 'Copy setup prompt',
aiSetupAgentCheckAgain: 'Check again',
+ aiSetupAgentInstallRuns: params('Installing runs {command}.'),
+ aiSetupDetectNotFound: 'Not found on this computer',
+ aiSetupDetectFound: 'Found on this computer',
+ aiSetupDetectSignedOut: 'Found · not signed in',
+ aiSetupDetectSignedIn: 'Signed in',
+ aiSetupDetectSignedInAs: params('Signed in · {account}'),
+ aiSetupAgentAccount: 'Account',
+ aiSetupAgentAccountChecking: 'checking…',
+ aiSetupAgentAccountUnknown: 'couldn’t check',
+ aiSetupAgentNotSignedIn: 'not signed in',
+ aiSetupAgentSigningIn: 'signing in…',
+ aiSetupAgentSignIn: 'Sign in',
+ aiSetupAgentSignInBrowser: 'Finish signing in in your browser.',
+ aiSetupAgentSignInOpenPage: 'Open the sign-in page',
+ aiSetupAgentSignInCode: 'Code from the sign-in page, if it shows one',
+ aiSetupAgentSignInSubmitCode: 'Submit code',
+ aiSetupAgentSignInFailed: params('Couldn’t sign in to {agent}. Try again.'),
+ aiSetupAgentTools: 'OpenPencil tools',
+ aiSetupAgentToolsConnected: 'connected',
+ aiSetupAgentToolsUnreachable: 'not reachable',
+ aiSetupAgentToolsFailed: params(
+ '{agent} can’t reach OpenPencil’s tools, so chats with it won’t start.'
+ ),
+ aiSetupAgentToolsHint:
+ 'Check that OpenPencil’s MCP server is running in Settings → MCP, then press Check again.',
+ aiSetupAgentAdapterMismatch: params(
+ 'OpenPencil found {path}, another adapter it doesn’t support. Install the supported one, then remove this one or move it later on your PATH.'
+ ),
aiSetupPiDescription:
'OpenPencil runs Pi through its Harness companion and uses the providers you signed in to in Pi.',
aiSetupPiCompanion: 'Harness companion',
diff --git a/src/app/ai/acp/auth/session.ts b/src/app/ai/acp/auth/session.ts
new file mode 100644
index 000000000..7b86263b2
--- /dev/null
+++ b/src/app/ai/acp/auth/session.ts
@@ -0,0 +1,241 @@
+import { ClientSideConnection, ndJsonStream, PROTOCOL_VERSION } from '@agentclientprotocol/sdk'
+import type { InitializeResponse, SessionUpdate } from '@agentclientprotocol/sdk'
+import { promiseTimeout } from '@vueuse/core'
+
+import type { ACPAgentDef } from '@open-pencil/core/constants'
+
+import { spawnACPProcess } from '@/app/ai/acp/process'
+import { createDeferred, type Deferred } from '@/app/runtime/deferred'
+
+import type { OwnToolsLink, OwnToolsOutcome } from '../own-tools'
+import {
+ isSignedIn,
+ parseAuthMethods,
+ parseAuthStatusUpdate,
+ type AgentAuthMethod,
+ type AgentAuthStatus
+} from './status'
+
+/** An agent process's stdio and the way to stop it. */
+export interface AgentStreams {
+ input: WritableStream<Uint8Array>
+ output: ReadableStream<Uint8Array>
+ close(): Promise<void>
+}
+
+export type SpawnAgent = (agent: ACPAgentDef) => Promise<AgentStreams>
+
+export interface AuthSessionOptions {
+ spawn?: SpawnAgent
+ /** How long to wait for a login report; adapters read their CLI's with a 5 s limit. */
+ statusTimeoutMs?: number
+ /** How long an agent may take to answer `initialize` before it counts as stuck. */
+ initializeTimeoutMs?: number
+ /** Also checks, for a signed-in agent, that a session reaches OpenPencil's tools. */
+ tools?: ToolsProbe
+}
+
+/** How a check starts a session the way a chat does, without sending a prompt. */
+export interface ToolsProbe {
+ /** The folder a chat's session starts in. */
+ cwd: () => Promise<string>
+ link: () => Promise<OwnToolsLink>
+}
+
+const STATUS_TIMEOUT_MS = 8_000
+const INITIALIZE_TIMEOUT_MS = 30_000
+
+/** What an agent says about its login when it starts, without a session or a prompt. */
+export interface AgentAuthCheck {
+ /** Null when the agent reported nothing in time, so its login is unknown. */
+ status: AgentAuthStatus | null
+ methods: AgentAuthMethod[]
+ /** The ACP program that answered, to tell a supported adapter from another with its name. */
+ adapter: { name: string; version: string } | null
+ /** Whether a session reached OpenPencil's tools; null when not checked or not signed in. */
+ tools: OwnToolsOutcome | null
+}
+
+export async function spawnAgentStreams(agent: ACPAgentDef): Promise<AgentStreams> {
+ let closing = false
+ const { child, input, output } = await spawnACPProcess({
+ command: agent.command,
+ args: agent.args,
+ logId: `${agent.id} sign-in`,
+ destroying: () => closing,
+ onUnexpectedClose: () => undefined
+ })
+ return {
+ input,
+ output,
+ async close() {
+ closing = true
+ await child.kill().catch(() => undefined)
+ }
+ }
+}
+
+/** Login reports in arrival order, so a caller can wait for one newer than it has seen. */
+function createStatusLog() {
+ const reports: AgentAuthStatus[] = []
+ let waiting: { after: number; deferred: Deferred<AgentAuthStatus | null> } | null = null
+ return {
+ get count() {
+ return reports.length
+ },
+ push(status: AgentAuthStatus) {
+ reports.push(status)
+ if (waiting && reports.length > waiting.after) waiting.deferred.resolve(status)
+ },
+ /** The first report after `after` reports, or the latest one if none comes in time. */
+ async next(after: number, timeoutMs: number): Promise<AgentAuthStatus | null> {
+ if (reports.length > after) return reports.at(-1) ?? null
+ const deferred = createDeferred<AgentAuthStatus | null>()
+ waiting = { after, deferred }
+ const timer = setTimeout(() => deferred.resolve(reports.at(-1) ?? null), timeoutMs)
+ try {
+ return await deferred.promise
+ } finally {
+ clearTimeout(timer)
+ waiting = null
+ }
+ }
+ }
+}
+
+async function openAuthSession(
+ agent: ACPAgentDef,
+ { spawn = spawnAgentStreams, initializeTimeoutMs = INITIALIZE_TIMEOUT_MS }: AuthSessionOptions
+) {
+ const streams = await spawn(agent)
+ const log = createStatusLog()
+ let onUpdate: ((update: SessionUpdate) => void) | null = null
+ const connection = new ClientSideConnection(
+ () => ({
+ // Nothing runs in this connection, so nothing may ask for permission.
+ requestPermission: async () => ({ outcome: { outcome: 'cancelled' } }),
+ sessionUpdate: async ({ update }) => onUpdate?.(update),
+ extNotification: async (method, params) => {
+ const status = parseAuthStatusUpdate(method, params)
+ if (status) log.push(status)
+ }
+ }),
+ ndJsonStream(streams.input, streams.output)
+ )
+ // The SDK leaves requests pending when the agent exits, so each one races the connection.
+ const stopped = connection.closed.then(() => {
+ throw new Error('The agent stopped.')
+ })
+ stopped.catch(() => undefined)
+ function untilStopped<T>(request: Promise<T>): Promise<T> {
+ return Promise.race([request, stopped])
+ }
+ let init: InitializeResponse
+ try {
+ init = await untilStopped(
+ Promise.race([
+ connection.initialize({
+ protocolVersion: PROTOCOL_VERSION,
+ // Without it, Claude's adapter offers no sign-in methods.
+ clientCapabilities: { _meta: { 'terminal-auth': true } }
+ }),
+ promiseTimeout(initializeTimeoutMs).then((): never => {
+ throw new Error('The agent did not start.')
+ })
+ ])
+ )
+ } catch (error) {
+ await streams.close()
+ throw error
+ }
+ return {
+ connection,
+ init,
+ log,
+ untilStopped,
+ set onUpdate(listener: ((update: SessionUpdate) => void) | null) {
+ onUpdate = listener
+ },
+ close: () => streams.close()
+ }
+}
+
+function adapterOf(init: InitializeResponse): AgentAuthCheck['adapter'] {
+ return init.agentInfo ? { name: init.agentInfo.name, version: init.agentInfo.version } : null
+}
+
+type AuthSession = Awaited<ReturnType<typeof openAuthSession>>
+
+/** Starts a session as a chat would, sends nothing, and reports whether it reached the tools. */
+async function checkTools(session: AuthSession, probe: ToolsProbe): Promise<OwnToolsOutcome> {
+ let link: OwnToolsLink | null = null
+ try {
+ // Linking reads the MCP server's token, which fails while the server is down.
+ link = await probe.link()
+ const linked = link
+ session.onUpdate = (update) => linked.noteUpdate(update)
+ await session.untilStopped(
+ session.connection.newSession({
+ cwd: await probe.cwd(),
+ mcpServers: link.mcpServers,
+ _meta: link.meta
+ })
+ )
+ return await session.untilStopped(link.outcome())
+ } catch (error) {
+ link?.stop()
+ return { connected: false, reason: error instanceof Error ? error.message : String(error) }
+ } finally {
+ session.onUpdate = null
+ }
+}
+
+/** Starts the agent, reads the login it reports, and stops it. */
+export async function checkAgentAuth(
+ agent: ACPAgentDef,
+ options: AuthSessionOptions = {}
+): Promise<AgentAuthCheck> {
+ const { statusTimeoutMs = STATUS_TIMEOUT_MS } = options
+ const session = await openAuthSession(agent, options)
+ try {
+ const status = await session.log.next(0, statusTimeoutMs)
+ return {
+ status,
+ methods: parseAuthMethods(session.init.authMethods),
+ adapter: adapterOf(session.init),
+ tools:
+ options.tools && status && isSignedIn(status)
+ ? await checkTools(session, options.tools)
+ : null
+ }
+ } finally {
+ await session.close()
+ }
+}
+
+/**
+ * Signs in through an auth method the agent runs itself, such as Codex's ChatGPT login, which
+ * opens the browser and waits for it. Aborting stops the agent and rejects.
+ */
+export async function signInWithAgent(
+ agent: ACPAgentDef,
+ methodId: string,
+ signal: AbortSignal,
+ options: AuthSessionOptions = {}
+): Promise<AgentAuthStatus | null> {
+ const { statusTimeoutMs = STATUS_TIMEOUT_MS } = options
+ const session = await openAuthSession(agent, options)
+ const stop = () => void session.close()
+ signal.addEventListener('abort', stop, { once: true })
+ try {
+ // The login reported at startup must not pass for the one after signing in.
+ await session.untilStopped(session.log.next(0, statusTimeoutMs))
+ signal.throwIfAborted()
+ const seen = session.log.count
+ await session.untilStopped(session.connection.authenticate({ methodId }))
+ return await session.log.next(seen, statusTimeoutMs)
+ } finally {
+ signal.removeEventListener('abort', stop)
+ await session.close()
+ }
+}
diff --git a/src/app/ai/acp/auth/status.ts b/src/app/ai/acp/auth/status.ts
new file mode 100644
index 000000000..14f839db1
--- /dev/null
+++ b/src/app/ai/acp/auth/status.ts
@@ -0,0 +1,55 @@
+import * as v from 'valibot'
+
+/**
+ * The `_auth/status_update` notification Claude's and Codex's ACP adapters push after
+ * `initialize`, after `authenticate`, and when the login changes. Silence means the agent cannot
+ * tell; `kind: 'none'` means it knows it is signed out.
+ */
+export const AUTH_STATUS_UPDATE_METHOD = '_auth/status_update'
+
+const authStatusSchema = v.object({
+ kind: v.picklist(['account', 'api_key', 'gateway', 'external', 'none']),
+ /** Ready to show on its own: "Claude Max", "ChatGPT Pro", "Not logged in". */
+ label: v.string(),
+ detail: v.optional(v.string()),
+ account: v.optional(
+ v.object({
+ email: v.optional(v.string()),
+ organization: v.optional(v.string()),
+ plan: v.optional(v.string())
+ })
+ )
+})
+
+export type AgentAuthStatus = v.InferOutput<typeof authStatusSchema>
+
+const notificationSchema = v.object({ authStatus: authStatusSchema })
+
+/** The status an `_auth/status_update` carries, or null for anything else. */
+export function parseAuthStatusUpdate(method: string, params: unknown): AgentAuthStatus | null {
+ if (method !== AUTH_STATUS_UPDATE_METHOD) return null
+ const result = v.safeParse(notificationSchema, params)
+ return result.success ? result.output.authStatus : null
+}
+
+export function isSignedIn(status: AgentAuthStatus): boolean {
+ return status.kind !== 'none'
+}
+
+const authMethodSchema = v.object({
+ id: v.string(),
+ name: v.string(),
+ /** `terminal` when the client runs the agent's command to sign in. */
+ type: v.optional(v.string())
+})
+
+export type AgentAuthMethod = v.InferOutput<typeof authMethodSchema>
+
+/** The auth methods an `initialize` response advertises, skipping any it cannot describe. */
+export function parseAuthMethods(methods: unknown): AgentAuthMethod[] {
+ if (!Array.isArray(methods)) return []
+ return methods.flatMap((method) => {
+ const result = v.safeParse(authMethodSchema, method)
+ return result.success ? [result.output] : []
+ })
+}
diff --git a/src/app/ai/acp/auth/terminal.ts b/src/app/ai/acp/auth/terminal.ts
new file mode 100644
index 000000000..bea7b312a
--- /dev/null
+++ b/src/app/ai/acp/auth/terminal.ts
@@ -0,0 +1,85 @@
+import type { ACPAgentDef } from '@open-pencil/core/constants'
+
+import { createDeferred } from '@/app/runtime/deferred'
+import { resolveScopedCommand } from '@/app/tauri/command'
+
+/** Long enough to sign in from a fresh browser, short enough not to leave a login waiting. */
+const SIGN_IN_TIMEOUT_MS = 5 * 60_000
+
+/**
+ * Terminal hyperlinks (OSC 8) and colour or cursor codes, which the login prints for a
+ * terminal and which the app shows as plain text.
+ */
+// eslint-disable-next-line no-control-regex -- Escape sequences are what it removes.
+const TERMINAL_CODES = /\u001B\]8;[^\u0007\u001B]*(?:\u0007|\u001B\\)|\u001B\[[0-9;?]*[A-Za-z]/g
+
+export function stripTerminalCodes(text: string): string {
+ return text.replace(TERMINAL_CODES, '')
+}
+
+/** The first web address in a line of the login's output. */
+export function findSignInURL(line: string): string | null {
+ return /https:\/\/\S+/.exec(stripTerminalCodes(line))?.[0] ?? null
+}
+
+/** The scope entry that pins an agent's sign-in arguments in the desktop shell scope. */
+export function signInScope(agent: ACPAgentDef): string {
+ return `${agent.command}-sign-in`
+}
+
+export interface TerminalSignIn {
+ /** Settles when the login exits: resolved when it signed in, rejected otherwise. */
+ done: Promise<void>
+ /** Sends the code the sign-in page shows, for when the browser cannot return to the login. */
+ submitCode: (code: string) => Promise<void>
+ cancel: () => Promise<void>
+}
+
+/**
+ * Runs an agent's terminal auth method without a terminal: the login opens the browser itself,
+ * prints a page to open by hand, and reads a pasted code from stdin if the browser cannot
+ * hand the sign-in back.
+ */
+export async function startTerminalSignIn(
+ agent: ACPAgentDef,
+ args: string[],
+ onURL: (url: string) => void
+): Promise<TerminalSignIn> {
+ const { Command } = await import('@tauri-apps/plugin-shell')
+ const resolved = resolveScopedCommand(signInScope(agent), agent.command, args)
+ const command = Command.create(resolved.command, resolved.args)
+ const finished = createDeferred<undefined>()
+ let closed = false
+ let urlSeen = false
+ command.stdout.on('data', (line: string) => {
+ const url = urlSeen ? null : findSignInURL(line)
+ if (!url) return
+ urlSeen = true
+ onURL(url)
+ })
+ command.on('close', ({ code }) => {
+ closed = true
+ if (code === 0) finished.resolve(undefined)
+ else finished.reject(new Error('Sign-in did not finish.'))
+ })
+ command.on('error', () => finished.reject(new Error('Sign-in could not start.')))
+ const child = await command.spawn()
+ const timer = setTimeout(() => {
+ finished.reject(new Error('Sign-in timed out.'))
+ void stop()
+ }, SIGN_IN_TIMEOUT_MS)
+ async function stop() {
+ if (!closed) await child.kill().catch(() => undefined)
+ }
+ const done = finished.promise.finally(() => clearTimeout(timer))
+ // A caller that only cancels must not see an unhandled rejection.
+ done.catch(() => undefined)
+ return {
+ done,
+ submitCode: (code) => child.write(`${code.trim()}\n`),
+ async cancel() {
+ finished.reject(new Error('Sign-in was cancelled.'))
+ await stop()
+ }
+ }
+}
diff --git a/src/app/ai/acp/map-update.ts b/src/app/ai/acp/map-update.ts
index 9ab7cefdc..572c7f1e8 100644
--- a/src/app/ai/acp/map-update.ts
+++ b/src/app/ai/acp/map-update.ts
@@ -1,91 +1,313 @@
import type { SessionUpdate } from '@agentclientprotocol/sdk'
import type { UIMessageChunk } from 'ai'
+import * as v from 'valibot'
+import { OPEN_PENCIL_MCP_SERVER } from '@open-pencil/core/constants'
import type { JSONObject } from '@open-pencil/scene-graph/primitives'
-export interface MapResult {
- chunks: UIMessageChunk[]
- textStarted: boolean
+type ToolCallReport = Extract<SessionUpdate, { sessionUpdate: 'tool_call' | 'tool_call_update' }>
+
+/**
+ * How a tool call shows in the chat. OpenPencil's own MCP tools take their plain names, input,
+ * and result, as the built-in chat's do; another server's tools keep the MCP `mcp__server__tool`
+ * form and result.
+ */
+type ToolKind = 'own' | 'mcp' | 'agent'
+
+interface ToolIdentity {
+ name: string
+ kind: ToolKind
+ /** The call's arguments, when the agent wraps them as Codex does. */
+ input?: unknown
}
-export function mapUpdate(update: SessionUpdate, textId: string, textStarted: boolean): MapResult {
- const chunks: UIMessageChunk[] = []
+const OWN_PREFIX = `mcp__${OPEN_PENCIL_MCP_SERVER}__`
- 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
+const codexMCPInputSchema = v.object({
+ server: v.string(),
+ tool: v.string(),
+ arguments: v.optional(v.unknown())
+})
+/** Codex's `{ result, error }`; both keys are always there, and an array is never one. */
+const codexMCPOutputSchema = v.pipe(
+ v.custom<Record<string, unknown>>(
+ (value) =>
+ typeof value === 'object' &&
+ value !== null &&
+ !Array.isArray(value) &&
+ 'result' in value &&
+ 'error' in value
+ ),
+ v.object({ result: v.unknown(), error: v.unknown() })
+)
+const claudeMetaSchema = v.object({ claudeCode: v.object({ toolName: v.string() }) })
+const mcpResultSchema = v.object({
+ content: v.array(v.unknown()),
+ isError: v.optional(v.boolean())
+})
+const textBlockSchema = v.object({ type: v.literal('text'), text: v.string() })
+const imageBlockSchema = v.object({
+ type: v.literal('image'),
+ data: v.string(),
+ mimeType: v.string()
+})
+const jsonObjectSchema = v.pipe(v.string(), v.parseJson(), v.record(v.string(), v.unknown()))
+const errorMessageSchema = v.object({ message: v.string() })
+
+/** Codex reports an MCP call with its server, tool, and arguments as the input. */
+function codexIdentity(update: ToolCallReport): ToolIdentity | null {
+ const input = v.safeParse(codexMCPInputSchema, update.rawInput)
+ if (!input.success || update.title !== `mcp.${input.output.server}.${input.output.tool}`) {
+ return null
+ }
+ const { server, tool } = input.output
+ return server === OPEN_PENCIL_MCP_SERVER
+ ? { name: tool, kind: 'own', input: input.output.arguments ?? {} }
+ : { name: `mcp__${server}__${tool}`, kind: 'mcp', input: input.output.arguments ?? {} }
+}
+
+/** Claude's adapter names the SDK tool, `mcp__server__tool` for an MCP one, in its metadata. */
+function claudeIdentity(update: ToolCallReport): ToolIdentity | null {
+ const meta = v.safeParse(claudeMetaSchema, update._meta)
+ if (!meta.success) return null
+ const { toolName } = meta.output.claudeCode
+ if (toolName.startsWith(OWN_PREFIX)) {
+ return { name: toolName.slice(OWN_PREFIX.length), kind: 'own' }
+ }
+ return toolName.startsWith('mcp__') ? { name: toolName, kind: 'mcp' } : null
+}
+
+function identify(update: ToolCallReport): ToolIdentity {
+ return (
+ codexIdentity(update) ??
+ claudeIdentity(update) ?? { name: update.title || 'unknown', kind: 'agent' }
+ )
+}
+
+/** A tool's text and image blocks, as MCP returns them and Claude's adapter passes them on. */
+function contentBlocks(value: unknown): unknown[] | null {
+ if (Array.isArray(value)) return value
+ const result = v.safeParse(mcpResultSchema, value)
+ return result.success ? result.output.content : null
+}
+
+function blockText(blocks: unknown[]): string | undefined {
+ const texts = blocks.flatMap((block) => {
+ const text = v.safeParse(textBlockSchema, block)
+ return text.success ? [text.output.text] : []
+ })
+ return texts.length > 0 ? texts.join('\n') : undefined
+}
+
+/**
+ * An OpenPencil tool's result as the built-in chat holds it: the JSON object the tool returned,
+ * with an exported image as `base64` and `mimeType`.
+ */
+function ownToolOutput(blocks: unknown[]): unknown {
+ const text = blockText(blocks)
+ const output: Record<string, unknown> = {}
+ if (text !== undefined) {
+ const parsed = v.safeParse(jsonObjectSchema, text)
+ Object.assign(output, parsed.success ? parsed.output : { text })
+ }
+ for (const block of blocks) {
+ const image = v.safeParse(imageBlockSchema, block)
+ if (image.success) {
+ output.base64 = image.output.data
+ output.mimeType = image.output.mimeType
}
- 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 })
+ }
+ return output
+}
+
+/** An OpenPencil tool reports a failure as `{ "error": … }` text. */
+function ownToolError(blocks: unknown[]): string | undefined {
+ const text = blockText(blocks)
+ if (text === undefined) return undefined
+ const parsed = v.safeParse(jsonObjectSchema, text)
+ return parsed.success && typeof parsed.output.error === 'string' ? parsed.output.error : text
+}
+
+function errorText(value: unknown): string | undefined {
+ if (typeof value === 'string') return value
+ const error = v.safeParse(errorMessageSchema, value)
+ return error.success ? error.output.message : undefined
+}
+
+type ToolResult = { ok: true; output: unknown } | { ok: false; errorText: string }
+
+const FAILED = 'Tool call failed'
+
+/** An MCP call's result, unwrapped from Codex's `{ result, error }`, or the error it reports. */
+function mcpOutcome(update: ToolCallReport): ToolResult {
+ const codex = v.safeParse(codexMCPOutputSchema, update.rawOutput)
+ if (!codex.success) return { ok: true, output: update.rawOutput }
+ const { error, result } = codex.output
+ if (error === null || error === undefined) return { ok: true, output: result }
+ return {
+ ok: false,
+ errorText: errorText(error) ?? textFromContent(update.content ?? undefined) ?? FAILED
+ }
+}
+
+function mcpFailed(update: ToolCallReport, output: unknown): boolean {
+ const result = v.safeParse(mcpResultSchema, output)
+ return update.status === 'failed' || (result.success && result.output.isError === true)
+}
+
+function toolResult(update: ToolCallReport, identity: ToolIdentity): ToolResult {
+ const fallback = textFromContent(update.content ?? undefined)
+ if (identity.kind === 'agent') {
+ return update.status === 'failed'
+ ? { ok: false, errorText: fallback ?? FAILED }
+ : { ok: true, output: update.rawOutput ?? fallback }
+ }
+ const outcome = mcpOutcome(update)
+ if (!outcome.ok) return outcome
+ const blocks = contentBlocks(outcome.output)
+ if (mcpFailed(update, outcome.output)) {
+ const reason = blocks && (identity.kind === 'own' ? ownToolError(blocks) : blockText(blocks))
+ return { ok: false, errorText: reason ?? fallback ?? FAILED }
+ }
+ if (identity.kind === 'mcp' || !blocks) return { ok: true, output: outcome.output ?? fallback }
+ return { ok: true, output: ownToolOutput(blocks) }
+}
+
+/**
+ * Turns one agent turn's ACP updates into the chat's message chunks. Consecutive text or
+ * thought chunks form one part, which closes when anything else arrives, so text after a tool
+ * call starts a new part and a run of thoughts shows as one.
+ */
+export function createUpdateMapper(idPrefix: string) {
+ let parts = 0
+ let text: string | null = null
+ let reasoning: string | null = null
+ const tools = new Map<string, ToolIdentity>()
+
+ function nextId(kind: string): string {
+ parts += 1
+ return `${idPrefix}-${kind}-${parts}`
+ }
+
+ function closeText(chunks: UIMessageChunk[]): void {
+ if (text) chunks.push({ type: 'text-end', id: text })
+ text = null
+ }
+
+ function closeReasoning(chunks: UIMessageChunk[]): void {
+ if (reasoning) chunks.push({ type: 'reasoning-end', id: reasoning })
+ reasoning = null
+ }
+
+ function toolInput(update: ToolCallReport, identity: ToolIdentity): unknown {
+ return identity.input ?? update.rawInput
+ }
+
+ function toolResultChunks(update: ToolCallReport, identity: ToolIdentity): UIMessageChunk[] {
+ if (update.status !== 'completed' && update.status !== 'failed') return []
+ const result = toolResult(update, identity)
+ return [
+ result.ok
+ ? {
+ type: 'tool-output-available',
+ toolCallId: update.toolCallId,
+ output: result.output,
+ providerExecuted: true
+ }
+ : {
+ type: 'tool-output-error',
+ toolCallId: update.toolCallId,
+ errorText: result.errorText,
+ providerExecuted: true
+ }
+ ]
+ }
+
+ function map(update: SessionUpdate): UIMessageChunk[] {
+ const chunks: UIMessageChunk[] = []
+ switch (update.sessionUpdate) {
+ case 'agent_message_chunk': {
+ if (update.content.type !== 'text') {
+ console.warn('[ACP] Unhandled content type:', update.content.type)
+ break
+ }
+ if (!update.content.text) break
+ closeReasoning(chunks)
+ if (!text) {
+ text = nextId('text')
+ chunks.push({ type: 'text-start', id: text })
+ }
+ chunks.push({ type: 'text-delta', id: text, delta: update.content.text })
+ break
}
- break
- }
- case 'tool_call': {
- if (!update.title) {
- console.warn('[ACP] Tool call without title:', update.toolCallId)
+ case 'agent_thought_chunk': {
+ if (update.content.type !== 'text' || !update.content.text) break
+ closeText(chunks)
+ if (!reasoning) {
+ reasoning = nextId('reasoning')
+ chunks.push({ type: 'reasoning-start', id: reasoning })
+ }
+ chunks.push({ type: 'reasoning-delta', id: reasoning, delta: update.content.text })
+ break
}
- const toolName = update.title || 'unknown'
- chunks.push({
- type: 'tool-input-start',
- toolCallId: update.toolCallId,
- toolName,
- providerExecuted: true,
- title: update.title
- })
- if (update.rawInput) {
+ case 'tool_call': {
+ closeText(chunks)
+ closeReasoning(chunks)
+ if (!update.title) console.warn('[ACP] Tool call without title:', update.toolCallId)
+ const identity = identify(update)
+ tools.set(update.toolCallId, identity)
+ const title = identity.kind === 'agent' ? update.title : undefined
chunks.push({
- type: 'tool-input-available',
+ type: 'tool-input-start',
toolCallId: update.toolCallId,
- toolName,
- input: update.rawInput,
+ toolName: identity.name,
providerExecuted: true,
- title: update.title
+ title
})
+ const input = toolInput(update, identity)
+ // A call can arrive already finished, as Codex reports an MCP server that failed to start.
+ const finished = update.status === 'completed' || update.status === 'failed'
+ if (input || finished) {
+ chunks.push({
+ type: 'tool-input-available',
+ toolCallId: update.toolCallId,
+ toolName: identity.name,
+ input: input ?? {},
+ providerExecuted: true,
+ title
+ })
+ }
+ chunks.push(...toolResultChunks(update, identity))
+ break
}
- 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
- })
+ case 'tool_call_update': {
+ const identity = tools.get(update.toolCallId) ?? identify(update)
+ // Claude's adapter sends a call's complete input once it has streamed in.
+ if (update.rawInput && identity.input === undefined) {
+ chunks.push({
+ type: 'tool-input-available',
+ toolCallId: update.toolCallId,
+ toolName: identity.name,
+ input: update.rawInput,
+ providerExecuted: true
+ })
+ }
+ chunks.push(...toolResultChunks(update, identity))
+ break
}
- break
}
+ return chunks
+ }
+
+ /** Closes the text or thought still open when the turn ends. */
+ function end(): UIMessageChunk[] {
+ const chunks: UIMessageChunk[] = []
+ closeText(chunks)
+ closeReasoning(chunks)
+ return chunks
}
- return { chunks, textStarted }
+ return { map, end }
}
export function textFromContent(content: JSONObject[] | undefined): string | undefined {
diff --git a/src/app/ai/acp/own-tools.ts b/src/app/ai/acp/own-tools.ts
new file mode 100644
index 000000000..d5b829748
--- /dev/null
+++ b/src/app/ai/acp/own-tools.ts
@@ -0,0 +1,80 @@
+import type { McpServer, SessionUpdate } from '@agentclientprotocol/sdk'
+import { promiseTimeout } from '@vueuse/core'
+
+import { OPEN_PENCIL_MCP_SERVER } from '@open-pencil/core/constants'
+import { randomHex } from '@open-pencil/scene-graph/random'
+
+import { textFromContent } from './map-update'
+
+/**
+ * Lets the agent use OpenPencil's own tools without asking each time: their edits are undoable
+ * and stay in the document the chat works on. Claude's adapter passes these options to the
+ * Claude Agent SDK, where a bare server name allows every tool on it; other agents ignore it.
+ */
+export const OWN_TOOLS_ALLOWED = {
+ claudeCode: { options: { allowedTools: [`mcp__${OPEN_PENCIL_MCP_SERVER}`] } }
+}
+
+/** How long an agent may take to reach OpenPencil's tools once its session starts. */
+export const TOOLS_CONNECT_TIMEOUT_MS = 20_000
+
+/** Whether an agent's session reached OpenPencil's tools; null when the server cannot tell. */
+export type OwnToolsOutcome =
+ | { connected: true }
+ | { connected: false; reason: string | null }
+ | { connected: null }
+
+/** What an agent's new session needs to reach OpenPencil's tools, and how to tell it did. */
+export interface OwnToolsLink {
+ mcpServers: McpServer[]
+ meta: typeof OWN_TOOLS_ALLOWED
+ /** Reads an update sent before any prompt, where a failed tool call is a server that failed. */
+ noteUpdate(update: SessionUpdate): void
+ /** Waits, once the session exists, for the server to say the agent opened its MCP session. */
+ outcome(timeoutMs?: number): Promise<OwnToolsOutcome>
+ stop(): void
+}
+
+/**
+ * Names a new agent session to OpenPencil's MCP server by a chat id, so the server can report
+ * when this agent connects. Watch before creating the session: the agent connects during it.
+ */
+export async function linkOwnTools(authorizationToken: string | null): Promise<OwnToolsLink> {
+ const [{ buildACPMCPServers }, { mcpRuntime }, { watchChatAgent }] = await Promise.all([
+ import('@/app/integrations/mcp'),
+ import('@/app/automation/mcp/runtime'),
+ import('@/app/automation/agents')
+ ])
+ const chat = randomHex(16)
+ // Built before watching, so a server list that fails to build leaves no chat waiting.
+ const mcpServers = await buildACPMCPServers({ authorizationToken, chat })
+ // An older MCP server reports no sessions, so only a current one can confirm the agent.
+ const watch = mcpRuntime.agentSessionEvents ? watchChatAgent(chat) : null
+ const failures: string[] = []
+ return {
+ mcpServers,
+ meta: OWN_TOOLS_ALLOWED,
+ noteUpdate(update) {
+ if (update.sessionUpdate !== 'tool_call' || update.status !== 'failed') return
+ const text = textFromContent(update.content ?? undefined)
+ if (text?.includes(OPEN_PENCIL_MCP_SERVER)) failures.push(text)
+ },
+ async outcome(timeoutMs = TOOLS_CONNECT_TIMEOUT_MS) {
+ if (!watch) return { connected: null }
+ try {
+ const connected = await Promise.race([
+ watch.connected.then(() => true),
+ promiseTimeout(timeoutMs).then(() => false)
+ ])
+ return connected
+ ? { connected: true }
+ : { connected: false, reason: failures.at(-1) ?? null }
+ } finally {
+ watch.stop()
+ }
+ },
+ stop() {
+ watch?.stop()
+ }
+ }
+}
diff --git a/src/app/ai/acp/transport.ts b/src/app/ai/acp/transport.ts
index 6520f2c2b..657936758 100644
--- a/src/app/ai/acp/transport.ts
+++ b/src/app/ai/acp/transport.ts
@@ -12,9 +12,10 @@ import type { ACPAgentDef } from '@open-pencil/core/constants'
import SYSTEM_PROMPT from '@/app/ai/chat/system-prompt'
import { describeDiagnosticError, recordACPTransportFailure } from '@/app/diagnostics'
-import { buildACPMCPServers } from '@/app/integrations/mcp'
-import { mapUpdate } from './map-update'
+import { parseAuthStatusUpdate } from './auth/status'
+import { createUpdateMapper } from './map-update'
+import { linkOwnTools } from './own-tools'
import { spawnACPProcess } from './process'
type TauriChild = Awaited<ReturnType<typeof spawnACPProcess>>['child']
@@ -55,9 +56,25 @@ export function formatConnectionError(e: unknown, agentDef?: ACPAgentDef): strin
if (isMissingCommandError(msg)) {
return missingCommandMessage(agentDef)
}
+ if (isAuthRequiredError(e)) {
+ return `${agentDef?.name ?? 'The agent'} is not signed in. Sign in from Set up AI, then try again.`
+ }
return msg
}
+/** ACP's `auth_required` error, which an agent returns for a new session before sign-in. */
+function isAuthRequiredError(e: unknown): boolean {
+ return typeof e === 'object' && e !== null && 'code' in e && e.code === -32000
+}
+
+/** The agent never opened its session with OpenPencil's MCP server, so it has no design tools. */
+function toolsUnreachableError(agentDef: ACPAgentDef, reason: string | null): Error {
+ return new Error(
+ `${agentDef.name} couldn't reach OpenPencil's tools, so your message wasn't sent.` +
+ (reason ? ` ${agentDef.name} reported: ${reason}` : '')
+ )
+}
+
function startupError(error: unknown, agentDef: ACPAgentDef): Error {
recordACPTransportFailure({ operation: 'start', ...describeDiagnosticError(error) })
return new Error(formatConnectionError(error, agentDef))
@@ -83,6 +100,8 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {
private cwd: string
private sentContext = false
private destroying = false
+ /** The agent while it starts, before it becomes the session, so destroying can stop it. */
+ private starting: TauriChild | null = null
constructor(options: { agentDef: ACPAgentDef; cwd?: string }) {
this.agentDef = options.agentDef
@@ -107,11 +126,19 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {
}
if (!this.session) {
- this.session = await this.spawnAgent()
+ const started = await this.spawnAgent()
+ // Destroyed between startup and here: the agent is still `starting`, so stop it.
+ if (this.destroying) {
+ await started.child.kill().catch(() => undefined)
+ throw new Error('The chat closed while its agent was starting.')
+ }
+ this.session = started
+ this.starting = null
this.sentContext = false
}
- const promptText = this.sentContext ? text : `${SYSTEM_PROMPT}\n\n${text}`
+ const carriesContext = !this.sentContext
+ const promptText = carriesContext ? `${SYSTEM_PROMPT}\n\n${text}` : text
this.sentContext = true
const { connection, sessionId } = this.session
@@ -119,15 +146,14 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {
return new ReadableStream<UIMessageChunk>({
start: (controller) => {
- const textId = `text-${Date.now()}`
- let textStarted = false
+ const mapper = createUpdateMapper(`turn-${Date.now()}`)
let closed = false
function finish(reason: 'stop' | 'other' | 'error', errorText?: string) {
if (closed) return
closed = true
if (errorText) controller.enqueue({ type: 'error', errorText })
- if (textStarted) controller.enqueue({ type: 'text-end', id: textId })
+ for (const chunk of mapper.end()) controller.enqueue(chunk)
controller.enqueue({ type: 'finish-step' })
controller.enqueue({ type: 'finish', finishReason: reason })
session.onUpdate = null
@@ -136,11 +162,7 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {
session.onUpdate = (params) => {
if (closed) return
- const result = mapUpdate(params.update, textId, textStarted)
- for (const chunk of result.chunks) {
- controller.enqueue(chunk)
- }
- textStarted = result.textStarted
+ for (const chunk of mapper.map(params.update)) controller.enqueue(chunk)
}
abortSignal?.addEventListener('abort', () => {
@@ -151,11 +173,21 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {
controller.enqueue({ type: 'start' })
controller.enqueue({ type: 'start-step' })
+ // Stopped while the agent started and reached its tools: the abort event already fired.
+ if (abortSignal?.aborted) {
+ // The instructions went out with nothing, so the next message carries them.
+ if (carriesContext) this.sentContext = false
+ finish('stop')
+ return
+ }
+
connection
.prompt({
sessionId,
prompt: [{ type: 'text', text: promptText }]
})
+ // The prompt answers once the agent's turn is over; nothing else ends the reply.
+ .then((result) => finish(result.stopReason === 'end_turn' ? 'stop' : 'other'))
.catch((e) => {
recordACPTransportFailure({
operation: 'message',
@@ -173,6 +205,9 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {
async destroy(): Promise<void> {
this.destroying = true
+ const starting = this.starting
+ this.starting = null
+ await starting?.kill().catch(() => undefined)
if (this.session) {
await this.session.child.kill()
this.session = null
@@ -211,10 +246,24 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {
async sessionUpdate(params: SessionNotification): Promise<void> {
onUpdate?.(params)
+ },
+
+ extNotification: async (method, params) => {
+ const status = parseAuthStatusUpdate(method, params)
+ if (!status) return
+ const { agentAccounts } = await import('@/app/ai/agents/accounts')
+ agentAccounts.report(this.agentDef.id, status)
}
}
const connection = new ClientSideConnection((_agent: Agent) => clientImpl, stream)
+ this.starting = child
+ // The SDK leaves requests pending when the agent exits, so each startup request races it.
+ const stopped = connection.closed.then((): never => {
+ throw new Error('The agent stopped while it was starting.')
+ })
+ stopped.catch(() => undefined)
+ const untilStopped = <T>(request: Promise<T>): Promise<T> => Promise.race([request, stopped])
const { getAutomationAuthToken } = await import('@/app/automation/mcp/spawn')
let automationAuthToken: string | null
try {
@@ -225,26 +274,63 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {
}
try {
- await connection.initialize({
- protocolVersion: PROTOCOL_VERSION,
- clientCapabilities: {}
- })
+ await untilStopped(
+ connection.initialize({
+ protocolVersion: PROTOCOL_VERSION,
+ clientCapabilities: {}
+ })
+ )
} catch (e) {
await child.kill().catch(() => undefined)
throw startupError(e, this.agentDef)
}
+ // The agent must reach OpenPencil's tools before it gets a prompt.
+ let tools: Awaited<ReturnType<typeof linkOwnTools>>
+ try {
+ tools = await linkOwnTools(automationAuthToken)
+ } catch (e) {
+ // An outside MCP connection whose credential cannot be read fails here.
+ await child.kill().catch(() => undefined)
+ throw startupError(e, this.agentDef)
+ }
+ onUpdate = ({ update }) => tools.noteUpdate(update)
+
let sessionResult
try {
- sessionResult = await connection.newSession({
- cwd: this.cwd,
- mcpServers: await buildACPMCPServers({ authorizationToken: automationAuthToken })
- })
+ sessionResult = await untilStopped(
+ connection.newSession({
+ cwd: this.cwd,
+ mcpServers: tools.mcpServers,
+ _meta: tools.meta
+ })
+ )
} catch (e) {
+ tools.stop()
await child.kill().catch(() => undefined)
throw startupError(e, this.agentDef)
}
+ let outcome: Awaited<ReturnType<typeof tools.outcome>>
+ try {
+ outcome = await untilStopped(tools.outcome())
+ } catch (e) {
+ tools.stop()
+ throw startupError(e, this.agentDef)
+ }
+ // Destroyed while starting, as when the chat closes: the agent must not get a prompt.
+ if (this.destroying) {
+ await child.kill().catch(() => undefined)
+ throw new Error('The chat closed while its agent was starting.')
+ }
+ if (outcome.connected === false) {
+ await child.kill().catch(() => undefined)
+ const error = toolsUnreachableError(this.agentDef, outcome.reason)
+ recordACPTransportFailure({ operation: 'start', ...describeDiagnosticError(error) })
+ throw error
+ }
+ onUpdate = null
+
const session: ACPSession = {
connection,
sessionId: sessionResult.sessionId,
diff --git a/src/app/ai/agents/accounts.ts b/src/app/ai/agents/accounts.ts
new file mode 100644
index 000000000..3d2e4307b
--- /dev/null
+++ b/src/app/ai/agents/accounts.ts
@@ -0,0 +1,193 @@
+import { ref } from 'vue'
+
+import { IS_TAURI, type ACPAgentDef, type ACPAgentID } from '@open-pencil/core/constants'
+
+import {
+ checkAgentAuth,
+ signInWithAgent,
+ type AgentAuthCheck,
+ type ToolsProbe
+} from '@/app/ai/acp/auth/session'
+import type { AgentAuthMethod, AgentAuthStatus } from '@/app/ai/acp/auth/status'
+import { startTerminalSignIn, type TerminalSignIn } from '@/app/ai/acp/auth/terminal'
+
+/** What setup knows about the account a coding agent uses. */
+export interface AgentAccount {
+ checking: boolean
+ /** Undefined until checked; null when the agent does not report its login. */
+ status: AgentAuthStatus | null | undefined
+ /** The ACP program that answered, null when it did not say. */
+ adapter: AgentAuthCheck['adapter']
+ /** The agent offers the auth method setup signs in with. */
+ canSignIn: boolean
+ signingIn: boolean
+ /** A sign-in page to open by hand, when the login printed one. */
+ signInURL: string | null
+ /** The sign-in reads a code pasted from its page. */
+ acceptsCode: boolean
+ /** Whether a session reached OpenPencil's tools; null until a signed-in check says. */
+ tools: AgentAuthCheck['tools']
+ error: 'check' | 'sign-in' | null
+}
+
+const NOT_CHECKED: AgentAccount = {
+ checking: false,
+ status: undefined,
+ adapter: null,
+ canSignIn: false,
+ signingIn: false,
+ signInURL: null,
+ acceptsCode: false,
+ tools: null,
+ error: null
+}
+
+type Accounts = Partial<Record<ACPAgentID, AgentAccount>>
+
+export function createAgentAccounts(options: {
+ enabled: boolean
+ check: (agent: ACPAgentDef) => Promise<AgentAuthCheck>
+ signInWithAgent: (
+ agent: ACPAgentDef,
+ methodId: string,
+ signal: AbortSignal
+ ) => Promise<AgentAuthStatus | null>
+ startTerminalSignIn: (
+ agent: ACPAgentDef,
+ args: string[],
+ onURL: (url: string) => void
+ ) => Promise<TerminalSignIn>
+}) {
+ const accounts = ref<Accounts>({})
+ const methods = new Map<ACPAgentID, AgentAuthMethod[]>()
+ const checks = new Map<ACPAgentID, Promise<void>>()
+ const signIns = new Map<
+ ACPAgentID,
+ { cancel(): Promise<void>; submitCode?: TerminalSignIn['submitCode'] }
+ >()
+
+ function account(id: ACPAgentID): AgentAccount {
+ return accounts.value[id] ?? NOT_CHECKED
+ }
+
+ function update(id: ACPAgentID, patch: Partial<AgentAccount>) {
+ accounts.value = { ...accounts.value, [id]: { ...account(id), ...patch } }
+ }
+
+ function signInMethod(agent: ACPAgentDef): AgentAuthMethod | undefined {
+ const wanted = agent.signIn
+ if (!wanted) return undefined
+ const method = methods.get(agent.id)?.find((candidate) => candidate.id === wanted.method)
+ if (wanted.via === 'terminal' && method?.type !== 'terminal') return undefined
+ return method
+ }
+
+ /** Starts the agent and records the login it reports; joins a check already running. */
+ function check(agent: ACPAgentDef): Promise<void> {
+ if (!options.enabled) return Promise.resolve()
+ const running = checks.get(agent.id)
+ if (running) return running
+ update(agent.id, { checking: true, error: null })
+ const pending = options
+ .check(agent)
+ .then((result) => {
+ methods.set(agent.id, result.methods)
+ update(agent.id, {
+ status: result.status,
+ adapter: result.adapter,
+ tools: result.tools,
+ canSignIn: signInMethod(agent) !== undefined
+ })
+ return undefined
+ })
+ .catch(() => update(agent.id, { error: 'check' }))
+ .finally(() => {
+ update(agent.id, { checking: false })
+ checks.delete(agent.id)
+ })
+ checks.set(agent.id, pending)
+ return pending
+ }
+
+ async function signIn(agent: ACPAgentDef): Promise<void> {
+ if (!options.enabled || account(agent.id).signingIn) return
+ if (!methods.has(agent.id)) await check(agent)
+ const method = signInMethod(agent)
+ if (!method) {
+ update(agent.id, { error: 'sign-in' })
+ return
+ }
+ update(agent.id, { signingIn: true, signInURL: null, acceptsCode: false, error: null })
+ // A field, so the cancel callbacks' writes are visible to the checks below.
+ const run = { cancelled: false, signedIn: false }
+ try {
+ if (agent.signIn?.via === 'terminal') {
+ const login = await options.startTerminalSignIn(agent, agent.signIn.args, (url) =>
+ update(agent.id, { signInURL: url })
+ )
+ signIns.set(agent.id, {
+ cancel: () => {
+ run.cancelled = true
+ return login.cancel()
+ },
+ submitCode: login.submitCode
+ })
+ update(agent.id, { acceptsCode: true })
+ await login.done
+ run.signedIn = true
+ } else {
+ const controller = new AbortController()
+ signIns.set(agent.id, {
+ cancel: async () => {
+ run.cancelled = true
+ controller.abort()
+ }
+ })
+ const status = await options.signInWithAgent(agent, method.id, controller.signal)
+ if (status) update(agent.id, { status })
+ run.signedIn = true
+ }
+ } catch {
+ if (!run.cancelled) update(agent.id, { error: 'sign-in' })
+ } finally {
+ signIns.delete(agent.id)
+ update(agent.id, { signingIn: false, signInURL: null, acceptsCode: false })
+ }
+ // The agent reports the new login when it starts again.
+ if (run.signedIn) await check(agent)
+ }
+
+ async function cancelSignIn(id: ACPAgentID): Promise<void> {
+ await signIns.get(id)?.cancel()
+ }
+
+ async function submitCode(id: ACPAgentID, code: string): Promise<void> {
+ await signIns.get(id)?.submitCode?.(code)
+ }
+
+ /** A login the agent reported elsewhere, such as during a chat. */
+ function report(id: ACPAgentID, status: AgentAuthStatus) {
+ update(id, { status })
+ }
+
+ return { supported: options.enabled, account, check, signIn, cancelSignIn, submitCode, report }
+}
+
+/** Starts a session as a chat does: in the agent workspace, linked to OpenPencil's tools. */
+const chatTools: ToolsProbe = {
+ cwd: async () => (await import('@/app/ai/agents/native')).agentWorkspace(),
+ link: async () => {
+ const [{ getAutomationAuthToken }, { linkOwnTools }] = await Promise.all([
+ import('@/app/automation/mcp/spawn'),
+ import('@/app/ai/acp/own-tools')
+ ])
+ return linkOwnTools(await getAutomationAuthToken())
+ }
+}
+
+export const agentAccounts = createAgentAccounts({
+ enabled: IS_TAURI,
+ check: (agent) => checkAgentAuth(agent, { tools: chatTools }),
+ signInWithAgent: (agent, methodId, signal) => signInWithAgent(agent, methodId, signal),
+ startTerminalSignIn
+})
diff --git a/src/app/ai/agents/detection.ts b/src/app/ai/agents/detection.ts
new file mode 100644
index 000000000..1459ee14d
--- /dev/null
+++ b/src/app/ai/agents/detection.ts
@@ -0,0 +1,40 @@
+import type { ACPAgentDef } from '@open-pencil/core/constants'
+
+import { agentSetupView, type AgentSetupState, type PiSetupState } from './setup'
+
+/** What setup found of an agent on this computer, shown before the person picks it. */
+export type AgentDetection =
+ | { state: 'checking' }
+ | { state: 'not-found' }
+ /** Installed, or its CLI is, with no account to report. */
+ | { state: 'found' }
+ | { state: 'signed-out' }
+ /** `account` joins the plan and email when the agent names them. */
+ | { state: 'signed-in'; account: string | null }
+
+function joined(parts: (string | null)[]): string | null {
+ const present = parts.filter((part): part is string => part !== null)
+ return present.length ? present.join(' · ') : null
+}
+
+export function codingAgentDetection(agent: ACPAgentDef, setup: AgentSetupState): AgentDetection {
+ if (!setup.checked) return { state: 'checking' }
+ const detected = setup.detected
+ if (detected?.status === 'available') {
+ const account = agentSetupView(agent, setup).account
+ if (account?.state === 'checking') return { state: 'checking' }
+ if (account?.state === 'signed-out') return { state: 'signed-out' }
+ if (account?.state === 'signed-in') {
+ return { state: 'signed-in', account: joined([account.label, account.detail]) }
+ }
+ return { state: 'found' }
+ }
+ return detected?.cliPath ? { state: 'found' } : { state: 'not-found' }
+}
+
+export function piDetection(setup: PiSetupState): AgentDetection {
+ if (!setup.checked) return { state: 'checking' }
+ // Pi signs in to providers, not one account, so there is no account to name.
+ if (setup.signedIn) return { state: 'signed-in', account: null }
+ return setup.companion ? { state: 'found' } : { state: 'not-found' }
+}
diff --git a/src/app/ai/agents/discovery.ts b/src/app/ai/agents/discovery.ts
index cd57b4104..7b39f2385 100644
--- a/src/app/ai/agents/discovery.ts
+++ b/src/app/ai/agents/discovery.ts
@@ -40,7 +40,8 @@ export function detectedAgents(lookup: AgentLookup): DetectedAgent[] {
return ACP_AGENTS.map((definition) => {
const cliPath = lookup.executables[definition.cliCommand ?? definition.command] ?? null
const adapterPath = lookup.executables[definition.command] ?? null
- const unavailableStatus = cliPath ? 'needs-adapter' : 'not-installed'
+ // An adapter package carries its agent, so it installs whether or not the CLI is there.
+ const unavailableStatus = definition.adapterPackage ? 'needs-adapter' : 'not-installed'
return {
definition,
cliPath,
diff --git a/src/app/ai/agents/native.ts b/src/app/ai/agents/native.ts
index c78d8fb37..8a7d7c702 100644
--- a/src/app/ai/agents/native.ts
+++ b/src/app/ai/agents/native.ts
@@ -24,6 +24,12 @@ export async function lookupAgents(): Promise<AgentLookup> {
return v.parse(lookupSchema, await invoke<unknown>('agent_lookup'))
}
+/** The folder coding agents start in, which the desktop shell creates in the app's data. */
+export async function agentWorkspace(): Promise<string> {
+ const { invoke } = await import('@tauri-apps/api/core')
+ return v.parse(v.string(), await invoke<unknown>('agent_workspace'))
+}
+
const INSTALL_TIMEOUT_MS = 120_000
export async function installAgentAdapter(agent: ACPAgentDef, searchPath: string): Promise<void> {
diff --git a/src/app/ai/agents/setup.ts b/src/app/ai/agents/setup.ts
index a583091fd..789620ca9 100644
--- a/src/app/ai/agents/setup.ts
+++ b/src/app/ai/agents/setup.ts
@@ -1,14 +1,17 @@
import { computed, ref, toValue, watch, type MaybeRefOrGetter } from 'vue'
-import type { ACPAgentDef } from '@open-pencil/core/constants'
+import { ACP_AGENTS, type ACPAgentDef, type ACPAgentID } from '@open-pencil/core/constants'
+import { isSignedIn } from '@/app/ai/acp/auth/status'
import { readPiAccount } from '@/app/ai/harness/pi-settings'
import { MCP_INSTALL_COMMAND } from '@/app/automation/mcp/failure'
import { detectUserAgent } from '@/app/tauri/command'
+import { agentAccounts, type AgentAccount } from './accounts'
import { agentDiscovery, type DetectedAgent, type DiscoveryError } from './discovery'
type AgentDiscovery = typeof agentDiscovery
+type AgentAccounts = typeof agentAccounts
/** What setup knows about one coding agent and the MCP server it needs. */
export interface AgentSetupState {
@@ -37,6 +40,8 @@ export interface AgentSetupState {
installingAgent: boolean
installingBridge: boolean
error: DiscoveryError | null
+ /** The account the agent uses, read from the agent once its adapter is installed. */
+ account?: AgentAccount
}
/** What setup knows about Pi: the Harness companion that runs it and Pi's own settings. */
@@ -62,6 +67,8 @@ export interface PiSetupState {
installingBridge: boolean
/** The default model set in Pi, used unless OpenPencil names another. */
defaultModel: string | null
+ /** Pi keeps sign-ins; null until read or where they cannot be read. */
+ signedIn?: boolean | null
error: DiscoveryError | null
}
@@ -142,6 +149,76 @@ export interface AgentSetupView {
/** Commands for where one-click installation cannot help. */
manualAgentCommand: string | null
manualBridgeCommand: string | null
+ /** The agent's account; null where the agent cannot run yet or does not report one. */
+ account: AgentAccountView | null
+ /**
+ * The program on PATH under the adapter's name is another adapter, such as an older one
+ * published under another package, so it neither reports nor signs in to the account.
+ */
+ adapterMismatch: boolean
+}
+
+/** The agent's account as setup shows it. */
+export interface AgentAccountView {
+ state: 'checking' | 'signed-in' | 'signed-out' | 'signing-in' | 'unknown'
+ /** The plan or login type the agent names, such as "Claude Max". */
+ label: string | null
+ /** The account's email, or the agent's own detail line. */
+ detail: string | null
+ /** One click can sign in, through the agent's own login. */
+ canSignIn: boolean
+ /** A sign-in page to open by hand while signing in. */
+ signInURL: string | null
+ acceptsCode: boolean
+ error: AgentAccount['error']
+ /**
+ * Whether a signed-in agent's session reached OpenPencil's tools, with the agent's reason when
+ * it did not; null when signed out or when the MCP server cannot report it.
+ */
+ tools: { state: 'checking' | 'connected' | 'unreachable'; reason: string | null } | null
+}
+
+function toolsView(account: AgentAccount, signedIn: boolean): AgentAccountView['tools'] {
+ if (!signedIn) return null
+ if (account.checking) return { state: 'checking', reason: null }
+ const tools = account.tools
+ if (tools?.connected === true) return { state: 'connected', reason: null }
+ if (tools?.connected === false) return { state: 'unreachable', reason: tools.reason }
+ return null
+}
+
+function accountState(account: AgentAccount): AgentAccountView['state'] | null {
+ if (account.signingIn) return 'signing-in'
+ if (account.status === undefined) {
+ if (account.checking) return 'checking'
+ return account.error ? 'unknown' : null
+ }
+ if (account.status === null) return account.error ? 'unknown' : null
+ return isSignedIn(account.status) ? 'signed-in' : 'signed-out'
+}
+
+function accountView(setup: AgentSetupState, mismatch: boolean): AgentAccountView | null {
+ const account = setup.account
+ if (!account || mismatch || setup.detected?.status !== 'available') return null
+ const state = accountState(account)
+ if (!state) return null
+ const status = account.status
+ const signedIn = state === 'signed-in'
+ return {
+ state,
+ label: signedIn ? (status?.label ?? null) : null,
+ detail: signedIn ? (status?.account?.email ?? status?.detail ?? null) : null,
+ canSignIn: state === 'signed-out' && account.canSignIn,
+ signInURL: account.signInURL,
+ acceptsCode: account.acceptsCode,
+ error: account.error,
+ tools: toolsView(account, signedIn)
+ }
+}
+
+function adapterMismatch(agent: ACPAgentDef, setup: AgentSetupState): boolean {
+ const adapter = setup.account?.adapter
+ return Boolean(agent.adapterPackage && adapter && adapter.name !== agent.adapterPackage)
}
/** The agent's install command to run by hand, or null where one click installs its adapter. */
@@ -180,13 +257,18 @@ export function agentSetupView(agent: ACPAgentDef, setup: AgentSetupState): Agen
!setup.npm &&
(status === 'needs-adapter' || (bridgeMissing && !bridgeInstallable && !bridgeAdmin))
const needsAdmin = (status === 'needs-adapter' && adapterAdmin) || (bridgeMissing && bridgeAdmin)
+ const mismatch = status === 'available' && adapterMismatch(agent, setup)
return {
bridge,
canInstallAdapter: status === 'needs-adapter' && setup.npm && !adapterAdmin,
busy: setup.installingAgent || setup.installingBridge,
problem: setupProblem(setup.error, needsNpm, ['install', 'canvas-install'], needsAdmin),
- manualAgentCommand: manualAgentCommand(agent, setup),
- manualBridgeCommand: manualBridgeCommand(setup, bridge)
+ manualAgentCommand: mismatch
+ ? (agent.installCommand ?? null)
+ : manualAgentCommand(agent, setup),
+ manualBridgeCommand: manualBridgeCommand(setup, bridge),
+ account: accountView(setup, mismatch),
+ adapterMismatch: mismatch
}
}
@@ -300,13 +382,15 @@ export function piSetupView(setup: PiSetupState): PiSetupView {
/** Setup state of the coding agents and Pi, for guided setup and model settings. */
export function useAgentSetup(
discovery: AgentDiscovery = agentDiscovery,
- readPi: typeof readPiAccount = readPiAccount
+ readPi: typeof readPiAccount = readPiAccount,
+ accounts: AgentAccounts = agentAccounts
) {
const piDefaultModel = ref<string | null>(null)
+ const piSignedIn = ref<boolean | null>(null)
const readingPi = ref(false)
- function agentID(providerID: string) {
- return providerID.startsWith('acp:') ? providerID.slice('acp:'.length) : null
+ function agentID(providerID: string): ACPAgentID | null {
+ return ACP_AGENTS.find((agent) => `acp:${agent.id}` === providerID)?.id ?? null
}
function agentSetup(providerID: string): AgentSetupState {
@@ -316,10 +400,29 @@ export function useAgentSetup(
scanning: discovery.scanning.value,
detected: discovery.agents.value.find((agent) => agent.definition.id === id) ?? null,
adapterNeedsAdmin: discovery.adapterNeedsAdmin.value,
- installingAgent: discovery.installing.value === id
+ installingAgent: discovery.installing.value === id,
+ account: id ? accounts.account(id) : undefined
}
}
+ function installedAgent(providerID: string): ACPAgentDef | undefined {
+ const detected = agentSetup(providerID).detected
+ return detected?.status === 'available' ? detected.definition : undefined
+ }
+
+ /**
+ * Reads the account of each installed agent setup can sign in to, all at once. Others, such
+ * as Gemini CLI, do not report a login, so starting them would show nothing.
+ */
+ function checkAccounts(): Promise<void> {
+ const installed = discovery.agents.value.filter(
+ (agent) => agent.status === 'available' && agent.definition.signIn
+ )
+ return Promise.all(installed.map((agent) => accounts.check(agent.definition))).then(
+ () => undefined
+ )
+ }
+
function piSetup(providerID: string): PiSetupState | undefined {
if (providerID !== 'harness:pi') return undefined
return {
@@ -331,7 +434,8 @@ export function useAgentSetup(
companionNeedsAdmin: discovery.harnessNeedsAdmin.value,
companionInstallable: discovery.harnessInstallable.value,
installingCompanion: discovery.installing.value === 'harness',
- defaultModel: piDefaultModel.value
+ defaultModel: piDefaultModel.value,
+ signedIn: piSignedIn.value
}
}
@@ -350,10 +454,13 @@ export function useAgentSetup(
}
}
- function installAgent(providerID: string): Promise<void> {
+ async function installAgent(providerID: string): Promise<void> {
if (providerID === 'harness:pi') return discovery.setupHarness()
const detected = agentSetup(providerID).detected
- return detected ? discovery.install(detected.definition.id) : Promise.resolve()
+ if (!detected) return
+ await discovery.install(detected.definition.id)
+ const installed = installedAgent(providerID)
+ if (installed) await accounts.check(installed)
}
async function refreshAgents(): Promise<void> {
@@ -362,9 +469,21 @@ export function useAgentSetup(
try {
const [, account] = await Promise.all([discovery.refresh(true), readPi().catch(() => null)])
piDefaultModel.value = account?.defaultModel ?? null
+ piSignedIn.value = account?.signedIn ?? null
} finally {
readingPi.value = false
}
+ await checkAccounts()
+ }
+
+ function signInAgent(providerID: string): Promise<void> {
+ const agent = installedAgent(providerID)
+ return agent ? accounts.signIn(agent) : Promise.resolve()
+ }
+
+ function agentAction(providerID: string, run: (id: ACPAgentID) => Promise<void>) {
+ const id = agentID(providerID)
+ return id ? run(id) : Promise.resolve()
}
return {
@@ -373,6 +492,10 @@ export function useAgentSetup(
mcpServerSetup,
installAgent,
refreshAgents,
+ signInAgent,
+ cancelAgentSignIn: (providerID: string) => agentAction(providerID, accounts.cancelSignIn),
+ submitAgentSignInCode: (providerID: string, code: string) =>
+ agentAction(providerID, (id) => accounts.submitCode(id, code)),
setupCanvasBridge: () => discovery.setupCanvasBridge()
}
}
diff --git a/src/app/ai/chat/transports.ts b/src/app/ai/chat/transports.ts
index 76e60dff6..019b8c135 100644
--- a/src/app/ai/chat/transports.ts
+++ b/src/app/ai/chat/transports.ts
@@ -112,8 +112,9 @@ export async function createACPTransport(providerID: AIProviderID) {
if (!agentDef) throw new Error(`Unknown ACP agent: ${agentId}`)
const { ACPChatTransport } = await import('@/app/ai/acp/transport')
- const { homeDir } = await import('@tauri-apps/api/path')
- return new ACPChatTransport({ agentDef, cwd: await homeDir() })
+ const { agentWorkspace } = await import('@/app/ai/agents/native')
+ // A folder of its own, not the home folder, whose project settings the agent would read.
+ return new ACPChatTransport({ agentDef, cwd: await agentWorkspace() })
}
export function createToolLoopTransport({
diff --git a/src/app/ai/models/settings/onboarding/plan.ts b/src/app/ai/models/settings/onboarding/plan.ts
index dc6f25dc9..d865dec11 100644
--- a/src/app/ai/models/settings/onboarding/plan.ts
+++ b/src/app/ai/models/settings/onboarding/plan.ts
@@ -279,7 +279,10 @@ export function planOnboarding(answers: OnboardingAnswers, options: PlanOptions)
review: planReview(design, vision, current),
fast: planFast(design, vision, current)
}
- return { ...roles, connections: planConnections(roles) }
+ // A selected agent is always shown, as only its card tells whether it is installed and signed
+ // in, and the person can make it the design model in review.
+ const agents = access.filter(isOnboardingAgent)
+ return { ...roles, connections: uniq([...planConnections(roles), ...agents]) }
}
/** Providers the planned models need connected, skipping models that are already configured. */
diff --git a/src/app/ai/models/settings/onboarding/use.ts b/src/app/ai/models/settings/onboarding/use.ts
index 931ed1317..6157bc3c1 100644
--- a/src/app/ai/models/settings/onboarding/use.ts
+++ b/src/app/ai/models/settings/onboarding/use.ts
@@ -1,8 +1,9 @@
import { uniq } from 'es-toolkit'
import { computed, reactive, ref, watch } from 'vue'
-import { IS_TAURI } from '@open-pencil/core/constants'
+import { ACP_AGENTS, IS_TAURI } from '@open-pencil/core/constants'
+import { codingAgentDetection, piDetection, type AgentDetection } from '@/app/ai/agents/detection'
import { useAgentSetup } from '@/app/ai/agents/setup'
import { refreshAIProviderStatus } from '@/app/ai/chat/storage'
import {
@@ -18,6 +19,7 @@ import { existingOnboardingConnection, useOnboardingConnections } from './connec
import { currentOnboardingModels } from './current'
import {
isOnboardingAccess,
+ ONBOARDING_AGENTS,
ONBOARDING_GOALS,
planOnboarding,
type OnboardingAccess,
@@ -82,9 +84,22 @@ export function useAIOnboarding({ agentsAvailable = IS_TAURI }: AIOnboardingOpti
const { connection, ready, markKeySaved } = connections
const signIn = useOnboardingSignIn(connections)
const agents = useAgentSetup()
- // Look for installed agents when they are about to be connected, and again on return.
+ // Look for installed agents when they are offered and when they are about to be connected.
watch(step, (current) => {
- if (current === 'connect') void agents.refreshAgents()
+ if (current === 'access' || current === 'connect') void agents.refreshAgents()
+ })
+
+ /** What setup found of each agent on this computer, for the access step. */
+ const detections = computed(() => {
+ const found: Partial<Record<OnboardingAccess, AgentDetection>> = {}
+ if (!agentsAvailable) return found
+ for (const providerID of ONBOARDING_AGENTS) {
+ const pi = agents.piSetup(providerID)
+ const agent = ACP_AGENTS.find((candidate) => `acp:${candidate.id}` === providerID)
+ if (pi) found[providerID] = piDetection(pi)
+ else if (agent) found[providerID] = codingAgentDetection(agent, agents.agentSetup(providerID))
+ }
+ return found
})
const canContinue = computed(() => {
@@ -172,6 +187,7 @@ export function useAIOnboarding({ agentsAvailable = IS_TAURI }: AIOnboardingOpti
saveResult,
canContinue,
plannedModel,
+ detections,
...connections,
...signIn,
...agents,
diff --git a/src/app/automation/agents.ts b/src/app/automation/agents.ts
index c4c1b8360..4c66e8507 100644
--- a/src/app/automation/agents.ts
+++ b/src/app/automation/agents.ts
@@ -4,6 +4,7 @@ import { isUnknownRecord } from '@/app/automation/bridge/target'
import type { EditorStore } from '@/app/editor/active-store'
import { addAgent, agentPlacement, type AgentHandle } from '@/app/presence/registry'
import { MAX_NAME_LENGTH } from '@/app/presence/schema'
+import { createDeferred } from '@/app/runtime/deferred'
/** After this long without a tool call, a session's agent rests and leaves the canvas. */
export const MCP_AGENT_IDLE_MS = 20_000
@@ -161,6 +162,28 @@ export function restAgents(kind: Exclude<AgentSession['kind'], 'mcp'>): void {
}
}
+/** App chats waiting for their agent to open its MCP session, by chat id. */
+const waitingChats = new Map<string, () => void>()
+
+/**
+ * Waits for the agent of the app chat `chat` to open its MCP session, which the server reports
+ * when the agent's initialize succeeds. Start watching before the agent starts its session.
+ */
+export function watchChatAgent(chat: string): { connected: Promise<void>; stop: () => void } {
+ const deferred = createDeferred<undefined>()
+ waitingChats.set(chat, () => deferred.resolve(undefined))
+ return { connected: deferred.promise, stop: () => waitingChats.delete(chat) }
+}
+
+/** The MCP server says an agent opened a session; the ACP chat waiting for it may go on. */
+export function agentSessionOpened(args: unknown): void {
+ if (!isUnknownRecord(args) || args.kind !== 'acp') return
+ const { chat } = args
+ if (typeof chat !== 'string') return
+ waitingChats.get(chat)?.()
+ waitingChats.delete(chat)
+}
+
/** The MCP server says a session ended: its agents leave every document. */
export function endAgentSession(sessionId: string): void {
// Removing entries while iterating a Map is safe: visited ones stay visited.
diff --git a/src/app/automation/bridge/handlers.ts b/src/app/automation/bridge/handlers.ts
index 51f9a3cd0..42ce729c6 100644
--- a/src/app/automation/bridge/handlers.ts
+++ b/src/app/automation/bridge/handlers.ts
@@ -1,6 +1,6 @@
import type { FigmaAPI } from '@open-pencil/core/figma-api'
-import { endAgentSession } from '@/app/automation/agents'
+import { agentSessionOpened, endAgentSession } from '@/app/automation/agents'
import {
handleActivateDocument,
handleGetSettings,
@@ -76,6 +76,10 @@ export function createAutomationCommandHandlers(makeFigma: FigmaFactory, files?:
return { ok: true, result: { documents: listAutomationDocuments(store) } }
}
if (command === 'list_recent_files') return handleListRecentFiles()
+ if (command === 'agent_session_opened') {
+ agentSessionOpened(args)
+ return { ok: true, result: null }
+ }
if (command === 'agent_session_closed') {
const session = isUnknownRecord(args) ? args.session : undefined
if (typeof session === 'string') endAgentSession(session)
diff --git a/src/app/automation/mcp/runtime.ts b/src/app/automation/mcp/runtime.ts
index c6390c036..6c7a59532 100644
--- a/src/app/automation/mcp/runtime.ts
+++ b/src/app/automation/mcp/runtime.ts
@@ -22,6 +22,8 @@ export interface MCPRuntimeState {
status: MCPRuntimeStatus
endpoint: string
version: string | null
+ /** Whether the running server reports agents opening sessions; older servers do not. */
+ agentSessionEvents: boolean
/** Structured reason the server is unavailable; Settings renders translated copy. */
failure: MCPFailure | null
checking: boolean
@@ -74,6 +76,7 @@ export function createMCPRuntimeService(dependencies: MCPRuntimeDependencies) {
status: 'idle',
endpoint: getMCPServerURL(),
version: null,
+ agentSessionEvents: false,
failure: null,
checking: false,
externallyManaged: false
@@ -95,6 +98,7 @@ export function createMCPRuntimeService(dependencies: MCPRuntimeDependencies) {
function applyHealth(health: AutomationHealth): void {
state.version = health.version ?? null
+ state.agentSessionEvents = health.agentSessionEvents ?? false
dependencies.setToolDescriptors(health.tools ?? [])
state.status = 'running'
state.failure = null
@@ -109,6 +113,7 @@ export function createMCPRuntimeService(dependencies: MCPRuntimeDependencies) {
return { ok: true }
}
state.version = null
+ state.agentSessionEvents = false
dependencies.setToolDescriptors([])
if (state.status !== 'error') state.status = 'stopped'
return { ok: true }
@@ -177,6 +182,7 @@ export function createMCPRuntimeService(dependencies: MCPRuntimeDependencies) {
if (releaseStore) activeStore = null
state.status = disconnectError ? 'error' : 'stopped'
state.version = null
+ state.agentSessionEvents = false
state.failure = disconnectError ? mcpFailure('unknown', disconnectError.message) : null
state.externallyManaged = false
dependencies.setToolDescriptors([])
diff --git a/src/app/automation/mcp/spawn.ts b/src/app/automation/mcp/spawn.ts
index 4272ad999..15ee0e737 100644
--- a/src/app/automation/mcp/spawn.ts
+++ b/src/app/automation/mcp/spawn.ts
@@ -40,6 +40,8 @@ export interface AutomationHealth {
authRequired?: boolean
discoveryPath?: string
tools?: ToolDescriptor[]
+ /** The server tells the app when an agent opens a session, so a chat can wait for its agent. */
+ agentSessionEvents?: boolean
}
export interface AutomationServerHandle {
@@ -237,6 +239,7 @@ interface AutomationHealthRecord {
authRequired?: unknown
discoveryPath?: unknown
tools?: unknown
+ agentSessionEvents?: unknown
}
function isAutomationHealthRecord(value: unknown): value is AutomationHealthRecord {
@@ -272,7 +275,14 @@ function parseAutomationHealth(value: unknown): AutomationHealth | null {
const authRequired = optionalBoolean(value.authRequired)
const discoveryPath = optionalString(value.discoveryPath)
const tools = parseToolDescriptors(value.tools)
- if (version === null || authRequired === null || discoveryPath === null || tools === null) {
+ const agentSessionEvents = optionalBoolean(value.agentSessionEvents)
+ if (
+ version === null ||
+ authRequired === null ||
+ discoveryPath === null ||
+ tools === null ||
+ agentSessionEvents === null
+ ) {
return null
}
const health: AutomationHealth = { status: value.status }
@@ -280,6 +290,7 @@ function parseAutomationHealth(value: unknown): AutomationHealth | null {
if (authRequired !== undefined) health.authRequired = authRequired
if (discoveryPath !== undefined) health.discoveryPath = discoveryPath
if (tools !== undefined) health.tools = tools
+ if (agentSessionEvents !== undefined) health.agentSessionEvents = agentSessionEvents
return health
}
diff --git a/src/app/integrations/mcp/pi.ts b/src/app/integrations/mcp/pi.ts
index 3d80cacc8..ffbd8a339 100644
--- a/src/app/integrations/mcp/pi.ts
+++ b/src/app/integrations/mcp/pi.ts
@@ -1,6 +1,6 @@
-import { AUTOMATION_HTTP_PORT, MCP_AGENT_HEADER } from '@open-pencil/core/constants'
+import { MCP_AGENT_HEADER, OPEN_PENCIL_MCP_SERVER } from '@open-pencil/core/constants'
-import { getAutomationAuthToken } from '@/app/automation/mcp/spawn'
+import { getAutomationAuthToken, getMCPServerURL } from '@/app/automation/mcp/spawn'
import { describeDiagnosticError, recordMCPConnectionFailure } from '@/app/diagnostics'
import { appCredentialServices } from '@/app/settings/credentials/app'
@@ -47,8 +47,8 @@ export async function buildPiMCPServers(options?: {
)
return {
...Object.fromEntries(entries),
- 'open-pencil': {
- url: `http://127.0.0.1:${AUTOMATION_HTTP_PORT}/mcp`,
+ [OPEN_PENCIL_MCP_SERVER]: {
+ url: getMCPServerURL(),
// The Pi harness chat's tool calls show as its agent rather than an outside MCP client.
headers: {
[MCP_AGENT_HEADER]: 'harness',
diff --git a/src/app/integrations/mcp/runtime.ts b/src/app/integrations/mcp/runtime.ts
index 63d87e1ac..687fc4fc0 100644
--- a/src/app/integrations/mcp/runtime.ts
+++ b/src/app/integrations/mcp/runtime.ts
@@ -1,24 +1,33 @@
import type { McpServer } from '@agentclientprotocol/sdk'
-import { AUTOMATION_HTTP_PORT, MCP_AGENT_HEADER } from '@open-pencil/core/constants'
+import {
+ MCP_AGENT_HEADER,
+ MCP_CHAT_HEADER,
+ OPEN_PENCIL_MCP_SERVER
+} from '@open-pencil/core/constants'
+import { getMCPServerURL } from '@/app/automation/mcp/spawn'
import { describeDiagnosticError, recordMCPConnectionFailure } from '@/app/diagnostics'
import { appCredentialServices } from '@/app/settings/credentials/app'
import { enabledMCPConnections } from './store'
import type { MCPConnection } from './types'
+
export type BuiltInMCPServerOptions = {
authorizationToken: string | null
+ /** The chat the agent works for, so the app sees when that agent reaches its tools. */
+ chat?: string
}
export function builtInMCPServer(options: BuiltInMCPServerOptions): McpServer {
return {
type: 'http',
- name: 'open-pencil',
- url: `http://127.0.0.1:${AUTOMATION_HTTP_PORT}/mcp`,
+ name: OPEN_PENCIL_MCP_SERVER,
+ url: getMCPServerURL(),
// An ACP chat's tool calls show as an ACP agent rather than an outside MCP client.
headers: [
{ name: MCP_AGENT_HEADER, value: 'acp' },
+ ...(options.chat ? [{ name: MCP_CHAT_HEADER, value: options.chat }] : []),
...(options.authorizationToken
? [{ name: 'Authorization', value: `Bearer ${options.authorizationToken}` }]
: [])
diff --git a/src/app/tauri/command.ts b/src/app/tauri/command.ts
index fba95033a..284b9ca4d 100644
--- a/src/app/tauri/command.ts
+++ b/src/app/tauri/command.ts
@@ -26,9 +26,22 @@ export function resolvePlatformCommand(
command: string,
args: string[] = [],
userAgent: string = detectUserAgent()
+): { command: string; args: string[] } {
+ return resolveScopedCommand(command, command, args, userAgent)
+}
+
+/**
+ * Like `resolvePlatformCommand`, for a scope entry named apart from the program it runs, such
+ * as `claude-agent-acp-sign-in`, which pins different arguments for `claude-agent-acp`.
+ */
+export function resolveScopedCommand(
+ scope: string,
+ program: string,
+ args: string[] = [],
+ userAgent: string = detectUserAgent()
): { command: string; args: string[] } {
if (userAgent.includes('Windows')) {
- return { command: `cmd-${command}`, args: ['/c', command, ...args] }
+ return { command: `cmd-${scope}`, args: ['/c', program, ...args] }
}
- return { command, args }
+ return { command: scope, args }
}
diff --git a/src/components/chat/tool/state.ts b/src/components/chat/tool/state.ts
index a3151e7e4..9a9bc799b 100644
--- a/src/components/chat/tool/state.ts
+++ b/src/components/chat/tool/state.ts
@@ -14,8 +14,15 @@ export function isMCPToolName(toolName: string): boolean {
return toolName.startsWith('mcp__')
}
+/** A result naming an error; `error: null`, as agents send for success, is not one. */
function hasErrorOutput(output: unknown): boolean {
- return typeof output === 'object' && output !== null && 'error' in output
+ return (
+ typeof output === 'object' &&
+ output !== null &&
+ 'error' in output &&
+ output.error !== null &&
+ output.error !== undefined
+ )
}
export function classifyToolState({ toolName, state, output }: ToolStateInput): ToolDisplayState {
diff --git a/src/components/settings/agents/AgentSetup.vue b/src/components/settings/agents/AgentSetup.vue
index 923e0555e..ab8972908 100644
--- a/src/components/settings/agents/AgentSetup.vue
+++ b/src/components/settings/agents/AgentSetup.vue
@@ -16,10 +16,18 @@ import { NODE_DOWNLOAD_URL } from '@/constants'
import theme from '@/theme/settings/agents'
import AgentSetupItem from './AgentSetupItem.vue'
+import AgentSignInProgress from './AgentSignInProgress.vue'
import { useSetupProblemMessage } from './problem'
const { agent, setup } = defineProps<{ agent: ACPAgentDef; setup: AgentSetupState }>()
-const emit = defineEmits<{ check: []; installAgent: []; installBridge: [] }>()
+const emit = defineEmits<{
+ check: []
+ installAgent: []
+ installBridge: []
+ signIn: []
+ cancelSignIn: []
+ submitSignInCode: [code: string]
+}>()
const { ai, common } = useI18n()
const styles = tv(theme)()
const setupProblemMessage = useSetupProblemMessage()
@@ -45,10 +53,35 @@ const bridgeAction = computed(() => {
return action === 'update' ? ai.value.aiSetupAgentUpdateMCP : ai.value.aiSetupAgentInstallMCP
})
const problemMessage = computed(() => setupProblemMessage(view.value.problem))
+const account = computed(() => view.value.account)
+const accountState = computed(() => {
+ const current = account.value
+ if (!current) return ''
+ if (current.state === 'signed-in') {
+ return [current.label, current.detail].filter((part) => part !== null).join(' · ')
+ }
+ if (current.state === 'signed-out') return ai.value.aiSetupAgentNotSignedIn
+ if (current.state === 'signing-in') return ai.value.aiSetupAgentSigningIn
+ if (current.state === 'checking') return ai.value.aiSetupAgentAccountChecking
+ return ai.value.aiSetupAgentAccountUnknown
+})
+const tools = computed(() => account.value?.tools ?? null)
+const toolsState = computed(() => {
+ const current = tools.value
+ if (current?.state === 'connected') return ai.value.aiSetupAgentToolsConnected
+ if (current?.state === 'unreachable') return ai.value.aiSetupAgentToolsUnreachable
+ return ai.value.aiSetupAgentAccountChecking
+})
+const accountAction = computed(() =>
+ account.value?.canSignIn ? ai.value.aiSetupAgentSignIn : undefined
+)
function agentState(): string {
if (detected.value?.status === 'available') return ai.value.aiSetupAgentInstalled
- if (detected.value?.status === 'needs-adapter') return ai.value.aiSetupAgentNeedsAdapter
+ // Without the agent's own CLI, the adapter installs the agent too.
+ if (detected.value?.status === 'needs-adapter' && detected.value.cliPath) {
+ return ai.value.aiSetupAgentNeedsAdapter
+ }
return ai.value.aiSetupAgentNotFound
}
</script>
@@ -88,7 +121,49 @@ function agentState(): string {
>
{{ ai.aiSetupAgentMCP }} · {{ bridgeState }}
</AgentSetupItem>
+ <AgentSetupItem
+ v-if="account"
+ :ready="account.state === 'signed-in'"
+ :action="accountAction"
+ :loading="account.state === 'checking'"
+ :disabled="view.busy"
+ @action="emit('signIn')"
+ >
+ {{ ai.aiSetupAgentAccount }} · {{ accountState }}
+ <template v-if="account.state === 'signing-in'" #action>
+ <AppButton size="xs" variant="outline" @click="emit('cancelSignIn')">
+ {{ common.cancel }}
+ </AppButton>
+ </template>
+ </AgentSetupItem>
+ <AgentSetupItem v-if="tools" :ready="tools.state === 'connected'">
+ {{ ai.aiSetupAgentTools }} · {{ toolsState }}
+ </AgentSetupItem>
</ul>
+ <AgentSignInProgress
+ v-if="account?.state === 'signing-in'"
+ :account="account"
+ @submit-code="emit('submitSignInCode', $event)"
+ />
+ <p v-if="view.canInstallAdapter && agent.installCommand" :class="styles.help()">
+ {{ ai.aiSetupAgentInstallRuns({ command: agent.installCommand }) }}
+ </p>
+ <AppAlert
+ v-if="account?.error === 'sign-in'"
+ tone="warning"
+ :heading="ai.aiSetupAgentSignInFailed({ agent: agent.name })"
+ />
+ <AppAlert
+ v-if="tools?.state === 'unreachable'"
+ tone="warning"
+ :heading="ai.aiSetupAgentToolsFailed({ agent: agent.name })"
+ :description="tools.reason ?? ai.aiSetupAgentToolsHint"
+ />
+ <AppAlert
+ v-if="view.adapterMismatch"
+ tone="warning"
+ :heading="ai.aiSetupAgentAdapterMismatch({ path: detected?.adapterPath ?? agent.command })"
+ />
<AppAlert v-if="problemMessage" tone="warning" :heading="problemMessage">
<template v-if="view.problem === 'needs-npm'" #actions>
<SettingsLink :href="NODE_DOWNLOAD_URL">Node.js</SettingsLink>
@@ -97,7 +172,9 @@ function agentState(): string {
</template>
<template v-if="view.manualAgentCommand">
- <p :class="styles.help()">{{ ai.aiSetupAgentInstall }}</p>
+ <p :class="styles.help()">
+ {{ view.adapterMismatch ? ai.aiSetupAgentInstallSupported : ai.aiSetupAgentInstall }}
+ </p>
<AppCopyField
:value="view.manualAgentCommand"
:copy-label="common.copy"
@@ -125,7 +202,8 @@ function agentState(): string {
<AppButton
v-if="setup.supported"
size="xs"
- :disabled="view.busy || setup.scanning"
+ :disabled="view.busy"
+ :loading="setup.scanning || setup.account?.checking"
@click="emit('check')"
>
{{ ai.aiSetupAgentCheckAgain }}
diff --git a/src/components/settings/agents/AgentSignInProgress.vue b/src/components/settings/agents/AgentSignInProgress.vue
new file mode 100644
index 000000000..345325389
--- /dev/null
+++ b/src/components/settings/agents/AgentSignInProgress.vue
@@ -0,0 +1,49 @@
+<script setup lang="ts">
+import { tv } from 'tailwind-variants'
+import { ref } from 'vue'
+
+import { useI18n } from '@open-pencil/vue'
+
+import type { AgentAccountView } from '@/app/ai/agents/setup'
+import SettingsLink from '@/components/settings/layout/SettingsLink.vue'
+import AppButton from '@/components/ui/button/AppButton.vue'
+import AppInput from '@/components/ui/input/AppInput.vue'
+import theme from '@/theme/settings/agents'
+
+/** An agent's own login while it runs: the browser does the work, with a code as fallback. */
+const { account } = defineProps<{ account: AgentAccountView }>()
+const emit = defineEmits<{ submitCode: [code: string] }>()
+const { ai } = useI18n()
+const styles = tv(theme)()
+const code = ref('')
+
+function submit() {
+ const value = code.value.trim()
+ if (!value) return
+ emit('submitCode', value)
+ code.value = ''
+}
+</script>
+
+<template>
+ <div :class="styles.signIn()">
+ <p role="status" :class="styles.status()">
+ <icon-lucide-loader-2 :class="styles.spinner()" aria-hidden="true" />
+ {{ ai.aiSetupAgentSignInBrowser }}
+ </p>
+ <SettingsLink v-if="account.signInURL" :href="account.signInURL">
+ {{ ai.aiSetupAgentSignInOpenPage }}
+ </SettingsLink>
+ <form v-if="account.acceptsCode" :class="styles.code()" @submit.prevent="submit">
+ <AppInput
+ v-model="code"
+ class="flex-1"
+ :aria-label="ai.aiSetupAgentSignInCode"
+ :placeholder="ai.aiSetupAgentSignInCode"
+ />
+ <AppButton size="xs" variant="outline" type="submit" :disabled="!code.trim()">
+ {{ ai.aiSetupAgentSignInSubmitCode }}
+ </AppButton>
+ </form>
+ </div>
+</template>
diff --git a/src/components/settings/ai-setup/AISetupAccess.vue b/src/components/settings/ai-setup/AISetupAccess.vue
index ebd9ae8f3..4c3840f7c 100644
--- a/src/components/settings/ai-setup/AISetupAccess.vue
+++ b/src/components/settings/ai-setup/AISetupAccess.vue
@@ -4,6 +4,7 @@ import { ref } from 'vue'
import { useI18n } from '@open-pencil/vue'
+import type { AgentDetection } from '@/app/ai/agents/detection'
import { modelProviderName } from '@/app/ai/models/provider-name'
import {
ONBOARDING_AGENTS,
@@ -20,7 +21,11 @@ import AppCheckboxCard from '@/components/ui/toggle/AppCheckboxCard.vue'
import { DESKTOP_DOWNLOAD_URL } from '@/constants'
import theme from '@/theme/settings/ai-setup/flow'
-const { agentsAvailable } = defineProps<{ agentsAvailable: boolean }>()
+const { agentsAvailable, detections = {} } = defineProps<{
+ agentsAvailable: boolean
+ /** What setup found of each agent on this computer. */
+ detections?: Partial<Record<OnboardingAccess, AgentDetection>>
+}>()
const access = defineModel<OnboardingAccess[]>({ required: true })
const { ai } = useI18n()
const styles = tv(theme)()
@@ -28,6 +33,20 @@ const moreOpen = ref(
ONBOARDING_MORE_API_PROVIDERS.some((provider) => access.value.includes(provider))
)
+function detectionText(providerID: OnboardingAccess): string | undefined {
+ const detection = detections[providerID]
+ if (!detection) return undefined
+ if (detection.state === 'checking') return ai.value.aiSetupAgentChecking
+ if (detection.state === 'not-found') return ai.value.aiSetupDetectNotFound
+ if (detection.state === 'signed-out') return ai.value.aiSetupDetectSignedOut
+ if (detection.state === 'signed-in') {
+ return detection.account
+ ? ai.value.aiSetupDetectSignedInAs({ account: detection.account })
+ : ai.value.aiSetupDetectSignedIn
+ }
+ return ai.value.aiSetupDetectFound
+}
+
function toggle(providerID: OnboardingAccess, checked: boolean): void {
access.value = checked
? [...access.value, providerID]
@@ -44,6 +63,8 @@ function toggle(providerID: OnboardingAccess, checked: boolean): void {
v-for="agent in ONBOARDING_AGENTS"
:key="agent"
:label="modelProviderName(agent)"
+ :description="detectionText(agent)"
+ :data-detection="detections[agent]?.state"
:model-value="access.includes(agent)"
@update:model-value="toggle(agent, $event)"
>
diff --git a/src/components/settings/ai-setup/AISetupConnection.stories.ts b/src/components/settings/ai-setup/AISetupConnection.stories.ts
index aa36d4860..12e7adbc2 100644
--- a/src/components/settings/ai-setup/AISetupConnection.stories.ts
+++ b/src/components/settings/ai-setup/AISetupConnection.stories.ts
@@ -3,6 +3,7 @@ import { expect, within } from 'storybook/test'
import { ACP_AGENTS, type ACPAgentID } from '@open-pencil/core/constants'
+import type { AgentAccount } from '@/app/ai/agents/accounts'
import type { DetectedAgent } from '@/app/ai/agents/discovery'
import type { AgentSetupState, PiSetupState } from '@/app/ai/agents/setup'
@@ -46,6 +47,21 @@ function agentSetup(overrides: Partial<AgentSetupState>): AgentSetupState {
}
}
+function account(overrides: Partial<AgentAccount>): AgentAccount {
+ return {
+ checking: false,
+ status: { kind: 'none', label: 'Not logged in' },
+ adapter: { name: '@agentclientprotocol/claude-agent-acp', version: '0.93.0' },
+ canSignIn: true,
+ signingIn: false,
+ signInURL: null,
+ acceptsCode: false,
+ tools: null,
+ error: null,
+ ...overrides
+ }
+}
+
function piSetup(overrides: Partial<PiSetupState>): PiSetupState {
return {
supported: true,
@@ -167,8 +183,11 @@ export const CodingAgentNeedsAdapter: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement)
await expect(canvas.getByRole('button', { name: 'Install adapter' })).toBeVisible()
+ await expect(
+ canvas.getByText('Installing runs npm i -g @agentclientprotocol/codex-acp.')
+ ).toBeVisible()
await expect(canvas.getByRole('button', { name: 'Install MCP server' })).toBeVisible()
- await expect(canvas.getByRole('link', { name: /Setup guide/ })).toHaveAttribute(
+ await expect(canvas.getByRole('link', { name: 'Learn more' })).toHaveAttribute(
'href',
'https://openpencil.dev/programmable/coding-agents#codex'
)
@@ -187,6 +206,108 @@ export const CodingAgentNeedsNpm: Story = {
await expect(canvas.getByText(/npm i -g @open-pencil\/mcp@/)).toBeVisible()
}
}
+export const CodingAgentSignedIn: Story = {
+ args: {
+ providerID: 'acp:claude-code',
+ recommended: false,
+ agentSetup: agentSetup({
+ detected: detected('claude-code', 'available'),
+ bridge: true,
+ account: account({
+ status: { kind: 'account', label: 'Claude Max', account: { email: '[email protected]' } },
+ tools: { connected: true }
+ })
+ })
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ await expect(canvas.getByText(/Claude Max · ada@example\.com/)).toBeVisible()
+ await expect(canvas.getByText(/OpenPencil tools · connected/)).toBeVisible()
+ await expect(canvas.queryByRole('button', { name: 'Sign in' })).toBeNull()
+ }
+}
+export const CodingAgentToolsUnreachable: Story = {
+ args: {
+ providerID: 'acp:codex',
+ recommended: false,
+ agentSetup: agentSetup({
+ detected: detected('codex', 'available'),
+ bridge: true,
+ account: account({
+ status: { kind: 'account', label: 'ChatGPT Pro', account: { email: '[email protected]' } },
+ adapter: { name: '@agentclientprotocol/codex-acp', version: '2.2.2' },
+ tools: {
+ connected: false,
+ reason:
+ '[codex-acp] MCP server `open-pencil` was not started, because the Codex config already defines an MCP server with this name.'
+ }
+ })
+ })
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ await expect(canvas.getByText(/OpenPencil tools · not reachable/)).toBeVisible()
+ await expect(canvas.getByText(/Codex can’t reach OpenPencil’s tools/)).toBeVisible()
+ await expect(canvas.getByText(/already defines an MCP server/)).toBeVisible()
+ }
+}
+export const CodingAgentSignedOut: Story = {
+ args: {
+ providerID: 'acp:claude-code',
+ recommended: false,
+ agentSetup: agentSetup({
+ detected: detected('claude-code', 'available'),
+ bridge: true,
+ account: account({})
+ })
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ await expect(canvas.getByText(/not signed in/)).toBeVisible()
+ await expect(canvas.getByRole('button', { name: 'Sign in' })).toBeVisible()
+ }
+}
+export const CodingAgentSigningIn: Story = {
+ args: {
+ providerID: 'acp:claude-code',
+ recommended: false,
+ agentSetup: agentSetup({
+ detected: detected('claude-code', 'available'),
+ bridge: true,
+ account: account({
+ signingIn: true,
+ signInURL: 'https://claude.com/cai/oauth/authorize',
+ acceptsCode: true
+ })
+ })
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ await expect(canvas.getByText('Finish signing in in your browser.')).toBeVisible()
+ await expect(canvas.getByRole('link', { name: /Open the sign-in page/ })).toBeVisible()
+ await expect(canvas.getByRole('button', { name: 'Submit code' })).toBeDisabled()
+ await expect(canvas.getByRole('button', { name: 'Cancel' })).toBeVisible()
+ }
+}
+export const CodingAgentOtherAdapter: Story = {
+ args: {
+ providerID: 'acp:codex',
+ recommended: false,
+ agentSetup: agentSetup({
+ detected: { ...detected('codex', 'available'), adapterPath: '/Users/ada/.bun/bin/codex-acp' },
+ bridge: true,
+ account: account({ status: null, adapter: { name: 'codex-acp', version: '0.10.0' } })
+ })
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ await expect(
+ canvas.getByText(/found \/Users\/ada\/\.bun\/bin\/codex-acp, another adapter/)
+ ).toBeVisible()
+ await expect(canvas.getByText('npm i -g @agentclientprotocol/codex-acp')).toBeVisible()
+ await expect(canvas.queryByText(/Account/)).toBeNull()
+ }
+}
export const PiNeedsCompanion: Story = {
args: {
providerID: 'harness:pi',
diff --git a/src/components/settings/ai-setup/AISetupConnection.vue b/src/components/settings/ai-setup/AISetupConnection.vue
index 84e1713fa..5f544facf 100644
--- a/src/components/settings/ai-setup/AISetupConnection.vue
+++ b/src/components/settings/ai-setup/AISetupConnection.vue
@@ -66,6 +66,9 @@ const emit = defineEmits<{
checkAgent: []
installAgent: []
installBridge: []
+ signInAgent: []
+ cancelAgentSignIn: []
+ submitAgentSignInCode: [code: string]
}>()
const { ai, credentials } = useI18n()
const styles = tv(theme)()
@@ -105,6 +108,9 @@ const keyHint = computed(() => {
@check="emit('checkAgent')"
@install-agent="emit('installAgent')"
@install-bridge="emit('installBridge')"
+ @sign-in="emit('signInAgent')"
+ @cancel-sign-in="emit('cancelAgentSignIn')"
+ @submit-sign-in-code="emit('submitAgentSignInCode', $event)"
/>
<PiSetup
v-else-if="piSetup"
diff --git a/src/components/settings/ai-setup/AISetupFlow.vue b/src/components/settings/ai-setup/AISetupFlow.vue
index 7a5d86149..6193e9d7a 100644
--- a/src/components/settings/ai-setup/AISetupFlow.vue
+++ b/src/components/settings/ai-setup/AISetupFlow.vue
@@ -34,8 +34,19 @@ const { ai, common } = useI18n()
const styles = tv(theme)()
const onboarding = useAIOnboarding({ agentsAvailable })
-const { answers, step, recommended, plan, roles, gaps, hasDesign, busy, saveResult, canContinue } =
- onboarding
+const {
+ answers,
+ step,
+ recommended,
+ plan,
+ roles,
+ gaps,
+ hasDesign,
+ busy,
+ saveResult,
+ canContinue,
+ detections
+} = onboarding
const { isRecommended } = roles
const phase = ref<'welcome' | 'wizard' | 'saved'>(entry === 'welcome' ? 'welcome' : 'wizard')
@@ -140,7 +151,11 @@ async function finish(): Promise<void> {
<template v-else-if="step === 'access'">
<p :class="styles.help()">{{ ai.aiSetupAccessDescription }}</p>
- <AISetupAccess v-model="answers.access" :agents-available="agentsAvailable" />
+ <AISetupAccess
+ v-model="answers.access"
+ :agents-available="agentsAvailable"
+ :detections="detections"
+ />
</template>
<template v-else-if="step === 'connect'">
@@ -195,6 +210,9 @@ async function finish(): Promise<void> {
@check-agent="onboarding.refreshAgents()"
@install-agent="onboarding.installAgent(providerID)"
@install-bridge="onboarding.setupCanvasBridge()"
+ @sign-in-agent="onboarding.signInAgent(providerID)"
+ @cancel-agent-sign-in="onboarding.cancelAgentSignIn(providerID)"
+ @submit-agent-sign-in-code="onboarding.submitAgentSignInCode(providerID, $event)"
/>
</template>
diff --git a/src/theme/settings/agents.ts b/src/theme/settings/agents.ts
index f3d438049..e9a9ed9a0 100644
--- a/src/theme/settings/agents.ts
+++ b/src/theme/settings/agents.ts
@@ -10,6 +10,8 @@ export default {
item: 'flex items-center gap-2 text-xs text-surface',
readyIcon: 'size-3.5 shrink-0 text-success',
missingIcon: 'size-3.5 shrink-0 text-muted',
- actions: 'flex items-center gap-2'
+ actions: 'flex items-center gap-2',
+ signIn: 'flex flex-col items-start gap-2',
+ code: 'flex w-full items-center gap-2'
}
}
diff --git a/tests/app/ai/acp/auth/session.test.ts b/tests/app/ai/acp/auth/session.test.ts
new file mode 100644
index 000000000..4dc4915ac
--- /dev/null
+++ b/tests/app/ai/acp/auth/session.test.ts
@@ -0,0 +1,247 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ AgentSideConnection,
+ ndJsonStream,
+ PROTOCOL_VERSION,
+ type Agent,
+ type InitializeRequest,
+ type NewSessionRequest
+} from '@agentclientprotocol/sdk'
+
+import { ACP_AGENTS } from '@open-pencil/core/constants'
+
+import {
+ checkAgentAuth,
+ signInWithAgent,
+ type AgentStreams,
+ type ToolsProbe
+} from '@/app/ai/acp/auth/session'
+import { AUTH_STATUS_UPDATE_METHOD, type AgentAuthStatus } from '@/app/ai/acp/auth/status'
+import type { OwnToolsOutcome } from '@/app/ai/acp/own-tools'
+import { createDeferred } from '@/app/runtime/deferred'
+
+import { expectDefined } from '#tests/helpers/assert'
+
+const codex = expectDefined(
+ ACP_AGENTS.find((agent) => agent.id === 'codex'),
+ 'Codex'
+)
+
+const SIGNED_OUT: AgentAuthStatus = { kind: 'none', label: 'Not logged in' }
+const SIGNED_IN: AgentAuthStatus = {
+ kind: 'account',
+ label: 'ChatGPT Pro',
+ account: { email: '[email protected]', plan: 'pro' }
+}
+
+/** An in-memory ACP agent that reports a login the way Claude's and Codex's adapters do. */
+function fakeAgent(options: {
+ /** Pushed after `initialize` answers; nothing when absent. */
+ status?: AgentAuthStatus
+ /** Pushed after `authenticate` finishes; `authenticate` never finishes when absent. */
+ afterSignIn?: AgentAuthStatus
+ /** False for an agent that starts but never answers `initialize`. */
+ answersInitialize?: boolean
+ /** Starts sessions, recording each request, instead of refusing them. */
+ startsSessions?: boolean
+}) {
+ const toAgent = new TransformStream<Uint8Array, Uint8Array>()
+ const toClient = new TransformStream<Uint8Array, Uint8Array>()
+ const initialized: InitializeRequest[] = []
+ const sessions: NewSessionRequest[] = []
+ const closed = createDeferred<undefined>()
+ const authenticating = createDeferred<undefined>()
+ let connection: AgentSideConnection | null = null
+ const push = (status: AgentAuthStatus) =>
+ void connection?.extNotification(AUTH_STATUS_UPDATE_METHOD, { authStatus: status })
+ const agent: Agent = {
+ async initialize(params) {
+ initialized.push(params)
+ if (options.answersInitialize === false) return createDeferred<never>().promise
+ if (options.status) {
+ const status = options.status
+ setTimeout(() => push(status), 5)
+ }
+ return {
+ protocolVersion: PROTOCOL_VERSION,
+ agentInfo: { name: '@agentclientprotocol/codex-acp', version: '2.2.2' },
+ authMethods: [
+ { id: 'chat-gpt', name: 'ChatGPT' },
+ { id: 'claude-ai-login', name: 'Claude Subscription', type: 'terminal', args: ['login'] },
+ { name: 'Missing id' }
+ ]
+ } as Awaited<ReturnType<Agent['initialize']>>
+ },
+ async newSession(params) {
+ if (!options.startsSessions) throw new Error('Not used')
+ sessions.push(params)
+ return { sessionId: `session-${sessions.length}` }
+ },
+ async authenticate() {
+ authenticating.resolve(undefined)
+ // Without a login to report, the sign-in waits as an unfinished browser login does.
+ if (!options.afterSignIn) return createDeferred<never>().promise
+ // Reported after the answer, so the sign-in must wait past `authenticate` for it.
+ const status = options.afterSignIn
+ setTimeout(() => push(status), 5)
+ return {}
+ },
+ async prompt() {
+ throw new Error('Not used')
+ },
+ cancel: async () => undefined
+ }
+ connection = new AgentSideConnection(
+ () => agent,
+ ndJsonStream(toClient.writable, toAgent.readable)
+ )
+ // Ending the pipe ends what the client reads, as a killed process does.
+ const output = new TransformStream<Uint8Array, Uint8Array>()
+ const stop = new AbortController()
+ toClient.readable
+ .pipeTo(output.writable, { signal: stop.signal, preventCancel: true })
+ .catch(() => undefined)
+ const streams: AgentStreams = {
+ input: toAgent.writable,
+ output: output.readable,
+ async close() {
+ stop.abort()
+ closed.resolve(undefined)
+ }
+ }
+ return {
+ spawn: async () => streams,
+ initialized,
+ sessions,
+ closed: closed.promise,
+ authenticating: authenticating.promise
+ }
+}
+
+describe('checkAgentAuth', () => {
+ test('reads the login an agent reports after initialize, then stops it', async () => {
+ const agent = fakeAgent({ status: SIGNED_IN })
+ const result = await checkAgentAuth(codex, { spawn: agent.spawn })
+ expect(result.status).toEqual(SIGNED_IN)
+ expect(result.adapter).toEqual({ name: '@agentclientprotocol/codex-acp', version: '2.2.2' })
+ expect(result.methods).toEqual([
+ { id: 'chat-gpt', name: 'ChatGPT' },
+ { id: 'claude-ai-login', name: 'Claude Subscription', type: 'terminal' }
+ ])
+ await agent.closed
+ })
+
+ test('asks for terminal sign-in methods, which Claude offers only to clients that run them', async () => {
+ const agent = fakeAgent({ status: SIGNED_OUT })
+ await checkAgentAuth(codex, { spawn: agent.spawn })
+ expect(agent.initialized[0]?.clientCapabilities?._meta).toEqual({ 'terminal-auth': true })
+ })
+
+ test('stops an agent that never answers initialize', async () => {
+ const agent = fakeAgent({ answersInitialize: false })
+ await expect(
+ checkAgentAuth(codex, { spawn: agent.spawn, initializeTimeoutMs: 20 })
+ ).rejects.toThrow('The agent did not start.')
+ await agent.closed
+ })
+
+ test('reports an unknown login when the agent says nothing in time', async () => {
+ const agent = fakeAgent({})
+ const result = await checkAgentAuth(codex, { spawn: agent.spawn, statusTimeoutMs: 20 })
+ expect(result.status).toBeNull()
+ await agent.closed
+ })
+})
+
+describe('signInWithAgent', () => {
+ test('returns the login the agent reports once authenticate finishes', async () => {
+ const agent = fakeAgent({ status: SIGNED_OUT, afterSignIn: SIGNED_IN })
+ const status = await signInWithAgent(codex, 'chat-gpt', new AbortController().signal, {
+ spawn: agent.spawn
+ })
+ expect(status).toEqual(SIGNED_IN)
+ await agent.closed
+ })
+
+ test('stops the agent when the sign-in is cancelled', async () => {
+ const agent = fakeAgent({ status: SIGNED_OUT })
+ const controller = new AbortController()
+ const signIn = signInWithAgent(codex, 'chat-gpt', controller.signal, { spawn: agent.spawn })
+ await agent.authenticating
+ controller.abort()
+ await expect(signIn).rejects.toThrow()
+ await agent.closed
+ })
+})
+
+/** A link to OpenPencil's tools that reports the given outcome once the session exists. */
+function toolsProbe(outcome: OwnToolsOutcome) {
+ const linked: string[] = []
+ const probe: ToolsProbe = {
+ cwd: async () => '/workspace',
+ link: async () => {
+ linked.push('link')
+ return {
+ mcpServers: [
+ { type: 'http', name: 'open-pencil', url: 'http://127.0.0.1:7600/mcp', headers: [] }
+ ],
+ meta: { claudeCode: { options: { allowedTools: ['mcp__open-pencil'] } } },
+ noteUpdate: () => undefined,
+ outcome: async () => outcome,
+ stop: () => undefined
+ }
+ }
+ }
+ return { probe, linked }
+}
+
+describe("checking a signed-in agent reaches OpenPencil's tools", () => {
+ test('starts a session as a chat does, sends no prompt, and reports the outcome', async () => {
+ const agent = fakeAgent({ status: SIGNED_IN, startsSessions: true })
+ const { probe } = toolsProbe({ connected: true })
+ const result = await checkAgentAuth(codex, { spawn: agent.spawn, tools: probe })
+ expect(result.tools).toEqual({ connected: true })
+ expect(agent.sessions).toHaveLength(1)
+ expect(agent.sessions[0]).toMatchObject({
+ cwd: '/workspace',
+ mcpServers: [{ name: 'open-pencil' }],
+ _meta: { claudeCode: { options: { allowedTools: ['mcp__open-pencil'] } } }
+ })
+ await agent.closed
+ })
+
+ test('leaves a signed-out agent unchecked', async () => {
+ const agent = fakeAgent({ status: SIGNED_OUT, startsSessions: true })
+ const { probe, linked } = toolsProbe({ connected: true })
+ const result = await checkAgentAuth(codex, { spawn: agent.spawn, tools: probe })
+ expect(result.tools).toBeNull()
+ expect(linked).toEqual([])
+ expect(agent.sessions).toHaveLength(0)
+ await agent.closed
+ })
+
+ test('keeps the login when linking to the tools fails, as with the MCP server down', async () => {
+ const agent = fakeAgent({ status: SIGNED_IN, startsSessions: true })
+ const probe: ToolsProbe = {
+ cwd: async () => '/workspace',
+ link: async () => {
+ throw new Error('MCP server is not running')
+ }
+ }
+ const result = await checkAgentAuth(codex, { spawn: agent.spawn, tools: probe })
+ expect(result.status).toEqual(SIGNED_IN)
+ expect(result.tools).toEqual({ connected: false, reason: 'MCP server is not running' })
+ expect(agent.sessions).toHaveLength(0)
+ await agent.closed
+ })
+
+ test('a session the agent refuses counts as unreachable, with its reason', async () => {
+ const agent = fakeAgent({ status: SIGNED_IN })
+ const { probe } = toolsProbe({ connected: true })
+ const result = await checkAgentAuth(codex, { spawn: agent.spawn, tools: probe })
+ expect(result.tools).toMatchObject({ connected: false })
+ expect(result.tools && 'reason' in result.tools ? result.tools.reason : null).toBeString()
+ await agent.closed
+ })
+})
diff --git a/tests/app/ai/acp/auth/status.test.ts b/tests/app/ai/acp/auth/status.test.ts
new file mode 100644
index 000000000..1e8df3a2d
--- /dev/null
+++ b/tests/app/ai/acp/auth/status.test.ts
@@ -0,0 +1,20 @@
+import { expect, test } from 'bun:test'
+
+import { isSignedIn, parseAuthStatusUpdate, type AgentAuthStatus } from '@/app/ai/acp/auth/status'
+
+test('reads the login from an auth status update and nothing else', () => {
+ const status: AgentAuthStatus = {
+ kind: 'account',
+ label: 'Claude Max',
+ account: { email: '[email protected]' }
+ }
+ expect(parseAuthStatusUpdate('_auth/status_update', { authStatus: status })).toEqual(status)
+ expect(parseAuthStatusUpdate('_other/update', { authStatus: status })).toBeNull()
+ expect(parseAuthStatusUpdate('_auth/status_update', { authStatus: { kind: 'robot' } })).toBeNull()
+})
+
+test('treats every known identity but none as signed in', () => {
+ expect(isSignedIn({ kind: 'none', label: 'Not logged in' })).toBe(false)
+ expect(isSignedIn({ kind: 'api_key', label: 'Anthropic API key' })).toBe(true)
+ expect(isSignedIn({ kind: 'external', label: 'AWS Bedrock' })).toBe(true)
+})
diff --git a/tests/app/ai/acp/auth/terminal.test.ts b/tests/app/ai/acp/auth/terminal.test.ts
new file mode 100644
index 000000000..3759cc7b7
--- /dev/null
+++ b/tests/app/ai/acp/auth/terminal.test.ts
@@ -0,0 +1,89 @@
+import { afterEach, describe, expect, test } from 'bun:test'
+
+import { ACP_AGENTS } from '@open-pencil/core/constants'
+
+import { findSignInURL, startTerminalSignIn, stripTerminalCodes } from '@/app/ai/acp/auth/terminal'
+
+import { expectDefined } from '#tests/helpers/assert'
+import { clearTauriMocks, mockTauriIPC } from '#tests/helpers/tauri/mocks'
+
+afterEach(clearTauriMocks)
+
+const claude = expectDefined(
+ ACP_AGENTS.find((agent) => agent.id === 'claude-code'),
+ 'Claude Code'
+)
+const LOGIN_ARGS = ['--cli', 'auth', 'login', '--claudeai']
+const PAGE = 'https://claude.com/cai/oauth/authorize?code=true&state=abc'
+
+describe('login output', () => {
+ test('drops terminal hyperlinks and colours', () => {
+ expect(
+ stripTerminalCodes(`\u001B[1mvisit:\u001B[0m \u001B]8;;${PAGE}\u0007${PAGE}\u001B]8;;\u0007`)
+ ).toBe(`visit: ${PAGE}`)
+ })
+
+ test('finds the sign-in page in a line, if any', () => {
+ expect(
+ findSignInURL(
+ `If the browser didn't open, visit: \u001B]8;;${PAGE}\u0007${PAGE}\u001B]8;;\u0007`
+ )
+ ).toBe(PAGE)
+ expect(findSignInURL('Opening browser to sign in…')).toBeNull()
+ })
+})
+
+type ShellEvent = { event: string; payload: unknown }
+
+/** Mocks the shell plugin and returns what the login was started with and sent. */
+async function mockLogin() {
+ const calls: { cmd: string; args: unknown }[] = []
+ let emit: (event: ShellEvent) => void = () => undefined
+ await mockTauriIPC((cmd, args) => {
+ calls.push({ cmd, args })
+ if (cmd === 'plugin:shell|spawn') {
+ emit = (args as { onEvent: { onmessage: (event: ShellEvent) => void } }).onEvent.onmessage
+ return 7
+ }
+ return null
+ })
+ return { calls, emit: (event: ShellEvent) => emit(event) }
+}
+
+describe('startTerminalSignIn', () => {
+ test('runs the agent under its sign-in scope entry and reports the page it prints', async () => {
+ const shell = await mockLogin()
+ const urls: string[] = []
+ const login = await startTerminalSignIn(claude, LOGIN_ARGS, (url) => urls.push(url))
+ expect(shell.calls[0]?.args).toMatchObject({
+ program: 'claude-agent-acp-sign-in',
+ args: LOGIN_ARGS
+ })
+ shell.emit({ event: 'Stdout', payload: 'Opening browser to sign in…' })
+ shell.emit({ event: 'Stdout', payload: `If the browser didn't open, visit: ${PAGE}` })
+ shell.emit({ event: 'Stdout', payload: `Again: ${PAGE}&other` })
+ await login.submitCode(' code-123 ')
+ shell.emit({ event: 'Terminated', payload: { code: 0, signal: null } })
+ await login.done
+ expect(urls).toEqual([PAGE])
+ expect(shell.calls.find((call) => call.cmd === 'plugin:shell|stdin_write')?.args).toEqual({
+ pid: 7,
+ buffer: 'code-123\n'
+ })
+ })
+
+ test('fails when the login exits without signing in', async () => {
+ const shell = await mockLogin()
+ const login = await startTerminalSignIn(claude, LOGIN_ARGS, () => undefined)
+ shell.emit({ event: 'Terminated', payload: { code: 1, signal: null } })
+ await expect(login.done).rejects.toThrow('Sign-in did not finish.')
+ })
+
+ test('stops the login when cancelled', async () => {
+ const shell = await mockLogin()
+ const login = await startTerminalSignIn(claude, LOGIN_ARGS, () => undefined)
+ await login.cancel()
+ await expect(login.done).rejects.toThrow('Sign-in was cancelled.')
+ expect(shell.calls.map((call) => call.cmd)).toEqual(['plugin:shell|spawn', 'plugin:shell|kill'])
+ })
+})
diff --git a/tests/app/ai/agents/accounts.test.ts b/tests/app/ai/agents/accounts.test.ts
new file mode 100644
index 000000000..76da20e01
--- /dev/null
+++ b/tests/app/ai/agents/accounts.test.ts
@@ -0,0 +1,206 @@
+import { describe, expect, mock, test } from 'bun:test'
+
+import { ACP_AGENTS, type ACPAgentDef } from '@open-pencil/core/constants'
+
+import type { AgentAuthCheck } from '@/app/ai/acp/auth/session'
+import type { AgentAuthStatus } from '@/app/ai/acp/auth/status'
+import type { TerminalSignIn } from '@/app/ai/acp/auth/terminal'
+import { createAgentAccounts } from '@/app/ai/agents/accounts'
+import { createDeferred } from '@/app/runtime/deferred'
+
+import { expectDefined } from '#tests/helpers/assert'
+
+const claude = expectDefined(
+ ACP_AGENTS.find((agent) => agent.id === 'claude-code'),
+ 'Claude Code'
+)
+const codex = expectDefined(
+ ACP_AGENTS.find((agent) => agent.id === 'codex'),
+ 'Codex'
+)
+
+const SIGNED_OUT: AgentAuthStatus = { kind: 'none', label: 'Not logged in' }
+const CLAUDE_MAX: AgentAuthStatus = {
+ kind: 'account',
+ label: 'Claude Max',
+ account: { email: '[email protected]' }
+}
+const ADAPTER = { name: '@agentclientprotocol/claude-agent-acp', version: '0.93.0' }
+
+function signedOut(): AgentAuthCheck {
+ return {
+ status: SIGNED_OUT,
+ adapter: ADAPTER,
+ tools: null,
+ methods: [
+ { id: 'claude-ai-login', name: 'Claude Subscription', type: 'terminal' },
+ { id: 'chat-gpt', name: 'ChatGPT' }
+ ]
+ }
+}
+
+function accountsWith(
+ checks: AgentAuthCheck[],
+ overrides: Partial<Parameters<typeof createAgentAccounts>[0]> = {}
+) {
+ const check = mock(async (_agent: ACPAgentDef) => expectDefined(checks.shift(), 'check'))
+ const accounts = createAgentAccounts({
+ enabled: true,
+ check,
+ signInWithAgent: async () => null,
+ startTerminalSignIn: async () => {
+ throw new Error('Not expected')
+ },
+ ...overrides
+ })
+ return { accounts, check }
+}
+
+describe('agent accounts', () => {
+ test('records the login an agent reports and whether setup can sign in to it', async () => {
+ const { accounts } = accountsWith([signedOut()])
+ expect(accounts.account('claude-code').status).toBeUndefined()
+ const checking = accounts.check(claude)
+ expect(accounts.account('claude-code').checking).toBe(true)
+ await checking
+ expect(accounts.account('claude-code')).toMatchObject({
+ checking: false,
+ status: SIGNED_OUT,
+ adapter: ADAPTER,
+ canSignIn: true,
+ error: null
+ })
+ })
+
+ test('offers no sign-in when the agent lacks the method setup uses', async () => {
+ const { accounts } = accountsWith([
+ { status: SIGNED_OUT, adapter: null, methods: [], tools: null }
+ ])
+ await accounts.check(codex)
+ expect(accounts.account('codex').canSignIn).toBe(false)
+ await accounts.signIn(codex)
+ expect(accounts.account('codex').error).toBe('sign-in')
+ })
+
+ test('joins a check that is already running', async () => {
+ const { accounts, check } = accountsWith([signedOut()])
+ await Promise.all([accounts.check(claude), accounts.check(claude)])
+ expect(check).toHaveBeenCalledTimes(1)
+ })
+
+ test('marks a check that could not start the agent', async () => {
+ const accounts = createAgentAccounts({
+ enabled: true,
+ check: async () => {
+ throw new Error('spawn failed')
+ },
+ signInWithAgent: async () => null,
+ startTerminalSignIn: async () => {
+ throw new Error('Not expected')
+ }
+ })
+ await accounts.check(claude)
+ expect(accounts.account('claude-code')).toMatchObject({ checking: false, error: 'check' })
+ })
+
+ test('signs in through the terminal login, then reads the new login from the agent', async () => {
+ const exited = createDeferred<undefined>()
+ const submitCode = mock(async (_code: string) => undefined)
+ const startTerminalSignIn = mock(
+ async (_agent: ACPAgentDef, _args: string[], onURL: (url: string) => void) => {
+ onURL('https://claude.com/sign-in')
+ const login: TerminalSignIn = {
+ done: exited.promise,
+ submitCode,
+ cancel: async () => undefined
+ }
+ return login
+ }
+ )
+ const { accounts } = accountsWith([signedOut(), { ...signedOut(), status: CLAUDE_MAX }], {
+ startTerminalSignIn
+ })
+ await accounts.check(claude)
+ const signingIn = accounts.signIn(claude)
+ await Bun.sleep(0)
+ expect(startTerminalSignIn.mock.calls[0]?.[1]).toEqual(['--cli', 'auth', 'login', '--claudeai'])
+ expect(accounts.account('claude-code')).toMatchObject({
+ signingIn: true,
+ signInURL: 'https://claude.com/sign-in',
+ acceptsCode: true
+ })
+ await accounts.submitCode('claude-code', 'abc')
+ expect(submitCode).toHaveBeenCalledWith('abc')
+ exited.resolve(undefined)
+ await signingIn
+ expect(accounts.account('claude-code')).toMatchObject({
+ signingIn: false,
+ signInURL: null,
+ status: CLAUDE_MAX,
+ error: null
+ })
+ })
+
+ test('signs in through a method the agent runs itself', async () => {
+ const chatGPT: AgentAuthStatus = { kind: 'account', label: 'ChatGPT Pro' }
+ const signInWithAgent = mock(async (_agent: ACPAgentDef, _method: string) => chatGPT)
+ const codexSignedOut = { ...signedOut(), adapter: null }
+ const { accounts } = accountsWith([codexSignedOut, { ...codexSignedOut, status: chatGPT }], {
+ signInWithAgent
+ })
+ await accounts.signIn(codex)
+ expect(signInWithAgent.mock.calls[0]?.[1]).toBe('chat-gpt')
+ expect(accounts.account('codex')).toMatchObject({ signingIn: false, status: chatGPT })
+ })
+
+ test('a cancelled sign-in is not a failure and does not check again', async () => {
+ const { accounts, check } = accountsWith([signedOut()], {
+ signInWithAgent: (_agent, _method, signal) =>
+ new Promise((_resolve, reject) => {
+ signal.addEventListener('abort', () => reject(new Error('aborted')))
+ })
+ })
+ await accounts.check(codex)
+ const signingIn = accounts.signIn(codex)
+ await Bun.sleep(0)
+ await accounts.cancelSignIn('codex')
+ await signingIn
+ expect(accounts.account('codex')).toMatchObject({ signingIn: false, error: null })
+ expect(check).toHaveBeenCalledTimes(1)
+ })
+
+ test('a failed sign-in keeps the last known login', async () => {
+ const { accounts } = accountsWith([signedOut()], {
+ startTerminalSignIn: async () => ({
+ done: Promise.reject(new Error('exit 1')),
+ submitCode: async () => undefined,
+ cancel: async () => undefined
+ })
+ })
+ await accounts.check(claude)
+ await accounts.signIn(claude)
+ expect(accounts.account('claude-code')).toMatchObject({ status: SIGNED_OUT, error: 'sign-in' })
+ })
+
+ test('takes logins the agent reports during a chat', () => {
+ const { accounts } = accountsWith([])
+ accounts.report('claude-code', CLAUDE_MAX)
+ expect(accounts.account('claude-code').status).toEqual(CLAUDE_MAX)
+ })
+
+ test('starts nothing where agents cannot run', async () => {
+ const check = mock(async () => signedOut())
+ const accounts = createAgentAccounts({
+ enabled: false,
+ check,
+ signInWithAgent: async () => null,
+ startTerminalSignIn: async () => {
+ throw new Error('Not expected')
+ }
+ })
+ await accounts.check(claude)
+ await accounts.signIn(claude)
+ expect(check).not.toHaveBeenCalled()
+ expect(accounts.account('claude-code').status).toBeUndefined()
+ })
+})
diff --git a/tests/app/ai/agents/detection.test.ts b/tests/app/ai/agents/detection.test.ts
new file mode 100644
index 000000000..739bfc0aa
--- /dev/null
+++ b/tests/app/ai/agents/detection.test.ts
@@ -0,0 +1,126 @@
+import { describe, expect, test } from 'bun:test'
+
+import { ACP_AGENTS } from '@open-pencil/core/constants'
+
+import type { AgentAccount } from '@/app/ai/agents/accounts'
+import { codingAgentDetection, piDetection } from '@/app/ai/agents/detection'
+import type { DetectedAgent } from '@/app/ai/agents/discovery'
+import type { AgentSetupState, PiSetupState } from '@/app/ai/agents/setup'
+
+import { expectDefined } from '#tests/helpers/assert'
+
+const claude = expectDefined(
+ ACP_AGENTS.find((agent) => agent.id === 'claude-code'),
+ 'Claude Code'
+)
+
+function detected(status: DetectedAgent['status'], cliPath: string | null = null): DetectedAgent {
+ return {
+ definition: claude,
+ status,
+ cliPath,
+ adapterPath: status === 'available' ? '/bin/a' : null
+ }
+}
+
+function account(overrides: Partial<AgentAccount>): AgentAccount {
+ return {
+ checking: false,
+ status: undefined,
+ adapter: { name: '@agentclientprotocol/claude-agent-acp', version: '0.93.0' },
+ canSignIn: true,
+ signingIn: false,
+ signInURL: null,
+ acceptsCode: false,
+ tools: null,
+ error: null,
+ ...overrides
+ }
+}
+
+function setup(overrides: Partial<AgentSetupState>): AgentSetupState {
+ return {
+ supported: true,
+ checked: true,
+ scanning: false,
+ detected: null,
+ bridge: true,
+ bridgeOutdated: false,
+ bridgeCommand: '',
+ npm: true,
+ installingAgent: false,
+ installingBridge: false,
+ error: null,
+ ...overrides
+ }
+}
+
+describe('codingAgentDetection', () => {
+ test('is checking until the first lookup and account check finish', () => {
+ expect(codingAgentDetection(claude, setup({ checked: false }))).toEqual({ state: 'checking' })
+ expect(
+ codingAgentDetection(
+ claude,
+ setup({ detected: detected('available'), account: account({ checking: true }) })
+ )
+ ).toEqual({ state: 'checking' })
+ })
+
+ test('names the account a signed-in agent uses', () => {
+ const status = { kind: 'account' as const, label: 'Claude Max', account: { email: '[email protected]' } }
+ expect(
+ codingAgentDetection(
+ claude,
+ setup({ detected: detected('available'), account: account({ status }) })
+ )
+ ).toEqual({ state: 'signed-in', account: 'Claude Max · [email protected]' })
+ })
+
+ test('tells a signed-out agent from one that is not there', () => {
+ const signedOut = { kind: 'none' as const, label: 'Not logged in' }
+ expect(
+ codingAgentDetection(
+ claude,
+ setup({ detected: detected('available'), account: account({ status: signedOut }) })
+ )
+ ).toEqual({ state: 'signed-out' })
+ expect(codingAgentDetection(claude, setup({ detected: detected('needs-adapter') }))).toEqual({
+ state: 'not-found'
+ })
+ })
+
+ test('counts the agent’s own CLI as found before its adapter is installed', () => {
+ expect(
+ codingAgentDetection(claude, setup({ detected: detected('needs-adapter', '/bin/claude') }))
+ ).toEqual({ state: 'found' })
+ })
+})
+
+describe('piDetection', () => {
+ const pi = (overrides: Partial<PiSetupState>): PiSetupState => ({
+ supported: true,
+ checked: true,
+ scanning: false,
+ companion: false,
+ companionOutdated: false,
+ companionCommand: '',
+ bridge: true,
+ bridgeOutdated: false,
+ bridgeCommand: '',
+ npm: true,
+ installingCompanion: false,
+ installingBridge: false,
+ defaultModel: null,
+ error: null,
+ ...overrides
+ })
+
+ test('reports Pi’s sign-ins without naming its default model as an account', () => {
+ expect(piDetection(pi({ signedIn: true, defaultModel: 'openai-codex/gpt-6' }))).toEqual({
+ state: 'signed-in',
+ account: null
+ })
+ expect(piDetection(pi({ companion: true }))).toEqual({ state: 'found' })
+ expect(piDetection(pi({}))).toEqual({ state: 'not-found' })
+ })
+})
diff --git a/tests/app/ai/agents/discovery.test.ts b/tests/app/ai/agents/discovery.test.ts
index fa67ac104..0e02086f1 100644
--- a/tests/app/ai/agents/discovery.test.ts
+++ b/tests/app/ai/agents/discovery.test.ts
@@ -149,6 +149,15 @@ describe('local agent discovery', () => {
])
})
+ test('offers an adapter that carries its agent even without the agent CLI', () => {
+ const agents = detectedAgents(lookup())
+ expect(agents.map((agent) => [agent.definition.id, agent.status])).toEqual([
+ ['claude-code', 'needs-adapter'],
+ ['codex', 'needs-adapter'],
+ ['gemini-cli', 'not-installed']
+ ])
+ })
+
test('browser discovery performs no native operations', async () => {
const scan = mock(async () => lookup('gemini'))
const install = mock(async () => undefined)
diff --git a/tests/app/ai/agents/setup.test.ts b/tests/app/ai/agents/setup.test.ts
index b33939dac..da662417d 100644
--- a/tests/app/ai/agents/setup.test.ts
+++ b/tests/app/ai/agents/setup.test.ts
@@ -4,6 +4,7 @@ import { nextTick, ref } from 'vue'
import { ACP_AGENTS, type ACPAgentDef } from '@open-pencil/core/constants'
+import { createAgentAccounts, type AgentAccount } from '@/app/ai/agents/accounts'
import { createAgentDiscovery, type DetectedAgent } from '@/app/ai/agents/discovery'
import type { AgentLookup } from '@/app/ai/agents/native'
import {
@@ -55,6 +56,40 @@ describe('useAgentSetup', () => {
expect(agents.piSetup('harness:pi')?.companion).toBe(true)
expect(agents.piSetup('acp:codex')).toBeUndefined()
})
+
+ test('reads the account of each installed agent and signs in to it', async () => {
+ const discovery = createAgentDiscovery({
+ enabled: true,
+ lookup: async () => lookup('npm', 'codex-acp', 'gemini'),
+ install: async () => undefined
+ })
+ const check = mock(async (_agent: ACPAgentDef) => ({
+ status: { kind: 'none' as const, label: 'Not logged in' },
+ adapter: { name: '@agentclientprotocol/codex-acp', version: '2.2.2' },
+ methods: [{ id: 'chat-gpt', name: 'ChatGPT' }],
+ tools: null
+ }))
+ const signInWithAgent = mock(async () => null)
+ const accounts = createAgentAccounts({
+ enabled: true,
+ check,
+ signInWithAgent,
+ startTerminalSignIn: async () => {
+ throw new Error('Not expected')
+ }
+ })
+ const agents = useAgentSetup(discovery, async () => null, accounts)
+ await agents.refreshAgents()
+ expect(check.mock.calls.map(([definition]) => definition.id)).toEqual(['codex'])
+ expect(agentSetupView(agent('codex'), agents.agentSetup('acp:codex')).account).toMatchObject({
+ state: 'signed-out',
+ canSignIn: true
+ })
+ await agents.signInAgent('acp:claude-code')
+ expect(signInWithAgent).not.toHaveBeenCalled()
+ await agents.signInAgent('acp:codex')
+ expect(signInWithAgent).toHaveBeenCalledTimes(1)
+ })
})
function agent(id: string): ACPAgentDef {
@@ -159,6 +194,141 @@ describe('agentSetupView', () => {
})
})
+describe('agent account in setup', () => {
+ const claude = agent('claude-code')
+ const installed: DetectedAgent = {
+ definition: claude,
+ status: 'available',
+ cliPath: null,
+ adapterPath: '/test/bin/claude-agent-acp'
+ }
+ const ADAPTER = { name: '@agentclientprotocol/claude-agent-acp', version: '0.93.0' }
+ const account = (overrides: Partial<AgentAccount> = {}): AgentAccount => ({
+ checking: false,
+ status: undefined,
+ adapter: ADAPTER,
+ canSignIn: true,
+ signingIn: false,
+ signInURL: null,
+ acceptsCode: false,
+ tools: null,
+ error: null,
+ ...overrides
+ })
+
+ test("shows whether a signed-in agent reached OpenPencil's tools", () => {
+ const signedIn = { kind: 'account' as const, label: 'Claude Max' }
+ const toolsOf = (overrides: Partial<AgentAccount>) =>
+ agentSetupView(
+ claude,
+ agentState({ detected: installed, account: account({ status: signedIn, ...overrides }) })
+ ).account?.tools
+ expect(toolsOf({ tools: { connected: true } })).toEqual({ state: 'connected', reason: null })
+ expect(toolsOf({ tools: { connected: false, reason: 'failed to start' } })).toEqual({
+ state: 'unreachable',
+ reason: 'failed to start'
+ })
+ expect(toolsOf({ checking: true })).toEqual({ state: 'checking', reason: null })
+ // An older MCP server cannot tell, and a signed-out agent has no sessions to check.
+ expect(toolsOf({ tools: { connected: null } })).toBeNull()
+ expect(
+ agentSetupView(
+ claude,
+ agentState({
+ detected: installed,
+ account: account({ status: { kind: 'none', label: 'Not logged in' } })
+ })
+ ).account?.tools
+ ).toBeNull()
+ })
+
+ test('names the plan and email of a signed-in agent', () => {
+ const view = agentSetupView(
+ claude,
+ agentState({
+ detected: installed,
+ account: account({
+ status: { kind: 'account', label: 'Claude Max', account: { email: '[email protected]' } }
+ })
+ })
+ )
+ expect(view.account).toMatchObject({
+ state: 'signed-in',
+ label: 'Claude Max',
+ detail: '[email protected]',
+ canSignIn: false
+ })
+ })
+
+ test('offers sign-in to a signed-out agent', () => {
+ const view = agentSetupView(
+ claude,
+ agentState({
+ detected: installed,
+ account: account({ status: { kind: 'none', label: 'Not logged in' } })
+ })
+ )
+ expect(view.account).toMatchObject({ state: 'signed-out', label: null, canSignIn: true })
+ })
+
+ test('shows nothing for an agent that does not report its login', () => {
+ const view = agentSetupView(
+ claude,
+ agentState({ detected: installed, account: account({ status: null }) })
+ )
+ expect(view.account).toBeNull()
+ })
+
+ test('shows the check and the sign-in while they run', () => {
+ const checking = agentSetupView(
+ claude,
+ agentState({ detected: installed, account: account({ checking: true }) })
+ )
+ expect(checking.account?.state).toBe('checking')
+ const signingIn = agentSetupView(
+ claude,
+ agentState({
+ detected: installed,
+ account: account({
+ status: { kind: 'none', label: 'Not logged in' },
+ signingIn: true,
+ signInURL: 'https://claude.com/sign-in',
+ acceptsCode: true
+ })
+ })
+ )
+ expect(signingIn.account).toMatchObject({
+ state: 'signing-in',
+ signInURL: 'https://claude.com/sign-in',
+ acceptsCode: true
+ })
+ })
+
+ test('has no account before the adapter is installed', () => {
+ const view = agentSetupView(
+ claude,
+ agentState({
+ detected: { ...installed, status: 'needs-adapter', adapterPath: null },
+ account: account({ status: { kind: 'none', label: 'Not logged in' } })
+ })
+ )
+ expect(view.account).toBeNull()
+ })
+
+ test('flags another adapter under the same name and offers the supported one', () => {
+ const view = agentSetupView(
+ claude,
+ agentState({
+ detected: installed,
+ account: account({ adapter: { name: 'claude-code-acp', version: '0.1.0' }, status: null })
+ })
+ )
+ expect(view.adapterMismatch).toBe(true)
+ expect(view.account).toBeNull()
+ expect(view.manualAgentCommand).toBe(claude.installCommand ?? null)
+ })
+})
+
describe('piSetupView', () => {
test('is ready with a matching companion and MCP server', () => {
const view = piSetupView(piState())
diff --git a/tests/app/ai/models/settings/onboarding/plan.test.ts b/tests/app/ai/models/settings/onboarding/plan.test.ts
index 9987bab95..4f779f0c7 100644
--- a/tests/app/ai/models/settings/onboarding/plan.test.ts
+++ b/tests/app/ai/models/settings/onboarding/plan.test.ts
@@ -135,6 +135,16 @@ describe('planOnboarding with configured models', () => {
expect(plan.connections).toEqual([])
})
+ test('connects a selected agent beside a configured design model it does not replace', () => {
+ const plan = planOnboarding(answers({ access: ['anthropic', 'acp:claude-code'] }), {
+ ...desktop,
+ current: { configured: true, design: opus, vision: null, review: null, fast: null }
+ })
+ expect(plan.design).toBe(opus)
+ expect(plan.connections).toEqual(['acp:claude-code'])
+ expect(roleOptions('design', plan, [opus]).map(roleChoiceKey)).toContain('acp:claude-code::')
+ })
+
test('replaces a configured design model whose access was deselected', () => {
const plan = planOnboarding(answers({ access: ['openai'] }), {
...desktop,
diff --git a/tests/app/automation/agents.test.ts b/tests/app/automation/agents.test.ts
index 8d55837cf..b3016f13d 100644
--- a/tests/app/automation/agents.test.ts
+++ b/tests/app/automation/agents.test.ts
@@ -6,12 +6,14 @@ import {
MCP_AGENT_GONE_MS,
MCP_AGENT_IDLE_MS,
agentFinished,
+ agentSessionOpened,
agentStarted,
endAgentSession,
readAgentSession,
restAgents,
touchedNodeIds,
- type AgentSession
+ type AgentSession,
+ watchChatAgent
} from '@/app/automation/agents'
import { createEditorStore, type EditorStore } from '@/app/editor/session'
import { presenceOf } from '@/app/presence/registry'
@@ -154,3 +156,33 @@ describe("the app's own ACP and Pi chats", () => {
expect(status(pi)).toBe('editing')
})
})
+
+describe("a chat's agent reaching OpenPencil's tools", () => {
+ test('the chat goes on once the server says its own agent opened a session', async () => {
+ const watch = watchChatAgent('0123456789abcdef')
+ let connected = false
+ void watch.connected.then(() => (connected = true))
+
+ agentSessionOpened({ session: 's-1', kind: 'acp', chat: 'fedcba9876543210' })
+ agentSessionOpened({ session: 's-2', kind: 'mcp' })
+ // An outside MCP client naming the chat does not stand in for its ACP agent.
+ agentSessionOpened({ session: 's-4', kind: 'mcp', chat: '0123456789abcdef' })
+ await Promise.resolve()
+ expect(connected).toBe(false)
+
+ agentSessionOpened({ session: 's-3', kind: 'acp', chat: '0123456789abcdef' })
+ await watch.connected
+ expect(connected).toBe(true)
+ })
+
+ test('a chat that stopped waiting ignores a late session', async () => {
+ const watch = watchChatAgent('00112233445566778899')
+ watch.stop()
+ agentSessionOpened({ session: 's-1', kind: 'acp', chat: '00112233445566778899' })
+ const settled = await Promise.race([
+ watch.connected.then(() => 'connected'),
+ Promise.resolve('waiting')
+ ])
+ expect(settled).toBe('waiting')
+ })
+})
diff --git a/tests/engine/acp/transport.test.ts b/tests/engine/acp/transport.test.ts
index 6fbf54fee..6316feb05 100644
--- a/tests/engine/acp/transport.test.ts
+++ b/tests/engine/acp/transport.test.ts
@@ -1,176 +1,246 @@
import { describe, expect, test } from 'bun:test'
import type { SessionUpdate } from '@agentclientprotocol/sdk'
+import { readUIMessageStream, type UIMessage, type UIMessageChunk } from 'ai'
import type { ACPAgentDef } from '@open-pencil/core/constants'
-import { mapUpdate } from '@/app/ai/acp/map-update'
+import { createUpdateMapper } from '@/app/ai/acp/map-update'
import { formatConnectionError, buildCrashChunks } from '@/app/ai/acp/transport'
+import { classifyToolState } from '@/components/chat/tool/state'
+
+import { expectDefined } from '#tests/helpers/assert'
const TEXT_ID = 'text-1'
-describe('mapUpdate', () => {
- test('agent_message_chunk with non-empty text starts text and emits delta', () => {
- const update: SessionUpdate = {
- sessionUpdate: 'agent_message_chunk',
- content: { type: 'text', text: 'Hello' }
+/** The message the chat builds from one turn's updates, as the transport streams them. */
+async function transcript(updates: SessionUpdate[]): Promise<UIMessage['parts']> {
+ const mapper = createUpdateMapper('turn')
+ const chunks: UIMessageChunk[] = [{ type: 'start' }, { type: 'start-step' }]
+ for (const update of updates) chunks.push(...mapper.map(update))
+ chunks.push(...mapper.end(), { type: 'finish-step' }, { type: 'finish', finishReason: 'stop' })
+ const stream = new ReadableStream<UIMessageChunk>({
+ start(controller) {
+ for (const chunk of chunks) controller.enqueue(chunk)
+ controller.close()
}
- const result = mapUpdate(update, TEXT_ID, false)
- expect(result.textStarted).toBe(true)
- expect(result.chunks).toEqual([
- { type: 'text-start', id: TEXT_ID },
- { type: 'text-delta', id: TEXT_ID, delta: 'Hello' }
- ])
})
+ let message: UIMessage | undefined
+ for await (const next of readUIMessageStream({ stream })) message = next
+ return (message?.parts ?? []).filter((part) => part.type !== 'step-start')
+}
- test('agent_message_chunk with empty text is skipped', () => {
- const update: SessionUpdate = {
- sessionUpdate: 'agent_message_chunk',
- content: { type: 'text', text: '' }
- }
- const result = mapUpdate(update, TEXT_ID, false)
- expect(result.textStarted).toBe(false)
- expect(result.chunks).toEqual([])
+function text(value: string): SessionUpdate {
+ return { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: value } }
+}
+
+function thought(value: string): SessionUpdate {
+ return { sessionUpdate: 'agent_thought_chunk', content: { type: 'text', text: value } }
+}
+
+function shown(part: UIMessage['parts'][number]) {
+ if (!('toolCallId' in part)) return null
+ const output = 'output' in part ? part.output : undefined
+ return {
+ type: part.type,
+ input: part.input,
+ state: classifyToolState({ toolName: part.type.slice(5), state: part.state, output }),
+ output,
+ errorText: 'errorText' in part ? part.errorText : undefined
+ }
+}
+
+/** Codex reports an MCP call titled by server and tool, with them and the arguments as input. */
+function codexCall(server: string, tool: string, args: unknown, id = 'call-1'): SessionUpdate {
+ return {
+ sessionUpdate: 'tool_call',
+ toolCallId: id,
+ title: `mcp.${server}.${tool}`,
+ kind: 'execute',
+ status: 'in_progress',
+ rawInput: { server, tool, arguments: args }
+ }
+}
+
+function codexDone(result: unknown, error: unknown = null, id = 'call-1'): SessionUpdate {
+ return {
+ sessionUpdate: 'tool_call_update',
+ toolCallId: id,
+ status: error ? 'failed' : 'completed',
+ rawOutput: { result, error }
+ }
+}
+
+function mcpText(value: unknown, isError?: boolean) {
+ return {
+ content: [{ type: 'text', text: JSON.stringify(value) }],
+ structuredContent: null,
+ ...(isError ? { isError } : {})
+ }
+}
+
+describe('an ACP turn in the chat', () => {
+ test('text forms one part until something else comes between', async () => {
+ const parts = await transcript([
+ text('I’ll inspect '),
+ text('the page.'),
+ codexCall('open-pencil', 'get_page_tree', {}),
+ codexDone(mcpText({ children: [] })),
+ text('Done.')
+ ])
+ expect(parts.filter((part) => part.type === 'text').map((part) => part.text)).toEqual([
+ 'I’ll inspect the page.',
+ 'Done.'
+ ])
})
- test('subsequent agent_message_chunk does not re-emit text-start', () => {
- const update: SessionUpdate = {
- sessionUpdate: 'agent_message_chunk',
- content: { type: 'text', text: 'world' }
- }
- const result = mapUpdate(update, TEXT_ID, true)
- expect(result.textStarted).toBe(true)
- expect(result.chunks).toEqual([{ type: 'text-delta', id: TEXT_ID, delta: 'world' }])
+ test('a run of thoughts shows as one reasoning part', async () => {
+ const parts = await transcript([thought('Plan'), thought(' the grid'), text('Building it.')])
+ expect(parts.map((part) => part.type)).toEqual(['reasoning', 'text'])
+ expect(parts[0]).toMatchObject({ text: 'Plan the grid' })
})
- test('agent_thought_chunk emits reasoning start/delta/end', () => {
- const update: SessionUpdate = {
- sessionUpdate: 'agent_thought_chunk',
- content: { type: 'text', text: 'thinking...' }
- }
- const result = mapUpdate(update, TEXT_ID, false)
- expect(result.chunks).toHaveLength(3)
- expect(result.chunks[0].type).toBe('reasoning-start')
- expect(result.chunks[1]).toEqual({
- type: 'reasoning-delta',
- id: `reasoning-${TEXT_ID}`,
- delta: 'thinking...'
+ test('OpenPencil’s own tools show as the built-in chat’s, with their arguments and result', async () => {
+ const [call] = await transcript([
+ codexCall('open-pencil', 'render', { jsx: '<Frame name="Calendar" />' }),
+ codexDone(mcpText({ id: '1:2', name: 'Calendar' }))
+ ])
+ expect(shown(expectDefined(call, 'tool part'))).toMatchObject({
+ type: 'tool-render',
+ input: { jsx: '<Frame name="Calendar" />' },
+ state: 'done',
+ output: { id: '1:2', name: 'Calendar' }
})
- expect(result.chunks[2].type).toBe('reasoning-end')
})
- test('tool_call emits tool-input-start', () => {
- const update: SessionUpdate = {
- sessionUpdate: 'tool_call',
- toolCallId: 'tc-1',
- title: 'create_shape',
- kind: 'edit',
- status: 'pending'
- }
- const result = mapUpdate(update, TEXT_ID, false)
- expect(result.chunks).toEqual([
- {
- type: 'tool-input-start',
- toolCallId: 'tc-1',
- toolName: 'create_shape',
- providerExecuted: true,
- title: 'create_shape'
- }
+ test('an exported image is passed on as the built-in chat holds it', async () => {
+ const [call] = await transcript([
+ codexCall('open-pencil', 'export_image', { ids: ['1:2'] }),
+ codexDone({ content: [{ type: 'image', data: 'iVBORw0KGgo=', mimeType: 'image/png' }] })
])
+ expect(shown(expectDefined(call, 'tool part'))?.output).toEqual({
+ base64: 'iVBORw0KGgo=',
+ mimeType: 'image/png'
+ })
})
- test('tool_call with rawInput emits tool-input-available', () => {
- const update: SessionUpdate = {
- sessionUpdate: 'tool_call',
- toolCallId: 'tc-2',
- title: 'set_fill',
- kind: 'edit',
- status: 'pending',
- rawInput: { id: '1:2', color: '#ff0000' }
- }
- const result = mapUpdate(update, TEXT_ID, false)
- expect(result.chunks).toHaveLength(2)
- expect(result.chunks[1]).toEqual({
- type: 'tool-input-available',
- toolCallId: 'tc-2',
- toolName: 'set_fill',
- input: { id: '1:2', color: '#ff0000' },
- providerExecuted: true,
- title: 'set_fill'
- })
+ test('a tool error shows as a failed call with the tool’s message', async () => {
+ const parts = await transcript([
+ codexCall('open-pencil', 'describe', { id: '9:9' }, 'a'),
+ codexDone(mcpText({ error: 'Node 9:9 not found' }, true), null, 'a'),
+ codexCall('open-pencil', 'describe', { id: '9:9' }, 'b'),
+ codexDone(null, { message: 'tool call timed out' }, 'b')
+ ])
+ expect(parts.map((part) => shown(part))).toMatchObject([
+ { state: 'error', errorText: 'Node 9:9 not found' },
+ { state: 'error', errorText: 'tool call timed out' }
+ ])
})
- test('tool_call with empty title falls back to "unknown"', () => {
- const update: SessionUpdate = {
- sessionUpdate: 'tool_call',
- toolCallId: 'tc-3',
- title: '',
- kind: 'other',
- status: 'pending'
- }
- const result = mapUpdate(update, TEXT_ID, false)
- expect(result.chunks[0]).toMatchObject({ toolName: 'unknown' })
+ test('another server’s tools keep the MCP name and result', async () => {
+ const result = mcpText({ url: 'https://example.com' })
+ const [call] = await transcript([
+ codexCall('playwriter', 'execute', { code: 'page.url()' }),
+ codexDone(result)
+ ])
+ expect(shown(expectDefined(call, 'tool part'))).toMatchObject({
+ type: 'tool-mcp__playwriter__execute',
+ input: { code: 'page.url()' },
+ state: 'done',
+ output: result
+ })
})
- test('tool_call_update completed emits tool-output-available', () => {
- const update: SessionUpdate = {
- sessionUpdate: 'tool_call_update',
- toolCallId: 'tc-1',
- status: 'completed',
- rawOutput: { id: '1:5', type: 'RECTANGLE' }
- }
- const result = mapUpdate(update, TEXT_ID, false)
- expect(result.chunks).toEqual([
+ test('Claude’s calls to OpenPencil’s tools show the same way, input arriving later', async () => {
+ const meta = { claudeCode: { toolName: 'mcp__open-pencil__render' } }
+ const [call] = await transcript([
{
- type: 'tool-output-available',
- toolCallId: 'tc-1',
- output: { id: '1:5', type: 'RECTANGLE' },
- providerExecuted: true
+ sessionUpdate: 'tool_call',
+ toolCallId: 'toolu_1',
+ title: 'render',
+ kind: 'other',
+ status: 'pending',
+ rawInput: {},
+ _meta: meta
+ },
+ {
+ sessionUpdate: 'tool_call_update',
+ toolCallId: 'toolu_1',
+ rawInput: { jsx: '<Frame />' },
+ _meta: meta
+ },
+ {
+ sessionUpdate: 'tool_call_update',
+ toolCallId: 'toolu_1',
+ status: 'completed',
+ rawOutput: [{ type: 'text', text: JSON.stringify({ id: '1:3' }) }],
+ _meta: meta
}
])
+ expect(shown(expectDefined(call, 'tool part'))).toMatchObject({
+ type: 'tool-render',
+ input: { jsx: '<Frame />' },
+ state: 'done',
+ output: { id: '1:3' }
+ })
})
- test('tool_call_update failed emits tool-output-error', () => {
- const update: SessionUpdate = {
- sessionUpdate: 'tool_call_update',
- toolCallId: 'tc-1',
- status: 'failed',
- content: [{ type: 'content', content: { type: 'text', text: 'Node not found' } }]
- }
- const result = mapUpdate(update, TEXT_ID, false)
- expect(result.chunks).toEqual([
+ test('an agent’s own tools keep its title and output', async () => {
+ const [call] = await transcript([
+ {
+ sessionUpdate: 'tool_call',
+ toolCallId: 'sh-1',
+ title: 'Run ls',
+ kind: 'execute',
+ status: 'in_progress',
+ rawInput: { command: 'ls' }
+ },
{
- type: 'tool-output-error',
- toolCallId: 'tc-1',
- errorText: 'Node not found',
- providerExecuted: true
+ sessionUpdate: 'tool_call_update',
+ toolCallId: 'sh-1',
+ status: 'failed',
+ content: [{ type: 'content', content: { type: 'text', text: 'Permission denied' } }]
}
])
+ expect(shown(expectDefined(call, 'tool part'))).toMatchObject({
+ type: 'tool-Run ls',
+ state: 'error',
+ errorText: 'Permission denied'
+ })
})
- test('agent_message_chunk with non-text content produces no chunks', () => {
- const update: SessionUpdate = {
- sessionUpdate: 'agent_message_chunk',
- content: {
- type: 'image',
- mimeType: 'image/png',
- data: '',
- uri: 'https://example.com/img.png'
+ test('a tool_call that arrives already failed ends with its error', async () => {
+ const [call] = await transcript([
+ {
+ sessionUpdate: 'tool_call',
+ toolCallId: 'mcp_startup.open-pencil',
+ title: 'mcp__open-pencil__startup',
+ kind: 'other',
+ status: 'failed',
+ content: [{ type: 'content', content: { type: 'text', text: 'failed to start' } }]
}
- }
- const result = mapUpdate(update, TEXT_ID, false)
- expect(result.textStarted).toBe(false)
- expect(result.chunks).toEqual([])
+ ])
+ expect(shown(expectDefined(call, 'tool part'))).toMatchObject({
+ state: 'error',
+ errorText: 'failed to start'
+ })
})
- test('unhandled update type produces no chunks', () => {
- const update = {
- sessionUpdate: 'available_commands_update',
- availableCommands: []
- } as SessionUpdate
- const result = mapUpdate(update, TEXT_ID, false)
- expect(result.chunks).toEqual([])
- expect(result.textStarted).toBe(false)
+ test('non-text content and other updates add nothing', async () => {
+ const parts = await transcript([
+ {
+ sessionUpdate: 'agent_message_chunk',
+ content: {
+ type: 'image',
+ mimeType: 'image/png',
+ data: '',
+ uri: 'https://example.com/a.png'
+ }
+ },
+ { sessionUpdate: 'available_commands_update', availableCommands: [] },
+ text('')
+ ])
+ expect(parts).toEqual([])
})
})
diff --git a/tests/engine/mcp/server/index.test.ts b/tests/engine/mcp/server/index.test.ts
index 2e27f98f4..30a01f400 100644
--- a/tests/engine/mcp/server/index.test.ts
+++ b/tests/engine/mcp/server/index.test.ts
@@ -7,7 +7,7 @@ import { join } from 'node:path'
import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client'
-import { MCP_AGENT_HEADER } from '@open-pencil/core/constants'
+import { MCP_AGENT_HEADER, MCP_CHAT_HEADER } from '@open-pencil/core/constants'
import { SceneGraph } from '@open-pencil/scene-graph'
import { startServer, type ServerHandle } from '#mcp/server'
@@ -955,4 +955,38 @@ describe('MCP sessions as agents', () => {
expect(closed()?.args).toEqual({ session: agent.session })
})
})
+
+ function openedNotice(browser: MockBrowser) {
+ return browser.requests.find((item) => item.command === 'agent_session_opened')
+ }
+
+ test("an ACP chat's session tells the app it opened, naming the chat", async () => {
+ const chat = '0123456789abcdef0123456789abcdef'
+ await withAgentClient(
+ { [MCP_AGENT_HEADER]: 'acp', [MCP_CHAT_HEADER]: chat },
+ async (client, browser) => {
+ // The notice reaches the app over its socket after initialize is answered.
+ for (let attempt = 0; attempt < 50 && !openedNotice(browser); attempt++) {
+ await Bun.sleep(10)
+ }
+ expect(openedNotice(browser)?.args).toMatchObject({ kind: 'acp', chat })
+ await client.callTool({ name: 'get_page_tree', arguments: {} })
+ const agent = agentOf(browser) as { session: string }
+ expect(openedNotice(browser)?.args).toMatchObject({ session: agent.session })
+ }
+ )
+ })
+
+ test('a chat header that is not a chat id is not forwarded', async () => {
+ await withAgentClient(
+ { [MCP_AGENT_HEADER]: 'acp', [MCP_CHAT_HEADER]: 'not hex' },
+ async (_client, browser) => {
+ for (let attempt = 0; attempt < 50 && !openedNotice(browser); attempt++) {
+ await Bun.sleep(10)
+ }
+ const notice = expectDefined(openedNotice(browser), 'agent_session_opened notice')
+ expect(notice.args).not.toHaveProperty('chat')
+ }
+ )
+ })
})
diff --git a/tests/engine/tauri/acp-transport.test.ts b/tests/engine/tauri/acp-transport.test.ts
index 378ae5487..3c8630ed2 100644
--- a/tests/engine/tauri/acp-transport.test.ts
+++ b/tests/engine/tauri/acp-transport.test.ts
@@ -16,15 +16,15 @@ function cwdOf(transport: object): string | null {
}
describe('Tauri ACP transport', () => {
- test('uses Tauri home directory for transport cwd', async () => {
- await mockTauriIPC((cmd, args) => {
- expect(cmd).toBe('plugin:path|resolve_directory')
- expect(args).toEqual({ directory: 21 })
- return '/Users/tester'
+ test('starts the agent in the folder the desktop shell sets aside for agents', async () => {
+ const workspace = '/Users/tester/Library/Application Support/OpenPencil/agent-workspace'
+ await mockTauriIPC((cmd) => {
+ expect(cmd).toBe('agent_workspace')
+ return workspace
})
const transport = await createACPTransport('acp:claude-code')
- expect(cwdOf(transport)).toBe('/Users/tester')
+ expect(cwdOf(transport)).toBe(workspace)
})
})
diff --git a/tests/engine/tauri/command.test.ts b/tests/engine/tauri/command.test.ts
index 43e3dfdae..8b8342338 100644
--- a/tests/engine/tauri/command.test.ts
+++ b/tests/engine/tauri/command.test.ts
@@ -5,10 +5,11 @@ import * as v from 'valibot'
import { ACP_AGENTS } from '@open-pencil/core/constants'
+import { signInScope } from '@/app/ai/acp/auth/terminal'
import { bunInstallArgs, npmInstallArgs } from '@/app/ai/agents/native'
import { HARNESS_PACKAGE } from '@/app/ai/harness/companion'
import { MCP_PACKAGE_NAME } from '@/app/automation/mcp/failure'
-import { resolvePlatformCommand } from '@/app/tauri/command'
+import { resolvePlatformCommand, resolveScopedCommand } from '@/app/tauri/command'
import { repoPath } from '#tests/helpers/paths'
@@ -46,6 +47,17 @@ describe('resolvePlatformCommand', () => {
})
})
+ test('runs a program through a scope entry named apart from it', () => {
+ expect(resolveScopedCommand('agent-sign-in', 'agent', ['login'], WINDOWS_UA)).toEqual({
+ command: 'cmd-agent-sign-in',
+ args: ['/c', 'agent', 'login']
+ })
+ expect(resolveScopedCommand('agent-sign-in', 'agent', ['login'], MAC_UA)).toEqual({
+ command: 'agent-sign-in',
+ args: ['login']
+ })
+ })
+
test('passes through when the user agent is unavailable (headless/non-browser)', () => {
expect(resolvePlatformCommand('openpencil-mcp-http', ['--stdio'], '')).toEqual({
command: 'openpencil-mcp-http',
@@ -109,6 +121,10 @@ describe('shell scope', () => {
`${MCP_PACKAGE_NAME}@${rootPackage.version}`,
`${HARNESS_PACKAGE}@${rootPackage.version}`
]
+ // Agents' terminal sign-ins run the agent under a scope entry of their own.
+ const signIns = ACP_AGENTS.flatMap((agent): [string, string, string[]][] =>
+ agent.signIn?.via === 'terminal' ? [[signInScope(agent), agent.command, agent.signIn.args]] : []
+ )
const spawns: [string, string[]][] = [
...ACP_AGENTS.map((agent): [string, string[]] => [agent.command, agent.args]),
['openpencil-mcp-http', []],
@@ -132,10 +148,24 @@ describe('shell scope', () => {
}
}
+ for (const userAgent of [WINDOWS_UA, MAC_UA]) {
+ for (const [scope, program, args] of signIns) {
+ test(`allows exactly ${program} ${args.join(' ')} as ${scope} on ${userAgent === MAC_UA ? 'macOS' : 'Windows'}`, () => {
+ const resolved = resolveScopedCommand(scope, program, args, userAgent)
+ const entry = spawnScope().find((candidate) => candidate.name === resolved.command)
+ expect(entry?.cmd).toBe(userAgent === WINDOWS_UA ? 'cmd' : program)
+ expect(allowedArgs(entry?.args, resolved.args)).toEqual(resolved.args)
+ })
+ }
+ }
+
test('allows nothing but those programs', () => {
- const expected = [WINDOWS_UA, MAC_UA].flatMap((userAgent) =>
- spawns.map(([name, args]) => resolvePlatformCommand(name, args, userAgent).command)
- )
+ const expected = [WINDOWS_UA, MAC_UA].flatMap((userAgent) => [
+ ...spawns.map(([name, args]) => resolvePlatformCommand(name, args, userAgent).command),
+ ...signIns.map(
+ ([scope, program, args]) => resolveScopedCommand(scope, program, args, userAgent).command
+ )
+ ])
expect(
spawnScope()
.map((entry) => entry.name)
diff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txt
index 56deb48f3..7590ecb16 100644
--- a/tools/checks/i18n/mixed-script-baseline.txt
+++ b/tools/checks/i18n/mixed-script-baseline.txt
@@ -1,6 +1,7 @@
ja:ai.aiSetupAccessAPI
ja:ai.aiSetupAccessAgentsDesktop
ja:ai.aiSetupAccessServerDescription
+ja:ai.aiSetupAgentAdapterMismatch
ja:ai.aiSetupAgentDescription
ja:ai.aiSetupAgentInstallMCP
ja:ai.aiSetupAgentMCP
@@ -10,6 +11,9 @@ ja:ai.aiSetupAgentNeedsAdapter
ja:ai.aiSetupAgentNeedsAdmin
ja:ai.aiSetupAgentNeedsNpm
ja:ai.aiSetupAgentPromptHint
+ja:ai.aiSetupAgentTools
+ja:ai.aiSetupAgentToolsFailed
+ja:ai.aiSetupAgentToolsHint
ja:ai.aiSetupConnectTitle
ja:ai.aiSetupGapAddOpenRouter
ja:ai.aiSetupGapCoveredByOpenRouter
@@ -210,6 +214,7 @@ ja:updates.upToDate
zh-cn:ai.aiSetupAccessAPI
zh-cn:ai.aiSetupAccessAgentsDesktop
zh-cn:ai.aiSetupAccessServerDescription
+zh-cn:ai.aiSetupAgentAdapterMismatch
zh-cn:ai.aiSetupAgentDescription
zh-cn:ai.aiSetupAgentInstallMCP
zh-cn:ai.aiSetupAgentMCP
@@ -219,6 +224,9 @@ zh-cn:ai.aiSetupAgentNeedsAdapter
zh-cn:ai.aiSetupAgentNeedsAdmin
zh-cn:ai.aiSetupAgentNeedsNpm
zh-cn:ai.aiSetupAgentPromptHint
+zh-cn:ai.aiSetupAgentTools
+zh-cn:ai.aiSetupAgentToolsFailed
+zh-cn:ai.aiSetupAgentToolsHint
zh-cn:ai.aiSetupConnectTitle
zh-cn:ai.aiSetupGapAddOpenRouter
zh-cn:ai.aiSetupGapCoveredByOpenRouter
diff --git a/tools/checks/i18n/translation-baseline.txt b/tools/checks/i18n/translation-baseline.txt
index 2187b4570..d4cea9792 100644
--- a/tools/checks/i18n/translation-baseline.txt
+++ b/tools/checks/i18n/translation-baseline.txt
@@ -198,6 +198,7 @@ fr:tools.ellipse
fr:tools.rectangle
fr:tools.section
fr:variables.modes
+it:ai.aiSetupAgentAccount
it:ai.chatSettings
it:ai.completions
it:ai.responses