Your team of AI agents, on your Mac, Windows or Linux. Agents that talk in channels, write code, review each other and use your tools, on the Claude Code, Codex, OpenCode or Pi you already have. Anything that touches the real world waits for your yes.
TypeScript agent-teamagentic-aiai-agentsai-assistantclaude-codecodexcursorelectrongrokgrok-bot-alternativelinuxlocal-firstmacosmcpmulti-agentopenclaw-alternativeopencodewindows
Guide new people from hello to a working agent, and connect the AI without a terminal (#189)
Eduardo Machadoe06f2c0c44c3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d6ef3fb..1c5e107 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,10 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht### Added+- **A first run anyone can follow, and that takes three clicks when everything's ready.** The introduction was nine steps (where agents run, the models, you, tools, skills, the agent, its powers, the first task) and told people to sign in "in the terminal that opened". Now it's one guided path in the look of the phone app: your name; the AI; the Tuca asking **"Qual é a primeira coisa que você queria tirar das suas costas?"**; the agent. If Claude Code, Codex or another one is already signed in, it shows up tested with a real reply (and how long it took), with switches to bring the tools and skills it found along (**ver quais** names them), and the two small models behind the scenes picked on their own (**Trocar** shows them as two cards, who replies and the memory, each opening one menu with every ready harness's models). If nothing is, **ChatGPT** or **Claude** sets it up with no terminal (below), and **Não assino nenhuma** explains which plan to get, with the official links; **Uso chave de API, gateway da empresa ou outro programa** opens the harnesses as before. The Tuca offers six goals (organize my week, research and summarize, write emails and posts, reply to customers, handle spreadsheets, code) or takes your own words, dictation included, and the agent is born from a built-in template at once, no wait on a model: its face, a name you can change, a color, what it does in plain words, and **"Quanto {nome} faz por conta própria?"**: **Me pergunta antes de mudar qualquer coisa** (Careful), **Faz o dia a dia por conta própria e pergunta antes do que importa** (Normal, recommended and picked) or **Faz tudo por conta própria, até enviar e pagar** (No guardrails, after the same confirmation as Settings), with a line under it saying what still asks. The answer is the agent's own autonomy level (Normal stays on Default, following Settings); the rules by kind and the outside-content guard stay on the agent's page. The detailed form asks the same, and **Ajustar com o Tuca** keeps the answer. It starts safe: no computer, connectors read-only, the web only where the goal needs it; a connector that fits the goal and signs in with one click in the browser is offered as optional (Todoist for the week, Notion for writing, Linear for code; none for the others, and nothing that needs an app, a token or an address of your own). **Ajustar com o Tuca** talks it over with him and brings his card back; **Prefiro configurar do zero** opens the detailed form. **Chamar … pro time** lands in #geral with the first message written and not sent, and a balloon over the field says to press send.+- **Codex and Claude Code set up from the app, with no terminal.** Picking ChatGPT or Claude in the introduction downloads the official CLI from where its own installer gets it (Codex's release package on GitHub, Claude Code's from downloads.claude.ai), checks it against the published sha256 and keeps it in the app's data folder (on the PATH after any the person installed), then starts the CLI's own sign-in (`codex login`, `claude auth login`), which opens the browser and finishes on its own callback on this computer. Tucano never sees the password or the tokens, and never relays a code; the binary isn't changed. The screen shows the steps (setting up, signing in, a real test reply), with **Abrir de novo** for the sign-in page and, if something fails, **Tentar de novo** or **Fazer pelo terminal**. macOS, Windows (x64 and arm64) and Linux (x64 and arm64, glibc or musl); on a server the sign-in stays in its terminal.+- **The tour, done instead of read.** Balloons over the real screens, once each: the first message; the first time an agent really asks you something (an approval, its questions, a proposal; nothing is staged, so it waits for one), **"Quando {nome} precisar de você, pede aqui"**, with what asks at the agent's level and never a promise that everything does; then the Tuca, for help; then the missions. The screen stays usable under them, Esc or **Entendi** closes one and **Pular tour** ends them.+- **A short welcome for someone invited to a team**, in the browser or the app: who invited them, the team's agents, their name and an optional "what you do", and the deal (direct messages with an agent are theirs alone, not even the owner's; channels are seen by everyone; agents ask whoever decides before what the team agreed on). Then the short tour. Only people who join from now on see it.- **An agent's profile card, from its face or name.** A click on an agent's face or name (on its message, in a thread, an `@mention`, the faces at the top of a channel, the top of its DM) opens a small card next to it, as Slack does; resting the mouse there for half a second opens it too, and it goes when the mouse leaves. The card shows its picture, name, `@handle` and role; what it's doing now (working, and on which step, with a link to the conversation; waiting for an answer or an approval, and whose, when there's a team; at its monthly limit; archived; or when it last spoke); its model and harness; its computer; the channels it's in; and buttons to message it or open its full page. The faces at the top of a channel and the name at the top of a DM open the card instead of the agent's page, and the DM's **See profile** button is now a gear for the conversation's settings. People's faces stay as they were. Esc gives the focus back to what opened it. Thanks [@rjgdias](https://github.com/rjgdias)! ([#134](https://github.com/eduwxyz/tucano/pull/134))- **An agent's decisions, answered one at a time with options to pick.** `ask_user` took a single string, so agents packed their findings, a proposal and several questions into one unformatted card. Now an agent asks for 1 to 4 decisions, each a single choice, a multiple choice or a short text, and writes its analysis in the reply, which renders as usual; a question over 200 characters goes back to the agent asking for the context in the reply. The decisions come as a card under the agent's reply, one at a time (with arrows and "1 of 2"): the agent suggests 1 to 3 options and the card always adds "Something else", which opens a field for your own answer. Pick with a click or the option's number, Enter confirms, "Skip" moves on, and with more than one decision there's a review before sending, where any answer can still change. The answer goes as your message, one line per decision. The message box below stays as it was: writing there answers too, and what you already picked on the card goes along. Once answered, the card keeps each decision with what was chosen, and the sidebar marks a channel or DM where an agent waits on you, with who in its tooltip. With a team, a question to someone carries its decisions too: the asked person (or whoever covers for them) answers them on the card, in the conversation or in **For you**; an admin can answer for them; everyone else sees what was asked and, afterwards, who answered. A question from a DM still waits for the DM's person's yes first, and the sidebar marks only what waits on you. Older pending questions still work, and Telegram gets the decisions as numbered text, answered by replying. Thanks [@cleitoncsalvagni](https://github.com/cleitoncsalvagni)! ([#145](https://github.com/eduwxyz/tucano/pull/145))- **How far each agent goes on its own.** **Settings › Agents › Autonomy** sets a level for every agent, and each agent's page (Tools) can set its own: **Careful** asks before anything that changes something (a write in a connector, a commit, a push, a risky click); **Normal** is how Tucano always worked, reading and writing on its own and asking before what's sensitive; **No guardrails** sends, deletes, publishes, pays and clicks without asking, after a confirmation. Under **Fine-tune action by action**, each kind (commit, push, pull request, merge, delete, send, publish, pay, a risky click in the agent's browser, a risky action in an app) can ask first, run alone or never happen, over the level; an agent's own rule wins over its level, which wins over Settings. A tool you marked high risk always asks, and a step that ran without asking says so ("Ran (no ask: autonomy)"). Commands on the agent's computer are read before they run, every command on the line (from #110, by @rjgdias): a commit, a push or an `rm -r` that a rule holds becomes an approval with the exact command, and approved, exactly that runs.@@ -14,9 +18,14 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht### Fixed+- **A harness that fails says why in one line, not a stack trace.** When Claude Code, Codex, Pi or another one fails its test (in the introduction or in **Settings › Modelos › Testar**), the row says what happened and what to do: an expired or invalid login names the harness and, for Pi and OpenCode, the provider ("O login da Anthropic no Pi expirou. Entre de novo no Pi pra usar."), with **Entrar de novo** and **Tentar de novo**; a limit or a timeout gets its own line; anything else a short line, with the raw text under **Ver detalhes** in a small scrolling box. In the introduction a harness that failed is muted and doesn't hold up the others: the button reads **Continuar com Claude Code**. The harnesses show their own marks instead of a letter (Grok keeps its initial).- **A server's one-time link signs in the browser that opens it, not whatever opened it first.** Opening the link from **Settings › People › Connect a phone** (or `server.js pair`) spent the code at once. A chat's link preview (Discord, WhatsApp, iMessage, Slack), a browser's prefetch or prerender of a pasted address, or a mail scanner got there first: each became a device no one holds, the person's own visit read "this link was already used or has expired", and "You're signed in on N devices" went up by one every time. Now the link opens a page that says whose Tucano it is and as whom, with a **Sign in on this browser** button; only that button (a POST from the same page) spends the code, once. A prefetch gets nothing, and a wrong or used code still counts as a guess, as before. The phone's QR code and link, the desktop app's pairing and invites (`/?invite=`, which never spent anything on opening) work as they did.- **Your devices can be seen and disconnected.** Under "You're signed in on N devices", **Settings › People** lists each browser and phone signed in as you, when it was added, when it was last seen (or "never used", like the ones a link preview made), and a **Disconnect** button. Disconnecting signs that device out at once and closes its open pages; the others stay. The one you're using is marked, and asks before going. On the desktop app, **Settings › Phone › Your iPhone** lists the iPhones paired over the home Wi-Fi the same way, and **Disconnect** cuts that phone off right away, open connection included.+### Changed++- **"Primeiros passos" is now Missões**, a card at the bottom of the sidebar and a page of its own, still checking itself off as things happen: talk to your agent, approve something, connect an account, build a second agent, put something on autopilot, keep something that matters. On a new install the sidebar starts short (the Tuca, what waits for you, the channel, the agent, the missions and the settings) and each mission brings a part of it, tagged **NOVO** until opened: Connectors, Channels, Routines, Memory and Wiki; a part with something in it shows anyway, and **Mostrar tudo de uma vez** shows the whole sidebar. An existing install keeps its sidebar as it was and never goes through the new introduction; **Configurações › Geral › Rever a introdução** still shows it.+## [0.2.17] - 2026-11-07> **Em português:**diff --git a/README.md b/README.mdindex 356d3d3..c905380 100644--- a/README.md+++ b/README.md@@ -155,7 +155,7 @@ On Linux and Windows, use **Ctrl** instead of **⌘**. Closing the window keeps- **Connect a tool:** **Connectors → Add**, paste the MCP server's address. OAuth servers open the browser; the others ask for a token. Then, on each agent's page, set its access to each connector.- **Archived agents** leave the sidebar and stop answering, but keep their history and receipts. Find them under **Archived** to bring them back.- **Approve from your phone:** connect the Telegram bot in **Settings → Phone**; approvals and questions arrive with their buttons.-- **Getting started**, in the sidebar, walks you through the rest: build a team, connect a tool, teach the memory, schedule a routine, lend a project.+- **Missions**, in the sidebar, walk you through the rest by doing it: talk to your agent, approve something, connect an account, build a second agent, put something on autopilot, keep something that matters.## How it worksdiff --git a/README.pt-BR.md b/README.pt-BR.mdindex 2190a48..9dceb32 100644--- a/README.pt-BR.md+++ b/README.pt-BR.md@@ -155,7 +155,7 @@ No Linux e no Windows, use **Ctrl** no lugar do **⌘**. Fechar a janela deixa o- **Conectar uma ferramenta:** **Conectores → Adicionar**, cole o endereço do servidor MCP. Os com OAuth abrem o navegador; os outros pedem um token. Depois, na página de cada agente, escolha o acesso dele a cada conector.- **Agentes arquivados** saem da barra lateral e param de responder, mas o histórico e os recibos ficam. Eles aparecem em **Arquivados**, pra reativar.- **Aprovar pelo celular:** conecte o bot do Telegram em **Configurações → Celular**; aprovações e perguntas chegam com os botões.-- **Primeiros passos**, na barra lateral, leva você pelo resto: montar um time, conectar uma ferramenta, ensinar a memória, agendar uma rotina, emprestar um projeto.+- **Missões**, na barra lateral, levam você pelo resto fazendo: falar com o seu agente, aprovar algo, conectar uma conta, montar um segundo agente, deixar algo no automático, guardar algo que importa.## Como funcionadiff --git a/docs/workspaces.md b/docs/workspaces.mdindex 38efa10..25c5520 100644--- a/docs/workspaces.md+++ b/docs/workspaces.md@@ -6,9 +6,7 @@ at the top of the sidebar to switch or use the **+** beside the gear to create athe 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.+every workspace with create, duplicate and delete actions.Each row also has a pause/resume control. It uses the same per-workspace pauseas the sidebar: no new agent work or routines start, but running work can finish.diff --git a/package-lock.json b/package-lock.jsonindex fe922d0..9b035c6 100644--- a/package-lock.json+++ b/package-lock.json@@ -10,6 +10,7 @@"license": "Apache-2.0","dependencies": {"@fontsource-variable/inter": "^5.3.0",+ "@fontsource-variable/nunito": "^5.3.0","@modelcontextprotocol/sdk": "^1.32.1","electron-updater": "^6.8.11","gsap": "^3.14.2",@@ -685,6 +686,15 @@"url": "https://github.com/sponsors/ayuhito"}},+ "node_modules/@fontsource-variable/nunito": {+ "version": "5.3.0",+ "resolved": "https://registry.npmjs.org/@fontsource-variable/nunito/-/nunito-5.3.0.tgz",+ "integrity": "sha512-tw0ch7evIDSwoeUy+0XzocYHfbRWLeCRPJy22KgbrLjDLAbNw/fErBiil10Ssrs3Sjr55zaZrr36a975j8cBkQ==",+ "license": "OFL-1.1",+ "funding": {+ "url": "https://github.com/sponsors/ayuhito"+ }+ },"node_modules/@hono/node-server": {"version": "2.1.5","resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.5.tgz",diff --git a/package.json b/package.jsonindex 2821b82..fff2387 100644--- a/package.json+++ b/package.json@@ -45,6 +45,7 @@},"dependencies": {"@fontsource-variable/inter": "^5.3.0",+ "@fontsource-variable/nunito": "^5.3.0","@modelcontextprotocol/sdk": "^1.32.1","electron-updater": "^6.8.11","gsap": "^3.14.2",diff --git a/scripts/screens-onboarding.mjs b/scripts/screens-onboarding.mjsindex c6836f9..d7f084c 100644--- a/scripts/screens-onboarding.mjs+++ b/scripts/screens-onboarding.mjs@@ -1,91 +1,304 @@-// Screenshots of the first-run introduction, step by step, on a new install-// (no sample team), with the fake engines. Then the "Primeiros passos" list.+// Screenshots of the first run, screen by screen, on a new install with the fake engines: nothing+// set up (TUCANO_FAKE_NO_AI: ChatGPT "set up" from the screen), then the Tuca's question, the agent,+// the first message with its balloon, an agent's request with its balloon, the Tuca's and the+// missions' balloons, and the missions. Then the same app found ready (three clicks), how far the+// agent goes on its own (each answer, No guardrails' confirmation, the balloon on that level), the+// advanced and from-scratch paths, English and dark. Only the window is captured.+// node scripts/screens-onboarding.mjs <out dir>import { _electron as electron } from 'playwright'import { mkdirSync, mkdtempSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'const out = process.argv[2] ?? 'screens'mkdirSync(out, { recursive: true })-const data = mkdtempSync(join(tmpdir(), 'tucano-'))-const app = await electron.launch({ args: ['.'], env: { ...process.env, TUCANO_DATA: data, TUCANO_FAKE_ENGINES: '1', TUCANO_SEED: '0' } })-const win = await app.firstWindow()-await win.setViewportSize({ width: 1360, height: 860 })const errors = []-win.on('pageerror', (e) => errors.push(String(e)))-win.on('console', (m) => m.type() === 'error' && errors.push(m.text()))-const shot = (name) => win.screenshot({ path: `${out}/${name}.png` })-const settle = () => win.waitForTimeout(500)-await win.waitForSelector('.splash')-await win.click('.splash') // skip the opening-await win.waitForSelector('.onb')-await win.fill('.onb__field input', 'Marina')-await settle()-await shot('1-boas-vindas')-await win.click('button:has-text("Começar")')-await settle()-await shot('2-motor')-await win.click('button:has-text("Continuar")')-await settle()-await shot('2b-modelos-vazio')-const picks = win.locator('.onb-pick select')-await picks.nth(0).selectOption('custom:claude')-await win.locator('.onb-pick').nth(0).locator('.model-name').fill('gw-claude-haiku')-await picks.nth(1).selectOption('haiku')-await settle()-await shot('2c-modelos')-await win.click('button:has-text("Continuar")')-await win.fill('.onb__textarea', 'Sou designer numa agência pequena em Curitiba. Cuido de três clientes de e-commerce.')-await win.click('.onb-chip:has-text("Prefiro respostas curtas")')-await settle()-await shot('3-voce')-await win.click('button:has-text("Continuar")')-await win.fill('.onb-add input >> nth=0', 'Jira interno')-await win.fill('.onb-add input >> nth=1', 'https://mcp.lumen.dev/jira')-await win.click('.onb-add .segmented button:has-text("Token")')-await win.fill('.onb-add input[type=password]', 'tok-123')-await win.click('.onb-add button:has-text("Conectar")')-await win.waitForTimeout(1500)-await shot('3b-ferramentas')-await win.click('.onb__nav .btn--primary')-await win.waitForTimeout(800)-await win.locator('.onb-skill').first().click().catch(() => {})-await settle()-await shot('3c-skills')-await win.click('.onb__nav .btn--primary')-await settle()-await shot('4-agente')-await win.click('.onb-template:has-text("Conteúdo")')-await settle()-await shot('4b-agente-conteudo')-await win.click('.onb-template:has-text("Pesquisa")')-await win.click('button:has-text("Continuar")')-await win.click('.onb-power-row:has-text("Navegador") .toggle')-await win.click('.segmented button:has-text("Este Mac")')-await settle()-await shot('5-poderes')-await win.click('.segmented button:has-text("Nenhum")')-await win.click('button:has-text("Continuar")')-await settle()-await shot('6-primeira-tarefa')-await win.click('button:has-text("e enviar")')-await win.waitForSelector('.sidebar')-await win.waitForTimeout(4000)-await shot('7-canal')-await win.click('.getting__bar')-await settle()-await shot('8-primeiros-passos')-await win.click('.getting__list li.is-next button')-await settle()-await shot('9-depois-do-clique')-await win.click('.sidebar button[title="Trocar tema"]')-await win.click('.sidebar__foot .nav-item:has-text("Configurações")')-await win.click('button:has-text("Rever a introdução")')-await win.waitForSelector('.onb')-await settle()-await shot('10-rever-escuro')-await win.click('button:has-text("Começar")')-await settle()-await shot('11-motor-escuro')+async function open(env = {}) {+ const data = mkdtempSync(join(tmpdir(), 'tucano-onb-'))+ const app = await electron.launch({ args: ['.'], env: { ...process.env, TUCANO_DATA: data, TUCANO_FAKE_ENGINES: '1', TUCANO_SEED: '0', TUCANO_LOCALE: 'pt-BR', ...env } })+ const win = await app.firstWindow()+ await win.setViewportSize({ width: 1280, height: 800 })+ win.on('pageerror', (e) => errors.push(String(e)))+ win.on('console', (m) => m.type() === 'error' && errors.push(m.text()))+ return { app, win }+}+const settle = (win, ms = 500) => win.waitForTimeout(ms)+// What this computer's Claude Code has (its tools and skills) stays out of the screenshots' install.+const untick = async (win) => {+ await win.waitForTimeout(800)+ while ((await win.locator('.intro-checkbox input:checked').count()) > 0) await win.locator('.intro-checkbox input:checked').first().uncheck()+}+const skipSplash = async (win) => {+ await win.waitForSelector('.splash')+ await win.click('.splash')+ await win.waitForSelector('.intro')+}++// ---------- nothing set up: the whole path ----------+{+ const { app, win } = await open({ TUCANO_FAKE_NO_AI: '1' })+ const shot = (name) => win.screenshot({ path: `${out}/${name}.png` })+ await skipSplash(win)+ await win.fill('.intro-input', 'Carol')+ await settle(win)+ await shot('01-boas-vindas')+ await win.click('button:has-text("Tenho um convite ou um servidor")')+ await settle(win)+ await shot('01b-convite-ou-servidor')+ await win.click('button:has-text("Tenho um convite ou um servidor")')+ await win.click('button:has-text("Começar")')+ await settle(win, 1200)+ await shot('02-conectar-nada')+ await win.click('button:has-text("Não assino nenhuma")')+ await settle(win)+ await shot('02b-nao-assino')+ await win.click('button:has-text("Não assino nenhuma")')+ await win.click('.intro-card--pick:has-text("ChatGPT")')+ await win.waitForSelector('.intro-step.is-now')+ await settle(win, 600)+ await shot('02c-preparando')+ await win.waitForSelector('text=Abri o login no seu navegador')+ await settle(win, 300)+ await shot('02d-login-no-navegador')+ await win.waitForSelector('button:has-text("Continuar")', { timeout: 20_000 })+ await settle(win)+ await shot('02e-conectado')+ await win.click('button:has-text("Continuar")')+ await settle(win)+ await shot('03-o-tuca-pergunta')+ await win.fill('#intro-say', 'responder clientes da minha loja no Instagram')+ await settle(win)+ await shot('03b-do-seu-jeito')+ await win.fill('#intro-say', '')+ await win.click('.intro-tile:has-text("Organizar minha semana")')+ await settle(win, 800)+ await shot('04-o-agente-nasce')+ await win.click('button[aria-label="Mudar o nome"]')+ await win.fill('.intro-name__input', 'Lia')+ await win.keyboard.press('Enter')+ await win.click('.intro-color[aria-label="Verde-água"]')+ await settle(win)+ await shot('04b-nome-e-cor')+ await win.click('.intro-color[aria-label="Lilás"]')+ await win.click('.intro-offer button:has-text("Conectar")')+ await settle(win, 800)+ await shot('04c-conectar-opcional')+ await win.keyboard.press('Escape')+ await win.click('button:has-text("Ajustar com o Tuca")')+ await win.waitForSelector('.intro-chat .composer textarea', { timeout: 20_000 })+ await settle(win, 800)+ await shot('04d-ajustar-com-o-tuca')+ await win.click('.intro__top button:has-text("Voltar")')+ await settle(win)+ await win.click('button:has-text("Chamar Lia pro time")')+ await win.waitForSelector('.coach__card--first', { timeout: 20_000 })+ await settle(win, 800)+ await shot('05-primeira-mensagem')+ // The first message asks something of the person, so the request's balloon shows on a real request.+ await win.fill('.main .composer textarea', '@lia me ajuda a decidir como organizar a semana')+ await win.keyboard.press('Enter')+ await win.waitForSelector('.coach__card--ask', { timeout: 30_000 })+ await settle(win, 800)+ await shot('06-tour-aprovacao')+ await win.click('.coach__skip').catch(() => {})+ await settle(win)+ await shot('06b-tour-pulado')+ // A new install's sidebar: short, and the missions.+ await win.click('.missions-card')+ await settle(win, 800)+ await shot('07-missoes')+ await win.click('.sidebar button[title="Trocar tema"]')+ await settle(win, 800)+ await shot('07b-missoes-escuro')+ await app.close()+}++// ---------- the tour's other balloons, the short sidebar growing ----------+{+ const { app, win } = await open({ TUCANO_FAKE_NO_AI: '1' })+ const shot = (name) => win.screenshot({ path: `${out}/${name}.png` })+ await skipSplash(win)+ await win.fill('.intro-input', 'Carol')+ await win.click('button:has-text("Começar")')+ await win.click('.intro-card--pick:has-text("Claude")')+ await win.waitForSelector('button:has-text("Continuar")', { timeout: 20_000 })+ await win.click('button:has-text("Continuar")')+ await win.click('.intro-tile:has-text("Pesquisar e resumir")')+ await win.click('button:has-text("Chamar Iris pro time")')+ await win.waitForSelector('.coach__card--first', { timeout: 20_000 })+ // A reply with no request in it: the Tuca's balloon, then the missions'.+ await win.fill('.main .composer textarea', '@iris quais as 3 notícias de IA mais importantes da semana?')+ await win.keyboard.press('Enter')+ await win.waitForSelector('.coach__card--tuca', { timeout: 30_000 })+ await settle(win, 800)+ await shot('08-tour-tuca')+ await win.click('.coach__ok')+ await win.waitForSelector('.coach__card--missions', { timeout: 10_000 })+ await settle(win, 800)+ await shot('08b-tour-missoes')+ await win.click('.coach__ok')+ await settle(win, 800)+ // "Lembre que…" keeps a memory: the last mission, which brings Memória and Wiki.+ await win.click('.sidebar .nav-item:has-text("geral")')+ await win.fill('.main .composer textarea', '@iris lembre que eu prefiro respostas curtas')+ await win.keyboard.press('Enter')+ await win.waitForSelector('.nav-item__new', { timeout: 30_000 })+ await settle(win, 800)+ await shot('09-barra-cresce')+ await win.click('.missions-card')+ await settle(win, 600)+ await shot('09b-missoes-liberou')+ await app.close()+}++// ---------- found ready: three clicks, in English, then dark ----------+{+ const { app, win } = await open({})+ const shot = (name) => win.screenshot({ path: `${out}/${name}.png` })+ await skipSplash(win)+ await win.fill('.intro-input', 'Carol')+ await win.click('.intro-lang button:has-text("English")')+ await win.waitForSelector('text=Get started')+ await settle(win)+ await shot('10-en-welcome')+ await win.click('button:has-text("Get started")')+ await win.waitForSelector('text=answered in', { timeout: 20_000 })+ await untick(win)+ await settle(win, 800)+ await shot('10b-en-found-ready')+ await win.click('button:has-text("Change")')+ await settle(win)+ await shot('10c-en-change-models')+ await win.click('button:has-text("Continue")')+ await settle(win)+ await shot('10d-en-tuca-asks')+ await win.fill('#intro-say', 'reply to customers of my Instagram shop')+ await win.keyboard.press('Enter')+ await settle(win, 800)+ await shot('10e-en-agent-from-own-words')+ await win.click('.intro__top button:has-text("Back")')+ await win.click('.intro-lang button:has-text("Português")').catch(() => {})+ await app.close()+}+{+ const { app, win } = await open({})+ await win.emulateMedia({ colorScheme: 'dark' })+ const shot = (name) => win.screenshot({ path: `${out}/${name}.png` })+ await skipSplash(win)+ await win.fill('.intro-input', 'Carol')+ await settle(win)+ await shot('11-escuro-boas-vindas')+ await win.click('button:has-text("Começar")')+ await win.waitForSelector('text=respondeu em', { timeout: 20_000 })+ await untick(win)+ await settle(win, 800)+ await shot('11b-escuro-achei')+ await win.click('button:has-text("Continuar")')+ await settle(win)+ await shot('11c-escuro-pergunta')+ await win.click('.intro-tile:has-text("Programar")')+ await settle(win, 800)+ await shot('11d-escuro-agente')+ await win.click('button:has-text("Chamar Leo pro time")')+ await win.waitForSelector('.coach__card--first', { timeout: 20_000 })+ await settle(win, 800)+ await shot('11e-escuro-primeira-mensagem')+ await app.close()+}++{+ const { app, win } = await open({ TUCANO_FAKE_NO_AI: '1' })+ await win.emulateMedia({ colorScheme: 'dark' })+ const shot = (name) => win.screenshot({ path: `${out}/${name}.png` })+ await skipSplash(win)+ await win.fill('.intro-input', 'Carol')+ await win.click('button:has-text("Começar")')+ await win.click('.intro-card--pick:has-text("Claude")')+ await win.waitForSelector('text=Abri o login no seu navegador')+ await settle(win, 300)+ await shot('11f-escuro-conectando')+ await app.close()+}++// ---------- how far the agent goes on its own: each answer, the confirmation, the balloon ----------+{+ const { app, win } = await open({})+ const shot = (name) => win.screenshot({ path: `${out}/${name}.png` })+ const row = (text) => win.locator(`.autonomy-pick__row:has-text("${text}")`)+ await skipSplash(win)+ await win.fill('.intro-input', 'Carol')+ await win.click('button:has-text("Começar")')+ await win.waitForSelector('button:has-text("Continuar"):not([disabled])')+ await untick(win)+ await win.click('button:has-text("Continuar")')+ await win.click('.intro-tile:has-text("Organizar minha semana")')+ await settle(win, 800)+ await shot('15-autonomia-normal')+ await row('Me pergunta antes').click()+ await settle(win)+ await shot('15b-autonomia-cuidadoso')+ await row('Faz tudo por conta própria').click()+ await win.waitForSelector('.modal')+ await settle(win)+ await shot('15c-autonomia-confirmacao')+ await win.click('.modal button:has-text("Sem travas")')+ await settle(win)+ await shot('15d-autonomia-sem-travas')+ await win.click('button:has-text("Chamar Lia pro time")')+ await win.waitForSelector('.coach__card--first', { timeout: 20_000 })+ await win.fill('.main .composer textarea', '@lia me ajuda a decidir como organizar a semana')+ await win.keyboard.press('Enter')+ await win.waitForSelector('.coach__card--ask', { timeout: 30_000 })+ await settle(win, 800)+ await shot('15e-tour-sem-travas')+ await app.close()+}++// ---------- the other ways: advanced, from scratch ----------+{+ const { app, win } = await open({ TUCANO_FAKE_NO_AI: '1' })+ const shot = (name) => win.screenshot({ path: `${out}/${name}.png` })+ await skipSplash(win)+ await win.fill('.intro-input', 'Carol')+ await win.click('button:has-text("Começar")')+ await win.click('button:has-text("Uso chave de API")')+ await settle(win, 800)+ await shot('12-avancado')+ await app.close()+}+{+ const { app, win } = await open({})+ const shot = (name) => win.screenshot({ path: `${out}/${name}.png` })+ await skipSplash(win)+ await win.fill('.intro-input', 'Carol')+ await win.click('button:has-text("Começar")')+ await win.waitForSelector('button:has-text("Continuar"):not([disabled])')+ await untick(win)+ await win.click('button:has-text("Continuar")')+ await win.click('button:has-text("Prefiro configurar do zero")')+ await settle(win, 800)+ await shot('13-do-zero')+ await win.click('.onb .btn--primary:has-text("Continuar")')+ await settle(win)+ await shot('13a-do-zero-poderes')+ await win.click('.onb .btn--primary:has-text("Continuar")')+ await settle(win)+ await shot('13b-do-zero-primeira-tarefa')+ await win.click('.onb .btn--primary:has-text("pro time")')+ await win.waitForSelector('.coach__card--first', { timeout: 20_000 })+ await settle(win, 800)+ await shot('13c-do-zero-no-canal')+ await app.close()+}++// ---------- someone who already uses Tucano: no short sidebar, no introduction ----------+{+ const { app, win } = await open({ TUCANO_SEED: '1' })+ const shot = (name) => win.screenshot({ path: `${out}/${name}.png` })+ await win.waitForSelector('.sidebar')+ await settle(win, 1200)+ await shot('14-quem-ja-usa')+ await app.close()+}+console.log('erros:', errors)-await app.close()diff --git a/src/core/context.ts b/src/core/context.tsindex 99f1066..7676f14 100644--- a/src/core/context.ts+++ b/src/core/context.ts@@ -10,12 +10,13 @@ import { CODE_SPANS, describeSchedule, PROJECTS_DIR, type Agent, type AgentApp,import type { ToolDef } from './gateway'import { describeQuestions, questionsOf } from '../shared/questions'import { osOf, shellCommand, systemName } from './platform'+import { levelOf, policyOf, type Autonomy } from '../shared/actions'export const HISTORY_LIMIT = 30export type PromptOpts = {agent: Agent- settings: Pick<Settings, 'workspaceName' | 'context'>+ settings: Pick<Settings, 'workspaceName' | 'context' | 'autonomy'>conversation: Conversationpeers: Agent[]memories?: { aboutMe: Memory[]; own: Memory[]; searchable?: number }@@ -131,10 +132,7 @@ export function systemPrompt(opts: PromptOpts): string {`- Quando descobrir um jeito de fazer algo que vale repetir (resolveu em vários passos, saiu de um beco sem saída, ${me} corrigiu você), proponha uma skill com propor_skill, ou uma mudança numa sua. Ela só vale depois que ${me} aprovar.`,`- When you find a way of doing something worth repeating (you solved it in several steps, got out of a dead end, ${me} corrected you), propose a skill with propor_skill, or a change to one of yours. It only counts once ${me} approves it.`),- L(- `- Suas outras ferramentas são as que ${me} liberou pra você. Ações sensíveis não rodam na hora: viram um pedido de aprovação, e você recebe o resultado depois da decisão.`,- `- Your other tools are the ones ${me} granted you. Sensitive actions don't run right away: they become an approval request, and you get the result after the decision.`- ),+ toolsLine(me, levelOf(policyOf(agent, settings))),connectors && readingData(me),hasComputer? L('- Não diga que fez algo que nenhuma ferramenta sua fez.', "- Don't say you did something none of your tools did.")@@ -212,6 +210,17 @@ function peopleSection(people: Person[]): string {// Reading a channel, a history, logs or a table: only the window the task needs, and no waiting by hand.// Without it an agent asked about "the alarm" pages through the whole channel and sleeps on slow queries.+// What waits for an approval at the agent's autonomy level (src/shared/actions.ts), in one line: the+// gateway holds the call either way and its result says so; this keeps the agent from promising,+// or asking in words, what the level already decides.+export function toolsLine(me: string, level: Autonomy): string {+ const granted = L(`- Suas outras ferramentas são as que ${me} liberou pra você.`, `- Your other tools are the ones ${me} granted you.`)+ const after = L('e você recebe o resultado depois da decisão.', 'and you get the result after the decision.')+ if (level === 'careful') return `${granted} ${L(`${me} quer aprovar tudo que muda algo: escrever, enviar, apagar, commit, push. Essas ações não rodam na hora: viram um pedido de aprovação,`, `${me} wants to approve anything that changes something: writing, sending, deleting, a commit, a push. Those don't run right away: they become an approval request,`)} ${after}`+ if (level === 'free') return `${granted} ${L(`${me} deixou você agir sem pedir aprovação. Só o que é de alto risco, ou o que vai pra fora depois de você ler algo de fora, vira um pedido de aprovação,`, `${me} lets you act without asking for approval. Only what's high risk, or what goes out after you read something from outside, becomes an approval request,`)} ${after}`+ return `${granted} ${L('Ações sensíveis (enviar, apagar, publicar, pagar) não rodam na hora: viram um pedido de aprovação,', "Sensitive actions (sending, deleting, publishing, paying) don't run right away: they become an approval request,")} ${after}`+}+export function readingData(me: string): string {return [L(diff --git a/src/core/engine-setup.ts b/src/core/engine-setup.tsnew file mode 100644index 0000000..6568a66--- /dev/null+++ b/src/core/engine-setup.ts@@ -0,0 +1,268 @@+// Setting up Codex or Claude Code with no terminal: the official CLI, downloaded from where its own+// installer downloads it and checked against the published checksum, into a folder of the app's+// (engines/ in the data folder); then the CLI's own sign-in, which opens the browser and finishes on+// its own callback on this computer. The person signs in on OpenAI's or Anthropic's page: Tucano+// never sees a password or a token, and doesn't relay the codes (the CLI stores the login where it+// always does). The binary isn't changed, and on a machine where this can't work the screen offers+// the terminal as before.+// Codex: github.com/openai/codex releases (codex-package-<target>.tar.gz, sha256 in the release),+// `codex login` (browser, callback on localhost:1455).+// Claude Code: downloads.claude.ai/claude-code-releases (manifest.json with each platform's sha256),+// `claude auth login` (browser, callback on localhost).+import { createHash } from 'node:crypto'+import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync, writeSync } from 'node:fs'+import { delimiter, dirname, join } from 'node:path'+import { L } from '../shared/lang'+import type { EngineStatus, Os, SetupEngine, SetupState } from '../shared/types'++export type { SetupEngine, SetupState }+export const SETUP_ENGINES: readonly SetupEngine[] = ['claude', 'codex']++export const CLAUDE_RELEASES = 'https://downloads.claude.ai/claude-code-releases'+export const CODEX_RELEASE = 'https://api.github.com/repos/openai/codex/releases/latest'++// ---------- what to download, per system (pure) ----------++export function codexTarget(os: Os, arch: string): string | undefined {+ const a = arch === 'arm64' ? 'aarch64' : arch === 'x64' ? 'x86_64' : undefined+ if (!a) return undefined+ return os === 'mac' ? `${a}-apple-darwin` : os === 'linux' ? `${a}-unknown-linux-musl` : `${a}-pc-windows-msvc`+}++export function claudePlatform(os: Os, arch: string, musl = false): string | undefined {+ if (arch !== 'arm64' && arch !== 'x64') return undefined+ if (os === 'mac') return `darwin-${arch}`+ if (os === 'windows') return `win32-${arch}`+ return `linux-${arch}${musl ? '-musl' : ''}`+}++interface Download {+ version: string+ url: string+ sha256: string+}++// The package Codex's own installer takes (the CLI with its helpers), from a release as GitHub's API lists it.+export function codexAsset(release: unknown, target: string): Download | undefined {+ const r = release as { tag_name?: unknown; assets?: { name?: unknown; browser_download_url?: unknown; digest?: unknown }[] } | null+ const version = typeof r?.tag_name === 'string' ? r.tag_name.replace(/^rust-v/, '') : ''+ const a = r?.assets?.find((x) => x.name === `codex-package-${target}.tar.gz`)+ const sha256 = typeof a?.digest === 'string' ? a.digest.replace(/^sha256:/, '') : ''+ if (!version || typeof a?.browser_download_url !== 'string' || !/^[0-9a-f]{64}$/.test(sha256)) return undefined+ return { version, url: a.browser_download_url, sha256 }+}++// Claude Code's binary for this platform, from the version's manifest.+export function claudeBinary(manifest: unknown, version: string, platform: string): Download | undefined {+ const p = (manifest as { platforms?: Record<string, { checksum?: unknown; binary?: unknown }> } | null)?.platforms?.[platform]+ const sha256 = typeof p?.checksum === 'string' ? p.checksum : ''+ if (!/^\d+\.\d+\.\d+/.test(version) || !/^[0-9a-f]{64}$/.test(sha256)) return undefined+ const binary = typeof p?.binary === 'string' && /^[\w.-]+$/.test(p.binary) ? p.binary : platform.startsWith('win32') ? 'claude.exe' : 'claude'+ return { version, url: `${CLAUDE_RELEASES}/${version}/${platform}/${binary}`, sha256 }+}++// The sign-in page a CLI printed, without the terminal's colors and hyperlink codes around it.+export function loginUrl(out: string): string | undefined {+ // eslint-disable-next-line no-control-regex+ const clean = out.replace(/\x1b\]8;[^\x07\x1b]*(\x07|\x1b\\)/g, '').replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '')+ return clean.match(/https:\/\/[^\s"'<>\x1b]+/)?.[0]+}++// ---------- the setup ----------++export interface SetupDeps {+ dir: string // engines/ in the data folder+ os: Os+ arch: string+ musl: () => boolean+ fetch: typeof fetch+ // tar, to unpack Codex's package (macOS, Linux and Windows 10 and later have it)+ untar: (archive: string, into: string) => Promise<void>+ // the CLI's sign-in, as a process: its output as it comes, and how it ended+ spawn: (bin: string, args: string[], env: NodeJS.ProcessEnv) => { output: (on: (text: string) => void) => void; exit: Promise<number>; kill: () => void }+ status: (engine: SetupEngine) => EngineStatus+ recheck: (engine: SetupEngine) => Promise<EngineStatus>+ env: (engine: SetupEngine) => NodeJS.ProcessEnv // where the login goes: Codex's home of the app's, Claude Code's usual one+ changed: () => void+ timeoutMs?: number // the sign-in, at most+}++export class EngineSetup {+ current: SetupState | null = null+ private abort?: AbortController+ private child?: { kill: () => void }++ constructor(private deps: SetupDeps) {}++ // The folders of the CLIs installed here, for PATH: after the person's own, which win.+ dirs(): string[] {+ try {+ const saved = JSON.parse(readFileSync(join(this.deps.dir, 'installed.json'), 'utf8')) as Record<string, unknown>+ return Object.values(saved).filter((d): d is string => typeof d === 'string' && existsSync(d))+ } catch {+ return []+ }+ }++ withDirs(path: string): string {+ const have = path.split(delimiter).filter(Boolean)+ return [...have, ...this.dirs().filter((d) => !have.includes(d))].join(delimiter)+ }++ start(engine: SetupEngine): SetupState {+ if (this.current?.state === 'running') return this.current+ this.set({ engine, step: 'install', state: 'running' })+ void this.run(engine)+ return this.current!+ }++ cancel(): void {+ if (this.current?.state !== 'running') return+ this.abort?.abort()+ this.child?.kill()+ this.set({ ...this.current, state: 'cancelled' })+ }++ private set(s: SetupState): void {+ this.current = s+ this.deps.changed()+ }++ private async run(engine: SetupEngine): Promise<void> {+ this.abort = new AbortController()+ try {+ let bin = this.deps.status(engine).installed ? this.deps.status(engine).path : undefined+ if (!bin) {+ bin = engine === 'codex' ? await this.installCodex() : await this.installClaude()+ process.env['PATH'] = this.withDirs(process.env['PATH'] ?? '')+ await this.deps.recheck(engine)+ }+ if (this.current?.state !== 'running') return+ if (this.deps.status(engine).loggedIn) return this.set({ engine, step: 'login', state: 'done' })+ this.set({ engine, step: 'login', state: 'running' })+ await this.login(engine, bin)+ const st = await this.deps.recheck(engine)+ if (this.current?.state !== 'running') return+ this.set(st.loggedIn ? { engine, step: 'login', state: 'done' } : { engine, step: 'login', state: 'error', error: L('O login não terminou. Tente de novo.', "The sign-in didn't finish. Try again.") })+ } catch (e) {+ if (this.current?.state !== 'running') return+ this.set({ ...this.current, state: 'error', error: e instanceof Error ? e.message : String(e) })+ }+ }++ private async json(url: string): Promise<unknown> {+ const r = await this.deps.fetch(url, { signal: this.abort?.signal, headers: { accept: 'application/json', 'user-agent': 'Tucano' } })+ if (!r.ok) throw new Error(L(`Não consegui falar com ${new URL(url).host} (${r.status}).`, `Couldn't reach ${new URL(url).host} (${r.status}).`))+ return r.json()+ }++ // Downloads to a temporary file, checking the sha256 as it comes; only a match is kept.+ private async download(d: Download, to: string): Promise<void> {+ const r = await this.deps.fetch(d.url, { signal: this.abort?.signal, headers: { 'user-agent': 'Tucano' } })+ if (!r.ok || !r.body) throw new Error(L(`O download falhou (${r.status}).`, `The download failed (${r.status}).`))+ const total = Number(r.headers.get('content-length')) || 0+ const hash = createHash('sha256')+ const part = `${to}.part`+ mkdirSync(dirname(to), { recursive: true })+ const fd = openSync(part, 'w')+ let got = 0+ let shown = 0+ try {+ const reader = r.body.getReader()+ for (;;) {+ const { done, value } = await reader.read()+ if (done) break+ hash.update(value)+ writeSync(fd, value)+ got += value.length+ // A new number every couple of percent: enough to see it move.+ if (total && got / total - shown >= 0.02) this.set({ ...this.current!, progress: (shown = got / total) })+ }+ } finally {+ closeSync(fd)+ }+ if (hash.digest('hex') !== d.sha256) {+ rmSync(part, { force: true })+ throw new Error(L('O arquivo baixado não bate com o publicado. Nada foi instalado.', "The downloaded file doesn't match the published one. Nothing was installed."))+ }+ renameSync(part, to)+ }++ private remember(engine: SetupEngine, binDir: string): void {+ const file = join(this.deps.dir, 'installed.json')+ let saved: Record<string, string> = {}+ try {+ saved = JSON.parse(readFileSync(file, 'utf8')) as Record<string, string>+ } catch {+ // the first one+ }+ writeFileSync(file, JSON.stringify({ ...saved, [engine]: binDir }, null, 2))+ }++ private async installCodex(): Promise<string> {+ const target = codexTarget(this.deps.os, this.deps.arch)+ if (!target) throw new Error(L('O Codex não tem uma versão pra este computador.', "Codex has no build for this computer."))+ const asset = codexAsset(await this.json(CODEX_RELEASE), target)+ if (!asset) throw new Error(L('Não achei o Codex pra este computador na última versão.', "Couldn't find Codex for this computer in the latest release."))+ const root = join(this.deps.dir, 'codex', asset.version)+ const archive = join(this.deps.dir, 'codex', `${asset.version}.tar.gz`)+ await this.download(asset, archive)+ rmSync(root, { recursive: true, force: true })+ mkdirSync(root, { recursive: true })+ await this.deps.untar(archive, root)+ rmSync(archive, { force: true })+ // The package says where its CLI is (bin/codex); its helpers stay next to it.+ let entry = 'bin/codex'+ try {+ const pkg = JSON.parse(readFileSync(join(root, 'codex-package.json'), 'utf8')) as { entrypoint?: unknown }+ if (typeof pkg.entrypoint === 'string' && !pkg.entrypoint.includes('..')) entry = pkg.entrypoint+ } catch {+ // an older package: the usual place+ }+ let bin = join(root, entry)+ if (this.deps.os === 'windows' && !bin.toLowerCase().endsWith('.exe')) bin += '.exe'+ if (!existsSync(bin)) throw new Error(L('O pacote do Codex veio sem o programa.', 'The Codex package came without the program.'))+ this.remember('codex', dirname(bin))+ return bin+ }++ private async installClaude(): Promise<string> {+ const platform = claudePlatform(this.deps.os, this.deps.arch, this.deps.os === 'linux' && this.deps.musl())+ if (!platform) throw new Error(L('O Claude Code não tem uma versão pra este computador.', 'Claude Code has no build for this computer.'))+ const r = await this.deps.fetch(`${CLAUDE_RELEASES}/latest`, { signal: this.abort?.signal })+ const version = r.ok ? (await r.text()).trim() : ''+ const binary = claudeBinary(await this.json(`${CLAUDE_RELEASES}/${version}/manifest.json`), version, platform)+ if (!binary) throw new Error(L('Não achei o Claude Code pra este computador na última versão.', "Couldn't find Claude Code for this computer in the latest release."))+ const binDir = join(this.deps.dir, 'claude', binary.version)+ const bin = join(binDir, this.deps.os === 'windows' ? 'claude.exe' : 'claude')+ await this.download(binary, bin)+ if (this.deps.os !== 'windows') chmodSync(bin, 0o755)+ this.remember('claude', binDir)+ return bin+ }++ // The CLI's own sign-in, as the person would start it in a terminal: it opens the browser and+ // waits for the page to call back. Its output only gives the page's address, for a "open it again".+ private async login(engine: SetupEngine, bin: string): Promise<void> {+ const args = engine === 'codex' ? ['login'] : ['auth', 'login']+ const p = this.deps.spawn(bin, args, this.deps.env(engine))+ this.child = p+ let text = ''+ p.output((chunk) => {+ text = (text + chunk).slice(-8_000)+ const url = loginUrl(text)+ if (url && this.current && this.current.url !== url) this.set({ ...this.current, url })+ })+ const late = setTimeout(() => p.kill(), this.deps.timeoutMs ?? 10 * 60_000)+ try {+ const code = await p.exit+ if (code !== 0 && this.current?.state === 'running') {+ const last = text.trim().split('\n').slice(-2).join(' ').trim()+ throw new Error(last ? L(`O login não deu certo: ${last}`, `The sign-in didn't work: ${last}`) : L('O login não deu certo.', "The sign-in didn't work."))+ }+ } finally {+ clearTimeout(late)+ this.child = undefined+ }+ }+}diff --git a/src/core/guide/comecar.md b/src/core/guide/comecar.mdindex cd60876..78bd9b5 100644--- a/src/core/guide/comecar.md+++ b/src/core/guide/comecar.md@@ -6,9 +6,11 @@ O Tucano é um time de agentes de IA que roda no seu computador. Você conversaOs agentes rodam nos programas que você já usa (Claude Code, Codex, OpenCode, Pi, Gemini CLI, Cursor CLI ou Grok), do jeito que você configurou cada um. Veja a página **motores**.## A introdução-Na primeira vez, o app mostra uma introdução em passos: onde os agentes rodam, os dois modelos pequenos (quem escolhe quem responde e quem cuida da memória), um pouco sobre você, conectores e skills (opcionais), e o primeiro agente. Dá pra pular com **Pular introdução** (Skip the introduction) e rever depois em **Configurações › Geral** (Settings › General) › **Rever a introdução**.+Na primeira vez, o app guia em poucos passos: o seu nome; conectar a IA (o que já está pronto aparece testado; quem não tem nada escolhe ChatGPT ou Claude e o Tucano instala o programa oficial e abre o login no navegador, sem terminal); a pergunta do Tuca sobre o que tirar das suas costas; e o primeiro agente, que entra no **#geral** com a primeira mensagem escrita, esperando você apertar enviar. Chave de API, gateway da empresa ou outro programa: **Uso chave de API, gateway da empresa ou outro programa**. Os modelos dos bastidores são escolhidos sozinhos (**Trocar** muda). Rever: **Configurações › Geral** (Settings › General) › **Rever a introdução**.-Depois dela aparece a lista **Primeiros passos** (Getting started), que se marca sozinha conforme você usa. Escondida, ela volta em **Configurações › Geral** › **Mostrar os primeiros passos**.+Depois, balões mostram o app enquanto você usa; **Pular tour** encerra. Na barra lateral ficam as **Missões** (Missions), que se marcam sozinhas. Numa instalação nova, a barra começa curta e cada missão libera uma parte (Conectores, Canais, Rotinas, Memória e Wiki); **Mostrar tudo de uma vez** mostra tudo. Escondidas, voltam em **Configurações › Geral** › **Mostrar as missões**.++Quem entra num time por convite vê uma boas-vindas curta: quem convidou, os agentes, o nome e o combinado (o que se fala direto com um agente só a pessoa lê; nos canais, o time todo vê).## O TucaO Tuca fica no topo da barra lateral. Ele monta agentes: você conta uma tarefa, ele faz poucas perguntas e propõe um agente num card. Nada é criado sem você clicar em **Criar** (ou **Editar antes**, ou **Descartar**).diff --git a/src/core/index.ts b/src/core/index.tsindex 2b1ca94..10df09a 100644--- a/src/core/index.ts+++ b/src/core/index.ts@@ -31,6 +31,8 @@ import { cursorAppDir, cursorEngine } from './engines/cursor'import { grokEngine } from './engines/grok'import { accountDir, accountStatus, adoptLoginShellPath, detectEngines } from './engines/detect'import { detectEngine, EngineCheck, type EngineFindings } from './engine-check'+import { EngineSetup, SETUP_ENGINES, type SetupEngine, type SetupState } from './engine-setup'+import { codexEnv } from './engines/codex'import { fakeEngine } from './engines/fake'import { relocating } from './engines/relocate'import { DesktopApps, macApps, SELF } from './apps'@@ -112,9 +114,19 @@ const people = new People(db)if (!db.owner().name) db.renamePerson(db.ownerId(), db.getSettings(DEFAULTS).workspaceName, false)const fakeStatus = (v: string): EngineStatus => ({ installed: true, loggedIn: true, path: 'fake', version: v, account: L('Motor de teste', 'Test engine'), route: 'plan' })+// TUCANO_FAKE_NO_AI: a computer with nothing set up yet, until the introduction's setup "signs in" (no network).+const fakeNoAi = fake && process.env['TUCANO_FAKE_NO_AI'] === '1'+const fakeSignedIn = new Set<EngineId>()+const fakeOne = (e: EngineId, s: EngineStatus): EngineStatus => (fakeNoAi && !fakeSignedIn.has(e) ? { installed: false, loggedIn: false } : s)+// TUCANO_FAKE_BROKEN_PI: Pi found signed in to Anthropic, whose login then fails every reply (an expired refresh token).+// TUCANO_FAKE_BROKEN_OPENCODE: OpenCode, found, fails every reply with an error nobody wrote for people.+const fakeBrokenPi = fake && process.env['TUCANO_FAKE_BROKEN_PI'] === '1'+const fakeBrokenOpencode = fake && process.env['TUCANO_FAKE_BROKEN_OPENCODE'] === '1'+const OPENCODE_CRASH = "TypeError: Cannot read properties of undefined (reading 'providers')\n at loadConfig (file:///opt/homebrew/lib/node_modules/opencode-ai/dist/config.js:212:30)\n at async main (file:///opt/homebrew/lib/node_modules/opencode-ai/dist/index.js:18:3)"+const PI_EXPIRED = 'OAuth refresh failed for anthropic: 400 {"type":"error","error":{"type":"invalid_grant","message":"Refresh token expired"}}\n at postJson (file:///opt/homebrew/lib/node_modules/@earendil-works/pi-coding-agent/dist/auth/oauth.js:88:11)\n at async refreshAnthropic (file:///opt/homebrew/lib/node_modules/@earendil-works/pi-coding-agent/dist/auth/anthropic.js:41:5)\n at async getAuth (file:///opt/homebrew/lib/node_modules/@earendil-works/pi-coding-agent/dist/auth/index.js:23:12)'const fakeFindings = (): Omit<EngineFindings, 'accounts'> => ({- engines: { claude: fakeStatus('0.0.0'), codex: fakeStatus('0.0.0'), opencode: { ...fakeStatus('0.0.0'), route: 'providers', account: 'OpenAI, OpenCode · 3 modelos' }, pi: { installed: false, loggedIn: false }, gemini: { installed: false, loggedIn: false }, cursor: { installed: false, loggedIn: false }, grok: { installed: false, loggedIn: false } },- listed: { opencode: ['openai/gpt-5.5', 'opencode/big-pickle', 'opencode-go/qwen3.8-max'] },+ engines: { claude: fakeOne('claude', fakeStatus('0.0.0')), codex: fakeOne('codex', fakeStatus('0.0.0')), opencode: fakeOne('opencode', { ...fakeStatus('0.0.0'), route: 'providers', account: 'OpenAI, OpenCode · 3 modelos' }), pi: fakeBrokenPi ? { ...fakeStatus('0.0.0'), route: 'providers', account: 'Anthropic · 1 modelo' } : { installed: false, loggedIn: false }, gemini: { installed: false, loggedIn: false }, cursor: { installed: false, loggedIn: false }, grok: { installed: false, loggedIn: false } },+ listed: { opencode: ['openai/gpt-5.5', 'opencode/big-pickle', 'opencode-go/qwen3.8-max'], ...(fakeBrokenPi ? { pi: ['anthropic/claude-haiku-4-5'] } : {}) },codexCatalog: []})// The harnesses' last check, kept in the data folder: the window opens on it while the next runs.@@ -171,9 +183,49 @@ function watchEngine(engine: EngineId, done: (s: EngineStatus) => boolean): voidwatching.unref()}+// Codex and Claude Code set up from the introduction, with no terminal (engine-setup.ts).+const engineSetup = new EngineSetup({+ dir: join(dataDir, 'engines'),+ os: osOf(),+ arch: process.arch,+ musl: () => existsSync('/lib/ld-musl-x86_64.so.1') || existsSync('/lib/ld-musl-aarch64.so.1'),+ fetch: (...a) => fetch(...a),+ untar: (archive, into) => new Promise((done, fail) => execFile('tar', ['-xzf', archive, '-C', into], { windowsHide: true }, (e) => (e ? fail(e) : done()))),+ spawn: (bin, args, env) => {+ // stdin stays open and unused: the sign-in finishes on the CLI's own callback, never on a pasted code.+ const p = spawn(bin, args, { env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true })+ const exit = new Promise<number>((done) => {+ p.on('error', () => done(1))+ p.on('exit', (code) => done(code ?? 1))+ })+ return { output: (on) => (p.stdout.on('data', (b: Buffer) => on(b.toString())), p.stderr.on('data', (b: Buffer) => on(b.toString()))), exit, kill: () => p.kill() }+ },+ status: (e) => engines[e],+ recheck: async (e) => (await engineCheck.recheck(e)).engines[e],+ env: (e) => (e === 'codex' ? codexEnv(codexHome) : { ...process.env, DISABLE_AUTOUPDATER: '1' }),+ changed: () => {}+})++// The same steps with the test engines: no network, no CLI; the harness is "signed in" at the end.+function fakeSetup(engine: SetupEngine): SetupState {+ if (fakeSetupState?.state === 'running') return fakeSetupState+ const at = (s: SetupState, ms: number): void => void setTimeout(() => fakeSetupState?.state === 'running' && (fakeSetupState = s), ms)+ fakeSetupState = { engine, step: 'install', state: 'running', progress: 0 }+ at({ engine, step: 'install', state: 'running', progress: 0.45 }, 700)+ at({ engine, step: 'login', state: 'running', url: 'https://example.invalid/login' }, 1500)+ setTimeout(() => {+ if (fakeSetupState?.state !== 'running') return+ fakeSignedIn.add(engine)+ void engineCheck.recheck(engine).then(() => (fakeSetupState = { engine, step: 'login', state: 'done' }))+ }, 3200)+ return fakeSetupState+}+let fakeSetupState: SetupState | null = null+const gateway = new Gateway()// The login shell's PATH comes before any CLI starts: harnesses, connectors and Docker are found on it.-const pathReady = fake ? Promise.resolve() : adoptLoginShellPath().catch((e: unknown) => console.error('[path]', e))+// Then the CLIs the introduction installed, after the person's own.+const pathReady = fake ? Promise.resolve() : adoptLoginShellPath().catch((e: unknown) => console.error('[path]', e)).then(() => void (process.env['PATH'] = engineSetup.withDirs(process.env['PATH'] ?? '')))// The harnesses are checked behind the window (it opens on the last check). What truly needs// them (a reply, the memory, routines, a connection test) waits for this.const enginesReady = pathReady.then(detect)@@ -223,7 +275,7 @@ function moved(id: EngineId): Parameters<typeof relocating>[1] {}const engineImpls: Record<EngineId, Engine> = fake- ? { claude: fakeEngine('claude'), codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }+ ? { claude: fakeEngine('claude'), codex: fakeEngine('codex'), opencode: fakeBrokenOpencode ? { ...fakeEngine('opencode'), async *run() { yield { type: 'error' as const, message: OPENCODE_CRASH } } } : fakeEngine('opencode'), pi: fakeBrokenPi ? { ...fakeEngine('pi'), async *run() { yield { type: 'error' as const, message: PI_EXPIRED } } } : fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }: {claude: relocating(claudeEngine(() => engines.claude.path, async () => quietClaude(userProvider())), moved('claude')),codex: relocating(codexEngine(() => engines.codex.path, codexHome, loginEnv, async () => quietCodex(userCodexProvider())), moved('codex')),@@ -1428,7 +1480,7 @@ const api: Handlers = {}if (error || !text.trim()) return { ok: false, message: error ?? L('O modelo não respondeu.', "The model didn't answer.") }const secs = ((Date.now() - started) / 1000).toLocaleString(locale(), { minimumFractionDigits: 1, maximumFractionDigits: 1 })- return { ok: true, message: L(`${m.id} respondeu em ${secs} s: “${text.trim().slice(0, 60)}”`, `${m.id} answered in ${secs} s: “${text.trim().slice(0, 60)}”`) }+ return { ok: true, seconds: (Date.now() - started) / 1000, message: L(`${m.id} respondeu em ${secs} s: “${text.trim().slice(0, 60)}”`, `${m.id} answered in ${secs} s: “${text.trim().slice(0, 60)}”`) }},voiceStatus: () => dictation(),@@ -1890,6 +1942,19 @@ const api: Handlers = {return openLogin(engine, engine === 'codex' ? { HOME: codexHome, CODEX_HOME: join(codexHome, '.codex') } : {})},+ // The introduction's setup with no terminal: Codex or Claude Code downloaded into the app's folder,+ // then the CLI's own sign-in in the browser. The screen asks how it goes every moment.+ setupEngine: ({ engine }) => {+ if (!SETUP_ENGINES.includes(engine as SetupEngine)) throw new Error(L('Só dá pra preparar o Codex ou o Claude Code daqui.', 'Only Codex or Claude Code can be set up from here.'))+ if (serverMode) throw new Error(L('Num servidor, o login é feito no terminal dele.', "On a server, the sign-in happens in its terminal."))+ return fake ? fakeSetup(engine as SetupEngine) : engineSetup.start(engine as SetupEngine)+ },+ engineSetupState: () => (fake ? fakeSetupState : engineSetup.current),+ cancelEngineSetup: () => {+ if (fake) return void (fakeSetupState = fakeSetupState && { ...fakeSetupState, state: 'cancelled' })+ engineSetup.cancel()+ },+// Another login of Claude Code or Codex: a folder of its own, signed into in a terminal like the first.addAccount: ({ engine, name }) => {if (!ACCOUNT_ENGINES.includes(engine)) throw new Error(L('Só dá pra ter outra conta do Claude Code ou do Codex.', 'Only Claude Code or Codex can have another account.'))diff --git a/src/core/people.ts b/src/core/people.tsindex 6ea0fa2..e2fbd13 100644--- a/src/core/people.ts+++ b/src/core/people.ts@@ -567,6 +567,8 @@ export class People {if (!this.db.useInvite(invite.id, id, now)) return { error: L('Esse convite não vale mais. Peça um novo a quem te convidou.', 'That invite is no longer valid. Ask whoever invited you for a new one.') }const routines = back ? this.db.restorePerson(id, { name: clean, role: invite.role, about: invite.about }) : undefinedif (!back) this.db.addPerson({ id, name: clean, role: invite.role, about: invite.about })+ // Someone new gets their own short welcome first (who invited them, the team, the deal).+ if (!back) this.db.setPrefs(id, { onboarding: { done: true, guest: { by: this.db.person(invite.createdBy)?.name } } })const key = newKey()this.db.addPersonKey(hashSecret(key), id, 'convite')this.db.addActivity({ personId: id, kind: back ? 'person.restored' : 'person.joined', target: id, detail: { role: invite.role, invitedBy: invite.createdBy }, at: now })diff --git a/src/core/policy-people.ts b/src/core/policy-people.tsindex b425dbe..71cb84b 100644--- a/src/core/policy-people.ts+++ b/src/core/policy-people.ts@@ -206,6 +206,9 @@ export const NEEDS: Record<Method, Need> = {loginAccount: 'admin',removeAccount: 'admin',installEngine: 'admin',+ setupEngine: 'admin',+ engineSetupState: 'admin',+ cancelEngineSetup: 'admin',engineModels: 'anyone', // the models a harness lists: an agent's page names its model with themtestEngine: 'admin',setJevKey: 'admin',diff --git a/src/core/seed.ts b/src/core/seed.tsindex 7df3021..5222dc7 100644--- a/src/core/seed.ts+++ b/src/core/seed.ts@@ -10,7 +10,8 @@ export function initializeWorkspace(db: Db, env: NodeJS.ProcessEnv = process.envconst 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 } })+ // A new install starts with the short sidebar; a workspace made from the switcher is someone's who knows the app.+ else db.setSettings({ onboarding: { done: false, ...(env['TUCANO_DEFAULT_WORKSPACE'] !== '0' ? { fresh: true } : {}) } })}// First run: a small team and three channels, so there is someone to talk to.diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsxindex 00d61e9..7bc60e6 100644--- a/src/renderer/src/App.tsx+++ b/src/renderer/src/App.tsx@@ -12,6 +12,9 @@ import { RoutinesPage } from './components/Routines'import { SkillsPage } from './components/Skills'import { ReportPage } from './components/Report'import { Onboarding } from './components/Onboarding'+import { GuestWelcome, guestWelcome, Intro } from './components/Intro'+import { MissionsPage } from './components/Missions'+import { CoachLayer } from './components/Coach'import { Dialogs } from './components/Dialogs'import { AgentCardLayer } from './components/AgentCard'import { WhatsNew } from './components/Update'@@ -24,6 +27,7 @@ export function App(): ReactNode {const theme = useStore((s) => s.settings.theme)const language = useStore((s) => s.settings.language)const intro = useStore((s) => s.ready && s.settings.onboarding?.done === false)+ const guest = useStore(guestWelcome)const mac = useStore((s) => s.platform === 'mac')const navOpen = useStore((s) => s.navOpen)@@ -44,7 +48,7 @@ export function App(): ReactNode {useEffect(() => {const keys = (e: KeyboardEvent): void => {const mod = mac ? e.metaKey && !e.ctrlKey : e.ctrlKey && !e.metaKey- if (!mod || e.altKey || intro) return+ if (!mod || e.altKey || intro || guest) returnconst s = getState()const channels = s.conversations.filter((c) => c.kind === 'channel')if (e.key === 'k') openDialog(s.dialog?.kind === 'search' ? null : { kind: 'search' })@@ -56,7 +60,7 @@ export function App(): ReactNode {}window.addEventListener('keydown', keys)return () => window.removeEventListener('keydown', keys)- }, [intro, mac])+ }, [intro, guest, mac])// The core may stop before the app shows: the banner says so even then.if (!view)@@ -66,10 +70,10 @@ export function App(): ReactNode {</div>)// Dialogs too: connecting a tool from the introduction may open one (on a server).- if (intro)+ if (intro || guest)return (<>- <Onboarding />+ {guest ? <GuestWelcome /> : <Intro />}<Dialogs /><Toasts /><CoreDown />@@ -106,7 +110,9 @@ export function App(): ReactNode {{view.kind === 'skills' && <SkillsPage />}{view.kind === 'report' && <ReportPage />}{view.kind === 'settings' && <SettingsPage />}+ {view.kind === 'missions' && <MissionsPage />}</main>+ <CoachLayer /><AgentCardLayer /><Dialogs /><NameModal />diff --git a/src/renderer/src/components/AutonomyPick.tsx b/src/renderer/src/components/AutonomyPick.tsxnew file mode 100644index 0000000..3e9867b--- /dev/null+++ b/src/renderer/src/components/AutonomyPick.tsx@@ -0,0 +1,37 @@+// "Quanto {nome} faz por conta própria?": the three answers of the introduction (and of the detailed+// form), each one of the autonomy levels, with a line under them saying what still asks. No guardrails+// asks the same confirmation as the agent's page and Settings. The finer rules and the outside-content+// guard stay on the agent's page.+import { L } from '../../../shared/lang'+import { AUTONOMY_CHOICES, autonomyChoiceHint } from '../../../shared/onboarding'+import type { Autonomy } from '../../../shared/actions'+import { useId, type ReactNode } from 'react'+import { confirmNoGuardrails } from './Pages'++export function AutonomyPick({ name, value, guard, onPick, compact }: { name: string; value: Autonomy; guard: boolean; onPick: (level: Autonomy) => void; compact?: boolean }): ReactNode {+ const q = useId()+ const pick = async (level: Autonomy): Promise<void> => {+ if (level === value) return+ if (level === 'free' && !(await confirmNoGuardrails())) return+ onPick(level)+ }+ return (+ <div className={`autonomy-pick ${compact ? 'autonomy-pick--compact' : ''}`}>+ <b id={q} className="autonomy-pick__q">+ {L(`Quanto ${name} faz por conta própria?`, `How much does ${name} do on its own?`)}+ </b>+ <div className="autonomy-pick__rows" role="radiogroup" aria-labelledby={q}>+ {AUTONOMY_CHOICES().map((c) => (+ <button key={c.level} type="button" role="radio" aria-checked={value === c.level} className={`autonomy-pick__row ${value === c.level ? 'is-on' : ''}`} onClick={() => void pick(c.level)}>+ <span className="autonomy-pick__dot" aria-hidden />+ <span className="grow">{c.title}</span>+ {c.recommended && <span className="autonomy-pick__tag">{L('Recomendado', 'Recommended')}</span>}+ </button>+ ))}+ </div>+ <p className="autonomy-pick__hint" aria-live="polite">+ {autonomyChoiceHint(value, guard)}+ </p>+ </div>+ )+}diff --git a/src/renderer/src/components/Coach.tsx b/src/renderer/src/components/Coach.tsxnew file mode 100644index 0000000..6e5d082--- /dev/null+++ b/src/renderer/src/components/Coach.tsx@@ -0,0 +1,214 @@+// The tour, done instead of read: a balloon over the real screen at the moment it matters, once+// each. The first message waiting in #geral; the first time an agent asks for something (only when+// one really does: nothing is staged, and its words follow how far that agent goes on its own); then+// the Tuca, for help; then the missions. The screen+// stays usable under it (the shade lets clicks through), each one closes on its own or with+// "Entendi", and "Pular tour" ends them all.+import { L } from '../../../shared/lang'+import { tourCount, tourOn, type TourMark } from '../../../shared/onboarding'+import { levelOf, policyOf, type Autonomy } from '../../../shared/actions'+import { useEffect, useId, useRef, useState, type CSSProperties, type ReactNode } from 'react'+import { agentById, amOwner, getState, messagesIn, navigate, teamMode, updateSettings, useStore } from '../store'+import { missionFacts } from './Missions'+import { TucaMark } from './ui'++// What an agent asks the person, in the conversation on screen: an approval, its questions, a proposal.+const ASKS = '.main .approval--pending, .main .ask--answer, .main .draft-card:not(.is-settled)'+const ANCHOR: Record<TourMark, string> = { first: '.main .composer', ask: ASKS, tuca: '[data-coach="tuca"]', missions: '[data-coach="missions"]' }++const done = (mark: TourMark): void => {+ const o = getState().settings.onboarding+ if (!o?.tour) return+ updateSettings({ onboarding: { ...o, tour: { ...o.tour, done: [...new Set([...(o.tour.done ?? []), mark])] } } })+}+const skip = (): void => {+ const o = getState().settings.onboarding+ if (o?.tour) updateSettings({ onboarding: { ...o, tour: { ...o.tour, skipped: true } } })+}++type Box = { top: number; left: number; width: number; height: number }++export function CoachLayer(): ReactNode {+ const onboarding = useStore((s) => s.settings.onboarding)+ const channel = onboarding?.channel+ const here = useStore((s) => (s.view?.kind === 'conversation' ? s.view.id : null))+ const sent = useStore((s) => !!channel && messagesIn(s, channel).some((m) => m.author.kind === 'person'))+ const replied = useStore((s) => missionFacts(s).replied)+ const missions = useStore((s) => amOwner(s) && !!s.settings.onboarding?.done && !s.settings.onboarding.checklistHidden)+ const [found, setFound] = useState<{ mark: TourMark; box: Box } | null>(null)+ const showing = useRef<TourMark | null>(null)++ // The first message went: its balloon is done, wherever it was sent from.+ useEffect(() => {+ if (sent && tourOn(onboarding, 'first')) done('first')+ }, [sent, onboarding])++ const on = !!onboarding?.tour && !onboarding.tour.skipped+ // Which balloon is due, and where its target is now: looked up a few times a second while the tour+ // runs (the target moves with the scroll, the window, a reply coming in).+ useEffect(() => {+ if (!on) return setFound(null)+ const look = (): void => {+ const box = (sel: string): Box | null => {+ const el = [...document.querySelectorAll<HTMLElement>(sel)].find((x) => x.offsetParent !== null)+ if (!el) return null+ const r = el.getBoundingClientRect()+ return r.width && r.height ? { top: r.top, left: r.left, width: r.width, height: r.height } : null+ }+ const due = (): { mark: TourMark; box: Box } | null => {+ const ask = box(ANCHOR.ask)+ if (tourOn(onboarding, 'first') && channel && here === channel && !sent) {+ const b = box(ANCHOR.first)+ return b && { mark: 'first', box: b }+ }+ if (tourOn(onboarding, 'ask') && ask) return { mark: 'ask', box: ask }+ if (tourOn(onboarding, 'first')) return null+ if (tourOn(onboarding, 'tuca') && replied && !ask) {+ const b = box(ANCHOR.tuca)+ return b && { mark: 'tuca', box: b }+ }+ if (tourOn(onboarding, 'missions') && missions && !tourOn(onboarding, 'tuca') && !ask) {+ const b = box(ANCHOR.missions)+ return b && { mark: 'missions', box: b }+ }+ return null+ }+ const next = due()+ // The request it pointed at was answered (or went): that one is done.+ if (showing.current === 'ask' && next?.mark !== 'ask' && tourOn(onboarding, 'ask')) done('ask')+ showing.current = next?.mark ?? null+ setFound((cur) => (JSON.stringify(cur) === JSON.stringify(next) ? cur : next))+ }+ look()+ const t = setInterval(look, 400)+ return () => clearInterval(t)+ }, [on, onboarding, channel, here, sent, replied, missions])++ if (!found) return null+ return <Balloon mark={found.mark} box={found.box} missions={missions} />+}++// The first request's balloon, true at every level: it shows only when something really asks, and says+// what asks at the level the agent is on (src/shared/actions.ts), never that everything does.+export const askTitle = (name: string | undefined): string => (name ? L(`Quando ${name} precisar de você, pede aqui.`, `When ${name} needs you, it asks here.`) : L('Quando um agente precisar de você, pede aqui.', 'When an agent needs you, it asks here.'))+export const askBody = (level: Autonomy, guard = true): string =>+ ({+ careful: L('Antes de mudar qualquer coisa, pede o seu ok: aprove, recuse ou responda.', 'Before changing anything, it asks for your ok: approve, refuse or answer.'),+ normal: L('Antes de enviar, apagar, publicar ou pagar, pede o seu ok: aprove, recuse ou responda.', 'Before sending, deleting, publishing or paying, it asks for your ok: approve, refuse or answer.'),+ free: guard+ ? L('Sem travas, só pede o que é de alto risco ou o que vai pra fora depois de ler algo de fora. Perguntas também chegam aqui.', 'With no guardrails, it asks only for what’s high risk or what goes out after reading something from outside. Questions land here too.')+ : L('Sem travas, só pede o que é de alto risco. Perguntas também chegam aqui.', 'With no guardrails, it asks only for what’s high risk. Questions land here too.')+ })[level]++const WIDTH: Record<TourMark, number> = { first: 440, ask: 370, tuca: 360, missions: 360 }++// Where the balloon goes: above the message field, else beside its target (right first), kept on screen.+function place(mark: TourMark, b: Box, height: number): { style: CSSProperties; arrow: CSSProperties } {+ const w = Math.min(WIDTH[mark], window.innerWidth - 32)+ const clamp = (v: number, lo: number, hi: number): number => Math.max(lo, Math.min(hi, v))+ if (mark === 'first') {+ const left = clamp(b.left + b.width - w - 30, 16, window.innerWidth - w - 16)+ const top = Math.max(16, b.top - height - 22)+ return { style: { left, top, width: w }, arrow: { left: clamp(b.left + b.width - 70 - left, 24, w - 40), bottom: -9 } }+ }+ const right = b.left + b.width + 22+ const side = right + w <= window.innerWidth - 16 ? right : Math.max(16, b.left - w - 22)+ const top = clamp(b.top + b.height / 2 - height / 2, 16, window.innerHeight - height - 16)+ const arrowTop = clamp(b.top + b.height / 2 - top - 9, 18, height - 30)+ return { style: { left: side, top, width: w }, arrow: side >= right ? { left: -9, top: arrowTop } : { right: -9, top: arrowTop } }+}++function Balloon({ mark, box, missions }: { mark: TourMark; box: Box; missions: boolean }): ReactNode {+ const title = useId()+ const card = useRef<HTMLDivElement>(null)+ const [height, setHeight] = useState(180)+ const onboarding = useStore((s) => s.settings.onboarding)+ const fresh = !!onboarding?.fresh && !onboarding.showAll+ const forYou = useStore((s) => (teamMode(s) ? L('Pra você', 'For you') : L('Aprovações', 'Approvals')))+ // The agent the first message calls: the one in the introduction's channel.+ const agent = useStore((s) => {+ const c = s.conversations.find((x) => x.id === s.settings.onboarding?.channel)+ const a = c?.members.map((id) => agentById(s, id)).find(Boolean)+ return a ? { name: a.name, handle: a.handle, level: levelOf(policyOf(a, s.settings)), guard: policyOf(a, s.settings).guard !== false } : null+ })+ useEffect(() => {+ if (card.current) setHeight(card.current.offsetHeight)+ })+ // Esc closes the balloon, unless it's meant for a field (a menu, a recording).+ useEffect(() => {+ const keys = (e: KeyboardEvent): void => {+ if (e.key !== 'Escape' || e.defaultPrevented) return+ const t = e.target as HTMLElement | null+ if (t && t !== document.body && !card.current?.contains(t)) return+ done(mark)+ }+ window.addEventListener('keydown', keys)+ return () => window.removeEventListener('keydown', keys)+ }, [mark])++ const { style, arrow } = place(mark, box, height)+ const count = tourCount(onboarding, missions)+ const kicker = mark === 'first' ? L('ÚLTIMO PASSO', 'LAST STEP') : L(`TOUR · ${count.at} DE ${count.of}`, `TOUR · ${count.at} OF ${count.of}`)+ const text: Record<TourMark, { title: string; body: ReactNode; foot?: ReactNode }> = {+ first: {+ title: agent ? L(`Sua primeira mensagem pra ${agent.name}.`, `Your first message to ${agent.name}.`) : L('Sua primeira mensagem.', 'Your first message.'),+ body: (+ <>+ {L('É como um chat: o ', 'It’s like a chat: ')}+ <b>@{agent?.handle ?? L('agente', 'agent')}</b>+ {L(' chama quem você quer. Mude o texto se quiser, e aperte enviar.', ' calls who you want. Change the text if you like, and press send.')}+ </>+ ),+ foot: (+ <button className="coach__ok coach__ok--quiet" onClick={() => done('first')}>+ {L('Entendi', 'Got it')}+ </button>+ )+ },+ ask: {+ title: askTitle(agent?.name),+ body: (+ <>+ {askBody(agent?.level ?? 'normal', agent?.guard ?? true)} {L('O que esperar por você também aparece em ', 'Whatever waits for you also shows up in ')}+ <b>{forYou}</b>.+ </>+ ),+ foot: <span className="coach__hint">{L('Escolha uma resposta pra seguir', 'Pick an answer to go on')}</span>+ },+ tuca: {+ title: L('Travou? Chama o Tuca.', 'Stuck? Call Tuca.'),+ body: L('Ele monta outros agentes, muda o que você quiser e explica o app. Fica aqui, no topo da barra.', 'He builds more agents, changes whatever you want and explains the app. He’s right here, at the top of the sidebar.')+ },+ missions: {+ title: L('Suas missões.', 'Your missions.'),+ body: fresh ? L('Cada uma te mostra uma parte do Tucano, fazendo. A barra lateral cresce conforme você avança.', 'Each one shows you a part of Tucano by doing it. The sidebar grows as you go.') : L('Cada uma te mostra uma parte do Tucano e se marca sozinha quando você usa.', 'Each one shows you a part of Tucano and checks itself off when you use it.')+ }+ }+ const t = text[mark]+ return (+ <div className="coach" aria-live="polite">+ <div className="coach__hole" style={{ top: box.top - 6, left: box.left - 6, width: box.width + 12, height: box.height + 12 }} />+ <div ref={card} className={`coach__card coach__card--${mark}`} style={style} role="dialog" aria-modal="false" aria-labelledby={title}>+ <span className="coach__kicker">+ {mark === 'first' && <TucaMark size={34} />}+ {kicker}+ </span>+ <b id={title} className="coach__title">+ {t.title}+ </b>+ <span className="coach__body">{t.body}</span>+ <span className="coach__foot">+ {t.foot ?? (+ <button className="coach__ok" onClick={() => (done(mark), mark === 'missions' && navigate({ kind: 'missions' }))}>+ {mark === 'missions' ? L('Ver as missões', 'See the missions') : L('Entendi', 'Got it')}+ </button>+ )}+ <button className="coach__skip" onClick={skip}>+ {L('Pular tour', 'Skip the tour')}+ </button>+ </span>+ <span className="coach__arrow" style={arrow} aria-hidden />+ </div>+ </div>+ )+}diff --git a/src/renderer/src/components/ConnectorStore.tsx b/src/renderer/src/components/ConnectorStore.tsxindex d3dc65d..b24eea6 100644--- a/src/renderer/src/components/ConnectorStore.tsx+++ b/src/renderer/src/components/ConnectorStore.tsx@@ -40,10 +40,11 @@ type Status = Record<Connector['status'], { label: string; tone: string }>// The connectors added, on top (with their state; a click opens them), then the ones ready to add, by// category, without those already added. The search looks through both.-export function ConnectorGrid({ status, onManage }: { status: Status; onManage: (id: string) => void }): ReactNode {+// `query`: what the search starts with (the introduction opens it on the connector its agent could use).+export function ConnectorGrid({ status, onManage, query: initial = '' }: { status: Status; onManage: (id: string) => void; query?: string }): ReactNode {const connectors = useStore((s) => s.connectors)const users = useStore((s) => s.agents)- const [query, setQuery] = useState('')+ const [query, setQuery] = useState(initial)const [busy, setBusy] = useState<string | null>(null)const [error, setError] = useState<{ id: string; text: string } | null>(null)const [setup, setSetup] = useState<CatalogEntry | null>(null)diff --git a/src/renderer/src/components/Conversation.tsx b/src/renderer/src/components/Conversation.tsxindex 8f4095b..569f472 100644--- a/src/renderer/src/components/Conversation.tsx+++ b/src/renderer/src/components/Conversation.tsx@@ -1581,6 +1581,8 @@ try {for (const [k, text] of Object.entries(kept)) if (typeof text === 'string' && text.trim()) drafts.set(k, { text, images: [] })sessionStorage.removeItem(RELOAD_KEY)} catch {}+// What a conversation's field starts with next time it opens (the introduction leaves the first message there, unsent).+export const setComposerDraft = (key: string, text: string): void => void drafts.set(key, { text, images: [] })const keepForReload = (current?: { key: string; text: string }): void => {const texts: Record<string, string> = {}for (const [k, d] of drafts) if (d.text.trim()) texts[k] = d.text@@ -1599,7 +1601,7 @@ const HOLD_MS = 400 // held at least this long, letting go ends it (push to talk// Click to record, click again to transcribe (or hold and let go). The text goes to the field to be reviewed, never sent:// dictation gets names wrong, and a message sets an agent working.-function useDictation(insert: (text: string) => void, setNote: (note: string) => void, conversationId: string): [DictationState, DictationControls] {+export function useDictation(insert: (text: string) => void, setNote: (note: string) => void, conversationId: string): [DictationState, DictationControls] {const [state, setState] = useState<DictationState>('idle')const rec = useRef<Recording | null>(null)const startedAt = useRef(0)@@ -1745,7 +1747,7 @@ function useDictation(insert: (text: string) => void, setNote: (note: string) =>return [state, { press, release, stop, cancel, startedAt: () => startedAt.current }]}-function VoiceButton({ controls, state }: { controls: DictationControls; state: DictationState }): ReactNode {+export function VoiceButton({ controls, state }: { controls: DictationControls; state: DictationState }): ReactNode {const platform = useStore((s) => s.platform)const hidden = useStore((s) => !!s.settings.voice?.hidden)const status = useVoice()diff --git a/src/renderer/src/components/EngineProblem.tsx b/src/renderer/src/components/EngineProblem.tsxnew file mode 100644index 0000000..403800e--- /dev/null+++ b/src/renderer/src/components/EngineProblem.tsx@@ -0,0 +1,37 @@+// A harness's failure on screen, the same everywhere (the introduction's list, Settings › Modelos):+// one plain line (src/shared/engine-errors.ts), "Entrar de novo" when it's the login and there's a+// way in, "Tentar de novo", and the raw text only under "Ver detalhes", in a small scrolling box.+import { L } from '../../../shared/lang'+import { explainEngineError } from '../../../shared/engine-errors'+import type { EngineId } from '../../../shared/types'+import type { ReactNode } from 'react'++export function EngineProblem({ engine, message, onSignIn, onRetry, look = 'app' }: { engine: EngineId; message: string; onSignIn?: () => void; onRetry?: () => void; look?: 'intro' | 'app' }): ReactNode {+ const p = explainEngineError(engine, message)+ const btn = look === 'intro' ? 'intro-link' : 'btn btn--ghost btn--sm'+ return (+ <div className={`engine-problem engine-problem--${look}`} role="alert">+ <span className="engine-problem__line">{p.line}</span>+ {(p.kind === 'login' && onSignIn) || onRetry || p.details ? (+ <span className="engine-problem__actions">+ {p.kind === 'login' && onSignIn && (+ <button className={btn} onClick={onSignIn}>+ {L('Entrar de novo', 'Sign in again')}+ </button>+ )}+ {onRetry && (+ <button className={btn} onClick={onRetry}>+ {L('Tentar de novo', 'Try again')}+ </button>+ )}+ {p.details && (+ <details className="engine-problem__more">+ <summary>{L('Ver detalhes', 'See details')}</summary>+ <pre>{p.details}</pre>+ </details>+ )}+ </span>+ ) : null}+ </div>+ )+}diff --git a/src/renderer/src/components/Harness.tsx b/src/renderer/src/components/Harness.tsxindex b700d24..dda33be 100644--- a/src/renderer/src/components/Harness.tsx+++ b/src/renderer/src/components/Harness.tsx@@ -37,6 +37,7 @@ import {type Settings} from '../store'import { Icon } from './ui'+import { EngineProblem } from './EngineProblem'import { Select } from './Select'// The harnesses agents may run on now: picked (or all, if never picked), ready, and runnable.@@ -312,11 +313,14 @@ function HarnessRow({ engine, st, picked, toggle }: { engine: EngineId; st: Engi{L('Mandar teste', 'Send a test')}</button></div>- {result && (- <p className={`note ${result.ok ? 'note--ok' : 'note--error'}`}>- <Icon name={result.ok ? 'check' : 'x'} size={14} /> {result.ok ? `${L('Funcionando.', 'Working.')} ${result.message}` : result.message}- </p>- )}+ {result &&+ (result.ok ? (+ <p className="note note--ok">+ <Icon name="check" size={14} /> {`${L('Funcionando.', 'Working.')} ${result.message}`}+ </p>+ ) : (+ <EngineProblem engine={engine} message={result.message} onSignIn={() => void loginEngine(engine).then((r) => setManual(r.opened ? null : r.command))} onRetry={() => void test()} />+ ))}</div>)}</div>diff --git a/src/renderer/src/components/Intro.tsx b/src/renderer/src/components/Intro.tsxnew file mode 100644index 0000000..37d0a96--- /dev/null+++ b/src/renderer/src/components/Intro.tsx@@ -0,0 +1,1377 @@+// The first run: one guided path that someone who never used an AI app can follow, and that+// someone who has Claude Code or Codex ready crosses in three clicks. Hello, then the AI (found+// already set up, or set up here with no terminal: the official CLI and its own sign-in in the+// browser), then the Tuca asks what to hand off and the first agent is born from the answer. It+// lands in #geral with the first message written and not sent (Coach.tsx points at it). Someone+// invited to a team gets their own short welcome instead (GuestWelcome).+import { L } from '../../../shared/lang'+import { CATALOG, entryOf } from '../../../shared/connector-catalog'+import { agentModel, aiState, autonomyChosen, isFastModel, backgroundModel, FIRST_AUTONOMY, GOALS, goalForText, needsSignIn, storedAutonomy, type Goal } from '../../../shared/onboarding'+import { useCallback, useEffect, useRef, useState, type CSSProperties, type ReactNode } from 'react'+import {+ ENGINES,+ ENGINE_IDS,+ cancelEngineSetup,+ engineModels,+ engineSetupState,+ ensureTuca,+ getState,+ harnessMcps,+ importHarnessMcp,+ isTeam,+ linkSkill,+ localSkills,+ loginEngine,+ installEngine,+ modelInfo,+ navigate,+ newAgentDraft,+ newChannel,+ openExternal,+ refreshEngines,+ saveAgent,+ setMyName,+ setupEngine,+ slug,+ testEngine,+ updateSettings,+ useStore,+ messagesIn,+ windowless,+ amOwner,+ initials,+ type Agent,+ type AgentColor,+ type AgentDraft,+ type EngineId,+ type HarnessMcp,+ type LocalSkill,+ type SetupEngine,+ type SetupState+} from '../store'+import { HarnessList } from './Harness'+import { STATUS, Toggle } from './Pages'+import { Select } from './Select'+import { useEngineModels } from './Harness'+import { Splash } from './Splash'+import { Composer, MessageList, setComposerDraft, useDictation, VoiceButton } from './Conversation'+import { draftAgent, UseDraft } from './Tuca'+import { Onboarding } from './Onboarding'+import { CatalogLogo, ConnectorGrid } from './ConnectorStore'+import { Modal } from './Modal'+import { AutonomyPick } from './AutonomyPick'+import { EngineProblem } from './EngineProblem'+import { explainEngineError } from '../../../shared/engine-errors'+import { ENGINE_LOGOS } from '../engine-logos'+import { AgentAvatar, Icon, MeAvatar, TucaMark } from './ui'++// The opening plays once per run of the app, not again when the language changes.+let opened = false++type Step = 'welcome' | 'ai' | 'goal' | 'agent' | 'adjust' | 'manual'+const DOT: Record<Step, number> = { welcome: 0, ai: 1, goal: 2, agent: 3, adjust: 3, manual: 3 }++export function unique(base: string, taken: string[]): string {+ if (!taken.includes(base)) return base+ for (let i = 2; ; i++) if (!taken.includes(`${base}-${i}`)) return `${base}-${i}`+}++// A goal as an agent draft: who it is, what it knows, the web when the goal needs it, nothing else.+export function agentFromGoal(goal: Goal, base: Agent, modelId: string | undefined): Agent {+ return { ...base, name: goal.name, role: goal.role, color: goal.color, customColor: undefined, instructions: goal.instructions, web: goal.web, browser: false, computer: false, ...(modelId ? { modelId } : {}) }+}++export function Intro(): ReactNode {+ const settings = useStore((s) => s.settings)+ const hasAgents = useStore((s) => s.agents.some(isTeam))+ const [opening, setOpening] = useState(!opened)+ const onOpened = useCallback(() => ((opened = true), setOpening(false)), [])+ const [step, setStep] = useState<Step>('welcome')+ const [name, setName] = useState(settings.workspaceName)+ const [models, setModels] = useState<{ router: string; memory: string } | null>(null)+ const [goal, setGoal] = useState<Goal | null>(null)+ // How far it goes on its own starts on Normal, the recommended answer (kept as "Padrão" while Settings say Normal).+ const [agent, setAgent] = useState<Agent>(() => ({ ...newAgentDraft(), autonomy: storedAutonomy(FIRST_AUTONOMY, settings.autonomy) }))+ const [busy, setBusy] = useState(false)+ const [error, setError] = useState('')+ const [cheer, setCheer] = useState(false)+ const [dir, setDir] = useState<'next' | 'back'>('next')+ const go = (s: Step): void => (setDir(DOT[s] < DOT[step] ? 'back' : 'next'), setStep(s), setError(''))++ const pick = (g: Goal): void => {+ setGoal(g)+ const s = getState().settings+ setAgent((a) => agentFromGoal(g, a, agentModel(s.engines, listedNow) ?? a.modelId))+ go('agent')+ }++ // The first agent joins #geral, the first message waits in the field, and the tour starts there.+ async function call(a: Agent, task: string): Promise<void> {+ if (busy) return+ setBusy(true)+ setError('')+ try {+ const s = getState()+ const handle = unique(slug(a.name).length >= 2 ? slug(a.name) : L('agente', 'agent'), s.agents.map((x) => x.handle))+ const channelId = await newChannel(unique(L('geral', 'general'), s.conversations.filter((c) => c.kind === 'channel').map((c) => c.name)))+ // What's connected starts read-only: writing is the person's to turn on, on the agent's page.+ const grants = Object.fromEntries(s.connectors.map((c) => [c.id, a.grants[c.id] ?? 'read' as const]))+ await saveAgent({ ...a, name: a.name.trim(), role: a.role.trim(), handle, grants }, [channelId])+ if (!matchMedia('(prefers-reduced-motion: reduce)').matches) {+ setCheer(true)+ await new Promise((done) => setTimeout(done, 650))+ }+ setComposerDraft(channelId, `@${handle} ${task.trim()}`)+ const o = getState().settings.onboarding+ updateSettings({+ workspaceName: name.trim() || settings.workspaceName,+ ...(models ? { routerModel: models.router, memoryModel: models.memory } : {}),+ onboarding: { ...o, done: true, channel: channelId, tour: { done: [] } }+ })+ navigate({ kind: 'conversation', id: channelId })+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e))+ setCheer(false)+ } finally {+ setBusy(false)+ }+ }++ const close = (): void => updateSettings({ onboarding: { ...settings.onboarding, done: true } })++ if (opening) return <Splash onDone={onOpened} />+ if (step === 'manual')+ return <Onboarding manual={{ onBack: () => go('goal'), onCreate: (a, task) => call(a, task) }} />++ return (+ <div className="intro">+ <div className="intro__drag" />+ {hasAgents && (+ <button className="intro__close" onClick={close}>+ {L('Fechar', 'Close')}+ </button>+ )}+ <div className="intro__stage" key={step} data-dir={dir}>+ {step === 'welcome' && <Welcome name={name} setName={setName} onNext={() => go('ai')} />}+ {step === 'ai' && <ConnectAi name={name} onBack={() => go('welcome')} onNext={(m) => (setModels(m), go('goal'))} />}+ {step === 'goal' && <AskGoal name={name} onPick={pick} onOwn={(t) => pick(goalForText(t))} onManual={() => go('manual')} onBack={() => go('ai')} />}+ {step === 'agent' && goal && <Born agent={agent} goal={goal} patch={(p) => setAgent((a) => ({ ...a, ...p }))} busy={busy} error={error} onCall={() => void call(agent, goal.task)} onAdjust={() => go('adjust')} onBack={() => go('goal')} />}+ {step === 'adjust' && goal && (+ <Adjust+ agent={agent}+ goal={goal}+ onUse={(d) => {+ // The Tuca's version keeps the answer to how far it goes on its own.+ setAgent((a) => ({ ...draftAgent(d), id: a.id, limit: a.limit, autonomy: a.autonomy }))+ if (d.task) setGoal({ ...goal, task: d.task })+ go('agent')+ }}+ onBack={() => go('agent')}+ />+ )}+ </div>+ {cheer && (+ <div className="onb-cheer" aria-hidden>+ <TucaMark size={96} happy />+ </div>+ )}+ </div>+ )+}++// What the harnesses list (Codex's catalog, OpenCode's providers…), asked once and kept for the run.+let listedNow: Partial<Record<EngineId, string[]>> = {}+function useListed(): Partial<Record<EngineId, string[]>> {+ const engines = useStore((s) => s.settings.engines)+ const [listed, setListed] = useState(listedNow)+ const ready = ENGINE_IDS.filter((e) => e !== 'claude' && engines[e].loggedIn && !engines[e].soon)+ useEffect(() => {+ let live = true+ for (const e of ready.filter((x) => !listedNow[x]))+ void engineModels(e).then(+ (r) => {+ listedNow = { ...listedNow, [e]: r.models }+ if (live) setListed(listedNow)+ },+ () => {}+ )+ return () => {+ live = false+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [ready.join()])+ return listed+}++// ---------- the pieces every screen shares ----------++function Dots({ at }: { at: number }): ReactNode {+ return (+ <span className="intro-dots" role="img" aria-label={L(`Passo ${at + 1} de 5`, `Step ${at + 1} of 5`)}>+ {[0, 1, 2, 3, 4].map((i) => (+ <span key={i} className={i === at ? 'is-now' : i < at ? 'is-done' : ''} />+ ))}+ </span>+ )+}++function Top({ at, onBack, right }: { at: number; onBack?: () => void; right?: ReactNode }): ReactNode {+ return (+ <div className="intro__top">+ <Dots at={at} />+ {right ?? (onBack && (+ <button className="intro-link intro-link--quiet" onClick={onBack}>+ {L('Voltar', 'Back')}+ </button>+ ))}+ </div>+ )+}++function Bubble({ children, strong }: { children: ReactNode; strong?: boolean }): ReactNode {+ return <div className={`intro-bubble ${strong ? 'is-strong' : ''}`}>{children}</div>+}++// The face of an agent as the mockups draw it, without a name to read: decoration.+function Face({ color, size, tilt = 0, style }: { color: AgentColor; size: number; tilt?: number; style?: CSSProperties }): ReactNode {+ return (+ <span className="intro-face" style={{ ...style, transform: `rotate(${tilt}deg)` }} aria-hidden>+ <AgentAvatar agent={{ name: '', color }} size={size} />+ </span>+ )+}++function Check({ size = 22 }: { size?: number }): ReactNode {+ return (+ <svg width={size} height={size} viewBox="0 0 22 22" aria-hidden className="intro-check">+ <circle cx="11" cy="11" r="11" />+ <path d="M6.5 11.5 L9.5 14 L15.5 8" />+ </svg>+ )+}++function Spinner(): ReactNode {+ return (+ <svg width="22" height="22" viewBox="0 0 22 22" aria-hidden className="intro-spin">+ <circle cx="11" cy="11" r="9" />+ </svg>+ )+}++function Pending(): ReactNode {+ return (+ <svg width="22" height="22" viewBox="0 0 22 22" aria-hidden className="intro-pending">+ <circle cx="11" cy="11" r="9.5" />+ </svg>+ )+}++function LangToggle(): ReactNode {+ const language = useStore((s) => s.settings.language)+ return (+ <span className="intro-lang" role="radiogroup" aria-label="Idioma · Language">+ {(['pt', 'en'] as const).map((l, i) => (+ <span key={l}>+ {i > 0 && <span aria-hidden> · </span>}+ <button role="radio" aria-checked={language === l} className={language === l ? 'is-on' : ''} onClick={() => language !== l && updateSettings({ language: l })}>+ {l === 'pt' ? 'Português' : 'English'}+ </button>+ </span>+ ))}+ </span>+ )+}++// ---------- 1. hello ----------++function Welcome({ name, setName, onNext }: { name: string; setName: (v: string) => void; onNext: () => void }): ReactNode {+ const servers = !!window.tucano?.servers+ const [joining, setJoining] = useState(false)+ return (+ <div className="intro__split">+ <div className="intro-art intro-art--peach" aria-hidden>+ <span className="intro-blob" style={{ left: 90, top: 150, width: 380, height: 380 }} />+ <span className="intro-hero">+ <TucaMark size={260} />+ </span>+ <Face color="violet" size={78} tilt={-9} style={{ left: 56, top: 110 }} />+ <Face color="amber" size={66} tilt={8} style={{ right: 70, top: 90 }} />+ <Face color="teal" size={84} tilt={-5} style={{ right: 60, top: 470 }} />+ <span className="intro-chip" style={{ left: 60, top: 520 }}>+ {L('Pesquisei 12 fontes', 'Read 12 sources')} <Icon name="check" size={14} />+ </span>+ <span className="intro-chip intro-chip--dark" style={{ right: 50, top: 610 }}>+ {L('Rascunho do e-mail pronto', 'Email draft ready')}+ </span>+ <span className="intro-chip" style={{ left: 110, top: 640 }}>+ {L('Posso enviar?', 'Can I send it?')} <b>{L('Aprovar', 'Approve')}</b>+ </span>+ </div>+ <section className="intro__main">+ <div className="intro__top">+ <Dots at={0} />+ <LangToggle />+ </div>+ <div className="intro__center">+ <h1 className="intro-h1">+ {L('Seu time de IA,', 'Your AI team,')}+ <br />+ {L('no seu computador.', 'on your computer.')}+ </h1>+ <p className="intro-lead">{L('Agentes que pesquisam, escrevem e organizam por você. Você conversa com eles como num chat, e nada importante acontece sem o seu ok.', 'Agents that research, write and organize for you. You talk to them like in a chat, and nothing important happens without your ok.')}</p>+ <label className="intro-field">+ {L('Como posso te chamar?', 'What should I call you?')}+ <input className="intro-input" autoFocus value={name} placeholder={L('Seu nome', 'Your name')} onChange={(e) => setName(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && name.trim() && onNext()} />+ </label>+ <div className="intro-actions">+ <button className="intro-btn" disabled={!name.trim()} onClick={onNext}>+ {L('Começar', 'Get started')}+ </button>+ {servers && (+ <button className="intro-link" aria-expanded={joining} onClick={() => setJoining(!joining)}>+ {L('Tenho um convite ou um servidor', 'I have an invite or a server')}+ </button>+ )}+ </div>+ {joining && <JoinLink />}+ </div>+ <span className="intro-foot">{L('Conversas, memória e logins ficam no seu computador.', 'Conversations, memory and logins stay on your computer.')}</span>+ </section>+ </div>+ )+}++// A server's connection link pairs this app with it; an invite link opens in the browser, where the+// invited person picks their name (the server keeps who they are there).+function JoinLink(): ReactNode {+ const [link, setLink] = useState('')+ const [note, setNote] = useState('')+ const go = async (): Promise<void> => {+ const v = link.trim()+ setNote('')+ if (/^https?:\/\/\S+[?&]invite=/.test(v)) {+ openExternal(v)+ return setNote(L('Abri o convite no seu navegador. É lá que você entra no time.', 'I opened the invite in your browser. That’s where you join the team.'))+ }+ const r = await window.tucano.servers!.pair(v)+ if (r === 'invalid') setNote(L('Esse link não é um convite nem um link de conexão. Peça de novo a quem te chamou.', 'That link isn’t an invite or a connection link. Ask whoever invited you again.'))+ }+ return (+ <form+ className="intro-join"+ onSubmit={(e) => {+ e.preventDefault()+ if (link.trim()) void go()+ }}+ >+ <label className="sr-only" htmlFor="intro-join">+ {L('O link que te mandaram', 'The link you were sent')}+ </label>+ <input id="intro-join" className="intro-input" autoFocus type="password" autoComplete="off" spellCheck={false} placeholder={L('Cole o link do convite ou do servidor', 'Paste the invite or server link')} value={link} onChange={(e) => (setLink(e.target.value), setNote(''))} />+ <button className="intro-btn intro-btn--sm" type="submit" disabled={!link.trim()}>+ {L('Entrar', 'Join')}+ </button>+ {note && (+ <p className="intro-note" role="status">+ {note}+ </p>+ )}+ </form>+ )+}++// ---------- 2. the AI ----------++// The harness's own mark on its brand color (engine-logos.ts); its initial where there's no mark (Grok).+function EngineMark({ engine, size = 44 }: { engine: EngineId; size?: number }): ReactNode {+ const logo = ENGINE_LOGOS[engine]+ return (+ <span className={`intro-mark ${logo?.hex === '211E1B' || !logo ? 'intro-mark--ink' : ''}`} style={{ width: size, height: size, ...(logo ? { background: `#${logo.hex}` } : { fontSize: 17 }) }} aria-hidden>+ {logo ? (+ <svg viewBox="0 0 24 24" width={Math.round(size * 0.54)} height={Math.round(size * 0.54)} fill="currentColor">+ <path d={logo.path} />+ </svg>+ ) : (+ ENGINES[engine].label[0]+ )}+ </span>+ )+}++// One real reply per harness, asked once per run: the screen says how long it took.+type Tested = { ok: boolean; seconds?: number; message: string }+const tests = new Map<string, Promise<Tested>>()+function useTest(model: string | undefined): [Tested | 'running' | undefined, () => void] {+ const [got, setGot] = useState<{ model: string; r: Tested } | null>(null)+ const [round, setRound] = useState(0)+ useEffect(() => {+ if (!model) return+ if (!tests.has(model)) tests.set(model, testEngine(model).catch((e: unknown) => ({ ok: false, message: e instanceof Error ? e.message : String(e) })))+ let live = true+ void tests.get(model)!.then((r) => live && setGot({ model, r }))+ return () => {+ live = false+ }+ }, [model, round])+ // "Tentar de novo": a new test, after the person fixed what was wrong (signed in again, say).+ const retry = (): void => {+ if (!model) return+ tests.delete(model)+ setGot(null)+ setRound((n) => n + 1)+ }+ if (!model) return [undefined, retry]+ return [got?.model === model ? got.r : 'running', retry]+}++const secs = (s: number): string => s.toLocaleString(L('pt-BR', 'en-US'), { minimumFractionDigits: 1, maximumFractionDigits: 1 })++// The everyday quick model of a harness, for its test reply.+function quickModel(engine: EngineId, listed: Partial<Record<EngineId, string[]>>): string | undefined {+ const s = getState().settings.engines+ const only = Object.fromEntries(ENGINE_IDS.map((e) => [e, e === engine ? s[e] : { installed: false, loggedIn: false }])) as typeof s+ return s[engine].route === 'gateway' ? undefined : backgroundModel(only, listed)+}++// The CLI being set up with no terminal, as the core reports it (asked every moment while it runs).+function useSetup(): [SetupState | null, (e: SetupEngine) => void, () => void] {+ const [state, setState] = useState<SetupState | null>(null)+ const timer = useRef<ReturnType<typeof setInterval> | undefined>(undefined)+ const poll = useCallback(() => {+ clearInterval(timer.current)+ timer.current = setInterval(() => {+ void engineSetupState().then((s) => {+ setState(s)+ if (!s || s.state !== 'running') clearInterval(timer.current)+ if (s && s.state === 'done') refreshEngines()+ })+ }, 700)+ }, [])+ useEffect(() => () => clearInterval(timer.current), [])+ const start = (e: SetupEngine): void => {+ setState({ engine: e, step: 'install', state: 'running' })+ void setupEngine(e).then(+ (s) => (setState(s), poll()),+ (err: unknown) => setState({ engine: e, step: 'install', state: 'error', error: err instanceof Error ? err.message : String(err) })+ )+ }+ const cancel = (): void => {+ cancelEngineSetup()+ clearInterval(timer.current)+ setState(null)+ }+ return [state, start, cancel]+}++function ConnectAi({ name, onBack, onNext }: { name: string; onBack: () => void; onNext: (m: { router: string; memory: string }) => void }): ReactNode {+ const engines = useStore((s) => s.settings.engines)+ const saved = useStore((s) => ({ router: s.settings.routerModel, memory: s.settings.memoryModel }))+ const keep = useStore((s) => s.agents.some(isTeam) || !!s.settings.onboarding?.carried)+ const listed = useListed()+ const [mode, setMode] = useState<'auto' | 'advanced'>(windowless() ? 'advanced' : 'auto')+ const [chosen, setChosen] = useState<SetupEngine | null>(null)+ const [setup, startSetup, cancelSetup] = useSetup()+ const state = aiState(engines)+ // Someone seeing this again keeps their models; a new install gets the quick one picked for it.+ const auto = backgroundModel(engines, listed)+ const [picked, setPicked] = useState<{ router: string; memory: string } | null>(keep ? saved : null)+ const models = picked ?? (auto ? { router: auto, memory: auto } : null)++ useEffect(() => {+ refreshEngines()+ if (state === 'ready') return+ const t = setInterval(refreshEngines, 5000)+ return () => clearInterval(t)+ }, [state])++ const begin = (e: SetupEngine): void => (setChosen(e), startSetup(e))+ const first = name.trim().split(' ')[0] ?? ''++ if (mode === 'advanced') return <Advanced models={models} setModels={setPicked} onBack={windowless() ? onBack : () => setMode('auto')} onNext={() => models && onNext(models)} />++ // Ready, and nothing being set up here: what was found, a click away.+ if (state === 'ready' && !chosen)+ return (+ <div className="intro__split">+ <aside className="intro-side intro-side--teal">+ <TucaHead />+ <Bubble>{L('Opa, você já tem tudo pronto aqui. Achei o que você usa.', 'Oh, you’re all set up already. I found what you use.')}</Bubble>+ <Bubble>{auto ? L('Já escolhi os modelos rápidos pros bastidores. Se quiser mexer, é ali embaixo.', 'I already picked the quick models for behind the scenes. To change them, it’s down there.') : L('Só falta escolher os modelos rápidos pros bastidores, ali embaixo.', 'Just pick the quick models for behind the scenes, down there.')}</Bubble>+ </aside>+ <section className="intro__main">+ <Top at={1} onBack={onBack} />+ <Found engines={engines} listed={listed} models={models} setModels={setPicked} onSignIn={begin} onNext={(m) => onNext(m)} />+ </section>+ </div>+ )++ return (+ <div className="intro__split">+ <aside className="intro-side intro-side--teal">+ <TucaHead />+ {state === 'checking' && !chosen ? (+ <Bubble>{L('Deixa eu ver o que você já tem por aqui…', 'Let me see what you already have here…')}</Bubble>+ ) : (+ <>+ <Bubble>{first ? L(`Oi, ${first}! Seus agentes precisam de uma IA pra pensar.`, `Hi, ${first}! Your agents need an AI to think with.`) : L('Oi! Seus agentes precisam de uma IA pra pensar.', 'Hi! Your agents need an AI to think with.')}</Bubble>+ <Bubble>{L('Eles usam a assinatura que você já tem, sem cobrança extra. Qual você assina?', 'They use the subscription you already have, at no extra cost. Which one do you have?')}</Bubble>+ </>+ )}+ <span className="grow" />+ <p className="intro-side__note">+ <Icon name="lock" size={20} /> {L('O login é feito no site deles. O Tucano nunca vê a sua senha.', 'You sign in on their website. Tucano never sees your password.')}+ </p>+ </aside>+ <section className="intro__main">+ <Top at={1} onBack={onBack} />+ <div className="intro__center intro__center--tight">+ <h1 className="intro-h2">{L('Conectar a IA', 'Connect the AI')}</h1>+ {state === 'checking' && !chosen ? (+ <p className="intro-wait" role="status">+ <Spinner /> {L('Procurando…', 'Looking…')}+ </p>+ ) : (+ <Plans engines={engines} chosen={chosen} setup={setup} begin={begin} cancel={() => (cancelSetup(), setChosen(null))} models={models} listed={listed} onNext={onNext} />+ )}+ <button className="intro-link" onClick={() => setMode('advanced')}>+ {L('Uso chave de API, gateway da empresa ou outro programa', 'I use an API key, a company gateway or another program')}+ </button>+ </div>+ </section>+ </div>+ )+}++function TucaHead(): ReactNode {+ return (+ <div className="intro-tuca">+ <TucaMark size={52} />+ <span>+ <b>Tuca</b>+ <span>{L('te ajuda a começar', 'helps you get started')}</span>+ </span>+ </div>+ )+}++// Nothing set up: ChatGPT or Claude, each set up here; or what to subscribe to.+function Plans(p: {+ engines: ReturnType<typeof getState>['settings']['engines']+ chosen: SetupEngine | null+ setup: SetupState | null+ begin: (e: SetupEngine) => void+ cancel: () => void+ models: { router: string; memory: string } | null+ listed: Partial<Record<EngineId, string[]>>+ onNext: (m: { router: string; memory: string }) => void+}): ReactNode {+ const [none, setNone] = useState(false)+ const card = (e: SetupEngine): ReactNode => {+ const title = e === 'codex' ? 'ChatGPT' : 'Claude'+ const plans = e === 'codex' ? L('Plus, Pro ou Business', 'Plus, Pro or Business') : L('Pro ou Max', 'Pro or Max')+ if (p.chosen === e) return <SetupCard key={e} engine={e} title={title} plans={plans} setup={p.setup} retry={() => p.begin(e)} cancel={p.cancel} models={p.models} listed={p.listed} onNext={p.onNext} />+ return (+ <button key={e} className="intro-card intro-card--pick" disabled={!!p.chosen && p.setup?.state === 'running'} onClick={() => p.begin(e)}>+ <EngineMark engine={e} />+ <span className="intro-card__text">+ <b>{title}</b>+ <span>{plans}</span>+ </span>+ </button>+ )+ }+ const order: SetupEngine[] = p.chosen === 'claude' ? ['claude', 'codex'] : ['codex', 'claude']+ return (+ <>+ {p.chosen && card(p.chosen)}+ <div className="intro-grid2">+ {order.filter((e) => e !== p.chosen).map(card)}+ <button className="intro-card intro-card--quiet" aria-expanded={none} onClick={() => setNone(!none)}>+ <b>{L('Não assino nenhuma', 'I don’t subscribe to any')}</b>+ <span>{L('Te explico qual escolher', 'I’ll explain which to pick')}</span>+ </button>+ </div>+ {none && (+ <div className="intro-panel" role="region" aria-label={L('Qual assinar', 'Which to subscribe to')}>+ <p>{L('Os agentes pensam com a IA de uma assinatura sua. Qualquer uma destas serve, e você paga direto pra empresa, não pro Tucano:', 'The agents think with the AI of a subscription of yours. Any of these works, and you pay the company directly, not Tucano:')}</p>+ <ul>+ <li>+ <b>ChatGPT Plus</b> {L('(ou Pro, Business): da OpenAI. Bom pra quase tudo.', '(or Pro, Business): from OpenAI. Good for almost everything.')}{' '}+ <button className="intro-link" onClick={() => openExternal('https://chatgpt.com/pricing')}>+ {L('Ver os planos', 'See the plans')}+ </button>+ </li>+ <li>+ <b>Claude Pro</b> {L('(ou Max): da Anthropic. Muito bom pra escrever e pesquisar.', '(or Max): from Anthropic. Very good for writing and research.')}{' '}+ <button className="intro-link" onClick={() => openExternal('https://claude.com/pricing')}>+ {L('Ver os planos', 'See the plans')}+ </button>+ </li>+ </ul>+ <p className="intro-muted">{L('O plano grátis de cada uma não serve: ele não inclui o programa que os agentes usam. Depois de assinar, volte aqui e escolha a sua.', 'The free plan of either won’t do: it doesn’t include the program the agents use. Once you subscribe, come back and pick yours.')}</p>+ </div>+ )}+ </>+ )+}++// One being set up: the program, the sign-in, then a real reply.+function SetupCard(p: { engine: SetupEngine; title: string; plans: string; setup: SetupState | null; retry: () => void; cancel: () => void; models: { router: string; memory: string } | null; listed: Partial<Record<EngineId, string[]>>; onNext: (m: { router: string; memory: string }) => void }): ReactNode {+ const st = useStore((s) => s.settings.engines[p.engine])+ const s = p.setup?.engine === p.engine ? p.setup : null+ const signedIn = st.loggedIn || (s?.step === 'login' && s.state === 'done')+ const [test] = useTest(signedIn && st.loggedIn ? quickModel(p.engine, p.listed) : undefined)+ const failed = s?.state === 'error'+ const installDone = st.installed || s?.step === 'login'+ const result = test && test !== 'running' ? test : undefined+ const ok = !!result?.ok+ const pill = failed ? L('Não deu certo', 'Didn’t work') : ok ? L('Conectado', 'Connected') : L('Conectando…', 'Connecting…')+ const label = (state: 'done' | 'now' | 'later' | 'error', text: ReactNode): ReactNode => (+ <li className={`intro-step is-${state}`}>+ {state === 'done' ? <Check /> : state === 'now' ? <Spinner /> : state === 'error' ? <Icon name="x" size={20} /> : <Pending />}+ <span>{text}</span>+ </li>+ )+ const pct = s?.step === 'install' && s.progress ? ` ${Math.round(s.progress * 100)}%` : ''+ return (+ <div className="intro-card intro-card--live" aria-live="polite">+ <div className="intro-card__head">+ <EngineMark engine={p.engine} size={48} />+ <span className="intro-card__text">+ <b>{p.title}</b>+ <span>{p.plans}</span>+ </span>+ <span className={`intro-pill ${ok ? 'is-ok' : failed ? 'is-bad' : ''}`}>{pill}</span>+ </div>+ <ol className="intro-steps">+ {label(installDone ? 'done' : failed && s?.step === 'install' ? 'error' : 'now', installDone ? L('Preparei tudo no seu computador', 'I set everything up on your computer') : L(`Preparando tudo no seu computador…${pct}`, `Setting everything up on your computer…${pct}`))}+ {label(+ signedIn ? 'done' : failed && s?.step === 'login' ? 'error' : installDone ? 'now' : 'later',+ signedIn ? (+ L('Você entrou na sua conta', 'You’re signed in')+ ) : installDone ? (+ <>+ <b>{L('Abri o login no seu navegador.', 'I opened the sign-in in your browser.')}</b> {L('Entre com a sua conta e volte.', 'Sign in with your account and come back.')}+ {s?.url && (+ <>+ {' '}+ <button className="intro-link" onClick={() => openExternal(s.url!)}>+ {L('Abrir de novo', 'Open it again')}+ </button>+ </>+ )}+ </>+ ) : (+ L('Abrir o login no seu navegador', 'Open the sign-in in your browser')+ )+ )}+ {label(+ ok ? 'done' : result ? 'error' : signedIn ? 'now' : 'later',+ result?.ok ? L(`Respondeu em ${secs(result.seconds ?? 0)} s. Tudo certo.`, `Answered in ${secs(result.seconds ?? 0)} s. All set.`) : result ? explainEngineError(p.engine, result.message).line : L('Testar com uma resposta de verdade', 'Test with a real reply')+ )}+ </ol>+ {failed && (+ <div className="intro-fail" role="alert">+ {s?.error && <EngineProblem look="intro" engine={p.engine} message={s.error} />}+ <div className="intro-actions">+ <button className="intro-btn intro-btn--sm" onClick={p.retry}>+ {L('Tentar de novo', 'Try again')}+ </button>+ <Terminal engine={p.engine} installed={st.installed} />+ </div>+ </div>+ )}+ {ok && p.models ? (+ <div className="intro-actions">+ <button className="intro-btn" autoFocus onClick={() => p.onNext(p.models!)}>+ {L('Continuar', 'Continue')}+ </button>+ </div>+ ) : (+ !failed && (+ <button className="intro-link intro-link--quiet" onClick={p.cancel}>+ {L('Cancelar', 'Cancel')}+ </button>+ )+ )}+ </div>+ )+}++// Where the setup can't finish on its own: the CLI's own installer or sign-in in a terminal, as before.+function Terminal({ engine, installed }: { engine: SetupEngine; installed: boolean }): ReactNode {+ const [cmd, setCmd] = useState('')+ const open = (): void => void (installed ? loginEngine(engine) : installEngine(engine)).then((r) => setCmd(r.opened ? '' : r.command))+ return (+ <>+ <button className="intro-link" onClick={open}>+ {L('Fazer pelo terminal', 'Do it in a terminal')}+ </button>+ {cmd && (+ <p className="intro-note">+ {L('Cole isto num terminal:', 'Paste this in a terminal:')} <code>{cmd}</code>+ </p>+ )}+ </>+ )+}++// Already set up: what was found, tested; what can come along from Claude Code; the models behind the scenes.+function Found(p: {+ engines: ReturnType<typeof getState>['settings']['engines']+ listed: Partial<Record<EngineId, string[]>>+ models: { router: string; memory: string } | null+ setModels: (m: { router: string; memory: string }) => void+ onSignIn: (e: SetupEngine) => void+ onNext: (m: { router: string; memory: string }) => void+}): ReactNode {+ const ready = ENGINE_IDS.filter((e) => p.engines[e].loggedIn && !p.engines[e].soon && !p.engines[e].off)+ const signIn = needsSignIn(p.engines).filter((e) => !ready.includes(e))+ const [mcps, setMcps] = useState<HarnessMcp[]>([])+ const [skills, setSkills] = useState<LocalSkill[]>([])+ const [bring, setBring] = useState({ mcps: true, skills: true })+ const [change, setChange] = useState(!p.models)+ const [busy, setBusy] = useState(false)+ // How each one's test went: one that failed doesn't hold the others up.+ const [results, setResults] = useState<Partial<Record<EngineId, boolean>>>({})+ const onResult = useCallback((e: EngineId, ok: boolean | undefined) => setResults((r) => (r[e] === ok ? r : { ...r, [e]: ok })), [])+ const working = ready.filter((e) => results[e] === true)+ const failing = ready.filter((e) => results[e] === false)+ useEffect(() => {+ void harnessMcps().then((f) => setMcps(f.filter((m) => !m.added)), () => {})+ void localSkills().then(setSkills, () => {})+ }, [])+ const fromClaude = mcps.every((m) => m.harnesses.includes('claude')) && skills.every((k) => k.origin === 'Claude Code')+ const label = (v: string): string => (v === 'jev' ? 'Jev' : (modelInfo(v)?.label ?? v))++ async function next(): Promise<void> {+ if (!p.models) return+ setBusy(true)+ // What comes along, in the background of the next screen: none of it is needed to go on.+ if (bring.mcps) for (const m of mcps) void importHarnessMcp(m.key).catch(() => {})+ if (bring.skills) for (const k of skills) void linkSkill(k.source).catch(() => {})+ p.onNext(p.models)+ }++ return (+ <div className="intro__center intro__center--tight intro__center--found">+ <h1 className="intro-h2">{foundTitle(working.length, ready.length - working.length - failing.length)}</h1>+ <div className="intro-card intro-card--list intro-found">+ {ready.map((e) => (+ <FoundRow key={e} engine={e} account={p.engines[e].account} gateway={p.engines[e].route === 'gateway'} listed={p.listed} onResult={onResult} onSignIn={() => (e === 'claude' || e === 'codex' ? p.onSignIn(e) : void loginEngine(e))} />+ ))}+ {signIn.map((e) => (+ <div key={e} className="intro-row">+ <EngineMark engine={e} />+ <span className="intro-card__text">+ <b>{ENGINES[e].label}</b>+ <span>{e === 'codex' ? L('Instalado. Falta entrar uma vez, pro Tucano.', 'Installed. Needs one sign-in, for Tucano.') : L('Instalado. Falta entrar.', 'Installed. Not signed in.')}</span>+ </span>+ <button className="intro-btn intro-btn--sm intro-btn--light" onClick={() => p.onSignIn(e as SetupEngine)}>+ {L('Entrar', 'Sign in')}+ </button>+ </div>+ ))}+ </div>+ {(mcps.length > 0 || skills.length > 0 || p.models || change) && (+ <div className="intro-panel intro-panel--tight">+ {(mcps.length > 0 || skills.length > 0) && <b className="intro-panel__title">{L('Também achei', 'I also found')}</b>}+ {mcps.length > 0 && (+ <BringRow+ from={fromClaude ? 'claude' : undefined}+ icon="plug"+ on={bring.mcps}+ onChange={(v) => setBring({ ...bring, mcps: v })}+ title={+ fromClaude+ ? mcps.length === 1 ? L('Trazer 1 ferramenta do Claude Code', 'Bring 1 tool from Claude Code') : L(`Trazer ${mcps.length} ferramentas do Claude Code`, `Bring ${mcps.length} tools from Claude Code`)+ : mcps.length === 1 ? L('Trazer 1 ferramenta', 'Bring 1 tool') : L(`Trazer ${mcps.length} ferramentas`, `Bring ${mcps.length} tools`)+ }+ names={mcps.map((m) => m.name)}+ />+ )}+ {skills.length > 0 && (+ <BringRow+ from={fromClaude ? 'claude' : undefined}+ icon="spark"+ on={bring.skills}+ onChange={(v) => setBring({ ...bring, skills: v })}+ title={skills.length === 1 ? L('Trazer 1 skill', 'Bring 1 skill') : L(`Trazer ${skills.length} skills`, `Bring ${skills.length} skills`)}+ names={skills.map((k) => k.name)}+ />+ )}+ {change ? (+ <BackgroundPickers models={p.models} setModels={p.setModels} />+ ) : (+ p.models && (+ <span className="intro-muted">+ {p.models.router === p.models.memory+ ? L(`Modelos dos bastidores: ${label(p.models.router)} pra escolher quem responde e pra memória.`, `Behind the scenes: ${label(p.models.router)} picks who replies and keeps the memory.`)+ : L(`Modelos dos bastidores: ${label(p.models.router)} pra escolher quem responde, ${label(p.models.memory)} pra memória.`, `Behind the scenes: ${label(p.models.router)} picks who replies, ${label(p.models.memory)} keeps the memory.`)}{' '}+ <button className="intro-link" onClick={() => setChange(true)}>+ {L('Trocar', 'Change')}+ </button>+ </span>+ )+ )}+ </div>+ )}+ <div className="intro-actions">+ <button className="intro-btn" disabled={!p.models || busy} onClick={() => void next()}>+ {continueLabel(failing.length > 0 ? working : [])}+ </button>+ <span className={`intro-muted ${failing.length && working.length ? 'intro-actions__note' : ''}`}>+ {failing.length && working.length+ ? leftOut(failing)+ : L('Clique 2 de 3', 'Click 2 of 3')}+ </span>+ </div>+ </div>+ )+}++// The title counts only what answered; while tests still run, it says so instead of a number that may drop.+export function foundTitle(working: number, testing: number): string {+ if (testing > 0) return L('Testando o que achei…', 'Testing what I found…')+ if (working === 0) return L('Nenhum respondeu ao teste', 'None of them answered the test')+ return working === 1 ? L('Achei 1 pronto pra usar', 'Found 1 ready to use') : L(`Achei ${working} prontos pra usar`, `Found ${working} ready to use`)+}++// With one that failed: who goes on, by name when it's one, by count when several (the rows name them).+export function continueLabel(working: EngineId[]): string {+ if (working.length === 1) return L(`Continuar com ${ENGINES[working[0]!].label}`, `Continue with ${ENGINES[working[0]!].label}`)+ if (working.length > 1) return L(`Continuar com os ${working.length}`, `Continue with these ${working.length}`)+ return L('Continuar', 'Continue')+}++// Who stays out, by name: "Pi fica de fora…", "OpenCode e Pi ficam de fora…".+export function leftOut(failing: EngineId[]): string {+ const names = failing.map((e) => ENGINES[e].label)+ const who = names.length > 1 ? `${names.slice(0, -1).join(', ')} ${L('e', 'and')} ${names.at(-1)}` : (names[0] ?? '')+ return names.length > 1 ? L(`${who} ficam de fora por agora; dá pra arrumar em Configurações.`, `${who} stay out for now; you can fix them in Settings.`) : L(`${who} fica de fora por agora; dá pra arrumar em Configurações.`, `${who} stays out for now; you can fix it in Settings.`)+}++const list = (names: string[]): string => (names.length > 4 ? `${names.slice(0, 4).join(', ')}${L(` e mais ${names.length - 4}`, ` and ${names.length - 4} more`)}` : names.join(', '))++function FoundRow({ engine, account, gateway, listed, onResult, onSignIn }: { engine: EngineId; account?: string; gateway: boolean; listed: Partial<Record<EngineId, string[]>>; onResult: (e: EngineId, ok: boolean | undefined) => void; onSignIn: () => void }): ReactNode {+ const [test, retry] = useTest(quickModel(engine, listed))+ const done = test && test !== 'running'+ const failed = !!done && !test.ok+ // A gateway names its own models, so there's nothing to test here: it counts as found.+ useEffect(() => onResult(engine, gateway ? true : done ? test.ok : undefined), [engine, gateway, done, test, onResult])+ return (+ <div className={`intro-row ${failed ? 'is-failed' : ''}`}>+ <EngineMark engine={engine} />+ <span className="intro-card__text">+ <b>{ENGINES[engine].label}</b>+ {/* Failed: the problem's line takes the account's place (it names the provider when it can). */}+ {failed ? (+ <EngineProblem look="intro" engine={engine} message={test.message} onSignIn={onSignIn} onRetry={retry} />+ ) : (+ <span>+ {account ?? L('Pronto', 'Ready')}+ {done && test.ok && test.seconds !== undefined && L(` · respondeu em ${secs(test.seconds)} s`, ` · answered in ${secs(test.seconds)} s`)}+ </span>+ )}+ </span>+ {gateway ? (+ <span role="img" aria-label={L('Pronto', 'Ready')}>+ <Check size={26} />+ </span>+ ) : !test || test === 'running' ? (+ <span role="img" aria-label={L('Testando', 'Testing')}>+ <Spinner />+ </span>+ ) : test.ok ? (+ <span role="img" aria-label={L('Pronto', 'Ready')}>+ <Check size={26} />+ </span>+ ) : (+ <Icon name="x" size={20} />+ )}+ </div>+ )+}++// Something found in the person's programs, to bring along: a switch, and the names under "ver quais".+function BringRow({ from, icon, on, onChange, title, names }: { from?: EngineId; icon: 'plug' | 'spark'; on: boolean; onChange: (v: boolean) => void; title: string; names: string[] }): ReactNode {+ const [open, setOpen] = useState(false)+ return (+ <div className={`intro-bring ${on ? '' : 'is-off'}`}>+ {from ? (+ <EngineMark engine={from} size={28} />+ ) : (+ <span className="intro-bring__dot" aria-hidden>+ <Icon name={icon} size={15} />+ </span>+ )}+ <span className="intro-bring__text">+ <span>+ {title}{' '}+ <button className="intro-link intro-bring__more" aria-expanded={open} onClick={() => setOpen(!open)}>+ {open ? L('esconder', 'hide') : names.length === 1 ? L('ver qual', 'see which') : L('ver quais', 'see which')}+ </button>+ </span>+ {open && <span className="intro-bring__names">{names.join(', ')}</span>}+ </span>+ <Toggle on={on} onChange={onChange} />+ </div>+ )+}++// The two small jobs behind the scenes, as two cards: the harness's mark, the model and how quick it is.+// A click opens the app's own menu, every ready harness's models grouped under its name.+function BackgroundPickers({ models, setModels }: { models: { router: string; memory: string } | null; setModels: (m: { router: string; memory: string }) => void }): ReactNode {+ const m = models ?? { router: '', memory: '' }+ const groups = useModelGroups()+ return (+ <div className="intro-jobs">+ <JobCard title={L('Escolhe quem responde', 'Picks who replies')} value={m.router} groups={groups} onChange={(v) => setModels({ ...m, router: v })} />+ <JobCard title={L('Cuida da memória', 'Keeps the memory')} value={m.memory} groups={groups} onChange={(v) => setModels({ ...m, memory: v })} />+ <span className="intro-muted intro-jobs__hint">{L('Quem responde decide, num canal, qual agente fala; a memória resume conversas longas. Um modelo rápido basta. Dá pra trocar depois em Configurações.', 'Who replies decides which agent speaks in a channel; the memory sums up long talks. A quick model is enough. You can change them later in Settings.')}</span>+ </div>+ )+}++// Every ready harness's models, by harness, for one menu (a hook per harness, in a fixed order).+function useModelGroups(): Record<string, Record<string, string>> {+ const engines = useStore((s) => s.settings.engines)+ // eslint-disable-next-line react-hooks/rules-of-hooks -- ENGINE_IDS is fixed, so the hooks keep their order+ const lists = ENGINE_IDS.map((e) => [e, useEngineModels(engines[e].loggedIn && !engines[e].soon && !engines[e].off ? e : undefined)] as const)+ const groups: Record<string, Record<string, string>> = {}+ for (const [e, l] of lists) {+ if (!l.options.length) continue+ groups[ENGINES[e].label] = Object.fromEntries(l.options.map((o) => [o.value, o.hint ? `${o.label} · ${o.hint}` : o.label]))+ }+ return groups+}++function JobCard({ title, value, groups, onChange }: { title: string; value: string; groups: Record<string, Record<string, string>>; onChange: (v: string) => void }): ReactNode {+ const info = modelInfo(value)+ const name = info?.label ?? (value.includes(':') ? value.slice(value.indexOf(':') + 1) : value)+ return (+ <div className="intro-job">+ {info ? <EngineMark engine={info.engine} size={36} /> : <span className="intro-bring__dot" aria-hidden />}+ <span className="intro-job__text">+ <span className="intro-job__title">{title}</span>+ <span className="intro-job__model">+ <b>{value ? name : L('Escolher', 'Choose')}</b>+ {value && <span className={`intro-job__tag ${isFastModel(value) ? 'is-fast' : ''}`}>{isFastModel(value) ? L('rápido', 'fast') : L('forte', 'strong')}</span>}+ </span>+ </span>+ <Icon name="caret" size={14} />+ {/* The whole card is the menu's trigger: the app's Select, laid over it. */}+ <Select className="intro-job__select" aria-label={title} value={value || null} groups={groups} searchable onChange={(v) => v && onChange(v)} />+ </div>+ )+}++// API keys, a company's gateway, OpenCode, Pi and the rest: the harnesses as they're set up, by hand.+function Advanced({ models, setModels, onBack, onNext }: { models: { router: string; memory: string } | null; setModels: (m: { router: string; memory: string }) => void; onBack: () => void; onNext: () => void }): ReactNode {+ const engines = useStore((s) => s.settings.engines)+ const ok = (v: string | undefined): boolean => !!v && (v === 'jev' || !!modelInfo(v)?.id)+ const ready = aiState(engines) === 'ready'+ return (+ <div className="intro__split">+ <aside className="intro-side intro-side--teal">+ <TucaHead />+ <Bubble>{L('Sem problema. O Tucano usa o Claude Code, o Codex, o OpenCode e outros do jeito que você configurou: no plano, no gateway da empresa ou com os seus provedores.', 'No problem. Tucano uses Claude Code, Codex, OpenCode and others the way you set them up: on a plan, your company’s gateway or your providers.')}</Bubble>+ <Bubble>{L('Ele só lê essa configuração. Nunca vê nem guarda as suas senhas e chaves.', 'It only reads that setup. It never sees or stores your passwords and keys.')}</Bubble>+ </aside>+ <section className="intro__main intro__main--scroll">+ <Top at={1} onBack={onBack} />+ <div className="intro__center intro__center--tight intro__center--top">+ <h1 className="intro-h2">{L('Outros jeitos de conectar', 'Other ways to connect')}</h1>+ <div className="intro-harnesses">+ <HarnessList />+ </div>+ <div className="intro-panel">+ <BackgroundPickers models={models} setModels={setModels} />+ </div>+ <div className="intro-actions">+ <button className="intro-btn" disabled={!ready || !ok(models?.router) || !ok(models?.memory)} onClick={onNext}>+ {L('Continuar', 'Continue')}+ </button>+ {!ready && (+ <span className="intro-muted" role="status">+ {L('Entre em um deles e eu sigo sozinho.', 'Sign in to one of them and I’ll move on.')}+ </span>+ )}+ </div>+ </div>+ </section>+ </div>+ )+}++// ---------- 3. the Tuca asks ----------++const TILE_ICONS: Record<string, { color: string; d: ReactNode }> = {+ week: { color: '#6D3FE0', d: <><rect x="3" y="5" width="18" height="16" rx="3" /><path d="M3 10h18M8 3v4M16 3v4" /></> },+ research: { color: '#0D7A7A', d: <><circle cx="11" cy="11" r="7" /><path d="M21 21l-4.3-4.3" /></> },+ write: { color: '#8A5A00', d: <path d="M4 20h4L19 9l-4-4L4 16zM13 7l4 4" /> },+ customers: { color: '#B8460F', d: <path d="M21 12a8 8 0 0 1-11.6 7.1L4 21l1.9-5.4A8 8 0 1 1 21 12z" /> },+ sheets: { color: '#2A6FB0', d: <><rect x="3" y="3" width="18" height="18" rx="3" /><path d="M3 9h18M3 15h18M9 3v18" /></> },+ code: { color: '#3F3A33', d: <path d="M8 9l-4 3 4 3M16 9l4 3-4 3M13 6l-2 12" /> }+}++function AskGoal({ name, onPick, onOwn, onManual, onBack }: { name: string; onPick: (g: Goal) => void; onOwn: (text: string) => void; onManual: () => void; onBack: () => void }): ReactNode {+ const engines = useStore((s) => s.settings.engines)+ const on = ENGINE_IDS.find((e) => engines[e].loggedIn && !engines[e].soon)+ const [text, setText] = useState('')+ const [note, setNote] = useState('')+ const field = useRef<HTMLInputElement>(null)+ const insert = (said: string): void => {+ setText((t) => (t.trim() ? `${t.trimEnd()} ${said}` : said))+ field.current?.focus()+ }+ const [voice, controls] = useDictation(insert, setNote, 'intro-goal')+ const first = name.trim().split(' ')[0] ?? ''+ const plan = on === 'codex' ? 'ChatGPT' : on === 'claude' ? 'Claude' : on ? ENGINES[on].label : ''+ return (+ <section className="intro__full">+ <Top+ at={2}+ right={+ <span className="intro__top-right">+ {plan && (+ <span className="intro-status">+ <span className="intro-status__dot" /> {L(`${plan} conectado`, `${plan} connected`)}+ </span>+ )}+ <button className="intro-link intro-link--quiet" onClick={onBack}>+ {L('Voltar', 'Back')}+ </button>+ </span>+ }+ />+ <div className="intro__center intro__center--narrow">+ <div className="intro-ask">+ <TucaMark size={56} />+ <div className="intro-ask__bubbles">+ <Bubble>{first ? L(`Pronto, ${first}! Agora vamos montar o seu primeiro agente.`, `Done, ${first}! Now let’s build your first agent.`) : L('Pronto! Agora vamos montar o seu primeiro agente.', 'Done! Now let’s build your first agent.')}</Bubble>+ <Bubble strong>+ <span id="intro-goal-q">{L('Qual é a primeira coisa que você queria tirar das suas costas?', 'What’s the first thing you’d like off your plate?')}</span>+ </Bubble>+ </div>+ </div>+ <div className="intro-tiles" role="group" aria-labelledby="intro-goal-q">+ {GOALS().map((g) => (+ <button key={g.id} className="intro-tile" onClick={() => onPick(g)}>+ <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke={TILE_ICONS[g.id]!.color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden className={`intro-tile__icon is-${g.id}`}>+ {TILE_ICONS[g.id]!.d}+ </svg>+ <span>{g.title}</span>+ </button>+ ))}+ </div>+ <form+ className="intro-say"+ onSubmit={(e) => {+ e.preventDefault()+ if (text.trim()) onOwn(text)+ }}+ >+ <label htmlFor="intro-say" className="sr-only">+ {L('Conte pro Tuca', 'Tell Tuca')}+ </label>+ <input id="intro-say" ref={field} type="text" value={text} placeholder={L('Ou conte do seu jeito: responder clientes da minha loja no Instagram…', 'Or say it your way: reply to customers of my Instagram shop…')} onChange={(e) => setText(e.target.value)} />+ {text.trim() ? (+ <button className="intro-round" type="submit" aria-label={L('Mandar pro Tuca', 'Send to Tuca')}>+ <Icon name="send" size={18} />+ </button>+ ) : (+ <span className="intro-voice">+ <VoiceButton controls={controls} state={voice} />+ </span>+ )}+ </form>+ {note && (+ <p className="intro-note" role="status">+ {note}+ </p>+ )}+ <button className="intro-link intro-link--center" onClick={onManual}>+ {L('Prefiro configurar do zero', 'I’d rather set it up from scratch')}+ </button>+ </div>+ </section>+ )+}++// ---------- 4. the agent is born ----------++const DOTS: AgentColor[] = ['violet', 'sky', 'teal', 'amber', 'rose', 'green', 'indigo']+const COLOR_NAME = (): Record<AgentColor, string> => ({ violet: L('Lilás', 'Violet'), sky: L('Azul', 'Blue'), teal: L('Verde-água', 'Teal'), amber: L('Amarelo', 'Amber'), rose: L('Rosa', 'Rose'), green: L('Verde', 'Green'), indigo: L('Anil', 'Indigo'), graphite: L('Grafite', 'Graphite') })++function Born(p: { agent: Agent; goal: Goal; patch: (a: Partial<Agent>) => void; busy: boolean; error: string; onCall: () => void; onAdjust: () => void; onBack: () => void }): ReactNode {+ const { agent, goal } = p+ const [naming, setNaming] = useState(false)+ const [connecting, setConnecting] = useState(false)+ const connected = useStore((s) => !!goal.connector && s.connectors.some((c) => entryOf(c)?.id === goal.connector!.id))+ const name = agent.name.trim() || L('seu agente', 'your agent')+ const offered = goal.connector && CATALOG.find((e) => e.id === goal.connector!.id)+ const settingsLevel = useStore((s) => s.settings.autonomy)+ const guard = useStore((s) => s.settings.outsideGuard ?? true)+ return (+ <div className="intro__split">+ <div className="intro-art intro-art--lilac">+ <div className="intro-art__say">+ <TucaMark size={44} />+ <Bubble>{L(`Pronto! Esse é o seu agente, ${name}. Quer mudar algo antes?`, `Done! This is your agent, ${name}. Want to change anything first?`)}</Bubble>+ </div>+ <span className="intro-blob intro-blob--lilac" aria-hidden style={{ left: 140, top: 190, width: 280, height: 280 }} />+ <span className="intro-born">+ <AgentAvatar agent={{ ...agent, name }} size={176} />+ </span>+ <div className="intro-name">+ {naming ? (+ <input+ className="intro-name__input"+ autoFocus+ aria-label={L('Nome do agente', 'The agent’s name')}+ value={agent.name}+ maxLength={40}+ onChange={(e) => p.patch({ name: e.target.value })}+ onBlur={() => setNaming(false)}+ onKeyDown={(e) => (e.key === 'Enter' || e.key === 'Escape') && setNaming(false)}+ />+ ) : (+ <>+ <b>{name}</b>+ <button className="intro-name__edit" aria-label={L('Mudar o nome', 'Change the name')} onClick={() => setNaming(true)}>+ <Icon name="edit" size={16} />+ </button>+ </>+ )}+ </div>+ <span className="intro-tagline">{goal.tagline}</span>+ <div className="intro-colors" role="group" aria-label={L('Cor', 'Color')}>+ {DOTS.map((c) => (+ <button key={c} aria-pressed={!agent.customColor && agent.color === c} aria-label={COLOR_NAME()[c]} className={`intro-color c-${c} ${!agent.customColor && agent.color === c ? 'is-on' : ''}`} onClick={() => p.patch({ color: c, customColor: undefined })} />+ ))}+ </div>+ </div>+ <section className="intro__main">+ <Top at={3} onBack={p.onBack} />+ <div className="intro__center intro__center--tight">+ <h1 className="intro-h2">{L(`O que ${name} faz por você`, `What ${name} does for you`)}</h1>+ <ul className="intro-card intro-card--list intro-does">+ {goal.does.map((d) => (+ <li key={d} className="intro-row">+ <span className="intro-tick" aria-hidden>+ <Icon name="check" size={16} />+ </span>+ {d}+ </li>+ ))}+ </ul>+ <AutonomyPick name={name} value={autonomyChosen(agent.autonomy, settingsLevel)} guard={guard} onPick={(level) => p.patch({ autonomy: storedAutonomy(level, settingsLevel) })} />+ {goal.connector && (+ <div className="intro-offer">+ {offered ? <CatalogLogo entry={offered} size={22} /> : <Icon name="plug" size={17} />}+ <span>+ {goal.connector.label} <span className="intro-muted">· {connected ? L('conectado, só leitura pra começar', 'connected, read-only to start') : L('opcional', 'optional')}</span>+ </span>+ {!connected && (+ <button className="intro-link" onClick={() => setConnecting(true)}>+ {L('Conectar', 'Connect')}+ </button>+ )}+ </div>+ )}+ {p.error && (+ <p className="intro-note intro-note--bad" role="alert">+ {p.error}+ </p>+ )}+ <div className="intro-actions">+ <button className="intro-btn" disabled={p.busy || !agent.name.trim() || !modelInfo(agent.modelId)?.id} onClick={p.onCall}>+ {L(`Chamar ${name} pro time`, `Bring ${name} to the team`)}+ </button>+ <button className="intro-link" onClick={p.onAdjust}>+ {L('Ajustar com o Tuca', 'Adjust with Tuca')}+ </button>+ </div>+ </div>+ </section>+ {connecting && goal.connector && (+ <Modal title={L('Conectar uma conta', 'Connect an account')} className="intro-connect" onClose={() => setConnecting(false)}>+ <ConnectorGrid status={STATUS()} query={goal.connector.id.startsWith('google-') ? `Google ${goal.connector.id.slice(7)}` : goal.connector.id} onManage={() => setConnecting(false)} />+ </Modal>+ )}+ </div>+ )+}++// "Ajustar com o Tuca": a talk with him about this agent; his card brings the new version back here.+function Adjust({ agent, goal, onUse, onBack }: { agent: Agent; goal: Goal; onUse: (d: AgentDraft) => void; onBack: () => void }): ReactNode {+ const tuca = useStore((s) => s.agents.find((a) => a.kind === 'tuca'))+ const [conv, setConv] = useState<string | null>(null)+ const [error, setError] = useState('')+ const messages = useStore((s) => (conv ? messagesIn(s, conv) : []))+ useEffect(() => {+ void ensureTuca(agent.modelId, true).then(+ (r) => {+ // What he's adjusting, written for the person to finish and send.+ setComposerDraft(r.conversationId, L(`Quero ajustar ${agent.name} antes de chamar pro time. Hoje: ${goal.tagline.toLowerCase()}. Quero que `, `I want to adjust ${agent.name} before bringing it to the team. Right now it ${goal.tagline.charAt(0).toLowerCase()}${goal.tagline.slice(1)}. I want it to `))+ setConv(r.conversationId)+ },+ (e: unknown) => setError(e instanceof Error ? e.message : String(e))+ )+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [])+ return (+ <section className="intro__full">+ <Top at={3} onBack={onBack} />+ <div className="intro__center intro__center--chat">+ <h1 className="intro-h2">{L(`Ajustar ${agent.name} com o Tuca`, `Adjust ${agent.name} with Tuca`)}</h1>+ <p className="intro-lead intro-lead--sm">{L('Diga o que quer diferente. Ele propõe uma versão nova, e você usa se gostar.', 'Say what you want different. He proposes a new version, and you use it if you like it.')}</p>+ <div className="intro-chat">+ {conv && tuca ? (+ <UseDraft.Provider value={(d) => onUse(d)}>+ <MessageList messages={messages} conversationId={conv} />+ <Composer conversationId={conv} members={[tuca]} placeholder={L('Escreva pro Tuca', 'Write to Tuca')} />+ </UseDraft.Provider>+ ) : (+ <p className="intro-wait" role="status">+ {error || (+ <>+ <Spinner /> {L('Chamando o Tuca…', 'Calling Tuca…')}+ </>+ )}+ </p>+ )}+ </div>+ </div>+ </section>+ )+}++// ---------- someone invited to a team ----------++const ABOUT = (): string[] => [L('Atendimento', 'Support'), L('Vendas', 'Sales'), 'Marketing', L('Financeiro', 'Finance')]++export function GuestWelcome(): ReactNode {+ const settings = useStore((s) => s.settings)+ const people = useStore((s) => s.people)+ const you = useStore((s) => s.you)+ const agents = useStore((s) => s.agents.filter(isTeam))+ const me = people.find((p) => p.id === you)+ const owner = people.find((p) => p.role === 'owner')+ const by = settings.onboarding?.guest?.by ?? owner?.name ?? ''+ const team = settings.workspaceLabel?.trim() || (owner ? L(`O time de ${owner.name}`, `${owner.name}’s team`) : L('O time', 'The team'))+ const others = people.filter((p) => p.id !== you)+ const [name, setName] = useState(me?.name ?? '')+ const [about, setAbout] = useState(me?.about ?? '')+ const [other, setOther] = useState(!!me?.about && !ABOUT().includes(me.about))+ const [busy, setBusy] = useState(false)+ const [error, setError] = useState('')++ async function enter(): Promise<void> {+ setBusy(true)+ setError('')+ try {+ if (name.trim() !== me?.name || about.trim() !== (me?.about ?? '')) await setMyName(name.trim(), about.trim())+ // The first message's mark is the introduction's: someone invited starts the tour at the first request.+ updateSettings({ onboarding: { done: true, tour: { done: ['first'] } } })+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e))+ } finally {+ setBusy(false)+ }+ }++ return (+ <div className="intro">+ <div className="intro__drag" />+ <div className="intro__stage">+ <div className="intro__split">+ <div className="intro-art intro-art--ink">+ <span className="intro-blob intro-blob--ember" aria-hidden />+ <span className="intro-invited">+ {by && <MeAvatar initials={initials(by)} size={32} />}+ {by ? L(`${by} te chamou pro time`, `${by} invited you to the team`) : L('Você foi chamado pro time', 'You were invited to the team')}+ </span>+ <h1 className="intro-h1 intro-h1--team">{team}</h1>+ {agents.length > 0 && (+ <div className="intro-team">+ <span className="intro-kicker">{L('O TIME', 'THE TEAM')}</span>+ {agents.slice(0, 4).map((a) => (+ <div key={a.id} className="intro-team__row">+ <AgentAvatar agent={a} size={44} />+ <span>+ <b>{a.name}</b>+ <br />+ <span>{a.role}</span>+ </span>+ </div>+ ))}+ {agents.length > 4 && <span className="intro-team__more">{L(`e mais ${agents.length - 4}`, `and ${agents.length - 4} more`)}</span>}+ </div>+ )}+ <span className="grow" />+ {others.length > 0 && (+ <div className="intro-people">+ <span className="intro-people__faces" aria-hidden>+ {others.slice(0, 3).map((p) => (+ <MeAvatar key={p.id} initials={initials(p.name)} size={30} />+ ))}+ </span>+ {others.length === 1 ? L(`${others[0]!.name} já está aqui`, `${others[0]!.name} is already here`) : L(`${list(others.map((p) => p.name)).replace(/, ([^,]*)$/, ' e $1')} já estão aqui`, `${list(others.map((p) => p.name)).replace(/, ([^,]*)$/, ' and $1')} are already here`)}+ </div>+ )}+ </div>+ <section className="intro__main">+ <div className="intro__top">+ <span />+ <LangToggle />+ </div>+ <div className="intro__center intro__center--tight">+ <h2 className="intro-h2">+ <label htmlFor="guest-name">{L('Como te chamam?', 'What do people call you?')}</label>+ </h2>+ <input id="guest-name" className="intro-input" value={name} maxLength={60} onChange={(e) => setName(e.target.value)} />+ <div className="intro-about" role="group" aria-labelledby="guest-about">+ <span id="guest-about" className="intro-label">+ {L('O que você faz no time?', 'What do you do on the team?')} <span className="intro-muted">{L('(opcional)', '(optional)')}</span>+ </span>+ <div className="intro-chips">+ {ABOUT().map((a) => (+ <button key={a} className={`intro-chipbtn ${!other && about === a ? 'is-on' : ''}`} aria-pressed={!other && about === a} onClick={() => (setOther(false), setAbout(about === a ? '' : a))}>+ {a}+ </button>+ ))}+ <button className={`intro-chipbtn ${other ? 'is-on' : ''}`} aria-pressed={other} onClick={() => (setOther(!other), setAbout(''))}>+ {L('Outro…', 'Other…')}+ </button>+ </div>+ {other && <input className="intro-input intro-input--sm" autoFocus aria-label={L('O que você faz', 'What you do')} value={about} maxLength={120} placeholder={L('Ex.: cuido das compras', 'E.g. I handle purchasing')} onChange={(e) => setAbout(e.target.value)} />}+ </div>+ <div className="intro-deal">+ <b>{L('O combinado', 'The deal')}</b>+ <span>{owner && owner.id !== you ? L(`O que você fala direto com um agente só você lê. Nem ${owner.name}.`, `What you say directly to an agent only you read. Not even ${owner.name}.`) : L('O que você fala direto com um agente só você lê.', 'What you say directly to an agent only you read.')}</span>+ <span>{L('Nos canais, o time todo vê.', 'In channels, the whole team sees.')}</span>+ <span>{L('Os agentes pedem o ok de quem decide antes do que o time combinou.', 'Agents ask whoever decides before what the team agreed on.')}</span>+ </div>+ {error && (+ <p className="intro-note intro-note--bad" role="alert">+ {error}+ </p>+ )}+ <div className="intro-actions">+ <button className="intro-btn" disabled={busy || !name.trim()} onClick={() => void enter()}>+ {L('Entrar no time', 'Join the team')}+ </button>+ <span className="intro-muted">{L('Depois, um tour de 1 minuto', 'Then a 1-minute tour')}</span>+ </div>+ </div>+ </section>+ </div>+ </div>+ </div>+ )+}++// Whether this window shows someone's invited welcome: theirs, once, and never the owner's.+export const guestWelcome = (s: ReturnType<typeof getState>): boolean => s.ready && !!s.settings.onboarding?.guest && !amOwner(s)diff --git a/src/renderer/src/components/Missions.tsx b/src/renderer/src/components/Missions.tsxnew file mode 100644index 0000000..56a2c75--- /dev/null+++ b/src/renderer/src/components/Missions.tsx@@ -0,0 +1,192 @@+// Missões: what's worth trying after the first message, each one checking itself off when it+// happens (as "Primeiros passos" did). On a new install each also brings a part of the sidebar,+// which starts short; a part with something in it shows anyway, and "Mostrar tudo de uma vez" ends it.+import { L } from '../../../shared/lang'+import { freshParts, MISSIONS, missionsDone, partShows, shortSidebar, type MissionFacts, type MissionId, type SidebarPart } from '../../../shared/onboarding'+import type { ReactNode } from 'react'+import { getState, isTeam, navigate, openTuca, updateSettings, useStore, type State, type View } from '../store'+import { Icon, TucaMark } from './ui'++// Whether one of the team's agents (not the Tuca) finished a reply, and whether an agent's question+// was answered: read once per change of the messages.+const talked = new WeakMap<State['messages'], { replied: boolean; answered: boolean }>()+function conversationFacts(s: State): { replied: boolean; answered: boolean } {+ const had = talked.get(s.messages)+ if (had) return had+ const team = new Set(s.agents.filter(isTeam).map((a) => a.id))+ const out = { replied: false, answered: false }+ for (const list of Object.values(s.messages))+ for (const m of list) {+ if (m.author.kind !== 'agent' || !m.run) continue+ if (m.run.status === 'done' && team.has(m.author.id)) out.replied = true+ if (m.run.question && m.run.status !== 'waiting_input') out.answered = true+ }+ talked.set(s.messages, out)+ return out+}++// What the missions look at, as values: the sidebar redraws only when one changes.+export const missionFacts = (s: State): MissionFacts => {+ const c = conversationFacts(s)+ return {+ replied: c.replied,+ decided: c.answered || s.approvals.some((a) => a.state !== 'pending'),+ connectors: s.connectors.length,+ agents: s.agents.filter(isTeam).length,+ routines: s.routines.length,+ memories: s.memories.filter((m) => m.state === 'active').length+ }+}++export function useMissions(): { facts: MissionFacts; done: Set<MissionId> } {+ // A plain object of values: the store keeps it while it's the same, so nothing redraws for nothing.+ const facts = useStore(missionFacts)+ return { facts, done: missionsDone(facts) }+}++// Which parts of the sidebar show, and which a mission just brought (tagged new until opened).+export function useSidebarParts(): { shows: (p: SidebarPart) => boolean; fresh: (p: SidebarPart) => boolean; seen: (p: SidebarPart) => void } {+ const onboarding = useStore((s) => s.settings.onboarding)+ const has = useStore((s) => `${s.memories.length > 0}|${s.routines.length > 0}|${s.skills.length > 0}|${s.connectors.length > 0}|${s.conversations.filter((c) => c.kind === 'channel').length > 1}`)+ const { done } = useMissions()+ const [memory, routines, skills, connectors, channels] = has.split('|').map((x) => x === 'true')+ const content: Partial<Record<SidebarPart, boolean>> = { memory, routines, skills, connectors, channels }+ const newOnes = freshParts(onboarding, done)+ return {+ shows: (p) => partShows(p, onboarding, done, content),+ fresh: (p) => newOnes.includes(p),+ seen: (p) => {+ const o = getState().settings.onboarding+ if (o && shortSidebar(o) && !(o.seen ?? []).includes(p)) updateSettings({ onboarding: { ...o, seen: [...(o.seen ?? []), p] } })+ }+ }+}++const agentName = (s: State): string => s.agents.find(isTeam)?.name ?? L('seu agente', 'your agent')++const go = (id: MissionId): View | 'tuca' => {+ const s = getState()+ const channel = s.conversations.find((c) => c.id === s.settings.onboarding?.channel) ?? s.conversations.find((c) => c.kind === 'channel')+ if (id === 'talk') return channel ? { kind: 'conversation', id: channel.id } : 'tuca'+ if (id === 'approve') return { kind: 'approvals' }+ if (id === 'connect') return { kind: 'connectors' }+ if (id === 'second') return 'tuca'+ if (id === 'auto') return { kind: 'routines' }+ return { kind: 'memory' }+}+const doIt = (id: MissionId): void => {+ const to = go(id)+ if (to === 'tuca') openTuca()+ else navigate(to)+}++// "Fale com a Lia" as the rest of a sentence: only its first letter goes down (names keep theirs).+const lower = (t: string): string => t.charAt(0).toLowerCase() + t.slice(1)++// At the bottom of the sidebar: how many are done, and the next one.+export function MissionsCard(): ReactNode {+ const { done } = useMissions()+ const name = useStore(agentName)+ const onboarding = useStore((s) => s.settings.onboarding)+ const active = useStore((s) => s.view?.kind === 'missions')+ const all = MISSIONS()+ const count = all.filter((m) => done.has(m.id)).length+ const next = all.find((m) => !done.has(m.id))+ const brought = freshParts(onboarding, done)+ const latest = [...all].reverse().find((m) => done.has(m.id) && m.unlocks.some((p) => brought.includes(p)))+ const line = latest ? L(`Você liberou ${latest.unlockName}`, `You unlocked ${latest.unlockName}`) : next ? L(`Próxima: ${lower(next.title(name))}`, `Next: ${lower(next.title(name))}`) : L('Você conhece o Tucano inteiro', 'You know all of Tucano')+ return (+ <button className={`missions-card ${active ? 'is-active' : ''} ${latest ? 'is-new' : ''}`} data-coach="missions" onClick={() => navigate({ kind: 'missions' })}>+ <span className="missions-ring" style={{ background: `conic-gradient(var(--m-accent) 0 ${(count / all.length) * 100}%, var(--m-track) ${(count / all.length) * 100}% 100%)` }} aria-hidden>+ <span>+ {count}/{all.length}+ </span>+ </span>+ <span className="missions-card__text">+ <b>{L('Missões', 'Missions')}</b>+ <span>{line}</span>+ </span>+ <span className="sr-only">{L(`${count} de ${all.length} feitas`, `${count} of ${all.length} done`)}</span>+ </button>+ )+}++export function MissionsPage(): ReactNode {+ const { done } = useMissions()+ const name = useStore(agentName)+ const onboarding = useStore((s) => s.settings.onboarding)+ const all = MISSIONS()+ const next = all.find((m) => !done.has(m.id))+ const short = shortSidebar(onboarding)+ return (+ <div className="missions">+ <div className="missions__head">+ <div>+ <h1>{L('Missões', 'Missions')}</h1>+ <p>{short ? L('Cada uma te mostra uma parte do Tucano, e ela aparece na barra quando você chega lá.', 'Each one shows you a part of Tucano, and it shows up in the sidebar when you get there.') : L('Cada uma te mostra uma parte do Tucano e se marca sozinha quando você usa.', 'Each one shows you a part of Tucano and checks itself off when you use it.')}</p>+ </div>+ {short && (+ <button className="missions-link" onClick={() => updateSettings({ onboarding: { ...onboarding!, showAll: true } })}>+ {L('Mostrar tudo de uma vez', 'Show everything at once')}+ </button>+ )}+ </div>+ <ol className="missions__grid">+ {all.map((m, i) => {+ const isDone = done.has(m.id)+ const isNext = m === next+ return (+ <li key={m.id} className={`mission ${isDone ? 'is-done' : isNext ? 'is-next' : ''}`}>+ {isDone ? (+ <span className="mission__check" aria-hidden>+ <Icon name="check" size={16} />+ </span>+ ) : (+ <span className="mission__n" aria-hidden>+ {i + 1}+ </span>+ )}+ <b>{m.title(name)}</b>+ {isDone ? (+ <span className="mission__state">{m.unlocks.length && short ? L(`Feita · liberou ${m.unlockName}`, `Done · unlocked ${m.unlockName}`) : L('Feita', 'Done')}</span>+ ) : (+ <span className="mission__how">+ {m.how}+ {m.unlocks.length > 0 && short && (+ <>+ {' '}+ {L('Libera', 'Unlocks')} <b>{m.unlockName}</b>.+ </>+ )}+ </span>+ )}+ {!isDone && (+ <button className={`mission__go ${isNext ? '' : 'is-quiet'}`} onClick={() => doIt(m.id)}>+ {L('Fazer agora', 'Do it now')}+ <span className="sr-only">: {m.title(name)}</span>+ </button>+ )}+ </li>+ )+ })}+ </ol>+ <div className="missions__help">+ <TucaMark size={40} />+ <span className="grow">+ {L('Travou em alguma? Me chama no ', 'Stuck on one? Call me at ')}+ <b>Tuca</b>+ {L(', no topo da barra. Eu faço com você.', ', at the top of the sidebar. I’ll do it with you.')}+ </span>+ <button className="missions-link" onClick={openTuca}>+ {L('Chamar o Tuca', 'Call Tuca')}+ </button>+ </div>+ <p className="missions__foot">+ <button className="missions-link missions-link--quiet" onClick={() => (updateSettings({ onboarding: { ...(onboarding ?? { done: true }), checklistHidden: true } }), navigate({ kind: 'approvals' }))}>+ {L('Esconder as missões', 'Hide the missions')}+ </button>{' '}+ <span>{L('Voltam em Configurações.', 'They come back in Settings.')}</span>+ </p>+ </div>+ )+}diff --git a/src/renderer/src/components/Onboarding.tsx b/src/renderer/src/components/Onboarding.tsxindex 84cbe4b..b0493b7 100644--- a/src/renderer/src/components/Onboarding.tsx+++ b/src/renderer/src/components/Onboarding.tsx@@ -1,55 +1,39 @@-// The first-run introduction, which is also the setup: how agents reach the-// models (the person's subscription, a provider they pay for, or the company's-// gateway) tested with a real reply, the models for routing and memory-// (required: a provider or gateway names its own), who you are, the tools (MCP) and skills to bring in (optional),-// the first agent and what it can use, and its first task, sent from here so-// the person lands in a channel watching it work. Then "Primeiros passos" in the sidebar-// walks through the rest, checking itself off as each feature gets used.-import { L, lang } from '../../../shared/lang'-import { RECOMMENDED_SKILL_BODY_LENGTH, skillLengthNote } from '../../../shared/skills'-import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from 'react'+// A new agent, step by step: the Tuca's builder screen (from the sidebar), where he proposes one and+// the person sets what it can use and its first task; and the introduction's "Prefiro configurar do+// zero" (Intro.tsx), the same form from a template, which hands the agent back to the introduction.+import { L } from '../../../shared/lang'+import { useEffect, useRef, useState, type ReactNode } from 'react'import {ENGINES,MODELS,- addConnector,- authorizeConnector,customModel,getState,dmWith,- linkSkill,- localSkills,modelInfo,usable,navigate,- openDialog,- newChannel,- refreshEngines,newAgentDraft,saveAgent,sendMessage,slug,ensureTuca,settleDraft,- updateSettings,- anyReplyDone,messagesIn,useStore,type Agent,type AgentColor,type AgentDraft,- type EngineId,type GrantLevel,- type LocalSkill,type State,- type View,- isTeam+ type View} from '../store'-import { HarnessList, ModelPicker, usableEngines } from './Harness'-import { ColorPicker, JevKey, LanguagePicker, LookPicker, ModelSelect, Toggle } from './Pages'-import { Splash } from './Splash'+import { ModelPicker, usableEngines } from './Harness'+import { ColorPicker, LookPicker, Toggle } from './Pages'import { Composer, MessageList } from './Conversation'import { draftAgent, UseDraft } from './Tuca'-import { AgentAvatar, Icon, MeAvatar, TucaMark, type IconName } from './ui'+import { AutonomyPick } from './AutonomyPick'+import { autonomyChosen, FIRST_AUTONOMY, storedAutonomy } from '../../../shared/onboarding'+import { AgentAvatar, Icon, type IconName } from './ui'type Computer = 'none' | 'linux' | 'mac'@@ -147,14 +131,8 @@ const TEMPLATES = (): Template[] => [}]-// The introduction draws again when the language changes: the opening plays only once.-let opened = false--const STEPS = ['welcome', 'engine', 'models', 'you', 'tools', 'skills', 'agent', 'powers', 'first'] as const+const STEPS = ['agent', 'powers', 'first'] as consttype Step = (typeof STEPS)[number]-// The builder screen (the Tuca, from the sidebar) is the introduction's last three steps.-const BUILD_STEPS: readonly Step[] = ['agent', 'powers', 'first']-const BuildMode = createContext(false)function unique(base: string, taken: string[]): string {if (!taken.includes(base)) return base@@ -170,44 +148,38 @@ function fromTemplate(a: Agent, t: Template, models: typeof MODELS): Agent {return { ...a, name: t.name, role: t.role, color: t.color, customColor: undefined, instructions: t.instructions, modelId: model?.id ?? a.modelId, web: true }}-export function Onboarding({ build = false, from }: { build?: boolean; from?: View } = {}): ReactNode {+// `manual`: the introduction's form, which gives the agent and its first message back to it.+export interface ManualIntro {+ onBack: () => void+ onCreate: (agent: Agent, task: string) => Promise<void>+}++export function Onboarding({ build = false, from, manual }: { build?: boolean; from?: View; manual?: ManualIntro } = {}): ReactNode {const settings = useStore((s) => s.settings)const handles = useStore((s) => s.agents.map((a) => a.handle))- const channels = useStore((s) => s.conversations.filter((c) => c.kind === 'channel').map((c) => c.name))- const hasAgents = useStore((s) => s.agents.some(isTeam))const connectors = useStore((s) => s.connectors)- const steps = build ? BUILD_STEPS : STEPS- const [step, setStep] = useState<Step>(build ? 'agent' : 'welcome')- const [name, setName] = useState(settings.workspaceName)- const [context, setContext] = useState(settings.context)+ const steps = STEPS+ const [step, setStep] = useState<Step>('agent')const [template, setTemplate] = useState<Template>(() => TEMPLATES()[0]!)- const [agent, setAgent] = useState<Agent>(() => fromTemplate(newAgentDraft(), TEMPLATES()[0]!, readyModels(settings.engines)))+ // From the introduction it starts on Normal, as the introduction's own agent does; the builder follows Settings.+ const [agent, setAgent] = useState<Agent>(() => ({ ...fromTemplate(newAgentDraft(), TEMPLATES()[0]!, readyModels(settings.engines)), ...(manual ? { autonomy: storedAutonomy(FIRST_AUTONOMY, settings.autonomy) } : {}) }))const [computer, setComputer] = useState<Computer>('none')const [task, setTask] = useState(() => TEMPLATES()[0]!.tasks[0]!)const [busy, setBusy] = useState(false)const [error, setError] = useState('') // why the agent wasn't created (a person's name, a taken @)- // 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.- const [manual, setManual] = useState(false)+ // The agent comes from the Tuca's card, or from the form for who prefers it (always, from the introduction).+ const [hand, setManual] = useState(!!manual)const [fromTuca, setFromTuca] = useState<{ messageId: string; task?: string } | null>(null)- const [opening, setOpening] = useState(!build && !opened)// A new session with the Tuca each time this screen opens (made when his step first shows).const [tucaConv, setTucaConv] = useState<{ id?: string; error?: string }>({})- const onOpened = useCallback(() => ((opened = true), setOpening(false)), [])const models = readyModels(settings.engines)const ready = usableEngines(settings)const at = steps.indexOf(step)// Which way the next step slides in: forward from the right, back from the left.const [dir, setDir] = useState<'next' | 'back'>('next')- const [cheer, setCheer] = useState(false)const go = (s: Step): void => {setDir(steps.indexOf(s) < at ? 'back' : 'next')setStep(s)@@ -219,10 +191,9 @@ export function Onboarding({ build = false, from }: { build?: boolean; from?: Viconst channel = getState().conversations.find((c) => c.kind === 'channel')navigate(from ?? (channel ? { kind: 'conversation', id: channel.id } : { kind: 'approvals' }))}- const close = (): void => (build ? leave() : updateSettings({ onboarding: { done: true } }))+ const close = (): void => (manual ? manual.onBack() : leave())- // On the builder screen the Tuca starts on his own model; in the introduction he waits- // for the person to pick one (MeetTuca).+ // On the builder screen the Tuca starts on his own model.useEffect(() => {if (!build || step !== 'agent' || tucaConv.id || tucaConv.error) returnensureTuca(agent.modelId, true)@@ -247,9 +218,9 @@ export function Onboarding({ build = false, from }: { build?: boolean; from?: VisetTask(t.tasks[0]!)}- // A Tuca card: its agent becomes the first one (same id), with its access; powers and first task follow.+ // A Tuca card: its agent becomes the new one (same id), with its access; powers and first task follow.const useDraft = (d: AgentDraft, messageId: string): void => {- setAgent((a) => ({ ...draftAgent(d), id: a.id, limit: a.limit }))+ setAgent((a) => ({ ...draftAgent(d), id: a.id, limit: a.limit, autonomy: a.autonomy }))setGrants(Object.fromEntries(connectors.map((c) => [c.id, d.grants[c.id] ?? 'none'])))setFromTuca({ messageId, task: d.task })if (d.task) setTask(d.task)@@ -270,27 +241,14 @@ export function Onboarding({ build = false, from }: { build?: boolean; from?: VisetError('')try {const a: Agent = { ...agent, name: agent.name.trim(), role: agent.role.trim(), handle, computer: computer !== 'none', computerKind: computer === 'mac' ? 'mac' : 'linux', grants: Object.fromEntries(connectors.map((c) => [c.id, grants[c.id] ?? 'read'])) }- if (build) {- // From the builder screen: the agent, then a DM with it and its first task.- await saveAgent(a, [])- if (fromTuca) settleDraft(fromTuca.messageId, a.id)- const dm = await dmWith(a.id)- navigate({ kind: 'conversation', id: dm })- sendMessage(dm, task.trim())- return- }- const channelId = await newChannel(unique(L('geral', 'general'), channels))- await saveAgent(a, [channelId])- if (fromTuca) settleDraft(fromTuca.messageId, a.id) // his card shows it was created- await Promise.all(skills.map((source) => linkSkill(source).catch(() => undefined))) // for every agent; who uses each changes in Skills- // A beat for the Tuca to cheer before the channel opens (none with reduced motion).- if (!matchMedia('(prefers-reduced-motion: reduce)').matches) {- setCheer(true)- await new Promise((done) => setTimeout(done, 650))- }- updateSettings({ workspaceName: name.trim() || settings.workspaceName, context: context.trim(), routerModel, memoryModel, onboarding: { done: true } })- navigate({ kind: 'conversation', id: channelId })- sendMessage(channelId, `@${a.handle} ${task.trim()}`)+ // From the introduction: it makes #geral and leaves the first message there, unsent.+ if (manual) return await manual.onCreate(a, task.trim())+ // From the builder screen: the agent, then a DM with it and its first task.+ await saveAgent(a, [])+ if (fromTuca) settleDraft(fromTuca.messageId, a.id)+ const dm = await dmWith(a.id)+ navigate({ kind: 'conversation', id: dm })+ sendMessage(dm, task.trim())} catch (e) {setError(e instanceof Error ? e.message : String(e))} finally {@@ -298,8 +256,6 @@ export function Onboarding({ build = false, from }: { build?: boolean; from?: Vi}}- if (opening) return <Splash onDone={onOpened} />-return (<div className="onb"><div className="onb__drag" />@@ -310,35 +266,22 @@ export function Onboarding({ build = false, from }: { build?: boolean; from?: Vi))}</div><button className="btn btn--ghost btn--sm" onClick={close}>- {build || hasAgents ? L('Fechar', 'Close') : L('Pular introdução', 'Skip the introduction')}+ {manual ? L('Voltar', 'Back') : L('Fechar', 'Close')}</button></header><div className="onb__scroll">- <BuildMode.Provider value={build}><div className="onb__stage" key={step} data-dir={dir}>- {step === 'welcome' && <Welcome name={name} setName={setName} onNext={next} />}- {step === 'engine' && <Harnesses ready={ready.length > 0} onBack={back} onNext={next} />}- {step === 'models' && <Models ready={ready} router={routerModel} setRouter={setRouterModel} memory={memoryModel} setMemory={setMemoryModel} onBack={back} onNext={next} />}- {step === 'you' && <You name={name} context={context} setContext={setContext} onBack={back} onNext={next} />}- {step === 'tools' && <Tools onBack={back} onNext={next} />}- {step === 'skills' && <SkillsStep picked={skills} setPicked={setSkills} onBack={back} onNext={next} />}{step === 'agent' &&- (manual ? (- <MakeAgent agent={agent} handle={handle} template={template} pick={pick} patch={patch} computer={computer} onBack={() => setManual(false)} onNext={next} />+ (hand ? (+ <MakeAgent agent={agent} handle={handle} template={template} pick={pick} patch={patch} computer={computer} onBack={() => (manual ? manual.onBack() : setManual(false))} onNext={next} />) : (- <MeetTuca conv={tucaConv} onUse={useDraft} onManual={() => setManual(true)} onBack={build ? undefined : back} />+ <MeetTuca conv={tucaConv} onUse={useDraft} onManual={() => setManual(true)} />))}{step === 'powers' && <Powers agent={agent} handle={handle} patch={patch} computer={computer} setComputer={setComputer} grants={grants} setGrants={setGrants} onBack={back} onNext={next} />}- {step === 'first' && <FirstTask agent={agent} handle={handle} computer={computer} channel={unique(L('geral', 'general'), channels)} tasks={tasks} task={task} setTask={setTask} busy={busy} error={error} onBack={back} onFinish={() => void finish()} />}+ {step === 'first' && <FirstTask agent={agent} handle={handle} computer={computer} manual={!!manual} tasks={tasks} task={task} setTask={setTask} busy={busy} error={error} onBack={back} onFinish={() => void finish()} />}</div>- </BuildMode.Provider></div>- {cheer && (- <div className="onb-cheer" aria-hidden>- <TucaMark size={96} happy />- </div>- )}</div>)}@@ -360,374 +303,21 @@ function Nav({ onBack, onNext, next = L('Continuar', 'Continue'), disabled }: {)}-// ---------- 1. welcome ------------function Welcome({ name, setName, onNext }: { name: string; setName: (v: string) => void; onNext: () => void }): ReactNode {- return (- <div className="onb__split">- <section className="onb__main">- <LanguagePicker className="onb__lang" />- <span className="onb__kicker">{L('Bem-vindo ao Tucano', 'Welcome to Tucano')}</span>- <h1>{L('Um time de agentes de IA, trabalhando no seu computador.', 'A team of AI agents, working on your computer.')}</h1>- <p className="onb__lead">{L('Você conversa com eles em canais, como num chat do trabalho. Eles pesquisam, escrevem, programam e usam as suas ferramentas, e você decide até onde cada um vai.', 'You talk to them in channels, like a work chat. They research, write, code and use your tools, and you decide how far each one goes.')}</p>- <ul className="onb__points">- <Point icon="zap" title={L('Nos programas que você já usa', 'In the tools you already use')}>- {L('Claude Code, Codex, OpenCode ou Pi, como você configurou: no seu plano, no gateway da empresa ou nos seus provedores.', 'Claude Code, Codex, OpenCode or Pi, the way you set them up: on your plan, your company’s gateway or your providers.')}- </Point>- <Point icon="shield" title={L('Você no controle', 'You’re in control')}>- {L('Cada agente só usa o que você liberar. Comprar, publicar, enviar e apagar sempre esperam o seu ok.', 'Each agent only uses what you allow. Buying, publishing, sending and deleting always wait for your OK.')}- </Point>- <Point icon="lock" title={L('Tudo fica aqui', 'Everything stays here')}>- {L('Conversas, memória e logins ficam no seu computador. Nada passa por um servidor do Tucano.', 'Conversations, memory and logins stay on your computer. Nothing goes through a Tucano server.')}- </Point>- </ul>- <label className="onb__field">- <span>{L('Como os agentes devem te chamar?', 'What should the agents call you?')}</span>- <input autoFocus value={name} placeholder={L('Seu nome', 'Your name')} onChange={(e) => setName(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && name.trim() && onNext()} />- </label>- <Nav onNext={onNext} next={L('Começar', 'Get started')} disabled={!name.trim()} />- </section>- <aside className="onb__aside">- <ChatPreview me={name} />- </aside>- </div>- )-}--function Point({ icon, title, children }: { icon: IconName; title: string; children: ReactNode }): ReactNode {- return (- <li>- <span className="onb__point-icon">- <Icon name={icon} size={16} />- </span>- <span>- <strong>{title}</strong>- <span>{children}</span>- </span>- </li>- )-}--// A still of what the app is: a channel where agents work and ask before acting.-function ChatPreview({ me }: { me: string }): ReactNode {- const initials = (me.trim()[0] ?? 'V').toUpperCase()- return (- <div className="onb-chat" aria-hidden>- <div className="onb-chat__head">- <Icon name="hash" size={14} /> {L('lancamento', 'launch')}- </div>- <div className="onb-chat__msg">- <MeAvatar initials={initials} size={26} />- <div>- <b>{me.trim() || L('Você', 'You')}</b>- <p>{L('@iris acha os 3 concorrentes que mais cresceram este ano. @nina, depois escreve o post.', '@iris find the 3 competitors that grew the most this year. @nina, then write the post.')}</p>- </div>- </div>- <div className="onb-chat__msg">- <AgentAvatar agent={{ name: 'Iris', color: 'sky' }} size={26} />- <div>- <b>Iris</b>- <span className="onb-chat__step">- <Icon name="globe" size={12} /> {L('Pesquisou na web · 6 fontes', 'Searched the web · 6 sources')}- </span>- <p>{L('Achei os três, com números e links. @nina, o resumo está acima.', 'Found all three, with numbers and links. @nina, the summary is above.')}</p>- </div>- </div>- <div className="onb-chat__msg">- <AgentAvatar agent={{ name: 'Nina', color: 'rose' }} size={26} />- <div>- <b>Nina</b>- <p>{L('Post pronto. Quer que eu publique no LinkedIn?', 'Post ready. Want me to publish it on LinkedIn?')}</p>- <div className="onb-chat__approval">- <Icon name="shield" size={13} />- <span>{L('Publicar post no LinkedIn', 'Publish post on LinkedIn')}</span>- <span className="onb-chat__btn">{L('Aprovar', 'Approve')}</span>- </div>- </div>- </div>- </div>- )-}--// ---------- 2. engine ------------function Harnesses({ ready, onBack, onNext }: { ready: boolean; onBack: () => void; onNext: () => void }): ReactNode {- // Logging in happens in the Terminal; keep checking until one is ready.- useEffect(() => {- refreshEngines()- if (ready) return- const t = setInterval(refreshEngines, 4000)- return () => clearInterval(t)- }, [ready])-- return (- <div className="onb__split">- <section className="onb__main">- <span className="onb__kicker">{L('Passo 1 · Onde rodam', 'Step 1 · Where they run')}</span>- <h1>{L('Onde seus agentes vão rodar?', 'Where will your agents run?')}</h1>- <p className="onb__lead">{L('No Claude Code, no Codex ou em outro que você já usa, do jeito que configurou cada um. O Tucano só lê essa configuração: nunca vê nem guarda as suas senhas e chaves.', 'In Claude Code, Codex or another one you already use, the way you set up each. Tucano only reads that setup: it never sees or stores your passwords and keys.')}</p>- <HarnessList />- {!ready && (- <p className="onb__wait">- <span className="pulse" /> {L('Entre em um deles (no terminal que abriu) e eu sigo sozinho.', 'Sign in to one of them (in the terminal that opened) and I’ll move on.')}- </p>- )}- <Nav onBack={onBack} onNext={onNext} disabled={!ready} />- </section>- <aside className="onb__aside">- <div className="onb-guard">- <Icon name="zap" size={16} />- <div>- <p>- <strong>{L('O que o Tucano lê de cada um', 'What Tucano reads from each one')}</strong>- </p>- <ul className="harness__guide">- <li>- <b>{L('Plano:', 'Plan:')}</b> {L('o login do Claude ou do ChatGPT. Sem chave e sem cobrança por uso.', 'your Claude or ChatGPT login. No key and no pay-per-use.')}- </li>- <li>- <b>Gateway:</b> {L('o proxy da empresa (ou um provedor) que está no settings.json do Claude Code ou no config.toml do Codex. Os agentes usam o mesmo, e a telemetria fica desligada.', 'your company’s proxy (or a provider) in Claude Code’s settings.json or Codex’s config.toml. The agents use the same one, and telemetry stays off.')}- </li>- <li>- <b>{L('Provedores:', 'Providers:')}</b> {L('os logins do OpenCode e do Pi, com os modelos de cada um.', 'your OpenCode and Pi logins, with each one’s models.')}- </li>- </ul>- </div>- </div>- </aside>- </div>- )-}--// ---------- 2. the models ------------function Models(p: { ready: EngineId[]; router: string; setRouter: (v: string) => void; memory: string; setMemory: (v: string) => void; onBack: () => void; onNext: () => void }): ReactNode {- const jevKey = useStore((s) => !!s.settings.jevKey)- const ok = (v: string): boolean => (v === 'jev' ? jevKey : !!usable(modelInfo(v)))- return (- <section className="onb__main onb__main--wide">- <span className="onb__kicker">{L('Passo 2 · Os modelos', 'Step 2 · The models')}</span>- <h1>{L('Quem decide e quem lembra.', 'Who decides and who remembers.')}</h1>- <p className="onb__lead">{L('Dois trabalhos pequenos rodam o tempo todo, fora dos agentes. Escolha um modelo rápido pra cada um; dá pra trocar depois em Configurações.', 'Two small jobs run all the time, outside the agents. Pick a fast model for each; you can change them later in Settings.')}</p>- <p className="onb-note">- <Icon name="zap" size={14} /> {L('Primeiro o programa (Claude Code, Codex…), depois o modelo da lista dele. Se o seu não aparece, escolha', 'First the tool (Claude Code, Codex…), then a model from its list. If yours isn’t there, pick')} <b>{L('Outro modelo…', 'Other model…')}</b> {L('e digite o nome.', 'and type its name.')}- </p>- <div className="onb-pair">- <div className="onb-pick">- <span className="onb-pick__icon">- <Icon name="spark" size={18} />- </span>- <strong>{L('Quem responde', 'Who replies')}</strong>- <p>{L('Lê a mensagem num canal sem @menção e escolhe o agente. Roda antes de cada resposta: prefira o mais rápido.', 'Reads a channel message with no @mention and picks the agent. It runs before every reply: go for the fastest.')}</p>- <ModelSelect value={p.router} onChange={p.setRouter} engines={p.ready} jev />- {p.router === 'jev' && <JevKey saved={jevKey} />}- </div>- <div className="onb-pick">- <span className="onb-pick__icon">- <Icon name="book" size={18} />- </span>- <strong>{L('Memória', 'Memory')}</strong>- <p>{L('Resume o que sai da janela das conversas longas e sugere o que vale lembrar sobre você.', 'Summarizes what leaves the window of long conversations and suggests what’s worth remembering about you.')}</p>- <ModelSelect value={p.memory} onChange={p.setMemory} engines={p.ready} />- </div>- </div>- <Nav onBack={p.onBack} onNext={p.onNext} disabled={!ok(p.router) || !ok(p.memory)} />- </section>- )-}--// ---------- 4. the tools ------------const SUGGESTED: { name: string; url: string; auth: 'oauth' | 'token' }[] = [- { name: 'Linear', url: 'https://mcp.linear.app/mcp', auth: 'oauth' },- { name: 'Notion', url: 'https://mcp.notion.com/mcp', auth: 'oauth' },- { name: 'Sentry', url: 'https://mcp.sentry.dev/mcp', auth: 'oauth' },- { name: 'GitHub', url: 'https://api.githubcopilot.com/mcp/', auth: 'token' },- { name: 'GitLab', url: 'https://gitlab.com/api/v4/mcp', auth: 'oauth' }-]--const STATUS = (): Record<string, { label: string; tone: string }> => ({- connected: { label: L('conectado', 'connected'), tone: 'tag--ok' },- connecting: { label: L('conectando…', 'connecting…'), tone: '' },- needs_auth: { label: L('precisa autorizar', 'needs authorization'), tone: 'tag--warn' },- error: { label: L('não conectou', 'didn’t connect'), tone: 'tag--danger' },- disconnected: { label: L('desconectado', 'disconnected'), tone: 'tag--warn' }-})--function Tools({ onBack, onNext }: { onBack: () => void; onNext: () => void }): ReactNode {- const connectors = useStore((s) => s.connectors)- const [form, setForm] = useState({ name: '', url: '', auth: 'oauth' as 'oauth' | 'token' | 'none', token: '' })- const [error, setError] = useState<string | null>(null)- const [adding, setAdding] = useState(false)- const add = (): void => {- setError(null)- setAdding(true)- addConnector({ name: form.name.trim(), kind: 'remote', url: form.url.trim(), auth: form.auth, token: form.auth === 'token' ? form.token.trim() : undefined })- .then(() => setForm({ name: '', url: '', auth: 'oauth', token: '' }))- .catch((e: unknown) => setError(e instanceof Error ? e.message.replace(/^Error invoking.*?: /, '') : String(e)))- .finally(() => setAdding(false))- }- return (- <section className="onb__main onb__main--wide">- <span className="onb__kicker">{L('Passo 4 · Ferramentas · opcional', 'Step 4 · Tools · optional')}</span>- <h1>{L('As ferramentas do seu trabalho.', 'The tools of your work.')}</h1>- <p className="onb__lead">{L('Jira, GitLab, Slack, Linear… qualquer servidor MCP, inclusive os internos da sua empresa. Mais adiante você escolhe o que cada agente pode usar.', 'Jira, GitLab, Slack, Linear… any MCP server, including your company’s internal ones. Later on you pick what each agent can use.')}</p>-- {connectors.length > 0 && (- <div className="onb-conns">- {connectors.map((c) => {- const st = STATUS()[c.status] ?? { label: c.status, tone: '' }- return (- <div key={c.id} className="onb-conn">- <Icon name={c.kind === 'stdio' ? 'terminal' : 'plug'} size={16} />- <strong>{c.name}</strong>- <span className={`tag ${st.tone}`}>{st.label}</span>- <span className="muted small grow">{c.tools.length ? L(`${c.tools.length} ferramentas`, `${c.tools.length} tools`) : c.error ?? ''}</span>- {c.status === 'needs_auth' && (- <button className="btn btn--primary btn--sm" onClick={() => authorizeConnector(c.id)}>- {L('Autorizar no navegador', 'Authorize in the browser')}- </button>- )}- </div>- )- })}- </div>- )}-- <div className="onb-add">- <div className="onb__chips">- {SUGGESTED.filter((x) => !connectors.some((c) => c.url === x.url)).map((x) => (- <button key={x.name} className="onb-chip" onClick={() => setForm({ name: x.name, url: x.url, auth: x.auth, token: '' })}>- <Icon name="plus" size={12} /> {x.name}- </button>- ))}- </div>- <div className="onb__row">- <label className="onb__field onb__field--narrow">- <span>{L('Nome', 'Name')}</span>- <input value={form.name} placeholder={L('Ex.: Jira', 'E.g. Jira')} onChange={(e) => setForm({ ...form, name: e.target.value })} />- </label>- <label className="onb__field">- <span>{L('Endereço do servidor MCP', 'MCP server address')}</span>- <input value={form.url} placeholder={L('https://mcp.suaempresa.com/jira', 'https://mcp.yourcompany.com/jira')} spellCheck={false} onChange={(e) => setForm({ ...form, url: e.target.value })} />- </label>- </div>- <div className="onb__row onb__row--center">- <div className="segmented">- {(- [- ['oauth', L('Login no navegador', 'Browser login')],- ['token', 'Token'],- ['none', L('Sem login', 'No login')]- ] as const- ).map(([v, label]) => (- <button key={v} className={form.auth === v ? 'is-active' : ''} onClick={() => setForm({ ...form, auth: v })}>- {label}- </button>- ))}- </div>- {form.auth === 'token' && <input className="grow" type="password" value={form.token} placeholder={L('O token (vai como Authorization: Bearer)', 'The token (sent as Authorization: Bearer)')} onChange={(e) => setForm({ ...form, token: e.target.value })} />}- <button className="btn btn--primary" disabled={adding || !form.name.trim() || !/^https?:\/\//.test(form.url.trim()) || (form.auth === 'token' && !form.token.trim())} onClick={add}>- {L('Conectar', 'Connect')}- </button>- </div>- {error && <p className="field__error">{error}</p>}- {/gitlab\.com/.test(form.url) && <p className="hint">{L('GitLab da empresa, num endereço próprio? Troque gitlab.com pelo endereço dela.', 'Your company’s GitLab, at its own address? Replace gitlab.com with it.')}</p>}- <p className="hint">{L('O token fica cifrado no cofre do sistema. Os agentes nunca veem nem o token nem a sua senha.', 'The token is encrypted in the system’s vault. Agents never see the token or your password.')}</p>- </div>- <Nav onBack={onBack} onNext={onNext} next={connectors.length ? L('Continuar', 'Continue') : L('Conectar depois', 'Connect later')} />- </section>- )-}--// ---------- 5. the skills ------------function SkillsStep({ picked, setPicked, onBack, onNext }: { picked: string[]; setPicked: (v: string[]) => void; onBack: () => void; onNext: () => void }): ReactNode {- const [found, setFound] = useState<LocalSkill[] | null>(null)- useEffect(() => {- void localSkills().then(setFound, () => setFound([]))- }, [])- const toggle = (src: string): void => setPicked(picked.includes(src) ? picked.filter((x) => x !== src) : [...picked, src])- return (- <section className="onb__main onb__main--wide">- <span className="onb__kicker">{L('Passo 5 · Skills · opcional', 'Step 5 · Skills · optional')}</span>- <h1>{L('Traga as suas skills.', 'Bring your skills.')}</h1>- <p className="onb__lead">{L('As receitas que você já usa no Claude Code e no Codex. Os agentes leem direto do arquivo: o que você mudar lá vale aqui. O resto da sua configuração (hooks, plugins, permissões) continua de fora.', 'The recipes you already use in Claude Code and Codex. Agents read them straight from the file: what you change there applies here. The rest of your setup (hooks, plugins, permissions) stays out.')}</p>- {found === null ? (- <p className="onb__wait">- <span className="pulse" /> {L('Procurando…', 'Looking…')}- </p>- ) : found.length === 0 ? (- <p className="onb-note">{L('Não achei skills no seu Claude Code nem no Codex. Dá pra escrever as suas depois, em Skills.', 'I didn’t find skills in your Claude Code or Codex. You can write your own later, in Skills.')}</p>- ) : (- <div className="onb-skills">- {found.map((k) => (- <button key={k.source} className={`onb-skill ${picked.includes(k.source) ? 'is-active' : ''}`} onClick={() => toggle(k.source)}>- <span className="onb-skill__check">{picked.includes(k.source) && <Icon name="check" size={12} />}</span>- <span className="grow">- <strong>{k.name}</strong> <span className="tag">{k.origin}</span>- <span className="onb-skill__desc">{k.description}</span>- {k.scripts && <span className="small warn-text">{L('Tem scripts: precisa de um agente com computador.', 'It has scripts: needs an agent with a computer.')}</span>}- {k.bodyLength > RECOMMENDED_SKILL_BODY_LENGTH && <span className="small warn-text" role="status">{skillLengthNote(k.bodyLength)}</span>}- </span>- </button>- ))}- </div>- )}- <Nav onBack={onBack} onNext={onNext} next={picked.length ? L(`Trazer ${picked.length} ${picked.length === 1 ? 'skill' : 'skills'}`, `Bring ${picked.length} ${picked.length === 1 ? 'skill' : 'skills'}`) : L('Pular', 'Skip')} />- </section>- )-}--// ---------- 3. you ------------const ABOUT_EXAMPLES = (): string[] => (lang() === 'en' ? ['I’m a developer working on…', 'I run an online store that sells…', 'I’m studying for…', 'I prefer short, direct answers.'] : ['Sou dev e trabalho com…', 'Tenho uma loja online de…', 'Estudo pra…', 'Prefiro respostas curtas e diretas.'])--function You({ name, context, setContext, onBack, onNext }: { name: string; context: string; setContext: (v: string) => void; onBack: () => void; onNext: () => void }): ReactNode {- return (- <section className="onb__main">- <span className="onb__kicker">{L('Passo 3 · Você', 'Step 3 · You')}</span>- <h1>{name.trim() ? L(`${name.trim().split(' ')[0]}, conta um pouco sobre você.`, `${name.trim().split(' ')[0]}, tell me a bit about yourself.`) : L('Conta um pouco sobre você.', 'Tell me a bit about yourself.')}</h1>- <p className="onb__lead">{L('Todo agente lê isso antes de cada resposta, então ninguém precisa te perguntar de novo. Seu trabalho, seus projetos, como você gosta das respostas.', 'Every agent reads this before each reply, so nobody has to ask you again. Your work, your projects, how you like your answers.')}</p>- <textarea- className="onb__textarea"- autoFocus- rows={6}- value={context}- placeholder={L('Ex.: Sou designer numa agência pequena em Curitiba. Cuido de três clientes de e-commerce. Gosto de respostas curtas, em português, com exemplos.', 'E.g. I’m a designer at a small agency in Austin. I look after three e-commerce clients. I like short answers, with examples.')}- onChange={(e) => setContext(e.target.value)}- />- <div className="onb__chips">- {ABOUT_EXAMPLES().map((x) => (- <button key={x} className="onb-chip" onClick={() => setContext(context.trim() ? `${context.trim()} ${x}` : x)}>- <Icon name="plus" size={12} /> {x}- </button>- ))}- </div>- <p className="hint">{L('Dá pra mudar quando quiser, em Configurações. Os agentes também aprendem com o tempo, e você aprova o que eles guardam.', 'You can change it any time in Settings. The agents also learn over time, and you approve what they keep.')}</p>- <Nav onBack={onBack} onNext={onNext} next={context.trim() ? L('Continuar', 'Continue') : L('Pular por enquanto', 'Skip for now')} />- </section>- )-}-// ---------- 4. the agent -----------// The first agent, made with the Tuca: he asks, proposes a card, "Usar esse agente" fills it in.-// His model is the person's choice: in the introduction nothing is picked for them, and-// he only starts once they pick; on the builder screen it's the one picked before.-// Changing it starts a new session with him on that model.-function MeetTuca({ conv: session, onUse, onManual, onBack }: { conv: { id?: string; error?: string }; onUse: (d: AgentDraft, messageId: string) => void; onManual: () => void; onBack?: () => void }): ReactNode {- const build = useContext(BuildMode)+// A new agent, made with the Tuca: he asks, proposes a card, "Usar esse agente" fills it in.+// He starts on his own model; changing it starts a new session with him on that model.+function MeetTuca({ conv: session, onUse, onManual }: { conv: { id?: string; error?: string }; onUse: (d: AgentDraft, messageId: string) => void; onManual: () => void }): ReactNode {const [conv, setConv] = useState(session.id)const tuca = useStore((s) => s.agents.find((a) => a.kind === 'tuca'))- const [model, setModel] = useState(build ? (tuca?.modelId ?? '') : '')+ const [model, setModel] = useState(tuca?.modelId ?? '')const [applying, setApplying] = useState(false)const [modelError, setModelError] = useState('')const typed = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)useEffect(() => setConv(session.id), [session.id])useEffect(() => {- if (build && !model && tuca?.modelId) setModel(tuca.modelId)- }, [build, model, tuca?.modelId])+ if (!model && tuca?.modelId) setModel(tuca.modelId)+ }, [model, tuca?.modelId])useEffect(() => () => clearTimeout(typed.current), [])const error = session.error ?? ''const messages = useStore((s) => (conv ? messagesIn(s, conv) : []))@@ -766,12 +356,10 @@ function MeetTuca({ conv: session, onUse, onManual, onBack }: { conv: { id?: strreturn (<div className="onb__split"><section className="onb__main">- <span className="onb__kicker">{build ? L('Tuca · Novo agente', 'Tuca · New agent') : L('Passo 6 · Seu primeiro agente', 'Step 6 · Your first agent')}</span>+ <span className="onb__kicker">{L('Tuca · Novo agente', 'Tuca · New agent')}</span><h1>{L('Conte pro Tuca o que você quer delegar', 'Tell Tuca what you want to delegate')}</h1><p className="onb__lead">- {build- ? L('Ele faz duas ou três perguntas e propõe um agente. Nada é criado sem você.', 'He asks two or three questions and proposes an agent. Nothing is created without you.')- : L('O Tuca monta os agentes do seu time. Ele faz duas ou três perguntas e propõe um; nada é criado sem você. Depois ele fica na barra lateral pra montar os próximos.', 'Tuca builds your team’s agents. He asks two or three questions and proposes one; nothing is created without you. Then he stays in the sidebar to build the next ones.')}+ {L('Ele faz duas ou três perguntas e propõe um agente. Nada é criado sem você.', 'He asks two or three questions and proposes an agent. Nothing is created without you.')}</p><div className="onb__field onb__field--tuca-model"><span>{L('Modelo do Tuca', 'Tuca’s model')}</span>@@ -792,17 +380,11 @@ function MeetTuca({ conv: session, onUse, onManual, onBack }: { conv: { id?: str<Composer conversationId={conv} members={[tuca]} placeholder={L('Ex.: quero alguém pra triar os tickets de suporte toda manhã', 'E.g. I want someone to triage the support tickets every morning')} /></UseDraft.Provider>) : (- <p className="muted onb-tuca__wait">{error || (applying || build ? L('Chamando o Tuca…', 'Calling Tuca…') : L('Escolha o modelo do Tuca acima pra começar.', 'Pick Tuca’s model above to start.'))}</p>+ <p className="muted onb-tuca__wait">{error || L('Chamando o Tuca…', 'Calling Tuca…')}</p>)}</div><div className="onb__nav">- {onBack ? (- <button className="btn btn--ghost" onClick={onBack}>- <Icon name="back" size={14} /> {L('Voltar', 'Back')}- </button>- ) : (- <span />- )}+ <span /><button className="btn btn--ghost" onClick={onManual}>{L('Prefiro montar eu mesmo', 'I’d rather build it myself')}</button>@@ -838,7 +420,7 @@ function MakeAgent(p: {return (<div className="onb__split"><section className="onb__main">- <span className="onb__kicker">{useContext(BuildMode) ? L('Novo agente', 'New agent') : L('Passo 6 · Seu primeiro agente', 'Step 6 · Your first agent')}</span>+ <span className="onb__kicker">{L('Novo agente', 'New agent')}</span><h1>{L('Quem vai trabalhar com você?', 'Who’s going to work with you?')}</h1><p className="onb__lead">{L('Comece por um dos exemplos e ajuste o que quiser. Depois você monta o resto do time.', 'Start from one of the examples and adjust anything. You build the rest of the team later.')}</p><div className="onb-templates">@@ -944,10 +526,12 @@ function Powers(p: {const name = agent.name.trim() || L('Ele', 'It')const connectors = useStore((s) => s.connectors)const isolated = useStore((s) => s.isolatedComputers)+ const settingsLevel = useStore((s) => s.settings.autonomy)+ const guard = useStore((s) => s.settings.outsideGuard ?? true)return (<div className="onb__split"><section className="onb__main">- <span className="onb__kicker">{useContext(BuildMode) ? L(`Novo agente · O que ${name} pode usar`, `New agent · What ${name} can use`) : L(`Passo 7 · O que ${name} pode usar`, `Step 7 · What ${name} can use`)}</span>+ <span className="onb__kicker">{L(`Novo agente · O que ${name} pode usar`, `New agent · What ${name} can use`)}</span><h1>{L('Dê ferramentas, não chaves.', 'Give tools, not keys.')}</h1><p className="onb__lead">{L('Ligue só o que a função pede. Tudo isso muda depois na página do agente, e cada ação aparece na conversa.', 'Turn on only what the role needs. All of this can change later on the agent’s page, and every action shows up in the conversation.')}</p><div className="onb-powers">@@ -1034,12 +618,7 @@ function Powers(p: {})}</div>)}- <div className="onb-guard">- <Icon name="shield" size={16} />- <p>- <strong>{L('Seja qual for a escolha,', 'Whatever you choose,')}</strong> {L('comprar, publicar, enviar e apagar viram um pedido de aprovação, com a ação exata. Nada disso acontece sem o seu ok.', 'buying, publishing, sending and deleting become an approval request, with the exact action. None of it happens without your OK.')}- </p>- </div>+ <AutonomyPick compact name={agent.name.trim() || L('o agente', 'the agent')} value={autonomyChosen(agent.autonomy, settingsLevel)} guard={guard} onPick={(level) => patch({ autonomy: storedAutonomy(level, settingsLevel) })} /><Nav onBack={p.onBack} onNext={p.onNext} /></section><aside className="onb__aside">@@ -1055,7 +634,7 @@ function FirstTask(p: {agent: Agenthandle: stringcomputer: Computer- channel: string+ manual: boolean // from the introduction: #geral, with the message waiting theretasks: string[]task: stringsetTask: (t: string) => void@@ -1065,21 +644,15 @@ function FirstTask(p: {onFinish: () => void}): ReactNode {const name = p.agent.name.trim()- const build = useContext(BuildMode)return (<div className="onb__split"><section className="onb__main">- <span className="onb__kicker">{build ? L('Novo agente · Mão na massa', 'New agent · Hands on') : L('Passo 8 · Mão na massa', 'Step 8 · Hands on')}</span>+ <span className="onb__kicker">{L('Novo agente · Mão na massa', 'New agent · Hands on')}</span><h1>{L(`O que ${name} faz primeiro?`, `What does ${name} do first?`)}</h1><p className="onb__lead">- {build ? (- <>{L(`Vou abrir uma conversa com ${name} e mandar o pedido.`, `I’ll open a conversation with ${name} and send the request.`)}</>- ) : (- <>- {L('Vou criar o canal', 'I’ll create the channel')} <b>#{p.channel}</b> {L(`com ${name} e mandar o pedido.`, `with ${name} and send the request.`)}- </>- )}{' '}- {L(`Você acompanha cada passo enquanto ${name} trabalha.`, `You follow every step while ${name} works.`)}+ {p.manual+ ? L(`Vou chamar ${name} pro canal #geral e deixar este pedido escrito lá. Você confere e aperta enviar.`, `I’ll bring ${name} into #general and leave this request written there. You check it and press send.`)+ : L(`Vou abrir uma conversa com ${name} e mandar o pedido. Você acompanha cada passo enquanto ${name} trabalha.`, `I’ll open a conversation with ${name} and send the request. You follow every step while ${name} works.`)}</p><div className="onb-tasks">{p.tasks.map((t) => (@@ -1103,7 +676,7 @@ function FirstTask(p: {disabled={!p.task.trim() || p.busy}next={<>- <Icon name="send" size={14} /> {L(`Criar ${name} e enviar`, `Create ${name} and send`)}+ {p.manual ? L(`Chamar ${name} pro time`, `Bring ${name} to the team`) : <><Icon name="send" size={14} /> {L(`Criar ${name} e enviar`, `Create ${name} and send`)}</>}</>}/>@@ -1114,158 +687,3 @@ function FirstTask(p: {</div>)}--// ---------- "Primeiros passos" ------------interface Item {- id: string- title: string- how: string- done: (s: State) => boolean- go?: (s: State) => View- open?: () => void- action: string-}--const firstChannel = (s: State): View => {- const c = s.conversations.find((x) => x.kind === 'channel')- return c ? { kind: 'conversation', id: c.id } : { kind: 'new-agent' }-}--const ITEMS = (): Item[] => [- { id: 'agent', title: L('Criar seu primeiro agente', 'Create your first agent'), how: L('Converse com o Tuca e ele monta um pra você.', 'Chat with Tuca and he builds one for you.'), done: (s) => s.agents.some(isTeam), go: () => ({ kind: 'tuca' }), action: L('Criar', 'Create') },- {- id: 'reply',- title: L('Ver um agente trabalhando', 'Watch an agent work'),- how: L('Mande uma tarefa e acompanhe cada passo na conversa.', 'Send a task and follow every step in the conversation.'),- done: anyReplyDone,- go: firstChannel,- action: L('Abrir canal', 'Open channel')- },- {- id: 'team',- title: L('Montar um time', 'Build a team'),- how: L('Crie um segundo agente e ponha os dois num canal: eles passam a vez com @menção.', 'Create a second agent and put both in a channel: they hand off with @mentions.'),- done: (s) => s.agents.filter(isTeam).length >= 2,- go: () => ({ kind: 'tuca' }),- action: L('Novo agente', 'New agent')- },- {- id: 'connector',- title: L('Conectar uma ferramenta', 'Connect a tool'),- how: L('Linear, GitHub, Notion… Cada agente só vê o que você liberar pra ele.', 'Linear, GitHub, Notion… Each agent only sees what you allow it.'),- done: (s) => s.connectors.length > 0,- go: () => ({ kind: 'connectors' }),- action: L('Conectores', 'Connectors')- },- {- id: 'memory',- title: L('Ensinar algo sobre você', 'Teach something about you'),- how: L('Uma coisa que todo agente deve lembrar, sempre.', 'Something every agent should always remember.'),- done: (s) => s.memories.some((m) => m.state === 'active'),- go: () => ({ kind: 'memory' }),- action: L('Memória', 'Memory')- },- {- id: 'routine',- title: L('Agendar uma rotina', 'Schedule a routine'),- how: L('Um agente trabalhando sozinho no dia e hora que você marcar.', 'An agent working on its own on the day and time you set.'),- done: (s) => s.routines.length > 0,- go: () => ({ kind: 'routines' }),- action: L('Rotinas', 'Routines')- },- {- id: 'approval',- title: L('Decidir uma aprovação', 'Decide an approval'),- how: L('Quando um agente quer enviar, publicar ou apagar, o pedido chega aqui com a ação exata.', 'When an agent wants to send, publish or delete, the request lands here with the exact action.'),- done: (s) => s.approvals.some((a) => a.state !== 'pending'),- go: () => ({ kind: 'approvals' }),- action: L('Aprovações', 'Approvals')- },- {- id: 'phone',- title: L('Aprovar pelo celular', 'Approve from your phone'),- how: L('Ligue o Telegram em Configurações e decida de qualquer lugar.', 'Turn on Telegram in Settings and decide from anywhere.'),- 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().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)- const count = done.filter(Boolean).length- const all = count === items.length- const nextIndex = done.indexOf(false)-- return (- <div className="getting">- {open && (- <div className="getting__pop" role="dialog" aria-label={L('Primeiros passos', 'Getting started')}>- <div className="getting__head">- <div>- <strong>{all ? L('Você conhece o Tucano inteiro', 'You know all of Tucano') : L('Primeiros passos', 'Getting started')}</strong>- <span className="muted small">- {L(`${count} de ${items.length} · cada um se marca sozinho quando você usa`, `${count} of ${items.length} · each one checks itself off when you use it`)}- </span>- </div>- <button className="icon-btn icon-btn--sm" title={L('Fechar', 'Close')} onClick={() => setOpen(false)}>- <Icon name="x" size={14} />- </button>- </div>- <ol className="getting__list">- {items.map((item, i) => (- <li key={item.id} className={`${done[i] ? 'is-done' : ''} ${i === nextIndex ? 'is-next' : ''}`}>- <span className="getting__check">{done[i] && <Icon name="check" size={12} />}</span>- <div className="grow">- <strong>{item.title}</strong>- {i === nextIndex && <span className="muted small">{item.how}</span>}- </div>- {!done[i] && (- <button- className={`btn btn--sm ${i === nextIndex ? 'btn--primary' : ''}`}- onClick={() => {- if (item.open) item.open()- else if (item.go) navigate(item.go(getState()))- setOpen(false)- }}- >- {item.action}- </button>- )}- </li>- ))}- </ol>- <div className="getting__foot">- <button className="link small" onClick={() => updateSettings({ onboarding: { ...(onboarding ?? { done: true }), checklistHidden: true } })}>- {L('Esconder a lista', 'Hide the list')}- </button>- <span className="muted small">{L('Volta em Configurações.', 'Bring it back in Settings.')}</span>- </div>- </div>- )}- <button className={`getting__bar ${all ? 'is-all' : ''}`} onClick={() => setOpen(!open)}>- <span className="getting__label">- <Icon name={all ? 'check' : 'spark'} size={14} /> {L('Primeiros passos', 'Getting started')}- <span className="muted">- {count}/{items.length}- </span>- </span>- <span className="getting__track">- <span style={{ transform: `scaleX(${count / items.length})` }} />- </span>- </button>- </div>- )-}diff --git a/src/renderer/src/components/Pages.tsx b/src/renderer/src/components/Pages.tsxindex 28c076c..e49b68a 100644--- a/src/renderer/src/components/Pages.tsx+++ b/src/renderer/src/components/Pages.tsx@@ -1037,6 +1037,18 @@ function LentFolders({ agentId }: { agentId: string }): ReactNode {)}+// Before an agent (or every agent) goes with no guardrails: here, in Settings and in the introduction.+export const confirmNoGuardrails = (): Promise<boolean> =>+ confirmDialog({+ title: L('Deixar agir sem travas?', 'Let it act with no guardrails?'),+ body: L(+ 'Envia, apaga, publica, paga e clica sem te perguntar. Continua pedindo o que você marcou como alto risco e, com a proteção ligada, o que vai pra fora depois de ler algo de fora. Tudo fica nos passos de cada resposta.',+ 'It sends, deletes, publishes, pays and clicks without asking you. It still asks for what you marked high risk and, with the guard on, for what goes out after reading something from outside. Everything stays in each reply’s steps.'+ ),+ confirm: L('Sem travas', 'No guardrails'),+ danger: true+ })+// How far an agent goes on its own (in Settings, every agent): a level, the outside-content guard, and a rule// per kind of action for whoever wants it finer. On an agent's page, `inherited` is Settings and "Padrão"// follows them. `readOnly`: someone who only looks at the agent.@@ -1048,16 +1060,7 @@ function AutonomyControls({ own, inherited, perAgent, readOnly, onChange }: { owconst guard = own.outsideGuard ?? inherited?.outsideGuard ?? trueconst pick = async (next: Autonomy | undefined): Promise<void> => {if ((next ?? inherited?.autonomy) === 'free' && effective !== 'free') {- const ok = await confirmDialog({- title: L('Deixar agir sem travas?', 'Let it act with no guardrails?'),- body: L(- 'Envia, apaga, publica, paga e clica sem te perguntar. Continua pedindo o que você marcou como alto risco e, com a proteção ligada, o que vai pra fora depois de ler algo de fora. Tudo fica nos passos de cada resposta.',- 'It sends, deletes, publishes, pays and clicks without asking you. It still asks for what you marked high risk and, with the guard on, for what goes out after reading something from outside. Everything stays in each reply’s steps.'- ),- confirm: L('Sem travas', 'No guardrails'),- danger: true- })- if (!ok) return+ if (!(await confirmNoGuardrails())) return}onChange({ autonomy: next })}@@ -1373,7 +1376,7 @@ export function HistoryRow({ id }: { id: string }): ReactNode {const CLASS_LABEL = (): Record<ToolClass, string> => ({ read: L('leitura', 'read'), write: L('escrita', 'write'), sensitive: L('sensível', 'sensitive') })-const STATUS = (): Record<Connector['status'], { label: string; tone: string }> => ({+export const STATUS = (): Record<Connector['status'], { label: string; tone: string }> => ({connected: { label: L('conectado', 'connected'), tone: 'tag--ok' },connecting: { label: L('conectando…', 'connecting…'), tone: '' },needs_auth: { label: L('precisa autorizar', 'needs authorization'), tone: 'tag--warn' },@@ -2273,12 +2276,18 @@ export function SettingsPage(): ReactNode {<textarea rows={5} value={settings.context} onChange={(e) => updateSettings({ context: e.target.value })} /></Field><div className="row">- <button className="btn btn--sm" onClick={() => updateSettings({ onboarding: { done: false } })}>+ {/* What the person already set (the short sidebar, the tour) stays as it was. */}+ <button className="btn btn--sm" onClick={() => updateSettings({ onboarding: { ...settings.onboarding, done: false } })}>{L('Rever a introdução', 'See the introduction again')}</button>{settings.onboarding?.checklistHidden && (- <button className="btn btn--sm" onClick={() => updateSettings({ onboarding: { done: true } })}>- {L('Mostrar os primeiros passos', 'Show getting started')}+ <button className="btn btn--sm" onClick={() => updateSettings({ onboarding: { ...settings.onboarding, done: true, checklistHidden: false } })}>+ {L('Mostrar as missões', 'Show the missions')}+ </button>+ )}+ {settings.onboarding?.fresh && !settings.onboarding.showAll && (+ <button className="btn btn--sm" onClick={() => updateSettings({ onboarding: { ...settings.onboarding!, showAll: true } })}>+ {L('Mostrar a barra lateral inteira', 'Show the whole sidebar')}</button>)}</div>diff --git a/src/renderer/src/components/Sidebar.tsx b/src/renderer/src/components/Sidebar.tsxindex 3d17c0e..d0fa223 100644--- a/src/renderer/src/components/Sidebar.tsx+++ b/src/renderer/src/components/Sidebar.tsx@@ -32,11 +32,12 @@ import {type State,type View} from '../store'+import type { SidebarPart } from '../../../shared/onboarding'import { addGroup, arrange, moveChannel, nudgeChannel, removeGroup, renameGroup, type ChannelLayout } from '../../../shared/channel-layout'import { call } from '../rpc'import { ContextMenu, confirmDialog, type MenuItem, type MenuState } from './Dialogs'import { FoldToggle, useFold } from './Fold'-import { GettingStarted } from './Onboarding'+import { MissionsCard, useSidebarParts } from './Missions'import { UpdateNote } from './Update'import { WorkspaceSelector } from './Workspaces'import { AgentAvatar, Icon, MeAvatar, TucaMark, useJustEnded, type IconName } from './ui'@@ -44,16 +45,19 @@ import { AgentAvatar, Icon, MeAvatar, TucaMark, useJustEnded, type IconName } fr// The wiki stays lit on any of its pages.const same = (a: View | null, b: View): boolean => (b.kind === 'wiki' ? a?.kind === 'wiki' : JSON.stringify(a) === JSON.stringify(b))-function NavItem({ view, icon, label, badge }: { view: View; icon: IconName; label: string; badge?: number }): ReactNode {+// `fresh`: a mission just brought it (a new install's short sidebar): tagged until it's opened.+function NavItem({ view, icon, label, badge, fresh }: { view: View; icon: IconName; label: string; badge?: number; fresh?: () => void }): ReactNode {const active = useStore((s) => same(s.view, view))return (- <button className={`nav-item ${active ? 'is-active' : ''}`} onClick={() => navigate(view)}>+ <button className={`nav-item ${active ? 'is-active' : ''} ${fresh ? 'is-fresh' : ''}`} onClick={() => (fresh?.(), navigate(view))}><Icon name={icon} /><span className="nav-item__label">{label}</span>{badge ? (<span key={badge} className="badge">{badge}</span>+ ) : fresh ? (+ <span className="nav-item__new">{L('NOVO', 'NEW')}</span>) : null}</button>)@@ -62,7 +66,7 @@ function NavItem({ view, icon, label, badge }: { view: View; icon: IconName; lab// The Tuca is a screen, not one of the agents: here at the top, and behind the "+" for a new agent.function TucaItem(): ReactNode {return (- <button className="nav-item" onClick={openTuca} title={L('Monte um agente conversando com o Tuca', 'Build an agent by chatting with Tuca')}>+ <button className="nav-item" data-coach="tuca" onClick={openTuca} title={L('Monte um agente conversando com o Tuca', 'Build an agent by chatting with Tuca')}><TucaMark size={18} /><span className="nav-item__label">Tuca</span><span className="nav-item__meta">{L('te ajuda', 'helps you')}</span>@@ -151,6 +155,9 @@ export function Sidebar(): ReactNode {const admin = amAdmin({ people, you })const owner = amOwner({ people, you })const me = youPerson({ people, you })+ // A new install's sidebar starts short and grows with the missions (Missions.tsx).+ const parts = useSidebarParts()+ const fresh = (p: SidebarPart): (() => void) | undefined => (parts.fresh(p) ? () => parts.seen(p) : undefined)const pending = useStore((s) => (teamMode(s) ? inboxCount(s) : pendingApprovals(s).length))const suggestions = useStore((s) => pendingMemories(s).length)const proposals = useStore((s) => s.skills.filter((k) => k.state === 'pending').length)@@ -332,11 +339,11 @@ export function Sidebar(): ReactNode {<nav className="sidebar__scroll"><TucaItem /><NavItem view={{ kind: 'approvals' }} icon="shield" label={team ? L('Pra você', 'For you') : L('Aprovações', 'Approvals')} badge={pending} />- <NavItem view={{ kind: 'memory' }} icon="book" label={L('Memória', 'Memory')} badge={suggestions} />- <NavItem view={{ kind: 'wiki' }} icon="layers" label="Wiki" />- <NavItem view={{ kind: 'routines' }} icon="clock" label={L('Rotinas', 'Routines')} />- <NavItem view={{ kind: 'skills' }} icon="layers" label="Skills" badge={proposals} />- {admin && <NavItem view={{ kind: 'report' }} icon="report" label={L('Boletim', 'Report')} />}+ {(parts.shows('memory') || suggestions > 0) && <NavItem view={{ kind: 'memory' }} icon="book" label={L('Memória', 'Memory')} badge={suggestions} fresh={fresh('memory')} />}+ {parts.shows('wiki') && <NavItem view={{ kind: 'wiki' }} icon="layers" label="Wiki" fresh={fresh('wiki')} />}+ {parts.shows('routines') && <NavItem view={{ kind: 'routines' }} icon="clock" label={L('Rotinas', 'Routines')} fresh={fresh('routines')} />}+ {(parts.shows('skills') || proposals > 0) && <NavItem view={{ kind: 'skills' }} icon="layers" label="Skills" badge={proposals} fresh={fresh('skills')} />}+ {admin && parts.shows('report') && <NavItem view={{ kind: 'report' }} icon="report" label={L('Boletim', 'Report')} fresh={fresh('report')} />}<Sectionid="channels"@@ -344,9 +351,11 @@ export function Sidebar(): ReactNode {unread={unreadIn(channels)}waiting={channelsWaiting}action={- <button className="icon-btn icon-btn--sm" title={L(`Novo canal (${shortcut(platform, 'N')})`, `New channel (${shortcut(platform, 'N')})`)} onClick={() => openDialog({ kind: 'new-channel' })}>- <Icon name="plus" size={14} />- </button>+ parts.shows('channels') ? (+ <button className="icon-btn icon-btn--sm" title={L(`Novo canal (${shortcut(platform, 'N')})`, `New channel (${shortcut(platform, 'N')})`)} onClick={() => (parts.seen('channels'), openDialog({ kind: 'new-channel' }))}>+ <Icon name="plus" size={14} />+ </button>+ ) : undefined}>{arranged.loose.map((c) => channelRow(c))}@@ -434,13 +443,13 @@ export function Sidebar(): ReactNode {</Section></nav>- {/* The introduction's checklist sets the Tucano up (and its phone): the owner's. */}- {owner && settings.onboarding?.done && !settings.onboarding.checklistHidden && <GettingStarted />}+ {/* The missions set the Tucano up and walk through it: the owner's. */}+ {owner && settings.onboarding?.done && !settings.onboarding.checklistHidden && <MissionsCard />}<ContextMenu menu={menu} onClose={closeMenu} /><div className="sidebar__foot"><UpdateNote />- {admin && <NavItem view={{ kind: 'usage' }} icon="chart" label={L('Uso e limites', 'Usage and limits')} />}- <NavItem view={{ kind: 'connectors' }} icon="plug" label={L('Conectores', 'Connectors')} />+ {admin && parts.shows('usage') && <NavItem view={{ kind: 'usage' }} icon="chart" label={L('Uso e limites', 'Usage and limits')} fresh={fresh('usage')} />}+ {parts.shows('connectors') && <NavItem view={{ kind: 'connectors' }} icon="plug" label={L('Conectores', 'Connectors')} fresh={fresh('connectors')} />}<NavItem view={{ kind: 'settings' }} icon="gear" label={L('Configurações', 'Settings')} /></div></aside>diff --git a/src/renderer/src/engine-logos.ts b/src/renderer/src/engine-logos.tsnew file mode 100644index 0000000..7eca6aa--- /dev/null+++ b/src/renderer/src/engine-logos.ts@@ -0,0 +1,20 @@+// The harnesses' marks, for the introduction and Settings: 24×24 paths, each on its brand color, kept+// here (nothing loads from the network). Simple Icons is CC0 1.0 (https://simpleicons.org); the marks stay+// their owners' trademarks, used only to name the program. Grok has no mark in Simple Icons and xAI+// publishes no brand kit with a license we could confirm, so it keeps its initial.+import type { EngineId } from '../../shared/types'++export const ENGINE_LOGOS: Partial<Record<EngineId, { hex: string; path: string }>> = {+ // Simple Icons 16.36.0 `claude` (source: claude.ai)+ claude: { hex: 'D97757', path: 'm4.7144 15.9555 4.7174-2.6471.079-.2307-.079-.1275h-.2307l-.7893-.0486-2.6956-.0729-2.3375-.0971-2.2646-.1214-.5707-.1215-.5343-.7042.0546-.3522.4797-.3218.686.0608 1.5179.1032 2.2767.1578 1.6514.0972 2.4468.255h.3886l.0546-.1579-.1336-.0971-.1032-.0972L6.973 9.8356l-2.55-1.6879-1.3356-.9714-.7225-.4918-.3643-.4614-.1578-1.0078.6557-.7225.8803.0607.2246.0607.8925.686 1.9064 1.4754 2.4893 1.8336.3643.3035.1457-.1032.0182-.0728-.164-.2733-1.3539-2.4467-1.445-2.4893-.6435-1.032-.17-.6194c-.0607-.255-.1032-.4674-.1032-.7285L6.287.1335 6.6997 0l.9957.1336.419.3642.6192 1.4147 1.0018 2.2282 1.5543 3.0296.4553.8985.2429.8318.091.255h.1579v-.1457l.1275-1.706.2368-2.0947.2307-2.6957.0789-.7589.3764-.9107.7468-.4918.5828.2793.4797.686-.0668.4433-.2853 1.8517-.5586 2.9021-.3643 1.9429h.2125l.2429-.2429.9835-1.3053 1.6514-2.0643.7286-.8196.85-.9046.5464-.4311h1.0321l.759 1.1293-.34 1.1657-1.0625 1.3478-.8804 1.1414-1.2628 1.7-.7893 1.36.0729.1093.1882-.0183 2.8535-.607 1.5421-.2794 1.8396-.3157.8318.3886.091.3946-.3278.8075-1.967.4857-2.3072.4614-3.4364.8136-.0425.0304.0486.0607 1.5482.1457.6618.0364h1.621l3.0175.2247.7892.522.4736.6376-.079.4857-1.2142.6193-1.6393-.3886-3.825-.9107-1.3113-.3279h-.1822v.1093l1.0929 1.0686 2.0035 1.8092 2.5075 2.3314.1275.5768-.3218.4554-.34-.0486-2.2039-1.6575-.85-.7468-1.9246-1.621h-.1275v.17l.4432.6496 2.3436 3.5214.1214 1.0807-.17.3521-.6071.2125-.6679-.1214-1.3721-1.9246L14.38 17.959l-1.1414-1.9428-.1397.079-.674 7.2552-.3156.3703-.7286.2793-.6071-.4614-.3218-.7468.3218-1.4753.3886-1.9246.3157-1.53.2853-1.9004.17-.6314-.0121-.0425-.1397.0182-1.4328 1.9672-2.1796 2.9446-1.7243 1.8456-.4128.164-.7164-.3704.0667-.6618.4008-.5889 2.386-3.0357 1.4389-1.882.929-1.0868-.0062-.1579h-.0546l-6.3385 4.1164-1.1293.1457-.4857-.4554.0608-.7467.2307-.2429 1.9064-1.3114Z' },+ // Simple Icons `openai` (as in site/assets/logos/openai.svg; dropped from later Simple Icons releases)+ codex: { hex: '10A37F', path: 'M22.2819 9.8211a5.9847 5.9847 0 0 0-.5157-4.9108 6.0462 6.0462 0 0 0-6.5098-2.9A6.0651 6.0651 0 0 0 4.9807 4.1818a5.9847 5.9847 0 0 0-3.9977 2.9 6.0462 6.0462 0 0 0 .7427 7.0966 5.98 5.98 0 0 0 .511 4.9107 6.051 6.051 0 0 0 6.5146 2.9001A5.9847 5.9847 0 0 0 13.2599 24a6.0557 6.0557 0 0 0 5.7718-4.2058 5.9894 5.9894 0 0 0 3.9977-2.9001 6.0557 6.0557 0 0 0-.7475-7.0729zm-9.022 12.6081a4.4755 4.4755 0 0 1-2.8764-1.0408l.1419-.0804 4.7783-2.7582a.7948.7948 0 0 0 .3927-.6813v-6.7369l2.02 1.1686a.071.071 0 0 1 .038.052v5.5826a4.504 4.504 0 0 1-4.4945 4.4944zm-9.6607-4.1254a4.4708 4.4708 0 0 1-.5346-3.0137l.142.0852 4.783 2.7582a.7712.7712 0 0 0 .7806 0l5.8428-3.3685v2.3324a.0804.0804 0 0 1-.0332.0615L9.74 19.9502a4.4992 4.4992 0 0 1-6.1408-1.6464zM2.3408 7.8956a4.485 4.485 0 0 1 2.3655-1.9728V11.6a.7664.7664 0 0 0 .3879.6765l5.8144 3.3543-2.0201 1.1685a.0757.0757 0 0 1-.071 0l-4.8303-2.7865A4.504 4.504 0 0 1 2.3408 7.872zm16.5963 3.8558L13.1038 8.364 15.1192 7.2a.0757.0757 0 0 1 .071 0l4.8303 2.7913a4.4944 4.4944 0 0 1-.6765 8.1042v-5.6772a.79.79 0 0 0-.407-.667zm2.0107-3.0231l-.142-.0852-4.7735-2.7818a.7759.7759 0 0 0-.7854 0L9.409 9.2297V6.8974a.0662.0662 0 0 1 .0284-.0615l4.8303-2.7866a4.4992 4.4992 0 0 1 6.6802 4.66zM8.3065 12.863l-2.02-1.1638a.0804.0804 0 0 1-.038-.0567V6.0742a4.4992 4.4992 0 0 1 7.3757-3.4537l-.142.0805L8.704 5.459a.7948.7948 0 0 0-.3927.6813zm1.0976-2.3654l2.602-1.4998 2.6069 1.4998v2.9994l-2.5974 1.4997-2.6067-1.4997Z' },+ // Simple Icons 16.36.0 `opencode` (source: OpenCode repo, packages/identity/mark.svg)+ opencode: { hex: '211E1B', path: 'M22 24H2V0h20zM17 4.8H7v14.4h10z' },+ // Simple Icons 16.36.0 `pi` (source: pi.dev/favicon.svg)+ pi: { hex: '211E1B', path: 'M0 0v24h6v-6h6v-6H6V6h6v6h6V0Zm18 12v12h6V12Z' },+ // Simple Icons 16.36.0 `googlegemini` (source: gemini.google.com)+ gemini: { hex: '8E75B2', path: 'M11.04 19.32Q12 21.51 12 24q0-2.49.93-4.68.96-2.19 2.58-3.81t3.81-2.55Q21.51 12 24 12q-2.49 0-4.68-.93a12.3 12.3 0 0 1-3.81-2.58 12.3 12.3 0 0 1-2.58-3.81Q12 2.49 12 0q0 2.49-.96 4.68-.93 2.19-2.55 3.81a12.3 12.3 0 0 1-3.81 2.58Q2.49 12 0 12q2.49 0 4.68.96 2.19.93 3.81 2.55t2.55 3.81' },+ // Simple Icons 16.36.0 `cursor` (source: cursor.com/brand)+ cursor: { hex: '211E1B', path: 'M11.503.131 1.891 5.678a.84.84 0 0 0-.42.726v11.188c0 .3.162.575.42.724l9.609 5.55a1 1 0 0 0 .998 0l9.61-5.55a.84.84 0 0 0 .42-.724V6.404a.84.84 0 0 0-.42-.726L12.497.131a1.01 1.01 0 0 0-.996 0M2.657 6.338h18.55c.263 0 .43.287.297.515L12.23 22.918c-.062.107-.229.064-.229-.06V12.335a.59.59 0 0 0-.295-.51l-9.11-5.257c-.109-.063-.064-.23.061-.23' }+}diff --git a/src/renderer/src/main.tsx b/src/renderer/src/main.tsxindex 6b312e6..6513536 100644--- a/src/renderer/src/main.tsx+++ b/src/renderer/src/main.tsx@@ -5,6 +5,7 @@ import { App } from './App'import { ServerBar } from './components/Servers'import { start, useStore } from './store'import '@fontsource-variable/inter/opsz.css'+import '@fontsource-variable/nunito/wght.css' // the first run's headingsimport './styles.css'void start()diff --git a/src/renderer/src/store.ts b/src/renderer/src/store.tsindex 4b4063b..0c12d33 100644--- a/src/renderer/src/store.ts+++ b/src/renderer/src/store.ts@@ -39,6 +39,8 @@ import {type Routine,type RoutineInput,type Settings,+ type SetupEngine,+ type SetupState,type Skill,type SkillInput,type SkillVersion,@@ -69,6 +71,7 @@ export type View =| { kind: 'skills' }| { kind: 'report' }| { kind: 'settings' }+ | { kind: 'missions' } // what to try next, each bringing a part of the sidebar on a new installexport interface State {webhookPort: number@@ -760,6 +763,10 @@ export const addAccount = (engine: AccountEngine, name: string): Promise<Accountexport const loginAccount = (id: string): Promise<{ opened: boolean; command: string }> => call('loginAccount', { id })export const removeAccount = (id: string): Promise<void> => call('removeAccount', { id })export const installEngine = (engine: keyof Settings['engines']): Promise<{ opened: boolean; command: string; needsNode?: boolean }> => call('installEngine', { engine })+// Codex or Claude Code with no terminal (the introduction): the CLI downloaded, then its own sign-in in the browser.+export const setupEngine = (engine: SetupEngine): Promise<SetupState> => call('setupEngine', { engine })+export const engineSetupState = (): Promise<SetupState | null> => call('engineSetupState')+export const cancelEngineSetup = (): void => void call('cancelEngineSetup').catch(() => {})// The person's own apps, through agent-desktop.export const desktopStatus = (): Promise<{ installed: boolean; version?: string; accessibility?: string; suggestion?: string; server?: boolean }> => call('desktopStatus')export type InstalledApp = { name: string; bundleId?: string; path?: string; running?: boolean; icon?: string }@@ -941,7 +948,7 @@ export const openExternal = (url: string): void =>export const saveRoutine = (routine: RoutineInput): Promise<Routine> => call('saveRoutine', { routine })export const setJevKey = (key: string | null): Promise<void> => call('setJevKey', { key })export const engineModels = (engine: EngineId): Promise<{ models: string[]; labels?: Record<string, { label: string; hint?: string }>; error?: string }> => call('engineModels', { engine })-export const testEngine = (model: string): Promise<{ ok: boolean; message: string }> => call('testEngine', { model })+export const testEngine = (model: string): Promise<{ ok: boolean; message: string; seconds?: number }> => call('testEngine', { model })export const saveSkill = (skill: SkillInput): Promise<Skill> => call('saveSkill', { skill })export const localSkills = (): Promise<LocalSkill[]> => call('localSkills')export const linkSkill = (source: string, agents: string[] = []): Promise<Skill> => call('linkSkill', { source, agents })diff --git a/src/renderer/src/styles.css b/src/renderer/src/styles.cssindex 689dd78..6e993f0 100644--- a/src/renderer/src/styles.css+++ b/src/renderer/src/styles.css@@ -908,8 +908,7 @@ h3 {.icon-btn:active,.segmented button:active,.days button:active,-.cal-nav button:active:not(:disabled),-.onb-chip:active {+.cal-nav button:active:not(:disabled) {transform: scale(0.97);transition-duration: var(--dur-instant);}@@ -4146,9 +4145,6 @@ table.csv th {.onb__main {max-width: 620px;}-.onb__main--wide {- max-width: 820px;-}.onb__aside {position: sticky;top: 12px;@@ -4162,10 +4158,6 @@ table.csv th {align-self: flex-start;width: fit-content;}-.onb__lang {- display: flex;- margin-bottom: 22px;-}.onb__kicker {display: inline-block;font-size: 12.5px;@@ -4188,28 +4180,6 @@ table.csv th {margin: 0 0 24px;max-width: 580px;}-.onb__points {- list-style: none;- padding: 0;- margin: 0 0 28px;- display: grid;- gap: 14px;-}-.onb__points li {- display: flex;- gap: 12px;- align-items: flex-start;-}-.onb__points li > span:last-child {- display: flex;- flex-direction: column;- color: var(--text-2);-}-.onb__points strong {- color: var(--text);- font-weight: 600;-}-.onb__point-icon,.onb-power-row__icon,.onb-engine__icon {flex: none;@@ -4233,15 +4203,10 @@ table.csv th {font-weight: 600;}.onb__field input,-.onb__field textarea,-.onb__textarea {+.onb__field textarea {font-size: 15px;padding: 10px 12px;}-.onb__textarea {- width: 100%;- margin-bottom: 10px;-}.onb__row {display: flex;gap: 12px;@@ -4258,97 +4223,6 @@ table.csv th {border-radius: 10px;gap: 8px;}-.onb__chips {- display: flex;- flex-wrap: wrap;- gap: 8px;- margin-bottom: 12px;-}-.onb-chip {- display: inline-flex;- align-items: center;- gap: 4px;- font-size: 12.5px;- padding: 5px 10px;- border-radius: 999px;- border: 1px solid var(--border-strong);- color: var(--text-2);- background: var(--panel);-}-.onb-chip:hover {- border-color: var(--accent);- color: var(--accent);-}-.onb__wait {- display: flex;- align-items: center;- gap: 8px;- color: var(--text-2);- font-size: 13px;- margin: 16px 0 0;-}--/* the still of a channel on the welcome screen */-.onb-chat {- background: var(--panel);- border: 1px solid var(--border);- border-radius: 16px;- box-shadow: var(--shadow-lg);- padding: 4px 0 14px;-}-.onb-chat__head {- display: flex;- align-items: center;- gap: 6px;- font-weight: 600;- padding: 10px 16px;- border-bottom: 1px solid var(--border);- margin-bottom: 6px;-}-.onb-chat__msg {- display: flex;- gap: 10px;- padding: 8px 16px;- font-size: 13px;-}-.onb-chat__msg b {- font-weight: 600;-}-.onb-chat__msg p {- margin: 2px 0 0;- color: var(--text);-}-.onb-chat__step {- display: flex;- align-items: center;- gap: 5px;- font-size: 11.5px;- color: var(--text-3);- margin-top: 2px;-}-.onb-chat__approval {- display: flex;- align-items: center;- gap: 8px;- margin-top: 8px;- padding: 8px 10px;- border-radius: 10px;- background: var(--warn-soft);- color: var(--warn);- font-size: 12.5px;- font-weight: 500;-}-.onb-chat__approval span:nth-child(2) {- flex: 1;- color: var(--text);-}-.onb-chat__btn {- background: var(--accent);- color: var(--accent-text);- border-radius: 6px;- padding: 2px 10px;- font-weight: 600;-}/* engines */.onb-engines {@@ -4590,21 +4464,6 @@ table.csv th {border-radius: 8px;padding: 8px 10px;}-.onb-guard {- display: flex;- gap: 10px;- margin-top: 16px;- padding: 12px 14px;- border-radius: 12px;- background: var(--accent-soft);- color: var(--accent);-}-.onb-guard p {- margin: 0;- color: var(--text);- font-size: 13px;-}-/* the first task */.onb-tasks {display: grid;@@ -4668,153 +4527,11 @@ table.csv th {grid-template-columns: repeat(3, 1fr);}}--/* "Primeiros passos" in the sidebar */-.getting {- position: relative;- padding: 0 8px 8px;-}-.getting__bar {- position: relative;- overflow: hidden;- display: flex;- flex-direction: column;- gap: 7px;- width: 100%;- padding: 10px 12px;- border-radius: 10px;- background: var(--panel);- border: 1px solid var(--border);- box-shadow: var(--shadow);-}-.getting__bar:hover {- border-color: var(--border-strong);-}-.getting__label {- display: flex;- align-items: center;- gap: 6px;- font-size: 13px;- font-weight: 600;- color: var(--accent);-}-.getting__label .muted {- margin-left: auto;- font-weight: 500;-}-.getting__bar.is-all .getting__label {- color: var(--ok);-}-/* All done: one gentle shine crosses the bar. */-.getting__bar.is-all::after {- content: '';- position: absolute;- inset: 0;- background: linear-gradient(100deg, transparent 30%, color-mix(in srgb, var(--ok) 22%, transparent) 50%, transparent 70%);- transform: translateX(-100%);- pointer-events: none;- animation: shine 1.2s var(--ease-in-out) 300ms forwards;-}@keyframes shine {to {transform: translateX(100%);}}-.getting__track {- height: 4px;- border-radius: 2px;- background: var(--border);- overflow: hidden;-}-.getting__track span {- display: block;- width: 100%;- height: 100%;- background: var(--accent);- transform-origin: left;- transition: transform var(--dur-slow) var(--ease-out), background-color var(--dur-base) var(--ease-out);-}-.getting__bar.is-all .getting__track span {- background: var(--ok);-}-.getting__pop {- position: fixed;- left: 12px;- bottom: 168px;- width: 360px;- max-height: calc(100vh - 240px);- overflow-y: auto;- background: var(--panel);- border: 1px solid var(--border);- border-radius: 14px;- box-shadow: var(--shadow-lg);- z-index: 40;- transform-origin: bottom left;- animation: pop var(--dur-base) var(--ease-out) both;-}-.getting__head {- display: flex;- justify-content: space-between;- align-items: flex-start;- padding: 14px 16px 10px;-}-.getting__head > div {- display: flex;- flex-direction: column;-}-.getting__list {- list-style: none;- margin: 0;- padding: 0 8px;-}-.getting__list li {- display: flex;- align-items: center;- gap: 10px;- padding: 9px 8px;- border-radius: 10px;-}-.getting__list li.is-next {- background: var(--accent-soft);-}-.getting__list li > div {- display: flex;- flex-direction: column;- font-size: 13px;-}-.getting__list li.is-done strong {- color: var(--text-3);- text-decoration: line-through;- font-weight: 500;-}-.getting__check {- flex: none;- display: grid;- place-items: center;- width: 20px;- height: 20px;- border-radius: 50%;- border: 1.5px solid var(--border-strong);- color: #fff;-}-.getting__list li.is-done .getting__check {- background: var(--ok);- border-color: var(--ok);- --pop-scale: 0.5;- --pop-y: 0;- animation: pop var(--dur-enter) var(--ease-spring) backwards;-}-/* Its check draws itself, a beat after the circle lands. */-.getting__check path {- stroke-dasharray: 26;- animation: draw 300ms var(--ease-out) 120ms backwards;-}-.getting__foot {- display: flex;- justify-content: space-between;- align-items: center;- padding: 10px 16px 14px;-}/* ---------- splash (the opening of the introduction: the forest, in short) ---------- */.splash {@@ -4901,177 +4618,37 @@ table.csv th {-webkit-box-orient: vertical;overflow: hidden;}--/* introduction: the setup steps */-.onb-note {- display: flex;- align-items: center;- gap: 8px;- padding: 10px 14px;- border-radius: 10px;- background: var(--accent-soft);- color: var(--text);- font-size: 13.5px;- margin: 0 0 18px;+/* The default window (1280×820) is short: tighten the introduction so its button fits without scrolling. */+@media (max-height: 900px) {+ .onb__top {+ padding-top: 30px;+ }+ .onb__stage {+ padding: 14px 40px 24px;+ }+ .onb__aside {+ padding-top: 24px;+ }+ .onb__kicker {+ margin-bottom: 6px;+ }+ .onb h1 {+ font-size: 27px;+ margin-bottom: 8px;+ }+ .onb__lead {+ font-size: 15px;+ margin-bottom: 16px;+ }+ .onb__field {+ margin-bottom: 12px;+ }}-.onb-note .icon {- color: var(--accent);- flex: none;+.onb-custom {+ margin-top: 10px;}-.onb-pair {- display: grid;- grid-template-columns: 1fr 1fr;- gap: 14px;-}-.onb-pick {- display: flex;- flex-direction: column;- gap: 8px;- padding: 18px;- border-radius: 14px;- border: 1px solid var(--border);- background: var(--panel);-}-.onb-pick strong {- font-size: 15px;-}-.onb-pick p {- margin: 0 0 6px;- color: var(--text-2);- font-size: 13px;- flex: 1;-}-.onb-pick__icon {- display: grid;- place-items: center;- width: 32px;- height: 32px;- border-radius: 9px;- background: var(--accent-soft);- color: var(--accent);-}-.onb-conns {- display: flex;- flex-direction: column;- border: 1px solid var(--border);- border-radius: 12px;- background: var(--panel);- margin-bottom: 16px;-}-.onb-conn {- display: flex;- align-items: center;- gap: 10px;- padding: 12px 14px;- border-bottom: 1px solid var(--border);-}-.onb-conn:last-child {- border-bottom: 0;-}-.onb-add {- padding: 18px;- border-radius: 14px;- border: 1px dashed var(--border-strong);- background: var(--panel);-}-.onb-add .onb__field {- margin-bottom: 12px;-}-/* The default window (1280×820) is short: tighten the introduction so its button fits without scrolling. */-@media (max-height: 900px) {- .onb__top {- padding-top: 30px;- }- .onb__stage {- padding: 14px 40px 24px;- }- .onb__aside {- padding-top: 24px;- }- .onb__kicker {- margin-bottom: 6px;- }- .onb h1 {- font-size: 27px;- margin-bottom: 8px;- }- .onb__lead {- font-size: 15px;- margin-bottom: 16px;- }- .onb__points {- gap: 9px;- margin-bottom: 18px;- }- .onb__field {- margin-bottom: 12px;- }-}-.onb__field--narrow {- flex: 0 0 200px;-}-.onb__row--center {- align-items: center;- margin-bottom: 4px;-}-.onb-add .hint {- margin: 10px 0 0;-}-.onb-skills {- display: grid;- grid-template-columns: 1fr 1fr;- gap: 10px;-}-.onb-skill {- display: flex;- gap: 12px;- align-items: flex-start;- text-align: left;- padding: 14px;- border-radius: 12px;- border: 1px solid var(--border);- background: var(--panel);-}-.onb-skill.is-active {- border-color: var(--accent);- box-shadow: 0 0 0 3px var(--accent-soft);-}-.onb-skill strong {- font-size: 14px;-}-.onb-skill__check {- flex: none;- display: grid;- place-items: center;- width: 20px;- height: 20px;- margin-top: 1px;- border-radius: 6px;- border: 1.5px solid var(--border-strong);- color: #fff;-}-.onb-skill.is-active .onb-skill__check {- background: var(--accent);- border-color: var(--accent);-}-.onb-skill__desc {- display: -webkit-box;- -webkit-line-clamp: 2;- -webkit-box-orient: vertical;- overflow: hidden;- margin-top: 4px;- font-size: 12.5px;- color: var(--text-2);-}-.onb-skill .warn-text {- display: block;- margin-top: 4px;-}-.onb-custom {- margin-top: 10px;-}-.onb-custom select {- flex: 0 0 160px;+.onb-custom select {+ flex: 0 0 160px;}.onb-powers--tools {margin-top: 14px;@@ -7918,26 +7495,15 @@ kbd {.onb__stage {padding: 20px 16px 32px;}- .onb-pair,- .onb-skills {- grid-template-columns: minmax(0, 1fr);- }.onb-templates {grid-template-columns: repeat(2, minmax(0, 1fr));}- .onb-note {- display: block;- }.onb__row {flex-wrap: wrap;}.onb__row > .onb__field {flex: 1 1 100%;}- .onb-note .icon {- vertical-align: -3px;- margin-right: 6px;- }/* iOS zooms into a field with text under 16 px. */input,textarea,@@ -8131,7 +7697,6 @@ kbd {height: 6px;}-/* The wiki: what you and the team know, as linked pages *//* the place: the map takes it all, a panel comes over it */@@ -8583,7 +8148,6 @@ button.wk-pill.is-on { box-shadow: 0 0 0 1.5px var(--k); background: color-mix(i.voice-clock { display: inline-flex; align-items: center; gap: 6px; margin-left: 6px; font-size: 12px; font-variant-numeric: tabular-nums; color: var(--danger); white-space: nowrap; }.voice-clock i { width: 7px; height: 7px; border-radius: 50%; background: var(--danger); }-/* ---------- the connector store ---------- */.catalog {display: grid;@@ -9210,7 +8774,1927 @@ button.agent-card__now:hover {}.field__required { color: var(--danger); margin-left: 2px; }+/* ---------- the first run (Intro.tsx) ----------+ Its own look, from the phone app's: warm paper, cream cards with soft shadows, round pills in the+ toucan's orange, Nunito for the headings and a lilac for what's picked. The rest of the app keeps+ its own look; the tour's balloons and the missions share these colors. */+:root {+ --i-bg: #f4efe6;+ --i-card: #fffdf9;+ --i-ink: #1d1a16;+ --i-ink-2: #5f584e;+ --i-ink-3: #6e675c;+ --i-muted: #8a8174;+ --i-accent: #c84e12;+ --i-accent-hover: #b0430f;+ --i-link: #b8460f;+ --i-link-hover: #8f3609;+ --i-quiet: #e9e1d4;+ --i-line: #efe8dc;+ --i-dot: #d9cfbf;+ --i-peach: #fbe6d8;+ --i-blob: #f08a3e;+ --i-teal: #ddf1ef;+ --i-teal-ink: #2f5551;+ --i-teal-sub: #3f6f6b;+ --i-lilac: #ede5ff;+ --i-lilac-blob: #d9cbff;+ --i-lilac-line: #8b5cf6;+ --i-lilac-ink: #5b3fc4;+ --i-lilac-tick: #6d3fe0;+ --i-ok: #2f9e44;+ --i-ok-soft: #e3f5e8;+ --i-ok-ink: #3d6b4a;+ --i-bad: #b3261e;+ --i-shadow: 0 1px 2px rgba(29, 26, 22, 0.05), 0 10px 30px rgba(29, 26, 22, 0.07);+ --i-display: 'Nunito Variable', 'Inter Variable', -apple-system, system-ui, sans-serif;+ --m-accent: var(--i-accent);+ --m-track: #d3cabb;+}+@media (prefers-color-scheme: dark) {+ :root:not([data-theme='light']) {+ --i-bg: #151311;+ --i-card: #211e1b;+ --i-ink: #f1ece4;+ --i-ink-2: #cbc3b7;+ --i-ink-3: #aaa296;+ --i-muted: #9a9286;+ --i-link: #f6a36b;+ --i-link-hover: #ffc196;+ --i-quiet: #2b2723;+ --i-line: #322d28;+ --i-dot: #4a443d;+ --i-peach: #3a2519;+ --i-blob: #c8601f;+ --i-teal: #142e2b;+ --i-teal-ink: #b6e2dc;+ --i-teal-sub: #8fc4bd;+ --i-lilac: #2a2142;+ --i-lilac-blob: #3b2d63;+ --i-lilac-line: #a685ff;+ --i-lilac-ink: #cbb9ff;+ --i-lilac-tick: #c3adff;+ --i-ok: #4bd08a;+ --i-ok-soft: #173826;+ --i-ok-ink: #9fdcb6;+ --i-bad: #ff8a80;+ --i-shadow: 0 1px 2px rgba(0, 0, 0, 0.35), 0 10px 30px rgba(0, 0, 0, 0.3);+ --m-track: #4a443d;+ }+}+:root[data-theme='dark'] {+ --i-bg: #151311;+ --i-card: #211e1b;+ --i-ink: #f1ece4;+ --i-ink-2: #cbc3b7;+ --i-ink-3: #aaa296;+ --i-muted: #9a9286;+ --i-link: #f6a36b;+ --i-link-hover: #ffc196;+ --i-quiet: #2b2723;+ --i-line: #322d28;+ --i-dot: #4a443d;+ --i-peach: #3a2519;+ --i-blob: #c8601f;+ --i-teal: #142e2b;+ --i-teal-ink: #b6e2dc;+ --i-teal-sub: #8fc4bd;+ --i-lilac: #2a2142;+ --i-lilac-blob: #3b2d63;+ --i-lilac-line: #a685ff;+ --i-lilac-ink: #cbb9ff;+ --i-lilac-tick: #c3adff;+ --i-ok: #4bd08a;+ --i-ok-soft: #173826;+ --i-ok-ink: #9fdcb6;+ --i-bad: #ff8a80;+ --i-shadow: 0 1px 2px rgba(0, 0, 0, 0.35), 0 10px 30px rgba(0, 0, 0, 0.3);+ --m-track: #4a443d;+}+.intro {+ position: fixed;+ inset: 0;+ z-index: 50;+ display: flex;+ background: var(--i-bg);+ color: var(--i-ink);+ font-size: 15px;+}+.intro__drag {+ position: absolute;+ inset: 0 0 auto 0;+ height: 20px;+ -webkit-app-region: drag;+}+.intro__close {+ position: absolute;+ top: 26px;+ right: 28px;+ z-index: 2;+ border: 0;+ background: transparent;+ color: var(--i-ink-2);+ font: inherit;+ font-weight: 600;+ cursor: pointer;+ -webkit-app-region: no-drag;+}+.intro__stage {+ flex: 1;+ min-width: 0;+ display: flex;+ --rise: 0;+ --rise-x: 12px;+ animation: rise var(--dur-slow) var(--ease-out) both;+}+.intro__stage[data-dir='back'] {+ --rise-x: -12px;+}+.intro__split {+ flex: 1;+ min-width: 0;+ display: flex;+ gap: 20px;+ padding: 20px;+}+.intro__main {+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+ padding: 28px 56px 36px 36px;+ overflow-y: auto;+}+.intro__full {+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+ padding: 28px 48px 32px;+ overflow-y: auto;+}+.intro__top {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 16px;+ min-height: 28px;+ -webkit-app-region: drag;+}+.intro__top button,+.intro__top a {+ -webkit-app-region: no-drag;+}+.intro__top-right {+ display: flex;+ align-items: center;+ gap: 16px;+}+.intro__center {+ flex: 1;+ display: flex;+ flex-direction: column;+ justify-content: center;+ gap: 22px;+ padding: 24px 0;+}+.intro__center--tight {+ gap: 14px;+ max-width: 620px;+}+.intro__center--top {+ justify-content: flex-start;+}+.intro__center--narrow {+ width: min(760px, 100%);+ align-self: center;+}+.intro__center--chat {+ width: min(760px, 100%);+ align-self: center;+ justify-content: flex-start;+ gap: 10px;+}+.intro-dots {+ display: flex;+ gap: 6px;+}+.intro-dots span {+ width: 8px;+ height: 8px;+ border-radius: 4px;+ background: var(--i-dot);+ transition: width var(--dur-slow) var(--ease-out), background-color var(--dur-slow) var(--ease-out);+}+.intro-dots span.is-done,+.intro-dots span.is-now {+ background: var(--i-accent);+}+.intro-dots span.is-now {+ width: 26px;+}+.intro-h1 {+ margin: 0;+ font-family: var(--i-display);+ font-weight: 900;+ font-size: clamp(40px, 4.6vw, 58px);+ line-height: 1.02;+ letter-spacing: -0.5px;+}+.intro-h2 {+ margin: 0 0 8px;+ font-family: var(--i-display);+ font-weight: 900;+ font-size: clamp(30px, 3.2vw, 40px);+ line-height: 1.05;+}+.intro-h2 label {+ cursor: inherit;+}+.intro-lead {+ margin: 0;+ font-size: 20px;+ line-height: 1.5;+ color: var(--i-ink-2);+ max-width: 520px;+}+.intro-lead--sm {+ font-size: 16px;+}+.intro-field {+ display: flex;+ flex-direction: column;+ gap: 8px;+ font-size: 15px;+ font-weight: 600;+ max-width: 460px;+}+.intro-input {+ height: 56px;+ box-sizing: border-box;+ padding: 0 22px;+ border: 0;+ border-radius: 999px;+ background: var(--i-card);+ font: inherit;+ font-size: 17px;+ font-weight: 500;+ color: var(--i-ink);+ box-shadow: 0 1px 2px rgba(29, 26, 22, 0.06), 0 8px 24px rgba(29, 26, 22, 0.08);+ max-width: 460px;+ width: 100%;+ outline: none;+ transition: box-shadow var(--dur-fast) var(--ease-out);+}+.intro-input:focus-visible {+ box-shadow: inset 0 0 0 2px var(--i-accent), 0 8px 24px rgba(29, 26, 22, 0.08);+}+.intro-input--sm {+ height: 46px;+ font-size: 15px;+}+.intro-actions {+ display: flex;+ align-items: center;+ flex-wrap: wrap;+ gap: 16px;+ margin-top: 6px;+}+.intro-btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ gap: 8px;+ height: 58px;+ padding: 0 34px;+ border: 0;+ border-radius: 999px;+ background: var(--i-accent);+ color: #fff;+ font: inherit;+ font-size: 18px;+ font-weight: 700;+ cursor: pointer;+ transition: var(--transition-ui);+ -webkit-app-region: no-drag;+}+.intro-btn:hover:not(:disabled) {+ background: var(--i-accent-hover);+}+.intro-btn:active:not(:disabled) {+ transform: scale(0.98);+}+.intro-btn:disabled {+ opacity: 0.45;+ cursor: default;+}+.intro-btn--sm {+ height: 42px;+ padding: 0 18px;+ font-size: 15px;+}+.intro-btn--light {+ background: var(--i-card);+ color: var(--i-ink);+ box-shadow: 0 1px 2px rgba(29, 26, 22, 0.08);+}+.intro-btn--light:hover:not(:disabled) {+ background: var(--i-line);+}+.intro-btn:focus-visible,+.intro-link:focus-visible,+.intro-card:focus-visible,+.intro-tile:focus-visible,+.intro-chipbtn:focus-visible,+.intro-color:focus-visible,+.intro-round:focus-visible,+.intro-name__edit:focus-visible,+.intro-lang button:focus-visible,+.coach button:focus-visible,+.missions button:focus-visible,+.autonomy-pick__row:focus-visible,+.missions-card:focus-visible {+ outline: 2px solid var(--i-accent);+ outline-offset: 3px;+}+.intro-link {+ border: 0;+ padding: 0;+ background: none;+ color: var(--i-link);+ font: inherit;+ font-size: 15px;+ font-weight: 600;+ text-align: left;+ cursor: pointer;+ -webkit-app-region: no-drag;+}+.intro-link:hover {+ color: var(--i-link-hover);+ text-decoration: underline;+}+.intro-link--quiet {+ color: var(--i-ink-2);+}+.intro-link--quiet:hover {+ color: var(--i-ink);+}+.intro-link--center {+ align-self: center;+ font-size: 14px;+}+.intro-muted {+ font-size: 14px;+ color: var(--i-ink-3);+}+.intro-warn {+ color: var(--i-bad);+}+.intro-note {+ margin: 0;+ font-size: 14px;+ line-height: 1.45;+ color: var(--i-ink-2);+}+.intro-note code {+ font-family: var(--mono);+ font-size: 12.5px;+ background: var(--i-quiet);+ border-radius: 6px;+ padding: 2px 6px;+ user-select: all;+}+.intro-note--bad {+ color: var(--i-bad);+}+.intro-foot {+ font-size: 14px;+ color: var(--i-ink-3);+}+.intro-lang {+ font-size: 14px;+ font-weight: 600;+ color: var(--i-ink-3);+}+.intro-lang button {+ border: 0;+ padding: 2px 0;+ background: none;+ font: inherit;+ color: var(--i-ink-3);+ cursor: pointer;+}+.intro-lang button.is-on {+ color: var(--i-ink);+}+.intro-wait {+ display: flex;+ align-items: center;+ gap: 10px;+ margin: 0;+ color: var(--i-ink-2);+}++/* The art beside each step: a colored panel with the toucan, faces and the Tuca talking. */+.intro-art {+ position: relative;+ width: min(560px, 42%);+ flex-shrink: 0;+ border-radius: 34px;+ overflow: hidden;+}+.intro-art--peach {+ background: var(--i-peach);+}+.intro-art--lilac {+ background: var(--i-lilac);+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 18px;+}+.intro-art--ink {+ background: #1d1a16;+ color: #f4efe6;+ padding: 44px 40px;+ display: flex;+ flex-direction: column;+ gap: 22px;+}+.intro-blob {+ position: absolute;+ border-radius: 42% 58% 55% 45% / 48% 42% 58% 52%;+ background: var(--i-blob);+}+.intro-blob--lilac {+ background: var(--i-lilac-blob);+}+.intro-blob--ember {+ right: -90px;+ top: -90px;+ width: 320px;+ height: 320px;+ background: var(--i-accent);+ opacity: 0.55;+}+.intro-hero {+ position: absolute;+ left: 150px;+ top: 200px;+ border-radius: 70px;+ box-shadow: 0 24px 50px rgba(120, 48, 10, 0.3);+ line-height: 0;+}+.intro-hero .avatar--tuca {+ border-radius: 70px;+}+.intro-face {+ position: absolute;+ line-height: 0;+ filter: drop-shadow(0 12px 14px rgba(29, 26, 22, 0.18));+}+.intro-face .avatar--agent {+ border-radius: 30%;+}+.intro-chip {+ position: absolute;+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 11px 16px;+ border-radius: 20px 20px 20px 6px;+ background: var(--i-card);+ color: var(--i-ink);+ font-size: 15px;+ font-weight: 600;+ box-shadow: 0 8px 22px rgba(29, 26, 22, 0.12);+ white-space: nowrap;+}+.intro-chip b {+ color: var(--i-link);+}+.intro-chip--dark {+ border-radius: 20px 20px 6px 20px;+ background: #1d1a16;+ color: #f4efe6;+}+.intro-art__say {+ position: absolute;+ left: 24px;+ top: 24px;+ right: 24px;+ display: flex;+ align-items: flex-end;+ gap: 10px;+ z-index: 1;+}+.intro-art__say .intro-bubble {+ max-width: 300px;+ font-size: 15px;+ padding: 12px 16px;+}+.intro-born {+ position: relative;+ margin-top: 40px;+ line-height: 0;+ filter: drop-shadow(0 24px 30px rgba(76, 40, 170, 0.3));+}+.intro-born .avatar--agent {+ border-radius: 30%;+}+.intro-name {+ position: relative;+ display: flex;+ align-items: center;+ gap: 10px;+ min-height: 52px;+}+.intro-name b {+ font-family: var(--i-display);+ font-weight: 900;+ font-size: 44px;+}+.intro-name__input {+ width: 260px;+ height: 52px;+ border: 0;+ border-radius: 999px;+ padding: 0 20px;+ background: var(--i-card);+ color: var(--i-ink);+ font-family: var(--i-display);+ font-weight: 900;+ font-size: 30px;+ text-align: center;+ box-shadow: inset 0 0 0 2px var(--i-lilac-line);+ outline: none;+}+.intro-name__edit {+ width: 36px;+ height: 36px;+ border: 0;+ border-radius: 18px;+ display: grid;+ place-items: center;+ background: color-mix(in srgb, var(--i-card) 80%, transparent);+ color: var(--i-lilac-ink);+ cursor: pointer;+}+.intro-tagline {+ position: relative;+ font-size: 17px;+ font-weight: 600;+ color: var(--i-lilac-ink);+}+.intro-colors {+ position: relative;+ display: flex;+ gap: 10px;+}+.intro-color {+ width: 30px;+ height: 30px;+ border: 0;+ border-radius: 15px;+ background: var(--agent);+ cursor: pointer;+}+.intro-color.is-on {+ box-shadow: 0 0 0 3px var(--i-lilac), 0 0 0 5px var(--agent);+}++/* The Tuca's side panel and speech. */+.intro-side {+ position: relative;+ width: min(460px, 36%);+ flex-shrink: 0;+ border-radius: 34px;+ padding: 40px 36px;+ display: flex;+ flex-direction: column;+ gap: 14px;+ overflow: hidden;+}+.intro-side--teal {+ background: var(--i-teal);+}+.intro-side--teal::after {+ content: '';+ position: absolute;+ right: -70px;+ bottom: -70px;+ width: 300px;+ height: 300px;+ border-radius: 42% 58% 55% 45% / 48% 42% 58% 52%;+ background: #14a3a3;+ opacity: 0.25;+ pointer-events: none;+}+.intro-side__note {+ position: relative;+ z-index: 1;+ display: flex;+ align-items: center;+ gap: 10px;+ margin: 0;+ padding: 14px 16px;+ border-radius: 20px;+ background: color-mix(in srgb, var(--i-card) 70%, transparent);+ font-size: 14px;+ line-height: 1.45;+ color: var(--i-teal-ink);+}+.intro-side__note .icon {+ flex-shrink: 0;+}+.intro-tuca {+ display: flex;+ align-items: center;+ gap: 12px;+}+.intro-tuca > span {+ display: flex;+ flex-direction: column;+}+.intro-tuca b {+ font-size: 17px;+}+.intro-tuca > span > span {+ font-size: 14px;+ color: var(--i-teal-sub);+}+.intro-bubble {+ position: relative;+ max-width: 340px;+ padding: 15px 18px;+ border-radius: 24px 24px 24px 6px;+ background: var(--i-card);+ color: var(--i-ink);+ font-size: 17px;+ line-height: 1.45;+ animation: rise var(--dur-enter) var(--ease-out) both;+}+.intro-bubble + .intro-bubble {+ animation-delay: 120ms;+}+.intro-bubble.is-strong {+ font-weight: 600;+}++/* Cards and rows. */+.intro-card {+ position: relative;+ padding: 18px 20px;+ border: 0;+ border-radius: 26px;+ background: var(--i-card);+ color: var(--i-ink);+ font: inherit;+ box-shadow: var(--i-shadow);+ display: flex;+ align-items: center;+ gap: 14px;+ text-align: left;+}+.intro-card--pick {+ cursor: pointer;+ transition: var(--transition-ui);+}+.intro-card--pick:hover:not(:disabled) {+ box-shadow: inset 0 0 0 2px var(--i-accent), var(--i-shadow);+}+.intro-card--pick:disabled {+ opacity: 0.6;+ cursor: default;+}+.intro-card--quiet {+ background: var(--i-quiet);+ box-shadow: none;+ flex-direction: column;+ align-items: flex-start;+ gap: 2px;+ cursor: pointer;+}+.intro-card--quiet b {+ font-size: 17px;+}+.intro-card--quiet span {+ font-size: 14px;+ color: var(--i-ink-2);+}+.intro-card--quiet[aria-expanded='true'] {+ box-shadow: inset 0 0 0 2px var(--i-ink-3);+}+.intro-card--live {+ flex-direction: column;+ align-items: stretch;+ gap: 16px;+ padding: 20px 22px;+ border-radius: 28px;+ box-shadow: inset 0 0 0 2px var(--i-accent), var(--i-shadow);+}+.intro-card--list {+ flex-direction: column;+ align-items: stretch;+ gap: 0;+ padding: 8px 22px;+ border-radius: 28px;+ margin: 0;+ list-style: none;+}+.intro-card__head {+ display: flex;+ align-items: center;+ gap: 14px;+}+.intro-card__text {+ display: flex;+ flex-direction: column;+ flex: 1;+ min-width: 0;+}+.intro-card__text b {+ font-size: 17px;+}+.intro-card__text > span {+ font-size: 14px;+ color: var(--i-ink-3);+}+.intro-row {+ display: flex;+ align-items: center;+ gap: 14px;+ padding: 14px 0;+ font-size: 16px;+}+.intro-row + .intro-row {+ border-top: 1px solid var(--i-line);+}+.intro-mark {+ flex-shrink: 0;+ border-radius: 15px;+ color: #fff;+ display: grid;+ place-items: center;+ font-weight: 800;+}+/* A black mark (Cursor, OpenCode, Pi) or an initial: a near-black tile that still reads on the dark theme. */+.intro-mark--ink {+ background: #211e1b;+ box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.14);+}+.intro-pill {+ flex-shrink: 0;+ font-size: 13px;+ font-weight: 700;+ color: var(--i-link);+ background: var(--i-peach);+ padding: 5px 10px;+ border-radius: 999px;+}+.intro-pill.is-ok {+ color: var(--i-ok-ink);+ background: var(--i-ok-soft);+}+.intro-pill.is-bad {+ color: var(--i-bad);+}+.intro-grid2 {+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: 14px;+}+.intro-steps {+ display: flex;+ flex-direction: column;+ gap: 12px;+ margin: 0;+ padding: 16px 18px;+ border-radius: 20px;+ background: var(--i-bg);+ list-style: none;+ font-size: 15px;+}+.intro-step {+ display: flex;+ gap: 12px;+ align-items: center;+ line-height: 1.4;+}+.intro-step > svg {+ flex-shrink: 0;+}+.intro-step.is-later {+ color: var(--i-muted);+}+.intro-step.is-error {+ color: var(--i-bad);+}+.intro-check circle {+ fill: var(--i-ok);+}+.intro-check path {+ stroke: #fff;+ stroke-width: 2.2;+ fill: none;+ stroke-linecap: round;+ stroke-linejoin: round;+}+.intro-spin circle {+ fill: none;+ stroke: var(--i-blob);+ stroke-width: 3.5;+ stroke-dasharray: 36 22;+}+.intro-spin {+ animation: spin 1s linear infinite;+}+.intro-pending circle {+ fill: none;+ stroke: var(--i-dot);+ stroke-width: 2;+}+.intro-fail {+ display: flex;+ flex-direction: column;+ gap: 8px;+}+.intro-fail p {+ margin: 0;+ font-size: 14px;+ color: var(--i-bad);+}+/* What was found: rows a little tighter, so a failing one still leaves "Continuar" on screen at 1280×800. */+.intro-found .intro-row {+ padding: 9px 0;+}+.intro__center--found {+ gap: 11px;+}+/* Beside the button, in two short lines, rather than a line of its own under it. */+.intro-actions__note {+ flex: 1 1 0;+ min-width: 180px;+ font-size: 14px;+ line-height: 1.4;+}+.intro-panel--tight {+ gap: 6px;+ padding: 12px 20px;+}+.intro-panel {+ display: flex;+ flex-direction: column;+ gap: 12px;+ padding: 18px 22px;+ border-radius: 26px;+ background: var(--i-quiet);+ font-size: 15px;+ line-height: 1.45;+}+.intro-panel p,+.intro-panel ul {+ margin: 0;+}+.intro-panel ul {+ padding-left: 18px;+ display: flex;+ flex-direction: column;+ gap: 6px;+}+.intro-panel .intro-link {+ font-size: 14px;+}+.intro-checkbox {+ display: flex;+ align-items: center;+ gap: 12px;+ font-size: 15px;+ cursor: pointer;+}+.intro-checkbox input {+ width: 20px;+ height: 20px;+ accent-color: var(--i-accent);+ flex-shrink: 0;+}+/* "Também achei": what comes along, as quiet switch rows. */+.intro-panel__title {+ font-size: 14px;+}+.intro-bring {+ display: flex;+ align-items: center;+ gap: 12px;+ font-size: 14.5px;+}+.intro-bring.is-off .intro-bring__text {+ color: var(--i-ink-3);+}+.intro-bring > .intro-mark {+ border-radius: 9px;+}+.intro-bring__dot {+ width: 28px;+ height: 28px;+ flex-shrink: 0;+ display: grid;+ place-items: center;+ border-radius: 9px;+ background: var(--i-card);+ color: var(--i-lilac-tick);+}+.intro-bring__text {+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+ gap: 2px;+}+.intro-bring__more.intro-link {+ font-size: 13px;+ font-weight: 600;+}+.intro-bring__names {+ font-size: 13px;+ color: var(--i-ink-2);+ max-height: 60px;+ overflow: auto;+}+.intro-bring .toggle.is-on,+.intro-panel .toggle.is-on {+ background: var(--i-lilac-tick);+}+/* The two jobs behind the scenes: two cream cards side by side, the whole card opens the menu. */+.intro-jobs {+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: 10px;+ margin-top: 2px;+}+.intro-jobs__hint {+ grid-column: 1 / -1;+ font-size: 13px;+}+.intro-job {+ position: relative;+ display: flex;+ align-items: center;+ gap: 12px;+ min-width: 0;+ padding: 12px 14px;+ border-radius: 20px;+ background: var(--i-card);+ color: var(--i-ink);+ box-shadow: 0 1px 2px rgba(29, 26, 22, 0.05);+ transition: var(--transition-ui);+}+.intro-job:hover,+.intro-job:focus-within {+ background: var(--i-lilac);+ box-shadow: inset 0 0 0 2px var(--i-lilac-line);+}+.intro-job > .intro-mark {+ border-radius: 11px;+}+.intro-job > .icon {+ flex-shrink: 0;+ color: var(--i-ink-3);+}+.intro-job__text {+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+ gap: 1px;+}+.intro-job__title {+ font-family: var(--i-display);+ font-weight: 800;+ font-size: 14px;+ color: var(--i-ink-2);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.intro-job__model {+ display: flex;+ align-items: center;+ gap: 8px;+ min-width: 0;+}+.intro-job__model b {+ font-size: 16px;+ font-weight: 700;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.intro-job__tag {+ flex-shrink: 0;+ font-size: 11.5px;+ font-weight: 700;+ padding: 3px 9px;+ border-radius: 999px;+ color: var(--i-ink-2);+ background: var(--i-quiet);+}+.intro-job__tag.is-fast {+ color: var(--i-lilac-ink);+ background: var(--i-lilac);+}+.intro-job:hover .intro-job__tag.is-fast,+.intro-job:focus-within .intro-job__tag.is-fast {+ background: var(--i-card);+}+/* The app's Select, laid invisibly over the card: its trigger is the card, its menu anchors there. */+.intro-job__select.select {+ position: absolute;+ inset: 0;+}+.intro-job__select .select__trigger {+ height: 100%;+ border: 0;+ border-radius: 20px;+ background: transparent;+ opacity: 0;+ cursor: pointer;+}+.intro-pickers {+ display: flex;+ flex-direction: column;+ gap: 10px;+}+.intro-picker {+ display: flex;+ flex-direction: column;+ gap: 6px;+ font-size: 14px;+ font-weight: 600;+}+.intro-harnesses .harnesses {+ max-height: none;+}+.intro-join {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 10px;+ max-width: 560px;+}+.intro-join .intro-input {+ flex: 1;+ min-width: 240px;+ height: 46px;+ font-size: 15px;+}+.intro-join .intro-note {+ flex-basis: 100%;+}++/* 3. The Tuca asks. */+.intro-status {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 7px 12px;+ border-radius: 999px;+ background: var(--i-card);+ font-size: 13px;+ font-weight: 600;+}+.intro-status__dot {+ width: 8px;+ height: 8px;+ border-radius: 4px;+ background: var(--i-ok);+}+.intro-ask {+ display: flex;+ gap: 14px;+ align-items: flex-end;+}+.intro-ask > .avatar--tuca {+ flex-shrink: 0;+}+.intro-ask__bubbles {+ display: flex;+ flex-direction: column;+ gap: 8px;+ align-items: flex-start;+}+.intro-ask__bubbles .intro-bubble {+ max-width: none;+ font-size: 18px;+ padding: 15px 19px;+}+.intro-tiles {+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ gap: 12px;+ padding-left: 70px;+}+.intro-tile {+ display: flex;+ flex-direction: column;+ align-items: flex-start;+ gap: 14px;+ padding: 18px;+ border: 0;+ border-radius: 26px;+ background: var(--i-card);+ color: var(--i-ink);+ font: inherit;+ font-size: 16px;+ font-weight: 700;+ text-align: left;+ box-shadow: 0 1px 2px rgba(29, 26, 22, 0.05);+ cursor: pointer;+ transition: var(--transition-ui);+}+.intro-tile:hover {+ background: var(--i-lilac);+ box-shadow: inset 0 0 0 2px var(--i-lilac-line);+}+.intro-tile:active {+ transform: scale(0.98);+}+/* The tiles' ink colors, lifted for the dark. */+@media (prefers-color-scheme: dark) {+ :root:not([data-theme='light']) .intro-tile__icon {+ filter: brightness(1.9) saturate(0.8);+ }+}+:root[data-theme='dark'] .intro-tile__icon {+ filter: brightness(1.9) saturate(0.8);+}+@media (prefers-color-scheme: dark) {+ :root:not([data-theme='light']) .intro-tile__icon.is-code {+ filter: none;+ stroke: var(--i-ink-2);+ }+}+:root[data-theme='dark'] .intro-tile__icon.is-code {+ filter: none;+ stroke: var(--i-ink-2);+}+.intro-say {+ margin-left: 70px;+ display: flex;+ align-items: center;+ gap: 8px;+ height: 60px;+ padding: 0 8px 0 22px;+ border-radius: 999px;+ background: var(--i-card);+ box-shadow: 0 1px 2px rgba(29, 26, 22, 0.06), 0 10px 28px rgba(29, 26, 22, 0.1);+}+.intro-say:focus-within {+ box-shadow: inset 0 0 0 2px var(--i-accent), 0 10px 28px rgba(29, 26, 22, 0.1);+}+.intro-say input {+ flex: 1;+ min-width: 0;+ height: 44px;+ border: 0;+ background: transparent;+ font: inherit;+ font-size: 16px;+ color: var(--i-ink);+ outline: none;+}+.intro-say input::placeholder {+ color: var(--i-muted);+}+.intro-round,+.intro-voice .voice-btn {+ width: 46px;+ height: 46px;+ border: 0;+ border-radius: 23px;+ background: var(--i-accent);+ color: #fff;+ display: grid;+ place-items: center;+ cursor: pointer;+}+.intro-voice .voice-btn.is-off {+ background: var(--i-accent);+ color: #fff;+ opacity: 1;+}+.intro-voice .voice-btn .icon {+ width: 20px;+ height: 20px;+}+.intro-voice {+ position: relative;+ display: flex;+}++/* 4. The agent. */+.intro-does .intro-row {+ font-size: 16px;+ padding: 11px 0;+}+.intro-tick {+ width: 30px;+ height: 30px;+ flex-shrink: 0;+ border-radius: 10px;+ background: var(--i-lilac);+ color: var(--i-lilac-tick);+ display: grid;+ place-items: center;+}+.intro-tick .icon {+ stroke-width: 3;+}+/* The optional connector: one slim line with a link, under the choice. */+.intro-offer {+ display: flex;+ align-items: center;+ flex-wrap: wrap;+ gap: 8px;+ padding: 0 4px;+ font-size: 14px;+ line-height: 1.4;+ color: var(--i-ink);+}+.intro-offer .intro-link {+ font-size: 14px;+}+.intro-offer > .icon {+ color: var(--i-ink-2);+ flex-shrink: 0;+}+/* How far the agent goes on its own: three rows, the picked one lilac like a goal tile. */+.autonomy-pick {+ display: flex;+ flex-direction: column;+ gap: 8px;+}+.autonomy-pick__q {+ font-size: 17px;+ font-weight: 800;+}+.autonomy-pick__rows {+ display: flex;+ flex-direction: column;+ gap: 7px;+}+.autonomy-pick__row {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 13px 16px;+ border: 0;+ border-radius: 20px;+ background: var(--i-card);+ color: var(--i-ink);+ font: inherit;+ font-size: 15px;+ font-weight: 600;+ line-height: 1.3;+ text-align: left;+ box-shadow: 0 1px 2px rgba(29, 26, 22, 0.05);+ cursor: pointer;+ transition: var(--transition-ui);+ -webkit-app-region: no-drag;+}+.autonomy-pick__row:hover {+ box-shadow: inset 0 0 0 2px var(--i-lilac-line);+}+.autonomy-pick__row.is-on {+ background: var(--i-lilac);+ box-shadow: inset 0 0 0 2px var(--i-lilac-line);+}+.autonomy-pick__dot {+ width: 20px;+ height: 20px;+ flex-shrink: 0;+ border-radius: 50%;+ box-shadow: inset 0 0 0 2px var(--i-ink-3);+}+.autonomy-pick__row.is-on .autonomy-pick__dot {+ box-shadow: inset 0 0 0 6px var(--i-lilac-tick);+}+.autonomy-pick__tag {+ flex-shrink: 0;+ font-size: 12px;+ font-weight: 700;+ color: var(--i-lilac-ink);+ background: var(--i-lilac);+ padding: 4px 9px;+ border-radius: 999px;+}+.autonomy-pick__row.is-on .autonomy-pick__tag {+ background: var(--i-card);+}+.autonomy-pick__hint {+ margin: 0;+ padding: 0 4px;+ font-size: 14px;+ line-height: 1.45;+ color: var(--i-ink-2);+}+/* In the detailed form, the app's own size. */+.autonomy-pick--compact {+ margin-top: 16px;+ gap: 8px;+}+.autonomy-pick--compact .autonomy-pick__q {+ font-size: 14px;+}+.autonomy-pick--compact .autonomy-pick__row {+ padding: 10px 12px;+ border-radius: 12px;+ font-size: 13px;+ box-shadow: inset 0 0 0 1px var(--border);+ background: var(--panel);+ color: var(--text);+}+.autonomy-pick--compact .autonomy-pick__row.is-on {+ background: var(--i-lilac);+ box-shadow: inset 0 0 0 2px var(--i-lilac-line);+}+.autonomy-pick--compact .autonomy-pick__dot {+ width: 16px;+ height: 16px;+}+.autonomy-pick--compact .autonomy-pick__row.is-on .autonomy-pick__dot {+ box-shadow: inset 0 0 0 5px var(--i-lilac-tick);+}+.autonomy-pick--compact .autonomy-pick__hint {+ font-size: 13px;+ color: var(--text-2);+}+/* A harness that failed: one plain line, what to do, and the raw text only under "Ver detalhes". */+.engine-problem {+ display: flex;+ flex-direction: column;+ gap: 6px;+ min-width: 0;+ margin-top: 4px;+}+.engine-problem__line {+ font-size: 14px;+ line-height: 1.4;+ color: var(--text-2);+}+.engine-problem--intro .engine-problem__line {+ color: var(--i-ink-2);+}+/* In the introduction's list, under the harness's name: as tight as its account line was. */+.engine-problem--intro {+ margin-top: 1px;+ gap: 2px;+}+.engine-problem__actions {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 6px 14px;+}+.engine-problem--intro .engine-problem__actions .intro-link {+ font-size: 14px;+}+.engine-problem__more {+ font-size: 13px;+ color: var(--text-2);+}+.engine-problem--intro .engine-problem__more {+ color: var(--i-ink-3);+}+.engine-problem__more[open] {+ flex-basis: 100%;+}+.engine-problem__more summary {+ cursor: pointer;+ font-weight: 600;+}+.engine-problem__more pre {+ margin: 6px 0 0;+ max-height: 120px;+ overflow: auto;+ padding: 8px 10px;+ border-radius: 8px;+ background: var(--code-bg);+ color: var(--text-2);+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 11.5px;+ line-height: 1.45;+ white-space: pre-wrap;+ word-break: break-word;+}+.engine-problem--intro .engine-problem__more pre {+ background: var(--i-quiet);+ color: var(--i-ink-2);+}+/* A harness whose test failed, beside one that works: muted, so it reads as optional. */+.intro-row.is-failed > .intro-mark,+.intro-row.is-failed > svg,+.intro-row.is-failed > .icon,+.intro-row.is-failed .intro-card__text > b,+.intro-row.is-failed .intro-card__text > span:not(.engine-problem) {+ opacity: 0.55;+}+.intro-row.is-failed {+ align-items: flex-start;+}+.intro-connect.modal__card,+.intro-connect {+ width: min(860px, calc(100vw - 48px));+}+.intro-chat {+ flex: 1;+ min-height: 320px;+ display: flex;+ flex-direction: column;+ border-radius: 28px;+ background: var(--i-card);+ box-shadow: var(--i-shadow);+ overflow: hidden;+}+.intro-chat .messages {+ flex: 1;+}+.intro-chat .intro-wait {+ margin: auto;+}++/* Someone invited to a team. */+.intro-invited {+ position: relative;+ display: flex;+ align-items: center;+ gap: 10px;+ font-size: 15px;+ color: #cfc7ba;+}+.intro-h1--team {+ position: relative;+ font-size: clamp(38px, 4vw, 52px);+}+.intro-kicker {+ font-size: 13px;+ font-weight: 700;+ letter-spacing: 0.6px;+ color: #a89f92;+}+.intro-team {+ position: relative;+ display: flex;+ flex-direction: column;+ gap: 12px;+}+.intro-team__row {+ display: flex;+ align-items: center;+ gap: 12px;+}+.intro-team__row .avatar--agent {+ border-radius: 30%;+}+.intro-team__row span span,+.intro-team__more {+ font-size: 14px;+ color: #cfc7ba;+}+.intro-people {+ position: relative;+ display: flex;+ align-items: center;+ gap: 10px;+ font-size: 14px;+ color: #cfc7ba;+}+.intro-people__faces {+ display: flex;+}+.intro-people__faces .avatar--me {+ border: 2px solid #1d1a16;+ box-sizing: content-box;+}+.intro-people__faces .avatar--me + .avatar--me {+ margin-left: -8px;+}+/* People's initials on the dark panel: each its own color, as in the phone app. */+.intro-art--ink .avatar--me {+ background: #3b9eea;+ color: #fff;+}+.intro-people__faces .avatar--me:nth-child(2) {+ background: #e5557a;+}+.intro-people__faces .avatar--me:nth-child(3) {+ background: #2f9e44;+}+.intro-label {+ font-size: 15px;+ font-weight: 600;+}+.intro-about {+ display: flex;+ flex-direction: column;+ gap: 10px;+}+.intro-chips {+ display: flex;+ flex-wrap: wrap;+ gap: 8px;+}+.intro-chipbtn {+ height: 40px;+ padding: 0 16px;+ border: 0;+ border-radius: 999px;+ background: var(--i-line);+ color: var(--i-ink);+ font: inherit;+ font-size: 14px;+ font-weight: 600;+ cursor: pointer;+}+.intro-chipbtn.is-on {+ background: var(--i-ink);+ color: var(--i-bg);+}+.intro-deal {+ display: flex;+ flex-direction: column;+ gap: 10px;+ max-width: 560px;+ padding: 18px 20px;+ border-radius: 24px;+ background: var(--i-card);+ box-shadow: var(--i-shadow);+ font-size: 15px;+ line-height: 1.45;+}+.intro-deal span {+ display: flex;+ gap: 10px;+}+.intro-deal span::before {+ content: '·';+ color: var(--i-lilac-line);+ font-weight: 800;+}++/* A narrow window: the art steps aside, the text keeps its room. */+@media (max-width: 980px) {+ .intro-art,+ .intro-side {+ display: none;+ }+ .intro__main {+ padding: 28px 28px 32px;+ }+ .intro-tiles,+ .intro-say {+ padding-left: 0;+ margin-left: 0;+ }+ .intro-tiles {+ grid-template-columns: repeat(2, minmax(0, 1fr));+ }+}+@media (max-height: 760px) {+ .intro-hero {+ top: 150px;+ }+}++/* ---------- the tour's balloons (Coach.tsx) ---------- */+.coach {+ position: fixed;+ inset: 0;+ z-index: 60;+ pointer-events: none;+}+/* The shade has a hole where the thing is, ringed in orange; clicks go through to the screen. */+.coach__hole {+ position: fixed;+ border-radius: 26px;+ box-shadow: 0 0 0 3px #f08a3e, 0 0 0 10px rgba(240, 138, 62, 0.22), 0 0 0 200vmax rgba(29, 26, 22, 0.45);+ transition: top var(--dur-base) var(--ease-out), left var(--dur-base) var(--ease-out), width var(--dur-base) var(--ease-out), height var(--dur-base) var(--ease-out);+}+.coach__card {+ position: fixed;+ pointer-events: auto;+ display: flex;+ flex-direction: column;+ gap: 10px;+ padding: 22px 24px;+ border-radius: 28px;+ background: #1d1a16;+ color: #f4efe6;+ box-shadow: 0 20px 44px rgba(0, 0, 0, 0.3);+ animation: pop var(--dur-enter) var(--ease-out) both;+}+.coach__kicker {+ display: flex;+ align-items: center;+ gap: 10px;+ font-size: 13px;+ font-weight: 700;+ letter-spacing: 0.6px;+ color: #f6a36b;+}+.coach__title {+ font-family: var(--i-display);+ font-weight: 900;+ font-size: 24px;+ line-height: 1.15;+}+.coach__body {+ font-size: 16px;+ line-height: 1.5;+ color: #d6cdbf;+}+.coach__body b {+ color: #f4efe6;+}+.coach__foot {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ margin-top: 4px;+}+.coach__hint {+ font-size: 14px;+ color: #a89f92;+}+.coach__ok {+ height: 38px;+ padding: 0 16px;+ border: 0;+ border-radius: 999px;+ background: #f4efe6;+ color: #1d1a16;+ font: inherit;+ font-size: 14px;+ font-weight: 700;+ cursor: pointer;+}+.coach__ok--quiet {+ background: transparent;+ color: #d6cdbf;+ padding: 0;+}+.coach__skip {+ margin-left: auto;+ border: 0;+ padding: 0;+ background: none;+ color: #f6a36b;+ font: inherit;+ font-size: 14px;+ font-weight: 600;+ cursor: pointer;+}+.coach__skip:hover {+ text-decoration: underline;+}+.coach__arrow {+ position: absolute;+ width: 18px;+ height: 18px;+ background: #1d1a16;+ transform: rotate(45deg);+}+@media (prefers-reduced-motion: reduce) {+ .coach__card,+ .coach__hole,+ .intro__stage,+ .intro-bubble {+ animation: none;+ transition: none;+ }+}++/* ---------- missions (Missions.tsx) ---------- */+.missions-card {+ display: flex;+ align-items: center;+ gap: 12px;+ margin: 8px 10px 4px;+ padding: 12px;+ border: 0;+ border-radius: 20px;+ background: var(--i-quiet);+ color: var(--i-ink);+ font: inherit;+ text-align: left;+ cursor: pointer;+ transition: var(--transition-ui);+}+.missions-card:hover {+ background: color-mix(in srgb, var(--i-quiet) 80%, var(--i-dot));+}+.missions-card.is-active,+.missions-card.is-new {+ --m-inner: var(--i-card);+ background: var(--i-card);+ box-shadow: inset 0 0 0 2px var(--i-accent);+}+.missions-ring {+ width: 36px;+ height: 36px;+ flex-shrink: 0;+ border-radius: 18px;+ display: grid;+ place-items: center;+}+.missions-ring > span {+ width: 26px;+ height: 26px;+ border-radius: 13px;+ display: grid;+ place-items: center;+ background: var(--m-inner, var(--i-quiet));+ font-size: 11px;+ font-weight: 800;+}+.missions-card__text {+ display: flex;+ flex-direction: column;+ min-width: 0;+}+.missions-card__text b {+ font-size: 14px;+}+.missions-card__text span {+ font-size: 12px;+ color: var(--i-ink-2);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.nav-item__new {+ margin-left: auto;+ font-size: 10.5px;+ font-weight: 800;+ padding: 2px 7px;+ border-radius: 99px;+ background: var(--i-accent);+ color: #fff;+}+.nav-item.is-fresh {+ background: var(--i-peach);+ color: var(--i-link);+ font-weight: 600;+}+.missions {+ flex: 1;+ overflow-y: auto;+ margin: 0;+ padding: 40px 56px;+ display: flex;+ flex-direction: column;+ gap: 22px;+ color: var(--i-ink);+}+.missions__head {+ display: flex;+ align-items: flex-end;+ justify-content: space-between;+ gap: 20px;+}+.missions__head h1 {+ margin: 0 0 6px;+ font-family: var(--i-display);+ font-weight: 900;+ font-size: 40px;+}+.missions__head p {+ margin: 0;+ font-size: 17px;+ color: var(--i-ink-2);+}+.missions-link {+ border: 0;+ padding: 0;+ background: none;+ color: var(--i-link);+ font: inherit;+ font-size: 15px;+ font-weight: 600;+ white-space: nowrap;+ cursor: pointer;+}+.missions-link:hover {+ text-decoration: underline;+}+.missions-link--quiet {+ color: var(--i-ink-2);+ font-size: 13px;+}+.missions__grid {+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ gap: 14px;+ margin: 0;+ padding: 0;+ list-style: none;+}+.mission {+ display: flex;+ flex-direction: column;+ gap: 10px;+ padding: 20px;+ border-radius: 26px;+ background: var(--i-bg);+}+.mission > b {+ font-size: 17px;+}+.mission__n,+.mission__check {+ width: 30px;+ height: 30px;+ border-radius: 10px;+ display: grid;+ place-items: center;+ font-weight: 800;+ background: var(--m-track);+ color: var(--i-ink);+}+.mission__how {+ font-size: 14px;+ line-height: 1.45;+ color: var(--i-ink-2);+}+.mission__state {+ font-size: 14px;+ color: var(--i-ok-ink);+}+.mission.is-done {+ background: var(--i-ok-soft);+}+.mission.is-done .mission__check {+ background: var(--i-ok);+ color: #fff;+}+.mission.is-next {+ background: var(--i-lilac);+ box-shadow: inset 0 0 0 2px var(--i-lilac-line);+}+.mission.is-next .mission__n {+ background: #8b5cf6;+ color: #fff;+}+.mission.is-next .mission__how {+ color: var(--i-lilac-ink);+}+.mission__go {+ align-self: flex-start;+ height: 40px;+ padding: 0 16px;+ margin-top: auto;+ border: 0;+ border-radius: 999px;+ background: var(--i-ink);+ color: var(--i-bg);+ font: inherit;+ font-size: 14px;+ font-weight: 700;+ cursor: pointer;+}+.mission__go.is-quiet {+ background: transparent;+ color: var(--i-link);+ padding: 0;+ height: auto;+}+.missions__help {+ margin-top: auto;+ display: flex;+ align-items: center;+ gap: 14px;+ padding: 16px 20px;+ border-radius: 22px;+ background: var(--i-quiet);+ font-size: 15px;+ line-height: 1.45;+}+.missions__foot {+ margin: 0;+ font-size: 13px;+ color: var(--i-ink-3);+}+@media (max-width: 900px) {+ .missions {+ padding: 28px 20px;+ }+ .missions__grid {+ grid-template-columns: minmax(0, 1fr);+ }+}/* How far an agent goes on its own: the level, the guard, and the rules by kind under a fold. */.autonomy { display: flex; flex-direction: column; gap: 12px; }diff --git a/src/shared/engine-errors.ts b/src/shared/engine-errors.tsnew file mode 100644index 0000000..60d113a--- /dev/null+++ b/src/shared/engine-errors.ts@@ -0,0 +1,56 @@+// A harness that failed its test (or a reply), said the way a person reads it: one plain line with+// what to do, never a stack trace or a file path. Known failures get their own line (an expired or+// invalid login, per harness and provider when the message says which; a limit; a timeout); anything+// else gets a short generic line, and the raw text goes only in "Ver detalhes".+import { L } from './lang'+import { ENGINES, type EngineId } from './types'++export type EngineProblemKind = 'login' | 'limit' | 'timeout' | 'other'++export interface EngineProblem {+ kind: EngineProblemKind+ line: string // one sentence, with what to do+ details?: string // the raw message, for "Ver detalhes" (absent when the line already says it all)+}++const PROVIDERS: [RegExp, string][] = [+ [/anthropic|claude\.ai|console\.anthropic/i, 'Anthropic'],+ [/openai|chatgpt/i, 'OpenAI'],+ [/google|gemini|vertex/i, 'Google'],+ [/\bx\.?ai\b|grok/i, 'xAI'],+ [/openrouter/i, 'OpenRouter'],+ [/github|copilot/i, 'GitHub'],+ [/cursor/i, 'Cursor']+]++const LOGIN = /invalid_grant|refresh[_ ]?token|token (has )?expired|expired token|oauth|\b401\b|unauthori[sz]ed|not (logged|signed) in|not authenticated|authentication (failed|required|error)|login required|please (log|sign) ?in|(log|sign) ?in again|invalid (api[_ ]?key|x-api-key|credentials)|credentials? (expired|invalid)/i+const EXPIRED = /expired|invalid_grant|refresh/i+const LIMIT = /\b429\b|rate.?limit|usage limit|hit your limit|quota|too many requests/i+const TIMEOUT = /timed? ?out|timeout|aborted|ETIMEDOUT|ECONNRESET/i+// A line someone wrote for people (the core's own messages): short, one line, nothing technical.+const TECHNICAL = /\n|\bat .+\(|file:\/\/|\/(opt|usr|home|Users|var|tmp)\/|[A-Z]:\\|node_modules|\{".*":|Error:|errno|stack/i++// The provider the message names, when the harness signs in to several (Pi, OpenCode).+export function providerOf(raw: string): string | undefined {+ // "… for anthropic: …" names it best; else the first one mentioned.+ const named = /\bfor ([a-z][\w.-]*)\b/i.exec(raw)?.[1]+ for (const [re, name] of PROVIDERS) if (named && re.test(named)) return name+ for (const [re, name] of PROVIDERS) if (re.test(raw)) return name+ return undefined+}++export function explainEngineError(engine: EngineId, raw: string): EngineProblem {+ const label = ENGINES[engine].label+ const text = raw.trim()+ if (LOGIN.test(text)) {+ // Pi and OpenCode sign in to providers; the others are the provider's own app.+ const provider = engine === 'pi' || engine === 'opencode' ? providerOf(text) : undefined+ const whose = provider ? L(`O login da ${provider} no ${label}`, `The ${provider} sign-in in ${label}`) : L(`O login do ${label}`, `${label}’s sign-in`)+ const state = EXPIRED.test(text) ? L('expirou', 'expired') : L('não está valendo', 'isn’t valid')+ return { kind: 'login', line: L(`${whose} ${state}. Entre de novo no ${label} pra usar.`, `${whose} ${state}. Sign in to ${label} again to use it.`), details: text }+ }+ if (LIMIT.test(text)) return { kind: 'limit', line: L(`O ${label} chegou no limite de uso. Tente de novo mais tarde.`, `${label} hit its usage limit. Try again later.`), details: text }+ if (TIMEOUT.test(text)) return { kind: 'timeout', line: L(`O ${label} demorou demais pra responder. Tente de novo.`, `${label} took too long to answer. Try again.`), details: text }+ if (text && text.length <= 140 && !TECHNICAL.test(text)) return { kind: 'other', line: text }+ return { kind: 'other', line: L(`O ${label} não funcionou agora.`, `${label} didn’t work just now.`), details: text || undefined }+}diff --git a/src/shared/onboarding.ts b/src/shared/onboarding.tsnew file mode 100644index 0000000..e67f0f6--- /dev/null+++ b/src/shared/onboarding.ts@@ -0,0 +1,334 @@+// The guided first run, as data and plain rules: the goals the Tuca offers and the agent each one+// starts (no model call, so the person never waits on one), which AI is ready, the models picked for+// the work behind the scenes, and the missions that make the sidebar grow on a new install.+import { L } from './lang'+import { codexValue, customModel, ENGINE_IDS, MODELS, type AgentColor, type EngineId, type EngineStatus, type Settings } from './types'+import type { Autonomy } from './actions'++// ---------- the goals ----------++export const GOAL_IDS = ['week', 'research', 'write', 'customers', 'sheets', 'code'] as const+export type GoalId = (typeof GOAL_IDS)[number]++export interface Goal {+ id: GoalId | 'own' // own: the person's own words, matched to none+ title: string // the tile+ name: string // the agent's+ role: string // short, for the sidebar+ tagline: string // under the name, as the person reads it ("Organiza a sua semana")+ color: AgentColor+ web: boolean+ instructions: string+ does: string[] // what it does, in plain words, one line each (how far it goes alone is chosen apart)+ task: string // the first message, after its @+ connector?: { id: string; label: string } // a catalog entry worth offering, optional: only one that signs in with one click in the browser (no app, token or address of the person's own)+}++export const GOALS = (): Goal[] => [+ {+ id: 'week',+ title: L('Organizar minha semana', 'Organize my week'),+ name: 'Lia',+ role: L('Agenda', 'Planning'),+ tagline: L('Organiza a sua semana', 'Organizes your week'),+ color: 'violet',+ web: true,+ instructions: L(+ 'Você ajuda a pessoa a organizar a semana: compromissos, tarefas e prioridades.\nAntes de montar um plano, pergunta o que ela tem pra fazer e o que não pode atrasar.\nEntrega o plano por dia, em listas curtas, deixando folga pro imprevisto.\nQuando algo não cabe, diz o que sugere adiar e por quê.\nPesquisa na internet só quando precisa (um endereço, um horário de funcionamento).',+ 'You help the person organize their week: appointments, tasks and priorities.\nBefore making a plan, you ask what they have to do and what can’t slip.\nYou deliver the plan by day, in short lists, leaving room for the unexpected.\nWhen something doesn’t fit, you say what you’d push back and why.\nYou search the web only when needed (an address, opening hours).'+ ),+ does: [L('Monta a sua semana a partir do que você contar', 'Plans your week from what you tell it'), L('Pesquisa na internet quando precisa', 'Searches the web when it needs to'), L('Te pergunta quando tiver dúvida', 'Asks you when it isn’t sure')],+ task: L('me ajuda a planejar a semana. Antes, me pergunta o que eu tenho pra fazer.', 'help me plan my week. First, ask me what I have to do.'),+ connector: { id: 'todoist', label: L('Ver as suas tarefas no Todoist', 'See your Todoist tasks') }+ },+ {+ id: 'research',+ title: L('Pesquisar e resumir', 'Research and summarize'),+ name: 'Iris',+ role: L('Pesquisa', 'Research'),+ tagline: L('Pesquisa e resume pra você', 'Researches and sums up for you'),+ color: 'sky',+ web: true,+ instructions: L(+ 'Você pesquisa na web antes de responder e cita as fontes com links.\nResume em tópicos curtos, separando o que é fato do que é opinião.\nQuando as fontes discordam, mostra as duas versões.\nDiz com clareza quando não achou nada confiável, em vez de chutar.\nPergunta o objetivo da pesquisa quando ele não estiver claro.',+ 'You search the web before answering and cite your sources with links.\nYou sum up in short bullet points, separating fact from opinion.\nWhen sources disagree, you show both sides.\nYou say plainly when you found nothing reliable, instead of guessing.\nYou ask what the research is for when that isn’t clear.'+ ),+ does: [L('Busca na internet e lê as fontes por você', 'Searches the web and reads the sources for you'), L('Resume em tópicos curtos, com os links', 'Sums up in short points, with the links'), L('Diz quando não achou nada confiável', 'Says when it found nothing reliable')],+ task: L('quais foram as 3 notícias mais importantes da minha área nesta semana? Antes, me pergunta qual é a minha área.', 'what were the 3 most important stories in my field this week? First, ask me what my field is.')+ },+ {+ id: 'write',+ title: L('Escrever e-mails e posts', 'Write emails and posts'),+ name: 'Nina',+ role: L('Textos', 'Writing'),+ tagline: L('Escreve e-mails e posts no seu tom', 'Writes emails and posts in your voice'),+ color: 'rose',+ web: true,+ instructions: L(+ 'Você escreve e-mails, posts e textos no tom da pessoa: leve, curto e sem jargão.\nEntrega o rascunho pronto pra usar, e no máximo duas versões quando o tom não estiver claro.\nPergunta pra quem é o texto e o que ele precisa conseguir, se ela não disser.',+ 'You write emails, posts and copy in the person’s voice: light, short and jargon-free.\nYou deliver a ready-to-use draft, and at most two versions when the tone isn’t clear.\nYou ask who the text is for and what it needs to achieve, if they don’t say.'+ ),+ does: [L('Escreve rascunhos prontos pra usar', 'Writes ready-to-use drafts'), L('Ajusta o tom ao que você pedir', 'Adjusts the tone to what you ask'), L('Te pergunta pra quem é o texto', 'Asks you who the text is for')],+ task: L('me ajuda a escrever um e-mail. Antes, me pergunta pra quem é e o que eu quero dizer.', 'help me write an email. First, ask me who it’s for and what I want to say.'),+ connector: { id: 'notion', label: L('Ler as suas páginas do Notion', 'Read your Notion pages') }+ },+ {+ id: 'customers',+ title: L('Responder clientes', 'Reply to customers'),+ name: 'Duda',+ role: L('Atendimento', 'Support'),+ tagline: L('Ajuda a responder os seus clientes', 'Helps you reply to your customers'),+ color: 'teal',+ web: false,+ instructions: L(+ 'Você ajuda a pessoa a responder clientes com rapidez e simpatia.\nEscreve a resposta pronta, curta e educada, no tom da marca dela.\nQuando falta uma informação (preço, prazo, política de troca), pergunta em vez de inventar.\nGuarda as respostas que funcionam pra usar de novo.',+ 'You help the person reply to customers quickly and kindly.\nYou write the reply ready to send, short and polite, in their brand’s voice.\nWhen a piece of information is missing (price, timing, return policy), you ask instead of making it up.\nYou keep the replies that work, to use again.'+ ),+ does: [L('Escreve respostas prontas pros seus clientes', 'Writes ready replies for your customers'), L('Pergunta quando falta uma informação', 'Asks when a piece of information is missing'), L('Aprende o jeito da sua marca', 'Learns your brand’s way of talking')],+ task: L('me ajuda a responder os meus clientes. Antes, me pergunta o que eu vendo e as dúvidas que mais chegam.', 'help me reply to my customers. First, ask me what I sell and the questions I get most.')+ },+ {+ id: 'sheets',+ title: L('Cuidar de planilhas', 'Handle spreadsheets'),+ name: 'Theo',+ role: L('Planilhas', 'Spreadsheets'),+ tagline: L('Cuida das suas planilhas', 'Looks after your spreadsheets'),+ color: 'amber',+ web: false,+ instructions: L(+ 'Você ajuda com planilhas: organizar dados, fazer contas, montar fórmulas e resumir o que os números dizem.\nMostra a conta ou a fórmula que usou, pra pessoa conferir.\nQuando os dados parecem errados ou incompletos, avisa antes de seguir.\nExplica em português simples, sem jargão de planilha.',+ 'You help with spreadsheets: organizing data, doing the math, building formulas and summing up what the numbers say.\nYou show the calculation or formula you used, so the person can check it.\nWhen the data looks wrong or incomplete, you say so before going on.\nYou explain in plain words, without spreadsheet jargon.'+ ),+ does: [L('Monta fórmulas e faz as contas', 'Builds formulas and does the math'), L('Mostra como chegou em cada número', 'Shows how it got each number'), L('Avisa quando os dados parecem errados', 'Warns you when the data looks wrong')],+ task: L('me ajuda com uma planilha. Antes, me pergunta o que ela tem e o que eu quero descobrir.', 'help me with a spreadsheet. First, ask me what’s in it and what I want to find out.')+ },+ {+ id: 'code',+ title: L('Programar', 'Code'),+ name: 'Leo',+ role: L('Código', 'Code'),+ tagline: L('Programa com você', 'Codes with you'),+ color: 'indigo',+ web: true,+ instructions: L(+ 'Você ajuda com código, arquitetura e bugs.\nExplica o raciocínio em poucas linhas e mostra código quando ajuda.\nAntes de propor uma mudança grande, descreve o plano e pergunta.\nQuando não tem certeza de como algo funciona no projeto da pessoa, pergunta em vez de supor.',+ 'You help with code, architecture and bugs.\nYou explain your reasoning in a few lines and show code when it helps.\nBefore proposing a big change, you describe the plan and ask.\nWhen you aren’t sure how something works in the person’s project, you ask instead of assuming.'+ ),+ does: [L('Explica, escreve e revisa código', 'Explains, writes and reviews code'), L('Descreve o plano antes de algo grande', 'Describes the plan before anything big'), L('Pesquisa a documentação quando precisa', 'Looks up the docs when it needs to')],+ task: L('me ajuda num projeto. Antes, me pergunta em que linguagem ele é e o que eu quero fazer.', 'help me with a project. First, ask me what language it’s in and what I want to do.'),+ connector: { id: 'linear', label: L('Ver as suas issues no Linear', 'See your Linear issues') }+ }+]++export const goalById = (id: string): Goal | undefined => GOALS().find((g) => g.id === id)++// Words that point to each goal, without accents, in both languages: the person's own words go to the+// goal they name most; none, and they get a helper made from what they said.+const WORDS: Record<GoalId, string[]> = {+ week: ['semana', 'agenda', 'calendar', 'organiz', 'tarefa', 'compromisso', 'lembr', 'prazo', 'rotina', 'planej', 'week', 'schedule', 'task', 'remind', 'deadline', 'planning'],+ research: ['pesquis', 'resum', 'noticia', 'estud', 'compar', 'descobr', 'research', 'summar', 'news', 'study', 'compare', 'find out', 'learn'],+ write: ['escrev', 'e-mail', 'email', 'post', 'texto', 'linkedin', 'newsletter', 'artigo', 'legenda', 'write', 'blog', 'article', 'caption', 'copy'],+ customers: ['client', 'atend', 'respond', 'whatsapp', 'instagram', 'loja', 'venda', 'suporte', 'pedido', 'customer', 'support', 'reply', 'store', 'shop', 'order', 'sales'],+ sheets: ['planilh', 'excel', 'sheets', 'tabela', 'financ', 'orcamento', 'gasto', 'numero', 'spreadsheet', 'table', 'budget', 'expense', 'invoice', 'numbers'],+ code: ['program', 'codigo', 'bug', 'site', 'aplicativo', 'deploy', 'github', 'script', 'code', 'coding', 'software', 'api', 'app']+}++const plain = (t: string): string => t.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase()++// The goal the person's words name most (ties go to the first in the list), or none. A word counts+// at the start of one of theirs ("organiz" in "organizar"), never inside another ("app" in "happy").+export function goalFromText(text: string): GoalId | undefined {+ const t = plain(text)+ const has = (w: string): boolean => new RegExp(`(^|[^a-z])${w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`).test(t)+ let best: GoalId | undefined+ let score = 0+ for (const id of GOAL_IDS) {+ const n = WORDS[id].filter(has).length+ if (n > score) (best = id), (score = n)+ }+ return best+}++// What the person typed, as an agent: the goal it names, with their words added to what it knows and+// sent as its first task; matched to nothing, a helper that starts from those words.+export function goalForText(text: string): Goal {+ const said = text.trim().replace(/\s+/g, ' ')+ const id = goalFromText(said)+ const base = id ? goalById(id)! : ownGoal()+ const note = L(`O que a pessoa contou que precisa: "${said}"`, `What the person said they need: "${said}"`)+ return { ...base, instructions: `${base.instructions}\n${note}`, task: firstTaskFrom(said) }+}++const ownGoal = (): Goal => ({+ id: 'own',+ title: '',+ name: 'Bia',+ role: L('Assistente', 'Assistant'),+ tagline: L('Ajuda no que você pediu', 'Helps with what you asked'),+ color: 'green',+ web: true,+ instructions: L(+ 'Você ajuda a pessoa com o que ela pediu, do jeito mais simples que funcionar.\nAntes de começar, pergunta o que falta pra entender a tarefa.\nResponde em listas curtas e fáceis de seguir.',+ 'You help the person with what they asked, in the simplest way that works.\nBefore starting, you ask what’s missing to understand the task.\nYou answer in short, easy-to-follow lists.'+ ),+ does: [L('Ajuda no que você pediu', 'Helps with what you asked'), L('Pesquisa na internet quando precisa', 'Searches the web when it needs to'), L('Te pergunta quando tiver dúvida', 'Asks you when it isn’t sure')],+ task: ''+})++// The first message from what the person said: lower-case start (it follows the @), and a nudge to ask first.+function firstTaskFrom(said: string): string {+ const s = said.replace(/[.!?…]+$/, '')+ const body = s ? s[0]!.toLowerCase() + s.slice(1) : ''+ return body ? `${body}. ${L('Antes de começar, me pergunta o que precisar.', 'Before you start, ask me whatever you need.')}` : ''+}++// ---------- the AI ----------++// Whether the agents have something to think with yet: still being checked, ready, or nothing.+export type AiState = 'checking' | 'ready' | 'none'++export function aiState(engines: Record<EngineId, EngineStatus>): AiState {+ const all = ENGINE_IDS.map((e) => engines[e])+ if (all.some((s) => s.loggedIn && !s.soon && !s.off)) return 'ready'+ return all.some((s) => s.checking) ? 'checking' : 'none'+}++// Installed but not signed in (Codex runs on a login of Tucano's own): one click away.+export const needsSignIn = (engines: Record<EngineId, EngineStatus>): EngineId[] => (['claude', 'codex'] as const).filter((e) => engines[e].installed && !engines[e].loggedIn && !engines[e].soon)++// The models for the two small jobs behind the scenes (who replies in a channel, and memory),+// picked for the person: the fastest one of a ready harness. A gateway names its own models,+// so there the person picks (undefined).+const FAST = /haiku|mini|flash|lite|fast|luna|spark|small/i+export const isFastModel = (id: string): boolean => FAST.test(id)++export function backgroundModel(engines: Record<EngineId, EngineStatus>, listed: Partial<Record<EngineId, string[]>> = {}): string | undefined {+ const ready = (e: EngineId): boolean => engines[e].loggedIn && !engines[e].soon && !engines[e].off && engines[e].route !== 'gateway'+ if (ready('claude')) return 'haiku'+ if (ready('codex')) {+ const catalog = listed.codex ?? []+ const fast = catalog.find((m) => FAST.test(m)) ?? catalog[0]+ return fast ? codexValue(fast) : MODELS.find((m) => m.engine === 'codex')!.id+ }+ for (const e of ENGINE_IDS) {+ if (e === 'claude' || e === 'codex' || !ready(e)) continue+ const models = listed[e] ?? []+ const pick = models.find((m) => FAST.test(m)) ?? models[0]+ if (pick) return customModel(e, pick)+ }+ return undefined+}++// The agent's own model: the everyday one of the first ready harness on a plan, or the first it lists.+export function agentModel(engines: Record<EngineId, EngineStatus>, listed: Partial<Record<EngineId, string[]>> = {}): string | undefined {+ const ready = (e: EngineId): boolean => engines[e].loggedIn && !engines[e].soon && !engines[e].off && engines[e].route !== 'gateway'+ if (ready('claude')) return 'sonnet'+ if (ready('codex')) return MODELS.find((m) => m.engine === 'codex')!.id+ for (const e of ENGINE_IDS) {+ const first = listed[e]?.[0]+ if (e !== 'claude' && e !== 'codex' && ready(e) && first) return customModel(e, first)+ }+ return undefined+}++// ---------- missions ----------++export const MISSION_IDS = ['talk', 'approve', 'connect', 'second', 'auto', 'remember'] as const+export type MissionId = (typeof MISSION_IDS)[number]++// The parts of the sidebar a new install starts without, each brought by a mission or by having something in it.+export type SidebarPart = 'memory' | 'wiki' | 'routines' | 'skills' | 'report' | 'usage' | 'connectors' | 'channels'++// What the missions look at, from the app's state (the renderer works it out).+export interface MissionFacts {+ replied: boolean // an agent finished a reply+ decided: boolean // an approval decided, or an agent's question answered+ connectors: number+ agents: number // the team's, not the Tuca+ routines: number+ memories: number // kept (active)+}++export interface Mission {+ id: MissionId+ title: (agent: string) => string+ how: string+ unlocks: SidebarPart[]+ unlockName: string // what it brings, as the sidebar names it+ done: (f: MissionFacts) => boolean+}++export const MISSIONS = (): Mission[] => [+ { id: 'talk', title: (a) => L(`Fale com ${a}`, `Talk to ${a}`), how: L('Mande uma mensagem e veja a resposta chegar.', 'Send a message and watch the reply come in.'), unlocks: ['usage', 'report'], unlockName: L('Uso e limites', 'Usage and limits'), done: (f) => f.replied },+ { id: 'approve', title: () => L('Aprove algo', 'Approve something'), how: L('Quando um agente quer fazer algo por conta própria, ele pede. Responda um pedido.', 'When an agent wants to do something on its own, it asks. Answer one request.'), unlocks: [], unlockName: '', done: (f) => f.decided },+ { id: 'connect', title: () => L('Conecte uma conta', 'Connect an account'), how: L('Sua agenda, seu e-mail ou outra ferramenta, pros agentes lerem por você.', 'Your calendar, email or another tool, for the agents to read for you.'), unlocks: ['connectors'], unlockName: L('Conectores', 'Connectors'), done: (f) => f.connectors > 0 },+ { id: 'second', title: () => L('Monte um segundo agente', 'Build a second agent'), how: L('Dois agentes num canal trabalham juntos.', 'Two agents in a channel work together.'), unlocks: ['channels', 'skills'], unlockName: L('Canais', 'Channels'), done: (f) => f.agents >= 2 },+ { id: 'auto', title: () => L('Deixe algo no automático', 'Put something on autopilot'), how: L('Uma tarefa que roda sozinha, todo dia ou toda semana.', 'A task that runs on its own, every day or every week.'), unlocks: ['routines'], unlockName: L('Rotinas', 'Routines'), done: (f) => f.routines > 0 },+ { id: 'remember', title: () => L('Guarde algo que importa', 'Keep something that matters'), how: L('O que o time precisa saber sempre, num lugar só.', 'What the team always needs to know, in one place.'), unlocks: ['memory', 'wiki'], unlockName: L('Memória e Wiki', 'Memory and Wiki'), done: (f) => f.memories > 0 }+]++export const missionsDone = (f: MissionFacts): Set<MissionId> => new Set(MISSIONS().filter((m) => m.done(f)).map((m) => m.id))++// The short sidebar is a new install's alone (never an existing one's), until "Mostrar tudo de uma vez".+export const shortSidebar = (o: Settings['onboarding']): boolean => !!o?.fresh && !o.showAll++// Whether a part of the sidebar shows: always, outside the short sidebar; in it, once its mission+// is done or once it has something in it.+export function partShows(part: SidebarPart, o: Settings['onboarding'], done: Set<MissionId>, has: Partial<Record<SidebarPart, boolean>> = {}): boolean {+ if (!shortSidebar(o) || has[part]) return true+ return MISSIONS().some((m) => m.unlocks.includes(part) && done.has(m.id))+}++// What a mission just brought that the person hasn't opened yet: marked new in the sidebar.+export const freshParts = (o: Settings['onboarding'], done: Set<MissionId>): SidebarPart[] =>+ shortSidebar(o) ? MISSIONS().filter((m) => done.has(m.id)).flatMap((m) => m.unlocks).filter((p) => !(o?.seen ?? []).includes(p)) : []++// ---------- the tour ----------++// The marks over the real screens, in the order they can come: the first message, the first request+// (whenever an agent makes one), the Tuca, and the missions.+export type TourMark = 'first' | 'ask' | 'tuca' | 'missions'++export const tourOn = (o: Settings['onboarding'], mark: TourMark): boolean => !!o?.tour && !o.tour.skipped && !(o.tour.done ?? []).includes(mark)++// "Tour · 2 de 3": the marks after the first message, numbered as they come.+export const tourCount = (o: Settings['onboarding'], withMissions: boolean): { at: number; of: number } => {+ const after = (o?.tour?.done ?? []).filter((m) => m !== 'first').length+ return { at: after + 1, of: withMissions ? 3 : 2 }+}++// ---------- how far the first agent goes on its own ----------+// "Quanto {nome} faz por conta própria?": three plain answers, each one of the autonomy levels+// (src/shared/actions.ts). Normal is the recommended one and comes picked.++export const FIRST_AUTONOMY: Autonomy = 'normal'++export interface AutonomyChoice {+ level: Autonomy+ title: string+ recommended?: boolean+}++export const AUTONOMY_CHOICES = (): AutonomyChoice[] => [+ { level: 'careful', title: L('Me pergunta antes de mudar qualquer coisa', 'Asks me before changing anything') },+ { level: 'normal', title: L('Faz o dia a dia por conta própria e pergunta antes do que importa', 'Handles the day to day and asks before what matters'), recommended: true },+ { level: 'free', title: L('Faz tudo por conta própria, até enviar e pagar', 'Does everything on its own, even sending and paying') }+]++// What still asks, in one line. True to verdict(): a high-risk action (or an app action that can't be+// placed) asks at any level, and with the outside-content guard on (the default), what goes out after+// reading something from outside asks too.+export function autonomyChoiceHint(level: Autonomy, guard = true): string {+ if (level === 'careful') return L('Pede antes de escrever num app, enviar, apagar ou clicar no que é arriscado. Ler e pesquisar nunca pede.', 'Asks before writing in an app, sending, deleting or a risky click. Reading and searching never ask.')+ if (level === 'normal') return L('Lê, pesquisa e organiza sem pedir. Pede antes de enviar, apagar, publicar, pagar ou clicar no que é arriscado.', 'Reads, searches and organizes without asking. Asks before sending, deleting, publishing, paying or a risky click.')+ return guard+ ? L('Ainda pede o que é de alto risco e, depois de ler algo de fora (um e-mail, uma página), antes de enviar, publicar, pagar ou apagar.', 'Still asks for what’s high risk and, after reading something from outside (an email, a page), before sending, publishing, paying or deleting.')+ : L('Ainda pede o que é de alto risco. O resto faz sem perguntar.', 'Still asks for what’s high risk. Everything else it does without asking.')+}++// What the agent keeps: Normal while Settings say Normal is left unset ("Padrão"), so the agent follows+// later changes in Settings; any other answer (or Normal when Settings say otherwise) is its own.+export const storedAutonomy = (choice: Autonomy, settingsLevel: Autonomy | undefined): Autonomy | undefined => (choice === 'normal' && (settingsLevel ?? 'normal') === 'normal' ? undefined : choice)++// The answer shown for an agent: its own level, else Settings', else Normal.+export const autonomyChosen = (agentLevel: Autonomy | undefined, settingsLevel: Autonomy | undefined): Autonomy => agentLevel ?? settingsLevel ?? 'normal'diff --git a/src/shared/rpc-shapes.ts b/src/shared/rpc-shapes.tsindex 53d0b6c..4f8cbe6 100644--- a/src/shared/rpc-shapes.ts+++ b/src/shared/rpc-shapes.ts@@ -45,6 +45,9 @@ export const SHAPES: Record<Method, Record<string, string>> = {loginAccount: { id: 's' },removeAccount: { id: 's' },installEngine: { engine: 's' },+ setupEngine: { engine: 's' },+ engineSetupState: {},+ cancelEngineSetup: {},desktopStatus: {},installedApps: {},openApps: {},diff --git a/src/shared/rpc.ts b/src/shared/rpc.tsindex b4fd500..bfc6c3a 100644--- a/src/shared/rpc.ts+++ b/src/shared/rpc.ts@@ -2,7 +2,7 @@import type { Answer } from './questions'import type { WikiChange, WikiHit, WikiPage, WikiImport, WikiPageInfo, WikiReview, WikiSource, WikiVersion } from './types'import type { AppProvider } from './connector-catalog'-import type { Os, Account, AccountEngine, ActivityEntry, Device, Inbox, Agent, BrowserInput, Approval, Artifact, ImageUpload, BrowserView, ComputerInfo, Connector, ConnectorInput, ConnectorTool, HarnessMcp, Conversation, EngineId, Invite, Memory, Person, Role, MemoryScope, Message, Routine, RoutineInput, Report, Settings, LocalSkill, Skill, SkillInput, SkillVersion, Trigger, UsageReport, LocalInfo, VoiceModelId, VoiceStatus } from './types'+import type { Os, Account, AccountEngine, ActivityEntry, Device, Inbox, Agent, BrowserInput, Approval, Artifact, ImageUpload, BrowserView, ComputerInfo, Connector, ConnectorInput, ConnectorTool, HarnessMcp, Conversation, EngineId, Invite, Memory, Person, Role, MemoryScope, Message, Routine, RoutineInput, Report, Settings, SetupState, LocalSkill, Skill, SkillInput, SkillVersion, Trigger, UsageReport, LocalInfo, VoiceModelId, VoiceStatus } from './types'export interface Snapshot {webhookPort?: number@@ -70,6 +70,9 @@ export interface Api {loginAccount(p: { id: string }): { opened: boolean; command: string }removeAccount(p: { id: string }): voidinstallEngine(p: { engine: EngineId }): { opened: boolean; command: string; needsNode?: boolean } // needsNode: an npm install with no npm here+ setupEngine(p: { engine: EngineId }): SetupState // Codex or Claude Code with no terminal: downloaded, then the CLI's own sign-in in the browser+ engineSetupState(): SetupState | null+ cancelEngineSetup(): voiddesktopStatus(): Promise<{ installed: boolean; version?: string; accessibility?: string; suggestion?: string; server?: boolean }> // agent-desktop, for the person's appsinstalledApps(): Promise<{ name: string; bundleId?: string; path?: string; icon?: string }[]> // the person's installed apps (a Mac's), kept on diskopenApps(): Promise<{ name: string; bundleId?: string }[]> // the apps with windows right now@@ -107,7 +110,7 @@ export interface Api {saveRoutine(p: { routine: RoutineInput }): Routine // throws a message for the formsetJevKey(p: { key: string | null }): Promise<void> // checks the key with TypeSafe; throws why it's refusedengineModels(p: { engine: EngineId }): Promise<{ models: string[]; labels?: Record<string, { label: string; hint?: string }>; error?: string }> // a harness's own list (OpenCode, Pi, a gateway)- testEngine(p: { model: string }): Promise<{ ok: boolean; message: string }> // one real reply through that model+ testEngine(p: { model: string }): Promise<{ ok: boolean; message: string; seconds?: number }> // one real reply through that modelsaveSkill(p: { skill: SkillInput }): Skill // throws a message for the formlocalSkills(): LocalSkill[] // the skills of the user's Claude Code, its plugins and CodexlinkSkill(p: { source: string; agents: string[] }): Skilldiff --git a/src/shared/types.ts b/src/shared/types.tsindex 27e0c02..720c652 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -415,7 +415,18 @@ 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; workspaceManagerSeen?: boolean; carried?: boolean } // carried: the general settings came from another workspace+ onboarding?: {+ done: boolean+ checklistHidden?: boolean // the missions, hidden from the sidebar+ workspaceManagerSeen?: boolean+ carried?: boolean // the general settings came from another workspace+ fresh?: boolean // a new install: the sidebar starts short and grows with the missions+ showAll?: boolean // "Mostrar tudo de uma vez": the whole sidebar, missions or not+ seen?: string[] // the sidebar parts a mission brought that the person already opened (no "new" tag)+ channel?: string // the channel the introduction made, where the first message waits+ tour?: { done?: string[]; skipped?: boolean } // the marks over the real screens, once each+ guest?: { by?: string } // someone just invited: their own short welcome first (who invited them)+ }folded?: string[] // the ids of what I folded in the sidebarsounds?: boolean // the toucan's chirp on a notification; unset: onseenVersion?: string // the last version whose news I closed; an update past it shows what's new once@@ -556,6 +567,18 @@ export const ENGINES: Record<EngineId, { label: string; cli: string; login: stri}export const ENGINE_IDS = Object.keys(ENGINES) as EngineId[]+// Codex or Claude Code being set up from the introduction, with no terminal (src/core/engine-setup.ts):+// getting the CLI, then the CLI's own sign-in (the screen does the test reply after).+export type SetupEngine = 'claude' | 'codex'+export interface SetupState {+ engine: SetupEngine+ step: 'install' | 'login'+ state: 'running' | 'done' | 'error' | 'cancelled'+ progress?: number // 0..1, while downloading+ url?: string // the sign-in page, in case the browser didn't open+ error?: string+}+// A harness starts picked only when it can actually run: one not installed or not// signed in yet starts off.export const startsPicked = (st: EngineStatus): boolean => !st.soon && st.loggedIndiff --git a/test/autonomy-core.test.ts b/test/autonomy-core.test.tsindex e4abb62..ab53e98 100644--- a/test/autonomy-core.test.ts+++ b/test/autonomy-core.test.ts@@ -59,6 +59,20 @@ describe("an agent's autonomy, saved from its page", () => {})})+describe("the introduction's agent", () => {+ it('is created with the level its answer gave, and left on "Padrão" for Normal', async () => {+ const { autonomy: _a, ...plain } = lia+ const make = async (handle: string, autonomy?: 'careful' | 'free'): Promise<Agent | undefined> => {+ // What the introduction sends: a new agent, its answer as the agent's own level (Normal: none).+ await ana.call('saveAgent', { agent: { ...plain, id: `intro-${handle}`, name: handle, handle, ...(autonomy ? { autonomy } : {}) }, channelIds: [] })+ return (await ana.call<Snap>('snapshot')).agents.find((a) => a.id === `intro-${handle}`)+ }+ expect((await make('cuidadosa', 'careful'))?.autonomy).toBe('careful')+ expect((await make('livre', 'free'))?.autonomy).toBe('free')+ expect((await make('normal'))?.autonomy).toBeUndefined()+ })+})+describe('autonomy for every agent, in Settings', () => {it('takes a level, rules and the guard', async () => {expect(await err(ana.call('updateSettings', { patch: { autonomy: 'careful', outsideGuard: false, actionRules: { delete: 'off' } } }))).toBe('ok')diff --git a/test/context.test.ts b/test/context.test.tsindex 8255159..e8124d5 100644--- a/test/context.test.ts+++ b/test/context.test.ts@@ -109,3 +109,19 @@ describe('transcript', () => {expect(next.at(-1)).toMatch(/^Edu aprovou o pedido\.\n\nAgora: .+\.$/)})})++describe('what waits for an approval, at the agent’s level', () => {+ const at = (a: Agent, autonomy?: 'careful' | 'normal' | 'free') => systemPrompt({ agent: a, settings: { workspaceName: 'Edu', context: '', autonomy }, conversation: dm, peers: [] })+ it('Normal (the default): sensitive actions become a request', () => {+ expect(at(theo)).toContain('Ações sensíveis (enviar, apagar, publicar, pagar) não rodam na hora')+ })+ it('Careful: anything that changes something asks, from Settings or the agent', () => {+ expect(at(theo, 'careful')).toContain('Edu quer aprovar tudo que muda algo')+ expect(at({ ...theo, autonomy: 'careful' }, 'free')).toContain('Edu quer aprovar tudo que muda algo')+ })+ it('No guardrails: it acts without asking, and never hears that sensitive actions wait', () => {+ const p = at({ ...theo, autonomy: 'free' })+ expect(p).toContain('Edu deixou você agir sem pedir aprovação')+ expect(p).not.toContain('Ações sensíveis')+ })+})diff --git a/test/engine-errors.test.ts b/test/engine-errors.test.tsnew file mode 100644index 0000000..8c56888--- /dev/null+++ b/test/engine-errors.test.ts@@ -0,0 +1,47 @@+// A harness's failure as people read it: one plain line with what to do, never a stack or a path;+// the raw text only for "Ver detalhes".+import { afterEach, describe, expect, it } from 'vitest'+import { setLang } from '../src/shared/lang'+import { explainEngineError, providerOf } from '../src/shared/engine-errors'++afterEach(() => setLang('pt'))++const PI_EXPIRED = `OAuth refresh failed for anthropic: 400 {"type":"error","error":{"type":"invalid_grant","message":"Refresh token expired"}}+ at postJson (file:///opt/homebrew/lib/node_modules/@earendil-works/pi-coding-agent/dist/auth/oauth.js:88:11)`++describe('a failing harness, in plain words', () => {+ it("Pi's expired Anthropic login: who, where, and what to do", () => {+ const p = explainEngineError('pi', PI_EXPIRED)+ expect(p.kind).toBe('login')+ expect(p.line).toBe('O login da Anthropic no Pi expirou. Entre de novo no Pi pra usar.')+ expect(p.line).not.toMatch(/file:|node_modules|at postJson|\n/)+ expect(p.details).toContain('at postJson')+ setLang('en')+ expect(explainEngineError('pi', PI_EXPIRED).line).toBe('The Anthropic sign-in in Pi expired. Sign in to Pi again to use it.')+ })++ it('other logins: 401, not logged in, an invalid key; the harness is the provider for Claude Code and Codex', () => {+ expect(explainEngineError('claude', 'API Error: 401 {"error":"authentication_error"}').line).toBe('O login do Claude Code não está valendo. Entre de novo no Claude Code pra usar.')+ expect(explainEngineError('codex', 'Not logged in. Run codex login.').kind).toBe('login')+ expect(explainEngineError('opencode', 'Invalid API key for openai').line).toBe('O login da OpenAI no OpenCode não está valendo. Entre de novo no OpenCode pra usar.')+ expect(explainEngineError('gemini', 'Please sign in again').kind).toBe('login')+ })++ it('a limit and a timeout get their own line', () => {+ expect(explainEngineError('claude', "You've hit your limit · resets 5pm")).toMatchObject({ kind: 'limit', line: 'O Claude Code chegou no limite de uso. Tente de novo mais tarde.' })+ expect(explainEngineError('codex', 'The operation was aborted due to timeout')).toMatchObject({ kind: 'timeout' })+ })++ it("anything else: a short generic line, the raw text kept for details; the core's own plain lines pass", () => {+ const p = explainEngineError('cursor', 'TypeError: Cannot read properties of undefined\n at run (/usr/local/lib/cursor/index.js:1:2)')+ expect(p).toMatchObject({ kind: 'other', line: 'O Cursor CLI não funcionou agora.' })+ expect(p.details).toContain('/usr/local/lib')+ expect(explainEngineError('codex', 'O modelo não respondeu.')).toEqual({ kind: 'other', line: 'O modelo não respondeu.' })+ })++ it('names the provider the message is about', () => {+ expect(providerOf('OAuth refresh failed for anthropic: x')).toBe('Anthropic')+ expect(providerOf('google token expired')).toBe('Google')+ expect(providerOf('something')).toBeUndefined()+ })+})diff --git a/test/engine-setup.test.ts b/test/engine-setup.test.tsnew file mode 100644index 0000000..61b9416--- /dev/null+++ b/test/engine-setup.test.ts@@ -0,0 +1,269 @@+// Codex and Claude Code set up with no terminal (src/core/engine-setup.ts): what to download for each+// system, the published checksum checked before anything is kept, the CLI's own sign-in driven as a+// process (its page's address read from its output), and what a failure or a cancel leaves.+// The network and the processes are stand-ins here.+import { createHash } from 'node:crypto'+import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { delimiter, join } from 'node:path'+import { describe, expect, it } from 'vitest'+import { claudeBinary, claudePlatform, CLAUDE_RELEASES, CODEX_RELEASE, codexAsset, codexTarget, EngineSetup, loginUrl, type SetupDeps } from '../src/core/engine-setup'+import type { EngineStatus, SetupEngine, SetupState } from '../src/shared/types'++const sha = (b: Buffer | string): string => createHash('sha256').update(b).digest('hex')++describe('what to download', () => {+ it("names Codex's build and Claude Code's platform for each system", () => {+ expect(codexTarget('mac', 'arm64')).toBe('aarch64-apple-darwin')+ expect(codexTarget('mac', 'x64')).toBe('x86_64-apple-darwin')+ expect(codexTarget('linux', 'x64')).toBe('x86_64-unknown-linux-musl')+ expect(codexTarget('linux', 'arm64')).toBe('aarch64-unknown-linux-musl')+ expect(codexTarget('windows', 'x64')).toBe('x86_64-pc-windows-msvc')+ expect(codexTarget('windows', 'arm64')).toBe('aarch64-pc-windows-msvc')+ expect(codexTarget('linux', 'ia32')).toBeUndefined()+ expect(claudePlatform('mac', 'arm64')).toBe('darwin-arm64')+ expect(claudePlatform('windows', 'x64')).toBe('win32-x64')+ expect(claudePlatform('linux', 'x64')).toBe('linux-x64')+ expect(claudePlatform('linux', 'arm64', true)).toBe('linux-arm64-musl')+ expect(claudePlatform('windows', 'ia32')).toBeUndefined()+ })++ it("takes Codex's package from the release, with its published sha256", () => {+ const digest = 'a'.repeat(64)+ const release = { tag_name: 'rust-v0.167.0', assets: [{ name: 'codex-aarch64-apple-darwin.tar.gz', browser_download_url: 'https://x/plain', digest: `sha256:${'b'.repeat(64)}` }, { name: 'codex-package-aarch64-apple-darwin.tar.gz', browser_download_url: 'https://x/pkg', digest: `sha256:${digest}` }] }+ expect(codexAsset(release, 'aarch64-apple-darwin')).toEqual({ version: '0.167.0', url: 'https://x/pkg', sha256: digest })+ expect(codexAsset(release, 'x86_64-pc-windows-msvc')).toBeUndefined()+ // Nothing without a checksum to check against.+ expect(codexAsset({ ...release, assets: [{ ...release.assets[1]!, digest: undefined }] }, 'aarch64-apple-darwin')).toBeUndefined()+ expect(codexAsset(null, 'aarch64-apple-darwin')).toBeUndefined()+ })++ it("takes Claude Code's binary from the version's manifest, only with a checksum", () => {+ const checksum = 'c'.repeat(64)+ const manifest = { platforms: { 'darwin-arm64': { checksum, size: 1 }, 'win32-x64': { checksum, binary: 'claude.exe' } } }+ expect(claudeBinary(manifest, '2.1.319', 'darwin-arm64')).toEqual({ version: '2.1.319', url: `${CLAUDE_RELEASES}/2.1.319/darwin-arm64/claude`, sha256: checksum })+ expect(claudeBinary(manifest, '2.1.319', 'win32-x64')?.url).toBe(`${CLAUDE_RELEASES}/2.1.319/win32-x64/claude.exe`)+ expect(claudeBinary(manifest, '2.1.319', 'linux-x64')).toBeUndefined()+ expect(claudeBinary({ platforms: { 'darwin-arm64': { checksum: 'nope' } } }, '2.1.319', 'darwin-arm64')).toBeUndefined()+ expect(claudeBinary(manifest, '<html>', 'darwin-arm64')).toBeUndefined()+ // A name that would leave the folder isn't taken.+ expect(claudeBinary({ platforms: { 'darwin-arm64': { checksum, binary: '../x' } } }, '2.1.319', 'darwin-arm64')?.url).toBe(`${CLAUDE_RELEASES}/2.1.319/darwin-arm64/claude`)+ })++ it('reads the sign-in page from what the CLI prints, colors and hyperlinks aside', () => {+ const codex = 'Starting local login server on http://localhost:1455.\nIf your browser did not open, navigate to this URL to authenticate:\n\nhttps://auth.openai.com/oauth/authorize?response_type=code&client_id=app_x&state=abc\n\n'+ expect(loginUrl(codex)).toBe('https://auth.openai.com/oauth/authorize?response_type=code&client_id=app_x&state=abc')+ const claude = "Opening browser to sign in…\nIf the browser didn't open, visit: \x1b]8;;https://claude.ai/oauth/authorize?code=true&state=s1\x07https://claude.ai/oauth/authorize?code=true&state=s1\x1b]8;;\x07\nPaste code here if prompted > "+ expect(loginUrl(claude)).toBe('https://claude.ai/oauth/authorize?code=true&state=s1')+ expect(loginUrl('\x1b[1mhttps://example.com/a\x1b[0m')).toBe('https://example.com/a')+ expect(loginUrl('nothing yet')).toBeUndefined()+ })+})++// A fake network: each URL answers what's given; a body is streamed in two pieces.+function network(routes: Record<string, unknown>): { fetch: typeof fetch; asked: string[] } {+ const asked: string[] = []+ const fetch: typeof globalThis.fetch = (async (url: string | URL | Request) => {+ const u = String(url)+ asked.push(u)+ const v = routes[u]+ if (v === undefined) return new Response('nope', { status: 404 })+ if (Buffer.isBuffer(v)) {+ const half = Math.floor(v.length / 2)+ const body = new ReadableStream({ start: (c) => (c.enqueue(new Uint8Array(v.subarray(0, half))), c.enqueue(new Uint8Array(v.subarray(half))), c.close()) })+ return new Response(body, { headers: { 'content-length': String(v.length) } })+ }+ return new Response(typeof v === 'string' ? v : JSON.stringify(v))+ }) as typeof globalThis.fetch+ return { fetch, asked }+}++// A fake CLI sign-in: prints, then ends with `code` (or never, until killed).+function signIn(print: string, code: number | null): { spawn: SetupDeps['spawn']; runs: { bin: string; args: string[]; env: NodeJS.ProcessEnv }[]; killed: () => boolean } {+ const runs: { bin: string; args: string[]; env: NodeJS.ProcessEnv }[] = []+ let killed = false+ return {+ runs,+ killed: () => killed,+ spawn: (bin, args, env) => {+ runs.push({ bin, args, env })+ let end: (c: number) => void = () => {}+ const exit = new Promise<number>((r) => (end = r))+ if (code !== null) setTimeout(() => end(code), 5)+ return { output: (on) => setTimeout(() => on(print), 1), exit, kill: () => ((killed = true), end(143)) }+ }+ }+}++function setup(over: Partial<SetupDeps> & { start?: EngineStatus; after?: EngineStatus }): { s: EngineSetup; dir: string; seen: SetupState[] } {+ const dir = mkdtempSync(join(tmpdir(), 'tucano-setup-'))+ let status: EngineStatus = over.start ?? { installed: false, loggedIn: false }+ const seen: SetupState[] = []+ const s: EngineSetup = new EngineSetup({+ dir,+ os: 'mac',+ arch: 'arm64',+ musl: () => false,+ fetch: network({}).fetch,+ untar: async () => {},+ spawn: signIn('', 0).spawn,+ status: () => status,+ recheck: async () => (status = over.after ?? { installed: true, loggedIn: true, path: '/x' }),+ env: (e: SetupEngine) => ({ WHO: e }),+ changed: () => void (s?.current && seen.push(s.current)),+ ...over+ })+ return { s, dir, seen }+}++const until = async (s: EngineSetup): Promise<void> => {+ for (let i = 0; i < 200 && s.current?.state === 'running'; i++) await new Promise((r) => setTimeout(r, 5))+}++describe('setting up Claude Code', () => {+ const binary = Buffer.from('the claude binary')+ const routes = (checksum = sha(binary)): Record<string, unknown> => ({+ [`${CLAUDE_RELEASES}/latest`]: '2.1.319\n',+ [`${CLAUDE_RELEASES}/2.1.319/manifest.json`]: { platforms: { 'darwin-arm64': { checksum } } },+ [`${CLAUDE_RELEASES}/2.1.319/darwin-arm64/claude`]: binary+ })++ it("downloads the checked binary into the app's folder, puts it on the PATH after the person's, then runs its own sign-in", async () => {+ const net = network(routes())+ const cli = signIn("Opening browser to sign in…\nIf the browser didn't open, visit: https://claude.ai/oauth/authorize?x=1\n", 0)+ const { s, dir, seen } = setup({ fetch: net.fetch, spawn: cli.spawn, after: { installed: true, loggedIn: false, path: '/dl/claude' } })+ let checks = 0+ // Installed and signed out after the download; signed in after the sign-in.+ ;(s as unknown as { deps: SetupDeps }).deps.recheck = async () => (++checks === 1 ? { installed: true, loggedIn: false, path: '/dl/claude' } : { installed: true, loggedIn: true, path: '/dl/claude' })+ s.start('claude')+ await until(s)+ expect(s.current).toMatchObject({ engine: 'claude', step: 'login', state: 'done' })+ // On the way: the download's progress, then the sign-in with its page, for "Abrir de novo".+ expect(seen.some((x) => x.step === 'install' && (x.progress ?? 0) > 0)).toBe(true)+ expect(seen.some((x) => x.step === 'login' && x.state === 'running' && x.url === 'https://claude.ai/oauth/authorize?x=1')).toBe(true)+ const bin = join(dir, 'claude', '2.1.319', 'claude')+ expect(readFileSync(bin, 'utf8')).toBe('the claude binary')+ expect(existsSync(`${bin}.part`)).toBe(false)+ expect(s.dirs()).toEqual([join(dir, 'claude', '2.1.319')])+ expect(s.withDirs(['/usr/bin', '/opt/homebrew/bin'].join(delimiter))).toBe(['/usr/bin', '/opt/homebrew/bin', join(dir, 'claude', '2.1.319')].join(delimiter))+ // The CLI's own sign-in, with the binary it just got.+ expect(cli.runs).toEqual([{ bin, args: ['auth', 'login'], env: { WHO: 'claude' } }])+ })++ it('keeps nothing when the file doesn\'t match the published checksum', async () => {+ const { s, dir } = setup({ fetch: network(routes('d'.repeat(64))).fetch })+ s.start('claude')+ await until(s)+ expect(s.current).toMatchObject({ step: 'install', state: 'error' })+ expect(s.current?.error).toMatch(/não bate|doesn't match/)+ expect(existsSync(join(dir, 'claude', '2.1.319', 'claude'))).toBe(false)+ expect(existsSync(join(dir, 'claude', '2.1.319', 'claude.part'))).toBe(false)+ expect(s.dirs()).toEqual([])+ })++ it('says so when the release server is out of reach', async () => {+ const { s } = setup({ fetch: network({}).fetch })+ s.start('claude')+ await until(s)+ expect(s.current).toMatchObject({ step: 'install', state: 'error' })+ })++ it("has no build for a system it doesn't support", async () => {+ const { s } = setup({ arch: 'ia32' })+ s.start('claude')+ await until(s)+ expect(s.current?.error).toMatch(/não tem uma versão|no build/)+ })+})++describe('setting up Codex', () => {+ const pkg = Buffer.from('a tarball')+ const release = { tag_name: 'rust-v0.167.0', assets: [{ name: 'codex-package-x86_64-pc-windows-msvc.tar.gz', browser_download_url: 'https://dl/pkg.tgz', digest: `sha256:${sha(pkg)}` }] }++ it("unpacks the package, finds its CLI by the package's own entry point, and signs in into the app's Codex home", async () => {+ const untarred: string[] = []+ const cli = signIn('Starting local login server on http://localhost:1455.\nhttps://auth.openai.com/oauth/authorize?a=1\nSuccessfully logged in\n', 0)+ const { s, dir, seen } = setup({+ os: 'windows',+ arch: 'x64',+ fetch: network({ [CODEX_RELEASE]: release, 'https://dl/pkg.tgz': pkg }).fetch,+ spawn: cli.spawn,+ untar: async (archive, into) => {+ untarred.push(readFileSync(archive, 'utf8'))+ mkdirSync(join(into, 'bin'), { recursive: true })+ writeFileSync(join(into, 'bin', 'codex.exe'), '')+ writeFileSync(join(into, 'codex-package.json'), JSON.stringify({ entrypoint: 'bin/codex' }))+ }+ })+ let checks = 0+ ;(s as unknown as { deps: SetupDeps }).deps.recheck = async () => (++checks === 1 ? { installed: true, loggedIn: false } : { installed: true, loggedIn: true })+ s.start('codex')+ await until(s)+ expect(untarred).toEqual(['a tarball'])+ expect(s.current).toMatchObject({ engine: 'codex', step: 'login', state: 'done' })+ expect(seen.some((x) => x.url === 'https://auth.openai.com/oauth/authorize?a=1')).toBe(true)+ const bin = join(dir, 'codex', '0.167.0', 'bin', 'codex.exe')+ expect(cli.runs).toEqual([{ bin, args: ['login'], env: { WHO: 'codex' } }])+ expect(s.dirs()).toEqual([join(dir, 'codex', '0.167.0', 'bin')])+ expect(existsSync(join(dir, 'codex', '0.167.0.tar.gz'))).toBe(false) // the archive goes once unpacked+ })++ it('skips the download when the CLI is there, and the sign-in when it is signed in', async () => {+ const net = network({})+ const cli = signIn('', 0)+ const { s } = setup({ fetch: net.fetch, spawn: cli.spawn, start: { installed: true, loggedIn: true, path: '/usr/local/bin/codex' } })+ s.start('codex')+ await until(s)+ expect(s.current).toMatchObject({ step: 'login', state: 'done' })+ expect(net.asked).toEqual([])+ expect(cli.runs).toEqual([])+ })++ it('uses the CLI the person has, for a sign-in only', async () => {+ const net = network({})+ const cli = signIn('', 0)+ const { s } = setup({ fetch: net.fetch, spawn: cli.spawn, start: { installed: true, loggedIn: false, path: '/usr/local/bin/codex' }, after: { installed: true, loggedIn: true } })+ s.start('codex')+ await until(s)+ expect(net.asked).toEqual([])+ expect(cli.runs.map((r) => [r.bin, ...r.args])).toEqual([['/usr/local/bin/codex', 'login']])+ expect(s.current).toMatchObject({ state: 'done' })+ })++ it("says the sign-in didn't work, with the CLI's last words, when it ends badly", async () => {+ const cli = signIn('Error logging in: the state did not match\n', 1)+ const { s } = setup({ spawn: cli.spawn, start: { installed: true, loggedIn: false, path: '/x/codex' }, after: { installed: true, loggedIn: false } })+ s.start('codex')+ await until(s)+ expect(s.current).toMatchObject({ step: 'login', state: 'error' })+ expect(s.current?.error).toContain('the state did not match')+ })++ it('stops a sign-in left open, on cancel or after its time', async () => {+ const cli = signIn('', null)+ const { s } = setup({ spawn: cli.spawn, start: { installed: true, loggedIn: false, path: '/x/codex' }, after: { installed: true, loggedIn: false } })+ s.start('codex')+ await new Promise((r) => setTimeout(r, 20))+ expect(s.current).toMatchObject({ step: 'login', state: 'running' })+ s.cancel()+ expect(s.current?.state).toBe('cancelled')+ expect(cli.killed()).toBe(true)+ await new Promise((r) => setTimeout(r, 20))+ expect(s.current?.state).toBe('cancelled') // the ended process doesn't turn it into an error++ const late = signIn('', null)+ const t = setup({ spawn: late.spawn, timeoutMs: 15, start: { installed: true, loggedIn: false, path: '/x/codex' }, after: { installed: true, loggedIn: false } })+ t.s.start('codex')+ await until(t.s)+ expect(late.killed()).toBe(true)+ expect(t.s.current?.state).toBe('error')+ })++ it('runs one setup at a time', async () => {+ const cli = signIn('', null)+ const { s } = setup({ spawn: cli.spawn, start: { installed: true, loggedIn: false, path: '/x/codex' } })+ s.start('codex')+ expect(s.start('claude').engine).toBe('codex')+ s.cancel()+ })+})diff --git a/test/onboarding-ui.test.tsx b/test/onboarding-ui.test.tsxnew file mode 100644index 0000000..f96081e--- /dev/null+++ b/test/onboarding-ui.test.tsx@@ -0,0 +1,410 @@+// The first run on screen: nothing set up (ChatGPT and Claude to set up here, or what to subscribe+// to), found ready (tested, in three clicks), the Tuca's question and the agent it makes, the first+// message left in #geral; someone invited and their welcome; the short sidebar of a new install and+// the missions. The core is a stand-in: what's sent to it is what's checked.+import { parseHTML } from 'linkedom'+import { act, useEffect } from 'react'+import type { Root } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { setLang } from '../src/shared/lang'+import type { Agent, EngineId, EngineStatus, Person, Settings } from '../src/shared/types'+import type { State } from '../src/renderer/src/store'++const { window, document } = parseHTML('<!doctype html><html><body><div id="root"></div></body></html>')+Object.assign(globalThis, { window, document, HTMLElement: window.HTMLElement, Node: window.Node, IS_REACT_ACT_ENVIRONMENT: true, matchMedia: () => ({ matches: true }) })+Object.assign(window, { tucano: {} })+// The conversation under "Ajustar com o Tuca" watches its size.+Object.assign(globalThis, { ResizeObserver: class { observe(): void {} unobserve(): void {} disconnect(): void {} } })+// React reads typing from the input event only where the document says it has one (linkedom doesn't).+Object.assign(document, { oninput: null })++vi.mock('open-bot-avatar/dom', () => ({ mountAvatar: () => new Proxy({}, { get: () => () => {} }) }))+// The opening animation: done at once.+vi.mock('../src/renderer/src/components/Splash', () => ({+ Splash: ({ onDone }: { onDone: () => void }) => {+ useEffect(onDone, [onDone])+ return null+ }+}))++let fake: State+vi.mock('../src/renderer/src/store', async (original) => {+ const real = await original<typeof import('../src/renderer/src/store')>()+ return {+ ...real,+ useStore: <T,>(select: (s: State) => T): T => select(fake),+ getState: () => fake,+ refreshEngines: vi.fn(),+ testEngine: vi.fn(async () => ({ ok: true, seconds: 1.2, message: 'ok' })),+ harnessMcps: vi.fn(async () => [{ key: 'claude:linear', name: 'Linear', address: 'https://mcp.linear.app/mcp', kind: 'remote', harnesses: ['claude'], added: false }]),+ importHarnessMcp: vi.fn(async () => 'c1'),+ localSkills: vi.fn(async () => [{ source: '/s/a', name: 'a', description: '', origin: 'Claude Code', scripts: false, bodyLength: 10 }]),+ linkSkill: vi.fn(async () => ({})),+ engineModels: vi.fn(async () => ({ models: [] })),+ setupEngine: vi.fn(async (engine: string) => ({ engine, step: 'install', state: 'running' })),+ engineSetupState: vi.fn(async () => null),+ newChannel: vi.fn(async () => 'ch1'),+ ensureTuca: vi.fn(async () => ({ conversationId: 't1' })),+ saveAgent: vi.fn(async () => {}),+ updateSettings: vi.fn(),+ navigate: vi.fn(),+ setMyName: vi.fn(async () => {}),+ openExternal: vi.fn(),+ loginEngine: vi.fn(async () => ({ opened: true, command: 'pi' })),+ voiceStatus: vi.fn(() => new Promise(() => {}))+ }+})+const store = await import('../src/renderer/src/store')+const { createRoot } = await import('react-dom/client')+const { Intro, GuestWelcome, foundTitle, continueLabel, leftOut } = await import('../src/renderer/src/components/Intro')+const { Sidebar } = await import('../src/renderer/src/components/Sidebar')+const { MissionsPage } = await import('../src/renderer/src/components/Missions')+const { Dialogs } = await import('../src/renderer/src/components/Dialogs')+const { askBody, askTitle } = await import('../src/renderer/src/components/Coach')++const off = (): EngineStatus => ({ installed: false, loggedIn: false })+const engines = (p: Partial<Record<EngineId, EngineStatus>> = {}): Settings['engines'] => ({ claude: off(), codex: off(), opencode: off(), pi: off(), gemini: off(), cursor: off(), grok: off(), ...p })++let root: Root+const base = (await vi.importActual<typeof import('../src/renderer/src/store')>('../src/renderer/src/store')).getState()+const ana: Person = { id: 'ana', name: 'Eduardo', role: 'owner', about: '' }+function state(p: Omit<Partial<State>, 'settings'> & { settings?: Partial<Settings> } = {}): State {+ return { ...base, ready: true, people: [], you: 'ana', agents: [], connectors: [], conversations: [], messages: {}, approvals: [], memories: [], routines: [], skills: [], tabs: {}, view: { kind: 'approvals' }, ...p, settings: { ...base.settings, workspaceName: 'Carol', engines: engines(), onboarding: { done: false, fresh: true }, ...p.settings } } as State+}++beforeEach(() => {+ fake = state()+ root = createRoot(document.getElementById('root')!)+})+afterEach(async () => {+ await act(async () => root.unmount())+ vi.clearAllMocks()+})++const text = (): string => document.body.textContent ?? ''+const tick = (): Promise<void> => act(async () => new Promise((r) => setTimeout(r, 10)))+const button = (name: RegExp): HTMLButtonElement => {+ const b = [...document.querySelectorAll('button')].find((x) => name.test((x.textContent ?? '').trim()) && !x.disabled)+ if (!b) throw new Error(`no enabled button ${name}: ${[...document.querySelectorAll('button')].map((x) => `${x.textContent}${x.disabled ? '(off)' : ''}`).join(' | ')}`)+ return b as HTMLButtonElement+}+const click = async (name: RegExp | Element): Promise<void> => {+ const b = name instanceof RegExp ? button(name) : name+ await act(async () => void b.dispatchEvent(new window.Event('click', { bubbles: true })))+ await tick()+}+// Typing as React sees it: the value set past React's own tracker, then the input event.+const type = async (input: HTMLInputElement, value: string): Promise<void> => {+ let proto: object | null = Object.getPrototypeOf(input)+ let set: ((v: string) => void) | undefined+ while (proto && !set) (set = Object.getOwnPropertyDescriptor(proto, 'value')?.set), (proto = Object.getPrototypeOf(proto))+ await act(async () => {+ set!.call(input, value)+ input.dispatchEvent(new window.Event('input', { bubbles: true }))+ })+}+const render = async (node: React.ReactNode): Promise<void> => {+ await act(async () => root.render(node))+ await tick()+}++describe('the first run', () => {+ it('with nothing set up: ChatGPT and Claude, set up here, or what to subscribe to; the escape hatch stays', async () => {+ await render(<Intro />)+ expect(text()).toContain('Seu time de IA')+ await click(/^Começar$/)+ expect(text()).toContain('Conectar a IA')+ expect(text()).toContain('O login é feito no site deles. O Tucano nunca vê a sua senha.')+ expect(text()).toContain('Uso chave de API, gateway da empresa ou outro programa')+ await click(/Não assino nenhuma/)+ expect(text()).toContain('você paga direto pra empresa, não pro Tucano')+ await click(button(/Ver os planos/))+ expect(store.openExternal).toHaveBeenCalledWith('https://chatgpt.com/pricing')+ await click(/ChatGPT/)+ expect(store.setupEngine).toHaveBeenCalledWith('codex')+ expect(text()).toContain('Preparando tudo no seu computador')+ expect(text()).toContain('Testar com uma resposta de verdade')+ // No jargon on the guided path.+ expect(text()).not.toMatch(/\b(MCP|harness|roteamento)\b/)+ })++ it('found ready: tested with a real reply, tools and skills to bring, the models picked; three clicks to the agent', async () => {+ fake = state({ settings: { engines: engines({ claude: { installed: true, loggedIn: true, route: 'plan', account: 'Plano Claude Max' } }) } })+ await render(<Intro />)+ await click(/^Começar$/)+ await tick()+ expect(text()).toContain('Achei 1 pronto pra usar')+ expect(store.testEngine).toHaveBeenCalledWith('haiku')+ expect(text()).toContain('Plano Claude Max · respondeu em 1,2 s')+ expect(text()).toContain('Também achei')+ expect(text()).toContain('Trazer 1 ferramenta do Claude Code')+ expect(text()).not.toContain('Linear')+ await click(/^ver qual$/)+ expect(text()).toContain('Linear')+ expect(text()).toContain('Modelos dos bastidores: Haiku pra escolher quem responde e pra memória.')+ // "Trocar": the two jobs as cards, each with its model and how quick it is, opening the app's Select.+ await click(/^Trocar$/)+ expect([...document.querySelectorAll('.intro-job__title')].map((x) => x.textContent)).toEqual(['Escolhe quem responde', 'Cuida da memória'])+ expect([...document.querySelectorAll('.intro-job b')].map((x) => x.textContent)).toEqual(['Haiku', 'Haiku'])+ expect([...document.querySelectorAll('.intro-job__tag')].map((x) => x.textContent)).toEqual(['rápido', 'rápido'])+ expect(document.querySelectorAll('.intro-job .select__trigger')).toHaveLength(2)+ expect(text()).not.toMatch(/\bMCP\b/)+ await click(/^Continuar$/)+ expect(store.importHarnessMcp).toHaveBeenCalledWith('claude:linear')+ expect(store.linkSkill).toHaveBeenCalledWith('/s/a')+ expect(text()).toContain('Qual é a primeira coisa que você queria tirar das suas costas?')+ await click(/Organizar minha semana/)+ expect(text()).toContain('O que Lia faz por você')+ expect(text()).toContain('Quanto Lia faz por conta própria?')+ expect(text()).toContain('Ver as suas tarefas no Todoist')+ expect(text()).not.toMatch(/Google/)+ await click(/Chamar Lia pro time/)+ await act(async () => new Promise((r) => setTimeout(r, 700)))+ expect(store.newChannel).toHaveBeenCalledWith('geral')+ const [saved, channels] = vi.mocked(store.saveAgent).mock.calls[0]! as [Agent, string[]]+ expect(channels).toEqual(['ch1'])+ // Safe by default: the web the goal needs, no computer, no browser of its own.+ expect(saved).toMatchObject({ name: 'Lia', handle: 'lia', web: true, computer: false, browser: false, modelId: 'sonnet' })+ // Normal, the recommended answer, untouched: the agent follows Settings ("Padrão").+ expect(saved.autonomy).toBeUndefined()+ // The models picked behind the scenes, the tour started in #geral, and nothing sent.+ expect(store.updateSettings).toHaveBeenCalledWith(expect.objectContaining({ routerModel: 'haiku', memoryModel: 'haiku', onboarding: { fresh: true, done: true, channel: 'ch1', tour: { done: [] } } }))+ expect(store.navigate).toHaveBeenCalledWith({ kind: 'conversation', id: 'ch1' })+ })++ it('a harness that fails its test says why in one line, and the one that works carries on', async () => {+ const expired = 'OAuth refresh failed for anthropic: 400 {"error":"invalid_grant","message":"Refresh token expired"}\n at postJson (file:///opt/homebrew/lib/node_modules/@earendil-works/pi-coding-agent/dist/auth.js:1:1)'+ vi.mocked(store.engineModels).mockImplementation(async (e: string) => ({ models: e === 'pi' ? ['anthropic/claude-haiku-4-5'] : [] }))+ vi.mocked(store.testEngine).mockImplementation(async (m: string) => (m.startsWith('pi') ? { ok: false, message: expired } : { ok: true, seconds: 1.2, message: 'ok' }))+ fake = state({ settings: { engines: engines({ claude: { installed: true, loggedIn: true, route: 'plan', account: 'Plano Claude Max' }, pi: { installed: true, loggedIn: true, route: 'providers', account: 'Anthropic' } }) } })+ await render(<Intro />)+ await click(/^Começar$/)+ await tick()+ await tick()+ expect(text()).toContain('O login da Anthropic no Pi expirou. Entre de novo no Pi pra usar.')+ // The raw text only inside "Ver detalhes".+ expect(document.querySelector('.engine-problem__line')!.textContent).not.toMatch(/file:|node_modules/)+ expect(document.querySelector('.engine-problem__more pre')!.textContent).toContain('at postJson')+ expect(document.querySelector('.intro-row.is-failed')).not.toBeNull()+ expect(text()).toContain('Pi fica de fora por agora')+ // Only what answered counts: Claude Code, not the Pi that failed.+ expect(text()).toContain('Achei 1 pronto pra usar')+ await click(/^Entrar de novo$/)+ expect(store.loginEngine).toHaveBeenCalledWith('pi')+ const before = vi.mocked(store.testEngine).mock.calls.length+ await click(/^Tentar de novo$/)+ expect(vi.mocked(store.testEngine).mock.calls.length).toBe(before + 1)+ expect(button(/^Continuar com Claude Code$/)).toBeTruthy()+ vi.mocked(store.engineModels).mockImplementation(async () => ({ models: [] }))+ vi.mocked(store.testEngine).mockImplementation(async () => ({ ok: true, seconds: 1.2, message: 'ok' }))+ })++ it('counts only what answered, says so while testing, and names who goes on', () => {+ expect(foundTitle(0, 2)).toBe('Testando o que achei…')+ expect(foundTitle(3, 0)).toBe('Achei 3 prontos pra usar')+ expect(foundTitle(1, 0)).toBe('Achei 1 pronto pra usar')+ expect(foundTitle(0, 0)).toBe('Nenhum respondeu ao teste')+ expect(continueLabel(['claude'])).toBe('Continuar com Claude Code')+ expect(continueLabel(['claude', 'codex', 'opencode'])).toBe('Continuar com os 3')+ expect(continueLabel([])).toBe('Continuar')+ expect(leftOut(['pi'])).toBe('Pi fica de fora por agora; dá pra arrumar em Configurações.')+ expect(leftOut(['opencode', 'pi'])).toBe('OpenCode e Pi ficam de fora por agora; dá pra arrumar em Configurações.')+ setLang('en')+ expect(foundTitle(1, 0)).toBe('Found 1 ready to use')+ expect(foundTitle(2, 0)).toBe('Found 2 ready to use')+ expect(continueLabel(['claude', 'codex'])).toBe('Continue with these 2')+ setLang('pt')+ })++ it("makes the agent from the person's own words", async () => {+ fake = state({ settings: { engines: engines({ codex: { installed: true, loggedIn: true, route: 'plan' } }) } })+ await render(<Intro />)+ await click(/^Começar$/)+ await click(/^Continuar$/)+ const input = document.querySelector<HTMLInputElement>('#intro-say')!+ await type(input, 'responder clientes da minha loja no Instagram')+ await act(async () => void document.querySelector('form.intro-say')!.dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true })))+ await tick()+ expect(text()).toContain('O que Duda faz por você')+ expect(text()).toContain('Ajuda a responder os seus clientes')+ })++ it('"Prefiro configurar do zero" opens the detailed form', async () => {+ fake = state({ settings: { engines: engines({ claude: { installed: true, loggedIn: true, route: 'plan' } }) } })+ await render(<Intro />)+ await click(/^Começar$/)+ await click(/^Continuar$/)+ await click(/Prefiro configurar do zero/)+ expect(text()).toContain('Quem vai trabalhar com você?')+ })+})++describe('how far the agent goes on its own', () => {+ const ready = (): State => state({ settings: { engines: engines({ claude: { installed: true, loggedIn: true, route: 'plan' } }) } })+ const toAgent = async (): Promise<void> => {+ await render(+ <>+ <Intro />+ <Dialogs />+ </>+ )+ await click(/^Começar$/)+ await click(/^Continuar$/)+ await click(/Organizar minha semana/)+ }+ const rows = (): HTMLButtonElement[] => [...document.querySelectorAll<HTMLButtonElement>('.autonomy-pick__row')]+ const picked = (): string => rows().find((r) => r.getAttribute('aria-checked') === 'true')?.textContent ?? ''+ const hint = (): string => document.querySelector('.autonomy-pick__hint')?.textContent ?? ''+ const create = async (): Promise<Agent> => {+ await click(/Chamar Lia pro time/)+ await act(async () => new Promise((r) => setTimeout(r, 700)))+ return vi.mocked(store.saveAgent).mock.calls[0]![0] as Agent+ }++ it('asks it on the agent, with Normal picked and recommended, and no lock line', async () => {+ fake = ready()+ await toAgent()+ expect(text()).toContain('Quanto Lia faz por conta própria?')+ expect(text()).not.toContain('pede o seu ok')+ expect(rows().map((r) => r.textContent)).toEqual(['Me pergunta antes de mudar qualquer coisa', 'Faz o dia a dia por conta própria e pergunta antes do que importaRecomendado', 'Faz tudo por conta própria, até enviar e pagar'])+ expect(picked()).toContain('Faz o dia a dia')+ expect(hint()).toContain('Pede antes de enviar, apagar, publicar, pagar')+ })++ it('creates the agent with Careful when that is the answer, and the hint follows', async () => {+ fake = ready()+ await toAgent()+ await click(rows()[0]!)+ expect(picked()).toContain('Me pergunta antes')+ expect(hint()).toContain('Pede antes de escrever num app')+ expect((await create()).autonomy).toBe('careful')+ })++ it('asks the same confirmation as Settings before No guardrails; cancelled, nothing changes', async () => {+ fake = ready()+ await toAgent()+ await click(rows()[2]!)+ expect(text()).toContain('Deixar agir sem travas?')+ expect(text()).toContain('Envia, apaga, publica, paga e clica sem te perguntar.')+ await click(/^Cancelar$/)+ expect(text()).not.toContain('Deixar agir sem travas?')+ expect(picked()).toContain('Faz o dia a dia')+ await click(rows()[2]!)+ await click(/^Sem travas$/)+ expect(picked()).toContain('Faz tudo por conta própria')+ expect(hint()).toContain('Ainda pede o que é de alto risco')+ expect((await create()).autonomy).toBe('free')+ })++ it('keeps Normal as the agent\'s own when Settings say otherwise', async () => {+ fake = ready()+ fake.settings.autonomy = 'careful'+ await toAgent()+ expect(picked()).toContain('Faz o dia a dia')+ expect((await create()).autonomy).toBe('normal')+ })++ it('is also in the detailed form, from "Prefiro configurar do zero"', async () => {+ fake = ready()+ await render(+ <>+ <Intro />+ <Dialogs />+ </>+ )+ await click(/^Começar$/)+ await click(/^Continuar$/)+ await click(/Prefiro configurar do zero/)+ await click(/^Continuar$/)+ expect(text()).toMatch(/Quanto .+ faz por conta própria\?/)+ expect(picked()).toContain('Faz o dia a dia')+ expect(text()).not.toContain('Nada disso acontece sem o seu ok')+ })++ it('"Ajustar com o Tuca" keeps the answer when his version is used', async () => {+ const tuca = { id: 'tuca', kind: 'tuca', name: 'Tuca', handle: 'tuca', role: '', color: 'amber', instructions: '', modelId: 'sonnet', effort: 'low', limit: 1, used: 0, grants: {}, memory: 'auto', computer: false, archived: false } as Agent+ const draft = { name: 'Lia', role: 'Agenda', color: 'violet', instructions: 'Organiza a semana, com mais calma.', modelId: 'sonnet', effort: 'low', web: true, grants: {} }+ const proposal = { id: 'm1', conversationId: 't1', author: { kind: 'agent', id: 'tuca' }, text: 'Assim?', at: 1, run: { status: 'done', steps: [], agentDraft: draft } } as unknown as State['messages'][string][number]+ fake = state({ agents: [tuca], conversations: [{ id: 't1', kind: 'dm', name: 'Tuca', members: ['tuca'] } as State['conversations'][number]], messages: { t1: [proposal] }, settings: { engines: engines({ claude: { installed: true, loggedIn: true, route: 'plan' } }) } })+ await toAgent()+ await click(rows()[0]!)+ await click(/Ajustar com o Tuca/)+ await click(/Usar esse agente/)+ expect(text()).toContain('O que Lia faz por você')+ expect(picked()).toContain('Me pergunta antes')+ const saved = await create()+ expect(saved).toMatchObject({ instructions: 'Organiza a semana, com mais calma.', autonomy: 'careful' })+ })++ it("the tour's balloon promises only what the level does", () => {+ expect(askTitle('Lia')).toBe('Quando Lia precisar de você, pede aqui.')+ expect(askBody('careful')).toContain('Antes de mudar qualquer coisa')+ expect(askBody('normal')).toContain('Antes de enviar, apagar, publicar ou pagar')+ expect(askBody('free')).toContain('só pede o que é de alto risco')+ expect(askBody('free')).toContain('depois de ler algo de fora')+ expect(askBody('free', false)).not.toContain('de fora')+ for (const l of ['careful', 'normal', 'free'] as const) expect(askTitle('Lia') + askBody(l)).not.toMatch(/Nada acontece sem você/)+ })+})++describe('someone invited to a team', () => {+ const lia: Agent = { id: 'a1', name: 'Lia', handle: 'lia', role: 'Pesquisa e resume', color: 'violet', instructions: '', modelId: 'sonnet', effort: 'low', limit: 1, used: 0, grants: {}, memory: 'auto', computer: false, archived: false }+ const marina: Person = { id: 'mar', name: 'Marina', role: 'member', about: '' }++ it('says who invited them, shows the team and the deal, and starts the short tour', async () => {+ fake = state({ people: [ana, marina, { id: 'rafa', name: 'Rafa', role: 'member', about: '' }], you: 'mar', agents: [lia], settings: { workspaceLabel: 'Agência Norte', onboarding: { done: true, guest: { by: 'Eduardo' } } } })+ await render(<GuestWelcome />)+ expect(text()).toContain('Eduardo te chamou pro time')+ expect(text()).toContain('Agência Norte')+ expect(text()).toContain('Pesquisa e resume')+ expect(text()).toContain('Eduardo e Rafa já estão aqui')+ expect(text()).toContain('O que você fala direto com um agente só você lê. Nem Eduardo.')+ expect(text()).toContain('Nos canais, o time todo vê.')+ expect(text()).toContain('Os agentes pedem o ok de quem decide antes do que o time combinou.')+ await click(/^Atendimento$/)+ await click(/Entrar no time/)+ expect(store.setMyName).toHaveBeenCalledWith('Marina', 'Atendimento')+ expect(store.updateSettings).toHaveBeenCalledWith({ onboarding: { done: true, tour: { done: ['first'] } } })+ })+})++describe('the sidebar and the missions', () => {+ const geral = { id: 'ch1', kind: 'channel', name: 'geral', members: ['a1'] } as State['conversations'][number]+ const lia: Agent = { id: 'a1', name: 'Lia', handle: 'lia', role: 'Agenda', color: 'violet', instructions: '', modelId: 'sonnet', effort: 'low', limit: 1, used: 0, grants: {}, memory: 'auto', computer: false, archived: false }+ const labels = (): string[] => [...document.querySelectorAll('.nav-item__label')].map((x) => x.textContent ?? '')++ it('starts short on a new install: the Tuca, what waits on you, the channel, the agent, the missions, the settings', async () => {+ fake = state({ agents: [lia], conversations: [geral], settings: { onboarding: { done: true, fresh: true } } })+ await render(<Sidebar />)+ expect(labels()).toEqual(['Tuca', 'Aprovações', 'geral', 'Lia', 'Configurações'])+ expect(text()).toContain('Missões')+ expect(text()).toContain('Próxima: fale com Lia')+ })++ it('grows as missions bring parts, tagged new until opened', async () => {+ fake = state({ agents: [lia], conversations: [geral], connectors: [{ id: 'c1' } as State['connectors'][number]], settings: { onboarding: { done: true, fresh: true } } })+ await render(<Sidebar />)+ expect(labels()).toContain('Conectores')+ expect(document.querySelector('.nav-item.is-fresh')?.textContent).toContain('NOVO')+ expect(text()).toContain('Você liberou Conectores')+ await click(document.querySelector('.nav-item.is-fresh')!)+ expect(store.updateSettings).toHaveBeenCalledWith({ onboarding: { done: true, fresh: true, seen: ['connectors'] } })+ })++ it('is whole for someone who already used Tucano, and after "Mostrar tudo de uma vez"', async () => {+ for (const onboarding of [undefined, { done: true }, { done: true, fresh: true, showAll: true }]) {+ fake = state({ agents: [lia], conversations: [geral], settings: { onboarding } })+ await render(<Sidebar />)+ expect(labels()).toEqual(expect.arrayContaining(['Memória', 'Wiki', 'Rotinas', 'Skills', 'Boletim', 'Uso e limites', 'Conectores']))+ }+ })++ it('lists the six missions, with what each brings, and turns the short sidebar off on request', async () => {+ fake = state({ agents: [lia], conversations: [geral], settings: { onboarding: { done: true, fresh: true } } })+ await render(<MissionsPage />)+ expect([...document.querySelectorAll('.mission > b')].map((b) => b.textContent)).toEqual(['Fale com Lia', 'Aprove algo', 'Conecte uma conta', 'Monte um segundo agente', 'Deixe algo no automático', 'Guarde algo que importa'])+ expect(text()).toContain('Libera Conectores')+ await click(/Mostrar tudo de uma vez/)+ expect(store.updateSettings).toHaveBeenCalledWith({ onboarding: { done: true, fresh: true, showAll: true } })+ })+})diff --git a/test/onboarding.test.ts b/test/onboarding.test.tsnew file mode 100644index 0000000..1fdccb4--- /dev/null+++ b/test/onboarding.test.ts@@ -0,0 +1,264 @@+// The guided first run's rules: which AI is ready, the models picked behind the scenes, the goals+// and the agent each one starts, the missions and the sidebar they grow (new installs only), the+// tour's marks, and someone invited getting their own welcome.+import { afterEach, describe, expect, it } from 'vitest'+import { setLang } from '../src/shared/lang'+import { CATALOG } from '../src/shared/connector-catalog'+import { agentModel, aiState, AUTONOMY_CHOICES, autonomyChoiceHint, autonomyChosen, backgroundModel, FIRST_AUTONOMY, freshParts, GOAL_IDS, goalById, goalForText, goalFromText, GOALS, MISSIONS, missionsDone, needsSignIn, partShows, shortSidebar, storedAutonomy, tourCount, tourOn, type MissionFacts } from '../src/shared/onboarding'+import { actionMode, levelOf, policyOf, verdict } from '../src/shared/actions'+import { ENGINE_IDS, type EngineId, type EngineStatus, type Settings } from '../src/shared/types'+import { Db } from '../src/core/db'+import { initializeWorkspace } from '../src/core/seed'+import { People } from '../src/core/people'++afterEach(() => setLang('pt'))++const none = (): Record<EngineId, EngineStatus> => Object.fromEntries(ENGINE_IDS.map((e) => [e, { installed: false, loggedIn: false }])) as Record<EngineId, EngineStatus>+const with_ = (p: Partial<Record<EngineId, EngineStatus>>): Record<EngineId, EngineStatus> => ({ ...none(), ...p })+const plan = (account = 'Plano'): EngineStatus => ({ installed: true, loggedIn: true, route: 'plan', account })++describe('which AI is ready', () => {+ it('is still being checked, then none, then ready', () => {+ const checking = Object.fromEntries(ENGINE_IDS.map((e) => [e, { installed: false, loggedIn: false, checking: true }])) as Record<EngineId, EngineStatus>+ expect(aiState(checking)).toBe('checking')+ expect(aiState(none())).toBe('none')+ expect(aiState(with_({ codex: plan() }))).toBe('ready')+ // Ready wins over a check still running for the others.+ expect(aiState({ ...checking, claude: plan() })).toBe('ready')+ })++ it("doesn't count a harness turned off or not run yet", () => {+ expect(aiState(with_({ claude: { ...plan(), off: true } }))).toBe('none')+ expect(aiState(with_({ cursor: { ...plan(), soon: true } }))).toBe('none')+ })++ it('offers a sign-in for what is installed and signed out (Codex runs on a login of its own)', () => {+ expect(needsSignIn(with_({ codex: { installed: true, loggedIn: false }, claude: plan() }))).toEqual(['codex'])+ expect(needsSignIn(with_({ opencode: { installed: true, loggedIn: false } }))).toEqual([])+ })+})++describe('the models behind the scenes and the agent’s', () => {+ it("picks Claude's quick one on a plan, then Codex's, then a provider's fastest listed", () => {+ expect(backgroundModel(with_({ claude: plan(), codex: plan() }))).toBe('haiku')+ expect(backgroundModel(with_({ codex: plan() }), { codex: ['gpt-5.6-sol', 'gpt-5.6-luna'] })).toBe('gpt-5.6-luna')+ expect(backgroundModel(with_({ codex: plan() }), { codex: ['gpt-6', 'gpt-6-mini'] })).toBe('codex:gpt-6-mini')+ expect(backgroundModel(with_({ codex: plan() }))).toBe('gpt-5.6-luna')+ expect(backgroundModel(with_({ opencode: { installed: true, loggedIn: true, route: 'providers' } }), { opencode: ['openai/gpt-5.5', 'google/gemini-3-flash'] })).toBe('opencode:google/gemini-3-flash')+ })++ it('leaves it to the person on a gateway, which names its own models', () => {+ expect(backgroundModel(with_({ claude: { ...plan(), route: 'gateway', gateway: 'gw.example.com' } }))).toBeUndefined()+ expect(backgroundModel(none())).toBeUndefined()+ })++ it("gives the agent the everyday model of what's ready", () => {+ expect(agentModel(with_({ claude: plan() }))).toBe('sonnet')+ expect(agentModel(with_({ codex: plan() }))).toBe('gpt-5.6-luna')+ expect(agentModel(with_({ pi: { installed: true, loggedIn: true, route: 'providers' } }), { pi: ['anthropic/claude-x'] })).toBe('pi:anthropic/claude-x')+ expect(agentModel(none())).toBeUndefined()+ })+})++describe('the goals', () => {+ it('has the six tiles, in both languages, each a whole agent with no jargon', () => {+ for (const l of ['pt', 'en'] as const) {+ setLang(l)+ const goals = GOALS()+ expect(goals.map((g) => g.id)).toEqual([...GOAL_IDS])+ for (const g of goals) {+ expect(g.name.length).toBeGreaterThanOrEqual(2)+ expect(g.title && g.role && g.tagline && g.instructions && g.task).toBeTruthy()+ expect(g.does).toHaveLength(3)+ expect(`${g.title} ${g.tagline} ${g.does.join(' ')} ${g.connector?.label ?? ''}`).not.toMatch(/\b(MCP|harness|roteamento|routing)\b/i)+ }+ }+ setLang('pt')+ expect(GOALS()[0]!.title).toBe('Organizar minha semana')+ setLang('en')+ expect(GOALS()[0]!.title).toBe('Organize my week')+ })++ it('turns on the web only where the goal needs it, and offers a connector that exists', () => {+ expect(goalById('research')!.web).toBe(true)+ expect(goalById('customers')!.web).toBe(false)+ expect(goalById('sheets')!.web).toBe(false)+ expect(goalById('research')!.connector).toBeUndefined()+ })++ it('offers only a connector that signs in with one click, and only where it helps', () => {+ expect(Object.fromEntries(GOALS().map((g) => [g.id, g.connector?.id]))).toEqual({ week: 'todoist', research: undefined, write: 'notion', customers: undefined, sheets: undefined, code: 'linear' })+ for (const g of GOALS()) {+ if (!g.connector) continue+ const entry = CATALOG.find((e) => e.id === g.connector!.id)!+ // Browser OAuth with no app of the person's own, no token, nothing to fill in, nobody else's servers.+ expect(entry).toMatchObject({ auth: 'oauth' })+ expect(entry.app ?? entry.fields ?? entry.local ?? entry.warning).toBeUndefined()+ expect(entry.id).not.toMatch(/^google-|^gmail$|composio/)+ }+ })++ it("matches the person's own words to a goal, accents and all", () => {+ expect(goalFromText('responder clientes da minha loja no Instagram')).toBe('customers')+ expect(goalFromText('Quero organizar minha agenda e os prazos')).toBe('week')+ expect(goalFromText('resumir as notícias do meu setor')).toBe('research')+ expect(goalFromText('escrever posts pro LinkedIn')).toBe('write')+ expect(goalFromText('cuidar do orçamento na planilha')).toBe('sheets')+ expect(goalFromText('arrumar um bug no meu site')).toBe('code')+ expect(goalFromText('help me reply to customers of my shop')).toBe('customers')+ expect(goalFromText('xyz')).toBeUndefined()+ })++ it('builds the agent from those words: what they said goes to what it knows and to its first message', () => {+ const g = goalForText('responder clientes da minha loja no Instagram.')+ expect(g.id).toBe('customers')+ expect(g.instructions).toContain('"responder clientes da minha loja no Instagram."')+ expect(g.task).toBe('responder clientes da minha loja no Instagram. Antes de começar, me pergunta o que precisar.')+ const own = goalForText('Cuidar das plantas do escritório')+ expect(own.id).toBe('own')+ expect(own.name).toBeTruthy()+ expect(own.task.startsWith('cuidar das plantas do escritório.')).toBe(true)+ })+})++const facts = (f: Partial<MissionFacts> = {}): MissionFacts => ({ replied: false, decided: false, connectors: 0, agents: 1, routines: 0, memories: 0, ...f })++describe('the missions', () => {+ it('are the six, each checking itself off from what happened', () => {+ expect(MISSIONS().map((m) => m.id)).toEqual(['talk', 'approve', 'connect', 'second', 'auto', 'remember'])+ expect([...missionsDone(facts())]).toEqual([])+ expect([...missionsDone(facts({ replied: true, decided: true, connectors: 1, agents: 2, routines: 1, memories: 1 }))]).toHaveLength(6)+ expect(missionsDone(facts({ agents: 2 })).has('second')).toBe(true)+ expect(missionsDone(facts({ memories: 1 })).has('remember')).toBe(true)+ })++ it('grow the short sidebar: a part shows once its mission is done, or once it has something in it', () => {+ const fresh: Settings['onboarding'] = { done: true, fresh: true }+ expect(shortSidebar(fresh)).toBe(true)+ expect(partShows('connectors', fresh, missionsDone(facts()))).toBe(false)+ expect(partShows('connectors', fresh, missionsDone(facts({ connectors: 1 })))).toBe(true)+ expect(partShows('routines', fresh, missionsDone(facts()), { routines: true })).toBe(true)+ expect(partShows('wiki', fresh, missionsDone(facts({ memories: 2 })))).toBe(true)+ expect(partShows('channels', fresh, missionsDone(facts({ agents: 2 })))).toBe(true)+ expect(partShows('usage', fresh, missionsDone(facts({ replied: true })))).toBe(true)+ })++ it('tag what they just brought until it is opened', () => {+ const done = missionsDone(facts({ connectors: 1 }))+ expect(freshParts({ done: true, fresh: true }, done)).toEqual(['connectors'])+ expect(freshParts({ done: true, fresh: true, seen: ['connectors'] }, done)).toEqual([])+ })++ it('never shorten the sidebar of an install that had one, nor after "Mostrar tudo de uma vez"', () => {+ for (const o of [undefined, { done: true }, { done: true, checklistHidden: true }, { done: true, fresh: true, showAll: true }] as Settings['onboarding'][]) {+ expect(shortSidebar(o)).toBe(false)+ for (const part of ['memory', 'wiki', 'routines', 'skills', 'report', 'usage', 'connectors', 'channels'] as const) expect(partShows(part, o, new Set())).toBe(true)+ expect(freshParts(o, missionsDone(facts({ connectors: 1 })))).toEqual([])+ }+ })+})++describe('a new install, an existing one, and a workspace made from the switcher', () => {+ const defaults = { workspaceName: 'Eu', context: '', routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1, approvalTtlHours: 1, theme: 'system', language: 'pt' } as Omit<Settings, 'engines'>++ it('marks only a new install for the short sidebar', () => {+ const fresh = new Db(':memory:')+ initializeWorkspace(fresh, {})+ expect(fresh.getSettings(defaults).onboarding).toEqual({ done: false, fresh: true })+ const switcher = new Db(':memory:')+ initializeWorkspace(switcher, { TUCANO_DEFAULT_WORKSPACE: '0' })+ expect(switcher.getSettings(defaults).onboarding).toEqual({ done: false })+ })++ it('leaves an existing install alone: no introduction, no short sidebar', () => {+ const file = new Db(':memory:')+ file.setSettings({ onboarding: { done: true } })+ const again = file.getSettings(defaults).onboarding+ expect(again).toEqual({ done: true })+ expect(shortSidebar(again)).toBe(false)+ })+})++describe('the tour', () => {+ it('shows each mark once, unless the whole tour was skipped', () => {+ expect(tourOn(undefined, 'first')).toBe(false)+ expect(tourOn({ done: true }, 'ask')).toBe(false) // before the introduction ended, or an install from before+ expect(tourOn({ done: true, tour: {} }, 'ask')).toBe(true)+ expect(tourOn({ done: true, tour: { done: ['ask'] } }, 'ask')).toBe(false)+ expect(tourOn({ done: true, tour: { skipped: true } }, 'tuca')).toBe(false)+ })++ it('numbers the marks after the first message as they come', () => {+ expect(tourCount({ done: true, tour: { done: ['first'] } }, true)).toEqual({ at: 1, of: 3 })+ expect(tourCount({ done: true, tour: { done: ['first', 'tuca'] } }, true)).toEqual({ at: 2, of: 3 })+ expect(tourCount({ done: true, tour: { done: ['first'] } }, false)).toEqual({ at: 1, of: 2 })+ })+})++describe('someone invited', () => {+ it('gets their own welcome, with who invited them; someone coming back does not', () => {+ const db = new Db(':memory:')+ const people = new People(db)+ db.renamePerson(db.ownerId(), 'Eduardo', false)+ const owner = db.owner()+ const r = people.join(people.createInvite(owner, { role: 'member' }).code, 'Marina')+ if (!('person' in r)) throw new Error(r.error)+ const s = people.settingsFor(r.person, { ...defaultsFor(), onboarding: { done: false, fresh: true } } as Settings)+ expect(s.onboarding).toEqual({ done: true, guest: { by: 'Eduardo' } })+ // In: the plain done, and the tour starts at the first request.+ people.takePrefs(r.person, { onboarding: { done: true, tour: { done: ['first'] } } })+ expect(people.settingsFor(r.person, defaultsFor() as Settings).onboarding).toEqual({ done: true, tour: { done: ['first'] } })+ // The owner never gets it.+ expect(people.settingsFor(owner, { ...defaultsFor(), onboarding: { done: true } } as Settings).onboarding).toEqual({ done: true })+ })+})++const defaultsFor = (): Omit<Settings, 'engines'> => ({ workspaceName: 'Eduardo', context: '', routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1, approvalTtlHours: 1, theme: 'system', language: 'pt' }) as Omit<Settings, 'engines'>++describe('how far the first agent goes on its own', () => {+ it('offers three answers, each one level, in order, with Normal recommended', () => {+ expect(AUTONOMY_CHOICES().map((c) => [c.title, c.level])).toEqual([+ ['Me pergunta antes de mudar qualquer coisa', 'careful'],+ ['Faz o dia a dia por conta própria e pergunta antes do que importa', 'normal'],+ ['Faz tudo por conta própria, até enviar e pagar', 'free']+ ])+ expect(AUTONOMY_CHOICES().filter((c) => c.recommended).map((c) => c.level)).toEqual(['normal'])+ setLang('en')+ expect(AUTONOMY_CHOICES().map((c) => c.title)).toEqual(['Asks me before changing anything', 'Handles the day to day and asks before what matters', 'Does everything on its own, even sending and paying'])+ })++ it('starts on Normal, kept as the agent\'s "Padrão" so it follows Settings later', () => {+ expect(FIRST_AUTONOMY).toBe('normal')+ expect(storedAutonomy(FIRST_AUTONOMY, undefined)).toBeUndefined()+ expect(storedAutonomy('normal', 'normal')).toBeUndefined()+ expect(autonomyChosen(undefined, undefined)).toBe('normal')+ // A later change in Settings reaches an agent left on "Padrão".+ expect(levelOf(policyOf({ autonomy: storedAutonomy('normal', undefined) }, { autonomy: 'careful' }))).toBe('careful')+ })++ it('keeps Careful and No guardrails as the agent\'s own, and Normal too when Settings say otherwise', () => {+ expect(storedAutonomy('careful', undefined)).toBe('careful')+ expect(storedAutonomy('free', 'normal')).toBe('free')+ expect(storedAutonomy('normal', 'careful')).toBe('normal')+ expect(autonomyChosen(storedAutonomy('normal', 'careful'), 'careful')).toBe('normal')+ expect(autonomyChosen('free', 'careful')).toBe('free')+ expect(levelOf(policyOf({ autonomy: 'careful' }, { autonomy: 'free' }))).toBe('careful')+ })++ it('says plainly what still asks, true to the rules', () => {+ const p = (a: 'careful' | 'normal' | 'free') => policyOf({ autonomy: storedAutonomy(a, undefined) }, {})+ // Careful: any change asks. Normal: what's sensitive asks. No guardrails: high risk still asks, and the guard is on.+ expect(verdict({ cls: 'write', kinds: [], p: p('careful') }).run).toBe(false)+ expect(autonomyChoiceHint('careful')).toContain('Pede antes de escrever num app')+ expect(verdict({ cls: 'write', kinds: [], p: p('normal') }).run).toBe(true)+ expect(verdict({ cls: 'sensitive', kinds: ['send'], p: p('normal') }).run).toBe(false)+ expect(autonomyChoiceHint('normal')).toContain('Pede antes de enviar, apagar, publicar, pagar')+ expect(actionMode('send', p('free'))).toBe('auto')+ expect(verdict({ cls: 'sensitive', kinds: ['send'], p: p('free') }).run).toBe(true)+ expect(verdict({ cls: 'sensitive', kinds: ['send'], p: p('free'), highRisk: true }).run).toBe(false)+ expect(verdict({ cls: 'sensitive', kinds: ['send'], p: p('free'), outside: true }).why).toBe('guard')+ expect(autonomyChoiceHint('free')).toContain('alto risco')+ expect(autonomyChoiceHint('free')).toContain('depois de ler algo de fora')+ expect(autonomyChoiceHint('free', false)).not.toContain('de fora')+ })+})diff --git a/test/people-prefs.test.ts b/test/people-prefs.test.tsindex 12a6802..e3a9e05 100644--- a/test/people-prefs.test.ts+++ b/test/people-prefs.test.ts@@ -62,11 +62,15 @@ describe('display preferences per person', () => {it("someone else starts with the Tucano's theme and language, no sidebar or sounds of the owner's, and never the setup introduction", () => {const { people, bia } = team()- expect(people.settingsFor(bia, { ...base, onboarding: { done: false } }).onboarding).toEqual({ done: true })+ // Someone who joins gets their own short welcome (who invited them), never the setup introduction.+ expect(people.settingsFor(bia, { ...base, onboarding: { done: false } }).onboarding).toEqual({ done: true, guest: { by: 'Ana' } })const s = people.settingsFor(bia, base)expect(s.theme).toBe('dark')expect(s.language).toBe('pt')- expect(s.onboarding).toEqual({ done: true })+ expect(s.onboarding).toEqual({ done: true, guest: { by: 'Ana' } })+ // Once they're in, it's the plain done.+ people.takePrefs(bia, { onboarding: { done: true } })+ expect(people.settingsFor(bia, base).onboarding).toEqual({ done: true })expect(s.seenVersion).toBe('0.2.10')expect(s.sounds).toBeUndefined()expect(s.folded).toBeUndefined()@@ -85,7 +89,8 @@ describe('display preferences per person', () => {expect(people.settingsFor(dani, base).theme).toBe('dark')// An admin's mixed change: the theme is theirs, the context the Tucano's.expect(people.takePrefs(dani, { theme: 'light', context: 'novo' })).toEqual({ context: 'novo' })- expect(db.prefs(dani.id)).toEqual({ theme: 'light' })+ const { onboarding: _welcome, ...prefs } = db.prefs(dani.id)+ expect(prefs).toEqual({ theme: 'light' })// Kept across changes: one key at a time.people.takePrefs(bia, { theme: 'system' })expect(people.settingsFor(bia, base)).toMatchObject({ theme: 'system', language: 'en' })diff --git a/test/rpc-fuzz.test.ts b/test/rpc-fuzz.test.tsindex e2963ab..34b191a 100644--- a/test/rpc-fuzz.test.ts+++ b/test/rpc-fuzz.test.ts@@ -13,7 +13,7 @@ const api = rpc.slice(rpc.indexOf('export interface Api {'))const methods = [...api.matchAll(/^ {2}(\w+)\((?:p: \{([^\n]*?)\})?\)/gm)].map((m) => ({ name: m[1]!, fields: [...(m[2] ?? '').matchAll(/(?:^|;)\s*(\w+)\??:/g)].map((f) => f[1]!) }))// What opens something on this computer (a terminal, a browser, a folder) or goes out to the// internet when given a well-typed value: called only with values the guard refuses.-const OUTSIDE = new Set(['installEngine', 'loginEngine', 'loginAccount', 'openLocal', 'openExternal', 'setTelegramToken', 'setJevKey', 'wikiAddLink', 'authorizeConnector', 'finishConnectorAuth', 'setWikiDir', 'harnessMcps', 'importHarnessMcp'])+const OUTSIDE = new Set(['installEngine', 'setupEngine', 'loginEngine', 'loginAccount', 'openLocal', 'openExternal', 'setTelegramToken', 'setJevKey', 'wikiAddLink', 'authorizeConnector', 'finishConnectorAuth', 'setWikiDir', 'harnessMcps', 'importHarnessMcp'])const crashes: unknown[] = []const onCrash = (e: unknown): void => void crashes.push(e)let owner: Clientdiff --git a/test/team-fixes.test.ts b/test/team-fixes.test.tsindex b891bc8..a7efb95 100644--- a/test/team-fixes.test.ts+++ b/test/team-fixes.test.ts@@ -93,9 +93,10 @@ describe("a member's read-only pages", () => {if (name && method) helpers.set(name, method)}expect(helpers.get('loadReport')).toBe('report')- // Screens only an admin reaches: the connectors' admin view, the introduction and the agent- // builder (admins'), the activity log, adding a skill from the terminal and a skill's history.- const ADMIN_SCREENS = new Set(['ConnectorStore.tsx:ownApp', 'Harness.tsx:harnessMcps', 'Onboarding.tsx:refreshEngines', 'Onboarding.tsx:localSkills', 'People.tsx:activity', 'People.tsx:removedPeople', 'Skills.tsx:localSkills', 'Skills.tsx:skillVersions'])+ // Screens only an admin reaches: the connectors' admin view, the introduction (the owner's; someone+ // invited gets GuestWelcome) and the agent builder (admins'), the activity log, adding a skill from+ // the terminal and a skill's history.+ const ADMIN_SCREENS = new Set(['ConnectorStore.tsx:ownApp', 'Harness.tsx:harnessMcps', 'Intro.tsx:testEngine', 'Intro.tsx:refreshEngines', 'Intro.tsx:harnessMcps', 'Intro.tsx:localSkills', 'People.tsx:activity', 'People.tsx:removedPeople', 'Skills.tsx:localSkills', 'Skills.tsx:skillVersions'])const found: string[] = []for (const file of readdirSync(join(root, 'components')).filter((f) => f.endsWith('.tsx'))) {const src = readFileSync(join(root, 'components', file), 'utf8')diff --git a/test/team-stress.test.ts b/test/team-stress.test.tsindex 12e6e7e..d541900 100644--- a/test/team-stress.test.ts+++ b/test/team-stress.test.ts@@ -699,13 +699,13 @@ describe('calling a person by the whole name (22)', () => {})describe('what the owner alone sees (23, 24)', () => {- it("the phone tab and the getting-started checklist are the owner's", async () => {+ it("the phone tab and the missions are the owner's", async () => {const pages = readFileSync(join(import.meta.dirname, '..', 'src', 'renderer', 'src', 'components', 'Pages.tsx'), 'utf8')expect(pages).toContain("...(owner ? [['integracoes', L('Celular', 'Phone')]] : [])")expect(pages).toContain('const tabs = SETTINGS_TABS(team, admin, owner)')const sidebar = readFileSync(join(import.meta.dirname, '..', 'src', 'renderer', 'src', 'components', 'Sidebar.tsx'), 'utf8')expect(sidebar).toMatch(/const owner = amOwner\(/)- expect(sidebar).toMatch(/\{owner && settings\.onboarding\?\.done && !settings\.onboarding\.checklistHidden && <GettingStarted \/>\}/)+ expect(sidebar).toMatch(/\{owner && settings\.onboarding\?\.done && !settings\.onboarding\.checklistHidden && <MissionsCard \/>\}/)})it('a locked channel routine says "Me avise" is all a member changes there', () => {