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.

Keep agents, connectors and memory apart in workspaces (#63)

Brunoa549562bd9c9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fbddfa5..bee891e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,12 +12,14 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht
> - **A resposta começa enquanto você digita.** O Tucano já abre o Claude Code de quem vai responder: o router escolhe quem responde num canal em 1,5 s em vez de 2,8 s, e numa DM parada há mais de 5 minutos a resposta começa meio segundo antes.
> - **Um agente só acorda outro quando precisa.** Quando um agente menciona outro na resposta, o router lê e chama só quem tem algo a fazer: um agradecimento ou um “combinado” não acordam ninguém. Na dúvida, chama.
> - **O app abre fora do instalador mesmo com uma versão estranha.** O atualizador, que nem é usado ali, conferia a versão ao abrir e derrubava o app.
+> - **Workspaces.** Empresa e emprego, por exemplo, em workspaces separados: cada um com seus agentes, conversas, conectores e credenciais, memórias e rotinas, e um não vê o outro. Você troca pelo nome no topo da barra lateral, que mostra as não lidas e aprovações dos outros; as rotinas de todos continuam rodando. Ao criar, você marca o que levar do workspace atual (configurações gerais, contexto, agentes, canais, skills, conectores e credenciais, rotinas); duplicar leva tudo isso, nunca as conversas nem as memórias.
> - **Agentes no Grok.** Um agente pode rodar no Grok CLI, com a assinatura do grok.com, como roda no Cursor CLI. Cada resposta usa uma pasta própria: os seus plugins, skills e hooks não carregam, e só as ferramentas do Tucano ficam à mão.
> - **Um conector que falha diz por quê.** O passo da resposta mostra o motivo em vermelho, e o agente recebe o mesmo motivo pra explicar, em vez de um ✗ sem nada.
> - **Os passos mostram o que o agente fez.** Cada consulta mostra o SQL ou o que foi pedido, e o que voltou ("120 linhas"); um comando mostra o comando inteiro, e o SQL quando roda um; uma skill diz qual foi lida. Tudo aparece enquanto o agente trabalha, sem nenhum segredo na tela.
### Added
+- **Workspaces.** Keep a company and a day job, say, apart: each workspace has its own agents, conversations, connectors and credentials, memories, routines, engine folders and browser sessions, and none sees another's. Switch from the name at the top of the sidebar, which shows the others' unread and pending approvals (and nothing else of them); every workspace's routines and triggers keep running while another is on screen, each on its own webhook and git proxy ports. Creating one asks what to bring from the workspace you're in, each ticked on its own: the general settings (your name, language, router and memory models, limits, quiet hours), the context, agents, channels, skills, connectors with their credentials, routines. What depends on something left behind comes without it (agents without connectors have no grants), and with nothing ticked it starts empty with the introduction. Duplicating ticks everything; never messages, memories or usage. Settings › General names the workspace apart from what the agents call you, and its Danger area deletes a workspace with all its data, Claude Code's transcripts of its agents included. The folder you had is the default workspace, unchanged, and keeps Telegram and opening at login. It's a separation of data, not an OS sandbox: an agent on your computer still reaches the same disk. Thanks [@b7s](https://github.com/b7s)! ([#63](https://github.com/eduwxyz/tucano/pull/63))
- **Agents on Grok.** An agent can run on the [Grok CLI](https://x.ai/cli) with a grok.com subscription, the way it runs on Cursor CLI: sign in with `grok login` and pick a Grok model. Each reply runs in a folder and a home of its own, so your MCP servers, skills, hooks and plugins (Grok's and the ones installed for Claude Code or Cursor) don't load, Grok's own shell and files stay off, and Tucano's tools are the only ones it has. An `XAI_API_KEY` in the environment is set aside when grok.com is signed in, so the subscription isn't billed per token. The official installer is macOS and Linux. Thanks [@matheus-apolonio](https://github.com/matheus-apolonio)! ([#87](https://github.com/eduwxyz/tucano/pull/87))
### Changed
diff --git a/docs/workspaces.md b/docs/workspaces.md
new file mode 100644
index 0000000..96a9a0a
--- /dev/null
+++ b/docs/workspaces.md
@@ -0,0 +1,84 @@
+# Desktop workspaces (in progress)
+
+A workspace keeps its own agents, conversations, memory, connector credentials,
+engine working directories, browser profiles and routines. Click the logo/name
+at the top of the sidebar to switch or use the **+** beside the gear to create a workspace. Creation uses
+the same setup as a fresh installation; it does not copy another workspace's data.
+
+Use the gear icon in the workspace menu to open **Manage workspaces**. It lists
+every workspace with create, duplicate and delete actions. You can also open it
+from **Getting started > Explore workspaces**; that item is marked done when the
+manager opens.
+
+Each row also has a pause/resume control. It uses the same per-workspace pause
+as the sidebar: no new agent work or routines start, but running work can finish.
+The button at the top pauses all workspaces, or resumes them when all available
+workspaces are paused. Unavailable cores are reported rather than started as a
+side effect of pausing. Pause state is saved in each workspace's own database.
+
+Creating and duplicating are one form: a name, and what to bring from a workspace,
+each part ticked on its own: the general settings (the person's name, language,
+router and memory models, limits, quiet hours, voice), the context, agents,
+channels, skills, connectors with their encrypted credentials (and GitHub's), and
+routines. Creating starts from the workspace on screen with only the general
+settings ticked; with nothing ticked it starts empty, with the introduction.
+Duplicating a row of the manager ticks everything and suggests the source name
+with the next available count, such as `Company (2)`. The app opens the new
+workspace once it's made.
+What depends on something left behind comes without it: agents without the
+connectors have no grants, a skill of specific agents comes archived without
+them, a routine comes only with its agent and place (and a connector it polls).
+With its agents, a set-up workspace skips the introduction; without, the
+introduction starts from what came. Never copied: messages, memories,
+conversation summaries, approvals, usage history, artifacts, running services,
+computer files, browser sessions, nor the extra Claude Code/Codex accounts (their
+sign-ins live in the source's folder and the keychain): agents use the usual sign-in.
+Lent folders and linked skills remain references to the same external files.
+Changes to those external files are not isolated by making a copy.
+
+Enabled routines remain enabled and run independently in the copy, with fresh
+schedules and webhook tokens. Telegram credentials and temporary authentication
+state are not copied; Telegram remains default-only. Some OAuth connectors may
+need reauthorization. Duplicating never changes the original workspace.
+
+The original data folder is the default workspace and stays where it was. New
+workspace folders use UUIDv7 identities under `workspaces/`, with a main-owned
+`workspaces.json` registry. Every registered workspace starts its own core when
+the app opens, migrates its database before work starts, and keeps its routines
+running even when another workspace is on screen. Explicit pause and quiet hours
+still apply. Closing the app entirely stops all cores.
+
+Theme is app-wide, not per workspace. Changing it in any workspace updates all
+running workspaces, and new or duplicated workspaces inherit it. The choice
+survives restarts; on the first upgrade, the default workspace's existing theme
+becomes the shared preference. Server mode keeps its single-workspace settings.
+
+The selector shares only names, unread counts and pending approval counts.
+Conversations, memory and credentials are not combined. Default webhook/git
+ports remain 47717/47718; other workspaces have persistent separate assignments.
+A port already taken (another Tucano open, say) is logged and that workspace keeps
+running without it: a call there reaches a server that doesn't know its tokens.
+
+At the end of **Settings > General**, the **Danger area** contains backup controls
+and workspace deletion. Deletion requires an OS confirmation dialog and removes
+that workspace's data, including its local backups and the transcripts Claude Code
+keeps for its agents in `~/.claude/projects`. Copy a backup outside the
+workspace before confirming. External project folders and other workspaces are
+kept. The default workspace is protected: it cannot be deleted from Settings,
+the manager or the backend. Its backup and duplication actions remain available.
+
+## Limits of this implementation slice
+
+- Workspace separation is not an OS sandbox or protection against hostile agents.
+ Folder restrictions, reviewed repository import and channel project resources
+ are planned separately and are not implemented yet.
+- Claude Code/OpenCode sign-ins remain machine-wide. Workspace separation does
+ not create different provider accounts or constrain network/MCP/desktop tools.
+- Telegram and the app's login-at-startup preference belong to the default
+ workspace. Every workspace starts together at application startup.
+ In other workspaces, the Telegram settings notice shows the default workspace's
+ name as a link that switches there. The link is hidden in the default workspace.
+- Server mode is unchanged: one workspace per `TUCANO_DATA`, with no desktop
+ workspace selector or registry management.
+- Failed cores can be retried from the selector. Automatic crash backoff and
+ comprehensive multi-platform/native lifecycle verification are still pending.
diff --git a/src/core/db.ts b/src/core/db.ts
index 46de774..20f736d 100644
--- a/src/core/db.ts
+++ b/src/core/db.ts
@@ -1,5 +1,43 @@
import { DatabaseSync } from 'node:sqlite'
-import { CACHE_READ_WEIGHT, routineCap, type Agent, type AgentApp, type AgentColor, type Approval, type ApprovalState, type Artifact, type ArtifactKind, type Author, type Connector, type ConnectorAuth, type ConnectorTool, type Conversation, type Effort, type LentFolder, type Memory, type MemoryMode, type MemoryState, type Message, type Receipt, type Routine, type RoutineRun, type Run, type Settings, type Skill, type SkillVersion, type ThreadSummary, type ToolClass, type Trigger } from '../shared/types'
+import { randomUUID } from 'node:crypto'
+import { existsSync, mkdirSync, renameSync, rmSync } from 'node:fs'
+import { ALL_PARTS, GENERAL_SETTINGS, WORKSPACE_PARTS, type WorkspaceParts } from '../shared/workspaces'
+import { dirname, join } from 'node:path'
+import {
+ CACHE_READ_WEIGHT,
+ nextRun,
+ routineCap,
+ type Agent,
+ type AgentApp,
+ type AgentColor,
+ type Approval,
+ type ApprovalState,
+ type Artifact,
+ type ArtifactKind,
+ type Author,
+ type Connector,
+ type ConnectorAuth,
+ type ConnectorTool,
+ type Conversation,
+ type Effort,
+ type LentFolder,
+ type Memory,
+ type MemoryMode,
+ type MemoryState,
+ type Message,
+ type Receipt,
+ type Routine,
+ type RoutineRun,
+ type Run,
+ type Settings,
+ type Skill,
+ type SkillVersion,
+ type ThreadSummary,
+ type ToolClass,
+ type Trigger
+} from '../shared/types'
+
+const JEV_KEY = 'typesafe:key' // jev.ts's JEV_SECRET: the router's key goes with the general settings
// Each entry runs once, in order; PRAGMA user_version records how far we got.
const MIGRATIONS = [
@@ -256,6 +294,17 @@ const MIGRATIONS = [
`,
`
ALTER TABLE conversations ADD COLUMN threads INTEGER;
+ `,
+ `
+ CREATE TABLE IF NOT EXISTS message_notifications (
+ message_id TEXT NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
+ phase TEXT NOT NULL,
+ unread INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY (message_id, phase)
+ );
+ INSERT OR IGNORE INTO message_notifications (message_id, phase)
+ SELECT id, COALESCE(json_extract(run, '$.status'), 'message') FROM messages;
+ CREATE INDEX IF NOT EXISTS message_notifications_unread ON message_notifications (message_id) WHERE unread = 1;
`
]
@@ -273,10 +322,11 @@ export class Db {
// "no agents", since someone may have deleted them all.
created = false
- constructor(file: string) {
+ constructor(private file: string) {
this.db = new DatabaseSync(file)
this.db.exec('PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;')
- this.migrate()
+ try { this.migrate(file) }
+ catch (error) { this.db.close(); throw error }
}
close(): void {
@@ -288,9 +338,89 @@ export class Db {
this.db.exec(`VACUUM INTO '${file.replace(/'/g, "''")}'`)
}
- private migrate(): void {
+ // Snapshot the live DB, then sanitize only the copy. Publish it only after
+ // VACUUM removes deleted history from its pages; no engine/browser files copy.
+ // The extra Claude Code and Codex logins stay too (their folders, and the Mac's keychain,
+ // are the source's): the copy's agents use the usual login.
+ duplicateTo(file: string, name: string, parts: WorkspaceParts = ALL_PARTS): void {
+ if (existsSync(file)) throw new Error('Workspace destination already exists')
+ // Keep the unsanitized snapshot with its source, not in the new workspace.
+ // A crash before sanitizing must not leave source memories in the copy.
+ const stagingDir = this.file === ':memory:' ? dirname(file) : join(dirname(this.file), 'backups')
+ mkdirSync(stagingDir, { recursive: true, mode: 0o700 })
+ const staging = join(stagingDir, `.workspace-copy-${randomUUID()}.preparing`)
+ let copy: Db | undefined
+ try {
+ this.backupTo(staging)
+ copy = new Db(staging)
+ const target = copy
+ target.db.exec('PRAGMA secure_delete = ON')
+ target.tx(() => {
+ target.db.exec(`
+ DELETE FROM messages;
+ DELETE FROM memories;
+ DELETE FROM approvals;
+ DELETE FROM receipts;
+ DELETE FROM artifacts;
+ DELETE FROM services;
+ UPDATE conversations SET summary = NULL, summary_until = NULL, summary_at = NULL;
+ DELETE FROM settings WHERE key IN ('quota', 'telegram', 'accounts');
+ UPDATE agents SET account = NULL, fallback_account = NULL;
+ DELETE FROM secrets WHERE key LIKE 'telegram:%' OR key = 'github:proxy-key' OR key LIKE '%:oauth_verifier';
+ `)
+ target.keepOnly(parts)
+ const setup = target.db.prepare("SELECT value FROM settings WHERE key = 'onboarding'").get() as { value: string } | undefined
+ const onboarding = setup ? JSON.parse(setup.value) as Settings['onboarding'] : undefined
+ // With its agents, a set-up workspace needs no introduction; without, it starts from what came.
+ const done = parts.agents && onboarding?.done !== false
+ target.setSettings({ workspaceLabel: name, onboarding: done ? { ...onboarding, done: true, workspaceManagerSeen: undefined } : { done: false, ...(parts.general ? { carried: true } : {}) } })
+ for (const r of target.routines()) {
+ const trigger: Trigger | undefined = r.trigger?.kind === 'webhook' ? { kind: 'webhook', token: randomUUID().replaceAll('-', '') }
+ : r.trigger?.kind === 'poll' ? { kind: 'poll', connectorId: r.trigger.connectorId, tool: r.trigger.tool, args: r.trigger.args, everyMinutes: r.trigger.everyMinutes } : undefined
+ target.saveRoutine({ ...r, lastAt: undefined, lastMessageId: undefined, trigger, nextAt: r.enabled && !trigger ? nextRun(r.schedule, Date.now()) : undefined })
+ }
+ })
+ target.db.exec('VACUUM; PRAGMA wal_checkpoint(TRUNCATE)')
+ target.close()
+ copy = undefined
+ renameSync(staging, file)
+ } finally {
+ copy?.close()
+ for (const path of [staging, `${staging}-wal`, `${staging}-shm`]) rmSync(path, { force: true })
+ }
+ }
+
+ // A copy keeps only what was picked to come along; what depends on something left behind goes,
+ // or comes without it: agents without connectors have no grants, a skill of agents left behind
+ // comes archived (with no agents it would apply to everyone), a routine needs its agent and place.
+ private keepOnly(parts: WorkspaceParts): void {
+ if (WORKSPACE_PARTS.every((p) => parts[p])) return
+ const kept = new Set(['seenVersion', 'theme', 'onboarding', ...(parts.general ? GENERAL_SETTINGS : []), ...(parts.context ? ['context'] : []), ...(parts.channels ? ['channelLayout', 'folded'] : [])])
+ for (const { key } of this.db.prepare('SELECT key FROM settings').all() as { key: string }[]) if (!kept.has(key)) this.db.prepare('DELETE FROM settings WHERE key = ?').run(key)
+ if (!parts.general) this.db.prepare('DELETE FROM secrets WHERE key = ?').run(JEV_KEY)
+ if (!parts.connectors) {
+ this.db.exec('DELETE FROM connectors; UPDATE agents SET grants = \'{}\', auto_approve = \'[]\'')
+ this.db.prepare('DELETE FROM secrets WHERE key <> ?').run(JEV_KEY) // the connectors' keys and logins, and GitHub's
+ }
+ if (!parts.agents) this.db.exec("DELETE FROM members; DELETE FROM conversations WHERE kind = 'dm'; DELETE FROM agents")
+ if (!parts.channels) this.db.exec("DELETE FROM conversations WHERE kind <> 'dm'")
+ if (!parts.skills) this.db.exec('DELETE FROM skill_versions; DELETE FROM skills')
+ else if (!parts.agents) this.db.exec("UPDATE skills SET state = 'archived' WHERE agents <> '[]'")
+ if (!parts.routines) this.db.exec('DELETE FROM routines')
+ const connectors = new Set(this.connectors().map((c) => c.id))
+ for (const r of this.routines())
+ if (!this.agent(r.agentId) || !this.conversation(r.conversationId) || (r.trigger?.kind === 'poll' && !connectors.has(r.trigger.connectorId))) this.removeRoutine(r.id)
+ }
+
+ private migrate(file: string): void {
const { user_version } = this.db.prepare('PRAGMA user_version').get() as { user_version: number }
this.created = user_version === 0
+ // A copy from before the update, among the daily ones (and pruned with them).
+ if (user_version > 0 && user_version < MIGRATIONS.length && file !== ':memory:') {
+ const backups = join(dirname(file), 'backups')
+ mkdirSync(backups, { recursive: true })
+ this.backupTo(join(backups, `tucano-${new Date().toISOString().slice(0, 16).replace(/[:T]/g, '-')}-schema-${user_version}.db`))
+ }
for (let v = user_version; v < MIGRATIONS.length; v++) {
this.tx(() => {
this.db.exec(MIGRATIONS[v]!)
@@ -401,7 +531,14 @@ export class Db {
// ---------- conversations ----------
conversations(): Conversation[] {
- const rows = this.db.prepare('SELECT * FROM conversations ORDER BY created_at').all() as Row[]
+ // Only the unread rows are read (a partial index): a conversation with years of messages costs nothing here.
+ const rows = this.db
+ .prepare(
+ `SELECT c.*, COALESCE(u.n, 0) AS unread FROM conversations c
+ LEFT JOIN (SELECT m.conversation_id AS id, COUNT(*) AS n FROM message_notifications n JOIN messages m ON m.id = n.message_id WHERE n.unread = 1 GROUP BY m.conversation_id) u ON u.id = c.id
+ ORDER BY created_at`
+ )
+ .all() as Row[]
const members = this.db.prepare('SELECT conversation_id, agent_id FROM members').all() as { conversation_id: string; agent_id: string }[]
return rows.map((r) => ({
id: str(r['id']),
@@ -413,7 +550,8 @@ export class Db {
summaryUntil: r['summary_until'] ? Number(r['summary_until']) : undefined,
summaryAt: r['summary_at'] ? Number(r['summary_at']) : undefined,
...(r['wiki_capture'] === 0 ? { wikiCapture: false } : {}),
- ...(r['threads'] === 1 ? { threads: true } : {})
+ ...(r['threads'] === 1 ? { threads: true } : {}),
+ unread: Number(r['unread'])
}))
}
@@ -484,6 +622,28 @@ export class Db {
// ---------- messages ----------
+ markRead(conversationId: string): void {
+ this.db.prepare('UPDATE message_notifications SET unread = 0 WHERE unread = 1 AND message_id IN (SELECT id FROM messages WHERE conversation_id = ?)').run(conversationId)
+ }
+
+ unread(conversationId?: string): number {
+ const sql = 'SELECT COUNT(*) AS n FROM message_notifications n JOIN messages m ON m.id = n.message_id WHERE n.unread = 1'
+ const row = (conversationId ? this.db.prepare(`${sql} AND m.conversation_id = ?`).get(conversationId) : this.db.prepare(sql).get()) as { n: number }
+ return Number(row.n)
+ }
+
+ // True when this made the conversation's unread count go up.
+ recordActivity(message: Message, viewing: string | null): boolean {
+ if (message.author.kind !== 'agent' && message.author.kind !== 'routine') return false
+ const phase = message.run?.status ?? 'message'
+ if (phase !== 'message' && !['working', 'done', 'failed', 'limit_reached', 'waiting_input', 'waiting_approval'].includes(phase)) return false
+ // A running reply counts once. If it was read while running, its completion
+ // is new content, but repeated terminal events and deltas must not count again.
+ const unread = message.conversationId !== viewing && (phase === 'working' || phase === 'message' || this.unread(message.conversationId) === 0)
+ const r = this.db.prepare('INSERT OR IGNORE INTO message_notifications (message_id, phase, unread) VALUES (?, ?, ?)').run(message.id, phase, unread ? 1 : 0)
+ return unread && Number(r.changes) > 0
+ }
+
private toMessage(r: Row): Message {
const kind = str(r['author_kind'])
const author: Author =
diff --git a/src/core/engines/claude.ts b/src/core/engines/claude.ts
index bb6268f..be1df66 100644
--- a/src/core/engines/claude.ts
+++ b/src/core/engines/claude.ts
@@ -180,7 +180,14 @@ export function claudeEnv(p: Provider, account?: string): NodeJS.ProcessEnv {
// Where Claude Code keeps a session: its config folder, then the working folder with every
// character other than a letter or digit turned into "-".
-export const claudeProjectDir = (configDir: string, cwd: string): string => join(configDir, 'projects', cwd.replace(/[^a-zA-Z0-9]/g, '-'))
+// As Claude Code names it: past 200 characters, cut there and followed by a hash of the whole path.
+export const claudeProjectDir = (configDir: string, cwd: string): string => {
+ const name = cwd.replace(/[^a-zA-Z0-9]/g, '-')
+ if (name.length <= 200) return join(configDir, 'projects', name)
+ let hash = 0
+ for (let i = 0; i < cwd.length; i++) hash = ((hash << 5) - hash + cwd.charCodeAt(i)) | 0
+ return join(configDir, 'projects', `${name.slice(0, 200)}-${Math.abs(hash).toString(36)}`)
+}
const configDirOf = (account?: string): string => account || process.env['CLAUDE_CONFIG_DIR'] || join(homedir(), '.claude')
// A process kept open after a reply waits this long for the next one, and only this many wait at
@@ -211,6 +218,7 @@ export function claudeEngine(bin: () => string | undefined, provider: () => Prom
const shapes = new Map<string, TurnShape>() // session id → the settings of its last turn, to start it again
const spares = new Map<string, { cli: LiveCli; timer: NodeJS.Timeout; at: number }>() // by flags and provider
+ const removing = new Set<Promise<void>>() // session files waiting for their process to exit
const close = (id: string): void => {
const k = kept.get(id)
if (!k) return
@@ -364,8 +372,13 @@ export function claudeEngine(bin: () => string | undefined, provider: () => Prom
/* not empty */
}
}
- if (open?.alive) void open.exited().then(remove)
- else remove()
+ if (!open?.alive) return remove()
+ const gone = open.exited().then(remove)
+ removing.add(gone)
+ void gone.finally(() => removing.delete(gone))
+ },
+ async settle() {
+ await Promise.all([...removing])
},
// Only the exact folders of the agents under workDir, in the usual config folder and in each
// account's: Claude Code's folder names are lossy, so a prefix could take someone else's.
diff --git a/src/core/engines/types.ts b/src/core/engines/types.ts
index 9d330de..97b573b 100644
--- a/src/core/engines/types.ts
+++ b/src/core/engines/types.ts
@@ -54,6 +54,7 @@ export interface Engine {
release?(sessionId: string): void // a session that won't be resumed: its process and its file go
clean?(workDir: string, accountDirs?: string[]): void // sessions left from an earlier run of the app, by agents under workDir
dispose?(): void // the app is quitting: processes kept open close
+ settle?(): Promise<void> // the files of sessions let go are gone (their processes write on their way out)
// Starting the CLI takes about a second before any model call; these do it ahead of time.
warm?(turn: TurnShape): void // a process ready for the next turn with these settings and no session (the router's)
rewarm?(sessionId: string): void // the session's process again, if it closed, ready for its next turn
diff --git a/src/core/github.ts b/src/core/github.ts
index a924c28..9a53bf0 100644
--- a/src/core/github.ts
+++ b/src/core/github.ts
@@ -12,6 +12,7 @@ import { L } from '../shared/lang'
import type { Agent } from '../shared/types'
import type { Db } from './db'
import type { Secrets } from './secrets'
+import { workspacePorts } from './ports'
export const GIT_PROXY_PORT = 47_718
export const GITHUB = 'github' // the approvals' connector id for abrir_pr
@@ -100,7 +101,7 @@ export class GitHub {
}
}
- listen(port = GIT_PROXY_PORT): Server {
+ listen(port = workspacePorts().git): Server {
this.server = createServer((req, res) => void this.proxy(req, res).catch((e: unknown) => send(res, 502, `Tucano: ${e instanceof Error ? e.message : String(e)}\n`)))
this.server.on('error', (e) => console.error(`[github] porta ${port}:`, e.message))
this.server.listen(port, '127.0.0.1')
@@ -151,7 +152,7 @@ export class GitHub {
// The git config that sends an agent's GitHub traffic through the proxy.
gitRemote(agentId: string): string | undefined {
const t = this.agentToken(agentId)
- return t && `http://host.docker.internal:${GIT_PROXY_PORT}/git/${t}/`
+ return t && `http://host.docker.internal:${workspacePorts().git}/git/${t}/`
}
// The folder lent to this agent whose repository is `repo`, and whether it may change it.
@@ -272,4 +273,3 @@ function read(req: IncomingMessage, max: number): Promise<Buffer> {
req.on('error', fail)
})
}
-
diff --git a/src/core/index.ts b/src/core/index.ts
index 465cf4f..40a4622 100644
--- a/src/core/index.ts
+++ b/src/core/index.ts
@@ -58,12 +58,16 @@ import { findLocalSkills } from './local-skills'
import { Routines } from './routines'
import { Runner } from './runs'
import { agentFromDraft, availableModels, tucaAgent, tucaHello } from './tuca'
-import { seed } from './seed'
+import { initializeWorkspace } from './seed'
+import { workspacePorts } from './ports'
+import { isTheme, workspaceLabel, workspaceParts } from '../shared/workspaces'
const dataDir = process.env['TUCANO_DATA'] ?? join(process.cwd(), '.tucano')
const fake = process.env['TUCANO_FAKE_ENGINES'] === '1'
// Run by the server (src/server): no window, and the screens are in a browser elsewhere.
const serverMode = process.env['TUCANO_SERVER'] === '1'
+const runtimePorts = workspacePorts()
+const defaultWorkspace = process.env['TUCANO_DEFAULT_WORKSPACE'] !== '0'
mkdirSync(dataDir, { recursive: true })
const db = new Db(join(dataDir, 'tucano.db'))
@@ -71,14 +75,13 @@ const codexHome = join(dataDir, 'codex-home')
mkdirSync(join(codexHome, '.codex'), { recursive: true })
// Until the settings are read, the language of a new install: the Mac's.
setLang(langOf(process.env['TUCANO_LOCALE']))
-// A new install starts empty and the introduction creates the first agent; the
-// fake engines (tests, screenshots) and TUCANO_SEED=1 get the sample team.
-if (db.created) {
- if (process.env['TUCANO_SEED'] === '1' || (fake && process.env['TUCANO_SEED'] !== '0')) seed(db)
- else db.setSettings({ onboarding: { done: false } })
- // A new install has nothing new to show: the news start with the next update.
- if (process.env['TUCANO_VERSION']) db.setSettings({ seenVersion: process.env['TUCANO_VERSION'] })
-}
+initializeWorkspace(db)
+// A workspace made from the switcher starts with the name it was given there.
+if (db.created && process.env['TUCANO_WORKSPACE_LABEL']) db.setSettings({ workspaceLabel: process.env['TUCANO_WORKSPACE_LABEL'] })
+const appTheme = process.env['TUCANO_THEME']
+if (!serverMode && isTheme(appTheme)) db.setSettings({ theme: appTheme })
+// A new install has nothing new to show: the news start with the next update.
+if (db.created && process.env['TUCANO_VERSION']) db.setSettings({ seenVersion: process.env['TUCANO_VERSION'] })
const interrupted = db.interruptStaleRuns()
if (interrupted) console.log(`[core] ${interrupted} run(s) marked as interrupted`)
@@ -226,10 +229,31 @@ const gatewayLists = new Map<EngineId, Promise<{ models: string[]; error?: strin
// ---------- ports ----------
const ports = new Set<MessagePortMain>()
+let viewing: string | null = null
+let closing = false
+// What the workspace switcher shows of this workspace: its name, whether it's paused, and two
+// counts. Coalesced: a reply streaming updates its message many times a second.
+let summaryTimer: NodeJS.Timeout | undefined
+let lastSummary = ''
+function workspaceSummary(): void {
+ summaryTimer ??= setTimeout(() => {
+ summaryTimer = undefined
+ const current = db.getSettings(DEFAULTS)
+ const summary = { type: 'workspace-summary', name: workspaceLabel(current), paused: !!current.paused, unread: db.unread(), approvals: db.approvals().filter((a) => a.state === 'pending').length }
+ const wire = JSON.stringify(summary)
+ if (wire !== lastSummary) process.parentPort.postMessage(summary)
+ lastSummary = wire
+ }, 250)
+}
function emit(event: CoreEvent): void {
+ const more = event.type === 'message' && db.recordActivity(event.message, viewing)
const wire: Wire = { event }
for (const p of ports) p.postMessage(wire)
toPhone(event)
+ // A new unread one: the sidebar's count goes up.
+ const conversation = more ? db.conversation(event.message.conversationId) : undefined
+ if (conversation) for (const p of ports) p.postMessage({ event: { type: 'conversation', conversation } } satisfies Wire)
+ if (['message', 'conversation', 'conversation_removed', 'approval', 'settings'].includes(event.type)) workspaceSummary()
}
// The phone gets each new approval and question as it happens (spec §19).
@@ -258,6 +282,8 @@ const notifyAll = (title: string, shortText: string, conversationId?: string, fu
// Asks the main process to do what only it can: open the browser or a folder, show a notification.
type ToMain =
+ | { type: 'theme'; theme: Settings['theme']; initial?: boolean }
+ | { type: 'ready' }
| { type: 'open'; url: string }
| { type: 'open_path'; path: string }
| { type: 'open_local'; path: string; how: 'open' | 'reveal' }
@@ -270,13 +296,66 @@ const toMain = (msg: ToMain): void =>
process.parentPort.postMessage(msg)
// The menu is the main process's: it follows the language picked here.
toMain({ type: 'lang', lang: db.getSettings(DEFAULTS).language })
+if (!serverMode && defaultWorkspace) toMain({ type: 'theme', theme: db.getSettings(DEFAULTS).theme, initial: true })
// Screenshots use Electron's Chromium, which lives in the main process.
const shots = new Map<string, { resolve: (b: Buffer) => void; reject: (e: Error) => void }>()
// Agents' browsers too (spec §24).
const pages = new Map<string, { resolve: (r: BrowserReply) => void; reject: (e: Error) => void }>()
process.parentPort.on('message', (e) => {
- const r = e.data as { type?: string; id: string; data?: unknown; error?: string; awake?: boolean; agentId?: string; shown?: boolean } | undefined
+ const r = e.data as { type?: string; id: string; data?: unknown; error?: string; awake?: boolean; agentId?: string; shown?: boolean; conversationId?: string | null; targetDir?: string; name?: string; theme?: unknown; paused?: unknown; parts?: unknown } | undefined
+ if (r?.type === 'workspace-pause') {
+ try {
+ if (closing || typeof r.paused !== 'boolean') throw new Error('Workspace cannot change pause state right now')
+ api.updateSettings({ patch: { paused: r.paused } })
+ process.parentPort.postMessage({ type: 'workspace-paused' })
+ } catch (error) {
+ process.parentPort.postMessage({ type: 'workspace-paused', error: error instanceof Error ? error.message : String(error) })
+ }
+ return
+ }
+ if (r?.type === 'workspace-theme' && isTheme(r.theme)) {
+ db.setSettings({ theme: r.theme })
+ emit({ type: 'settings', settings: settings() })
+ return
+ }
+ if (r?.type === 'duplicate-workspace') {
+ try {
+ if (closing || !r.targetDir || !r.name) throw new Error('Workspace cannot be duplicated right now')
+ mkdirSync(r.targetDir, { recursive: true, mode: 0o700 })
+ db.duplicateTo(join(r.targetDir, 'tucano.db'), r.name, r.parts === undefined ? undefined : workspaceParts(r.parts))
+ process.parentPort.postMessage({ type: 'workspace-duplicated' })
+ } catch (error) {
+ process.parentPort.postMessage({ type: 'workspace-duplicated', error: error instanceof Error ? error.message : String(error) })
+ }
+ return
+ }
+ if (r?.type === 'delete-workspace') {
+ if (closing) return
+ closing = true
+ routines.stop()
+ telegram?.stop()
+ hooks.close()
+ github.stop()
+ runner.stopAll()
+ void (async () => {
+ await runner.idle()
+ await memory.idle()
+ await runner.settled() // a Claude Code process writes its session's last prompt on its way out
+ runner.cleanTranscripts()
+ const agents = db.agents()
+ for (const a of agents) if (a.computer) await computers.erase(a.id)
+ chrome?.quit()
+ process.parentPort.postMessage({ type: 'workspace-cleaned', agentIds: agents.map((a) => a.id) })
+ })().catch((e: unknown) => process.parentPort.postMessage({ type: 'workspace-cleaned', error: e instanceof Error ? e.message : String(e) }))
+ return
+ }
+ if (r?.type === 'viewing') {
+ viewing = typeof r.conversationId === 'string' ? r.conversationId : null
+ if (viewing) { db.markRead(viewing); emitConversations([viewing]) }
+ workspaceSummary()
+ return
+ }
if (r?.type === 'power') return routines.setAwake(r.awake === true)
if (r?.type === 'browser-shown') return browser.setShown(r.agentId ?? '', r.shown === true)
if (r?.type === 'browser-result') {
@@ -464,6 +543,7 @@ const routines = new Routines({
runner: { runRoutine: (r, when) => runner.runRoutine(r, when), retryRoutine: (r, when, id) => runner.retryRoutine(r, when, id) },
connectors: { call: (id, tool, args) => connectors.call(id, tool, args), list: () => connectors.list() },
blocked: () => !!settings().paused || inQuietHours(settings().quietHours),
+ paused: () => !!settings().paused,
emit,
notify: notifyAll
})
@@ -539,7 +619,7 @@ void ready.then(() => {
if (settings().onboarding?.done) ensureTuca()
})
-telegram = new Telegram({
+if (defaultWorkspace) telegram = new Telegram({
secrets,
decide: (id, decision, reason) => runner.decide(id, decision, reason),
approval: (id) => db.approval(id),
@@ -562,11 +642,19 @@ const hooks = createServer((req, res) => {
if (tooBig) return void res.writeHead(413).end(L('Grande demais (máx. 64 KB).\n', 'Too big (max. 64 KB).\n'))
const r = routines.webhook(m[1]!, body)
res
- .writeHead(r === 'ok' ? 202 : r === 'busy' ? 409 : 404)
- .end(r === 'ok' ? L('Rotina disparada.\n', 'Routine fired.\n') : r === 'busy' ? L('A rotina ainda está rodando.\n', 'The routine is still running.\n') : L('Nenhuma rotina ligada com esse endereço.\n', 'No routine on with that address.\n'))
+ .writeHead(r === 'ok' ? 202 : r === 'busy' || r === 'paused' ? 409 : 404)
+ .end(
+ r === 'ok'
+ ? L('Rotina disparada.\n', 'Routine fired.\n')
+ : r === 'busy'
+ ? L('A rotina ainda está rodando.\n', 'The routine is still running.\n')
+ : r === 'paused'
+ ? L('Os agentes estão pausados.\n', 'The agents are paused.\n')
+ : L('Nenhuma rotina ligada com esse endereço.\n', 'No routine on with that address.\n')
+ )
})
})
-hooks.on('error', (e) => console.error(`[gatilhos] porta ${WEBHOOK_PORT}:`, e.message))
+hooks.on('error', (e) => console.error(`[gatilhos] porta ${runtimePorts.webhook}:`, e.message))
void ready.then(async () => {
@@ -577,25 +665,32 @@ void ready.then(async () => {
setInterval(() => void runner.expireApprovals(), 60_000).unref()
// A thread that went quiet gets its own summary, and the memories in it.
setInterval(() => void memory.sweep().catch((e: unknown) => console.error('[memory]', e)), 60_000).unref()
- routines.start()
// Nothing here waits on the keychain: the first use after an update can be a
// macOS prompt that stays open until someone answers it.
void github.start().catch((e: unknown) => console.error('[github]', e))
if (!fake) {
- hooks.listen(WEBHOOK_PORT, '127.0.0.1')
+ // A port taken (another Tucano open, say) is logged and the rest goes on: a call there reaches
+ // a server that doesn't know its token, never this workspace's data.
+ hooks.listen(runtimePorts.webhook, '127.0.0.1')
github.listen()
void telegram?.start()
}
+ routines.start()
// A copy of the database once a day, the last 7 kept.
const daily = (): void => {
try {
- backupIfDue(db, backups)
+ backupIfDue(db, backups, workspaceLabel(db.getSettings(DEFAULTS)))
} catch (e) {
console.error('[backup]', e)
}
}
daily()
setInterval(daily, 3_600_000).unref()
+ toMain({ type: 'ready' })
+ workspaceSummary()
+}).catch((e: unknown) => {
+ console.error('[core] startup failed', e)
+ process.exit(1)
})
toMain({ type: 'login_item', open: !!settings().openAtLogin })
@@ -682,6 +777,10 @@ function settleDraft(messageId: string, agentId?: string): void {
const api: Api = {
+ markRead: ({ conversationId }) => {
+ db.markRead(conversationId)
+ emitConversations([conversationId])
+ },
// The page loads from file://, which can't fetch tucano:// (CORS); text comes through the core instead.
artifactText: ({ id }) => {
const a = db.artifacts().find((x) => x.id === id)
@@ -695,6 +794,8 @@ const api: Api = {
},
snapshot: () => ({
+ webhookPort: runtimePorts.webhook,
+ defaultWorkspace,
settings: settings(),
agents: db.agents(),
conversations: db.conversations(),
@@ -856,7 +957,10 @@ const api: Api = {
checkTrigger: ({ trigger }) => routines.preview(trigger),
- setTelegramToken: ({ token }) => telegram!.setToken(token),
+ setTelegramToken: ({ token }) => {
+ if (!telegram) throw new Error(L('O Telegram fica no workspace padrão.', 'Telegram belongs to the default workspace.'))
+ return telegram.setToken(token)
+ },
setGithubToken: ({ token }) => github.setToken(token),
exportTeam: () => exportTeam(db),
importTeam: ({ text }) => {
@@ -883,7 +987,7 @@ const api: Api = {
zip.close()
}
},
- backupNow: () => backup(db, backups),
+ backupNow: () => backup(db, backups, workspaceLabel(db.getSettings(DEFAULTS))),
openBackups: () => {
mkdirSync(backups, { recursive: true })
toMain({ type: 'open_path', path: backups })
@@ -952,9 +1056,11 @@ const api: Api = {
cancelTranscribe: ({ id }) => transcriber.cancel(id),
updateSettings: ({ patch: { jevKey: _computed, telegram: _phone, accounts: _own, ...patch } }) => {
+ if (patch.theme !== undefined && !isTheme(patch.theme)) throw new Error('Invalid theme')
const why = voiceRefusal(patch.voice)
if (why) throw new Error(why)
db.setSettings(patch)
+ if (!serverMode && patch.theme !== undefined) toMain({ type: 'theme', theme: patch.theme })
if (patch.paused !== undefined) runner.setPaused(patch.paused)
if (patch.openAtLogin !== undefined) toMain({ type: 'login_item', open: patch.openAtLogin })
if (patch.onboarding?.done) void ready.then(() => ensureTuca()) // skipping the introduction still gets the Tuca
@@ -1196,6 +1302,7 @@ function handle(port: MessagePortMain, req: Request): void {
const reply = (r: Omit<Extract<Wire, { id: number }>, 'id'>): void => port.postMessage({ id: req.id, ...r } satisfies Wire)
const fn = api[req.method as Method] as ((p: unknown) => unknown) | undefined
if (!fn) return reply({ error: `unknown method ${req.method}` })
+ if (closing) return reply({ error: L('Este workspace está sendo excluído.', 'This workspace is being deleted.') })
Promise.resolve()
.then(() => fn(req.params))
.then(
diff --git a/src/core/mac.ts b/src/core/mac.ts
index e98f361..c9948ee 100644
--- a/src/core/mac.ts
+++ b/src/core/mac.ts
@@ -11,6 +11,7 @@ import { homedir } from 'node:os'
import { basename, dirname, isAbsolute, join, normalize } from 'node:path'
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'
import { L } from '../shared/lang'
+import { workspacePorts } from './ports'
import type { CoreEvent } from '../shared/rpc'
import type { Agent, Artifact, ComputerInfo, Service } from '../shared/types'
import type { Db } from './db'
@@ -20,7 +21,7 @@ import { artifactKind, badName, edited, manyMatches, clipOutput, diedAtStart, em
const MAX_FILE = 200_000
const MAX_SHOW_BYTES = 50 * 1024 * 1024
-const RESERVED_PORTS = [47_717, 47_718] // the app's own webhook and git proxy
+const RESERVED_PORTS = Object.values(workspacePorts()) // this workspace's webhook and git proxy
// What the agent is told about this computer: the system, and what is usually installed.
const installed = (): string => ({ mac: 'Homebrew, Python, Node…', linux: 'apt, Python, Node…', windows: 'Python, Node, git…' })[osOf()]
diff --git a/src/core/ports.ts b/src/core/ports.ts
new file mode 100644
index 0000000..0a8e58f
--- /dev/null
+++ b/src/core/ports.ts
@@ -0,0 +1,11 @@
+export function workspacePorts(env: NodeJS.ProcessEnv = process.env): { webhook: number; git: number } {
+ const read = (key: string, fallback: number): number => {
+ const port = env[key] === undefined ? fallback : Number(env[key])
+ if (!Number.isInteger(port) || port < 1024 || port > 65535) throw new Error(`Invalid ${key}`)
+ return port
+ }
+ const webhook = read('TUCANO_WEBHOOK_PORT', 47717)
+ const git = read('TUCANO_GIT_PORT', 47718)
+ if (webhook === git) throw new Error('Workspace ports must be different')
+ return { webhook, git }
+}
diff --git a/src/core/routines.ts b/src/core/routines.ts
index 36d9c33..a99bc53 100644
--- a/src/core/routines.ts
+++ b/src/core/routines.ts
@@ -86,6 +86,7 @@ export interface RoutineDeps {
}
connectors?: { call(id: string, tool: string, args: Record<string, unknown>): Promise<CallToolResult>; list(): Connector[] }
blocked?: () => boolean // paused, or quiet hours: nothing is due until it ends (then it runs late)
+ paused?: () => boolean // paused: a call from outside says so instead of starting a run
emit: (e: CoreEvent) => void
notify?: (title: string, shortText: string, conversationId: string, fullText?: string) => void
now?: () => number
@@ -214,6 +215,7 @@ export class Routines {
// the rest wait for the next check, which comes right after that run.
private async check(r: Routine): Promise<void> {
if (r.trigger?.kind !== 'poll' || this.checking.has(r.id) || this.running.has(r.id)) return
+ if (this.deps.blocked?.()) return
this.checking.add(r.id)
const t = r.trigger
try {
@@ -235,7 +237,8 @@ export class Routines {
}
// A call to http://127.0.0.1:WEBHOOK_PORT/gatilho/<token>, from something on this Mac.
- webhook(token: string, body: string): 'ok' | 'unknown' | 'busy' {
+ webhook(token: string, body: string): 'ok' | 'unknown' | 'busy' | 'paused' {
+ if (this.deps.paused?.()) return 'paused'
const r = this.deps.db.routines().find((x) => x.trigger?.kind === 'webhook' && x.trigger.token === token)
if (!r || !r.enabled) return 'unknown'
if (this.running.has(r.id)) return 'busy'
diff --git a/src/core/runs.ts b/src/core/runs.ts
index f24a989..c06fd78 100644
--- a/src/core/runs.ts
+++ b/src/core/runs.ts
@@ -164,15 +164,39 @@ export class Runner {
}
})
// Left by an earlier run of the app, under the usual login and each account's.
- const accounts = deps.dataDir ? join(deps.dataDir, 'accounts') : undefined
+ this.cleanTranscripts()
+ setInterval(() => this.sessions.sweep(), 10 * 60_000).unref()
+ }
+
+ // What the engines keep outside the app's folder (Claude Code's transcripts, in ~/.claude) for
+ // agents here, but not of a session still kept.
+ cleanTranscripts(): void {
+ const accounts = this.deps.dataDir ? join(this.deps.dataDir, 'accounts') : undefined
let accountDirs: string[] = []
try {
if (accounts) accountDirs = readdirSync(accounts).map((d) => join(accounts, d))
} catch {
// no accounts
}
- for (const e of Object.values(deps.engines)) e.clean?.(deps.workDir, accountDirs)
- setInterval(() => this.sessions.sweep(), 10 * 60_000).unref()
+ for (const e of Object.values(this.deps.engines)) e.clean?.(this.deps.workDir, accountDirs)
+ }
+
+ // The sessions let go are gone from disk: their processes exited and their files went after.
+ async settled(): Promise<void> {
+ await Promise.all(Object.values(this.deps.engines).map((e) => e.settle?.()))
+ }
+
+ // For good (the workspace is being deleted): what's queued is dropped, what's running stops,
+ // and the kept sessions go, with their transcripts.
+ stopAll(): void {
+ this.paused = true
+ this.queue.length = 0
+ for (const c of this.controllers.values()) {
+ c.reason = 'stopped'
+ c.ctl.abort()
+ }
+ this.sessions.dropWhere(() => true)
+ this.checkIdle()
}
// An archived agent's sessions, or a deleted conversation's, go now: their process and the
@@ -186,6 +210,7 @@ export class Runner {
setPaused(paused: boolean): void {
this.paused = paused
+ if (!paused) this.pump() // resumed: any queued work that was blocked can go on
}
// The person is writing here. What will answer gets its Claude Code started now, so the reply
@@ -298,6 +323,7 @@ export class Runner {
retry(messageId: string): void {
const { db } = this.deps
const msg = db.message(messageId)
+ if (this.paused) return // nobody starts working while paused
if (!msg?.run || msg.author.kind !== 'agent' || !RETRYABLE.includes(msg.run.status)) return
const agent = db.agent(msg.author.id)
const conv = db.conversation(msg.conversationId)
@@ -311,6 +337,7 @@ export class Runner {
const { db } = this.deps
const msg = db.message(messageId)
if (msg?.run?.status !== 'paused' || msg.author.kind !== 'agent') return
+ if (this.paused) return // nobody starts working while paused
const agent = db.agent(msg.author.id)
const conv = db.conversation(msg.conversationId)
if (!agent || !conv) return
@@ -338,6 +365,7 @@ export class Runner {
// Resolves with the agent's reply once that run ends, or undefined when it can't run.
async runRoutine(r: Routine, when: { scheduledAt: number; late: boolean; event?: RoutineEvent }): Promise<Message | undefined> {
const { db, emit } = this.deps
+ if (this.paused) return undefined // routines don't run while paused
const conv = db.conversation(r.conversationId)
const agent = db.agent(r.agentId)
if (!conv || !agent || agent.archived) return undefined
@@ -367,6 +395,7 @@ export class Runner {
// A routine's reply that failed, run again in place with the same request.
async retryRoutine(r: Routine, when: { scheduledAt: number; late: boolean; event?: RoutineEvent }, messageId: string): Promise<Message | undefined> {
+ if (this.paused) return undefined // routines don't run while paused
const { db } = this.deps
const msg = db.message(messageId)
const conv = db.conversation(r.conversationId)
@@ -452,6 +481,7 @@ export class Runner {
// The router reads the thread it picks for, and the conversation's other threads in a line each.
private async routeAndRun(conv: Conversation, members: Agent[], threadId?: string): Promise<void> {
const { db, engines } = this.deps
+ if (this.paused) return // nobody starts working while paused
this.routing++
const note = this.post(conv.id, threadId, L('Escolhendo quem responde…', 'Picking who answers…'), { status: 'working', steps: [] })
const fail = (why: string): void =>
@@ -509,6 +539,7 @@ export class Runner {
private pump(): void {
while (this.active < MAX_CONCURRENT && this.queue.length > 0) {
+ if (this.paused) return // paused: nothing new starts, queued work waits
const job = this.queue.shift()!
if (this.active++ === 0) this.deps.onBusy?.(true)
void job()
diff --git a/src/core/seed.ts b/src/core/seed.ts
index 5fac594..7df3021 100644
--- a/src/core/seed.ts
+++ b/src/core/seed.ts
@@ -3,6 +3,16 @@ import { L } from '../shared/lang'
import type { Agent } from '../shared/types'
import type { Db } from './db'
+export function initializeWorkspace(db: Db, env: NodeJS.ProcessEnv = process.env): void {
+ if (!db.created) return
+ // Demo seeding belongs to the original test install, never a workspace made
+ // from the switcher. Even in fake mode those follow the normal introduction.
+ const demo = env['TUCANO_DEFAULT_WORKSPACE'] !== '0' &&
+ (env['TUCANO_SEED'] === '1' || (env['TUCANO_FAKE_ENGINES'] === '1' && env['TUCANO_SEED'] !== '0'))
+ if (demo) seed(db)
+ else db.setSettings({ onboarding: { done: false } })
+}
+
// First run: a small team and three channels, so there is someone to talk to.
export function seed(db: Db): void {
const agent = (a: Omit<Agent, 'id' | 'used' | 'grants' | 'memory' | 'computer' | 'archived'>): Agent => ({ ...a, id: randomUUID(), used: 0, grants: {}, memory: 'auto', computer: false, archived: false })
diff --git a/src/core/team.ts b/src/core/team.ts
index aba6045..b3c09d2 100644
--- a/src/core/team.ts
+++ b/src/core/team.ts
@@ -210,10 +210,17 @@ export function importTeam(db: Db, text: string, defaultLimit: number): string {
// ---------- backups ----------
-// A copy of the database (secrets stay encrypted for this Mac's keychain).
-export function backup(db: Db, dir: string): string {
+// A copy of the database (secrets stay encrypted for this Mac's keychain), named by
+// when and then which workspace: names sort by date, so the oldest go first.
+export function backup(db: Db, dir: string, workspaceName?: string): string {
mkdirSync(dir, { recursive: true })
- const file = join(dir, `tucano-${new Date().toISOString().slice(0, 16).replace(/[:T]/g, '-')}.db`)
+ const safe = (workspaceName ?? '')
+ .normalize('NFD')
+ .replace(/[\u0300-\u036f]/g, '')
+ .replace(/[^a-z0-9]+/gi, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 40)
+ const file = join(dir, `tucano-${new Date().toISOString().slice(0, 16).replace(/[:T]/g, '-')}${safe ? `-${safe}` : ''}.db`)
if (existsSync(file)) rmSync(file)
db.backupTo(file)
const old = readdirSync(dir)
@@ -225,7 +232,7 @@ export function backup(db: Db, dir: string): string {
}
// Once a day, at startup or while the app stays open.
-export function backupIfDue(db: Db, dir: string): void {
+export function backupIfDue(db: Db, dir: string, workspaceName?: string): void {
const last = existsSync(dir)
? readdirSync(dir)
.filter((f) => f.endsWith('.db'))
@@ -233,6 +240,6 @@ export function backupIfDue(db: Db, dir: string): void {
.sort()
.at(-1)
: undefined
- if (!last || Date.now() - last > DAY) backup(db, dir)
+ if (!last || Date.now() - last > DAY) backup(db, dir, workspaceName)
}
diff --git a/src/main/browser.ts b/src/main/browser.ts
index d8d3cea..ce5017a 100644
--- a/src/main/browser.ts
+++ b/src/main/browser.ts
@@ -32,7 +32,7 @@ export class Browsers {
private titles = new Map<string, string>() // "Lia's browser · close the window to hand it back", from the core
private quitting = false
- constructor(private onShown: (agentId: string, shown: boolean) => void) {}
+ constructor(private onShown: (agentId: string, shown: boolean) => void, private namespace = '') {}
// "{page} — Lia's browser · close the window to hand it back".
private titled(agentId: string, page: string): string {
@@ -47,7 +47,7 @@ export class Browsers {
}
private partition(agentId: string): string {
- return `persist:navegador-${agentId}`
+ return `persist:navegador-${this.namespace}${agentId}`
}
private win(agentId: string): BrowserWindow {
diff --git a/src/main/index.ts b/src/main/index.ts
index bacf151..6df72ae 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -6,10 +6,12 @@ import { mkdirSync, 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 } from '../shared/types'
+import { chirpOf, type BrowserOp, type Settings } from '../shared/types'
import { Browsers } from './browser'
import { bundleOf, moveFromAgentDesk, type Moved } from './migrate'
import { Updates } from './updates'
+import { Workspaces } from './workspaces'
+import { suggestWorkspaceCopyName, workspaceParts, type Workspace, type WorkspaceList, type WorkspaceSummary } from '../shared/workspaces'
import { autostartEntry, autostartFile, onPath } from '../core/platform'
const NAME = 'Tucano'
@@ -39,39 +41,82 @@ const moved: Moved =
if (moved === 'old-app-open' || moved === 'keychain-denied') app.setPath('userData', join(app.getPath('temp'), 'tucano-esperando'))
const dataDir = (): string => process.env['TUCANO_DATA'] ?? app.getPath('userData')
-// The wiki's folder, as the core says (an Obsidian vault, say): the one folder outside the app's own it may open.
-let wikiFolder = ''
-
// tucano://artifact/<id>/<name> serves what agents showed in the chat.
protocol.registerSchemesAsPrivileged([{ scheme: 'tucano', privileges: { standard: true, secure: true, supportFetchAPI: true, stream: true } }])
-let core: UtilityProcess | null = null
-
-// Agents' browsers (spec §24); the core is told when I take one over or hand it back.
-const browsers = new Browsers((agentId, shown) => core?.postMessage({ type: 'browser-shown', agentId, shown }))
+let registry: Workspaces
+// `wikiFolder`: the wiki's folder, as that core says (an Obsidian vault, say): the one folder outside the app's own it may open.
+type Runtime = { child: UtilityProcess; browsers: Browsers; ready: Promise<void>; summary: WorkspaceSummary; busy: boolean; wikiFolder: string }
+const cores = new Map<string, Runtime>()
+const workspaceList = (): WorkspaceList => ({ selected: registry.selected().id, workspaces: registry.list().map((w) => cores.get(w.id)?.summary ?? { id: w.id, name: w.name, isDefault: w.isDefault, paused: false, unread: 0, approvals: 0, status: 'starting' }) })
+const publishWorkspaces = (): void => { mainWindow?.webContents.send('workspaces', workspaceList()) }
// 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 {
+function startCore(workspace: Workspace): Runtime {
+ const existing = cores.get(workspace.id)
+ if (existing && existing.summary.status !== 'failed') return existing
+ if (existing) {
+ existing.browsers.quit()
+ existing.child.kill()
+ cores.delete(workspace.id)
+ }
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_VERSION: app.getVersion(), TUCANO_WHISPER: whisperDir(), TUCANO_LOCAL_KEY: localKey, TUCANO_LOCALE: systemLocale ?? '' }
+ serviceName: `tucano-core-${workspace.id}`,
+ env: { ...process.env, TUCANO_DATA: workspace.dataDir, TUCANO_WORKSPACE_ID: workspace.id, ...(workspace.isDefault ? {} : { TUCANO_WORKSPACE_LABEL: workspace.name }), TUCANO_DEFAULT_WORKSPACE: workspace.isDefault ? '1' : '0', TUCANO_THEME: registry.theme() ?? (workspace.isDefault ? '' : 'system'), TUCANO_WEBHOOK_PORT: String(workspace.webhookPort), TUCANO_GIT_PORT: String(workspace.gitPort), TUCANO_PACKAGED: app.isPackaged ? '1' : '0', TUCANO_VERSION: app.getVersion(), TUCANO_WHISPER: whisperDir(), TUCANO_LOCAL_KEY: localKey, TUCANO_LOCALE: systemLocale ?? '' }
+ })
+ let resolve!: () => void
+ let reject!: (e: Error) => void
+ const ready = new Promise<void>((yes, no) => { resolve = yes; reject = no })
+ // Background startup errors are visible in the switcher, not unhandled rejections.
+ void ready.catch(() => {})
+ const runtime: Runtime = { child, ready, busy: false, wikiFolder: '', summary: { id: workspace.id, name: workspace.name, isDefault: workspace.isDefault, paused: false, unread: 0, approvals: 0, status: 'starting' }, browsers: new Browsers((agentId, shown) => child.postMessage({ type: 'browser-shown', agentId, shown }), workspace.isDefault ? '' : `${workspace.id}-`) }
+ cores.set(workspace.id, runtime)
+ const timer = setTimeout(() => {
+ reject(new Error(L('O workspace demorou demais para iniciar.', 'The workspace took too long to start.')))
+ runtime.summary.status = 'failed'
+ publishWorkspaces()
+ child.kill()
+ }, 90_000)
+ child.on('message', (msg: CoreRequest) => {
+ if (msg.type === 'ready') {
+ clearTimeout(timer)
+ const theme = registry.theme()
+ if (theme) child.postMessage({ type: 'workspace-theme', theme })
+ runtime.summary.status = 'ready'
+ resolve()
+ publishWorkspaces()
+ } else if (msg.type === 'workspace-summary') {
+ registry.rename(workspace.id, msg.name)
+ runtime.summary = { ...runtime.summary, name: msg.name || runtime.summary.name, paused: msg.paused, unread: msg.unread, approvals: msg.approvals }
+ publishWorkspaces()
+ } else handleCore(child, msg, workspace, runtime)
})
- child.on('message', (msg: CoreRequest) => handleCore(child, msg))
child.on('exit', (code) => {
- console.error(`[main] core exited with code ${code}`)
- if (core !== child) return
- core = null
- // Not while quitting: the window would say so on its way out. Reloading the page
- // connects again, and connecting starts a new core.
- if (!quitting && mainWindow && !mainWindow.isDestroyed()) mainWindow.webContents.send('core:down')
+ console.error(`[main] core of workspace ${workspace.id} exited with code ${code}`)
+ clearTimeout(timer)
+ if (cores.get(workspace.id) !== runtime) return // replaced by a new one already
+ reject(new Error(`Workspace core exited (${code})`))
+ runtime.summary.status = 'failed'
+ runtime.busy = false
+ runtime.browsers.quit()
+ syncBusy()
+ if (!quitting) publishWorkspaces()
+ // The one on screen: the window says so. Reloading the page connects again, and connecting starts a new core.
+ if (!quitting && registry.selected().id === workspace.id && mainWindow && !mainWindow.isDestroyed()) mainWindow.webContents.send('core:down')
})
- return child
+ return runtime
}
type CoreRequest =
+ | { type: 'theme'; theme: Settings['theme']; initial?: boolean }
+ | { type: 'ready' }
+ | { type: 'workspace-summary'; name: string; paused: boolean; unread: number; approvals: number }
+ | { type: 'workspace-cleaned'; agentIds?: string[]; error?: string }
+ | { type: 'workspace-duplicated'; error?: string }
+ | { type: 'workspace-paused'; error?: string }
| { type: 'secret'; id: string; op: 'encrypt' | 'decrypt'; data: string }
| { type: 'open'; url: string }
| { type: 'open_path'; path: string }
@@ -88,7 +133,9 @@ type CoreRequest =
// 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
viewing = typeof id === 'string' ? id : null
+ cores.get(registry.selected().id)?.child.postMessage({ type: 'viewing', conversationId: viewing })
})
// The toucan's own sound, instead of the system's: a knock at the door when an agent needs
@@ -117,6 +164,14 @@ function chirp(sound: 'chama' | 'pronto'): void {
// While an agent is replying, the Mac doesn't go to sleep on its own (closing the lid still does).
let awakeBlocker: number | null = null
+function syncBusy(): void {
+ const busy = [...cores.values()].some((r) => r.busy)
+ if (busy && awakeBlocker === null) awakeBlocker = powerSaveBlocker.start('prevent-app-suspension')
+ else if (!busy && awakeBlocker !== null) {
+ powerSaveBlocker.stop(awakeBlocker)
+ awakeBlocker = null
+ }
+}
// Opening at login: the system's login items on a Mac; on Linux a desktop entry in
// ~/.config/autostart (an AppImage starts from wherever the person keeps it).
@@ -171,8 +226,15 @@ function stillOpen(): void {
}
// Things the core can't do itself: the OS keychain, the browser, notifications.
-function handleCore(child: UtilityProcess, msg: CoreRequest): void {
- if (msg.type === 'secret') {
+function handleCore(child: UtilityProcess, msg: CoreRequest, workspace: Workspace, runtime: Runtime): void {
+ if (msg.type === 'theme') {
+ // Adopt the default workspace's old preference once. Other startup events
+ // and stale workspace snapshots must never overwrite the app preference.
+ if (msg.initial && (!workspace.isDefault || registry.theme() !== undefined)) return
+ registry.setTheme(msg.theme)
+ if (nativeTheme.themeSource !== msg.theme) nativeTheme.themeSource = msg.theme
+ for (const core of cores.values()) if (core.summary.status !== 'failed') core.child.postMessage({ type: 'workspace-theme', theme: msg.theme })
+ } else if (msg.type === 'secret') {
try {
// Linux without an open keyring falls back to a fixed key, or to nothing: Tucano keeps no
// secret that way, and says what to do.
@@ -213,34 +275,33 @@ function handleCore(child: UtilityProcess, msg: CoreRequest): void {
if (msg.how === 'open') void shell.openPath(msg.path)
else shell.showItemInFolder(msg.path)
} else if (msg.type === 'wiki_dir') {
- wikiFolder = normalize(msg.path)
+ runtime.wikiFolder = normalize(msg.path)
} else if (msg.type === 'open_path') {
// Only folders the app keeps (an agent's computer, the backups), never an arbitrary path.
const path = normalize(msg.path)
- if (path.startsWith(join(dataDir(), 'computers') + sep) || path === join(dataDir(), 'backups') || (!!wikiFolder && (path === wikiFolder || path.startsWith(join(wikiFolder, 'fontes', 'arquivos') + sep)))) void shell.openPath(path)
+ const wikiFolder = runtime.wikiFolder
+ if (path.startsWith(join(workspace.dataDir, 'computers') + sep) || path === join(workspace.dataDir, 'backups') || (!!wikiFolder && (path === wikiFolder || path.startsWith(join(wikiFolder, 'fontes', 'arquivos') + sep)))) void shell.openPath(path)
} else if (msg.type === 'notify') {
// Already looking at that conversation: nothing to tell.
- if (msg.conversationId && msg.conversationId === viewing && mainWindow?.isFocused()) return
+ if (registry.selected().id === workspace.id && msg.conversationId && msg.conversationId === viewing && mainWindow?.isFocused()) return
const sound = chirpOf(msg.kind, msg.sound)
if (sound) chirp(sound)
if (!Notification.isSupported()) return
const n = new Notification({ title: msg.title, body: msg.body, silent: true, ...noteIcon() })
- n.on('click', () => showWindow(msg.conversationId, msg.page, msg.threadId))
+ n.on('click', () => { void switchWorkspace(workspace.id).then(() => showWindow(msg.conversationId, msg.page, msg.threadId)).catch(console.error) })
n.show()
} else if (msg.type === 'busy') {
- if (msg.busy && awakeBlocker === null) awakeBlocker = powerSaveBlocker.start('prevent-app-suspension')
- else if (!msg.busy && awakeBlocker !== null) {
- powerSaveBlocker.stop(awakeBlocker)
- awakeBlocker = null
- }
+ runtime.busy = msg.busy
+ syncBusy()
} else if (msg.type === 'lang') {
+ if (registry.selected().id !== workspace.id) return
setLang(msg.lang)
setMenu()
} else if (msg.type === 'login_item') {
// Only the installed app: in dev this would register the bare Electron binary.
- if (app.isPackaged) openAtLogin(msg.open)
+ if (app.isPackaged && workspace.isDefault) openAtLogin(msg.open)
} else if (msg.type === 'browser') {
- browsers.run(msg.agentId, msg.op, msg.args).then(
+ runtime.browsers.run(msg.agentId, msg.op, msg.args).then(
(data) => child.postMessage({ type: 'browser-result', id: msg.id, data }),
(e: unknown) => child.postMessage({ type: 'browser-result', id: msg.id, error: e instanceof Error ? e.message : String(e) })
)
@@ -302,7 +363,7 @@ function serveArtifact(req: Request): Promise<Response> | Response {
})
}
const [id = '', name = ''] = u.pathname.slice(1).split('/')
- const dir = join(dataDir(), 'artifacts', id)
+ const dir = join(registry.selected().dataDir, 'artifacts', id)
const file = normalize(join(dir, decodeURIComponent(name)))
if (u.host !== 'artifact' || !/^[0-9a-f-]{36}$/.test(id) || !file.startsWith(dir + sep)) return new Response('not found', { status: 404 })
return net.fetch(pathToFileURL(file).toString()).then((r) => {
@@ -314,13 +375,151 @@ 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', (event) => {
- core ??= startCore()
+ipcMain.on('core:connect', async (event) => {
+ if (event.sender !== mainWindow?.webContents || event.senderFrame !== event.sender.mainFrame) return
+ const workspace = registry.selected()
+ const runtime = startCore(workspace)
+ try { await runtime.ready } catch { return }
+ if (event.sender.isDestroyed() || registry.selected().id !== workspace.id) return
const { port1, port2 } = new MessageChannelMain()
- core.postMessage(null, [port1])
+ runtime.child.postMessage(null, [port1])
event.sender.postMessage('core:port', null, [port2])
})
+let switching = false
+async function switchWorkspace(id: string): Promise<void> {
+ if (id === registry.selected().id) return // already on screen: nothing to reload
+ if (switching) throw new Error(L('Aguarde a troca de workspace.', 'Wait for the workspace switch.'))
+ switching = true
+ try {
+ const workspace = registry.get(id)
+ await startCore(workspace).ready
+ cores.get(registry.selected().id)?.child.postMessage({ type: 'viewing', conversationId: null })
+ registry.select(id)
+ viewing = null
+ mainWindow?.reload()
+ } finally { switching = false }
+}
+
+function trustedWorkspaceRequest(event: Electron.IpcMainInvokeEvent): void {
+ if (event.sender !== mainWindow?.webContents || event.senderFrame !== event.sender.mainFrame) throw new Error('Not the app window')
+}
+function requestWorkspace(runtime: Runtime, request: object, response: 'workspace-cleaned' | 'workspace-duplicated' | 'workspace-paused'): Promise<string[]> {
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => { cleanup(); reject(new Error('Workspace operation timed out')) }, 180_000)
+ const onExit = (): void => { cleanup(); reject(new Error('Workspace stopped before the operation finished')) }
+ const onMessage = (msg: CoreRequest): void => {
+ if (msg.type !== response) return
+ cleanup()
+ if (msg.error) reject(new Error(msg.error))
+ else resolve('agentIds' in msg ? msg.agentIds ?? [] : [])
+ }
+ const cleanup = (): void => { clearTimeout(timer); runtime.child.removeListener('message', onMessage); runtime.child.removeListener('exit', onExit) }
+ runtime.child.on('message', onMessage)
+ runtime.child.once('exit', onExit)
+ runtime.child.postMessage(request)
+ })
+}
+ipcMain.handle('workspaces:list', (event) => { trustedWorkspaceRequest(event); return workspaceList() })
+ipcMain.handle('workspaces:pause', async (event, paused: unknown, id?: unknown) => {
+ trustedWorkspaceRequest(event)
+ if (switching) throw new Error('Wait for the workspace operation')
+ if (typeof paused !== 'boolean' || (id !== undefined && typeof id !== 'string')) throw new Error('Invalid workspace pause request')
+ const targets = typeof id === 'string' ? [registry.get(id)] : registry.list()
+ switching = true
+ try {
+ const results = await Promise.allSettled(targets.map(async (w) => {
+ const runtime = cores.get(w.id)
+ // Pausing must never start a failed core and accidentally fire its jobs.
+ if (!runtime || runtime.summary.status === 'failed') throw new Error('Workspace is unavailable')
+ await runtime.ready
+ await requestWorkspace(runtime, { type: 'workspace-pause', paused }, 'workspace-paused')
+ }))
+ const failed = targets.filter((_w, index) => results[index]!.status === 'rejected')
+ if (failed.length) throw new Error(L(`Não foi possível atualizar a pausa de: ${failed.map((w) => w.name).join(', ')}.`, `Could not update pause state for: ${failed.map((w) => w.name).join(', ')}.`))
+ } finally { switching = false }
+})
+ipcMain.handle('workspaces:switch', async (event, id: unknown) => {
+ trustedWorkspaceRequest(event)
+ if (typeof id !== 'string') throw new Error('Invalid workspace')
+ await switchWorkspace(id)
+})
+ipcMain.handle('workspaces:create', async (event, name?: unknown) => {
+ trustedWorkspaceRequest(event)
+ if (switching) throw new Error('Wait for the workspace switch')
+ if (name !== undefined && (typeof name !== 'string' || !name.trim() || name.trim().length > 120)) throw new Error(L('Dê um nome ao workspace, com até 120 caracteres.', 'Give the workspace a name, up to 120 characters.'))
+ const workspace = registry.create(typeof name === 'string' ? name.trim() : undefined)
+ startCore(workspace)
+ await switchWorkspace(workspace.id)
+})
+// `parts`: what comes along; unset, all of it.
+ipcMain.handle('workspaces:duplicate', async (event, id: unknown, requestedName?: unknown, parts?: unknown) => {
+ trustedWorkspaceRequest(event)
+ if (switching) throw new Error('Wait for the workspace operation')
+ if (typeof id !== 'string') throw new Error('Invalid workspace')
+ if (requestedName !== undefined && (typeof requestedName !== 'string' || !requestedName.trim() || requestedName.trim().length > 120)) throw new Error(L('Dê um nome ao workspace, com até 120 caracteres.', 'Give the workspace a name, up to 120 characters.'))
+ const source = registry.get(id)
+ switching = true
+ let target: Workspace | undefined
+ try {
+ const runtime = startCore(source)
+ await runtime.ready
+ const name = typeof requestedName === 'string' ? requestedName.trim() : suggestWorkspaceCopyName(source.name, registry.list().map((w) => w.name))
+ target = registry.create(name)
+ await requestWorkspace(runtime, { type: 'duplicate-workspace', targetDir: target.dataDir, name: target.name, ...(parts !== undefined ? { parts: workspaceParts(parts) } : {}) }, 'workspace-duplicated')
+ await startCore(target).ready
+ publishWorkspaces()
+ return target.id
+ } catch (error) {
+ // Only remove a failed, newly generated copy, never the source workspace.
+ if (target && !cores.has(target.id)) registry.deleteData(target.id)
+ publishWorkspaces()
+ throw error
+ } finally { switching = false }
+})
+ipcMain.handle('workspaces:delete', async (event, id: unknown) => {
+ trustedWorkspaceRequest(event)
+ if (switching) throw new Error('Wait for the workspace switch')
+ if (id !== undefined && typeof id !== 'string') throw new Error('Invalid workspace')
+ const workspace = id === undefined ? registry.selected() : registry.get(id as string)
+ if (workspace.isDefault) throw new Error(L('O workspace padrão não pode ser excluído.', 'The default workspace cannot be deleted.'))
+ switching = true
+ try {
+ const answer = await dialog.showMessageBox(mainWindow!, {
+ type: 'warning',
+ title: L('Excluir workspace', 'Delete workspace'),
+ message: L(`Excluir “${workspace.name}” e todos os seus dados?`, `Delete “${workspace.name}” and all its data?`),
+ detail: L('Conversas, agentes, memórias, credenciais, rotinas e backups deste workspace serão apagados. Não dá para desfazer. Pastas de projetos e outros workspaces ficam intactos.', 'Conversations, agents, memories, credentials, routines and backups in this workspace will be deleted. This cannot be undone. Project folders and other workspaces are kept.'),
+ buttons: [L('Cancelar', 'Cancel'), L('Excluir todos os dados', 'Delete all data')], defaultId: 0, cancelId: 0, noLink: true
+ })
+ if (answer.response !== 1) return
+ const runtime = startCore(workspace)
+ await runtime.ready
+ const agentIds = await requestWorkspace(runtime, { type: 'delete-workspace' }, 'workspace-cleaned')
+ for (const agentId of agentIds) await runtime.browsers.run(agentId, 'clear')
+ runtime.browsers.quit()
+ await new Promise<void>((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error('Workspace did not stop. Data has not been removed.')), 10_000)
+ runtime.child.once('exit', () => { clearTimeout(timer); resolve() })
+ if (!runtime.child.kill()) { clearTimeout(timer); reject(new Error('Could not stop workspace')) }
+ })
+ const active = registry.selected().id === workspace.id
+ registry.deleteData(workspace.id)
+ cores.delete(workspace.id)
+ for (const w of registry.list()) startCore(w)
+ if (active) { viewing = null; mainWindow?.reload() }
+ else publishWorkspaces()
+ } catch (error) {
+ const runtime = cores.get(workspace.id)
+ if (runtime) {
+ runtime.summary.status = 'failed'
+ runtime.child.kill()
+ publishWorkspaces()
+ }
+ throw error
+ } finally { switching = false }
+})
+
// Brings the window back (closing it keeps the app and its routines running),
// optionally opening a conversation (and a thread in it).
// The app's own window; agents' browsers are windows too, hidden, and never count as it.
@@ -393,7 +592,11 @@ function createWindow(): BrowserWindow {
win.once('ready-to-show', () => win.show())
mainWindow = win
win.on('closed', () => {
- if (mainWindow === win) mainWindow = null
+ if (mainWindow === win) {
+ cores.get(registry.selected().id)?.child.postMessage({ type: 'viewing', conversationId: null })
+ viewing = null
+ mainWindow = null
+ }
stillOpen()
})
@@ -484,11 +687,13 @@ if (moved === 'old-app-open' || moved === 'keychain-denied') {
})
setMenu()
protocol.handle('tucano', serveArtifact)
- core = startCore()
+ registry = new Workspaces(dataDir())
+ nativeTheme.themeSource = registry.theme() ?? 'system'
+ for (const workspace of registry.list()) startCore(workspace)
// The Mac wakes for a few seconds at a time while asleep (maintenance, "DarkWake"):
// routines wait for a real wake, so a run doesn't start and freeze mid-way.
- powerMonitor.on('suspend', () => core?.postMessage({ type: 'power', awake: false }))
- powerMonitor.on('resume', () => core?.postMessage({ type: 'power', awake: true }))
+ powerMonitor.on('suspend', () => { for (const r of cores.values()) r.child.postMessage({ type: 'power', awake: false }) })
+ powerMonitor.on('resume', () => { for (const r of cores.values()) r.child.postMessage({ type: 'power', awake: true }) })
createWindow()
setTray()
updates.start()
@@ -504,9 +709,9 @@ app.on('window-all-closed', () => {
app.on('before-quit', () => {
quitting = true
- browsers.quit()
+ for (const r of cores.values()) r.browsers.quit()
})
app.on('will-quit', () => {
- core?.kill()
+ for (const r of cores.values()) r.child.kill()
})
diff --git a/src/main/workspaces.ts b/src/main/workspaces.ts
new file mode 100644
index 0000000..ecf97f0
--- /dev/null
+++ b/src/main/workspaces.ts
@@ -0,0 +1,123 @@
+import { randomBytes } from 'node:crypto'
+import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { isTheme, type Workspace } from '../shared/workspaces'
+import type { Settings } from '../shared/types'
+
+const UUID7 = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
+
+// RFC 9562: 48 bits of milliseconds, version 7, random payload and RFC variant.
+export function workspaceId(): string {
+ const bytes = randomBytes(16)
+ bytes.writeUIntBE(Date.now(), 0, 6)
+ bytes[6] = (bytes[6]! & 0x0f) | 0x70
+ bytes[8] = (bytes[8]! & 0x3f) | 0x80
+ const hex = bytes.toString('hex')
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
+}
+
+interface Registry {
+ version: 1
+ theme?: Settings['theme']
+ selected: string
+ workspaces: Workspace[]
+}
+
+export class Workspaces {
+ private state: Registry
+ readonly root: string
+ private file: string
+
+ constructor(root: string) {
+ mkdirSync(root, { recursive: true })
+ this.root = realpathSync(root)
+ this.file = join(this.root, 'workspaces.json')
+ if (existsSync(this.file)) {
+ const state: unknown = JSON.parse(readFileSync(this.file, 'utf8'))
+ this.validate(state)
+ this.state = state
+ } else {
+ const id = workspaceId()
+ this.state = { version: 1, selected: id, workspaces: [{ id, name: 'Workspace', dataDir: this.root, webhookPort: 47717, gitPort: 47718, isDefault: true }] }
+ this.save(this.state)
+ }
+ }
+
+ private validate(raw: unknown): asserts raw is Registry {
+ const fail = (): never => { throw new Error('Invalid workspaces.json. Your data has not been changed; restore the registry from a backup.') }
+ if (!raw || typeof raw !== 'object') fail()
+ const r = raw as Registry
+ if (r.version !== 1 || !Array.isArray(r.workspaces) || !r.workspaces.length) fail()
+ if (r.theme !== undefined && !isTheme(r.theme)) fail()
+ const managed = join(this.root, 'workspaces')
+ if (existsSync(managed) && realpathSync(managed) !== managed) fail()
+ const ids = new Set<string>()
+ const ports = new Set<number>()
+ for (const w of r.workspaces) {
+ if (!w || typeof w.id !== 'string' || !UUID7.test(w.id) || ids.has(w.id) || typeof w.name !== 'string' || !w.name.trim() || typeof w.isDefault !== 'boolean') fail()
+ ids.add(w.id)
+ const expected = w.isDefault ? this.root : join(this.root, 'workspaces', w.id)
+ if (w.dataDir !== expected || (existsSync(expected) && realpathSync(expected) !== expected)) fail()
+ for (const port of [w.webhookPort, w.gitPort]) {
+ if (!Number.isInteger(port) || port < 1024 || port > 65535 || ports.has(port)) fail()
+ ports.add(port)
+ }
+ if (w.isDefault && (w.webhookPort !== 47717 || w.gitPort !== 47718)) fail()
+ }
+ if (r.workspaces.filter((w) => w.isDefault).length !== 1 || !ids.has(r.selected)) fail()
+ }
+
+ private save(next: Registry): void {
+ this.validate(next)
+ const temp = `${this.file}.tmp`
+ writeFileSync(temp, JSON.stringify(next, null, 2) + '\n', { mode: 0o600 })
+ renameSync(temp, this.file)
+ this.state = next
+ }
+
+ list(): Workspace[] { return this.state.workspaces.map((w) => ({ ...w })) }
+ theme(): Settings['theme'] | undefined { return this.state.theme }
+ setTheme(theme: Settings['theme']): void {
+ if (theme !== this.state.theme) this.save({ ...this.state, theme })
+ }
+ selected(): Workspace { return this.get(this.state.selected) }
+ get(id: string): Workspace {
+ const w = this.state.workspaces.find((w) => w.id === id)
+ if (!w) throw new Error('Workspace not found')
+ return { ...w }
+ }
+
+ create(name = 'Workspace'): Workspace {
+ // Names come from the existing onboarding, not another workspace wizard.
+ const id = workspaceId()
+ const used = new Set(this.list().flatMap((w) => [w.webhookPort, w.gitPort]))
+ let port = 47719
+ while (used.has(port) || used.has(port + 1)) port += 2
+ if (port + 1 > 65535) throw new Error('No workspace ports available')
+ const workspace: Workspace = { id, name: name.trim() || 'Workspace', dataDir: join(this.root, 'workspaces', id), webhookPort: port, gitPort: port + 1, isDefault: false }
+ this.save({ ...this.state, workspaces: [...this.list(), workspace] })
+ return workspace
+ }
+
+ select(id: string): void {
+ this.get(id)
+ this.save({ ...this.state, selected: id })
+ }
+
+ rename(id: string, name: string): void {
+ const clean = name.trim()
+ if (!clean || this.get(id).name === clean) return
+ this.save({ ...this.state, workspaces: this.list().map((w) => w.id === id ? { ...w, name: clean } : w) })
+ }
+
+ // Main must stop the owning core, processes and browser sessions first.
+ deleteData(id: string): void {
+ this.validate(this.state)
+ const workspace = this.get(id)
+ if (workspace.isDefault) throw new Error('The default workspace cannot be deleted')
+ rmSync(workspace.dataDir, { recursive: true, force: true })
+ const kept = this.list().filter((w) => w.id !== id)
+ const selected = this.state.selected === id ? kept[0]!.id : this.state.selected
+ this.save({ ...this.state, selected, workspaces: kept })
+ }
+}
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 219b4a3..975cb9e 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -8,6 +8,19 @@ ipcRenderer.on('core:port', (event) => {
})
contextBridge.exposeInMainWorld('tucano', {
+ workspaces: {
+ list: () => ipcRenderer.invoke('workspaces:list'),
+ create: (name?: string) => ipcRenderer.invoke('workspaces:create', name),
+ delete: (id?: string) => ipcRenderer.invoke('workspaces:delete', id),
+ duplicate: (id: string, name?: string, parts?: object) => ipcRenderer.invoke('workspaces:duplicate', id, name, parts),
+ setPaused: (paused: boolean, id?: string) => ipcRenderer.invoke('workspaces:pause', paused, id),
+ switch: (id: string) => ipcRenderer.invoke('workspaces:switch', id),
+ subscribe: (cb: (list: unknown) => void) => {
+ const listener = (_event: Electron.IpcRendererEvent, list: unknown): void => cb(list)
+ ipcRenderer.on('workspaces', listener)
+ return () => ipcRenderer.removeListener('workspaces', listener)
+ }
+ },
connect: (): void => ipcRenderer.send('core:connect'),
pickFolder: (): Promise<string | null> => ipcRenderer.invoke('pick-folder') as Promise<string | null>,
// A picked file's path, so the core reads a big .zip in parts instead of through the page.
diff --git a/src/renderer/src/components/Dialogs.tsx b/src/renderer/src/components/Dialogs.tsx
index 5a48c70..70e55e0 100644
--- a/src/renderer/src/components/Dialogs.tsx
+++ b/src/renderer/src/components/Dialogs.tsx
@@ -5,6 +5,8 @@ import { L } from '../../../shared/lang'
import { useEffect, useRef, useState, useSyncExternalStore, type KeyboardEvent as KeyEvent, type ReactNode } from 'react'
import { agentById, archiveAgent, isTeam, openTuca, createChannel, finishConnectorAuth, getState, navigate, openDialog, openDm, renameChannel, setChannelMembers, setThreads, setTopic, shortcut, useStore, type Conversation, type State, type View } from '../store'
import { AgentAvatar, Icon, type IconName } from './ui'
+import { WorkspaceManager } from './WorkspaceManager'
+import { Modal } from './Modal'
const message = (e: unknown): string => (e instanceof Error ? e.message.replace(/^Error invoking.*?: /, '') : String(e))
@@ -73,6 +75,7 @@ function DialogBody(): ReactNode {
const dialog = useStore((s) => s.dialog)
const conv = useStore((s) => (s.dialog && 'id' in s.dialog ? s.conversations.find((c) => c.id === (s.dialog as { id: string }).id) : undefined))
const close = (): void => openDialog(null)
+ if (dialog?.kind === 'workspaces') return <WorkspaceManager onClose={close} create={dialog.create} />
if (dialog?.kind === 'search') return <Search onClose={close} />
if (dialog?.kind === 'archived') return <Archived onClose={close} />
if (dialog?.kind === 'oauth') return <OAuthDialog id={dialog.id} url={dialog.url} onClose={close} />
@@ -163,58 +166,6 @@ function SettingsDialog({ conv, onClose }: { conv?: Conversation; onClose: () =>
)
}
-// Open windows, newest last: Esc and Tab belong to the one on top only.
-const openModals: object[] = []
-const FOCUSABLE = 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'
-
-// `className`: a card of another size (the news after an update).
-export function Modal({ title, onClose, children, className }: { title: string; onClose: () => void; children: ReactNode; className?: string }): ReactNode {
- const card = useRef<HTMLDivElement>(null)
- const close = useRef(onClose)
- close.current = onClose
- useEffect(() => {
- const me = {}
- openModals.push(me)
- const before = document.activeElement as HTMLElement | null
- if (!card.current?.contains(document.activeElement)) card.current?.querySelector<HTMLElement>(FOCUSABLE)?.focus()
- // Captured before the page's own keys, so an Esc here doesn't also close what's behind.
- const keys = (e: KeyboardEvent): void => {
- if (openModals[openModals.length - 1] !== me) return
- if (e.key === 'Escape') {
- e.stopImmediatePropagation()
- e.preventDefault()
- close.current()
- } else if (e.key === 'Tab' && card.current) {
- const all = [...card.current.querySelectorAll<HTMLElement>(FOCUSABLE)]
- if (!all.length) return
- const [first, last] = [all[0]!, all[all.length - 1]!]
- const inside = card.current.contains(document.activeElement)
- if (e.shiftKey && (document.activeElement === first || !inside)) (e.preventDefault(), last.focus())
- else if (!e.shiftKey && (document.activeElement === last || !inside)) (e.preventDefault(), first.focus())
- }
- }
- window.addEventListener('keydown', keys, true)
- return () => {
- window.removeEventListener('keydown', keys, true)
- openModals.splice(openModals.indexOf(me), 1)
- if (before?.isConnected) before.focus()
- }
- }, [])
- return (
- <div className="modal" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
- <div className={`modal__card ${className ?? ''}`} role="dialog" aria-modal="true" aria-label={title} ref={card}>
- <header className="modal__head">
- <strong>{title}</strong>
- <button className="icon-btn icon-btn--sm" title={L('Fechar', 'Close')} onClick={onClose}>
- <Icon name="x" size={14} />
- </button>
- </header>
- {children}
- </div>
- </div>
- )
-}
-
// Who is in the channel: a row per agent, on or off, saved together.
function MembersDialog({ id, name, members, onClose }: { id: string; name: string; members: string[]; onClose: () => void }): ReactNode {
const agents = useStore((s) => s.agents.filter(isTeam))
diff --git a/src/renderer/src/components/Modal.tsx b/src/renderer/src/components/Modal.tsx
new file mode 100644
index 0000000..ae38f3b
--- /dev/null
+++ b/src/renderer/src/components/Modal.tsx
@@ -0,0 +1,68 @@
+import { useEffect, useRef, type ReactNode } from 'react'
+import { L } from '../../../shared/lang'
+import { Icon } from './ui'
+
+// Open windows, newest last: Esc and Tab belong to the one on top only.
+const openModals: object[] = []
+const FOCUSABLE = 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'
+
+// `className`: a card of another size (the news after an update). `variant: 'form'`: a form
+// that draws its own heading (a routine, a skill). `actions`: buttons beside the close one.
+export function Modal({ title, onClose, children, className, variant = 'dialog', actions }: {
+ title: string
+ onClose: () => void
+ children: ReactNode
+ className?: string
+ variant?: 'dialog' | 'form'
+ actions?: ReactNode
+}): ReactNode {
+ const card = useRef<HTMLDivElement>(null)
+ const close = useRef(onClose)
+ close.current = onClose
+ useEffect(() => {
+ const me = {}
+ openModals.push(me)
+ const before = document.activeElement as HTMLElement | null
+ if (!card.current?.contains(document.activeElement)) card.current?.querySelector<HTMLElement>(FOCUSABLE)?.focus()
+ // Captured before the page's own keys, so an Esc here doesn't also close what's behind.
+ const keys = (e: KeyboardEvent): void => {
+ if (openModals[openModals.length - 1] !== me) return
+ if (e.key === 'Escape') {
+ e.stopImmediatePropagation()
+ e.preventDefault()
+ close.current()
+ } else if (e.key === 'Tab' && card.current) {
+ const all = [...card.current.querySelectorAll<HTMLElement>(FOCUSABLE)]
+ if (!all.length) return
+ const [first, last] = [all[0]!, all[all.length - 1]!]
+ const inside = card.current.contains(document.activeElement)
+ if (e.shiftKey && (document.activeElement === first || !inside)) (e.preventDefault(), last.focus())
+ else if (!e.shiftKey && (document.activeElement === last || !inside)) (e.preventDefault(), first.focus())
+ }
+ }
+ window.addEventListener('keydown', keys, true)
+ return () => {
+ window.removeEventListener('keydown', keys, true)
+ openModals.splice(openModals.indexOf(me), 1)
+ if (before?.isConnected) before.focus()
+ }
+ }, [])
+ return (
+ <div className="modal" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
+ <div className={`${variant === 'form' ? 'form-modal' : 'modal__card'} ${className ?? ''}`} role="dialog" aria-modal="true" aria-label={title} ref={card}>
+ {variant === 'dialog' && (
+ <header className="modal__head">
+ <strong>{title}</strong>
+ <div className="modal__actions">
+ {actions}
+ <button className="icon-btn icon-btn--sm" title={L('Fechar', 'Close')} onClick={onClose}>
+ <Icon name="x" size={14} />
+ </button>
+ </div>
+ </header>
+ )}
+ {children}
+ </div>
+ </div>
+ )
+}
diff --git a/src/renderer/src/components/Onboarding.tsx b/src/renderer/src/components/Onboarding.tsx
index b2d534b..6f083d5 100644
--- a/src/renderer/src/components/Onboarding.tsx
+++ b/src/renderer/src/components/Onboarding.tsx
@@ -20,6 +20,7 @@ import {
modelInfo,
usable,
navigate,
+ openDialog,
newChannel,
refreshEngines,
newAgentDraft,
@@ -182,9 +183,11 @@ export function Onboarding({ build = false, from }: { build?: boolean; from?: Vi
const [computer, setComputer] = useState<Computer>('none')
const [task, setTask] = useState(() => TEMPLATES()[0]!.tasks[0]!)
const [busy, setBusy] = useState(false)
- // A new install picks both models; seeing the introduction again starts from what's set.
- const [routerModel, setRouterModel] = useState(hasAgents ? settings.routerModel : '')
- const [memoryModel, setMemoryModel] = useState(hasAgents ? settings.memoryModel : '')
+ // A new install picks both models; seeing the introduction again, or a workspace that brought
+ // another's settings, starts from what's set.
+ const keep = hasAgents || !!settings.onboarding?.carried
+ const [routerModel, setRouterModel] = useState(keep ? settings.routerModel : '')
+ const [memoryModel, setMemoryModel] = useState(keep ? settings.memoryModel : '')
const [skills, setSkills] = useState<string[]>([])
const [grants, setGrants] = useState<Record<string, GrantLevel>>({})
// The first agent comes from the Tuca's card, or from the form for who prefers it.
@@ -1102,7 +1105,8 @@ interface Item {
title: string
how: string
done: (s: State) => boolean
- go: (s: State) => View
+ go?: (s: State) => View
+ open?: () => void
action: string
}
@@ -1168,11 +1172,19 @@ const ITEMS = (): Item[] => [
done: (s) => !!s.settings.telegram?.chat,
go: () => ({ kind: 'settings' }),
action: L('Configurações', 'Settings')
+ },
+ {
+ id: 'workspaces',
+ title: L('Conhecer os workspaces', 'Explore workspaces'),
+ how: L('Separe seus contextos. Crie, duplique e gerencie seus workspaces.', 'Keep your contexts separate. Create, duplicate and manage your workspaces.'),
+ done: (s) => !!s.settings.onboarding?.workspaceManagerSeen,
+ open: () => openDialog({ kind: 'workspaces' }),
+ action: L('Workspaces', 'Workspaces')
}
]
export function GettingStarted(): ReactNode {
- const items = ITEMS()
+ const items = ITEMS().filter((item) => item.id !== 'workspaces' || !!window.tucano.workspaces)
const done = useStore((s) => items.map((i) => i.done(s)))
const onboarding = useStore((s) => s.settings.onboarding)
const [open, setOpen] = useState(false)
@@ -1207,7 +1219,8 @@ export function GettingStarted(): ReactNode {
<button
className={`btn btn--sm ${i === nextIndex ? 'btn--primary' : ''}`}
onClick={() => {
- navigate(item.go(getState()))
+ if (item.open) item.open()
+ else if (item.go) navigate(item.go(getState()))
setOpen(false)
}}
>
diff --git a/src/renderer/src/components/Pages.tsx b/src/renderer/src/components/Pages.tsx
index efca502..b377b7b 100644
--- a/src/renderer/src/components/Pages.tsx
+++ b/src/renderer/src/components/Pages.tsx
@@ -70,9 +70,12 @@ import { AccountPicker, AccountsCard, HarnessList, HarnessMcps, ModelPicker, onG
import { AppsCard } from './Apps'
import { ConnectorGrid } from './ConnectorStore'
import { ApprovalCard, toolWords } from './Conversation'
-import { confirmDialog, Modal } from './Dialogs'
+import { confirmDialog } from './Dialogs'
+import { Modal } from './Modal'
import { AgentAvatar, AVATARS, Icon, NumberInput, SleepingToucan, time, tokens, UsageBar } from './ui'
import { UpdateSettings } from './Update'
+import { useWorkspaceList } from './Workspaces'
+import { workspaceLabel } from '../../../shared/workspaces'
import exportSkill from '../assets/tucano-export-skill.md?raw'
export function Page({ title, subtitle, actions, children }: { title: ReactNode; subtitle?: ReactNode; actions?: ReactNode; children: ReactNode }): ReactNode {
@@ -1564,6 +1567,7 @@ function GithubCard({ info }: { info?: { user?: string; error?: string } }): Rea
const MAX_UPLOAD = 40_000_000 // a browser's request has a cap (64 MB) and base64 grows a third
function TeamCard(): ReactNode {
const [note, setNote] = useState('')
+ const settings = useStore((s) => s.settings)
// Grok Bot has no export: one of the person's agents there runs this skill and writes our .zip.
const grokSkill = (): void => {
const a = document.createElement('a')
@@ -1579,13 +1583,22 @@ function TeamCard(): ReactNode {
)
}
const download = (): void => {
- void exportTeam().then((md) => {
+ setNote('')
+ exportTeam().then((md) => {
+ const safe = workspaceLabel(settings)
+ .normalize('NFD')
+ .replace(/[\u0300-\u036f]/g, '')
+ .replace(/[^a-z0-9]+/gi, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 40) || 'workspace'
+ const file = `${L('time-tucano', 'tucano-team')}-${safe}-${new Date().toISOString().slice(0, 10)}.md`
const a = document.createElement('a')
a.href = URL.createObjectURL(new Blob([md], { type: 'text/markdown' }))
- a.download = `${L('time-tucano', 'tucano-team')}-${new Date().toISOString().slice(0, 10)}.md`
+ a.download = file
a.click()
URL.revokeObjectURL(a.href)
- })
+ setNote(L(`Exportação feita: ${file}.`, `Exported: ${file}.`))
+ }).catch((e: unknown) => setNote(e instanceof Error ? e.message : String(e)))
}
const failed = (e: unknown): void => setNote(e instanceof Error ? e.message.replace(/^Error invoking remote method '[^']+': (Error: )?/, '') : String(e))
const upload = (file?: File): void => {
@@ -1610,7 +1623,7 @@ function TeamCard(): ReactNode {
.then(setNote, failed)
}
return (
- <Card title={L('Time e backup', 'Team and backup')} lead={L('O time num arquivo .md (agentes, skills, canais e rotinas, sem credenciais nem conversas), pra guardar ou levar pra outro computador. Os agentes do OpenBot e do Grok Bot também entram, sem nenhum conector e com a busca na web desligada. E uma cópia de tudo uma vez por dia (as últimas 7).', 'The team in a .md file (agents, skills, channels and routines, without credentials or conversations), to keep or take to another computer. Agents from OpenBot and Grok Bot come in too, with no connector and web search off. And a copy of everything once a day (the last 7).')}>
+ <Card title={L('Time', 'Team')} lead={L('O time num arquivo .md (agentes, skills, canais e rotinas, sem credenciais nem conversas), pra guardar ou levar pra outro computador. Os agentes do OpenBot e do Grok Bot também entram, sem nenhum conector e com a busca na web desligada.', 'The team in a .md file (agents, skills, channels and routines, without credentials or conversations), to keep or take to another computer. Agents from OpenBot and Grok Bot come in too, with no connector and web search off.')}>
<div className="row" style={{ flexWrap: 'wrap' }}>
<button className="btn btn--sm" onClick={download}>
{L('Exportar time', 'Export team')}
@@ -1645,19 +1658,67 @@ function TeamCard(): ReactNode {
{L('Skill pro Grok Bot (experimental)', 'Skill for Grok Bot (experimental)')}
</button>
</div>
- <div className="row" style={{ marginTop: 8 }}>
- <button className="btn btn--sm" onClick={() => void backupNow().then((f) => setNote(L(`Backup feito: ${f.split('/').pop()}`, `Backup done: ${f.split('/').pop()}`)))}>
- {L('Fazer backup agora', 'Back up now')}
- </button>
- <button className="btn btn--sm btn--ghost" onClick={openBackups}>
- {L('Abrir pasta', 'Open folder')}
- </button>
- </div>
{note && <p className="small muted" style={{ whiteSpace: 'pre-line' }}>{note}</p>}
</Card>
)
}
+function WorkspaceDangerArea(): ReactNode {
+ const name = useStore((s) => workspaceLabel(s.settings))
+ const defaultWorkspace = useStore((s) => s.defaultWorkspace)
+ const [note, setNote] = useState('')
+ const [busy, setBusy] = useState(false)
+ const [error, setError] = useState('')
+ const remove = async (): Promise<void> => {
+ setBusy(true)
+ setError('')
+ try { await window.tucano.workspaces?.delete() }
+ catch (e) { setError(e instanceof Error ? e.message : String(e)) }
+ finally { setBusy(false) }
+ }
+ return <section className="workspace-danger" aria-label={L('Área de perigo', 'Danger area')}>
+ <Card title={L('Área de perigo', 'Danger area')}>
+ <div className="workspace-danger__section">
+ <h3>{L('Backups', 'Backups')}</h3>
+ <p className="small muted">{L('Faça uma cópia antes de apagar dados. O backup automático guarda as últimas 7 cópias diárias.', 'Make a copy before deleting data. Automatic backup keeps the last 7 daily copies.')}</p>
+ <div className="row">
+ <button className="btn btn--sm" disabled={busy} onClick={() => { backupNow().then((file) => setNote(L(`Backup feito: ${file.split('/').pop()}`, `Backup done: ${file.split('/').pop()}`))).catch((e: unknown) => setError(String(e))) }}>{L('Fazer backup agora', 'Back up now')}</button>
+ <button className="btn btn--sm btn--ghost" onClick={openBackups}>{L('Abrir pasta', 'Open folder')}</button>
+ </div>
+ {note && <p className="small muted">{note}</p>}
+ </div>
+ {window.tucano.workspaces && <div className="workspace-danger__section">
+ <h3>{L('Excluir workspace', 'Delete workspace')}</h3>
+ <p className="small muted">{defaultWorkspace ? L('O workspace padrão não pode ser excluído. Você ainda pode fazer backup ou duplicá-lo.', 'The default workspace cannot be deleted. You can still back it up or duplicate it.') : L(`Excluir “${name}” apaga também seus backups locais, agentes, conversas, memórias, credenciais e rotinas. Copie o backup para fora deste workspace antes. Os outros workspaces e suas pastas de projetos ficam intactos.`, `Deleting “${name}” also deletes its local backups, agents, conversations, memories, credentials and routines. Copy your backup outside this workspace first. Other workspaces and project folders are kept.`)}</p>
+ <button className="btn btn--danger btn--sm" disabled={busy || defaultWorkspace} onClick={() => void remove()}>{busy ? L('Aguarde…', 'Please wait…') : L('Excluir workspace e todos os dados', 'Delete workspace and all data')}</button>
+ </div>}
+ {error && <p className="field__error" role="alert">{error}</p>}
+ </Card>
+ </section>
+}
+
+function WorkspaceTelegramNotice(): ReactNode {
+ const { list, error: loadError } = useWorkspaceList()
+ const workspace = list?.workspaces.find((w) => w.isDefault)
+ const [busy, setBusy] = useState(false)
+ const [error, setError] = useState('')
+ const switchWorkspace = async (): Promise<void> => {
+ if (!workspace || !window.tucano.workspaces) return
+ setBusy(true)
+ setError('')
+ try { await window.tucano.workspaces.switch(workspace.id) }
+ catch (e) { setError(e instanceof Error ? e.message : String(e)) }
+ finally { setBusy(false) }
+ }
+ return <Card title="Telegram" lead={L('O bot do Telegram fica no workspace padrão. Dois workspaces não podem consultar o mesmo token.', 'The Telegram bot stays in the default workspace. Two workspaces cannot poll the same token.')}>
+ {workspace ? <p className="muted small">
+ {L('Para configurar o Telegram, abra o workspace ', 'To configure Telegram, open workspace ')}
+ <button className="link" disabled={busy} title={L(`Trocar para ${workspace.name}`, `Switch to ${workspace.name}`)} onClick={() => void switchWorkspace()}>{workspace.name}</button>.
+ </p> : !loadError && <p className="muted small">{L('Carregando o workspace padrão…', 'Loading the default workspace…')}</p>}
+ {(error || loadError) && <p className="field__error" role="alert">{error || loadError}</p>}
+ </Card>
+}
+
// The phone (spec §19): a Telegram bot of the user's own, paired with a code.
function PhoneCard({ info }: { info?: TelegramInfo }): ReactNode {
const [token, setToken] = useState('')
@@ -1842,6 +1903,7 @@ function VoiceCard(): ReactNode {
export function SettingsPage(): ReactNode {
const settings = useStore((s) => s.settings)
const packaged = useStore((s) => s.packaged)
+ const defaultWorkspace = useStore((s) => s.defaultWorkspace)
// At work, Jev and Telegram stay: the person decides, told what leaves the gateway.
const work = onGateway(settings)
const tabs = SETTINGS_TABS()
@@ -1853,7 +1915,13 @@ export function SettingsPage(): ReactNode {
<div className="agent-form">
{pane('geral') && (
<Card title="Workspace">
- <Field label={L('Nome', 'Name')}>
+ <p className="muted small">{L('Agentes, conversas, conectores e memórias ficam neste workspace. Os logins do Claude Code e OpenCode continuam compartilhados no computador. Um workspace não é uma sandbox do sistema.', 'Agents, conversations, connectors and memories stay in this workspace. Claude Code and OpenCode sign-ins are still shared on this computer. A workspace is not an OS sandbox.')}</p>
+ {window.tucano.workspaces && (
+ <Field label={L('Nome do workspace', 'Workspace name')}>
+ <input value={settings.workspaceLabel ?? ''} placeholder={settings.workspaceName} maxLength={120} onChange={(e) => updateSettings({ workspaceLabel: e.target.value })} />
+ </Field>
+ )}
+ <Field label={L('Como os agentes te chamam', 'What the agents call you')}>
<input value={settings.workspaceName} onChange={(e) => updateSettings({ workspaceName: e.target.value })} />
</Field>
<div className="field">
@@ -1960,7 +2028,7 @@ export function SettingsPage(): ReactNode {
)}
{pane('integracoes') && work && <OutsideGateway what={L('as aprovações, as perguntas dos agentes e o fim das rotinas vão pro seu Telegram, com o texto de cada uma.', 'approvals, the agents’ questions and routine results go to your Telegram, with the text of each.')} />}
- {pane('integracoes') && <PhoneCard info={settings.telegram} />}
+ {pane('integracoes') && (defaultWorkspace ? <PhoneCard info={settings.telegram} /> : <WorkspaceTelegramNotice />)}
{pane('modelos') && (
<Card title={L('Memória', 'Memory')} lead={L('Um modelo pequeno resume o que sai da janela de cada conversa e, do mesmo trecho, tira o que vale lembrar sobre você.', 'A small model summarizes what leaves each conversation’s window and, from the same stretch, picks what’s worth remembering about you.')}>
@@ -1987,8 +2055,9 @@ export function SettingsPage(): ReactNode {
<strong>{L('Abrir ao ligar o computador', 'Open when the computer starts')}</strong>
<p className="muted small">{packaged ? L('Assim nenhuma rotina depende de você lembrar de abrir o app.', 'So no routine depends on you remembering to open the app.') : L('Só no app instalado. Rodando com npm run dev, fica desligado.', 'Only in the installed app. Running with npm run dev, it stays off.')}</p>
</div>
- <Toggle on={!!settings.openAtLogin && packaged} onChange={(v) => packaged && updateSettings({ openAtLogin: v })} />
+ <Toggle on={!!settings.openAtLogin && packaged && defaultWorkspace} onChange={(v) => packaged && defaultWorkspace && updateSettings({ openAtLogin: v })} />
</div>
+ {!defaultWorkspace && <p className="muted small">{L('Abrir ao ligar o computador é uma configuração do app: ajuste no workspace padrão. Todos os workspaces iniciam juntos.', 'Opening at login is an app setting: change it in the default workspace. All workspaces start together.')}</p>}
<div className="key-row">
<Icon name="moon" />
<div className="grow">
@@ -2048,6 +2117,7 @@ export function SettingsPage(): ReactNode {
</div>
</Card>
)}
+ {pane('geral') && <WorkspaceDangerArea />}
</div>
</Page>
)
diff --git a/src/renderer/src/components/Routines.tsx b/src/renderer/src/components/Routines.tsx
index 29d2b9b..2133d25 100644
--- a/src/renderer/src/components/Routines.tsx
+++ b/src/renderer/src/components/Routines.tsx
@@ -23,6 +23,7 @@ import {
} from '../store'
import { Card, Field, Sheet, Toggle } from './Pages'
import { AgentAvatar, Icon, ownColor, shiftWeek, startOfWeek, weekRange } from './ui'
+import { Modal } from './Modal'
const DAYS = (): string[] => (lang() === 'en' ? ['S', 'M', 'T', 'W', 'T', 'F', 'S'] : ['D', 'S', 'T', 'Q', 'Q', 'S', 'S'])
const DAY_NAMES = (): string[] => (lang() === 'en' ? ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] : ['domingo', 'segunda', 'terça', 'quarta', 'quinta', 'sexta', 'sábado'])
@@ -62,7 +63,7 @@ const LAST = (): Partial<Record<RunStatus, { label: string; tone: string }>> =>
interrupted: { label: L('interrompida', 'interrupted'), tone: '' }
})
-export const webhookUrl = (token: string): string => `http://127.0.0.1:${WEBHOOK_PORT}/gatilho/${token}`
+export const webhookUrl = (token: string, port = WEBHOOK_PORT): string => `http://127.0.0.1:${port}/gatilho/${token}`
// "Todo dia às 9h", "A cada 5 min, quando aparecer algo novo em Linear · list_issues"
function describeRoutine(r: Pick<Routine, 'schedule' | 'trigger'>, connectorName?: string): string {
@@ -115,7 +116,6 @@ export function RoutinesPage(): ReactNode {
useEffect(() => {
const onKey = (e: KeyboardEvent): void => {
const typing = (e.target as HTMLElement | null)?.closest('input, textarea, select, [contenteditable]')
- if (draft && e.key === 'Escape') return setDraft(null)
if (draft || typing || e.metaKey || e.ctrlKey || e.altKey) return
if (e.key === 'ArrowLeft') setWeek((w) => shiftWeek(w, -1))
else if (e.key === 'ArrowRight') setWeek((w) => shiftWeek(w, 1))
@@ -256,11 +256,9 @@ export function RoutinesPage(): ReactNode {
{open && <Popover occ={open.occ} rect={open.rect} now={now} onClose={() => setOpen(null)} onEdit={(r) => (setOpen(null), setDraft({ ...r }))} />}
{draft && (
- <div className="modal" onMouseDown={(e) => e.target === e.currentTarget && setDraft(null)}>
- <div className="form-modal">
- <RoutineForm key={draft.id ?? 'new'} draft={draft} onChange={setDraft} onClose={() => setDraft(null)} />
- </div>
- </div>
+ <Modal title={draft.id ? L('Editar rotina', 'Edit routine') : L('Nova rotina', 'New routine')} variant="form" onClose={() => setDraft(null)}>
+ <RoutineForm key={draft.id ?? 'new'} draft={draft} onChange={setDraft} onClose={() => setDraft(null)} />
+ </Modal>
)}
</Sheet>
)
@@ -508,7 +506,8 @@ function Calendar({
function Hook({ token }: { token: string }): ReactNode {
const [copied, setCopied] = useState(false)
- const cmd = `curl -d "${L('o que aconteceu', 'what happened')}" ${webhookUrl(token)}`
+ const port = useStore((s) => s.webhookPort)
+ const cmd = `curl -d "${L('o que aconteceu', 'what happened')}" ${webhookUrl(token, port)}`
return (
<div className="row row--center routine__hook">
<code className="small grow truncate">{cmd}</code>
diff --git a/src/renderer/src/components/Sidebar.tsx b/src/renderer/src/components/Sidebar.tsx
index f3f3334..371a63a 100644
--- a/src/renderer/src/components/Sidebar.tsx
+++ b/src/renderer/src/components/Sidebar.tsx
@@ -24,6 +24,7 @@ import { ContextMenu, confirmDialog, type MenuItem, type MenuState } from './Dia
import { FoldToggle, useFold } from './Fold'
import { GettingStarted } from './Onboarding'
import { UpdateNote } from './Update'
+import { WorkspaceSelector } from './Workspaces'
import { AgentAvatar, Icon, TucaMark, useJustEnded, type IconName } from './ui'
// The wiki stays lit on any of its pages.
@@ -231,11 +232,10 @@ export function Sidebar(): ReactNode {
<aside className="sidebar">
<div className="sidebar__drag" />
<div className="workspace">
- <span className="workspace__logo">{s.settings.workspaceName.slice(0, 1)}</span>
- <span className="workspace__name">{s.settings.workspaceName}</span>
+ <WorkspaceSelector />
<button
className={`icon-btn ${s.settings.paused ? 'is-paused' : ''}`}
- title={s.settings.paused ? L('Retomar os agentes', 'Resume the agents') : L('Pausar tudo: nenhum agente começa a trabalhar e nenhuma rotina roda', 'Pause everything: no agent starts working and no routine runs')}
+ title={s.settings.paused ? L('Retomar os agentes deste workspace', 'Resume agents in this workspace') : L('Pausar este workspace: nenhum agente começa a trabalhar e nenhuma rotina roda', 'Pause this workspace: no agent starts working and no routine runs')}
onClick={() => updateSettings({ paused: !s.settings.paused })}
>
<Icon name={s.settings.paused ? 'play' : 'pause'} />
diff --git a/src/renderer/src/components/Skills.tsx b/src/renderer/src/components/Skills.tsx
index 2a06bd5..8582fb7 100644
--- a/src/renderer/src/components/Skills.tsx
+++ b/src/renderer/src/components/Skills.tsx
@@ -27,6 +27,7 @@ import {
import { Card, Field, Sheet } from './Pages'
import { confirmDialog } from './Dialogs'
import { ago, AgentAvatar, Icon, time } from './ui'
+import { Modal } from './Modal'
type Place = { kind: 'list' } | { kind: 'skill'; id: string } | { kind: 'review' }
@@ -62,11 +63,9 @@ export function SkillsPage(): ReactNode {
const toList = (): void => setPlace({ kind: 'list' })
const form = draft && (
- <div className="modal" onMouseDown={(e) => e.target === e.currentTarget && setDraft(null)}>
- <div className="form-modal">
- <SkillForm key={draft.id ?? 'new'} draft={draft} onChange={setDraft} onClose={() => setDraft(null)} />
- </div>
- </div>
+ <Modal title={draft.id ? L('Editar skill', 'Edit skill') : L('Nova skill', 'New skill')} variant="form" onClose={() => setDraft(null)}>
+ <SkillForm key={draft.id ?? 'new'} draft={draft} onChange={setDraft} onClose={() => setDraft(null)} />
+ </Modal>
)
if (open)
diff --git a/src/renderer/src/components/Update.tsx b/src/renderer/src/components/Update.tsx
index 25a3581..65d51c6 100644
--- a/src/renderer/src/components/Update.tsx
+++ b/src/renderer/src/components/Update.tsx
@@ -7,7 +7,7 @@ import { L, lang, locale } from '../../../shared/lang'
import { newsSince, type PtSummary, type ReleaseNotes } from '../../../shared/release-notes'
import type { UpdateState } from '../../../shared/types'
import { updateSettings, useStore } from '../store'
-import { Modal } from './Dialogs'
+import { Modal } from './Modal'
import { ago } from './ui'
const RELEASES = 'https://github.com/eduwxyz/tucano/releases'
diff --git a/src/renderer/src/components/WorkspaceManager.tsx b/src/renderer/src/components/WorkspaceManager.tsx
new file mode 100644
index 0000000..c149700
--- /dev/null
+++ b/src/renderer/src/components/WorkspaceManager.tsx
@@ -0,0 +1,136 @@
+import { useEffect, useState, type ReactNode } from 'react'
+import { L } from '../../../shared/lang'
+import { ALL_PARTS, suggestWorkspaceCopyName, sortWorkspaces, WORKSPACE_PARTS, workspaceParts, type WorkspacePart, type WorkspaceParts } from '../../../shared/workspaces'
+import { updateSettings, useStore } from '../store'
+import { Modal } from './Modal'
+import { Icon } from './ui'
+import { useWorkspaceList } from './Workspaces'
+
+const PARTS = (): Record<WorkspacePart, { label: string; about: string }> => ({
+ general: { label: L('Configurações gerais', 'General settings'), about: L('Seu nome, o idioma, os modelos do roteador e da memória, limites, horário de silêncio e voz.', 'Your name, the language, the router and memory models, limits, quiet hours and voice.') },
+ context: { label: L('Contexto', 'Context'), about: L('O texto que entra em toda conversa: quem você é, o que faz, o que importa.', 'The text that goes in every conversation: who you are, what you do, what matters.') },
+ agents: { label: L('Agentes', 'Agents'), about: L('Instruções, modelos, computadores e pastas emprestadas, sem as memórias nem os arquivos.', 'Instructions, models, computers and lent folders, without their memories or files.') },
+ channels: { label: L('Canais', 'Channels'), about: L('Nomes, temas e quem está em cada um, sem as mensagens.', 'Names, topics and who is in each, without the messages.') },
+ skills: { label: L('Skills', 'Skills'), about: L('Sem os agentes, as de agentes específicos vêm arquivadas.', 'Without the agents, those of specific agents come archived.') },
+ connectors: { label: L('Conectores e credenciais', 'Connectors and credentials'), about: L('Os conectores com suas chaves e logins, e o GitHub. Sem eles, os agentes vêm sem permissões.', 'The connectors with their keys and sign-ins, and GitHub. Without them, agents come with no grants.') },
+ routines: { label: L('Rotinas', 'Routines'), about: L('As ligadas rodam aqui também, com endereços de gatilho novos. Vêm com os agentes.', 'Enabled ones run here too, with new trigger addresses. They come with the agents.') }
+})
+
+// Creating and duplicating are the same: a name, and what comes along from a workspace.
+type Draft = { from: { id: string; name: string }; name: string; parts: WorkspaceParts; duplicate: boolean }
+
+// `create`: opened from the switcher's +, straight to naming the new workspace.
+export function WorkspaceManager({ onClose, create = false }: { onClose: () => void; create?: boolean }): ReactNode {
+ const { list, error: loadError } = useWorkspaceList()
+ const selectedId = list?.selected
+ const workspaces = sortWorkspaces(list?.workspaces)
+ const onboarding = useStore((s) => s.settings.onboarding)
+ const [draft, setDraft] = useState<Draft | null>(null)
+ const [busy, setBusy] = useState(false)
+ const [error, setError] = useState('')
+ const api = window.tucano.workspaces
+ const available = list?.workspaces.filter((w) => w.status === 'ready') ?? []
+ const allPaused = available.length > 0 && available.every((w) => w.paused)
+ useEffect(() => {
+ if (api && !onboarding?.workspaceManagerSeen) updateSettings({ onboarding: { ...(onboarding ?? { done: true }), workspaceManagerSeen: true } })
+ }, [api, onboarding])
+ const newDraft = (): Draft | null => {
+ const here = list?.workspaces.find((w) => w.id === list.selected)
+ return here ? { from: { id: here.id, name: here.name }, name: '', parts: workspaceParts({ general: true }), duplicate: false } : null
+ }
+ // From the switcher's +: the form as soon as the list says which workspace this is.
+ useEffect(() => {
+ if (create && list && !draft) setDraft(newDraft())
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [create, list])
+ const perform = async (action: () => Promise<unknown>): Promise<void> => {
+ setBusy(true)
+ setError('')
+ try { await action() } catch (e) { setError(e instanceof Error ? e.message : String(e)) }
+ finally { setBusy(false) }
+ }
+ const back = (): void => { if (create) onClose(); else { setDraft(null); setError('') } }
+ const close = (): void => { if (!busy) { if (draft) back(); else onClose() } }
+ const save = (): Promise<void> => perform(async () => {
+ if (!api || !draft || !draft.name.trim()) return
+ if (!WORKSPACE_PARTS.some((p) => draft.parts[p])) return api.create(draft.name.trim())
+ const id = await api.duplicate(draft.from.id, draft.name.trim(), draft.parts)
+ await api.switch(id)
+ })
+ if (!api) return null
+ if (create && !draft) return null // waiting for the list
+ if (draft) {
+ const info = PARTS()
+ const nothing = !WORKSPACE_PARTS.some((p) => draft.parts[p])
+ const pick = (p: WorkspacePart, on: boolean): void => setDraft({ ...draft, parts: workspaceParts({ ...draft.parts, [p]: on }) })
+ const title = draft.duplicate ? L('Duplicar workspace', 'Duplicate workspace') : L('Criar workspace', 'Create Workspace')
+ return <Modal key="draft" title={title} onClose={close} className="workspace-manager">
+ <div className="workspace-manager__body">
+ <label className="field">
+ <span className="field__label">{L('Nome do workspace', 'Workspace name')}</span>
+ <input autoFocus maxLength={120} disabled={busy} value={draft.name} placeholder={L('Ex.: Empresa, Pessoal', 'E.g. Company, Personal')} onChange={(event) => setDraft({ ...draft, name: event.target.value })} onKeyDown={(event) => { if (event.key === 'Enter' && !busy && draft.name.trim()) { event.preventDefault(); void save() } }} />
+ </label>
+ <div className="field">
+ <span className="field__label">{L(`O que levar de “${draft.from.name}”?`, `What to bring from “${draft.from.name}”?`)}</span>
+ <div className="workspace-manager__parts">
+ {WORKSPACE_PARTS.map((p) => {
+ const locked = p === 'routines' && !draft.parts.agents
+ return <label key={p} className={`check workspace-manager__carry ${locked ? 'is-locked' : ''}`}>
+ <input type="checkbox" checked={draft.parts[p]} disabled={busy || locked} onChange={(event) => pick(p, event.target.checked)} />
+ <span>
+ <strong>{info[p].label}</strong>
+ <small className="muted">{info[p].about}</small>
+ </span>
+ </label>
+ })}
+ </div>
+ </div>
+ <p className="small muted">{nothing
+ ? L('Sem nada marcado, começa vazio, com a introdução.', 'With nothing ticked, it starts empty, with the introduction.')
+ : draft.parts.agents
+ ? L('Com os agentes, um workspace já configurado pula a introdução.', 'With the agents, a set-up workspace skips the introduction.')
+ : L('Sem os agentes, começa pela introdução, já com o que veio.', 'Without the agents, it starts with the introduction, from what came.')}</p>
+ <p className="small muted">{L('Nunca vêm: mensagens, memórias, resumos, aprovações, histórico de uso, arquivos dos computadores, sessões do navegador e as contas extras do Claude Code e do Codex (na cópia, os agentes usam o login padrão). O Telegram fica no workspace padrão. Mudanças aqui não alteram o original; pastas emprestadas continuam sendo as mesmas.', 'Never coming: messages, memories, summaries, approvals, usage history, computers’ files, browser sessions and the extra Claude Code and Codex accounts (in the copy, agents use the usual sign-in). Telegram stays in the default workspace. Changes here don’t change the original; lent folders are still the same ones.')}</p>
+ {error && <p className="field__error" role="alert">{error}</p>}
+ </div>
+ <footer className="modal__foot">
+ <button className="btn btn--ghost btn--sm" disabled={busy} onClick={back}>{L('Cancelar', 'Cancel')}</button>
+ <button className="btn btn--primary btn--sm" disabled={busy || !draft.name.trim()} onClick={() => void save()}>{busy ? L('Criando…', 'Creating…') : title}</button>
+ </footer>
+ </Modal>
+ }
+ return <Modal key="manager" title={L('Gerenciar workspaces', 'Manage workspaces')} onClose={close} className="workspace-manager" actions={
+ <button className="btn btn--sm" disabled={busy || !available.length} title={allPaused ? L('Ativar todas as rotinas', 'Resume all routines') : L('Pausar todas as rotinas', 'Pause all routines')} aria-label={allPaused ? L('Ativar todas as rotinas', 'Resume all routines') : L('Pausar todas as rotinas', 'Pause all routines')} onClick={() => void perform(() => api.setPaused(!allPaused))}>
+ <Icon name={allPaused ? 'play' : 'pause'} size={14} />{allPaused ? L('Retomar todos', 'Resume all') : L('Pausar todos', 'Pause all')}
+ </button>
+ }>
+ <p className="muted small modal__lead">{L('Cada workspace tem seus próprios agentes, conversas, memórias e configurações.', 'Each workspace has its own agents, conversations, memories and settings.')}</p>
+ <div className="workspace-manager__list">
+ {!list && !loadError && <p className="muted small">{L('Carregando…', 'Loading…')}</p>}
+ {workspaces.map((w) => {
+ const selected = w.id === selectedId
+ const switchTitle = selected ? L(`Workspace atual: ${w.name}`, `Current workspace: ${w.name}`) : L(`Trocar para ${w.name}`, `Switch to ${w.name}`)
+ const duplicateTitle = L(`Duplicar ${w.name}`, `Duplicate ${w.name}`)
+ const pauseTitle = w.paused ? L(`Retomar as rotinas de ${w.name}`, `Resume ${w.name}'s routines`) : L(`Pausar as rotinas de ${w.name}`, `Pause ${w.name}'s routines`)
+ const deleteTitle = w.isDefault ? L('O workspace padrão não pode ser excluído.', 'The default workspace cannot be deleted.') : L(`Excluir ${w.name}`, `Delete ${w.name}`)
+ return <div className="workspace-manager__row" key={w.id}>
+ <div className="workspace-manager__name">
+ <span>{w.name}</span>
+ <span className="workspace-manager__id" title={w.id}>{w.id.slice(-7)}</span>
+ </div>
+ <div className="row">
+ <button className="icon-btn workspace-manager__switch" disabled={busy || selected} aria-pressed={selected} title={switchTitle} aria-label={switchTitle} onClick={() => void perform(() => api.switch(w.id))}><Icon name="check" size={16} /></button>
+ <button className="icon-btn workspace-manager__pause" disabled={busy || w.status !== 'ready'} aria-pressed={w.paused} title={pauseTitle} aria-label={pauseTitle} onClick={() => void perform(() => api.setPaused(!w.paused, w.id))}><Icon name={w.paused ? 'play' : 'pause'} size={16} /></button>
+ <button className="icon-btn" disabled={busy || w.status !== 'ready'} title={duplicateTitle} aria-label={duplicateTitle} onClick={() => { setError(''); setDraft({ from: { id: w.id, name: w.name }, name: suggestWorkspaceCopyName(w.name, (list?.workspaces ?? []).map((workspace) => workspace.name)), parts: ALL_PARTS, duplicate: true }) }}><Icon name="copy" size={16} /></button>
+ <button className="icon-btn workspace-manager__delete" disabled={busy || w.isDefault} title={deleteTitle} aria-label={deleteTitle} onClick={() => void perform(() => api.delete(w.id))}><Icon name="trash" size={16} /></button>
+ </div>
+ </div>
+ })}
+ </div>
+ {(error || loadError) && <p className="field__error modal__lead" role="alert">{error || loadError}</p>}
+ <footer className="modal__foot">
+ <button className="btn btn--ghost btn--sm" disabled={busy} onClick={onClose}>{L('Fechar', 'Close')}</button>
+ <button className="btn btn--primary btn--sm" disabled={busy || !list} onClick={() => { setError(''); setDraft(newDraft()) }}><Icon name="plus" size={14} />{L('Criar workspace', 'Create Workspace')}</button>
+ </footer>
+ </Modal>
+}
diff --git a/src/renderer/src/components/Workspaces.tsx b/src/renderer/src/components/Workspaces.tsx
new file mode 100644
index 0000000..3456cd2
--- /dev/null
+++ b/src/renderer/src/components/Workspaces.tsx
@@ -0,0 +1,79 @@
+import { useEffect, useRef, useState, type ReactNode } from 'react'
+import { L } from '../../../shared/lang'
+import { sortWorkspaces, workspaceLabel, type WorkspaceList } from '../../../shared/workspaces'
+import { openDialog, useStore } from '../store'
+import { Icon } from './ui'
+
+export function useWorkspaceList(): { list: WorkspaceList | null; error: string } {
+ const [list, setList] = useState<WorkspaceList | null>(null)
+ const [error, setError] = useState('')
+ const api = window.tucano.workspaces
+ useEffect(() => {
+ if (!api) return
+ let active = true
+ const off = api.subscribe((next) => { if (active) setList(next) })
+ void api.list().then((next) => { if (active) setList(next) }, (e: unknown) => { if (active) setError(String(e)) })
+ return () => { active = false; off() }
+ }, [api])
+ return { list, error }
+}
+
+export function WorkspaceSelector(): ReactNode {
+ const name = useStore((s) => workspaceLabel(s.settings))
+ const { list, error: loadError } = useWorkspaceList()
+ const selectedId = list?.selected
+ const workspaces = sortWorkspaces(list?.workspaces)
+ const [open, setOpen] = useState(false)
+ const [busy, setBusy] = useState(false)
+ const [error, setError] = useState('')
+ const root = useRef<HTMLDivElement>(null)
+ const button = useRef<HTMLButtonElement>(null)
+ const api = window.tucano.workspaces
+ useEffect(() => {
+ if (!open) return
+ const outside = (event: MouseEvent): void => { if (!root.current?.contains(event.target as Node)) setOpen(false) }
+ document.addEventListener('mousedown', outside)
+ root.current?.querySelector<HTMLButtonElement>('[role="menuitemradio"]')?.focus()
+ return () => document.removeEventListener('mousedown', outside)
+ }, [open])
+ const perform = async (action: () => Promise<void>): Promise<void> => {
+ setBusy(true)
+ setError('')
+ try { await action() } catch (e) { setError(e instanceof Error ? e.message : String(e)) }
+ finally { setBusy(false) }
+ }
+ const label = <><span className="workspace__logo">{name.slice(0, 1)}</span><span className="workspace__name">{name}</span></>
+ if (!api) return <div className="workspace-picker__label" title={name}>{label}</div>
+ return (
+ <div className="workspace-picker" ref={root}>
+ <button ref={button} className="workspace-picker__button" title={name} aria-label={L('Trocar workspace', 'Switch workspace')} aria-haspopup="menu" aria-expanded={open} onClick={() => setOpen(!open)}>{label}</button>
+ {open && <div className="workspace-picker__menu" role="menu" aria-label="Workspaces" onKeyDown={(event) => {
+ if (event.key === 'Escape') { setOpen(false); button.current?.focus() }
+ if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) {
+ event.preventDefault()
+ const items = [...event.currentTarget.querySelectorAll<HTMLButtonElement>('button:not(:disabled)')]
+ const index = items.indexOf(document.activeElement as HTMLButtonElement)
+ const next = event.key === 'Home' ? 0 : event.key === 'End' ? items.length - 1 : (index + (event.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length
+ items[next]?.focus()
+ }
+ }}>
+ <div className="workspace-picker__head">
+ <span className="muted small">Workspaces</span>
+ <div className="workspace-picker__actions">
+ <button className="icon-btn icon-btn--sm" role="menuitem" disabled={busy} title={L('Criar workspace', 'Create Workspace')} aria-label={L('Criar workspace', 'Create Workspace')} onClick={() => { setOpen(false); openDialog({ kind: 'workspaces', create: true }) }}><Icon name="plus" size={14} /></button>
+ <button className="icon-btn icon-btn--sm" role="menuitem" disabled={busy} title={L('Gerenciar workspaces', 'Manage workspaces')} aria-label={L('Gerenciar workspaces', 'Manage workspaces')} onClick={() => { setOpen(false); openDialog({ kind: 'workspaces' }) }}><Icon name="gear" size={14} /></button>
+ </div>
+ </div>
+ {workspaces.map((w) => <button key={w.id} className="menu__item" role="menuitemradio" aria-checked={w.id === selectedId} disabled={busy} onClick={() => void perform(() => api.switch(w.id))}>
+ <span className="workspace-picker__check" aria-hidden="true">{w.id === selectedId && <Icon name="check" size={14} />}</span>
+ <span className="grow">{w.name}</span>
+ {w.status === 'failed' ? <span className="muted small">{L('Tentar de novo', 'Retry')}</span> : <>
+ {!!w.approvals && <span className="badge" title={L('Aprovações', 'Approvals')}>{w.approvals}</span>}
+ {!!w.unread && <span className="badge badge--soft" title={L('Não lidas', 'Unread')}>{w.unread}</span>}
+ </>}
+ </button>)}
+ {(error || loadError) && <p className="field__error" role="alert">{error || loadError}</p>}
+ </div>}
+ </div>
+ )
+}
diff --git a/src/renderer/src/rpc.ts b/src/renderer/src/rpc.ts
index 287c547..7a37144 100644
--- a/src/renderer/src/rpc.ts
+++ b/src/renderer/src/rpc.ts
@@ -1,10 +1,20 @@
import { L } from '../../shared/lang'
import type { CoreEvent, Method, Params, Request, Result, Wire } from '../../shared/rpc'
import type { UpdateState } from '../../shared/types'
+import type { WorkspaceList, WorkspaceParts } from '../../shared/workspaces'
declare global {
interface Window {
tucano: {
+ workspaces?: {
+ list: () => Promise<WorkspaceList>
+ create: (name?: string) => Promise<void>
+ delete: (id?: string) => Promise<void>
+ duplicate: (id: string, name?: string, parts?: WorkspaceParts) => Promise<string>
+ setPaused: (paused: boolean, id?: string) => Promise<void>
+ switch: (id: string) => Promise<void>
+ subscribe: (cb: (list: WorkspaceList) => void) => () => void
+ }
connect: () => void
pickFolder: () => Promise<string | null>
pathOf?: (file: File) => string // a dropped or picked file's path on this computer (desktop only)
diff --git a/src/renderer/src/store.ts b/src/renderer/src/store.ts
index 48d56aa..a79f4c0 100644
--- a/src/renderer/src/store.ts
+++ b/src/renderer/src/store.ts
@@ -62,6 +62,8 @@ export type View =
| { kind: 'settings' }
export interface State {
+ webhookPort: number
+ defaultWorkspace: boolean
ready: boolean
threadSeen: Record<string, number> // thread root id → when I last had it open (what came after is new)
navOpen: boolean // on a phone, the sidebar slid in over the view
@@ -99,7 +101,7 @@ export interface Toast {
leaving?: boolean // fading out
}
-export type Dialog = { kind: 'members' | 'settings'; id: string } | { kind: 'archived' | 'new-channel' | 'search' } | { kind: 'oauth'; id: string; url: string }
+export type Dialog = { kind: 'members' | 'settings'; id: string } | { kind: 'archived' | 'new-channel' | 'search' } | { kind: 'workspaces'; create?: boolean } | { kind: 'oauth'; id: string; url: string }
// `thread`: the replies to a message (its id), next to the conversation.
export type Panel = { kind: 'artifact'; id: string } | { kind: 'service'; agentId: string; name: string } | { kind: 'browser'; agentId: string } | { kind: 'thread'; id: string }
@@ -123,6 +125,8 @@ const loadSeen = (): Record<string, number> => {
}
let state: State = {
+ webhookPort: 47717,
+ defaultWorkspace: true,
ready: false,
threadSeen: loadSeen(),
wikiRev: 0,
@@ -220,31 +224,14 @@ function apply(e: CoreEvent): void {
set((s) => {
switch (e.type) {
case 'message': {
- const known = s.messages.some((m) => m.id === e.message.id)
- const viewing = s.view?.kind === 'conversation' && s.view.id === e.message.conversationId
- const fromAgent = e.message.author.kind === 'agent' || e.message.author.kind === 'routine'
- // A reply that lands while you're elsewhere is new content too: the end of
- // the run, or it stopping for your turn (a question, an approval — the
- // states the core notifies). Counted once: if the badge already counts
- // this conversation, the run's start is already in it.
- const finished =
- known && fromAgent && !viewing && e.message.run !== undefined
- && ['done', 'failed', 'limit_reached', 'waiting_input', 'waiting_approval'].includes(e.message.run.status)
- && s.messages.find((m) => m.id === e.message.id)?.run?.status !== e.message.run.status
- && (s.conversations.find((c) => c.id === e.message.conversationId)?.unread ?? 0) === 0
- const conversations =
- fromAgent && !viewing && (!known || finished)
- ? s.conversations.map((c) => (c.id === e.message.conversationId ? { ...c, unread: (c.unread ?? 0) + 1 } : c))
- : s.conversations
- return { ...s, conversations, messages: upsert(s.messages, e.message) }
+ return { ...s, messages: upsert(s.messages, e.message) }
}
case 'delta':
return { ...s, messages: s.messages.map((m) => (m.id === e.id ? { ...m, text: m.text + e.text } : m)) }
case 'agent':
return { ...s, agents: upsert(s.agents, e.agent) }
case 'conversation': {
- const prev = s.conversations.find((c) => c.id === e.conversation.id)
- return { ...s, conversations: upsert(s.conversations, { ...e.conversation, unread: prev?.unread }) }
+ return { ...s, conversations: upsert(s.conversations, e.conversation) }
}
case 'settings':
return withSettings(s, e.settings)
@@ -309,7 +296,10 @@ export async function start(): Promise<void> {
let viewing: string | null = null
subscribe(() => {
const id = state.view?.kind === 'conversation' ? state.view.id : null
- if (id !== viewing) window.tucano.viewing((viewing = id))
+ if (id !== viewing) {
+ window.tucano.viewing((viewing = id))
+ if (id && state.ready) void call('markRead', { conversationId: id })
+ }
})
await connect(apply)
const snap = await call('snapshot')
@@ -319,6 +309,8 @@ export async function start(): Promise<void> {
return {
...withSettings(s, snap.settings),
ready: true,
+ webhookPort: snap.webhookPort ?? 47717,
+ defaultWorkspace: snap.defaultWorkspace ?? true,
view,
agents: snap.agents,
conversations: snap.conversations,
@@ -512,7 +504,7 @@ export const setTopic = (id: string, topic: string): Promise<void> => call('setT
export const setThreads = (conversationId: string, on: boolean): Promise<void> => call('setThreads', { conversationId, on })
export const setChannelMembers = (id: string, agentIds: string[]): Promise<void> => call('setChannelMembers', { id, agentIds })
export const deleteConversation = (id: string): Promise<void> => call('deleteConversation', { id })
-export const markRead = (id: string): void => set((s) => ({ ...s, conversations: s.conversations.map((c) => (c.id === id ? { ...c, unread: 0 } : c)) }))
+export const markRead = (id: string): void => { void call('markRead', { conversationId: id }) }
// `threadId`: a reply in the thread that message started.
export const sendMessage = (conversationId: string, text: string, images: ImageUpload[] = [], threadId?: string): void => {
diff --git a/src/renderer/src/styles.css b/src/renderer/src/styles.css
index 72ee31a..8f14816 100644
--- a/src/renderer/src/styles.css
+++ b/src/renderer/src/styles.css
@@ -423,6 +423,7 @@ h3 {
padding: 0 12px 10px 14px;
}
.workspace__logo {
+ flex-shrink: 0;
width: 26px;
height: 26px;
border-radius: 7px;
@@ -436,7 +437,43 @@ h3 {
.workspace__name {
font-weight: 600;
flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
}
+.workspace-picker { position: relative; flex: 1; min-width: 0; }
+.workspace-picker__check { display: flex; align-items: center; width: 14px; flex-shrink: 0; }
+.workspace-picker__head { display: flex; align-items: center; justify-content: space-between; padding: 2px 8px 5px; }
+.workspace-picker__actions { display: flex; align-items: center; gap: 4px; }
+.modal__card.workspace-manager { width: min(600px, calc(100vw - 32px)); }
+.workspace-manager__body { min-height: 0; overflow-y: auto; padding-bottom: 12px; }
+.workspace-manager__list { min-height: 0; max-height: 50vh; overflow-y: auto; }
+.workspace-manager__row { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 12px 0; }
+.workspace-manager__row + .workspace-manager__row { border-top: 1px solid var(--border); }
+.workspace-manager__name { display: flex; flex-direction: column; align-items: flex-start; gap: 2px; min-width: 0; text-align: left; }
+.workspace-manager__name > span:first-child { overflow-wrap: anywhere; font-weight: 600; }
+.workspace-manager__id { font-size: 11px; color: var(--text-3); }
+.workspace-manager__parts { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 6px; }
+.workspace-manager__carry { display: flex; align-items: flex-start; gap: 10px; padding: 8px 12px; }
+.workspace-manager__carry.is-locked { opacity: 0.55; cursor: not-allowed; }
+.workspace-manager__carry input { margin-top: 3px; }
+.workspace-manager__carry span { display: flex; flex-direction: column; gap: 2px; }
+.workspace-manager__carry small { font-size: 12px; line-height: 1.4; }
+.workspace-manager__row > .row { flex-shrink: 0; }
+.workspace-manager__switch[aria-pressed='true'] { background: var(--ok-soft); color: var(--ok); }
+.workspace-manager__pause[aria-pressed='true'] { background: var(--warn-soft); color: var(--warn); }
+.workspace-manager__row .workspace-manager__delete { color: var(--danger); }
+.workspace-manager__row .workspace-manager__delete:hover { background: var(--danger-soft); }
+.workspace-manager__row .workspace-manager__delete:disabled { color: var(--text-3); background: transparent; cursor: not-allowed; }
+.workspace-danger .card { border-color: var(--danger); }
+.workspace-danger .card__head h2 { color: var(--danger); }
+.workspace-danger__section + .workspace-danger__section { margin-top: 20px; padding-top: 20px; border-top: 1px solid var(--border); }
+.workspace-danger__section h3 { margin: 0 0 8px; font-size: 14px; font-weight: 600; }
+.workspace-picker__button, .workspace-picker__label { display: flex; align-items: center; gap: 10px; min-width: 0; }
+.workspace-picker__button { width: 100%; padding: 4px; margin: -4px; box-sizing: content-box; border: 1px solid transparent; border-radius: 7px; background: transparent; color: inherit; text-align: left; cursor: pointer; font: inherit; }
+.workspace-picker__button:hover, .workspace-picker__button:focus-visible { border-color: var(--border); }
+.workspace-picker__menu { position: absolute; top: calc(100% + 8px); left: 0; width: 260px; max-width: calc(100vw - 32px); max-height: 60vh; overflow-y: auto; padding: 5px; border: 1px solid var(--border); border-radius: 9px; background: var(--panel); box-shadow: 0 8px 28px #0002; z-index: 50; }
.sidebar__scroll {
flex: 1;
overflow-y: auto;
@@ -883,6 +920,17 @@ h3 {
border-color: var(--danger);
color: #fff;
}
+.btn--danger:hover {
+ background: var(--danger);
+}
+.btn--danger:not(:disabled):hover {
+ background: color-mix(in srgb, var(--danger) 88%, #000);
+ border-color: color-mix(in srgb, var(--danger) 88%, #000);
+}
+.btn--danger:focus-visible {
+ outline: 2px solid var(--danger);
+ outline-offset: 2px;
+}
.btn--ghost {
border-color: transparent;
background: transparent;
@@ -4849,6 +4897,9 @@ table.csv th {
.search {
animation: pop var(--dur-base) var(--ease-out) backwards;
}
+.modal__card, .form-modal {
+ animation: cal-pop 0.18s var(--ease);
+}
.modal__card {
width: min(460px, calc(100vw - 32px));
max-height: calc(100vh - 80px);
@@ -4867,6 +4918,7 @@ table.csv th {
margin-bottom: 6px;
font-size: 15px;
}
+.modal__actions { display: flex; align-items: center; gap: 8px; }
.modal__lead {
margin: 0 0 12px;
}
diff --git a/src/shared/rpc.ts b/src/shared/rpc.ts
index 8c558ca..0d5d757 100644
--- a/src/shared/rpc.ts
+++ b/src/shared/rpc.ts
@@ -3,6 +3,8 @@ import type { WikiChange, WikiHit, WikiPage, WikiImport, WikiPageInfo, WikiRevie
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, VoiceModelId, VoiceStatus } from './types'
export interface Snapshot {
+ webhookPort?: number
+ defaultWorkspace?: boolean
settings: Settings
agents: Agent[]
conversations: Conversation[]
@@ -21,6 +23,7 @@ export interface Snapshot {
}
export interface Api {
+ markRead(p: { conversationId: string }): void
snapshot(): Snapshot
artifactText(p: { id: string }): string | null // a text file an agent showed (Markdown, CSV, code), for the side panel
sendMessage(p: { conversationId: string; text: string; images?: ImageUpload[]; threadId?: string }): void // threadId: a reply in the thread that message started
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 3f7fa97..996371a 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -241,7 +241,8 @@ export interface LocalInfo {
}
export interface Settings {
- workspaceName: string
+ workspaceName: string // the person's name: what the agents call them
+ workspaceLabel?: string // the workspace's own name, in the switcher; unset: workspaceName
context: string
engines: Record<EngineId, EngineStatus>
routerModel: string // a model id, or 'jev' for TypeSafe's Jev (falls back to Haiku)
@@ -270,7 +271,7 @@ export interface Settings {
// The harnesses agents may run on, picked in the introduction. Unset: every one that's ready.
harnesses?: EngineId[]
// The first-run introduction: unset on an existing install (no intro), done:false to show it (a new install, or "Rever a introdução")
- onboarding?: { done: boolean; checklistHidden?: boolean }
+ onboarding?: { done: boolean; checklistHidden?: boolean; workspaceManagerSeen?: boolean; carried?: boolean } // carried: the general settings came from another workspace
folded?: string[] // the ids of what I folded in the sidebar
sounds?: boolean // the toucan's chirp on a notification; unset: on
seenVersion?: string // the last version whose news I closed; an update past it shows what's new once
diff --git a/src/shared/workspaces.ts b/src/shared/workspaces.ts
new file mode 100644
index 0000000..fe94de0
--- /dev/null
+++ b/src/shared/workspaces.ts
@@ -0,0 +1,72 @@
+// The desktop registry exposes metadata and counts, never another workspace's content.
+import type { Settings } from './types'
+
+// What a workspace is called on screen: its own name, or else the person's (one workspace, as before).
+export const workspaceLabel = (s: Pick<Settings, 'workspaceName' | 'workspaceLabel'>): string => s.workspaceLabel?.trim() || s.workspaceName
+
+// The general settings: how things work, not what the workspace holds (never its context, wiki
+// folder, accounts, keys or phone).
+export const GENERAL_SETTINGS = ['workspaceName', 'language', 'routerModel', 'memoryModel', 'memoryLearning', 'defaultLimit', 'approvalTtlHours', 'runBudgetPct', 'runStallMinutes', 'quietHours', 'harnesses', 'sounds', 'voice', 'browserJev', 'wikiCapture', 'wikiEdits', 'wikiReview'] as const satisfies readonly (keyof Settings)[]
+// What a new workspace takes from another, each picked when creating it (a duplicate takes it all).
+// Never messages, memories, approvals, usage, computers' files, browser sessions or extra logins.
+export const WORKSPACE_PARTS = ['general', 'context', 'agents', 'channels', 'skills', 'connectors', 'routines'] as const
+export type WorkspacePart = (typeof WORKSPACE_PARTS)[number]
+export type WorkspaceParts = Record<WorkspacePart, boolean>
+export const ALL_PARTS: WorkspaceParts = { general: true, context: true, agents: true, channels: true, skills: true, connectors: true, routines: true }
+
+export function workspaceParts(raw: unknown): WorkspaceParts {
+ const from = raw && typeof raw === 'object' && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {}
+ const parts = Object.fromEntries(WORKSPACE_PARTS.map((p) => [p, from[p] === true])) as WorkspaceParts
+ return { ...parts, routines: parts.routines && parts.agents } // a routine is an agent's
+}
+
+export function isTheme(value: unknown): value is Settings['theme'] {
+ return value === 'system' || value === 'light' || value === 'dark'
+}
+
+export interface Workspace {
+ id: string
+ name: string
+ dataDir: string
+ webhookPort: number
+ gitPort: number
+ isDefault: boolean
+}
+
+export interface WorkspaceSummary {
+ id: string
+ name: string
+ isDefault: boolean
+ paused: boolean
+ unread: number
+ approvals: number
+ status: 'starting' | 'ready' | 'failed'
+}
+
+export interface WorkspaceList {
+ selected: string
+ workspaces: WorkspaceSummary[]
+}
+
+// UUIDv7: bytes 0-5 (48 bits) = Unix timestamp in milliseconds.
+export function workspaceCreatedAt(id: string): number {
+ return parseInt(id.replace(/-/g, '').slice(0, 12), 16)
+}
+
+export function sortWorkspaces(workspaces: WorkspaceSummary[] | undefined | null): WorkspaceSummary[] {
+ if (!workspaces) return []
+ return [...workspaces].sort((a, b) => {
+ const nameCmp = a.name.localeCompare(b.name)
+ if (nameCmp !== 0) return nameCmp
+ return workspaceCreatedAt(a.id) - workspaceCreatedAt(b.id)
+ })
+}
+
+export function suggestWorkspaceCopyName(name: string, existing: string[]): string {
+ const taken = new Set(existing)
+ for (let count = 2; ; count++) {
+ const suffix = ` (${count})`
+ const candidate = `${name.trim().slice(0, 120 - suffix.length).trimEnd()}${suffix}`
+ if (!taken.has(candidate)) return candidate
+ }
+}
diff --git a/test/governance.test.ts b/test/governance.test.ts
index 7567669..60a6851 100644
--- a/test/governance.test.ts
+++ b/test/governance.test.ts
@@ -14,7 +14,9 @@ import { Db } from '../src/core/db'
import { fakeEngine } from '../src/core/engines/fake'
import type { Engine, Turn } from '../src/core/engines/types'
import { Gateway } from '../src/core/gateway'
+import { LATE_GRACE_MS, MAX_AGENT_ROUTINES, Routines } from '../src/core/routines'
import { Runner } from '../src/core/runs'
+
import { plainCipher, Secrets } from '../src/core/secrets'
const DEMO = join(import.meta.dirname, '..', 'scripts', 'demo-mcp-server.mjs')
@@ -57,6 +59,7 @@ let events: CoreEvent[]
let settings: Settings
let connectorId: string
let seen: { turns: Turn[]; tools: string[][]; results: unknown[] }
+let runnerRef = { current: undefined as Runner | undefined }
const agent = (grant: GrantLevel): Agent => ({
id: 'a1', name: 'Lia', handle: 'lia', role: '', color: 'sky', instructions: '', modelId: 'sonnet', effort: 'low',
@@ -64,15 +67,18 @@ const agent = (grant: GrantLevel): Agent => ({
})
function runner(plan: (turn: Turn, tools: string[]) => Plan, onDb: Db = db): Runner {
- return new Runner({
+ const r = new Runner({
db: onDb,
engines: { claude: scripted(plan, seen), codex: fakeEngine('codex', { delayMs: 1 }), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') },
settings: async () => settings,
emit: (e) => events.push(e),
workDir: join(dir, 'work'),
gateway,
- connectors
+ connectors,
+ routines
})
+ runnerRef.current = r
+ return r
}
const tasks = (): { id: number; title: string; done: boolean }[] => {
@@ -84,6 +90,10 @@ const tasks = (): { id: number; title: string; done: boolean }[] => {
}
const agentMessages = (d: Db = db): Message[] => d.messages().filter((m) => m.author.kind === 'agent')
const textOf = (r: unknown): string => ((r as { content: { text: string }[] }).content[0]?.text ?? '')
+const at = (y: number, mo: number, d: number, h = 0, mi = 0): number => new Date(y, mo - 1, d, h, mi).getTime()
+let clock = at(2026, 10, 19, 8, 0)
+const posted = (conv = 'c1') => db.messages().filter((m) => m.conversationId === conv)
+let routines: Routines
beforeEach(async () => {
dir = mkdtempSync(join(tmpdir(), 'ad-gov-'))
@@ -97,6 +107,7 @@ beforeEach(async () => {
connectors = new ConnectorManager({ db, secrets: new Secrets(db, plainCipher), emit: (e) => events.push(e), openUrl: () => {}, oauthCallbackUrl: () => gateway.url('/oauth/callback') })
connectorId = await connectors.add({ kind: 'stdio', name: 'Tarefas', command: process.execPath, args: [DEMO], env: { DEMO_TASKS_FILE: tasksFile } })
await connectors.connect(connectorId)
+ routines = new Routines({ db, runner: { runRoutine: (r, when) => runnerRef.current!.runRoutine(r, when), retryRoutine: (r, when, id) => runnerRef.current!.retryRoutine(r, when, id) }, emit: () => {}, now: () => clock, wait: async () => {}, notify: () => {} })
db.saveAgent(agent('none'))
db.createConversation({ id: 'd1', kind: 'dm', name: 'a1', members: ['a1'] })
})
@@ -134,7 +145,7 @@ describe('grants', () => {
const r = runner((_, tools) => ({ tool: tools.find((t) => t.endsWith('__create_task')) ?? 'tarefas__create_task', args: { title: 'invasora' } }))
await r.send('d1', 'oi')
await r.idle()
- expect(seen.tools[0]).toEqual(['ask_user', 'pedir_acesso', 'tarefas__list_tasks']) // it can ask for more, not take it
+ expect(seen.tools[0]).toEqual(['ask_user', 'pedir_acesso', 'agendar_rotina', 'cancelar_rotina', 'tarefas__list_tasks']) // it can ask for more, not take it
expect(seen.results[0]).toMatchObject({ isError: true })
expect(textOf(seen.results[0])).toContain('não permitida')
expect(tasks().some((t) => t.title === 'invasora')).toBe(false)
@@ -295,6 +306,69 @@ describe('approvals', () => {
})
})
+describe('pause and resume', () => {
+ it('a message while paused gets the note and starts nothing', async () => {
+ const r = runner(() => null)
+ r.setPaused(true)
+ await r.send('d1', 'oi')
+ await r.idle()
+ expect(agentMessages()).toHaveLength(0)
+ expect(db.messages().at(-1)!.text).toContain('Os agentes estão pausados')
+ expect(seen.turns).toHaveLength(0)
+ r.setPaused(false)
+ await r.send('d1', 'oi de novo')
+ await r.idle()
+ expect(agentMessages()).toHaveLength(1)
+ expect(seen.turns).toHaveLength(1)
+ })
+
+ it('a failed reply keeps its retry note while paused and retries after resume', async () => {
+ db.saveAgent(agent('read_write'))
+ let shouldFail = true
+ const failing: Engine = {
+ id: 'claude',
+ async *run(turn) {
+ seen.turns.push(turn)
+ if (shouldFail) yield { type: 'error', message: 'provider down' }
+ else yield { type: 'done', text: 'feito', usage: { inputTokens: 1, cacheReadTokens: 0, outputTokens: 1 } }
+ }
+ }
+ const r = new Runner({ db, engines: { claude: failing, codex: failing, opencode: failing, pi: failing, gemini: failing, cursor: failing, grok: failing }, settings: async () => settings, emit: (e) => events.push(e), workDir: join(dir, 'work'), gateway, connectors, routines })
+ runnerRef.current = r
+ await r.send('d1', 'oi')
+ await r.idle()
+ expect(seen.turns).toHaveLength(1)
+ const failed = db.messages().filter((m) => m.author.kind === 'agent' && m.run?.status === 'failed').at(-1)
+ expect(failed).toBeDefined()
+ shouldFail = false
+ r.setPaused(true)
+ r.retry(failed!.id)
+ await r.idle()
+ expect(seen.turns).toHaveLength(1) // no retry while paused
+ r.setPaused(false)
+ r.retry(failed!.id)
+ await r.idle()
+ expect(seen.turns).toHaveLength(2) // retry ran after resume
+ })
+
+ it('a due routine does not run while paused', async () => {
+ const r = runner(() => null)
+ db.createConversation({ id: 'c1', kind: 'channel', name: 'geral', members: ['a1'] })
+ const routine = routines.save({ name: 'Bom dia', agentId: 'a1', conversationId: 'c1', prompt: 'hi', schedule: { days: [1, 2, 3, 4, 5], time: '09:00' }, enabled: true })
+ clock = at(2026, 10, 19, 9, 0) + 10_000
+ routines.tick()
+ expect(posted('c1').filter((m) => m.author.kind === 'routine')).toHaveLength(0)
+ r.setPaused(true)
+ routines.tick()
+ expect(posted('c1').filter((m) => m.author.kind === 'routine')).toHaveLength(0)
+ r.setPaused(false)
+ routines.tick()
+ await r.idle()
+ expect(posted('c1').filter((m) => m.author.kind === 'routine')).toHaveLength(1)
+ db.deleteConversation(routine.conversationId)
+ })
+})
+
describe('always allow and asking for access', () => {
const askDelete = (turn: Turn): Plan => (turn.prompt.includes('apaga') && !turn.prompt.includes('aprovou') ? { tool: 'tarefas__delete_task', args: { id: 2, _motivo: 'duplicada' } } : null)
diff --git a/test/kept-session.test.ts b/test/kept-session.test.ts
index d97efb6..bc45592 100644
--- a/test/kept-session.test.ts
+++ b/test/kept-session.test.ts
@@ -349,6 +349,12 @@ describe('Claude Code with a session', () => {
it('keeps its file under the config folder, by working folder', () => {
expect(claudeProjectDir('/cfg', 'E:\\tucano-tmp\\probe-agent')).toBe(join('/cfg', 'projects', 'E--tucano-tmp-probe-agent'))
})
+
+ it('names a long working folder as Claude Code does: cut at 200, then a hash of the whole path', () => {
+ // A real folder Claude Code made, for an agent of a second workspace under a long data folder.
+ const cwd = '/private/tmp/claude-501/-Users-eduardo-dev-agent-desk/a8f0d917-0489-4ee3-b90e-3ab79f9c8560/scratchpad/ws-leak-ySAaAW/workspaces/01a1ade8-40cc-79b7-bd30-8b0854d380d3/agents/9f3ef99c-7f51-4ea2-a06d-8cfbc28ee75c'
+ expect(claudeProjectDir('/cfg', cwd)).toBe(join('/cfg', 'projects', '-private-tmp-claude-501--Users-eduardo-dev-agent-desk-a8f0d917-0489-4ee3-b90e-3ab79f9c8560-scratchpad-ws-leak-ySAaAW-workspaces-01a1ade8-40cc-79b7-bd30-8b0854d380d3-agents-9f3ef99c-7f51-4ea2-a06d-8cfb-nrss68'))
+ })
})
// ---------- a process kept open between turns (a stand-in for Claude Code) ----------
@@ -418,7 +424,7 @@ describe('a Claude Code process kept open', () => {
writeFileSync(file, '{}\n')
mkdirSync(join(claudeProjectDir(cfg, dir), 's1', 'tool-results'), { recursive: true })
engine.release!('s1')
- for (let i = 0; i < 50 && existsSync(file); i++) await new Promise((r) => setTimeout(r, 100)) // once its process is gone
+ await engine.settle!() // once its process is gone
expect(existsSync(file)).toBe(false)
expect(existsSync(join(claudeProjectDir(cfg, dir), 's1'))).toBe(false)
engine.dispose!()
diff --git a/test/sidebar-layout.test.ts b/test/sidebar-layout.test.ts
index 1cfb092..1c706f8 100644
--- a/test/sidebar-layout.test.ts
+++ b/test/sidebar-layout.test.ts
@@ -2,6 +2,50 @@ import { existsSync, readFileSync } from 'node:fs'
import { chromium } from 'playwright'
import { expect, it } from 'vitest'
+it.skipIf(!existsSync(chromium.executablePath()))('shares the routine entrance animation with dialogs and respects reduced motion', async () => {
+ const browser = await chromium.launch({ headless: true })
+ try {
+ const page = await browser.newPage()
+ await page.emulateMedia({ reducedMotion: 'no-preference' })
+ await page.setContent(`<style>${readFileSync(new URL('../src/renderer/src/styles.css', import.meta.url), 'utf8')}</style><div class="modal__card">Dialog</div><div class="form-modal">Form</div>`)
+ const animations = () => page.locator('.modal__card, .form-modal').evaluateAll((els) => els.map((el) => {
+ const style = getComputedStyle(el)
+ return { name: style.animationName, seconds: parseFloat(style.animationDuration) }
+ }))
+ expect(await animations()).toEqual([{ name: 'cal-pop', seconds: 0.18 }, { name: 'cal-pop', seconds: 0.18 }])
+ await page.emulateMedia({ reducedMotion: 'reduce' })
+ for (const animation of await animations()) expect(animation.seconds).toBeLessThanOrEqual(0.001)
+ } finally { await browser.close() }
+})
+
+it.skipIf(!existsSync(chromium.executablePath()))('keeps danger buttons colored on hover and visible on keyboard focus', async () => {
+ const browser = await chromium.launch({ headless: true })
+ try {
+ const page = await browser.newPage()
+ await page.setContent(`<style>${readFileSync(new URL('../src/renderer/src/styles.css', import.meta.url), 'utf8')}</style><button>Before</button><button class="btn btn--danger">Delete workspace</button>`)
+ const button = page.getByRole('button', { name: 'Delete workspace' })
+ for (const theme of ['light', 'dark']) {
+ await page.evaluate((value) => { document.documentElement.dataset.theme = value }, theme)
+ await button.hover()
+ const colors = await button.evaluate((el) => {
+ const style = getComputedStyle(el)
+ const probe = document.createElement('span')
+ probe.style.background = 'var(--hover)'
+ document.body.append(probe)
+ const genericHover = getComputedStyle(probe).backgroundColor
+ probe.remove()
+ return { background: style.backgroundColor, genericHover, color: style.color }
+ })
+ expect(colors.background).not.toBe(colors.genericHover)
+ expect(colors.background).not.toBe('rgba(0, 0, 0, 0)')
+ expect(colors.color).toBe('rgb(255, 255, 255)')
+ await page.getByRole('button', { name: 'Before', exact: true }).focus()
+ await page.keyboard.press('Tab')
+ expect(await button.evaluate((el) => getComputedStyle(el).outlineStyle)).toBe('solid')
+ }
+ } finally { await browser.close() }
+})
+
// Layout needs a browser: DOM-only tests cannot detect a name squeezed out by flex.
it.skipIf(!existsSync(chromium.executablePath()))('keeps the agent name visible when the sidebar role is long', async () => {
const browser = await chromium.launch({ headless: true })
diff --git a/test/team.test.ts b/test/team.test.ts
index 13f88ae..4f48bb7 100644
--- a/test/team.test.ts
+++ b/test/team.test.ts
@@ -1,4 +1,4 @@
-import { existsSync, mkdtempSync } from 'node:fs'
+import { existsSync, mkdtempSync, readdirSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
@@ -51,6 +51,16 @@ describe('the team as a file', () => {
expect(existsSync(file)).toBe(true)
expect(new Db(file).agents()[0]!.handle).toBe('staff')
})
+
+ it("keeps a backup named after the workspace, beside a week of older ones", () => {
+ const dir = mkdtempSync(join(tmpdir(), 'bk-'))
+ for (let d = 1; d <= 7; d++) writeFileSync(join(dir, `tucano-2026-10-0${d}-09-00.db`), '')
+ const file = backup(fresh(), dir, 'Empresa São Paulo')
+ expect(file.endsWith('-Empresa-Sao-Paulo.db')).toBe(true)
+ expect(existsSync(file)).toBe(true)
+ expect(readdirSync(dir)).toHaveLength(7)
+ expect(existsSync(join(dir, 'tucano-2026-10-01-09-00.db'))).toBe(false) // the oldest went
+ })
})
describe('the report', () => {
diff --git a/test/threads.test.ts b/test/threads.test.ts
index 040d36f..95a303b 100644
--- a/test/threads.test.ts
+++ b/test/threads.test.ts
@@ -408,11 +408,11 @@ describe('what a thread message sets off stays in the thread', () => {
describe('the database', () => {
it('an existing database gains thread_id, thread_summary and threads, and round-trips them', () => {
const file = join(mkdtempSync(join(tmpdir(), 'ad-db-')), 'old.db')
- // A database from before threads: the schema three migrations back, with a message in it.
+ // A database from before threads: the schema four migrations back (the unread one came after), with a message in it.
new Db(file).close()
const raw = new DatabaseSync(file)
const { user_version } = raw.prepare('PRAGMA user_version').get() as { user_version: number }
- raw.exec(`ALTER TABLE conversations DROP COLUMN threads; ALTER TABLE messages DROP COLUMN thread_summary; DROP INDEX messages_by_thread; ALTER TABLE messages DROP COLUMN thread_id; PRAGMA user_version = ${user_version - 3};`)
+ raw.exec(`ALTER TABLE conversations DROP COLUMN threads; ALTER TABLE messages DROP COLUMN thread_summary; DROP INDEX messages_by_thread; ALTER TABLE messages DROP COLUMN thread_id; PRAGMA user_version = ${user_version - 4};`)
raw.exec("INSERT INTO conversations (id, kind, name, created_at) VALUES ('c1', 'channel', 'geral', 1)")
raw.exec("INSERT INTO messages (id, conversation_id, author_kind, text, at) VALUES ('old', 'c1', 'me', 'antes das threads', 1)")
raw.close()
diff --git a/test/workspace-data.test.ts b/test/workspace-data.test.ts
new file mode 100644
index 0000000..249d37a
--- /dev/null
+++ b/test/workspace-data.test.ts
@@ -0,0 +1,245 @@
+import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { DatabaseSync } from 'node:sqlite'
+import { afterEach, expect, it } from 'vitest'
+import { Db } from '../src/core/db'
+import { workspacePorts } from '../src/core/ports'
+import { Memories } from '../src/core/memory'
+import { fakeEngine } from '../src/core/engines/fake'
+import { initializeWorkspace } from '../src/core/seed'
+import type { Agent, Message, Settings } from '../src/shared/types'
+
+const defaults: Omit<Settings, 'engines'> = { workspaceName: 'Test', context: '', routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'en' }
+
+const dirs: string[] = []
+const dbs: Db[] = []
+const open = (file: string): Db => { const db = new Db(file); dbs.push(db); return db }
+afterEach(() => {
+ for (const db of dbs.splice(0)) db.close()
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
+})
+
+it('uses legacy ports by default and validates per-workspace ports', () => {
+ expect(workspacePorts({})).toEqual({ webhook: 47717, git: 47718 })
+ expect(workspacePorts({ TUCANO_WEBHOOK_PORT: '49001', TUCANO_GIT_PORT: '49002' })).toEqual({ webhook: 49001, git: 49002 })
+ for (const port of ['0', 'NaN', '65536', '47718', '4000.1']) expect(() => workspacePorts({ TUCANO_WEBHOOK_PORT: port })).toThrow()
+})
+
+it('starts newly created workspaces with onboarding, even when the original install uses demo seeds', () => {
+ const original = open(':memory:')
+ const env = { TUCANO_FAKE_ENGINES: '1', TUCANO_SEED: '1' }
+ initializeWorkspace(original, env)
+ expect(original.agents().length).toBeGreaterThan(0)
+ for (const seed of [undefined, '0', '1']) {
+ const workspace = open(':memory:')
+ initializeWorkspace(workspace, { ...env, TUCANO_DEFAULT_WORKSPACE: '0', TUCANO_SEED: seed })
+ expect(workspace.getSettings(defaults)).toMatchObject({ onboarding: { done: false } })
+ expect(workspace.agents()).toEqual([])
+ expect(workspace.conversations()).toEqual([])
+ expect(workspace.memories()).toEqual([])
+ expect(workspace.routines()).toEqual([])
+ }
+})
+
+it('preserves existing agents and onboarding state on restart, independently in each workspace', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'tucano-workspace-agents-'))
+ dirs.push(dir)
+ const agent: Agent = { id: 'same-agent', name: 'Aurora Company', handle: 'aurora', role: '', color: 'sky', instructions: 'Company only', modelId: 'sonnet', effort: 'low', limit: 1000, used: 0, grants: {}, memory: 'auto', computer: false, archived: false }
+ const work = new Db(join(dir, 'work.db'))
+ const personal = new Db(join(dir, 'personal.db'))
+ initializeWorkspace(work, { TUCANO_DEFAULT_WORKSPACE: '0' })
+ initializeWorkspace(personal, { TUCANO_DEFAULT_WORKSPACE: '0' })
+ work.saveAgent(agent)
+ personal.saveAgent({ ...agent, name: 'Boreal Personal', handle: 'boreal', instructions: 'Personal only' })
+ work.setSettings({ onboarding: { done: true } })
+ personal.setSettings({ onboarding: { done: true } })
+ work.close()
+ personal.close()
+ const reopenedWork = open(join(dir, 'work.db'))
+ const reopenedPersonal = open(join(dir, 'personal.db'))
+ for (const db of [reopenedWork, reopenedPersonal]) initializeWorkspace(db, { TUCANO_DEFAULT_WORKSPACE: '0', TUCANO_FAKE_ENGINES: '1', TUCANO_SEED: '1' })
+ expect(reopenedWork.agents().map((a) => a.name)).toEqual(['Aurora Company'])
+ expect(reopenedPersonal.agents().map((a) => a.name)).toEqual(['Boreal Personal'])
+ expect(reopenedWork.agent(agent.id)?.instructions).toBe('Company only')
+ expect(reopenedPersonal.agent(agent.id)?.instructions).toBe('Personal only')
+ expect(reopenedWork.getSettings(defaults)).toMatchObject({ onboarding: { done: true } })
+ expect(reopenedPersonal.getSettings(defaults)).toMatchObject({ onboarding: { done: true } })
+})
+
+it('keeps unread counts and memory data in the owning database with identical IDs', () => {
+ const a = open(':memory:')
+ const b = open(':memory:')
+ for (const db of [a, b]) db.createConversation({ id: 'same-channel', kind: 'channel', name: 'project', members: [] })
+ const message: Message = { id: 'same-message', conversationId: 'same-channel', author: { kind: 'agent', id: 'agent' }, text: '', at: 1, run: { status: 'working', steps: [] } }
+ for (const db of [a, b]) db.saveMessage(message)
+ a.recordActivity(message, null)
+ a.recordActivity(message, null)
+ expect(a.conversation('same-channel')?.unread).toBe(1)
+ expect(b.conversation('same-channel')?.unread).toBe(0)
+ a.markRead('same-channel')
+ const completed: Message = { ...message, text: 'Company result', run: { status: 'done', steps: [] } }
+ a.saveMessage(completed)
+ a.recordActivity(completed, null)
+ a.recordActivity(completed, null)
+ expect(a.conversation('same-channel')?.unread).toBe(1)
+ b.recordActivity(completed, 'same-channel')
+ expect(b.conversation('same-channel')?.unread).toBe(0)
+ a.saveMemory({ id: 'memory', scope: 'me', text: 'Only in A', state: 'active', origin: 'me', messageIds: [], createdAt: 1, confirmedAt: 1 })
+ expect(a.memories().map((m) => m.text)).toEqual(['Only in A'])
+ expect(b.memories()).toEqual([])
+ const agent: Agent = { id: 'same-agent', name: 'Agent', handle: 'agent', role: '', color: 'sky', instructions: '', modelId: 'sonnet', effort: 'low', limit: 1000, used: 0, grants: {}, memory: 'auto', computer: false, archived: false }
+ const memory = (db: Db): Memories => new Memories({ db, engines: { claude: fakeEngine('claude'), codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }, settings: async () => { throw new Error('Prompt lookup must not invoke a model') }, emit: () => {}, workDir: '' })
+ expect(memory(a).forPrompt(agent).aboutMe.map((m) => m.text)).toEqual(['Only in A'])
+ expect(memory(b).forPrompt(agent).aboutMe).toEqual([])
+ a.deleteConversation('same-channel')
+ expect(a.conversations()).toEqual([])
+})
+
+it('migrates every opened workspace and backs up older schemas before changing them', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'tucano-migrations-'))
+ dirs.push(dir)
+ const file = join(dir, 'tucano.db')
+ const first = new Db(file)
+ first.createConversation({ id: 'kept', name: 'kept', kind: 'channel', members: [] })
+ first.close()
+ const raw = new DatabaseSync(file)
+ const version = (raw.prepare('PRAGMA user_version').get() as { user_version: number }).user_version
+ raw.exec(`DROP TABLE message_notifications; PRAGMA user_version = ${version - 1}`)
+ raw.close()
+ const migrated = open(file)
+ expect(migrated.conversation('kept')?.unread).toBe(0)
+ const backups = readdirSync(join(dir, 'backups'))
+ expect(backups).toHaveLength(1)
+ const before = new DatabaseSync(join(dir, 'backups', backups[0]!))
+ expect(before.prepare('PRAGMA user_version').get()).toMatchObject({ user_version: version - 1 })
+ before.close()
+ const again = open(file)
+ expect(again.conversation('kept')?.name).toBe('kept')
+ expect(readdirSync(join(dir, 'backups'))).toEqual(backups)
+})
+
+it('duplicates configuration and credentials without copying history or mutating the source', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'tucano-duplicate-'))
+ dirs.push(dir)
+ const sourceFile = join(dir, 'source.db')
+ const source = open(sourceFile)
+ source.setSettings({ ...defaults, workspaceName: 'Company', context: 'Workspace instructions', routerModel: 'sonnet', onboarding: { done: true, checklistHidden: true, workspaceManagerSeen: true } })
+ source.saveAgent({ id: 'agent', name: 'Aurora', handle: 'aurora', role: 'Research', color: 'sky', instructions: 'Agent instructions', modelId: 'sonnet', effort: 'low', limit: 1000, used: 0, grants: { connector: 'read_write' }, memory: 'auto', computer: false, archived: false, accountId: 'work', fallbackAccountId: 'work' })
+ source.setSettings({ accounts: [{ id: 'work', engine: 'claude', name: 'Work' }] })
+ source.createConversation({ id: 'channel', kind: 'channel', name: 'company', members: ['agent'], topic: 'Channel configuration' })
+ source.saveConnector({ id: 'connector', name: 'Company tool', kind: 'remote', url: 'https://example.com/mcp', auth: 'token' })
+ source.setSecret('connector:token', 'encrypted-connector-credential')
+ source.setSecret('telegram:token', 'default-only-token')
+ source.setSecret('github:proxy-key', 'old-proxy-key')
+ source.setSecret('connector:oauth_verifier', 'pending-oauth')
+ const message: Message = { id: 'message', conversationId: 'channel', author: { kind: 'agent', id: 'agent' }, text: 'PRIVATE_MESSAGE_NOT_FOR_COPY', at: 1 }
+ source.saveMessage(message)
+ source.recordActivity(message, null)
+ source.setSummary('channel', 'PRIVATE_SUMMARY_NOT_FOR_COPY', 1)
+ source.saveMemory({ id: 'memory', scope: 'me', text: 'PRIVATE_MEMORY_NOT_FOR_COPY', state: 'active', origin: 'me', messageIds: ['message'], createdAt: 1, confirmedAt: 1 })
+ source.addReceipt({ messageId: 'message', agentId: 'agent', engine: 'claude', model: 'sonnet', inputTokens: 100, outputTokens: 10, cacheReadTokens: 0, ms: 1, at: 1 })
+ source.saveService('agent', { name: 'web', command: 'npm start', port: 3000, startedAt: 1 })
+ source.saveSkill({ id: 'skill', name: 'Review', description: 'Review code', body: 'Check tests', agents: ['agent'], state: 'active', createdAt: 1, updatedAt: 1 })
+ source.saveRoutine({ id: 'routine', name: 'Daily', agentId: 'agent', conversationId: 'channel', prompt: 'Daily task', schedule: { days: [0, 1, 2, 3, 4, 5, 6], time: '09:00' }, enabled: true, nextAt: 1, lastAt: 1, lastMessageId: 'message', createdAt: 1 })
+ source.saveRoutine({ ...source.routine('routine')!, id: 'hook', trigger: { kind: 'webhook', token: 'old-webhook-token' } })
+ const raw = new DatabaseSync(sourceFile)
+ raw.exec(`INSERT INTO approvals (id, hash, agent_id, conversation_id, message_id, connector_id, connector_name, tool, args, created_at, expires_at) VALUES ('approval', 'hash', 'agent', 'channel', 'message', 'connector', 'Tool', 'send', '{}', 1, 2)`)
+ raw.close()
+ const file = join(dir, 'copy.db')
+ source.duplicateTo(file, 'Company (copy)')
+ const copy = open(file)
+ expect(copy.getSettings(defaults)).toMatchObject({ workspaceName: 'Company', workspaceLabel: 'Company (copy)', context: 'Workspace instructions', routerModel: 'sonnet', onboarding: { done: true } })
+ expect(copy.getSettings(defaults).onboarding?.workspaceManagerSeen).toBeUndefined()
+ expect(copy.getSettings(defaults).onboarding?.checklistHidden).toBe(true)
+ expect(copy.agents().map((a) => a.name)).toEqual(['Aurora'])
+ expect(copy.agent('agent')?.grants).toEqual({ connector: 'read_write' })
+ // The extra login's folder is the source's: the copy's agent uses the usual one.
+ expect(copy.getSettings(defaults).accounts).toBeUndefined()
+ expect(copy.agent('agent')?.accountId).toBeUndefined()
+ expect(copy.agent('agent')?.fallbackAccountId).toBeUndefined()
+ expect(source.agent('agent')?.accountId).toBe('work')
+ expect(copy.conversation('channel')).toMatchObject({ members: ['agent'], topic: 'Channel configuration', summary: undefined, unread: 0 })
+ expect(copy.connectors().map((c) => c.name)).toEqual(['Company tool'])
+ expect(copy.getSecret('connector:token')).toBe('encrypted-connector-credential')
+ for (const key of ['telegram:token', 'github:proxy-key', 'connector:oauth_verifier']) expect(copy.getSecret(key)).toBeUndefined()
+ expect(copy.skills().map((s) => s.name)).toEqual(['Review'])
+ expect(copy.routine('routine')).toMatchObject({ enabled: true, lastAt: undefined, lastMessageId: undefined })
+ expect(copy.routine('routine')!.nextAt).toBeGreaterThan(Date.now() - 1000)
+ expect(copy.routine('hook')?.trigger).not.toEqual(source.routine('hook')?.trigger)
+ expect(copy.messages()).toEqual([])
+ expect(copy.memories()).toEqual([])
+ expect(copy.approvals()).toEqual([])
+ expect(copy.artifacts()).toEqual([])
+ expect(copy.receiptsSince(0)).toEqual([])
+ expect(copy.services('agent')).toEqual([])
+ const bytes = readFileSync(file).toString('utf8')
+ for (const marker of ['PRIVATE_MESSAGE_NOT_FOR_COPY', 'PRIVATE_MEMORY_NOT_FOR_COPY', 'PRIVATE_SUMMARY_NOT_FOR_COPY']) expect(bytes).not.toContain(marker)
+ expect(existsSync(`${file}.preparing`)).toBe(false)
+ expect(source.messages()).toHaveLength(1)
+ expect(source.memories()).toHaveLength(1)
+ expect(source.routine('routine')?.lastMessageId).toBe('message')
+ expect(() => source.duplicateTo(file, 'overwrite')).toThrow('already exists')
+ source.setSettings({ onboarding: { done: false } })
+ const unfinished = join(dir, 'unfinished.db')
+ source.duplicateTo(unfinished, 'Unfinished')
+ expect(open(unfinished).getSettings(defaults).onboarding?.done).toBe(false)
+})
+
+it('brings only what was picked to a new workspace, and what depends on it comes without what stayed', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'tucano-parts-'))
+ dirs.push(dir)
+ const source = open(join(dir, 'source.db'))
+ source.setSettings({ ...defaults, workspaceName: 'Edu', context: 'SECRET CONTEXT', routerModel: 'sonnet', defaultLimit: 4242, wikiDir: '/vault', channelLayout: { order: [] } as unknown as Settings['channelLayout'], onboarding: { done: true } })
+ source.saveAgent({ id: 'lia', name: 'Lia', handle: 'lia', role: '', color: 'sky', instructions: 'Lia instructions', modelId: 'sonnet', effort: 'low', limit: 1000, used: 0, grants: { linear: 'read_write' }, autoApprove: ['linear:create'], memory: 'auto', computer: false, archived: false })
+ source.createConversation({ id: 'dm', kind: 'dm', name: 'lia', members: ['lia'] })
+ source.createConversation({ id: 'eng', kind: 'channel', name: 'eng', members: ['lia'] })
+ source.saveConnector({ id: 'linear', name: 'Linear', kind: 'remote', url: 'https://example.com/mcp', auth: 'token' })
+ source.setSecret('connector:linear:token', 'encrypted')
+ source.setSecret('github:token', 'encrypted-github')
+ source.setSecret('typesafe:key', 'encrypted-jev')
+ source.saveSkill({ id: 'all', name: 'For all', description: 'x', body: 'y', agents: [], state: 'active', createdAt: 1, updatedAt: 1 })
+ source.saveSkill({ id: 'own', name: 'For Lia', description: 'x', body: 'y', agents: ['lia'], state: 'active', createdAt: 1, updatedAt: 1 })
+ source.saveRoutine({ id: 'daily', name: 'Daily', agentId: 'lia', conversationId: 'eng', prompt: 'p', schedule: { days: [1], time: '09:00' }, enabled: true, createdAt: 1 })
+ source.saveRoutine({ id: 'poll', name: 'Poll', agentId: 'lia', conversationId: 'dm', prompt: 'p', schedule: { days: [], time: '09:00' }, enabled: true, createdAt: 1, trigger: { kind: 'poll', connectorId: 'linear', tool: 'list', args: {}, everyMinutes: 5 } })
+ const none = { general: false, context: false, agents: false, channels: false, skills: false, connectors: false, routines: false }
+
+ // The general settings only: an empty workspace whose introduction starts from them.
+ source.duplicateTo(join(dir, 'general.db'), 'General', { ...none, general: true })
+ const general = open(join(dir, 'general.db'))
+ const g = general.getSettings(defaults)
+ expect(g).toMatchObject({ workspaceName: 'Edu', workspaceLabel: 'General', routerModel: 'sonnet', defaultLimit: 4242, context: '', onboarding: { done: false, carried: true } })
+ expect(g.wikiDir).toBeUndefined()
+ expect(g.channelLayout).toBeUndefined()
+ expect([general.agents(), general.conversations(), general.connectors(), general.skills(), general.routines()].map((x) => x.length)).toEqual([0, 0, 0, 0, 0])
+ expect(general.getSecret('typesafe:key')).toBe('encrypted-jev')
+ expect(general.getSecret('github:token')).toBeUndefined()
+
+ // Agents and their routines, no connectors: no grants, and the routine that polls one stays behind.
+ source.duplicateTo(join(dir, 'agents.db'), 'Agents', { ...none, agents: true, channels: true, skills: true, routines: true })
+ const agents = open(join(dir, 'agents.db'))
+ expect(agents.agent('lia')).toMatchObject({ instructions: 'Lia instructions', grants: {}, autoApprove: [] })
+ expect(agents.conversations().map((c) => c.id).sort()).toEqual(['dm', 'eng'])
+ expect(agents.routines().map((r) => r.id)).toEqual(['daily'])
+ expect(agents.connectors()).toEqual([])
+ for (const key of ['connector:linear:token', 'github:token', 'typesafe:key']) expect(agents.getSecret(key)).toBeUndefined()
+ expect(agents.getSettings(defaults)).toMatchObject({ routerModel: 'haiku', context: '', onboarding: { done: true } }) // defaults: the general settings stayed
+
+ // Skills and connectors without agents: a skill of agents left behind comes archived.
+ source.duplicateTo(join(dir, 'skills.db'), 'Skills', { ...none, skills: true, connectors: true })
+ const skills = open(join(dir, 'skills.db'))
+ expect(skills.skills().map((k) => [k.id, k.state]).sort()).toEqual([['all', 'active'], ['own', 'archived']])
+ expect(skills.connectors().map((c) => c.id)).toEqual(['linear'])
+ expect(skills.getSecret('connector:linear:token')).toBe('encrypted')
+ expect(skills.agents()).toEqual([])
+ expect(skills.routines()).toEqual([])
+ expect(skills.getSettings(defaults).onboarding).toEqual({ done: false })
+
+ // Everything: the duplicate, as before (context and the wiki folder too).
+ source.duplicateTo(join(dir, 'all.db'), 'All')
+ const all = open(join(dir, 'all.db'))
+ expect(all.getSettings(defaults)).toMatchObject({ context: 'SECRET CONTEXT', wikiDir: '/vault', onboarding: { done: true } })
+ expect(all.routines().map((r) => r.id).sort()).toEqual(['daily', 'poll'])
+ expect(source.agents()).toHaveLength(1) // the source is untouched
+ expect(source.getSecret('github:token')).toBe('encrypted-github')
+})
diff --git a/test/workspaces.test.ts b/test/workspaces.test.ts
new file mode 100644
index 0000000..a07a8a0
--- /dev/null
+++ b/test/workspaces.test.ts
@@ -0,0 +1,167 @@
+import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync, symlinkSync, mkdirSync } from 'node:fs'
+import { join } from 'node:path'
+import { tmpdir } from 'node:os'
+import { afterEach, expect, it } from 'vitest'
+import { Workspaces, workspaceId } from '../src/main/workspaces'
+import { suggestWorkspaceCopyName, workspaceCreatedAt, workspaceLabel, workspaceParts } from '../src/shared/workspaces'
+
+const dirs: string[] = []
+const root = (): string => { const dir = mkdtempSync(join(tmpdir(), 'tucano-workspaces-')); dirs.push(dir); return dir }
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })
+
+it('suggests the current name with the next available duplicate count', () => {
+ expect(suggestWorkspaceCopyName('Company', ['Company'])).toBe('Company (2)')
+ expect(suggestWorkspaceCopyName('Company', ['Company', 'Company (2)', 'Company (3)'])).toBe('Company (4)')
+ expect(suggestWorkspaceCopyName('Company', ['Company', 'Company (3)'])).toBe('Company (2)')
+ expect(suggestWorkspaceCopyName('A'.repeat(120), [])).toHaveLength(120)
+})
+
+it('reads what comes along to a new workspace, routines only with their agents', () => {
+ expect(workspaceParts({ general: true, agents: true, routines: true, extra: true })).toEqual({ general: true, context: false, agents: true, channels: false, skills: false, connectors: false, routines: true })
+ expect(workspaceParts({ routines: true }).routines).toBe(false)
+ expect(workspaceParts({ general: 'yes' }).general).toBe(false)
+ expect(Object.values(workspaceParts(null)).some(Boolean)).toBe(false)
+})
+
+it("names a workspace by its own name, or else the person's", () => {
+ expect(workspaceLabel({ workspaceName: 'Edu', workspaceLabel: 'Empresa' })).toBe('Empresa')
+ expect(workspaceLabel({ workspaceName: 'Edu', workspaceLabel: ' ' })).toBe('Edu')
+ expect(workspaceLabel({ workspaceName: 'Edu' })).toBe('Edu')
+})
+
+it('uses unique UUIDv7 identities', () => {
+ const ids = Array.from({ length: 1000 }, workspaceId)
+ expect(new Set(ids).size).toBe(ids.length)
+ for (const id of ids) expect(id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/)
+ const before = Date.now()
+ expect(workspaceCreatedAt(workspaceId())).toBeGreaterThanOrEqual(before) // the time in it, to the millisecond
+ expect(workspaceCreatedAt(workspaceId())).toBeLessThanOrEqual(Date.now())
+})
+
+it('persists one app theme across workspace selection, creation and removal', () => {
+ const dir = root()
+ const registry = new Workspaces(dir)
+ // Older registries can adopt the default workspace's theme on first start.
+ expect(registry.theme()).toBeUndefined()
+ registry.setTheme('dark')
+ const workspace = registry.create()
+ registry.select(workspace.id)
+ expect(new Workspaces(dir).theme()).toBe('dark')
+ registry.setTheme('light')
+ registry.deleteData(workspace.id)
+ expect(new Workspaces(dir).theme()).toBe('light')
+ registry.setTheme('system')
+ expect(new Workspaces(dir).theme()).toBe('system')
+})
+
+it('adopts the existing folder without moving its data and persists selection', () => {
+ const dir = root()
+ writeFileSync(join(dir, 'tucano.db'), 'existing data')
+ const registry = new Workspaces(dir)
+ const original = registry.selected()
+ const a = registry.create()
+ const b = registry.create()
+ registry.select(a.id)
+ registry.rename(a.id, 'Company')
+ const loaded = new Workspaces(dir)
+ expect(loaded.selected()).toEqual({ ...a, name: 'Company' })
+ expect(loaded.get(original.id).dataDir).toBe(realpathSync(dir))
+ expect(readFileSync(join(dir, 'tucano.db'), 'utf8')).toBe('existing data')
+ expect(a.dataDir).toBe(join(realpathSync(dir), 'workspaces', a.id))
+ expect(new Set(loaded.list().flatMap((w) => [w.gitPort, w.webhookPort])).size).toBe(6)
+ expect(b.isDefault).toBe(false)
+ expect(() => registry.select('../outside')).toThrow('Workspace not found')
+})
+
+it.skipIf(process.platform === 'win32')('adopts a symlinked root using canonical paths without moving its data', () => {
+ const dir = root()
+ const alias = join(root(), 'alias')
+ symlinkSync(dir, alias)
+ writeFileSync(join(alias, 'tucano.db'), 'existing data')
+ const registry = new Workspaces(alias)
+ const original = registry.selected()
+ const workspace = registry.create()
+ registry.select(workspace.id)
+ const loaded = new Workspaces(alias)
+ expect(loaded.get(original.id).dataDir).toBe(realpathSync(dir))
+ expect(loaded.selected()).toEqual(workspace)
+ expect(workspace.dataDir).toBe(join(realpathSync(dir), 'workspaces', workspace.id))
+ expect(new Workspaces(dir).list()).toEqual(loaded.list())
+ expect(readFileSync(join(alias, 'tucano.db'), 'utf8')).toBe('existing data')
+})
+
+it('refuses invalid registries without overwriting them', () => {
+ const dir = root()
+ new Workspaces(dir)
+ const file = join(dir, 'workspaces.json')
+ const good = JSON.parse(readFileSync(file, 'utf8'))
+ for (const mutate of [
+ (s: typeof good) => { s.version = 2 },
+ (s: typeof good) => { s.theme = 'invalid' },
+ (s: typeof good) => { s.workspaces[0].dataDir = '/' },
+ (s: typeof good) => { s.workspaces[0].gitPort = s.workspaces[0].webhookPort },
+ (s: typeof good) => { s.selected = workspaceId() }
+ ]) {
+ const bad = structuredClone(good)
+ mutate(bad)
+ const text = JSON.stringify(bad)
+ writeFileSync(file, text)
+ expect(() => new Workspaces(dir)).toThrow()
+ expect(readFileSync(file, 'utf8')).toBe(text)
+ }
+})
+
+it.skipIf(process.platform === 'win32')('rejects a managed workspace aliased to another folder', () => {
+ const dir = root()
+ const registry = new Workspaces(dir)
+ const a = registry.create()
+ mkdirSync(join(dir, 'workspaces'))
+ symlinkSync(root(), a.dataDir)
+ expect(() => new Workspaces(dir)).toThrow('Invalid workspaces.json')
+})
+
+it('deletes only non-default data and protects the default and sibling workspaces', () => {
+ const dir = root()
+ const registry = new Workspaces(dir)
+ const original = registry.selected()
+ const a = registry.create()
+ const b = registry.create()
+ for (const w of [original, a, b]) {
+ mkdirSync(w.dataDir, { recursive: true })
+ writeFileSync(join(w.dataDir, 'tucano.db'), w.id)
+ }
+ const external = root()
+ writeFileSync(join(external, 'project.txt'), 'keep me')
+ writeFileSync(join(dir, 'application-metadata'), 'keep this too')
+ registry.select(a.id)
+ registry.deleteData(a.id)
+ expect(existsSync(a.dataDir)).toBe(false)
+ expect(() => registry.get(a.id)).toThrow()
+ const before = readFileSync(join(dir, 'workspaces.json'), 'utf8')
+ expect(() => registry.deleteData(original.id)).toThrow('default workspace cannot be deleted')
+ expect(readFileSync(join(dir, 'workspaces.json'), 'utf8')).toBe(before)
+ expect(readFileSync(join(b.dataDir, 'tucano.db'), 'utf8')).toBe(b.id)
+ expect(readFileSync(join(dir, 'tucano.db'), 'utf8')).toBe(original.id)
+ expect(readFileSync(join(dir, 'application-metadata'), 'utf8')).toBe('keep this too')
+ expect(readFileSync(join(external, 'project.txt'), 'utf8')).toBe('keep me')
+ const loaded = new Workspaces(dir)
+ expect(loaded.list()).toHaveLength(2)
+ expect(loaded.list().find((w) => w.isDefault)?.id).toBe(original.id)
+ expect(loaded.get(b.id)).toEqual(b)
+})
+
+it('refuses to delete the only workspace and keeps its identity and selection', () => {
+ const registry = new Workspaces(root())
+ const old = registry.selected()
+ expect(() => registry.deleteData(old.id)).toThrow('default workspace cannot be deleted')
+ expect(registry.list()).toHaveLength(1)
+ expect(registry.selected().id).toBe(old.id)
+ expect(registry.selected().dataDir).toBe(old.dataDir)
+})
+
+it.skipIf(process.platform === 'win32')('rejects a symlinked workspace parent before creating folders outside the root', () => {
+ const dir = root()
+ const registry = new Workspaces(dir)
+ symlinkSync(root(), join(dir, 'workspaces'))
+ expect(() => registry.create()).toThrow('Invalid workspaces.json')
+})