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
Connect the desktop app to Tucanos on servers (#165)
Eduardo Machado91061b0d0664
diff --git a/package.json b/package.jsonindex c40e661..c662843 100644--- a/package.json+++ b/package.json@@ -149,6 +149,14 @@"!VERSION"]}+ ],+ "protocols": [+ {+ "name": "Tucano",+ "schemes": [+ "tucano"+ ]+ }]}}diff --git a/src/main/index.ts b/src/main/index.tsindex bb06052..f76b8d3 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -1,6 +1,6 @@import { randomBytes } from 'node:crypto'import { verifyLocalUrl } from '../core/local-paths'-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 { app, BrowserWindow, clipboard, 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'@@ -9,6 +9,7 @@ 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 { Servers } from './servers'import { bundleOf, moveFromAgentDesk, type Moved } from './migrate'import { Updates } from './updates'import { Workspaces } from './workspaces'@@ -218,6 +219,7 @@ function setTray(): void {tray.setContextMenu(Menu.buildFromTemplate([{ label: L(`Abrir o ${NAME}`, `Open ${NAME}`), click: () => showWindow() },+ ...(servers.list().length ? [{ type: 'separator' as const }, ...servers.windowsMenu()] : []),{ type: 'separator' },{ label: L(`Encerrar o ${NAME}`, `Quit ${NAME}`), click: () => app.quit() }])@@ -563,6 +565,7 @@ function showWindow(conversationId?: string, page?: 'skills', threadId?: string)win.show()win.focus()if (!conversationId && !page) return+ servers.showLocal() // a conversation of this computer's: its Tucano on screenconst go = (): void => (page ? win.webContents.send('navigate-page', page) : win.webContents.send('navigate', conversationId, threadId))if (win.webContents.isLoading()) win.webContents.once('did-finish-load', go)else go()@@ -625,6 +628,9 @@ function createWindow(): BrowserWindow {win.once('ready-to-show', () => win.show())mainWindow = win+ // A server on screen keeps the window's size (servers.ts), and comes back in a window made again.+ win.on('resize', () => servers.place())+ win.webContents.once('did-finish-load', () => servers.place())win.on('closed', () => {if (mainWindow === win) {cores.get(registry.selected().id)?.child.postMessage({ type: 'viewing', conversationId: null })@@ -670,7 +676,50 @@ if (process.env['TUCANO_DATA']) app.setPath('userData', process.env['TUCANO_DATAconst quitOnly = process.argv.includes('--quit')const primary = app.requestSingleInstanceLock() && !quitOnlyif (!primary) app.quit()-app.on('second-instance', (_e, argv) => (argv.includes('--quit') ? app.quit() : showWindow()))+// Tucanos on servers, shown in the app's window (servers.ts). The keychain keeps their access, as it+// keeps the core's secrets; where it can't, nothing is saved.+const servers = new Servers({+ dataDir,+ seal: (text) => (safeStorage.isEncryptionAvailable() && safeStorage.getSelectedStorageBackend?.() !== 'basic_text' ? safeStorage.encryptString(text).toString('base64') : null),+ unseal: (sealed) => {+ try {+ return safeStorage.decryptString(Buffer.from(sealed, 'base64'))+ } catch {+ return null+ }+ },+ changed: () => {+ setMenu()+ if (mainWindow && !mainWindow.isDestroyed()) mainWindow.webContents.send('servers')+ },+ window: () => (mainWindow && !mainWindow.isDestroyed() ? mainWindow : null),+ showLocal: () => showWindow()+})+// Settings › Servers, on the app's own page only (fromApp): the list without tokens, pairing with a+// pasted link, opening and forgetting.+ipcMain.handle('servers:list', (e) => (fromApp(e) ? servers.summary() : []))+ipcMain.handle('servers:pair', (e, link: unknown) => (fromApp(e) && typeof link === 'string' && link.length < 4096 ? servers.pair(link, false) : 'invalid'))+ipcMain.on('servers:open', (e, id: unknown) => fromApp(e) && typeof id === 'string' && void servers.show(id))+ipcMain.on('servers:local', (e) => fromApp(e) && servers.showLocal())+ipcMain.handle('servers:forget', (e, id: unknown) => (fromApp(e) && typeof id === 'string' ? servers.forget(id, false) : false))+// A tucano://connect link: on a Mac the system hands it over by open-url; on Windows and Linux it+// comes as an argument, to this instance or (the app already open) to second-instance.+const linkIn = (argv: string[]): string | undefined => argv.find((a) => a.startsWith('tucano://'))+let pendingLink = linkIn(process.argv)+const openLink = (link: string): void => {+ if (app.isReady()) void servers.pairFromOutside(link)+ else pendingLink = link+}+app.on('open-url', (e, url) => {+ e.preventDefault()+ openLink(url)+})+app.on('second-instance', (_e, argv) => {+ if (argv.includes('--quit')) return app.quit()+ const link = linkIn(argv)+ if (link) openLink(link)+ else showWindow()+})// The app's own menu, in the app's language (Electron's would be in English).function setMenu(): void {@@ -695,6 +744,7 @@ function setMenu(): void {},{ role: 'editMenu', label: L('Editar', 'Edit') },{ role: 'viewMenu', label: L('Visualizar', 'View') },+ { label: L('Servidores', 'Servers'), submenu: servers.menu(() => clipboard.readText()) },{ role: 'windowMenu', label: L('Janela', 'Window') }]))@@ -734,6 +784,11 @@ if (moved === 'old-app-open' || moved === 'keychain-denied') {createWindow()setTray()updates.start()+ // Only the installed app takes tucano:// links: a development run would take them from it.+ if (app.isPackaged) app.setAsDefaultProtocolClient('tucano')+ servers.restore()+ if (pendingLink) void servers.pairFromOutside(pendingLink)+ pendingLink = undefinedapp.on('activate', () => {if (!mainWindow || mainWindow.isDestroyed()) createWindow()})@@ -746,6 +801,7 @@ app.on('window-all-closed', () => {app.on('before-quit', () => {quitting = true+ servers.quit()for (const r of cores.values()) r.browsers.quit()})diff --git a/src/main/servers.ts b/src/main/servers.tsnew file mode 100644index 0000000..6544a55--- /dev/null+++ b/src/main/servers.ts@@ -0,0 +1,316 @@+// Tucanos on servers (docs/server.md), shown in the app's own window: picking one puts its page+// over the app, under a bar the app draws (BAR px) to go back. The page is in a view of its own,+// which brings its own bridge to its core over HTTP: it never gets this app's preload, so a server,+// even one taken over, can't reach this computer through it. Each server keeps its own session+// (cookies, storage), apart from this app's and from the others'.+import { BrowserWindow, dialog, session, shell, WebContentsView, type MenuItemConstructorOptions, type Session } from 'electron'+import { randomUUID } from 'node:crypto'+import { readFileSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { L } from '../shared/lang'+import { isOutsideLink } from '../shared/links'+import { isPreviewOf, onServer, parsePairing, serverName } from '../shared/servers'++interface Saved {+ id: string+ origin: string+ token: string // sealed with the system's keychain+ open?: boolean // it was on screen when the app last quit: it comes back there+}++// The app's bar above a server's page (the renderer's ServerBar): where to go back.+export const BAR = 40++// What the app's own page sees of a server: never its token.+export interface ServerInfo {+ id: string+ name: string+ origin: string+ open: boolean // on screen now, in the app's window+}++// paired; cancelled (the person said no); invalid (not a pairing link); unsafe (nowhere safe to keep it)+export type PairResult = 'paired' | 'cancelled' | 'invalid' | 'unsafe'++export interface ServersDeps {+ dataDir: () => string+ seal: (text: string) => string | null // null: this computer can't keep it safely+ unseal: (sealed: string) => string | null+ changed: () => void // the menus and the app's page list the servers, and which is on screen+ window: () => BrowserWindow | null // the app's window, where a server is shown+ showLocal: () => void // the app's window, on screen+}++// What a server's page may ask for: notifications, writing to the clipboard, the microphone for+// dictation (audio only), full screen. Never the camera, the screen, files, devices or the location.+function guard(ses: Session, origin: string): void {+ ses.setPermissionRequestHandler((_c, permission, done, details) => {+ if (!onServer((details as { requestingUrl?: string }).requestingUrl ?? '', origin)) return done(false)+ if (permission === 'media') {+ const types = (details as { mediaTypes?: string[] }).mediaTypes ?? []+ return done(types.length > 0 && types.every((t) => t === 'audio'))+ }+ done(['notifications', 'clipboard-sanitized-write', 'fullscreen'].includes(permission))+ })+ ses.setPermissionCheckHandler((_c, permission, requestingOrigin) => requestingOrigin === origin && ['notifications', 'clipboard-sanitized-write', 'media', 'fullscreen'].includes(permission))+ ses.setDevicePermissionHandler(() => false)+}++export class Servers {+ private views = new Map<string, WebContentsView>() // kept while the app runs: going back and forth is instant+ private active: string | null = null // the server on screen; null: this computer+ private host: BrowserWindow | null = null // the window the view is in now+ private guarded = new WeakSet<Session>()+ private quitting = false++ constructor(private deps: ServersDeps) {}++ private file(): string {+ return join(this.deps.dataDir(), 'servers.json')+ }++ list(): Saved[] {+ try {+ const l = JSON.parse(readFileSync(this.file(), 'utf8')) as Saved[]+ return Array.isArray(l) ? l.filter((s) => s && typeof s.id === 'string' && typeof s.origin === 'string' && typeof s.token === 'string') : []+ } catch {+ return []+ }+ }++ private save(list: Saved[]): void {+ writeFileSync(this.file(), JSON.stringify(list, null, 2), { mode: 0o600 })+ this.deps.changed()+ }++ summary(): ServerInfo[] {+ return this.list().map((s) => ({ id: s.id, name: serverName(s.origin), origin: s.origin, open: this.active === s.id }))+ }++ // A pairing link from outside the app (the system, the menu's clipboard): it says so when it isn't one.+ async pairFromOutside(link: string): Promise<void> {+ if ((await this.pair(link, true)) !== 'invalid') return+ await dialog.showMessageBox({+ type: 'warning',+ message: L('Esse não é um link de conexão do Tucano', "That's not a Tucano connection link"),+ detail: L('O link de conexão começa com tucano://connect e sai do servidor (node out/main/server.js link).', 'A connection link starts with tucano://connect and comes from the server (node out/main/server.js link).')+ })+ }++ // A pairing link. One from outside the app may come from any web page (it can make the system+ // hand one over), so the person is asked first, with the address in plain sight. One pasted in+ // Settings was put there by the person, who reads the same warning on that screen.+ async pair(link: string, ask: boolean): Promise<PairResult> {+ const p = parsePairing(link)+ if (!p) return 'invalid'+ const name = serverName(p.origin)+ const { response } = !ask ? { response: 0 } : await dialog.showMessageBox({+ type: 'question',+ buttons: [L('Conectar', 'Connect'), L('Cancelar', 'Cancel')],+ defaultId: 0,+ cancelId: 1,+ message: L(`Conectar ao Tucano em ${name}?`, `Connect to the Tucano at ${name}?`),+ detail: L(+ 'Esse link dá acesso a um Tucano num servidor: quem tem o link controla os agentes de lá. Conecte só se foi você quem criou esse servidor ou se confia em quem mandou o link.',+ 'This link gives access to a Tucano on a server: whoever has it controls the agents there. Connect only if you made that server or trust whoever sent the link.'+ )+ })+ if (response !== 0) return 'cancelled'+ const sealed = this.deps.seal(p.token)+ if (!sealed) {+ await dialog.showMessageBox({+ type: 'error',+ message: L('Não dá pra guardar esse acesso com segurança aqui', "This access can't be kept safely here"),+ detail: L('O cofre de senhas do sistema não está disponível. Abra o endereço no navegador por enquanto.', "The system's password store isn't available. Open the address in a browser for now.")+ })+ return 'unsafe'+ }+ const list = this.list()+ const known = list.find((s) => s.origin === p.origin)+ // A new token for a server already here: its page starts again with it.+ if (known) this.drop(known.id)+ const id = known?.id ?? randomUUID()+ this.save([...list.filter((s) => s.origin !== p.origin), { id, origin: p.origin, token: sealed, open: true }])+ await this.show(id)+ return 'paired'+ }++ // A server on screen, in the app's window, over the app; made the first time, kept after.+ async show(id: string): Promise<void> {+ const s = this.list().find((x) => x.id === id)+ if (!s) return+ let view = this.views.get(id)+ if (!view || view.webContents.isDestroyed()) {+ const made = await this.make(s)+ if (!made) return+ view = made+ }+ this.active = id+ this.setOpen(id, true)+ this.place()+ this.deps.showLocal() // the window, in front+ view.webContents.focus()+ this.deps.changed()+ }++ // Back to this computer's Tucano, in the same window.+ showLocal(): void {+ if (this.active) this.setOpen(this.active, false)+ this.active = null+ this.place()+ this.deps.changed()+ }++ // The view on screen, or none, in the app's window as it is now (made again, resized).+ place(): void {+ const win = this.deps.window()+ if (this.host && this.host !== win && !this.host.isDestroyed()) for (const v of this.views.values()) this.host.contentView.removeChildView(v)+ this.host = win+ if (!win || win.isDestroyed()) return+ for (const [id, v] of this.views) if (id !== this.active) win.contentView.removeChildView(v)+ const view = this.active ? this.views.get(this.active) : undefined+ if (!view) return void win.setTitle('Tucano')+ const { width, height } = win.getContentBounds()+ view.setBounds({ x: 0, y: BAR, width, height: Math.max(0, height - BAR) })+ win.contentView.addChildView(view)+ const s = this.list().find((x) => x.id === this.active)+ if (s) win.setTitle(`Tucano · ${serverName(s.origin)}`)+ }++ private async make(s: Saved): Promise<WebContentsView | null> {+ const token = this.deps.unseal(s.token)+ if (!token) {+ console.error('[servers] the saved access could not be unsealed')+ void dialog.showMessageBox({ type: 'error', message: L('Não consegui abrir o acesso guardado', "Couldn't open the saved access"), detail: L('Conecte de novo com o link do servidor.', "Connect again with the server's link.") })+ return null+ }+ const ses = session.fromPartition(`persist:server-${s.id}`)+ if (!this.guarded.has(ses)) {+ guard(ses, s.origin)+ this.guarded.add(ses)+ }+ // Signed in the way the server's own link would: its cookie, so the token is never in an address.+ await ses.cookies.set({ url: s.origin, name: 'tucano', value: token, httpOnly: true, secure: s.origin.startsWith('https:'), sameSite: 'lax', expirationDate: Date.now() / 1000 + 365 * 86400 })+ const name = serverName(s.origin)+ const webPreferences = { session: ses, sandbox: true, contextIsolation: true, nodeIntegration: false, webviewTag: false }+ const view = new WebContentsView({ webPreferences })+ const wc = view.webContents+ this.views.set(s.id, view)+ // Only the server's own pages in this view. Web and mail links open in the system; anything+ // else (a local file, the app's own tucano: pages, another server) goes nowhere.+ // An agent's page, opened from the panel: in a window of this server's own session, where its+ // sign-in is (the system's browser hasn't signed in to the server).+ wc.setWindowOpenHandler(({ url }) => {+ if (onServer(url, s.origin) && new URL(url).pathname.startsWith('/preview/')) return { action: 'allow', overrideBrowserWindowOptions: { width: 1100, height: 760, title: `Tucano · ${name}`, webPreferences } }+ if (isOutsideLink(url) && !onServer(url, s.origin)) void shell.openExternal(url)+ return { action: 'deny' }+ })+ // That window goes only to the server and its preview addresses; the rest opens in the system.+ wc.on('did-create-window', (child) => {+ const keep = (event: { preventDefault: () => void }, url: string): void => {+ if (onServer(url, s.origin) || isPreviewOf(url, s.origin)) return+ event.preventDefault()+ if (isOutsideLink(url)) void shell.openExternal(url)+ }+ child.webContents.on('will-navigate', keep)+ child.webContents.on('will-redirect', keep)+ child.webContents.setWindowOpenHandler(({ url }) => {+ if (isOutsideLink(url) && !onServer(url, s.origin) && !isPreviewOf(url, s.origin)) void shell.openExternal(url)+ return { action: 'deny' }+ })+ })+ const stay = (event: { preventDefault: () => void }, url: string): void => {+ if (onServer(url, s.origin)) return+ event.preventDefault()+ if (isOutsideLink(url)) void shell.openExternal(url)+ }+ wc.on('will-navigate', stay)+ wc.on('will-redirect', stay)+ wc.on('will-attach-webview', (e) => e.preventDefault())+ wc.on('did-fail-load', (_e, code, _desc, url, mainFrame) => {+ if (!mainFrame || code === -3) return // -3: a navigation cut short, not a failure+ void wc.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(unreachable(name, s.origin, url))}`)+ })+ wc.on('render-process-gone', () => {+ // Its page crashed: made again the next time it's picked.+ this.drop(s.id)+ if (this.active === s.id) this.showLocal()+ })+ // Not awaited: the view is there, its page comes as the server answers (or the page above says why not).+ void wc.loadURL(`${s.origin}/`).catch(() => {})+ return view+ }++ // A server's view, gone (forgotten, paired again, crashed).+ private drop(id: string): void {+ const v = this.views.get(id)+ if (!v) return+ this.views.delete(id)+ if (this.host && !this.host.isDestroyed()) this.host.contentView.removeChildView(v)+ if (!v.webContents.isDestroyed()) v.webContents.close()+ }++ private setOpen(id: string, open: boolean): void {+ const list = this.list()+ const s = list.find((x) => x.id === id)+ if (!s || !!s.open === open) return+ s.open = open+ writeFileSync(this.file(), JSON.stringify(list, null, 2), { mode: 0o600 })+ }++ // Forgetting a server: its window, its cookie and storage, its saved access. Settings asks in+ // its own dialog first; the menu asks here.+ async forget(id: string, ask: boolean): Promise<boolean> {+ const s = this.list().find((x) => x.id === id)+ if (!s) return false+ const { response } = !ask ? { response: 0 } : await dialog.showMessageBox({+ type: 'warning',+ buttons: [L('Esquecer', 'Forget'), L('Cancelar', 'Cancel')],+ defaultId: 1,+ cancelId: 1,+ message: L(`Esquecer o Tucano em ${serverName(s.origin)}?`, `Forget the Tucano at ${serverName(s.origin)}?`),+ detail: L('Só este computador esquece o acesso. O Tucano do servidor continua lá, com tudo.', 'Only this computer forgets the access. The Tucano on the server stays there, with everything.')+ })+ if (response !== 0) return false+ if (this.active === id) this.showLocal()+ this.drop(id)+ await session.fromPartition(`persist:server-${id}`).clearStorageData()+ this.save(this.list().filter((x) => x.id !== id))+ return true+ }++ // At launch: the server that was on screen when the app quit, on screen again.+ restore(): void {+ const last = this.list().find((s) => s.open)+ if (last) void this.show(last.id).catch((e: unknown) => console.error('[servers] restore', e instanceof Error ? e.message : e))+ }++ quit(): void {+ this.quitting = true+ }++ // For the tray: each server, to show.+ windowsMenu(): MenuItemConstructorOptions[] {+ return this.list().map((s): MenuItemConstructorOptions => ({ label: serverName(s.origin), click: () => void this.show(s.id) }))+ }++ // For the app's menu: this computer, each server, and pairing.+ menu(pasted: () => string | Promise<string>): MenuItemConstructorOptions[] {+ const list = this.list()+ return [+ { label: L('Este computador', 'This computer'), click: () => (this.showLocal(), this.deps.showLocal()) },+ ...this.windowsMenu(),+ { type: 'separator' },+ { label: L('Conectar com o link copiado', 'Connect with the copied link'), click: () => void Promise.resolve(pasted()).then((t) => this.pairFromOutside(t)) },+ ...(list.length+ ? [{ label: L('Esquecer um servidor', 'Forget a server'), submenu: list.map((s): MenuItemConstructorOptions => ({ label: serverName(s.origin), click: () => void this.forget(s.id, true) })) }]+ : [])+ ]+ }+}++// When the server doesn't answer: what to check, in the window itself (no app bridge here either).+function unreachable(name: string, origin: string, url: string): string {+ const esc = (t: string): string => t.replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]!)+ return `<!doctype html><meta charset="utf-8"><title>Tucano</title><style>body{font:15px system-ui;margin:0;display:grid;place-items:center;height:100vh;background:#f6f3ee;color:#1d1a16}@media(prefers-color-scheme:dark){body{background:#1a1917;color:#f1ece4}}main{max-width:440px;padding:24px}p{opacity:.75;line-height:1.5}a{color:inherit;font-weight:600}</style><main><h2>${esc(L(`O Tucano em ${name} não respondeu`, `The Tucano at ${name} didn't answer`))}</h2><p>${esc(L('Confira a internet e se o servidor está no ar.', 'Check the internet and whether the server is up.'))}</p><p><a href="${esc(origin)}/">${esc(L('Tentar de novo', 'Try again'))}</a></p><p><small>${esc(url)}</small></p></main>`+}diff --git a/src/preload/index.ts b/src/preload/index.tsindex 975cb9e..b47a1dc 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -45,5 +45,16 @@ contextBridge.exposeInMainWorld('tucano', {ipcRenderer.on('update', (_e, state: unknown) => cb(state))},checkUpdates: (): void => ipcRenderer.send('update:check'),- installUpdate: (): void => ipcRenderer.send('update:install')+ installUpdate: (): void => ipcRenderer.send('update:install'),+ // Tucanos on servers, shown in this window over the app (Settings › Servers, the workspace list).+ servers: {+ list: (): Promise<unknown> => ipcRenderer.invoke('servers:list'),+ pair: (link: string): Promise<unknown> => ipcRenderer.invoke('servers:pair', link),+ open: (id: string): void => ipcRenderer.send('servers:open', id),+ local: (): void => ipcRenderer.send('servers:local'),+ forget: (id: string): Promise<unknown> => ipcRenderer.invoke('servers:forget', id),+ onChanged: (cb: () => void): void => {+ ipcRenderer.on('servers', () => cb())+ }+ }})diff --git a/src/renderer/src/components/Pages.tsx b/src/renderer/src/components/Pages.tsxindex 97240bb..1ae9ce2 100644--- a/src/renderer/src/components/Pages.tsx+++ b/src/renderer/src/components/Pages.tsx@@ -75,6 +75,7 @@ import { confirmDialog } from './Dialogs'import { Modal } from './Modal'import { AgentAvatar, AVATARS, Icon, NumberInput, SleepingToucan, time, tokens, UsageBar } from './ui'import { UpdateSettings } from './Update'+import { hasServers, ServersCard } from './Servers'import { useWorkspaceList } from './Workspaces'import { workspaceLabel } from '../../../shared/workspaces'import exportSkill from '../assets/tucano-export-skill.md?raw'@@ -1401,7 +1402,8 @@ const SETTINGS_TABS = (): TabList => [['geral', L('Geral', 'General')],['modelos', L('Modelos', 'Models')],['agentes', L('Agentes', 'Agents')],- ['integracoes', L('Celular e GitHub', 'Phone and GitHub')]+ ['integracoes', L('Celular e GitHub', 'Phone and GitHub')],+ ...(hasServers() ? [['servidores', L('Servidores', 'Servers')] as [string, string]] : [])]const AGENT_TABS = (): TabList => [['perfil', L('Perfil', 'Profile')],@@ -2092,6 +2094,7 @@ export function SettingsPage(): ReactNode {{pane('integracoes') && <GithubCard info={settings.github} />}{pane('geral') && <TeamCard />}+ {pane('servidores') && <ServersCard />}{pane('agentes') && (<Card title={L('Limites', 'Limits')}>diff --git a/src/renderer/src/components/Servers.tsx b/src/renderer/src/components/Servers.tsxnew file mode 100644index 0000000..4111a18--- /dev/null+++ b/src/renderer/src/components/Servers.tsx@@ -0,0 +1,148 @@+// Settings › Servers: Tucanos that run on a server (yours, or your company's), shown in this+// window over the app. Desktop only; the pairing link comes from the server (`server.js link`).+import { useEffect, useState, type ReactNode } from 'react'+import { L } from '../../../shared/lang'+import { confirmDialog } from './Dialogs'+import { Card } from './Pages'+import { Icon } from './ui'++type Server = { id: string; name: string; origin: string; open: boolean }++export const hasServers = (): boolean => !!window.tucano?.servers++export function ServersCard(): ReactNode {+ const api = window.tucano.servers!+ const [list, setList] = useState<Server[]>([])+ const [link, setLink] = useState('')+ const [error, setError] = useState('')+ const [busy, setBusy] = useState(false)+ useEffect(() => {+ let alive = true+ const load = (): void => void api.list().then((l) => alive && setList(l))+ load()+ api.onChanged(load)+ return () => {+ alive = false+ }+ }, [api])++ const connect = async (): Promise<void> => {+ setError('')+ setBusy(true)+ const r = await api.pair(link).finally(() => setBusy(false))+ if (r === 'paired') return setLink('')+ if (r === 'invalid') setError(L('Esse não é um link de conexão. Ele começa com tucano://connect e sai do servidor.', "That's not a connection link. It starts with tucano://connect and comes from the server."))+ }+ const forget = async (s: Server): Promise<void> => {+ const ok = await confirmDialog({+ title: L(`Esquecer o Tucano em ${s.name}?`, `Forget the Tucano at ${s.name}?`),+ body: L('Só este computador esquece o acesso. O Tucano do servidor continua lá, com tudo.', 'Only this computer forgets the access. The Tucano on the server stays there, with everything.'),+ confirm: L('Esquecer', 'Forget'),+ danger: true+ })+ if (ok) await api.forget(s.id)+ }++ return (+ <>+ <Card+ title={L('Servidores', 'Servers')}+ lead={L(+ 'Um Tucano que roda num servidor, ligado o tempo todo, aberto aqui mesmo: escolha na lista do topo da barra lateral, e volte pela faixa de cima. Os agentes e as conversas são os de lá; nada deste computador vai pra ele.',+ 'A Tucano running on a server, always on, opened right here: pick it in the list at the top of the sidebar, and come back from the bar above it. The agents and conversations are the server’s; nothing on this computer goes to it.'+ )}+ >+ <div className="key-row">+ <Icon name="laptop" />+ <div className="grow">+ <strong>{L('Este computador', 'This computer')}</strong>+ <p className="muted small">{L('O Tucano desta janela: os agentes, as rotinas e os apps deste computador.', 'The Tucano in this window: the agents, routines and apps of this computer.')}</p>+ </div>+ </div>+ {list.map((s) => (+ <div key={s.id} className="key-row">+ <Icon name="globe" />+ <div className="grow">+ <strong>{s.name}</strong>+ <p className="muted small">{s.open ? L('Aberto numa janela', 'Open in a window') : L('Pareado com este computador', 'Paired with this computer')}</p>+ </div>+ <div className="row">+ <button className="btn btn--sm btn--primary" onClick={() => api.open(s.id)}>+ {s.open ? L('Mostrar', 'Show') : L('Abrir', 'Open')}+ </button>+ <button className="btn btn--sm btn--ghost" onClick={() => void forget(s)}>+ {L('Esquecer', 'Forget')}+ </button>+ </div>+ </div>+ ))}+ </Card>+ <Card+ title={L('Conectar a um servidor', 'Connect to a server')}+ lead={L(+ 'Cole o link de conexão que o servidor deu (tucano://connect…). Quem tem o link controla os agentes de lá: cole só links seus ou de quem você confia.',+ 'Paste the connection link the server gave you (tucano://connect…). Whoever has the link controls the agents there: paste only links of your own or from someone you trust.'+ )}+ >+ <form+ className="row"+ onSubmit={(e) => {+ e.preventDefault()+ if (link.trim() && !busy) void connect()+ }}+ >+ <input className="grow" type="password" autoComplete="off" spellCheck={false} placeholder="tucano://connect?url=…" value={link} onChange={(e) => (setLink(e.target.value), setError(''))} />+ <button className="btn btn--sm btn--primary" type="submit" disabled={!link.trim() || busy}>+ {L('Conectar', 'Connect')}+ </button>+ </form>+ {error && <p className="note note--error">{error}</p>}+ </Card>+ </>+ )+}++// The servers, live: the list and which one is on screen.+export function useServers(): Server[] {+ const api = window.tucano?.servers+ const [list, setList] = useState<Server[]>([])+ useEffect(() => {+ if (!api) return+ let alive = true+ const load = (): void => void api.list().then((l) => alive && setList(l))+ load()+ api.onChanged(load)+ return () => {+ alive = false+ }+ }, [api])+ return list+}++// Over a server's page, which fills the rest of the window: which Tucano it is, the other+// servers, and the way back to this computer's (src/main/servers.ts keeps BAR px for it).+export function ServerBar(): ReactNode {+ const servers = useServers()+ const on = servers.find((s) => s.open)+ if (!on) return null+ const api = window.tucano.servers!+ return (+ <div className="server-bar">+ <Icon name="globe" size={14} />+ <span className="server-bar__name">+ {L('Tucano em', 'Tucano at')} <strong>{on.name}</strong>+ </span>+ <span className="grow" />+ {servers+ .filter((s) => !s.open)+ .map((s) => (+ <button key={s.id} className="btn btn--ghost btn--sm" onClick={() => api.open(s.id)}>+ {s.name}+ </button>+ ))}+ <button className="btn btn--sm" onClick={() => api.local()}>+ <Icon name="laptop" size={14} /> {L('Voltar pra este computador', 'Back to this computer')}+ </button>+ </div>+ )+}diff --git a/src/renderer/src/components/Workspaces.tsx b/src/renderer/src/components/Workspaces.tsxindex 3456cd2..ea30493 100644--- a/src/renderer/src/components/Workspaces.tsx+++ b/src/renderer/src/components/Workspaces.tsx@@ -3,6 +3,7 @@ import { L } from '../../../shared/lang'import { sortWorkspaces, workspaceLabel, type WorkspaceList } from '../../../shared/workspaces'import { openDialog, useStore } from '../store'import { Icon } from './ui'+import { useServers } from './Servers'export function useWorkspaceList(): { list: WorkspaceList | null; error: string } {const [list, setList] = useState<WorkspaceList | null>(null)@@ -23,6 +24,7 @@ export function WorkspaceSelector(): ReactNode {const { list, error: loadError } = useWorkspaceList()const selectedId = list?.selectedconst workspaces = sortWorkspaces(list?.workspaces)+ const servers = useServers()const [open, setOpen] = useState(false)const [busy, setBusy] = useState(false)const [error, setError] = useState('')@@ -72,6 +74,13 @@ export function WorkspaceSelector(): ReactNode {{!!w.unread && <span className="badge badge--soft" title={L('Não lidas', 'Unread')}>{w.unread}</span>}</>}</button>)}+ {servers.length > 0 && <>+ <div className="workspace-picker__head workspace-picker__head--servers"><span className="muted small">{L('Servidores', 'Servers')}</span></div>+ {servers.map((s) => <button key={s.id} className="menu__item" role="menuitemradio" aria-checked={s.open} disabled={busy} onClick={() => { setOpen(false); window.tucano.servers!.open(s.id) }}>+ <span className="workspace-picker__check" aria-hidden="true"><Icon name="globe" size={14} /></span>+ <span className="grow">{s.name}</span>+ </button>)}+ </>}{(error || loadError) && <p className="field__error" role="alert">{error || loadError}</p>}</div>}</div>diff --git a/src/renderer/src/main.tsx b/src/renderer/src/main.tsxindex 281a3ee..6b312e6 100644--- a/src/renderer/src/main.tsx+++ b/src/renderer/src/main.tsx@@ -2,6 +2,7 @@ import { StrictMode } from 'react'import { createRoot } from 'react-dom/client'import type { ReactNode } from 'react'import { App } from './App'+import { ServerBar } from './components/Servers'import { start, useStore } from './store'import '@fontsource-variable/inter/opsz.css'import './styles.css'@@ -11,7 +12,12 @@ void start()// Switching the language draws everything again, in the new one.function Root(): ReactNode {const language = useStore((s) => s.settings.language)- return <App key={language} />+ return (+ <>+ <App key={language} />+ <ServerBar key={`bar-${language}`} />+ </>+ )}createRoot(document.getElementById('root')!).render(diff --git a/src/renderer/src/rpc.ts b/src/renderer/src/rpc.tsindex d6db392..5bfb442 100644--- a/src/renderer/src/rpc.ts+++ b/src/renderer/src/rpc.ts@@ -27,6 +27,15 @@ declare global {onUpdate: (cb: (state: UpdateState) => void) => voidcheckUpdates: () => voidinstallUpdate: () => void+ servers?: {+ // desktop only: Tucanos on servers, shown in this window over the app; open: the one on screen+ list: () => Promise<{ id: string; name: string; origin: string; open: boolean }[]>+ pair: (link: string) => Promise<'paired' | 'cancelled' | 'invalid' | 'unsafe'>+ open: (id: string) => void+ local: () => void // back to this computer's Tucano+ forget: (id: string) => Promise<boolean>+ onChanged: (cb: () => void) => void+ }}}}diff --git a/src/renderer/src/styles.css b/src/renderer/src/styles.cssindex d816adb..03d29c5 100644--- a/src/renderer/src/styles.css+++ b/src/renderer/src/styles.css@@ -8282,3 +8282,10 @@ button.wk-pill.is-on { box-shadow: 0 0 0 1.5px var(--k); background: color-mix(i.catalog__card .btn {flex: none;}++/* Over a server's page (Servers.tsx): the window's top 40 px stay the app's. */+.server-bar { position: fixed; inset: 0 0 auto 0; height: 40px; z-index: 1000; display: flex; align-items: center; gap: 8px; padding: 0 12px; background: var(--panel); border-bottom: 1px solid var(--border); -webkit-app-region: drag; font-size: 13px; }+.server-bar button { -webkit-app-region: no-drag; }+[data-os='mac'] .server-bar { padding-left: 84px; }+.server-bar__name { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.workspace-picker__head--servers { margin-top: 6px; border-top: 1px solid var(--border); padding-top: 8px; }diff --git a/src/server/index.ts b/src/server/index.tsindex 9c722f6..76a8cb6 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -20,6 +20,7 @@ import { ARTIFACT_CSP, BASE_HEADERS, clientIp, decodedPath, Limiter, PAGE_HEADERimport { Preview } from './preview'import { vault } from './vault'import { verifyLocalUrl } from '../core/local-paths'+import { pairingLink } from '../shared/servers'import { INSECURE_CONTEXT_SHIM } from './web-shim'const dataDir = process.env['TUCANO_DATA'] || join(homedir(), '.tucano-server')@@ -41,8 +42,10 @@ const publicUrl = (process.env['TUCANO_URL'] || `http://${host === '0.0.0.0' ||// `server.js link`: the one place the token is printed. The log never has it, since logs// get kept, shipped and pasted into issues.+// The second line pairs the desktop app or the phone (Settings › Servers, or a QR code of it).if (process.argv[2] === 'link') {console.log(`${publicUrl}/?token=${token}`)+ console.log(pairingLink({ origin: publicUrl, token }))process.exit(0)}// The secrets (Telegram, GitHub, connector keys) are sealed with this key; on adiff --git a/src/shared/servers.ts b/src/shared/servers.tsnew file mode 100644index 0000000..59ea470--- /dev/null+++ b/src/shared/servers.ts@@ -0,0 +1,59 @@+// A Tucano on a server, opened from this app: the link that pairs it, and what belongs to it.+//+// tucano://connect?url=https://ana.example.com&token=… (`server.js link` prints it)++export interface Pairing {+ origin: string // https://ana.example.com, nothing after it+ token: string+}++// A link from anywhere (a chat, a web page) can ask the system to open this one, so it's read+// strictly: only https, or http on this machine's loopback (a server under test), and a token+// of the shape the server makes. Anything else is not a pairing.+export function parsePairing(link: string): Pairing | null {+ let u: URL+ try {+ u = new URL(link.trim())+ } catch {+ return null+ }+ if (u.protocol !== 'tucano:' || u.hostname !== 'connect') return null+ const token = u.searchParams.get('token') ?? ''+ if (!/^[A-Za-z0-9_-]{16,256}$/.test(token)) return null+ let server: URL+ try {+ server = new URL(u.searchParams.get('url') ?? '')+ } catch {+ return null+ }+ const loopback = server.hostname === '127.0.0.1' || server.hostname === 'localhost'+ if (server.protocol !== 'https:' && !(server.protocol === 'http:' && loopback)) return null+ if (server.username || server.password) return null+ return { origin: server.origin, token }+}++// The link that pairs it again (`server.js link` prints the first one).+export const pairingLink = (p: Pairing): string => `tucano://connect?url=${encodeURIComponent(p.origin)}&token=${encodeURIComponent(p.token)}`++// Where a server's window may go: its own pages, and nothing else.+export function onServer(url: string, origin: string): boolean {+ try {+ return new URL(url).origin === origin+ } catch {+ return false+ }+}++// One of a server's preview addresses (src/server/preview.ts): https://5173-ana.example.com for https://ana.example.com.+export function isPreviewOf(url: string, origin: string): boolean {+ try {+ const u = new URL(url)+ const host = new URL(origin).host+ return u.protocol === 'https:' && new RegExp(`^\\d{2,5}-${host.replace(/[.]/g, '\\.')}$`, 'i').test(u.host)+ } catch {+ return false+ }+}++// What the person sees for a server: its address, without the scheme.+export const serverName = (origin: string): string => origin.replace(/^https?:\/\//, '')diff --git a/test/servers.test.ts b/test/servers.test.tsnew file mode 100644index 0000000..545cca3--- /dev/null+++ b/test/servers.test.ts@@ -0,0 +1,53 @@+import { describe, expect, it } from 'vitest'+import { isPreviewOf, onServer, pairingLink, parsePairing, serverName } from '../src/shared/servers'++const token = 'Zx9-abc_DEF0123456789xyzQ'++describe('pairing with a Tucano on a server', () => {+ it('reads the link `server.js link` prints, down to the origin', () => {+ expect(parsePairing(`tucano://connect?url=https://ana.example.com&token=${token}`)).toEqual({ origin: 'https://ana.example.com', token })+ expect(parsePairing(`tucano://connect?url=${encodeURIComponent('https://ana.example.com/some/path?x=1')}&token=${token}`)?.origin).toBe('https://ana.example.com')+ // A server under test, on this machine.+ expect(parsePairing(`tucano://connect?url=http://127.0.0.1:7400&token=${token}`)?.origin).toBe('http://127.0.0.1:7400')+ })++ it('refuses what a page could send to take the app somewhere else', () => {+ for (const bad of [+ `tucano://connect?url=http://ana.example.com&token=${token}`, // plain http on the internet+ `tucano://connect?url=file:///etc/passwd&token=${token}`,+ `tucano://connect?url=javascript:alert(1)&token=${token}`,+ `tucano://connect?url=https://user:[email protected]&token=${token}`,+ `tucano://artifact/x?url=https://ana.example.com&token=${token}`, // the app's own pages, not a pairing+ `https://connect?url=https://ana.example.com&token=${token}`,+ 'tucano://connect?url=https://ana.example.com&token=short',+ 'tucano://connect?url=https://ana.example.com&token=has spaces and <tags>',+ 'tucano://connect?url=https://ana.example.com',+ 'not a link'+ ])+ expect(parsePairing(bad), bad).toBeNull()+ })++ it('makes the same link again', () => {+ const p = { origin: 'https://ana.example.com', token }+ expect(parsePairing(pairingLink(p))).toEqual(p)+ })++ it("keeps a server's window on its own pages", () => {+ const o = 'https://ana.example.com'+ expect(onServer('https://ana.example.com/#/agent/1', o)).toBe(true)+ expect(onServer('https://bruno.example.com/', o)).toBe(false)+ expect(onServer('http://ana.example.com/', o)).toBe(false)+ expect(onServer('file:///etc/hosts', o)).toBe(false)+ expect(onServer('garbage', o)).toBe(false)+ expect(serverName(o)).toBe('ana.example.com')+ })++ it("knows a server's preview addresses from anything else", () => {+ const o = 'https://ana.example.com'+ expect(isPreviewOf('https://5173-ana.example.com/app', o)).toBe(true)+ expect(isPreviewOf('https://5173-bruno.example.com/', o)).toBe(false)+ expect(isPreviewOf('http://5173-ana.example.com/', o)).toBe(false)+ expect(isPreviewOf('https://5173-anaxexample.com/', o)).toBe(false)+ expect(isPreviewOf('https://evil-ana.example.com/', o)).toBe(false)+ })+})