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.
TypeScript agent-teamagentic-aiai-agentsai-assistantclaude-codecodexcursorelectrongrokgrok-bot-alternativelinuxlocal-firstmacosmcpmulti-agentopenclaw-alternativeopencodewindows
Make file paths in agents' messages clickable (#61)
Rayanne B. Lima2fda298aa941
diff --git a/src/core/index.ts b/src/core/index.tsindex a2e5ae2..b7d51ff 100644--- a/src/core/index.ts+++ b/src/core/index.ts@@ -5,6 +5,7 @@ import { createHash } from 'node:crypto'import { execFile, spawn } from 'node:child_process'import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'import { userInfo } from 'node:os'+import { isLimited, localUrl, resolveLocal, type LocalReach } from './local-paths'import { basename, join } from 'node:path'import { randomUUID } from 'node:crypto'import type { MessagePortMain } from 'electron'@@ -251,6 +252,7 @@ const notifyAll = (title: string, body: string, conversationId?: string): void =type ToMain =| { type: 'open'; url: string }| { type: 'open_path'; path: string }+ | { type: 'open_local'; path: string; how: 'open' | 'reveal' }| { type: 'wiki_dir'; path: string } // the wiki's folder, which the app may open| { type: 'notify'; title: string; body: string; conversationId?: string; kind?: 'approval' | 'question' | 'done'; sound?: boolean }| { type: 'login_item'; open: boolean }@@ -374,6 +376,21 @@ const chrome =: undefinedconst host: BrowserHost = chrome ? (agentId, op, args) => chrome.run(agentId, op, args) : electronHost+// Out of the environment before anything starts: commands the agents run inherit it.+const localKey = process.env['TUCANO_LOCAL_KEY']+delete process.env['TUCANO_LOCAL_KEY']++// What the author of a message reaches, for the paths it cites. An agent on this Mac reaches what+// its commands do; any other, only its own files. Not on a server, where the page isn't on this+// computer, and not on Windows yet, where paths don't look like this.+function localReach(messageId: string): LocalReach | undefined {+ const message = db.message(messageId)+ if (serverMode || isWin || message?.author.kind !== 'agent') return undefined+ const agent = db.agent(message.author.id)+ if (!agent) return undefined+ return { agentId: agent.id, own: computers.folder(agent.id), dataRoot: dataDir, limited: isLimited(agent) }+}+const secrets = new Secrets(db, fake ? plainCipher : mainCipher(process.parentPort))// The person's own apps, through agent-desktop (none on a server: no screen there).// Off a Mac it needs the installed apps to know each one's program.@@ -747,6 +764,18 @@ const api: Api = {},// Everything that only made sense there goes too: replies still running stop,// its routines, its pending approvals.+ localPath: ({ messageId, path }) => {+ const reach = localReach(messageId)+ const found = reach && resolveLocal(path, reach)+ if (!found) return null+ return { kind: found.kind, ...((found.kind === 'image' || found.kind === 'video') && localKey ? { url: localUrl(localKey, found.path) } : {}) }+ },+ openLocal: ({ messageId, path, how }) => {+ const reach = localReach(messageId)+ const found = reach && resolveLocal(path, reach)+ if (found) toMain({ type: 'open_local', path: found.path, how: how === 'open' && (found.kind === 'folder' || found.kind === 'pdf') ? 'open' : 'reveal' })+ },+deleteConversation: ({ id }) => {if (!db.conversation(id)) returnfor (const m of db.messages()) if (m.conversationId === id && (m.run?.status === 'working' || m.run?.status === 'waiting_approval')) runner.stop(m.id)diff --git a/src/core/local-paths.ts b/src/core/local-paths.tsnew file mode 100644index 0000000..55e96c0--- /dev/null+++ b/src/core/local-paths.ts@@ -0,0 +1,76 @@+// What a path cited by an agent may do when clicked. The message only suggests it: here it has to+// exist and be within this agent's reach, and nothing here ever runs what it finds.+import { createHmac, timingSafeEqual } from 'node:crypto'+import { realpathSync, statSync } from 'node:fs'+import { homedir, tmpdir } from 'node:os'+import { extname, isAbsolute, join, sep } from 'node:path'+import type { LocalInfo } from '../shared/types'++const IMAGES = ['.png', '.jpg', '.jpeg', '.gif', '.webp', '.avif', '.bmp']+const VIDEOS = ['.mp4', '.webm', '.mov', '.m4v']+const NEVER = new Set(['.ssh', '.aws', '.gnupg', '.kube', 'Keychains'])++const inside = (path: string, folder: string): boolean => path === folder || path.startsWith(folder.endsWith(sep) ? folder : folder + sep)+// The native call, so the name comes back as it is on disk: on a Mac "~/.SSH" is "~/.ssh", and+// the checks below compare names.+const real = (p: string): string => {+ try {+ return realpathSync.native(p)+ } catch {+ return p+ }+}++export interface LocalReach {+ agentId: string+ own: string // the agent's folder+ limited: boolean // only its own files: an agent on this Mac isn't+ dataRoot: string // the app's data: other agents' files, the database+ tmp?: string[] // where a harness keeps its scratchpad+}++// Only an agent on this computer reaches what its commands do: with no computer or on Linux, its own files.+export const isLimited = (agent: { computer?: boolean; computerKind?: string }): boolean => !(agent.computer && agent.computerKind === 'mac')++// The harness's own scratch folder for this agent, which carries the agent's id in its name.+const isScratch = (path: string, agentId: string, tmp: string[]): boolean =>+ tmp.some((t) => inside(path, t)) && new RegExp(`(^|[-/\\\\])agents-${agentId.replace(/[^\w-]/g, '')}([/\\\\]|$)`).test(path)++export function resolveLocal(raw: string, reach: LocalReach, home = homedir()): { path: string; kind: LocalInfo['kind'] } | null {+ const asked = raw === '~' || raw.startsWith('~/') ? join(home, raw.slice(2)) : raw+ if (!isAbsolute(asked) || asked.includes('\0')) return null+ let path: string+ let isFolder: boolean+ try {+ path = realpathSync.native(asked)+ isFolder = statSync(path).isDirectory()+ } catch {+ return null+ }+ if (path.split(sep).some((part) => NEVER.has(part))) return null+ const own = inside(path, real(reach.own))+ const scratch = isScratch(path, reach.agentId, reach.tmp ?? ['/private/tmp', '/tmp', real(tmpdir())])+ if (!own && !scratch) {+ if (inside(path, real(reach.dataRoot))) return null+ if (reach.limited) return null+ }+ const ext = extname(path).toLowerCase()+ if (isFolder) return { path, kind: ext ? 'file' : 'folder' } // a .app is a folder that would run: it only gets shown+ if (IMAGES.includes(ext)) return { path, kind: 'image' }+ if (VIDEOS.includes(ext)) return { path, kind: 'video' }+ return { path, kind: ext === '.pdf' ? 'pdf' : 'file' }+}++// An address for the window to load a file by. Signed, so the protocol serves only what the core+// has checked, and a page in the window can't ask for anything else.+const sign = (key: string, path: string): string => createHmac('sha256', key).update(path).digest('base64url')++export const localUrl = (key: string, path: string): string => `tucano://local/${sign(key, path)}/${Buffer.from(path).toString('base64url')}`++export function verifyLocalUrl(key: string, url: URL): string | null {+ const [signature = '', encoded = ''] = url.pathname.slice(1).split('/')+ const path = Buffer.from(encoded, 'base64url').toString()+ const want = Buffer.from(sign(key, path))+ const got = Buffer.from(signature)+ return want.length === got.length && timingSafeEqual(want, got) ? path : null+}diff --git a/src/main/index.ts b/src/main/index.tsindex 67379aa..3de7fba 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -1,3 +1,5 @@+import { randomBytes } from 'node:crypto'+import { verifyLocalUrl } from '../core/local-paths'import { app, BrowserWindow, dialog, ipcMain, 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, rmSync, writeFileSync } from 'node:fs'@@ -50,10 +52,12 @@ const browsers = new Browsers((agentId, shown) => core?.postMessage({ type: 'bro// The core (database, engines, runs) lives in its own process so agent work// never blocks the window or the main process.+const localKey = randomBytes(32).toString('hex')+function startCore(): UtilityProcess {const child = utilityProcess.fork(join(import.meta.dirname, 'core.js'), [], {serviceName: 'tucano-core',- env: { ...process.env, TUCANO_DATA: dataDir(), TUCANO_PACKAGED: app.isPackaged ? '1' : '0', TUCANO_LOCALE: systemLocale ?? '' }+ env: { ...process.env, TUCANO_DATA: dataDir(), TUCANO_PACKAGED: app.isPackaged ? '1' : '0', TUCANO_LOCAL_KEY: localKey, TUCANO_LOCALE: systemLocale ?? '' }})child.on('message', (msg: CoreRequest) => handleCore(child, msg))child.on('exit', (code) => {@@ -67,6 +71,7 @@ type CoreRequest =| { type: 'secret'; id: string; op: 'encrypt' | 'decrypt'; data: string }| { type: 'open'; url: string }| { type: 'open_path'; path: string }+ | { type: 'open_local'; path: string; how: 'open' | 'reveal' }| { type: 'wiki_dir'; path: string }| { type: 'notify'; title: string; body: string; conversationId?: string; kind?: 'approval' | 'question' | 'done'; sound?: boolean }| { type: 'login_item'; open: boolean }@@ -178,6 +183,10 @@ function handleCore(child: UtilityProcess, msg: CoreRequest): void {}} else if (msg.type === 'open') {if (/^https?:\/\//.test(msg.url)) void shell.openExternal(msg.url)+ } else if (msg.type === 'open_local') {+ // Never openPath on what isn't a folder or a PDF: that would run an app or a script.+ if (msg.how === 'open') void shell.openPath(msg.path)+ else shell.showItemInFolder(msg.path)} else if (msg.type === 'wiki_dir') {wikiFolder = normalize(msg.path)} else if (msg.type === 'open_path') {@@ -257,6 +266,16 @@ async function screenshot(o: { url: string; width: number; height: number; fullPfunction serveArtifact(req: Request): Promise<Response> | Response {const u = new URL(req.url)+ if (u.host === 'local') {+ // A file the core checked and signed for the window: see resolveLocal.+ const path = verifyLocalUrl(localKey, u)+ if (!path) return new Response('not found', { status: 404 })+ return net.fetch(pathToFileURL(path).toString(), { headers: req.headers }).then((r) => {+ const headers = new Headers(r.headers)+ headers.set('Content-Security-Policy', 'sandbox')+ return new Response(r.body, { status: r.status, headers })+ })+ }const [id = '', name = ''] = u.pathname.slice(1).split('/')const dir = join(dataDir(), 'artifacts', id)const file = normalize(join(dir, decodeURIComponent(name)))diff --git a/src/renderer/src/components/Conversation.tsx b/src/renderer/src/components/Conversation.tsxindex 8eff306..475e2dd 100644--- a/src/renderer/src/components/Conversation.tsx+++ b/src/renderer/src/components/Conversation.tsx@@ -1,7 +1,9 @@import { L } from '../../../shared/lang'import { CODE_SPANS } from '../../../shared/types'-import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react'-import Markdown from 'react-markdown'+import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react'+import Markdown, { defaultUrlTransform } from 'react-markdown'+import { LOCAL_LINK, remarkLocalPaths } from '../../../shared/path-text'+import { localLinkFor } from './LocalLink'import remarkGfm from 'remark-gfm'import { KeepInWiki, WikiChip, WikiLink, wikiLinks } from './Wiki'import {@@ -183,6 +185,9 @@ export function MessageList({ messages, conversationId, empty, focus }: { messag)}+const AGENT_PLUGINS = [remarkGfm, remarkLocalPaths]+const keepLocalLinks = (url: string): string => (url.startsWith(LOCAL_LINK) ? url : defaultUrlTransform(url))+function MessageRow({ message, grouped }: { message: Message; grouped: boolean }): ReactNode {const me = useStore((s) => s.me)const agent = useStore((s) => (message.author.kind === 'agent' ? agentById(s, message.author.id) : undefined))@@ -196,6 +201,9 @@ function MessageRow({ message, grouped }: { message: Message; grouped: boolean }s.messages.findLast((m) => m.conversationId === message.conversationId && m.run?.browser && m.author.kind === 'agent' && m.author.id === agent?.id)?.id === message.id)+ // The same object between renders, or every link would start over.+ const agentMarkdown = useMemo(() => ({ pre: CodeBlock, a: localLinkFor(message.id) }), [message.id])+if (message.author.kind === 'system') {return (<div className={`system-line ${message.run?.status === 'working' ? 'is-pending' : ''}`}>@@ -235,7 +243,11 @@ function MessageRow({ message, grouped }: { message: Message; grouped: boolean }{message.run && <RunSteps message={message} />}{message.text ? (<div className="md">- <Markdown remarkPlugins={[remarkGfm]} components={{ pre: CodeBlock, a: (p) => <WikiLink href={p.href}>{p.children}</WikiLink> }}>{highlightMentions(message.text)}</Markdown>+ {agent && message.run?.status !== 'working' ? (+ <Markdown remarkPlugins={AGENT_PLUGINS} urlTransform={keepLocalLinks} components={agentMarkdown}>{highlightMentions(message.text)}</Markdown>+ ) : (+ <Markdown remarkPlugins={[remarkGfm]} components={{ pre: CodeBlock, a: (p) => <WikiLink href={p.href}>{p.children}</WikiLink> }}>{highlightMentions(message.text)}</Markdown>+ )}</div>) : null}{attached.length > 0 && (diff --git a/src/renderer/src/components/Lightbox.tsx b/src/renderer/src/components/Lightbox.tsxindex 56e7e35..9feab04 100644--- a/src/renderer/src/components/Lightbox.tsx+++ b/src/renderer/src/components/Lightbox.tsx@@ -1,4 +1,4 @@-// An image the size of the window: the wheel zooms where the pointer is, dragging moves it+// An image or video the size of the window: the wheel zooms where the pointer is, dragging moves it// and the arrows go through the others.import { useEffect, useRef, useState, type ReactNode } from 'react'import { L } from '../../../shared/lang'@@ -16,6 +16,8 @@ export function Lightbox(): ReactNode {const stage = useRef<HTMLDivElement>(null)const drag = useRef<{ x: number; y: number; moved: boolean } | null>(null)const dragged = useRef(false)+ const video = useRef(false) // its controls keep the arrows and the wheel, and zoom doesn't apply+ video.current = !!item?.videouseEffect(() => setView(FIT), [item?.url])const zoomBy = (factor: number, at?: { x: number; y: number }): void =>@@ -43,7 +45,7 @@ export function Lightbox(): ReactNode {'0': () => setView(FIT)}const act = keys[e.key]- if (!act) return+ if (!act || (video.current && e.key !== 'Escape')) returne.preventDefault()e.stopPropagation() // Esc here is for this, not for what's behind itact()@@ -57,6 +59,7 @@ export function Lightbox(): ReactNode {const el = stage.currentif (!el) returnconst onWheel = (e: WheelEvent): void => {+ if (video.current) returne.preventDefault()zoomBy(Math.exp(-e.deltaY * 0.002), { x: e.clientX, y: e.clientY })}@@ -72,9 +75,13 @@ export function Lightbox(): ReactNode {<strong className="lightbox__title">{item.title}</strong>{many && <span className="small">{box.index + 1} / {box.items.length}</span>}<span className="grow" />- <button className="icon-btn" title={L('Afastar (−)', 'Zoom out (−)')} aria-label={L('Afastar', 'Zoom out')} onClick={() => zoomBy(1 / 1.4)}>−</button>- <span className="small lightbox__zoom">{Math.round(view.scale * 100)}%</span>- <button className="icon-btn" title={L('Aproximar (+)', 'Zoom in (+)')} aria-label={L('Aproximar', 'Zoom in')} onClick={() => zoomBy(1.4)}>+</button>+ {!item.video && (+ <>+ <button className="icon-btn" title={L('Afastar (−)', 'Zoom out (−)')} aria-label={L('Afastar', 'Zoom out')} onClick={() => zoomBy(1 / 1.4)}>−</button>+ <span className="small lightbox__zoom">{Math.round(view.scale * 100)}%</span>+ <button className="icon-btn" title={L('Aproximar (+)', 'Zoom in (+)')} aria-label={L('Aproximar', 'Zoom in')} onClick={() => zoomBy(1.4)}>+</button>+ </>+ )}<button className="icon-btn" title={L('Fechar (Esc)', 'Close (Esc)')} aria-label={L('Fechar', 'Close')} onClick={closeLightbox}><Icon name="x" size={16} /></button>@@ -87,7 +94,7 @@ export function Lightbox(): ReactNode {dragged.current = false}}onPointerDown={(e) => {- if (view.scale === 1) return+ if (view.scale === 1 || item.video) returndrag.current = { x: e.clientX - view.x, y: e.clientY - view.y, moved: false }}}onPointerMove={(e) => {@@ -103,17 +110,21 @@ export function Lightbox(): ReactNode {drag.current = null}}>- <img- src={item.url}- alt={item.title}- draggable={false}- style={{ transform: `translate(${view.x}px, ${view.y}px) scale(${view.scale})` }}- onDoubleClick={(e) => {- if (view.scale > 1) return setView(FIT)- const img = e.currentTarget- zoomBy(Math.max(1.5, img.naturalWidth / img.clientWidth), { x: e.clientX, y: e.clientY })- }}- />+ {item.video ? (+ <video src={item.url} controls autoPlay />+ ) : (+ <img+ src={item.url}+ alt={item.title}+ draggable={false}+ style={{ transform: `translate(${view.x}px, ${view.y}px) scale(${view.scale})` }}+ onDoubleClick={(e) => {+ if (view.scale > 1) return setView(FIT)+ const img = e.currentTarget+ zoomBy(Math.max(1.5, img.naturalWidth / img.clientWidth), { x: e.clientX, y: e.clientY })+ }}+ />+ )}</div>{many && (<>diff --git a/src/renderer/src/components/LocalLink.tsx b/src/renderer/src/components/LocalLink.tsxnew file mode 100644index 0000000..ab778c3--- /dev/null+++ b/src/renderer/src/components/LocalLink.tsx@@ -0,0 +1,81 @@+// A path an agent cited, as a link if the core says it can be one. What a click does comes from what+// the core found there, never from the text.+import { useEffect, useState, type MouseEvent, type ReactNode } from 'react'+import { L } from '../../../shared/lang'+import { LOCAL_LINK } from '../../../shared/path-text'+import { localPath, openLightbox, openLocal, useStore, type LocalInfo } from '../store'+import { WikiLink } from './Wiki'++const known = new Map<string, Promise<LocalInfo | null>>()+const lookUp = (messageId: string, path: string): Promise<LocalInfo | null> => {+ const key = `${messageId}\n${path}`+ let found = known.get(key)+ if (!found) {+ found = localPath(messageId, path).catch(() => null)+ known.set(key, found)+ }+ return found+}++function LocalLink({ messageId, path, children }: { messageId: string; path: string; children: ReactNode }): ReactNode {+ const [info, setInfo] = useState<LocalInfo | null>(null)+ const onMac = useStore((s) => s.platform) === 'mac'+ useEffect(() => {+ let alive = true+ void lookUp(messageId, path).then((r) => alive && setInfo(r))+ return () => {+ alive = false+ }+ }, [messageId, path])+ if (!info) return <>{children}</>+ const title = path.split('/').filter(Boolean).pop() ?? path+ const open = (e: MouseEvent<HTMLButtonElement>): void => {+ if (info.url) {+ // The others cited in this message, so the arrows go through them.+ const here = [...(e.currentTarget.closest('.md')?.querySelectorAll<HTMLElement>('[data-media-url]') ?? [])]+ const items = here.map((el) => ({ url: el.dataset['mediaUrl']!, title: el.dataset['mediaTitle']!, video: el.dataset['mediaVideo'] === '1' }))+ const unique = items.filter((x, i) => items.findIndex((y) => y.url === x.url) === i)+ openLightbox(unique, Math.max(0, unique.findIndex((x) => x.url === info.url)))+ } else openLocal(messageId, path, info.kind === 'folder' || info.kind === 'pdf' ? 'open' : 'reveal')+ }+ return (+ <button+ type="button"+ className="local-link"+ title={+ info.url ? L(`Abrir aqui (botão direito: mostrar ${onMac ? 'no Finder' : 'na pasta'})`, `Open here (right click: show ${onMac ? 'in Finder' : 'in its folder'})`)+ : info.kind === 'file' ? L(`Mostrar ${onMac ? 'no Finder' : 'na pasta'}`, `Show ${onMac ? 'in Finder' : 'in its folder'}`)+ : L('Abrir (botão direito: mostrar onde está)', 'Open (right click: show where it is)')+ }+ data-media-url={info.url}+ data-media-title={info.url ? title : undefined}+ data-media-video={info.kind === 'video' ? '1' : undefined}+ onClick={open}+ onContextMenu={(e) => {+ e.preventDefault()+ openLocal(messageId, path, 'reveal')+ }}+ >+ {children}+ </button>+ )+}++// An agent can write this address by hand, malformed.+const decoded = (text: string): string | undefined => {+ try {+ return decodeURIComponent(text)+ } catch {+ return undefined+ }+}++// react-markdown's `a`, for a message of an agent: its own links stay plain.+export const localLinkFor = (messageId: string) =>+ function MessageLink({ href, children, node: _node, ...rest }: { href?: string; children?: ReactNode; node?: unknown }): ReactNode {+ const path = href?.startsWith(LOCAL_LINK) ? decoded(href.slice(LOCAL_LINK.length)) : undefined+ if (path) return <LocalLink messageId={messageId} path={path}>{children}</LocalLink>+ if (href?.startsWith(LOCAL_LINK)) return <>{children}</>+ if (href?.startsWith('#wiki/')) return <WikiLink href={href}>{children}</WikiLink> // a [[page]] of the wiki+ return <a href={href} {...rest}>{children}</a>+ }diff --git a/src/renderer/src/store.ts b/src/renderer/src/store.tsindex 7afcf84..7f2da01 100644--- a/src/renderer/src/store.ts+++ b/src/renderer/src/store.ts@@ -37,7 +37,8 @@ import {type UsageReport,type Trigger,type ImageUpload,- type Os+ type Os,+ type LocalInfo} from '../../shared/types'import { call, connect } from './rpc'@@ -67,7 +68,7 @@ export interface State {models: Model[]agents: Agent[]connectors: Connector[]- lightbox: { items: { url: string; title: string }[]; index: number } | null+ lightbox: { items: { url: string; title: string; video?: boolean }[]; index: number } | nullconversations: Conversation[]messages: Message[]approvals: Approval[]@@ -450,8 +451,10 @@ export function patchAgent(agentId: string, patch: Partial<Agent>): void {void saveAgent({ ...agent, ...patch }, channelIds)}+export const localPath = (messageId: string, path: string): Promise<LocalInfo | null> => call('localPath', { messageId, path })+export const openLocal = (messageId: string, path: string, how: 'open' | 'reveal'): void => void call('openLocal', { messageId, path, how })export const openPanel = (panel: Panel | null): void => set((s) => ({ ...s, panel }))-export const openLightbox = (items: { url: string; title: string }[], index: number): void => set((s) => ({ ...s, lightbox: { items, index } }))+export const openLightbox = (items: { url: string; title: string; video?: boolean }[], index: number): void => set((s) => ({ ...s, lightbox: { items, index } }))export const closeLightbox = (): void => set((s) => ({ ...s, lightbox: null }))export const moveLightbox = (by: number): void =>set((s) => (s.lightbox ? { ...s, lightbox: { ...s.lightbox, index: (s.lightbox.index + by + s.lightbox.items.length) % s.lightbox.items.length } } : s))diff --git a/src/renderer/src/styles.css b/src/renderer/src/styles.cssindex b367bff..bd44c6c 100644--- a/src/renderer/src/styles.css+++ b/src/renderer/src/styles.css@@ -6587,7 +6587,8 @@ kbd {.lightbox__stage.is-zoomed:active {cursor: grabbing;}-.lightbox__stage img {+.lightbox__stage img,+.lightbox__stage video {max-width: 100%;max-height: 100%;object-fit: contain;@@ -6619,6 +6620,21 @@ kbd {}[data-os='mac'] .lightbox__bar {padding-left: 84px; /* the window's buttons are here */+.local-link {+ display: inline;+ padding: 0;+ border: 0;+ background: none;+ color: var(--accent);+ font: inherit;+ text-align: left;+ text-decoration: underline;+ text-underline-offset: 2px;+ overflow-wrap: anywhere;+ cursor: pointer;+}+.local-link code {+ color: inherit;}/* An agent's own color and picture */diff --git a/src/shared/path-text.ts b/src/shared/path-text.tsnew file mode 100644index 0000000..821a8a1--- /dev/null+++ b/src/shared/path-text.ts@@ -0,0 +1,88 @@+// Finding what looks like a path in a message. Only a candidate: the core checks that it exists and+// that this agent reaches it, and the text never decides what happens when it's clicked.+export type PathPart = { text: string } | { path: string; text: string }++const W = String.raw`\p{L}\p{M}\p{N}_` // not \w: folders here have accents, in either of macOS's forms+const PATH = new RegExp(String.raw`(?<![${W}:/.~@+-])(?:~/|/)(?:[${W}.@+-]+/)*[${W}.@+-]*`, 'gu')+const NAME = new RegExp(String.raw`(?<![${W}./~@+-])[${W}@+-][${W}.@+-]*\.[A-Za-z0-9]{1,8}(?![${W}/@+-])`, 'gu')+const TRAILING = /[.,;:!?]+$/++const worthIt = (p: string): boolean => p !== '/' && p !== '~/' && (p.match(/\//g) ?? []).length >= (p.startsWith('~') ? 1 : 2)++export const joinPath = (folder: string, name: string): string => (folder.endsWith('/') ? `${folder}${name}` : `${folder}/${name}`)++// Splits a piece of text. A name alone, like "home-390.png", counts only after a folder was cited:+// `folder` is the last one, and what's returned as `folder` goes on to the next piece.+export function splitPaths(text: string, folder?: string): { parts: PathPart[]; folder?: string } {+ const found: { at: number; end: number; path: string; text: string }[] = []+ let current = folder+ const paths = [...text.matchAll(PATH)].flatMap((m) => {+ const raw = m[0].replace(TRAILING, '')+ return worthIt(raw) ? [{ at: m.index, end: m.index + raw.length, raw }] : []+ })+ const names = [...text.matchAll(NAME)].flatMap((m) => {+ const raw = m[0].replace(TRAILING, '')+ return paths.some((p) => m.index < p.end && m.index + raw.length > p.at) ? [] : [{ at: m.index, end: m.index + raw.length, raw }]+ })+ for (const item of [...paths.map((p) => ({ ...p, isPath: true })), ...names.map((n) => ({ ...n, isPath: false }))].sort((a, b) => a.at - b.at)) {+ if (item.isPath) {+ found.push({ at: item.at, end: item.end, path: item.raw, text: item.raw })+ if (item.raw.endsWith('/')) current = item.raw+ } else if (current) found.push({ at: item.at, end: item.end, path: joinPath(current, item.raw), text: item.raw })+ }+ const parts: PathPart[] = []+ let last = 0+ for (const f of found) {+ if (f.at > last) parts.push({ text: text.slice(last, f.at) })+ parts.push({ path: f.path, text: f.text })+ last = f.end+ }+ if (last < text.length) parts.push({ text: text.slice(last) })+ return { parts, folder: current }+}++// Inline code is taken whole, since a path there may have spaces ("Application Support").+export function codePath(code: string, folder?: string): string | undefined {+ const value = code.trim()+ if (value.includes('\n')) return undefined+ if (/^(~\/|\/)/.test(value)) return worthIt(value) ? value : undefined+ return folder && new RegExp(`^${NAME.source}$`, 'u').test(value) ? joinPath(folder, value) : undefined+}++interface Node {+ type: string+ value?: string+ url?: string+ children?: Node[]+}++export const LOCAL_LINK = 'tucano-local:'++// A remark plugin: paths in a message's text and inline code become links only this app understands.+// Code blocks and links stay as they are.+export function remarkLocalPaths(): (tree: Node) => void {+ return (tree) => {+ let folder: string | undefined+ const link = (path: string, children: Node[]): Node => ({ type: 'link', url: `${LOCAL_LINK}${encodeURIComponent(path)}`, children })+ const walk = (node: Node): void => {+ if (!node.children) return+ const next: Node[] = []+ for (const child of node.children) {+ if (child.type === 'text' && child.value) {+ const r = splitPaths(child.value, folder)+ folder = r.folder+ for (const p of r.parts) next.push('path' in p ? link(p.path, [{ type: 'text', value: p.text }]) : { type: 'text', value: p.text })+ } else if (child.type === 'inlineCode' && child.value) {+ const path = codePath(child.value, folder)+ if (path?.endsWith('/')) folder = path+ next.push(path ? link(path, [child]) : child)+ } else {+ if (child.type !== 'link' && child.type !== 'code') walk(child)+ next.push(child)+ }+ }+ node.children = next+ }+ walk(tree)+ }+}diff --git a/src/shared/rpc.ts b/src/shared/rpc.tsindex 12095f2..40054e1 100644--- a/src/shared/rpc.ts+++ b/src/shared/rpc.ts@@ -1,6 +1,6 @@// The contract between the renderer and the core, carried over a MessagePort.import type { WikiChange, WikiHit, WikiPage, WikiImport, WikiPageInfo, WikiReview, WikiSource, WikiVersion } from './types'-import type { Os, Account, AccountEngine, Agent, BrowserInput, Approval, Artifact, ImageUpload, BrowserView, ComputerInfo, Connector, ConnectorInput, ConnectorTool, HarnessMcp, Conversation, EngineId, Memory, MemoryScope, Message, Routine, RoutineInput, Report, Settings, LocalSkill, Skill, SkillInput, SkillVersion, Trigger, UsageReport } from './types'+import type { Os, Account, AccountEngine, Agent, BrowserInput, Approval, Artifact, ImageUpload, BrowserView, ComputerInfo, Connector, ConnectorInput, ConnectorTool, HarnessMcp, Conversation, EngineId, Memory, MemoryScope, Message, Routine, RoutineInput, Report, Settings, LocalSkill, Skill, SkillInput, SkillVersion, Trigger, UsageReport, LocalInfo } from './types'export interface Snapshot {settings: Settings@@ -40,6 +40,8 @@ export interface Api {settleDraft(p: { messageId: string; agentId?: string }): void // the card is done: created elsewhere (the introduction), or dismissedupdateSettings(p: { patch: Partial<Omit<Settings, 'engines'>> }): voidrefreshEngines(): void+ localPath(p: { messageId: string; path: string }): LocalInfo | null // what a path this agent cited can do; null: it stays text+ openLocal(p: { messageId: string; path: string; how: 'open' | 'reveal' }): voidloginEngine(p: { engine: EngineId }): { opened: boolean; command: string } // not opened: no terminal to open, the person runs the commandaddAccount(p: { engine: AccountEngine; name: string }): AccountloginAccount(p: { id: string }): { opened: boolean; command: string }diff --git a/src/shared/types.ts b/src/shared/types.tsindex 3834290..d80261d 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -199,6 +199,11 @@ export interface Message {routine?: RoutineRun // set on the message a routine posts (author kind 'routine')}+export interface LocalInfo {+ kind: 'image' | 'video' | 'pdf' | 'folder' | 'file'+ url?: string // to see it here: images and videos+}+export interface Settings {workspaceName: stringcontext: stringdiff --git a/test/local-paths.test.ts b/test/local-paths.test.tsnew file mode 100644index 0000000..9ceba38--- /dev/null+++ b/test/local-paths.test.ts@@ -0,0 +1,145 @@+import { chmodSync, mkdirSync, mkdtempSync, realpathSync, symlinkSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { beforeEach, describe, expect, it } from 'vitest'+import { isLimited, localUrl, resolveLocal, verifyLocalUrl, type LocalReach } from '../src/core/local-paths'+import { codePath, LOCAL_LINK, remarkLocalPaths, splitPaths } from '../src/shared/path-text'++const paths = (text: string, folder?: string): string[] => splitPaths(text, folder).parts.flatMap((p) => ('path' in p ? [p.path] : []))++describe('finding paths in text', () => {+ it('finds absolute and home paths, leaving out the punctuation after them', () => {+ expect(paths('Salvei em /tmp/x/a.png, e também ~/Desktop/b.txt.')).toEqual(['/tmp/x/a.png', '~/Desktop/b.txt'])+ })+ it('reads accents, in either form', () => {+ expect(paths('Veja /tmp/relatório/área.png.')).toEqual(['/tmp/relatório/área.png'])+ expect(paths('Veja /tmp/relato\u0301rio/a.png.')).toEqual(['/tmp/relato\u0301rio/a.png'])+ expect(paths('Em /tmp/relatório/ ficou capa-açaí.png.')).toEqual(['/tmp/relatório/', '/tmp/relatório/capa-açaí.png'])+ })++ it('leaves out links, slashes in words, routes of one level and the root', () => {+ expect(paths('https://site.com/a/b e/ou and/or /api / 16/10/2026 x:/y/z')).toEqual([])+ })+ it('keeps the text around them', () => {+ const { parts } = splitPaths('veja /tmp/a/b.png agora')+ expect(parts).toEqual([{ text: 'veja ' }, { path: '/tmp/a/b.png', text: '/tmp/a/b.png' }, { text: ' agora' }])+ })+ it('reads names after a folder, as in the real message', () => {+ const r = splitPaths('/private/tmp/s/scratchpad/: home-390.png, stmt-1280.png e stmt-scrolled-390.png.')+ expect(r.parts.flatMap((p) => ('path' in p ? [p.path] : []))).toEqual(['/private/tmp/s/scratchpad/', '/private/tmp/s/scratchpad/home-390.png', '/private/tmp/s/scratchpad/stmt-1280.png', '/private/tmp/s/scratchpad/stmt-scrolled-390.png'])+ expect(r.folder).toBe('/private/tmp/s/scratchpad/')+ })+ it('a name with no folder before it stays text', () => {+ expect(paths('olhe home-390.png')).toEqual([])+ expect(paths('olhe home-390.png', '/tmp/s/')).toEqual(['/tmp/s/home-390.png'])+ })+ it('takes inline code whole, spaces included', () => {+ expect(codePath('~/Library/Application Support/Tucano')).toBe('~/Library/Application Support/Tucano')+ expect(codePath('npm run dev')).toBeUndefined()+ expect(codePath('a.png')).toBeUndefined()+ expect(codePath('a.png', '/tmp/s/')).toBe('/tmp/s/a.png')+ })+ it('turns text and inline code into links, and leaves code blocks and links alone', () => {+ const tree = {+ type: 'root',+ children: [+ { type: 'paragraph', children: [{ type: 'text', value: 'em /tmp/s/: ' }, { type: 'inlineCode', value: 'a.png' }] },+ { type: 'code', value: '/tmp/s/nao.png' },+ { type: 'paragraph', children: [{ type: 'link', url: 'https://x.com', children: [{ type: 'text', value: '/tmp/s/nao.png' }] }] }+ ]+ }+ remarkLocalPaths()(tree)+ const urls = JSON.stringify(tree).match(/tucano-local:[^"]+/g)!.map((u) => decodeURIComponent(u.slice(LOCAL_LINK.length)))+ expect(urls).toEqual(['/tmp/s/', '/tmp/s/a.png'])+ })+})++describe.runIf(process.platform !== 'win32')('what a path can do', () => {+ let root = ''+ let reach: LocalReach+ const file = (rel: string): string => {+ const p = join(root, rel)+ mkdirSync(join(p, '..'), { recursive: true })+ writeFileSync(p, 'x')+ return p+ }+ beforeEach(() => {+ root = realpathSync(mkdtempSync(join(tmpdir(), 'ad-local-')))+ mkdirSync(join(root, 'dados/computers/ada/work'), { recursive: true })+ reach = { agentId: 'ada', own: join(root, 'dados/computers/ada/work'), dataRoot: join(root, 'dados'), tmp: [join(root, 'tmp')], limited: false }+ })++ it('says what each thing is, and a missing one is nothing', () => {+ expect(resolveLocal(file('p/a.PNG'), reach)?.kind).toBe('image')+ expect(resolveLocal(file('p/a.mp4'), reach)?.kind).toBe('video')+ expect(resolveLocal(file('p/a.pdf'), reach)?.kind).toBe('pdf')+ expect(resolveLocal(file('p/a.sh'), reach)?.kind).toBe('file')+ expect(resolveLocal(join(root, 'p'), reach)?.kind).toBe('folder')+ expect(resolveLocal(join(root, 'p/sumiu.png'), reach)).toBeNull()+ expect(resolveLocal('relativo/a.png', reach)).toBeNull()+ })++ it('a folder with an extension, like an app, is only ever shown', () => {+ mkdirSync(join(root, 'Calc.app/Contents'), { recursive: true })+ expect(resolveLocal(join(root, 'Calc.app'), reach)?.kind).toBe('file')+ })++ it('limited: only its own folder and scratchpad', () => {+ const limited = { ...reach, limited: true }+ expect(resolveLocal(file('cliente-y/a.png'), limited)).toBeNull()+ expect(resolveLocal(file('dados/computers/ada/work/a.png'), limited)).not.toBeNull()+ expect(resolveLocal(file('tmp/claude/-Tucano-agents-ada/s/scratchpad/a.png'), limited)).not.toBeNull()+ expect(resolveLocal(file('tmp/claude/-Tucano-agents-theo/s/scratchpad/a.png'), limited)).toBeNull()+ expect(resolveLocal(file('tmp/outro/a.png'), limited)).toBeNull()+ })++ it('a link can’t reach out of its folder', () => {+ file('cliente-y/a.png')+ symlinkSync(join(root, 'cliente-y/a.png'), join(root, 'dados/computers/ada/work/atalho.png'))+ expect(resolveLocal(join(root, 'dados/computers/ada/work/atalho.png'), { ...reach, limited: true })).toBeNull()+ })++ it('`..` can’t climb out of its folder', () => {+ file('cliente-y/a.png')+ file('dados/computers/theo/work/b.png')+ const limited = { ...reach, limited: true }+ expect(resolveLocal(join(root, 'dados/computers/ada/work') + '/../../../../cliente-y/a.png', limited)).toBeNull()+ expect(resolveLocal(join(root, 'dados/computers/ada/work') + '/../../theo/work/b.png', reach)).toBeNull()+ })++ it('an agent with no computer, or on Linux, is limited; only one on this computer isn’t', () => {+ expect(isLimited({ computer: false })).toBe(true)+ expect(isLimited({})).toBe(true)+ expect(isLimited({ computer: false, computerKind: 'mac' })).toBe(true)+ expect(isLimited({ computer: true, computerKind: 'linux' })).toBe(true)+ expect(isLimited({ computer: true, computerKind: 'mac' })).toBe(false)+ })++ it('never the app’s data, another agent’s folder or a place that holds logins', () => {+ expect(resolveLocal(file('dados/tucano.db'), reach)).toBeNull()+ expect(resolveLocal(file('dados/computers/theo/work/a.png'), reach)).toBeNull()+ expect(resolveLocal(file('casa/.ssh/id_rsa'), reach)).toBeNull()+ expect(resolveLocal(file('casa/.aws/credentials'), reach)).toBeNull()+ chmodSync(root, 0o755)+ })++ it('the same, written in other capitals (a Mac doesn’t tell them apart)', () => {+ file('casa/.ssh/id_rsa')+ file('dados/notas.png')+ expect(resolveLocal(join(root, 'casa/.SSH/id_rsa'), reach)).toBeNull()+ expect(resolveLocal(join(root, 'DADOS/notas.png'), reach)).toBeNull()+ })++ it('expands the home folder', () => {+ expect(resolveLocal('~/p/a.png', reach, (file('p/a.png'), root))?.kind).toBe('image')+ })++ it('an address only opens what was signed', () => {+ const url = new URL(localUrl('chave', '/tmp/a.png'))+ expect(url.host).toBe('local')+ expect(verifyLocalUrl('chave', url)).toBe('/tmp/a.png')+ expect(verifyLocalUrl('outra', url)).toBeNull()+ const [sig] = url.pathname.slice(1).split('/')+ expect(verifyLocalUrl('chave', new URL(`tucano://local/${sig}/${Buffer.from('/etc/passwd').toString('base64url')}`))).toBeNull()+ })+})