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
Stop Codex agents calling the session read-only, tell agents how to publish to GitHub, and fix the computer card (#197)
Eduardo Machado55bf5c98c4e3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0e44d79..70ba16d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,15 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht## [Unreleased]+> **Em português:**+>+> **Correções:** um agente com o GitHub em **Ler e escrever** volta a subir a branch e abrir a PR em vez de dizer que "a sessão é só leitura" (e, se algo pede aprovação ou está desligado, diz exatamente o quê); e o cartão **Computador** mostra o que vale pra cada escolha, sem misturar a confirmação de **Este computador** com o painel do Linux.++### Fixed++- **An agent with GitHub on "Ler e escrever" pushes and opens the PR instead of saying the session is read-only.** On Codex, the CLI's own text about its sandbox ("`sandbox_mode` is `read-only`... Network access is restricted", "Approval policy is never") reached the model, and it answered "Estou bloqueado porque esta sessão permite apenas leitura" for a push or a PR it had every grant for. That text is left out now (in `codex exec` and the app-server), and the note an agent with the app's tools gets says Codex's sandbox doesn't limit them, that git and other commands on its computer run with `bash`, and to say exactly what was refused or waits for approval, never "read-only". On every harness, an agent with a GitHub connector gets a **GitHub** section in its instructions, made from what it really has: the tools it publishes with (`create_branch`, `push_files`, `create_or_update_file`, `create_pull_request`, by the names it sees); on **Este computador**, that `git push` also runs with your own git credentials; on **Linux isolado**, that there are none there; what your autonomy level or rules make ask first or turn off; and, with read-only access, to ask for read and write with `pedir_acesso`. Before, an agent on this computer was told only "git push only when asked", with no word about the connector.+- **The agent page's Computador card shows what each choice means, from the first look.** Clicking **Este computador** after **Linux isolado** showed the confirmation on top of the Linux panel (the Docker state, **Pastas do seu computador**, **Apagar computador**), with Linux still picked and already saved, and that mix read as this computer's full card, while the real one looked cut short. Now the confirmation shows alone, with **Este computador** picked, and **Cancelar** (or clicking the saved choice) goes back to it; once allowed, the card says the commands run on your computer as you, starting in its folder, and that it reaches your folders without lending them and needs no Docker.+## [0.2.18] - 2026-11-07> **Em português:**diff --git a/src/core/context.ts b/src/core/context.tsindex 7676f14..00eb764 100644--- a/src/core/context.ts+++ b/src/core/context.ts@@ -6,11 +6,11 @@// and the live context again only when it changed.import { L, lang, locale } from '../shared/lang'import { MENTION } from '../shared/mention-text'-import { CODE_SPANS, describeSchedule, PROJECTS_DIR, type Agent, type AgentApp, type Conversation, type Memory, type Message, type Person, type Routine, type Settings, type Skill } from '../shared/types'+import { ACCESS_REQUEST, CODE_SPANS, describeSchedule, PROJECTS_DIR, type Agent, type AgentApp, type Conversation, type Memory, type Message, type Person, type Routine, type Settings, type Skill } from '../shared/types'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'+import { kindLabel, levelOf, policyOf, type ActionKind, type Autonomy } from '../shared/actions'export const HISTORY_LIMIT = 30@@ -35,6 +35,19 @@ export type PromptOpts = {wiki?: { pages: number; kinds: string[] } // the wiki it may readconnectors?: boolean // it has connector tools (Slack, Databricks…)people?: Person[] // the Tucano's people; with more than one, the agent is told who they are+ github?: GitHubAccess // a GitHub connector it has access to: how it publishes, and what waits for the person+}++// What an agent may do on GitHub through a connector, as this turn exposes it: the grant, the tools+// that publish (a branch, files, a PR) by the names the agent sees, and the kinds (push, pr) a rule+// makes ask first or turns off. Without it, an agent told only "you have no credentials" or "push+// only when asked", with Codex adding "read-only", answered "this session is read-only" (0.2.18).+export interface GitHubAccess {+ connector: string // its name, as the person sees it+ level: 'read' | 'read_write'+ tools: string[] // the publishing tools exposed this turn+ ask: ActionKind[]+ off: ActionKind[]}// What doesn't change between replies unless the agent's setup does. A change here starts a new@@ -86,11 +99,12 @@ export function systemPrompt(opts: PromptOpts): string {`Não há credenciais no seu computador, então git push e deploy não funcionam: faça commit só se ${me} pedir e diga o que falta ${me} fazer. Pra publicar no GitHub (uma branch, uma PR), use as ferramentas do conector do GitHub, se você tiver.`,`There are no credentials on your computer, so git push and deploys don't work: commit only if ${me} asks and say what's left for ${me} to do. To publish to GitHub (a branch, a PR), use the GitHub connector's tools, if you have it.`)- }\``+ }`].join('\n')].filter(Boolean).join('\n'),+ opts.github && githubSection(me, opts.github, hasComputer ? (macFolder ? 'mac' : computerOff ? undefined : 'linux') : undefined),browser && browserSection(me),apps?.length && appsSection(me, apps),builderGuide,@@ -284,6 +298,43 @@ function browserSection(me: string): string {].join('\n')}+// GitHub through its connector: what to publish with, what the computer adds (the person's own git+// credentials on this computer, none on Linux), and what waits for the person or never runs. Ends+// with what to say when something doesn't go: exactly what and why, never "the session is read-only".+export function githubSection(me: string, gh: GitHubAccess, computer?: 'mac' | 'linux'): string {+ const labels = (ks: ActionKind[]): string => ks.map((k) => kindLabel(k).toLowerCase()).join(', ')+ const git =+ computer === 'mac'+ ? L(`No computador de ${me}, git push também roda, com as credenciais do git de ${me}, se houver; se falhar por falta de credencial, publique pelo conector.`, `On ${me}'s computer, git push runs too, with ${me}'s git credentials, if there are any; if it fails for lack of credentials, publish through the connector.`)+ : computer === 'linux'+ ? L('Seu computador Linux não tem credenciais: git push não funciona nele, então publique pelo conector.', "Your Linux computer has no credentials: git push doesn't work on it, so publish through the connector.")+ : ''+ const ask = gh.ask.length ? L(`Pedem aprovação de ${me} antes de rodar: ${labels(gh.ask)}. Viram um pedido, e você recebe o resultado depois da decisão.`, `These ask ${me} for approval before running: ${labels(gh.ask)}. They become a request, and you get the result after the decision.`) : ''+ const off = gh.off.length ? L(`Desligado pra você: ${labels(gh.off)} (${me} decide isso em Configurações ou na sua página).`, `Turned off for you: ${labels(gh.off)} (${me} decides that in Settings or on your page).`) : ''+ const say = L(+ `Não diga que a sessão é só leitura nem que não pode publicar: se algo for recusado, pedir aprovação ou faltar, diga a ${me} exatamente o quê e por quê.`,+ `Don't say the session is read-only or that you can't publish: if something is refused, asks for approval or is missing, tell ${me} exactly what and why.`+ )+ const body =+ gh.level === 'read'+ ? L(+ `Você só lê o GitHub pelo conector ${gh.connector}: criar uma branch, mandar arquivos e abrir uma PR precisam de leitura e escrita nele. Se a tarefa precisar, peça com ${ACCESS_REQUEST} (nivel read_write).`,+ `You only read GitHub through the ${gh.connector} connector: creating a branch, sending files and opening a PR need read and write on it. If the task needs it, ask with ${ACCESS_REQUEST} (nivel read_write).`+ )+ : gh.tools.length+ ? L(+ `Você lê e escreve no GitHub pelo conector ${gh.connector}. Pra publicar (criar uma branch, mandar arquivos num commit, abrir uma PR), use as ferramentas dele: ${gh.tools.join(', ')}.`,+ `You read and write GitHub through the ${gh.connector} connector. To publish (create a branch, send files in a commit, open a PR), use its tools: ${gh.tools.join(', ')}.`+ )+ : gh.off.length+ ? L(`Você lê e escreve no GitHub pelo conector ${gh.connector}, mas as ferramentas de publicar não estão com você.`, `You read and write GitHub through the ${gh.connector} connector, but its publishing tools aren't yours.`)+ : L(+ `Você lê e escreve no GitHub pelo conector ${gh.connector}, mas as ferramentas de publicar dele estão desligadas na página do conector; se a tarefa precisar, diga isso a ${me}.`,+ `You read and write GitHub through the ${gh.connector} connector, but its publishing tools are turned off on the connector's page; if the task needs them, tell ${me} so.`+ )+ return [L('## GitHub', '## GitHub'), [body, git, ask, off, say].filter(Boolean).join(' ')].join('\n')+}+// An agent whose computer is the user's own: no isolation, so the care is in the instructions.function macSection(me: string, cwd: string): string {const os = osOf()diff --git a/src/core/engines/codex.ts b/src/core/engines/codex.tsindex f0f73a5..74adb0f 100644--- a/src/core/engines/codex.ts+++ b/src/core/engines/codex.ts@@ -87,15 +87,32 @@ export const CODEX_DISABLED_FEATURES = [// took that for the agent's computer: it answered "this session has read-only filesystem access"// without trying write_file, or tried Codex's own apply_patch and gave up. Said plainly, it writes// (GPT-6-Astra: 0 of 6 without it, 6 of 6 with it); hedged ("if you have a computer"), 1 of 3.-// So only an agent whose instructions give it write_file gets it.-const sandboxNote = (): string =>- L(- 'O sandbox do próprio Codex aqui é só leitura e vazio de propósito: não é o seu computador, e o apply_patch e o shell dele não chegam lá. Os seus arquivos estão no seu computador: crie e mude com write_file e edit_file, que funcionam.',- "Codex's own sandbox here is read-only and empty on purpose: it isn't your computer, and its apply_patch and shell don't reach it. Your files are on your computer: create and change them with write_file and edit_file, which do work."- )+// So only an agent whose instructions give it write_file gets the part about files.+// The same block also says "Network access is restricted" and "Approval policy is never", and a model+// read that as "this session is read-only" for a push or a PR it had every grant for (0.2.18, an agent+// on "Este computador" with GitHub "Ler e escrever"). Codex's own sandbox has no say over the gateway's+// tools, so that block is left out (include_permissions_instructions=false), and the note says what+// does decide: each tool's result.+const sandboxNote = (computer: boolean): string =>+ [+ L(+ 'O sandbox do próprio Codex aqui é vazio de propósito e não limita as suas ferramentas. Nunca diga que a sessão é só leitura: o que cada ferramenta pode fazer, e o que pede aprovação, vem do resultado dela; se algo for recusado ou pedir aprovação, diga exatamente o quê e por quê, com as palavras do resultado.',+ "Codex's own sandbox here is empty on purpose and doesn't limit your tools. Never say the session is read-only: what each tool can do, and what asks for approval, comes from its result; if something is refused or asks for approval, say exactly what and why, in the result's words."+ ),+ computer &&+ L(+ 'Ele não é o seu computador, e o apply_patch e o shell dele não chegam lá. Os seus arquivos estão no seu computador: crie e mude com write_file e edit_file, que funcionam; comandos (git, instalar, rede) rodam com bash.',+ "It isn't your computer, and its apply_patch and shell don't reach it. Your files are on your computer: create and change them with write_file and edit_file, which do work; commands (git, installs, network) run with bash."+ )+ ]+ .filter(Boolean)+ .join(' ')++// The agent's instructions, with the sandbox note when it has the app's tools (and its part about files when it has a computer).+export const codexInstructions = (turn: Pick<Turn, 'system' | 'mcpUrl'>): string => (turn.mcpUrl ? `${turn.system}\n\n${sandboxNote(turn.system.includes('write_file'))}` : turn.system)-// The agent's instructions, with the sandbox note when it has a computer.-export const codexInstructions = (turn: Pick<Turn, 'system' | 'mcpUrl'>): string => (turn.mcpUrl && turn.system.includes('write_file') ? `${turn.system}\n\n${sandboxNote()}` : turn.system)+// What Codex says about its own sandbox and approvals: left out (see sandboxNote).+const NO_PERMISSIONS_TEXT = 'include_permissions_instructions=false'export function codexArgs(turn: Pick<Turn, 'model' | 'effort' | 'system' | 'cwd' | 'mcpUrl' | 'web' | 'images'>, provider: string[] = []): string[] {const gateway = turn.mcpUrl@@ -123,6 +140,7 @@ export function codexArgs(turn: Pick<Turn, 'model' | 'effort' | 'system' | 'cwd''-c', 'skills.bundled.enabled=false','-c', `web_search=${turn.web ? '"live"' : '"disabled"'}`,'-c', 'project_doc_max_bytes=0',+ '-c', NO_PERMISSIONS_TEXT,...CODEX_DISABLED_FEATURES.flatMap((f) => ['--disable', f]),...provider,...gateway,@@ -191,6 +209,7 @@ export function codexAppArgs(provider: string[] = []): string[] {...CODEX_DISABLED_FEATURES.flatMap((f) => ['--disable', f]),'-c', 'sandbox_mode="read-only"','-c', 'approval_policy="never"',+ '-c', NO_PERMISSIONS_TEXT,'-c', 'skills.include_instructions=false','-c', 'skills.bundled.enabled=false','-c', 'project_doc_max_bytes=0',diff --git a/src/core/guide/computadores.md b/src/core/guide/computadores.mdindex 45b1e0a..c2a3bf2 100644--- a/src/core/guide/computadores.md+++ b/src/core/guide/computadores.md@@ -5,7 +5,7 @@Na página do agente, aba **Ferramentas** › **Computador**:- **Nenhum**: só conversa, web e navegador.- **Linux isolado**: um computador só dele, separado do seu, num contêiner do Docker. Instala e roda o que precisar sem pedir. A pasta de trabalho é `/work`. Precisa do Docker aberto (Docker Desktop no Mac e no Windows). Liga sozinho quando ele precisar; há **Ligar agora**, **Reiniciar** e **Apagar computador** (apaga tudo, inclusive `/work`).-- **Este computador**: os comandos rodam direto no seu computador, como você. É preciso confirmar em **Liberar o computador pra ele**. Os comandos começam na pasta dele (**Abrir pasta dele**). Na barra lateral, o agente ganha a marca "no seu computador".+- **Este computador**: os comandos rodam direto no seu computador, como você. É preciso confirmar em **Liberar o computador pra ele**. Os comandos começam na pasta dele (**Abrir pasta dele**). Não precisa do Docker nem de pastas emprestadas: ele alcança as suas pastas direto. Na barra lateral, o agente ganha a marca "no seu computador".Com computador, o agente cria arquivos, roda comandos e sobe sites e apps pra você ver.@@ -16,7 +16,7 @@ Um site ou app que o agente sobe aparece com a **porta** e o estado (**no ar** oEm **Pastas do seu computador**, **Emprestar pasta…** dá ao agente a pasta de um projeto. Pra cada uma: **Só ler** ou **Pode mudar**, e **Devolver**. Ele mexe nos arquivos de verdade, então use git pra poder desfazer. Emprestar ou devolver reinicia o computador do agente: os serviços param, o que ele instalou fica.## GitHub-O computador do agente não tem credenciais: `git push` não funciona nele. Pra publicar no GitHub (criar uma branch, mandar arquivos, abrir uma PR), o agente usa o **conector do GitHub** (em **Conectores**), com as permissões e aprovações de qualquer conector.+Pra publicar no GitHub (criar uma branch, mandar arquivos, abrir uma PR), o agente usa o **conector do GitHub** (em **Conectores**) com **Ler e escrever**, com as permissões e aprovações de qualquer conector. No **Linux isolado** não há credenciais: `git push` não funciona nele. Em **Este computador**, `git push` roda com as credenciais do git que você já tem. Se um agente disser que "a sessão é só leitura", confira se ele tem **Ler e escrever** no GitHub e se **Subir commits (push)** ou **Abrir pull request** não estão em **Nunca**.## O navegador do agenteNa aba **Ferramentas**, **Navegador**: um Chrome só dele, com logins separados dos seus. Ele abre páginas, clica, preenche e lê como uma pessoa. Um clique que compra, publica, envia ou apaga pede sua aprovação.diff --git a/src/core/runs.ts b/src/core/runs.tsindex 0ff7780..d62b569 100644--- a/src/core/runs.ts+++ b/src/core/runs.ts@@ -6,7 +6,7 @@ import { friendly, toolLabel } from '../shared/errors'import type { CoreEvent } from '../shared/rpc'import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'import { ACCESS_REQUEST, CACHE_READ_WEIGHT, describeSchedule, workIn, ENGINES, ERRORS_STOP, usable, modelInfo, PENDING_WAIT_MINUTES, REPEAT_STOP, REPEAT_WARN, SAME_TOOL_STOP, SAME_TOOL_WARN, SLEEPS_FREE, SLEEPS_STOP, RUN_BUDGET_PCT, RUN_STALL_MINUTES, chainDepthCap, IMAGE_MIMES, MAX_IMAGE_BYTES, MAX_IMAGES_PER_MESSAGE, type Account, type Agent, type Approval, type Artifact, type ImageUpload, type Connector, type ConnectorTool, type Conversation, type EngineId, type Message, type Quota, type Receipt, type Person, type Question, type Routine, type Run, type RunStatus, type Settings, type Step, delegating, wikiAccess } from '../shared/types'-import { BUSCAR_THREADS, clock, HISTORY_LIMIT, LER_THREAD, liveContext, mentioned, NO_LIVE, snip, systemPrompt, transcript, transcriptBlocks, type PromptOpts } from './context'+import { BUSCAR_THREADS, clock, HISTORY_LIMIT, LER_THREAD, liveContext, mentioned, NO_LIVE, snip, systemPrompt, transcript, transcriptBlocks, type GitHubAccess, type PromptOpts } from './context'import { BUSCAR_MEMORIAS, contextWindow, LEMBRAR, searchThreads, type Memories } from './memory'import { WIKI_TOOL_NAMES, WIKI_TOOLS, wikiCall, type Wiki } from './wiki'import { BROWSER_TOOL_NAMES, browserStep, browserTools, NAVEGADOR, type Browser } from './browser'@@ -196,6 +196,20 @@ function exposedName(connector: Connector, tool: string, taken: Set<string>): streturn name}+// A GitHub connector this agent has access to (the first, if there are several): its grant, the+// tools it publishes with (a branch, files, a PR) by the names this turn exposes, and what a rule+// makes ask first or turns off. A tool turned off by a rule isn't exposed, so it shows only as "off".+const IS_GITHUB = /github/i+const MAKES = /^create_?(a_)?branch$|^create_or_update_file$/i // GitHub's MCP; push and PR tools go by their kind+const publishes = (name: string): boolean => MAKES.test(name) || toolActions(name).some((k) => k === 'push' || k === 'pr' || k === 'commit')+export function githubAccess(connectors: Connector[], agent: Pick<Agent, 'grants'>, exposed: Map<string, Exposed>, policy: Policy): GitHubAccess | undefined {+ const c = connectors.find((x) => (IS_GITHUB.test(x.url ?? '') || IS_GITHUB.test(x.name)) && (agent.grants[x.id] === 'read' || agent.grants[x.id] === 'read_write'))+ if (!c) return undefined+ const tools = [...exposed].filter(([, e]) => e.connector.id === c.id && e.tool.cls !== 'read' && publishes(e.tool.name) && !toolActions(e.tool.name).some((k) => k === 'merge' || k === 'delete')).map(([name]) => name)+ const kinds: ActionKind[] = ['push', 'pr']+ return { connector: c.name, level: agent.grants[c.id] as 'read' | 'read_write', tools, ask: kinds.filter((k) => actionMode(k, policy) === 'ask'), off: kinds.filter((k) => actionMode(k, policy) === 'off') }+}+// "2,4 mi", "850 mil"const tokenCount = (n: number): string =>n >= 1_000_000 ? `${(n / 1_000_000).toLocaleString(locale(), { maximumFractionDigits: 1 })} ${L('mi', 'M')}` : `${Math.round(n / 1000).toLocaleString(locale())}${L(' mil', 'k')}`@@ -1050,6 +1064,8 @@ export class Runner {if (c.status !== 'connected' && c.status !== 'disconnected' && c.status !== 'connecting') continuefor (const t of db.tools(c.id)) if (allowed(t, agent.grants[c.id], perCallTool(c.url, t.name)) && gate(kindsOf(t), policy).mode !== 'off') exposed.set(exposedName(c, t.name, taken), { connector: c, tool: t })}+ // GitHub through its connector, as this turn has it: the prompt says how to publish and what waits (context.ts).+ const github = githubAccess(this.deps.connectors?.list() ?? [], agent, exposed, policy)// pedir_acesso: the connectors this agent could get more of; I decide, like any approval.const lacking = (this.deps.connectors?.list() ?? []).filter((c) => agent.grants[c.id] !== 'read_write')const accessTool: ToolDef | undefined =@@ -1889,6 +1905,7 @@ ${note}`,skills: skills && mySkills,wiki: wiki ? { pages: wiki.count(), kinds: wiki.kinds() } : undefined,connectors: exposed.size > 0,+ github,people,builder: proposes? builderSection(settings, { models: this.deps.models?.() ?? availableModels(settings), connectors: this.deps.connectors?.list() ?? [], team: db.agents().filter((a) => !a.archived && a.kind !== 'tuca'), own: agent.modelId })diff --git a/src/renderer/src/components/Pages.tsx b/src/renderer/src/components/Pages.tsxindex e49b68a..186ae50 100644--- a/src/renderer/src/components/Pages.tsx+++ b/src/renderer/src/components/Pages.tsx@@ -827,7 +827,12 @@ function ComputerCard({ agentId, kind, onChange }: { agentId: string; kind: Compconst [confirmErase, setConfirmErase] = useState(false)const [confirmMac, setConfirmMac] = useState(false)useEffect(() => computerAction(agentId, 'refresh'), [agentId])- const on = kind === 'linux'+ // "Este computador" picked but not let yet: the choice shows picked, and only its confirmation+ // shows under it. Before, the card kept the last kind's panel (Linux's Docker, folders, erase)+ // under the confirmation, with Linux still picked, and that mix read as this computer's full card.+ const confirming = confirmMac && kind !== 'mac'+ const shown: ComputerChoice = confirming ? 'mac' : kind+ const on = kind === 'linux' && !confirmingconst state = on ? (info && info.state !== 'off' ? info.state : 'stopped') : 'off'const st = COMPUTER_STATE()[state]!const isolated = useStore((s) => s.isolatedComputers)@@ -847,10 +852,10 @@ function ComputerCard({ agentId, kind, onChange }: { agentId: string; kind: Comp<buttonkey={c.value}role="radio"- aria-checked={kind === c.value}- className={kind === c.value ? 'is-active' : ''}+ aria-checked={shown === c.value}+ className={shown === c.value ? 'is-active' : ''}onClick={() => {- if (kind === c.value) return+ if (kind === c.value) return setConfirmMac(false)if (c.value === 'mac') return setConfirmMac(true)setConfirmMac(false)onChange(c.value)@@ -860,7 +865,7 @@ function ComputerCard({ agentId, kind, onChange }: { agentId: string; kind: Comp</button>))}</div>- {confirmMac && kind !== 'mac' && (+ {confirming && (<div className="mac-confirm"><p><strong>{L('Os comandos dele vão rodar direto no seu computador, como você.', 'Its commands will run right on your computer, as you.')}</strong>{' '}@@ -889,7 +894,12 @@ function ComputerCard({ agentId, kind, onChange }: { agentId: string; kind: Comp<><div className="computer"><span className="tag tag--warn">{L('no seu computador', 'on your computer')}</span>- <span className="muted small grow">{L('Os comandos começam na pasta dele.', 'Commands start in its folder.')}</span>+ <span className="muted small grow">+ {L(+ 'Liberado: os comandos rodam direto no seu computador, como você, e começam na pasta dele. Ele alcança as suas pastas sem emprestar e não precisa do Docker.',+ 'Allowed: its commands run right on your computer, as you, and start in its folder. It reaches your folders without lending them and needs no Docker.'+ )}+ </span></div><Services agentId={agentId} />{admin && (diff --git a/test/codex-app.test.ts b/test/codex-app.test.tsindex d7ac6f2..c7ac2f7 100644--- a/test/codex-app.test.ts+++ b/test/codex-app.test.ts@@ -89,7 +89,7 @@ describe('Codex app-server isolation', () => {expect(args[0]).toBe('app-server')for (const f of CODEX_DISABLED_FEATURES) expect(args[args.indexOf(f) - 1]).toBe('--disable')expect(args).toEqual(- expect.arrayContaining(['sandbox_mode="read-only"', 'approval_policy="never"', 'skills.include_instructions=false', 'skills.bundled.enabled=false', 'project_doc_max_bytes=0', 'history.persistence="none"', 'mcp_optional_startup_grace_ms=0'])+ expect.arrayContaining(['sandbox_mode="read-only"', 'approval_policy="never"', 'skills.include_instructions=false', 'skills.bundled.enabled=false', 'project_doc_max_bytes=0', 'history.persistence="none"', 'mcp_optional_startup_grace_ms=0', 'include_permissions_instructions=false']))})@@ -101,7 +101,7 @@ describe('Codex app-server isolation', () => {cwd: '/tmp/x',sandbox: 'read-only',approvalPolicy: 'never',- developerInstructions: 'Você é Theo.',+ developerInstructions: expect.stringMatching(/^Você é Theo\.\n\nO sandbox do próprio Codex aqui é vazio de propósito e não limita as suas ferramentas\. Nunca diga que a sessão é só leitura/), // with the app's toolsconfig: { model_reasoning_effort: 'low', web_search: 'disabled', 'mcp_servers.tucano': { url, default_tools_approval_mode: 'approve', tool_timeout_sec: 900 } }})expect(codexAppArgs(['-c', 'model_provider="corp"']).join(' ')).not.toContain('/mcp/')diff --git a/test/computer-card-ui.test.tsx b/test/computer-card-ui.test.tsxnew file mode 100644index 0000000..191f96a--- /dev/null+++ b/test/computer-card-ui.test.tsx@@ -0,0 +1,103 @@+// The agent's "Computador" card (0.2.18, a person's report): on "Este computador" it showed a short+// line and two buttons, and only after clicking Linux and back did the "full" card appear. That+// card was Linux's panel (Docker, lent folders, erase) under the confirmation, with Linux still+// picked and already saved. Each saved state shows its own content on the first render, and a+// confirmation shows alone, with the choice it confirms picked.+import { parseHTML } from 'linkedom'+import { act } from 'react'+import type { Root } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import type { Agent, ComputerInfo, Person } 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 })+vi.mock('open-bot-avatar/dom', () => ({ mountAvatar: () => new Proxy({}, { get: () => () => {} }) }))++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), computerAction: vi.fn(), patchAgent: vi.fn(), ensureTuca: vi.fn(() => new Promise(() => {})) }+})+const { getState, patchAgent } = await import('../src/renderer/src/store')+const { createRoot } = await import('react-dom/client')+const { AgentPage } = await import('../src/renderer/src/components/Pages')++const ana: Person = { id: 'ana', name: 'Ana', role: 'owner', about: '' }+const lia = (p: Partial<Agent>): Agent => ({ id: 'a1', name: 'Lia', handle: 'lia', role: '', color: 'sky', instructions: '', modelId: 'sonnet', effort: 'low', limit: 1_000_000, used: 0, grants: {}, memory: 'auto', computer: false, archived: false, ...p })+const info = (kind: 'mac' | 'linux', state: ComputerInfo['state']): ComputerInfo => ({ agentId: 'a1', kind, state, folder: '/Users/ana/x', services: [] })++let root: Root+const render = async (agent: Agent, computer?: ComputerInfo): Promise<void> => {+ fake = { ...getState(), ready: true, people: [ana], you: 'ana', agents: [agent], connectors: [], tabs: { agent: 'ferramentas' }, computers: computer ? [computer] : [], isolatedComputers: true }+ await act(async () => root.render(<AgentPage id="a1" />))+}+const card = (): Element => [...document.querySelectorAll('.card')].find((c) => c.textContent?.startsWith('Computador'))!+const text = (): string => card().textContent ?? ''+const picked = (): string => [...card().querySelectorAll('[role="radio"]')].filter((b) => b.getAttribute('aria-checked') === 'true').map((b) => b.textContent).join()+const click = async (name: string): Promise<void> => {+ const b = [...card().querySelectorAll('button')].find((x) => x.textContent === name)!+ await act(async () => void b.dispatchEvent(new window.Event('click', { bubbles: true })))+}++beforeEach(() => (root = createRoot(document.getElementById('root')!)))+afterEach(async () => {+ await act(async () => root.unmount())+ vi.clearAllMocks()+})++describe('the Computador card, on its first render', () => {+ it('none: just the choice', async () => {+ await render(lia({ computer: false }))+ expect(picked()).toBe('Nenhum')+ expect(text()).not.toContain('Liberar o computador pra ele')+ expect(text()).not.toContain('Emprestar pasta')+ })++ it("Linux: Docker's state, lent folders and the computer's buttons", async () => {+ await render(lia({ computer: true, computerKind: 'linux' }), info('linux', 'no_docker'))+ expect(picked()).toBe('Linux isolado')+ for (const t of ['sem Docker', 'Verificar de novo', 'Pastas do seu computador', 'Emprestar pasta…', 'Abrir pasta', 'Reiniciar', 'Apagar computador']) expect(text()).toContain(t)+ expect(text()).not.toContain('Liberar o computador pra ele')+ })++ it('this computer, let: what it means, its folder and services, and nothing of Linux nor the confirmation', async () => {+ await render(lia({ computer: true, computerKind: 'mac' }), info('mac', 'running'))+ expect(picked()).toBe('Este computador')+ for (const t of ['no seu computador', 'Liberado: os comandos rodam direto no seu computador', 'alcança as suas pastas sem emprestar e não precisa do Docker', 'Abrir pasta dele', 'Parar serviços']) expect(text()).toContain(t)+ for (const t of ['Liberar o computador pra ele', 'Emprestar pasta', 'sem Docker', 'Verificar de novo', 'Apagar computador']) expect(text()).not.toContain(t)+ })+})++describe('picking "Este computador"', () => {+ it('from Linux: the confirmation alone, with "Este computador" picked; Cancelar goes back, nothing saved', async () => {+ await render(lia({ computer: true, computerKind: 'linux' }), info('linux', 'no_docker'))+ await click('Este computador')+ expect(picked()).toBe('Este computador')+ expect(text()).toContain('Liberar o computador pra ele')+ for (const t of ['sem Docker', 'Emprestar pasta', 'Apagar computador']) expect(text()).not.toContain(t)+ expect(patchAgent).not.toHaveBeenCalled()+ await click('Cancelar')+ expect(picked()).toBe('Linux isolado')+ expect(text()).toContain('Emprestar pasta')+ })++ it('clicking the saved choice again drops the confirmation', async () => {+ await render(lia({ computer: false }))+ await click('Este computador')+ expect(text()).toContain('Liberar o computador pra ele')+ await click('Nenhum')+ expect(picked()).toBe('Nenhum')+ expect(text()).not.toContain('Liberar o computador pra ele')+ })++ it('Liberar saves it and shows this computer’s card', async () => {+ await render(lia({ computer: false }))+ await click('Este computador')+ await click('Liberar o computador pra ele')+ expect(patchAgent).toHaveBeenCalledWith('a1', { computer: true, computerKind: 'mac' })+ expect(picked()).toBe('Este computador')+ expect(text()).toContain('Abrir pasta dele')+ expect(text()).not.toContain('Liberar o computador pra ele')+ })+})diff --git a/test/github-publish.test.ts b/test/github-publish.test.tsnew file mode 100644index 0000000..b472925--- /dev/null+++ b/test/github-publish.test.ts@@ -0,0 +1,168 @@+// An agent on "Este computador" with GitHub "Ler e escrever" (0.2.18, a person's report): it said+// "esta sessão permite apenas leitura" and didn't push or open the PR. What it's told and what it+// has, on Claude Code and on Codex: the GitHub tools that publish are there, the prompt names them+// and says what the computer adds and what waits for the person, and Codex no longer hears from its+// own sandbox that the session is read-only.+import { mkdtempSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { Client } from '@modelcontextprotocol/sdk/client/index.js'+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import type { CoreEvent } from '../src/shared/rpc'+import type { Agent, Connector, EngineId, GrantLevel, Settings } from '../src/shared/types'+import type { Autonomy } from '../src/shared/actions'+import { classify } from '../src/shared/classify'+import { Db } from '../src/core/db'+import { codexAppArgs, codexArgs, codexInstructions, codexThread } from '../src/core/engines/codex'+import { fakeEngine } from '../src/core/engines/fake'+import type { Engine, Turn } from '../src/core/engines/types'+import { Gateway, textResult } from '../src/core/gateway'+import { Runner } from '../src/core/runs'++const ready = { installed: true, loggedIn: true }+// Some of what GitHub's MCP server lists, with its annotations' effect: reads are read.+const GITHUB_TOOLS = ['get_file_contents', 'list_branches', 'search_pull_requests', 'create_branch', 'push_files', 'create_or_update_file', 'create_pull_request', 'merge_pull_request', 'delete_file', 'add_issue_comment']++let db: Db+let gateway: Gateway+let settings: Settings+let events: CoreEvent[]+let called: { name: string; args: Record<string, unknown> }[]+const github: Connector = { id: 'gh', name: 'GitHub', kind: 'remote', url: 'https://api.githubcopilot.com/mcp/', args: [], envKeys: [], auth: 'token', status: 'connected', tools: [] }+const connectors = {+ list: () => [{ ...github, tools: db.tools('gh') }],+ call: async (_id: string, name: string, args: Record<string, unknown>) => (called.push({ name, args }), textResult(`${name}: ok`))+}+const computers = {+ call: async () => ({ result: textResult('exit code 0') }),+ mac: { cwd: () => '/Users/edu/Library/Application Support/Tucano/computadores/lia' }+}++type Seen = { turn?: Turn; tools: string[]; results: string[] }+// A turn like a CLI's: lists the tools and makes the calls it's given, each by the name it sees.+function scripted(id: EngineId, seen: Seen, calls: { tool: string; args: Record<string, unknown> }[]): Engine {+ return {+ id,+ async *run(turn) {+ seen.turn = turn+ const client = new Client({ name: 'scripted', version: '0' })+ await client.connect(new StreamableHTTPClientTransport(new URL(turn.mcpUrl!)))+ seen.tools = (await client.listTools()).tools.map((t) => t.name)+ for (const c of calls) {+ const r = (await client.callTool({ name: c.tool, arguments: c.args })) as { content: { text: string }[] }+ seen.results.push(r.content[0]?.text ?? '')+ }+ await client.close()+ yield { type: 'text', delta: 'ok' }+ yield { type: 'done', text: 'ok', usage: { inputTokens: 10, cacheReadTokens: 0, outputTokens: 2 } }+ }+ }+}++async function turn(engine: EngineId, o: { grant?: GrantLevel; kind?: 'mac' | 'linux' | 'none'; autonomy?: Autonomy; calls?: { tool: string; args: Record<string, unknown> }[] } = {}): Promise<Seen> {+ const kind = o.kind ?? 'mac'+ const lia: Agent = {+ ...db.agent('lia')!,+ modelId: engine === 'codex' ? 'gpt-5.6-luna' : 'sonnet',+ grants: { gh: o.grant ?? 'read_write' },+ computer: kind !== 'none',+ computerKind: kind === 'mac' ? 'mac' : 'linux',+ ...(o.autonomy ? { autonomy: o.autonomy } : {})+ }+ db.saveAgent(lia)+ const seen: Seen = { tools: [], results: [] }+ const engines = Object.fromEntries((['claude', 'codex', 'opencode', 'pi', 'gemini', 'cursor', 'grok'] as EngineId[]).map((e) => [e, e === engine ? scripted(e, seen, o.calls ?? []) : fakeEngine(e)])) as Record<EngineId, Engine>+ const runner = new Runner({ db, engines, settings: async () => settings, emit: (e) => events.push(e), workDir: mkdtempSync(join(tmpdir(), 'gh-w-')), gateway, connectors, computers: computers as never })+ await runner.send('dm', 'sobe a branch fix-login e abre a PR')+ await runner.idle()+ return seen+}++beforeEach(async () => {+ db = new Db(join(mkdtempSync(join(tmpdir(), 'gh-db-')), 'test.db'))+ events = []+ called = []+ settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready, grok: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }+ db.saveConnector(github)+ db.syncTools('gh', GITHUB_TOOLS.map((name) => ({ name, description: name, inputSchema: { type: 'object' }, cls: /^(get|list|search)_/.test(name) ? 'read' : classify({ name }) })))+ db.saveAgent({ id: 'lia', name: 'Lia', handle: 'lia', role: '', color: 'sky', instructions: '', modelId: 'sonnet', effort: 'low', limit: 1_000_000, used: 0, grants: {}, memory: 'auto', computer: false, archived: false })+ db.createConversation({ id: 'dm', kind: 'dm', name: 'lia', members: ['lia'] })+ gateway = new Gateway()+ await gateway.start()+})+afterEach(() => gateway.stop())++describe.each(['claude', 'codex'] as EngineId[])('on %s, an agent on this computer with GitHub "Ler e escrever"', (engine) => {+ it('has the tools that publish, and the prompt names them and says what the computer adds', async () => {+ const seen = await turn(engine)+ for (const t of ['github__create_branch', 'github__push_files', 'github__create_or_update_file', 'github__create_pull_request', 'bash', 'write_file']) expect(seen.tools).toContain(t)+ const system = seen.turn!.system+ expect(system).toContain('## GitHub')+ expect(system).toContain('Você lê e escreve no GitHub pelo conector GitHub. Pra publicar (criar uma branch, mandar arquivos num commit, abrir uma PR), use as ferramentas dele: github__create_branch, github__push_files, github__create_or_update_file, github__create_pull_request.')+ expect(system).toContain('No computador de Edu, git push também roda, com as credenciais do git de Edu')+ expect(system).toContain('Não diga que a sessão é só leitura nem que não pode publicar')+ expect(system).not.toContain('github__merge_pull_request') // a merge isn't publishing a branch+ expect(system).not.toContain('Pedem aprovação') // at the normal level, a push and a PR don't wait+ })++ it('pushes the files and opens the PR through the connector, without asking', async () => {+ const seen = await turn(engine, {+ calls: [+ { tool: 'github__push_files', args: { owner: 'o', repo: 'r', branch: 'fix-login', files: [], message: 'fix' } },+ { tool: 'github__create_pull_request', args: { owner: 'o', repo: 'r', head: 'fix-login', base: 'main', title: 'Fix login' } }+ ]+ })+ expect(called.map((c) => c.name)).toEqual(['push_files', 'create_pull_request'])+ expect(seen.results).toEqual(['push_files: ok', 'create_pull_request: ok'])+ expect(db.approvals()).toHaveLength(0)+ })++ it('careful: the push and the PR wait for me, and the prompt says so', async () => {+ const seen = await turn(engine, { autonomy: 'careful', calls: [{ tool: 'github__create_pull_request', args: { owner: 'o', repo: 'r', head: 'fix-login', base: 'main', title: 'Fix login' } }] })+ expect(seen.turn!.system).toContain('Pedem aprovação de Edu antes de rodar: subir commits (push), abrir pull request.')+ expect(called).toEqual([])+ expect(db.approvals()).toHaveLength(1)+ })++ it('reading only: no tools that publish, and it is told to ask for access, not that the session is read-only', async () => {+ const seen = await turn(engine, { grant: 'read' })+ expect(seen.tools).not.toContain('github__push_files')+ expect(seen.tools).toContain('pedir_acesso')+ expect(seen.turn!.system).toContain('Você só lê o GitHub pelo conector GitHub')+ expect(seen.turn!.system).toContain('peça com pedir_acesso (nivel read_write)')+ })++ it('on Linux: no credentials there, so it publishes through the connector', async () => {+ const seen = await turn(engine, { kind: 'linux' })+ expect(seen.turn!.system).toContain('Seu computador Linux não tem credenciais: git push não funciona nele, então publique pelo conector.')+ expect(seen.turn!.system).not.toContain('git push também roda')+ })++ it('a rule that turns pushing off: the tool is gone and the prompt says why', async () => {+ db.saveAgent({ ...db.agent('lia')!, actionRules: { push: 'off' } })+ const seen = await turn(engine)+ expect(seen.tools).not.toContain('github__push_files')+ expect(seen.tools).toContain('github__create_pull_request')+ expect(seen.turn!.system).toContain('Desligado pra você: subir commits (push)')+ })+})++describe('Codex, for an agent with the app tools', () => {+ it("leaves out its own sandbox's read-only text, in exec and in the app-server", () => {+ expect(codexArgs({ model: 'm', effort: 'low', system: 'x', cwd: '/tmp/x' })).toContain('include_permissions_instructions=false')+ expect(codexAppArgs()).toContain('include_permissions_instructions=false')+ })++ it('is told never to call the session read-only, and on a computer, to run git with bash', async () => {+ const seen = await turn('codex')+ const dev = codexInstructions(seen.turn!)+ expect(dev).toContain('Nunca diga que a sessão é só leitura')+ expect(dev).toContain('comandos (git, instalar, rede) rodam com bash')+ expect(codexThread(seen.turn!).developerInstructions).toBe(dev)+ // No computer, still the app's tools: the first part, not the one about files.+ const none = codexInstructions({ system: 'Você é Lia.', mcpUrl: 'http://127.0.0.1:1/mcp/t' })+ expect(none).toContain('Nunca diga que a sessão é só leitura')+ expect(none).not.toMatch(/apply_patch/)+ })+})