Skip to content

Your team of AI agents, on your Mac, Windows or Linux. Agents that talk in channels, write code, review each other and use your tools, on the Claude Code, Codex, OpenCode or Pi you already have. Anything that touches the real world waits for your yes.

Merge commit from fork

Eduardo Machado5a77a5fee363
diff --git a/src/core/apps.ts b/src/core/apps.ts
index 04cb4d6..e899448 100644
--- a/src/core/apps.ts
+++ b/src/core/apps.ts
@@ -298,6 +298,10 @@ export function pick(target: string, items: Item[]): Item | { error: string } {
}
}
+// Tucano itself (or Electron, while developing) is never an app an agent drives: it could
+// click its own approval.
+export const isTucano = (a: { name: string; bundleId?: string }): boolean => /^(tucano|tucano dev|electron)(\.exe)?$/i.test(a.name.trim()) || /^dev\.tucano\./i.test(a.bundleId ?? '') || /^com\.github\.electron/i.test(a.bundleId ?? '')
+
// The app the agent named, among those it was given (by name, ignoring case and accents).
export function grantOf(agent: Pick<Agent, 'apps'>, app: string): AgentApp | undefined {
const want = norm(app)
@@ -308,7 +312,8 @@ export function grantOf(agent: Pick<Agent, 'apps'>, app: string): AgentApp | und
// A key that can send (Return in a chat, ⌘↩ in Mail) or delete in bulk (⌘⌫) asks first.
// Desktop apps name the act of scheduling by what it makes ("Novo Evento"), not by a verb.
const CREATES = /\b(nov[oa]|criar|crie|new|create)\s+(evento|event|reuniao|meeting|compromisso|appointment)\b/
-export const riskyClick = (name: string): boolean => risky(name) || CREATES.test(norm(name))
+// One with no name can't be judged by it, so it asks too.
+export const riskyClick = (name: string): boolean => !norm(name).trim() || risky(name) || CREATES.test(norm(name))
// A shortcut as the system takes it: off a Mac, ⌘ is Ctrl (agent-desktop reads "cmd" as the
// Windows or Super key) and ⌥ is Alt.
@@ -317,9 +322,16 @@ export const keyFor = (combo: string, platform: NodeJS.Platform = process.platfo
return platform === 'darwin' ? c : c.replace(/\b(cmd|command|meta)\+/g, 'ctrl+').replace(/\boption\+/g, 'alt+')
}
+// The modifiers count in any order: shift+cmd+d is cmd+shift+d.
export const riskyKey = (combo: string): boolean => {
- const c = combo.replace(/\s+/g, '').toLowerCase()
- return /^(return|enter)$/.test(c) || /(cmd|command|ctrl|control)\+.*(return|enter|shift\+d)$/.test(c) || /(cmd|command|ctrl|control|alt|option)\+.*(backspace|delete)$/.test(c)
+ const parts = combo.replace(/\s+/g, '').toLowerCase().split('+')
+ const key = parts.pop() ?? ''
+ const mods = new Set(parts.map((m) => ({ command: 'cmd', meta: 'cmd', control: 'ctrl', option: 'alt' })[m] ?? m))
+ const cmd = mods.has('cmd') || mods.has('ctrl')
+ if (key === 'return' || key === 'enter') return mods.size === 0 || cmd
+ if (key === 'd') return cmd && mods.has('shift')
+ if (key === 'backspace' || key === 'delete') return cmd || mods.has('alt')
+ return false
}
// ---------- the tools ----------
@@ -550,11 +562,11 @@ export class DesktopApps {
// On a Mac the system answers at once (lsappinfo); agent-desktop's inventory can take seconds.
async foreground(): Promise<{ name: string; bundleId?: string }[]> {
if (this.platform === 'darwin') {
- const mac = await macOpenApps().catch(() => [])
+ const mac = (await macOpenApps().catch(() => [])).filter((a) => !isTucano(a))
if (mac.length) return mac
}
const all = await this.installed().catch(() => [])
- const mine = (n: string): boolean => /^(tucano|electron)(\.exe)?$/i.test(n)
+ const mine = (n: string): boolean => isTucano({ name: n })
const once = (list: { name: string; bundleId?: string }[]): { name: string; bundleId?: string }[] => list.filter((a, i) => a.name && !mine(a.name) && list.findIndex((b) => b.name === a.name) === i)
// Windows: the system's own list of windows answers at once; each by the name in the Start menu.
if (this.platform === 'win32') {
@@ -634,6 +646,10 @@ export class DesktopApps {
}
}
const app = grant.name
+ if (isTucano({ name: app }))
+ return {
+ result: textResult(L('O Tucano não pode ser usado como app por um agente.', "Tucano can't be used as an app by an agent."), true)
+ }
if (WRITE.has(name) && grant.level !== 'read_write')
return {
result: textResult(L(`Você só pode ler o ${app}.`, `You may only read ${app}.`), true)
@@ -804,15 +820,9 @@ export class DesktopApps {
// Spends a permit for this action, if there is one.
private permitted(agentId: string, app: string, args: Record<string, unknown>): boolean {
const list = (this.permits.get(agentId) ?? []).filter((p) => p.until > Date.now())
- // The same action under a slightly different name ("Apagar" in one menu, "Apagar Nota" in another) counts.
+ // Only the exact element that was approved: approving "Apagar" never lets "Apagar Tudo" through.
const key = permitKey(app, args)
- const same = (k: string): boolean => {
- if (k === key) return true
- const [a, x] = k.split('|') as [string, string]
- const [b, y] = key.split('|') as [string, string]
- return a === b && !x.startsWith('key:') && !y.startsWith('key:') && x.length > 2 && y.length > 2 && (x.startsWith(y) || y.startsWith(x))
- }
- const i = list.findIndex((p) => same(p.key))
+ const i = list.findIndex((p) => p.key === key)
if (i < 0) return false
list.splice(i, 1)
this.permits.set(agentId, list)
diff --git a/src/core/chrome.ts b/src/core/chrome.ts
index 9e70018..8b63ae6 100644
--- a/src/core/chrome.ts
+++ b/src/core/chrome.ts
@@ -6,7 +6,8 @@
// protocol; the page scripts are the same as in the Electron fallback. The
// screen streams to the app while it changes, so the panel is a live view.
import { spawn, type ChildProcess } from 'node:child_process'
-import { existsSync, mkdirSync, readFileSync, readlinkSync, rmSync } from 'node:fs'
+import type { Readable, Writable } from 'node:stream'
+import { existsSync, mkdirSync, readlinkSync, rmSync } from 'node:fs'
import { join } from 'node:path'
import { L } from '../shared/lang'
import { chromeKeyringFlags, findChrome, userAgentPlatform } from './platform'
@@ -61,9 +62,11 @@ type Pending = { resolve: (v: Record<string, unknown>) => void; reject: (e: Erro
// A new frame of the screen; says whether the app wants frames at full speed now.
export type OnFrame = (agentId: string, jpeg: string) => boolean
-// One Chrome process and its DevTools connection, following one tab.
+// One Chrome process and its DevTools connection, following one tab. The connection is a
+// pipe to that process (--remote-debugging-pipe): no port another program on the computer
+// (a command an agent runs) could find and drive this profile through.
class Tab {
- private ws!: WebSocket
+ private closed = false
private n = 0
private pending = new Map<number, Pending>()
session = '' // the tab we drive
@@ -79,18 +82,28 @@ class Tab {
private onFrame?: (jpeg: string) => boolean
) {}
- async connect(port: string): Promise<void> {
- const { webSocketDebuggerUrl } = (await (await fetch(`http://127.0.0.1:${port}/json/version`)).json()) as { webSocketDebuggerUrl: string }
- this.ws = new WebSocket(webSocketDebuggerUrl)
- await new Promise<void>((resolve, reject) => {
- this.ws.addEventListener('open', () => resolve(), { once: true })
- this.ws.addEventListener('error', () => reject(new Error(L('o Chrome não aceitou a conexão', "Chrome didn't accept the connection"))), { once: true })
+ // Chrome reads commands on its fd 3 and writes on fd 4, each message ending in a NUL.
+ private get input(): Writable {
+ return this.proc.stdio[3] as Writable
+ }
+
+ async connect(): Promise<void> {
+ const output = this.proc.stdio[4] as Readable
+ let buffered = ''
+ output.setEncoding('utf8')
+ output.on('data', (chunk: string) => {
+ const parts = (buffered + chunk).split('\0')
+ buffered = parts.pop() ?? ''
+ for (const m of parts) if (m) this.onMessage(JSON.parse(m) as Record<string, unknown>)
})
- this.ws.addEventListener('message', (e) => this.onMessage(JSON.parse(String(e.data)) as Record<string, unknown>))
- this.ws.addEventListener('close', () => {
+ const gone = (): void => {
+ this.closed = true
for (const p of this.pending.values()) p.reject(new Error(L('o Chrome fechou', 'Chrome closed')))
this.pending.clear()
- })
+ }
+ output.on('close', gone)
+ output.on('error', gone)
+ this.input.on('error', gone)
await this.send('Target.setDiscoverTargets', { discover: true })
const { targetInfos } = (await this.send('Target.getTargets')) as { targetInfos: { targetId: string; type: string; url: string }[] }
const page = targetInfos.find((t) => t.type === 'page')
@@ -100,8 +113,9 @@ class Tab {
send(method: string, params: Record<string, unknown> = {}, session = ''): Promise<Record<string, unknown>> {
return new Promise((resolve, reject) => {
const id = ++this.n
+ if (this.closed) return reject(new Error(L('o Chrome fechou', 'Chrome closed')))
this.pending.set(id, { resolve, reject })
- this.ws.send(JSON.stringify({ id, method, params, ...(session ? { sessionId: session } : {}) }))
+ this.input.write(JSON.stringify({ id, method, params, ...(session ? { sessionId: session } : {}) }) + '\0')
setTimeout(() => this.pending.get(id) && (this.pending.delete(id), reject(new Error(L(`o Chrome não respondeu (${method})`, `Chrome didn't answer (${method})`)))), 30_000).unref()
})
}
@@ -191,8 +205,9 @@ class Tab {
}
close(): void {
+ this.closed = true
try {
- this.ws.close()
+ this.input.end()
} catch {}
}
}
@@ -234,10 +249,9 @@ export class ChromeBrowsers {
for (let i = 0; i < 50 && alive(pid); i++) await wait(200)
}
} catch {}
- rmSync(join(profile, 'DevToolsActivePort'), { force: true })
const args = [
`--user-data-dir=${profile}`,
- '--remote-debugging-port=0',
+ '--remote-debugging-pipe',
'--disable-blink-features=AutomationControlled', // navigator.webdriver stays false, as in any Chrome
'--no-first-run',
'--no-default-browser-check',
@@ -248,22 +262,22 @@ export class ChromeBrowsers {
...(headed ? ['--new-window'] : ['--headless=new', '--mute-audio']),
url && /^https?:/.test(url) ? url : 'about:blank'
]
- const proc = spawn(this.bin, args, { stdio: 'ignore' })
- let port = ''
- for (let i = 0; i < 75 && !port; i++) {
- await wait(200)
- if (proc.exitCode !== null) throw new Error(L('o Chrome fechou logo ao abrir', 'Chrome closed right after opening'))
- try {
- port = readFileSync(join(profile, 'DevToolsActivePort'), 'utf8').split('\n')[0] ?? ''
- } catch {}
- }
- if (!port) {
- proc.kill()
- throw new Error(L('o Chrome não abriu em 15 s', "Chrome didn't open in 15 s"))
- }
+ const proc = spawn(this.bin, args, { stdio: ['ignore', 'ignore', 'ignore', 'pipe', 'pipe'] })
const onFrame = this.onFrame
const tab = new Tab(proc, headed, onFrame && ((jpeg) => onFrame(agentId, jpeg)))
- await tab.connect(port)
+ let timer: ReturnType<typeof setTimeout> | undefined
+ const failed = new Promise<never>((_, reject) => {
+ proc.once('exit', () => reject(new Error(L('o Chrome fechou logo ao abrir', 'Chrome closed right after opening'))))
+ timer = setTimeout(() => reject(new Error(L('o Chrome não abriu em 15 s', "Chrome didn't open in 15 s"))), 15_000)
+ })
+ try {
+ await Promise.race([tab.connect(), failed])
+ } catch (e) {
+ proc.kill()
+ throw e
+ } finally {
+ clearTimeout(timer)
+ }
proc.once('exit', () => {
if (this.tabs.get(agentId) !== tab) return
this.tabs.delete(agentId)
diff --git a/src/core/engines/claude.ts b/src/core/engines/claude.ts
index be1df66..e44f1ed 100644
--- a/src/core/engines/claude.ts
+++ b/src/core/engines/claude.ts
@@ -34,10 +34,14 @@ export function userProvider(dir = process.env['CLAUDE_CONFIG_DIR'] || join(home
// --bare: it turns off the subscription login. The app's gateway, when given,
// is the only MCP server, and its tools are pre-allowed: the gateway decides.
// With web, the only built-in tools are web search and page reading.
+export const GATEWAY_ENV = 'TUCANO_MCP_URL'
+
export function claudeArgs(turn: Pick<Turn, 'model' | 'effort' | 'system' | 'mcpUrl' | 'web' | 'blocks' | 'images' | 'session'>, apiKeyHelper?: string): string[] {
const web = turn.web ? WEB_TOOLS : []
const allowed = [...(turn.mcpUrl ? [`mcp__${GATEWAY_NAME}`] : []), ...web]
- const gateway = turn.mcpUrl ? ['--mcp-config', JSON.stringify({ mcpServers: { [GATEWAY_NAME]: { type: 'http', url: turn.mcpUrl } } })] : []
+ // The address carries the gateway's token: the CLI fills it in from the environment, so it
+ // never shows in the arguments, which any program on the computer can list.
+ const gateway = turn.mcpUrl ? ['--mcp-config', JSON.stringify({ mcpServers: { [GATEWAY_NAME]: { type: 'http', url: `\${${GATEWAY_ENV}}` } } })] : []
return [
'-p',
...(turn.session || turn.blocks?.some((b) => b.trim()) || turn.images?.length ? ['--input-format', 'stream-json'] : []),
@@ -174,8 +178,9 @@ export function claudeParser(): Parser {
// Without CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC the CLI makes one more model call after the
// reply (its post-turn summary) and only then sends `result`: about 2.5 s on every reply, at
// times over 10 s. Nobody reads that summary here.
-export function claudeEnv(p: Provider, account?: string): NodeJS.ProcessEnv {
- return { ...process.env, CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1', ...p.env, ...(account ? { CLAUDE_CONFIG_DIR: account } : {}), MCP_TOOL_TIMEOUT: '900000' }
+// The gateway's address goes in the environment, not the arguments (see claudeArgs).
+export function claudeEnv(p: Provider, account?: string, mcpUrl?: string): NodeJS.ProcessEnv {
+ return { ...process.env, CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1', ...p.env, ...(account ? { CLAUDE_CONFIG_DIR: account } : {}), ...(mcpUrl ? { [GATEWAY_ENV]: mcpUrl } : {}), MCP_TOOL_TIMEOUT: '900000' }
}
// Where Claude Code keeps a session: its config folder, then the working folder with every
@@ -240,7 +245,7 @@ export function claudeEngine(bin: () => string | undefined, provider: () => Prom
trim()
}
// The same flags and provider as an open process: then it can take this turn.
- const keyOf = (path: string, t: TurnShape, args: string[], p: Provider): string => JSON.stringify([path, t.cwd, args, p.env, t.account ?? ''])
+ const keyOf = (path: string, t: TurnShape, args: string[], p: Provider): string => JSON.stringify([path, t.cwd, args, p.env, t.account ?? '', t.mcpUrl ?? ''])
const keptKey = (path: string, t: TurnShape, id: string, p: Provider): string => keyOf(path, t, claudeArgs({ ...t, session: { id, resume: true } }, p.apiKeyHelper), p)
const dropSpare = (key: string): void => {
const s = spares.get(key)
@@ -261,7 +266,7 @@ export function claudeEngine(bin: () => string | undefined, provider: () => Prom
}
// The gateway's token goes in the environment, never in the arguments (other processes can read those).
const p = await provider()
- const env = claudeEnv(p, turn.account)
+ const env = claudeEnv(p, turn.account, turn.mcpUrl)
const session = turn.session
if (!session) {
// A process started for it ahead of time takes the turn, then goes.
@@ -325,7 +330,7 @@ export function claudeEngine(bin: () => string | undefined, provider: () => Prom
return
}
if (had) dropSpare(key)
- const cli = new LiveCli({ bin: path, args, cwd: turn.cwd, env: claudeEnv(p, turn.account) })
+ const cli = new LiveCli({ bin: path, args, cwd: turn.cwd, env: claudeEnv(p, turn.account, turn.mcpUrl) })
const spare = { cli, at: Date.now(), timer: setTimeout(() => spares.get(key)?.cli === cli && dropSpare(key), SPARE_MS) }
spare.timer.unref()
spares.set(key, spare)
@@ -344,7 +349,7 @@ export function claudeEngine(bin: () => string | undefined, provider: () => Prom
if (!path || !shape) return
void provider().then((p) => {
if (kept.has(id) || !shapes.has(id)) return // a turn or a release got there first
- const k: Kept = { cli: new LiveCli({ bin: path, args: claudeArgs({ ...shape, session: { id, resume: true } }, p.apiKeyHelper), cwd: shape.cwd, env: claudeEnv(p, shape.account) }), key: keptKey(path, shape, id, p), usedAt: Date.now() }
+ const k: Kept = { cli: new LiveCli({ bin: path, args: claudeArgs({ ...shape, session: { id, resume: true } }, p.apiKeyHelper), cwd: shape.cwd, env: claudeEnv(p, shape.account, shape.mcpUrl) }), key: keptKey(path, shape, id, p), usedAt: Date.now() }
kept.set(id, k)
park(id, k)
})
diff --git a/src/main/index.ts b/src/main/index.ts
index 5b10752..bb06052 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1,12 +1,13 @@
import { randomBytes } from 'node:crypto'
import { verifyLocalUrl } from '../core/local-paths'
-import { app, BrowserWindow, session, type MediaAccessPermissionRequest, dialog, ipcMain, Menu, MessageChannelMain, nativeImage, nativeTheme, net, Notification, powerMonitor, powerSaveBlocker, protocol, safeStorage, shell, Tray, utilityProcess, type UtilityProcess } from 'electron'
+import { app, BrowserWindow, session, type MediaAccessPermissionRequest, dialog, ipcMain, type IpcMainEvent, type IpcMainInvokeEvent, Menu, MessageChannelMain, nativeImage, nativeTheme, net, Notification, powerMonitor, powerSaveBlocker, protocol, safeStorage, shell, Tray, utilityProcess, type UtilityProcess } from 'electron'
import { execFile } from 'node:child_process'
import { mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs'
import { dirname, join, normalize, sep } from 'node:path'
import { pathToFileURL } from 'node:url'
import { L, langOf, setLang, type Lang } from '../shared/lang'
import { chirpOf, type BrowserOp, type Settings } from '../shared/types'
+import { isAppPage, isOutsideLink } from '../shared/links'
import { Browsers } from './browser'
import { bundleOf, moveFromAgentDesk, type Moved } from './migrate'
import { Updates } from './updates'
@@ -131,10 +132,22 @@ type CoreRequest =
| { type: 'icons'; id: string; paths: string[] }
| { type: 'browser'; id: string; agentId: string; op: BrowserOp; args?: Record<string, unknown> }
+// The app's page: the dev server while developing, the built index.html otherwise.
+const APP_PAGE = process.env['ELECTRON_RENDERER_URL'] ?? pathToFileURL(join(import.meta.dirname, '../renderer/index.html')).toString()
+
+// Only the app's own page, in the app's window, talks to main: never a page that window
+// was somehow taken to, nor a frame inside it. Its bridge reaches the core.
+function fromApp(event: IpcMainEvent | IpcMainInvokeEvent): boolean {
+ const frame = event.senderFrame
+ const ok = !!frame && frame === event.sender.mainFrame && !!mainWindow && !mainWindow.isDestroyed() && event.sender === mainWindow.webContents && isAppPage(frame.url, APP_PAGE)
+ if (!ok) console.error('[main] ignored a message from', frame?.url ?? 'a closed frame')
+ return ok
+}
+
// The conversation open in the window, so a notification about it can stay quiet.
let viewing: string | null = null
-ipcMain.on('viewing', (_e, id: unknown) => {
- if (_e.sender !== mainWindow?.webContents || _e.senderFrame !== _e.sender.mainFrame) return
+ipcMain.on('viewing', (e, id: unknown) => {
+ if (!fromApp(e)) return
viewing = typeof id === 'string' ? id : null
cores.get(registry.selected().id)?.child.postMessage({ type: 'viewing', conversationId: viewing })
})
@@ -377,7 +390,7 @@ function serveArtifact(req: Request): Promise<Response> | Response {
// Each page load asks for a port; one end goes to the core, the other to the page.
ipcMain.on('core:connect', async (event) => {
- if (event.sender !== mainWindow?.webContents || event.senderFrame !== event.sender.mainFrame) return
+ if (!fromApp(event)) return
const workspace = registry.selected()
const runtime = startCore(workspace)
try { await runtime.ready } catch { return }
@@ -559,9 +572,10 @@ function showWindow(conversationId?: string, page?: 'skills', threadId?: string)
const updates = new Updates((state) => {
if (mainWindow && !mainWindow.isDestroyed()) mainWindow.webContents.send('update', state)
})
-ipcMain.handle('update:state', () => updates.get())
-ipcMain.on('update:check', () => updates.check())
-ipcMain.on('update:install', () => {
+ipcMain.handle('update:state', (e) => (fromApp(e) ? updates.get() : null))
+ipcMain.on('update:check', (e) => fromApp(e) && updates.check())
+ipcMain.on('update:install', (e) => {
+ if (!fromApp(e)) return
// A reply in progress would be cut off: the person decides.
if (awakeBlocker !== null && mainWindow && !mainWindow.isDestroyed()) {
const answer = dialog.showMessageBoxSync(mainWindow, {
@@ -579,6 +593,7 @@ ipcMain.on('update:install', () => {
// The Mac's folder picker, for a folder lent to an agent's computer. The core checks the choice.
ipcMain.handle('pick-folder', async (event) => {
+ if (!fromApp(event)) return null
const win = BrowserWindow.fromWebContents(event.sender)
const opts = { title: L('Escolher pasta', 'Choose a folder'), buttonLabel: L('Escolher', 'Choose'), properties: ['openDirectory' as const] }
const r = win ? await dialog.showOpenDialog(win, opts) : await dialog.showOpenDialog(opts)
@@ -619,21 +634,24 @@ function createWindow(): BrowserWindow {
stillOpen()
})
- // Links in messages open in the default browser, never inside the app.
+ // Links in messages open in the default browser or the mail app, never inside the app;
+ // any other scheme isn't handed to the system either.
win.webContents.setWindowOpenHandler(({ url }) => {
- void shell.openExternal(url)
+ if (isOutsideLink(url)) void shell.openExternal(url)
return { action: 'deny' }
})
- // react-markdown renders message links as plain <a href>, and a plain click
- // navigates this whole window away (the app "disappears" behind the site).
- // Same promise as above, for those: web links go to the real browser;
- // a same-URL navigation (reload) is not a link and stays.
- win.webContents.on('will-navigate', (event, url) => {
- if (!/^https?:\/\//.test(url) || url === win.webContents.getURL()) return
+ // react-markdown renders message links as plain <a href>, and a plain click navigates
+ // this whole window. The window only ever shows the app: a reload stays, web and mail
+ // links go to the system, and anything else (a local page, which would get the app's
+ // bridge to the core) goes nowhere.
+ const guard = (event: { preventDefault: () => void }, url: string): void => {
+ if (isAppPage(url, APP_PAGE)) return
event.preventDefault()
- void shell.openExternal(url)
- })
+ if (isOutsideLink(url)) void shell.openExternal(url)
+ }
+ win.webContents.on('will-navigate', guard)
+ win.webContents.on('will-redirect', guard)
if (process.env['ELECTRON_RENDERER_URL']) {
void win.loadURL(process.env['ELECTRON_RENDERER_URL'])
diff --git a/src/renderer/src/components/Conversation.tsx b/src/renderer/src/components/Conversation.tsx
index 8af1255..4ad3c0b 100644
--- a/src/renderer/src/components/Conversation.tsx
+++ b/src/renderer/src/components/Conversation.tsx
@@ -1,7 +1,8 @@
import { L, lang, locale } from '../../../shared/lang'
import { memo, useEffect, useLayoutEffect, useMemo, useRef, useState, type ComponentProps, type ReactNode } from 'react'
-import Markdown, { defaultUrlTransform, type ExtraProps } from 'react-markdown'
-import { LOCAL_LINK, remarkLocalPaths } from '../../../shared/path-text'
+import Markdown, { type ExtraProps } from 'react-markdown'
+import { safeUrl } from '../links'
+import { remarkLocalPaths } from '../../../shared/path-text'
import { remarkMentions, splitMentions } from '../../../shared/mention-text'
import { localLinkFor } from './LocalLink'
import remarkGfm from 'remark-gfm'
@@ -315,7 +316,6 @@ export function MessageList({ messages: all, conversationId, empty, focus, threa
const AGENT_PLUGINS = [remarkGfm, remarkMentions, remarkLocalPaths]
const PLAIN_PLUGINS = [remarkGfm, remarkMentions]
-const keepLocalLinks = (url: string): string => (url.startsWith(LOCAL_LINK) ? url : defaultUrlTransform(url))
// Parsing is by far the most expensive part of drawing a message, so it only runs when the text changes.
const MessageMarkdown = memo(Markdown)
@@ -380,9 +380,9 @@ const MessageRow = memo(function MessageRow({ message, grouped, replies }: { mes
{message.text ? (
<div className="md">
{agent && message.run?.status !== 'working' ? (
- <MessageMarkdown remarkPlugins={AGENT_PLUGINS} urlTransform={keepLocalLinks} components={agentMarkdown}>{wikiLinks(message.text)}</MessageMarkdown>
+ <MessageMarkdown urlTransform={safeUrl} remarkPlugins={AGENT_PLUGINS} components={agentMarkdown}>{wikiLinks(message.text)}</MessageMarkdown>
) : (
- <MessageMarkdown remarkPlugins={PLAIN_PLUGINS} components={plainMarkdown}>{wikiLinks(message.text)}</MessageMarkdown>
+ <MessageMarkdown urlTransform={safeUrl} remarkPlugins={PLAIN_PLUGINS} components={plainMarkdown}>{wikiLinks(message.text)}</MessageMarkdown>
)}
</div>
) : null}
@@ -480,7 +480,7 @@ function RoutineMessage({ message, replies }: { message: Message; replies?: Mess
</div>
)}
<div className="md">
- <MessageMarkdown remarkPlugins={PLAIN_PLUGINS} components={plainMarkdown}>{wikiLinks(message.text)}</MessageMarkdown>
+ <MessageMarkdown urlTransform={safeUrl} remarkPlugins={PLAIN_PLUGINS} components={plainMarkdown}>{wikiLinks(message.text)}</MessageMarkdown>
</div>
{replies && <ThreadLink message={message} replies={replies} />}
</div>
@@ -494,7 +494,7 @@ function SystemText({ text }: { text: string }): ReactNode {
const [head = '', ...why] = text.split(' · ')
return (
<>
- <Markdown>{head}</Markdown>
+ <Markdown urlTransform={safeUrl}>{head}</Markdown>
{why.length > 0 && (
<span className="system-line__why" title={why.join(' · ').replace(/\*\*/g, '')}>
{why.join(' · ').replace(/\*\*/g, '')}
diff --git a/src/renderer/src/components/Panel.tsx b/src/renderer/src/components/Panel.tsx
index 552c9cd..30f5708 100644
--- a/src/renderer/src/components/Panel.tsx
+++ b/src/renderer/src/components/Panel.tsx
@@ -3,6 +3,7 @@
import { L, locale } from '../../../shared/lang'
import { useEffect, useState, type ReactNode } from 'react'
import Markdown from 'react-markdown'
+import { safeUrl } from '../links'
import remarkGfm from 'remark-gfm'
import { agentById, getState, openLightbox, artifactUrl, browserAction, browserInput, browserOf, reachable, windowless, computerOf, openExternal, openPanel, stopService, useStore, type Artifact } from '../store'
import { call } from '../rpc'
@@ -441,7 +442,7 @@ function ArtifactView({ artifact }: { artifact: Artifact }): ReactNode {
case 'pdf':
return <iframe src={url} title={artifact.title} />
case 'markdown':
- return <div className="side-panel__doc md">{text !== null && <Markdown remarkPlugins={[remarkGfm]}>{text}</Markdown>}</div>
+ return <div className="side-panel__doc md">{text !== null && <Markdown urlTransform={safeUrl} remarkPlugins={[remarkGfm]}>{text}</Markdown>}</div>
case 'csv':
return <div className="side-panel__doc">{text !== null && <CsvTable text={text} tab={artifact.name.endsWith('.tsv')} />}</div>
case 'text':
diff --git a/src/renderer/src/components/Skills.tsx b/src/renderer/src/components/Skills.tsx
index 8582fb7..ae988e1 100644
--- a/src/renderer/src/components/Skills.tsx
+++ b/src/renderer/src/components/Skills.tsx
@@ -3,6 +3,7 @@
import { L } from '../../../shared/lang'
import { useEffect, useRef, useState, type ReactNode } from 'react'
import Markdown from 'react-markdown'
+import { safeUrl } from '../links'
import remarkGfm from 'remark-gfm'
import {
agentById,
@@ -231,7 +232,7 @@ function SkillPage({ skill: k, stat, onBack, onEdit }: { skill: Skill; stat?: Sk
<h2>{L('Receita', 'Recipe')}</h2>
{k.body.trim() ? (
<article className="recipe">
- <Markdown remarkPlugins={[remarkGfm]}>{k.body}</Markdown>
+ <Markdown urlTransform={safeUrl} remarkPlugins={[remarkGfm]}>{k.body}</Markdown>
</article>
) : (
<p className="read-empty">{L(`A receita é lida de ${k.source} a cada uso.`, `The recipe is read from ${k.source} on every use.`)}</p>
@@ -441,7 +442,7 @@ function Proposal({ proposal: p }: { proposal: Skill }): ReactNode {
<span>{L('Quando usar:', 'When to use:')}</span> {p.description}
</p>
<article className="recipe recipe--box">
- <Markdown remarkPlugins={[remarkGfm]}>{p.body}</Markdown>
+ <Markdown urlTransform={safeUrl} remarkPlugins={[remarkGfm]}>{p.body}</Markdown>
</article>
<p className="proposal__who">
{L('Vale pra', 'For')} <Who ids={p.agents} />. {L('Depois de aprovar, dá pra liberar pra outros agentes.', 'After approving, you can open it to other agents.')}
diff --git a/src/renderer/src/components/Wiki.tsx b/src/renderer/src/components/Wiki.tsx
index 2f2ef8b..5ca9f86 100644
--- a/src/renderer/src/components/Wiki.tsx
+++ b/src/renderer/src/components/Wiki.tsx
@@ -7,6 +7,7 @@ import { L, locale } from '../../../shared/lang'
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import { createPortal } from 'react-dom'
import Markdown from 'react-markdown'
+import { safeUrl } from '../links'
import remarkGfm from 'remark-gfm'
import { call } from '../rpc'
import { agentById, navigate, setTab, updateSettings, useStore, type View, type WikiChange, type WikiFinding, type WikiHit, type WikiImport, type WikiPage, type WikiPageInfo, type WikiReview, type WikiSource, type WikiVersion } from '../store'
@@ -920,7 +921,7 @@ function WikiSearch({ pages, onClose }: { pages: WikiPageInfo[]; onClose: () =>
<b>{r.title}</b>
{r.snippet && (
<small>
- <Markdown allowedElements={['p', 'strong', 'em']} unwrapDisallowed>
+ <Markdown urlTransform={safeUrl} allowedElements={['p', 'strong', 'em']} unwrapDisallowed>
{r.snippet}
</Markdown>
</small>
@@ -1077,7 +1078,7 @@ function WikiSettingsDialog({ data, onClose, onImport }: { data: WikiData | null
// One change, as the curator wrote it: what goes where.
function OpView({ op }: { op: WikiChange['ops'][number] }): ReactNode {
const md = (t?: string): ReactNode => (
- <Markdown remarkPlugins={[remarkGfm]} components={mdLinks()}>
+ <Markdown urlTransform={safeUrl} remarkPlugins={[remarkGfm]} components={mdLinks()}>
{wikiLinks(t ?? '')}
</Markdown>
)
@@ -1229,7 +1230,7 @@ function WikiReviewPane(): ReactNode {
if (!r) return null
const sorted = [...r.findings].sort((a, b) => FINDING_ORDER.indexOf(a.kind) - FINDING_ORDER.indexOf(b.kind))
const md = (t: string): ReactNode => (
- <Markdown components={{ ...mdLinks(), p: (p) => <span>{p.children}</span> }}>{wikiLinks(t)}</Markdown>
+ <Markdown urlTransform={safeUrl} components={{ ...mdLinks(), p: (p) => <span>{p.children}</span> }}>{wikiLinks(t)}</Markdown>
)
return (
<div className="wk-pane">
@@ -1525,7 +1526,7 @@ function WikiSourceView({ id }: { id: string }): ReactNode {
</div>
{src.error && <p className="field__error">{src.error}</p>}
<article className="wk-doc md wk-doc--source">
- <Markdown remarkPlugins={[remarkGfm]}>{src.text.trimStart().replace(/^# .*\n+/, '')}</Markdown>
+ <Markdown urlTransform={safeUrl} remarkPlugins={[remarkGfm]}>{src.text.trimStart().replace(/^# .*\n+/, '')}</Markdown>
</article>
</div>
)
@@ -1654,7 +1655,7 @@ function WikiPageView({ title, data }: { title: string; data: WikiData | null })
</div>
<h1 className="wk-page__title">{page.title}</h1>
<div className="wk-doc md">
- <Markdown remarkPlugins={[remarkGfm]} components={mdLinks(missing)}>
+ <Markdown urlTransform={safeUrl} remarkPlugins={[remarkGfm]} components={mdLinks(missing)}>
{wikiLinks(page.body)}
</Markdown>
</div>
@@ -1803,7 +1804,7 @@ function WikiEditor({ title }: { title?: string }): ReactNode {
<textarea className="wiki-editor__text" value={body} onChange={(e) => setBody(e.target.value)} spellCheck placeholder={L('Comece com uma frase que diga o que é. Depois, seções com ##.', 'Start with one sentence that says what it is. Then sections with ##.')} />
<div className="wiki-editor__preview wk-doc md">
{body.trim() ? (
- <Markdown remarkPlugins={[remarkGfm]} components={mdLinks()}>
+ <Markdown urlTransform={safeUrl} remarkPlugins={[remarkGfm]} components={mdLinks()}>
{wikiLinks(body)}
</Markdown>
) : (
diff --git a/src/renderer/src/links.ts b/src/renderer/src/links.ts
new file mode 100644
index 0000000..e1f76ff
--- /dev/null
+++ b/src/renderer/src/links.ts
@@ -0,0 +1,12 @@
+import { defaultUrlTransform } from 'react-markdown'
+import { isOutsideLink } from '../../shared/links'
+import { LOCAL_LINK } from '../../shared/path-text'
+
+// What a link in markdown (a message, the wiki, a skill, a document) may point to: the web,
+// an email, a place in the app (#wiki/…) or a file the core resolves (tucano-local:). A bare
+// path would load as the app (file://), so it stays plain text. Images keep the default.
+export function safeUrl(url: string, key: string): string | undefined {
+ if (key !== 'href') return defaultUrlTransform(url)
+ if (url.startsWith('#') || url.startsWith(LOCAL_LINK) || isOutsideLink(url)) return url
+ return undefined
+}
diff --git a/src/shared/links.ts b/src/shared/links.ts
new file mode 100644
index 0000000..8204324
--- /dev/null
+++ b/src/shared/links.ts
@@ -0,0 +1,19 @@
+// Where a link may take the person. The app's window only ever shows the app: a link
+// opens in the real browser or the mail app, and anything else (a bare path, file:,
+// javascript:, the app's own tucano: pages) goes nowhere. A local page loaded as the
+// app would get the app's bridge to the core.
+
+export const isOutsideLink = (url: string): boolean => /^(https?:\/\/|mailto:)/i.test(url)
+
+// The app's own page, again (a reload, or the same page with another #hash). appPage is
+// the dev server's URL while developing, the built index.html's file: URL otherwise.
+export function isAppPage(url: string, appPage: string): boolean {
+ try {
+ const u = new URL(url)
+ const app = new URL(appPage)
+ if (u.protocol === 'file:' || app.protocol === 'file:') return u.protocol === app.protocol && u.pathname === app.pathname && u.host === app.host
+ return u.origin === app.origin
+ } catch {
+ return false
+ }
+}
diff --git a/test/apps.test.ts b/test/apps.test.ts
index 9e8b401..da49eab 100644
--- a/test/apps.test.ts
+++ b/test/apps.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { setLang } from '../src/shared/lang'
-import { appStep, appTools, DesktopApps, grantOf, itemize, keyFor, parseLsappinfo, pick, riskyClick, riskyKey, run, typeKeys, type Cli, type Envelope } from '../src/core/apps'
+import { appStep, appTools, DesktopApps, grantOf, isTucano, itemize, keyFor, parseLsappinfo, pick, riskyClick, riskyKey, run, typeKeys, type Cli, type Envelope } from '../src/core/apps'
import type { Agent } from '../src/shared/types'
// A Notes window as agent-desktop describes it.
@@ -139,6 +139,15 @@ describe('what an agent may do with an app', () => {
expect(calls.filter((c) => c[0] === 'click')).toHaveLength(0)
expect((await apps.call(nina, 'app_tecla', { app: 'Notas', tecla: 'return' })).approval).toBeDefined()
expect(riskyKey('cmd+shift+d')).toBe(true)
+ expect(riskyKey('shift+cmd+d')).toBe(true)
+ expect(riskyKey('Shift + Command + D')).toBe(true)
+ expect(riskyKey('return')).toBe(true)
+ expect(riskyKey('shift+return')).toBe(false)
+ expect(riskyKey('shift+ctrl+enter')).toBe(true)
+ expect(riskyKey('option+delete')).toBe(true)
+ expect(riskyKey('cmd+d')).toBe(false)
+ expect(riskyClick('')).toBe(true)
+ expect(riskyClick(' ')).toBe(true)
expect(riskyKey('cmd+n')).toBe(false)
expect(riskyKey('cmd+backspace')).toBe(true)
expect(riskyKey('alt + delete')).toBe(true)
@@ -155,18 +164,28 @@ describe('what an agent may do with an app', () => {
const again = await apps.call(nina, 'app_clicar', { app: 'Notas', alvo: 'Apagar' })
expect(again.approval).toBeUndefined()
expect(calls.filter((c) => c[0] === 'click').at(-1)?.[1]).toMatch(/^@s\d+:e2$/)
- // The same action under a longer name counts too, once.
- apps.approved(nina, { app: 'Notas', alvo: 'Apagar Nota' })
- await apps.call(nina, 'app_ver', { app: 'Notas' })
- expect((await apps.call(nina, 'app_clicar', { app: 'Notas', alvo: 'Apagar' })).approval).toBeUndefined()
// Once: the next one asks again.
await apps.call(nina, 'app_ver', { app: 'Notas' })
expect((await apps.call(nina, 'app_clicar', { app: 'Notas', alvo: 'Apagar' })).approval).toBeDefined()
+ // Only the exact element: a longer or shorter name ("Apagar Nota", "Apagar Tudo") asks again.
+ apps.approved(nina, { app: 'Notas', alvo: 'Apagar Nota' })
+ await apps.call(nina, 'app_ver', { app: 'Notas' })
+ expect((await apps.call(nina, 'app_clicar', { app: 'Notas', alvo: 'Apagar' })).approval).toBeDefined()
expect(apps.approved(agent([{ name: 'Notas', level: 'read' }]), del.approval!.args).ok).toBe(false)
})
})
+describe('Tucano itself', () => {
+ it('is never an app an agent drives, which could click its own approval', () => {
+ expect(isTucano({ name: 'Tucano' })).toBe(true)
+ expect(isTucano({ name: 'Tucano.exe' })).toBe(true)
+ expect(isTucano({ name: 'Electron' })).toBe(true)
+ expect(isTucano({ name: 'Algo', bundleId: 'dev.tucano.app' })).toBe(true)
+ expect(isTucano({ name: 'Notas', bundleId: 'com.apple.Notes' })).toBe(false)
+ })
+})
+
describe('the open apps on a Mac', () => {
it('reads lsappinfo: only the apps with windows, by their shown name', () => {
const out = `2) "Finder" ASN:0x0-0x1001:
diff --git a/test/engines.test.ts b/test/engines.test.ts
index 4034379..a22bbf1 100644
--- a/test/engines.test.ts
+++ b/test/engines.test.ts
@@ -66,7 +66,9 @@ describe('Claude Code stream', () => {
it('gets the gateway as its only MCP server, with its tools pre-allowed', () => {
const args = claudeArgs({ model: 'sonnet', effort: 'low', system: 'x', mcpUrl: 'http://127.0.0.1:1/mcp/abc' })
- expect(JSON.parse(args[args.indexOf('--mcp-config') + 1]!)).toEqual({ mcpServers: { tucano: { type: 'http', url: 'http://127.0.0.1:1/mcp/abc' } } })
+ // The address (and its token) comes from the environment: never in the arguments, which other programs can list.
+ expect(JSON.parse(args[args.indexOf('--mcp-config') + 1]!)).toEqual({ mcpServers: { tucano: { type: 'http', url: '${TUCANO_MCP_URL}' } } })
+ expect(args.join(' ')).not.toContain('/mcp/abc')
expect(args[args.indexOf('--allowedTools') + 1]).toBe('mcp__tucano')
expect(args).toContain('--strict-mcp-config')
expect(claudeArgs({ model: 'sonnet', effort: 'low', system: 'x' })).not.toContain('--mcp-config')
diff --git a/test/links.test.ts b/test/links.test.ts
new file mode 100644
index 0000000..5e23f75
--- /dev/null
+++ b/test/links.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it } from 'vitest'
+import { isAppPage, isOutsideLink } from '../src/shared/links'
+import { LOCAL_LINK } from '../src/shared/path-text'
+import { safeUrl } from '../src/renderer/src/links'
+
+const BUILT = 'file:///Applications/Tucano.app/Contents/Resources/app.asar/out/renderer/index.html'
+const DEV = 'http://localhost:5173'
+
+describe('the app window only shows the app', () => {
+ it('lets the built page reload, with or without a #hash', () => {
+ expect(isAppPage(BUILT, BUILT)).toBe(true)
+ expect(isAppPage(`${BUILT}#/c/1`, BUILT)).toBe(true)
+ })
+
+ it('never takes a local page for the app, which would hand it the bridge to the core', () => {
+ expect(isAppPage('file:///Users/x/report.html', BUILT)).toBe(false)
+ expect(isAppPage('file:///Applications/Tucano.app/Contents/Resources/app.asar/out/renderer/other.html', BUILT)).toBe(false)
+ expect(isAppPage('file:///Users/x/report.html', DEV)).toBe(false)
+ expect(isAppPage('tucano://artifact/x/a.html', BUILT)).toBe(false)
+ })
+
+ it('takes the dev server for the app while developing, and nothing else', () => {
+ expect(isAppPage(`${DEV}/`, DEV)).toBe(true)
+ expect(isAppPage('http://localhost:5174/', DEV)).toBe(false)
+ expect(isAppPage('https://example.com/', DEV)).toBe(false)
+ })
+
+ it('says no to what is not a URL', () => {
+ expect(isAppPage('/Users/x/report.html', BUILT)).toBe(false)
+ })
+})
+
+describe('links handed to the system', () => {
+ it('are the web and mail only', () => {
+ expect(isOutsideLink('https://linear.app/x')).toBe(true)
+ expect(isOutsideLink('http://localhost:3000')).toBe(true)
+ expect(isOutsideLink('mailto:[email protected]')).toBe(true)
+ for (const url of ['file:///etc/passwd', 'javascript:alert(1)', 'smb://host/share', 'x-apple.systempreferences:', 'tucano://artifact/x', '/Users/x/report.html'])
+ expect(isOutsideLink(url)).toBe(false)
+ })
+})
+
+describe('links in markdown', () => {
+ it('keep the web, mail, places in the app and files the core resolves', () => {
+ for (const url of ['https://github.com', 'mailto:[email protected]', '#wiki/Clientes', '#att/a.png', `${LOCAL_LINK}%2Ftmp%2Fa.png`]) expect(safeUrl(url, 'href')).toBe(url)
+ })
+
+ it('drop a bare path, which would load a local page as the app', () => {
+ expect(safeUrl('/path/to/report.html', 'href')).toBeUndefined()
+ expect(safeUrl('report.html', 'href')).toBeUndefined()
+ expect(safeUrl('file:///path/to/report.html', 'href')).toBeUndefined()
+ expect(safeUrl('javascript:alert(1)', 'href')).toBeUndefined()
+ })
+
+ it('leave images as react-markdown does', () => {
+ expect(safeUrl('a.png', 'src')).toBe('a.png')
+ expect(safeUrl('javascript:alert(1)', 'src')).toBe('')
+ })
+})