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
Show what each tool call, skill and command did, as it runs (#135)
Dias9ebafe68fdd4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3084a22..41cf287 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,7 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht> - **O app abre fora do instalador mesmo com uma versão estranha.** O atualizador, que nem é usado ali, conferia a versão ao abrir e derrubava o app.> - **Agentes no Grok.** Um agente pode rodar no Grok CLI, com a assinatura do grok.com, como roda no Cursor CLI. Cada resposta usa uma pasta própria: os seus plugins, skills e hooks não carregam, e só as ferramentas do Tucano ficam à mão.> - **Um conector que falha diz por quê.** O passo da resposta mostra o motivo em vermelho, e o agente recebe o mesmo motivo pra explicar, em vez de um ✗ sem nada.+> - **Os passos mostram o que o agente fez.** Cada consulta mostra o SQL ou o que foi pedido, e o que voltou ("120 linhas"); um comando mostra o comando inteiro, e o SQL quando roda um; uma skill diz qual foi lida. Tudo aparece enquanto o agente trabalha, sem nenhum segredo na tela.### Added@@ -19,6 +20,7 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht### Changed+- **A reply's steps say what each call did, as it runs.** A connector call shows what it asked (the SQL, a path, a search) from the moment it starts, and what came back once it ends, in a few words: the rows of a table or a SQL answer, the items of a list, the lines of a long text. A command shows whole, or as **Ran SQL** with the SQL taken out of it, and ends with what it printed or its exit code and the last lines of stderr; reading a skill says which skill and file. Tokens, passwords, keys and auth headers are masked on the screen and in the log (the agent still gets the real output). The steps list stays open while the agent works, unless closed, and folds when the reply is done. Thanks [@rjgdias](https://github.com/rjgdias)! ([#135](https://github.com/eduwxyz/tucano/pull/135))- **An agent wakes another only when it needs to.** When an agent's reply mentions other agents, the router reads it first and hands the turn only to those asked to do something: a request, a question, a task, a decision. A thank-you, an "okay" or a credit wakes no one, and the decision shows as a step on the reply. In doubt, or if the router fails, everyone mentioned is called, as before; a mention in your own message still goes straight to the agent. Thanks [@eialanjones](https://github.com/eialanjones)! ([#139](https://github.com/eduwxyz/tucano/pull/139))### Fixeddiff --git a/src/core/engines/fake.ts b/src/core/engines/fake.tsindex a8d3253..ba85000 100644--- a/src/core/engines/fake.ts+++ b/src/core/engines/fake.ts@@ -68,6 +68,15 @@ export function fakeEngine(id: Engine['id'], opts: { delayMs?: number; reply?: (const statement = /(?:consulte|run the sql) `([^`]+)`/i.exec(last)![1]!const r = await callTool(turn.mcpUrl, await toolNamed(turn.mcpUrl, 'execute_sql_read_only'), { statement })reply = textOf(r)+ } else if (turn.mcpUrl && /com a skill ([\w-]+),? rode `([^`]+)`(?: e depois `([^`]+)`)?/is.test(last)) {+ // A skill that runs a CLI (a databricks-query skill and the databricks command): read it, then run.+ const [, skill, first, then] = /com a skill ([\w-]+),? rode `([^`]+)`(?: e depois `([^`]+)`)?/is.exec(last)!+ await callTool(turn.mcpUrl, 'ler_skill', { nome: skill })+ for (const command of [first!, then].filter(Boolean)) await callTool(turn.mcpUrl, 'bash', { command })+ reply = L(+ 'Rodei o SQL pela skill: Sudeste lidera, depois Sul e Nordeste. O segundo comando falhou: o token foi recusado.',+ 'I ran the SQL through the skill: Southeast leads, then South and Northeast. The second command failed: the token was refused.'+ )} else if (turn.mcpUrl && /rode `([^`]+)`/i.test(last)) {const r = await callTool(turn.mcpUrl, 'bash', { command: /rode `([^`]+)`/i.exec(last)![1]! })reply = `Saída:\n\n${textOf(r)}`diff --git a/src/core/runs.ts b/src/core/runs.tsindex b9207a3..b1fbb27 100644--- a/src/core/runs.ts+++ b/src/core/runs.ts@@ -25,6 +25,7 @@ import { JEV_MODEL, routeJev } from './jev'import { ROUTER_HISTORY, route, screenHandoff } from './router'import { allowed, approvalHash, canonical } from './policy'import { callError, contentText, errorReason } from './connectors'+import { commandStep, execSummary, keyArg, maskSecrets, resultSummary } from './step-text'const MAX_CONCURRENT = 4const MAX_TURN_IMAGES = 6 // attached images a reply sees as images; older ones only by name@@ -43,6 +44,7 @@ const BUDGET_OVERRUN = 1.3 // past the budget by this much without wrapping up,const USAGE_ALERT = 0.8const NARRATION_MAX = 600 // longer text before a tool call is an answer, and stays in the replyconst STEP_ERROR_MAX = 2_000 // the reason a step failed, as kept on the step+const SUMMED_COMPUTER_TOOLS = new Set(['read_file', 'write_file', 'edit_file', 'start_service', 'stop_service']) // a result line when doneconst THOUGHT = (): string => L('Pensou', 'Thought') // the thinking step, closedexport const ASK_USER: ToolDef = {@@ -838,7 +840,9 @@ export class Runner {if (skills && SKILL_TOOL_NAMES.has(name)) {const r = name === LER_SKILL.name ? skills.read(agent, args) : skills.propose(db.agent(agent.id) ?? agent, args)- if (r.skill) addSteps({ id: randomUUID(), label: name === LER_SKILL.name ? L('Leu a skill', 'Read the skill') : L('Propôs uma skill', 'Proposed a skill'), detail: r.skill.name, status: 'done' })+ const file = name === LER_SKILL.name && typeof args['arquivo'] === 'string' && args['arquivo'].trim() ? ` · ${args['arquivo'].trim()}` : ''+ if (r.skill) addSteps({ id: randomUUID(), label: name === LER_SKILL.name ? L('Leu a skill', 'Read the skill') : L('Propôs uma skill', 'Proposed a skill'), detail: r.skill.name + file, status: r.error ? 'error' : 'done', ...(r.error ? { error: r.reply } : {}) })+ else if (name === LER_SKILL.name && r.error) addSteps({ id: randomUUID(), label: L('Leu a skill', 'Read the skill'), detail: String(args['nome'] ?? '') + file, status: 'error', error: r.reply })return textResult(r.reply, r.error)}@@ -857,11 +861,24 @@ export class Runner {if (!current?.computer) return textResult(L('Seu computador foi desligado.', 'Your computer was turned off.'), true)const t0 = Date.now()const { label, detail } = stepFor(name, args, current.computerKind === 'mac')- const step: Step = { id: randomUUID(), label, detail, status: 'running' }+ // A command shows whole (or the SQL it runs, pulled out), masked, from the moment it starts.+ const command = name === 'bash' && typeof args['command'] === 'string' ? commandStep(args['command']) : undefined+ const step: Step = command+ ? { id: randomUUID(), label: command.sql ? L('Rodou SQL', 'Ran SQL') : label, detail: command.detail, input: command.input, status: 'running' }+ : { id: randomUUID(), label, detail: maskSecrets(detail), status: 'running' }flush()msg.run = { ...msg.run!, steps: [...closeThinking('done', THOUGHT()), step] }save()const out = await computers.call(current, name, args, { conversationId: conv.id, messageId: msg.id, signal: control.ctl.signal })+ const failed = !!out.result.isError+ const end: Pick<Step, 'output' | 'error'> = command+ ? execSummary(resultText(out.result), failed)+ : failed+ ? { error: maskSecrets(errorReason(out.result)) }+ : SUMMED_COMPUTER_TOOLS.has(name)+ ? { output: resultSummary(resultText(out.result)) }+ : {}+ if (end.error && end.error.length > STEP_ERROR_MAX) end.error = `${end.error.slice(0, STEP_ERROR_MAX)}…`// No tool of the computer can work: the turn ends here, before the model tries the next one.if (out.down) {computerDown = out.down@@ -873,7 +890,7 @@ export class Runner {...msg.run!,artifactIds: artifactIds.length ? [...artifactIds] : undefined,services: services.length ? [...services] : undefined,- steps: [...msg.run!.steps.map((s) => (s.id === step.id ? { ...s, status: out.result.isError ? ('error' as const) : ('done' as const), ms: Date.now() - t0 } : s)), thinking()]+ steps: [...msg.run!.steps.map((s) => (s.id === step.id ? { ...s, ...end, status: failed ? ('error' as const) : ('done' as const), ms: Date.now() - t0 } : s)), thinking()]}stepStarted = Date.now()save()@@ -1111,22 +1128,26 @@ export class Runner {const t0 = Date.now()const step: Step = { id: randomUUID(), label: current.cls === 'read' ? L('Consultou', 'Looked up') : always ? L('Executou (sempre permitido)', 'Ran (always allowed)') : L('Executou', 'Ran'), detail, status: 'running' }+ // What it asked (the SQL, the path) shows while it runs; what came back, when it's done.+ const { [REASON_PARAM]: _reason, ...toolArgs } = args+ const input = keyArg(toolArgs)+ if (input) step.input = inputflush()msg.run = { ...msg.run!, steps: [...closeThinking('done', THOUGHT()), step] }save()// A failure keeps its reason on the step: a bare ✗ leaves nobody knowing why.- const finish = (status: 'done' | 'error', error?: string): void => {+ const finish = (status: 'done' | 'error', why?: string, output?: string): void => {+ const error = why && maskSecrets(why)if (error) console.warn(`[connector] ${detail} failed: ${error}`)- const reason = error ? { error: error.length > STEP_ERROR_MAX ? `${error.slice(0, STEP_ERROR_MAX)}…` : error } : {}+ const reason = error ? { error: error.length > STEP_ERROR_MAX ? `${error.slice(0, STEP_ERROR_MAX)}…` : error } : output ? { output } : {}msg.run = { ...msg.run!, steps: [...msg.run!.steps.map((s) => (s.id === step.id ? { ...s, status, ms: Date.now() - t0, ...reason } : s)), thinking()] }stepStarted = Date.now()save()}try {- const { [REASON_PARAM]: _reason, ...toolArgs } = argsconst r = await this.deps.connectors!.call(hit.connector.id, current.name, toolArgs)if (r.isError) finish('error', errorReason(r))- else finish('done')+ else finish('done', undefined, resultSummary(resultText(r)))return clip(r)} catch (e) {const why = callError(e)diff --git a/src/core/step-text.ts b/src/core/step-text.tsnew file mode 100644index 0000000..103b2df--- /dev/null+++ b/src/core/step-text.ts@@ -0,0 +1,187 @@+// What a reply's step says about a tool call, so its steps read as they go: the argument that tells+// what was asked (the SQL, the path, the search) and the result in a few words ("120 rows").+// Everything here is for the screen, so it passes through maskSecrets: the agent still gets the real text.+import { L, locale } from '../shared/lang'++const INPUT_MAX = 4_000 // the step keeps this much of the argument; the row shows a few lines of it+const LINE_MAX = 120++// The arguments that say what a call did, best first. Tools name them in many ways.+const KEYS = ['statement', 'sql', 'query', 'command', 'cmd', 'code', 'path', 'file', 'file_path', 'filename', 'url', 'q', 'search', 'term', 'prompt', 'title', 'name', 'table', 'table_name', 'id']++export function keyArg(args: Record<string, unknown>): string | undefined {+ const pick = (v: unknown): string | undefined => (typeof v === 'string' && v.trim() ? v.trim() : typeof v === 'number' ? String(v) : undefined)+ const lower = new Map(Object.entries(args).map(([k, v]) => [k.toLowerCase(), v]))+ let value: string | undefined+ for (const k of KEYS) if ((value = pick(lower.get(k)))) break+ value ??= Object.entries(args)+ .filter(([k]) => !k.startsWith('_') && !SECRET_NAME.test(k))+ .map(([, v]) => pick(v))+ .find(Boolean)+ if (!value) return undefined+ return clipInput(maskSecrets(value))+}++const clipInput = (v: string): string => (v.length > INPUT_MAX ? `${v.slice(0, INPUT_MAX)}…` : v)+const n = (x: number): string => x.toLocaleString(locale())+const rows = (x: number): string => (x === 1 ? L('1 linha', '1 row') : L(`${n(x)} linhas`, `${n(x)} rows`))++// Rows in a JSON answer: an array, or the shapes SQL tools answer with (Databricks' statement API among them).+function jsonCount(v: unknown): string | undefined {+ if (Array.isArray(v)) return v.length === 1 ? L('1 item', '1 item') : L(`${n(v.length)} itens`, `${n(v.length)} items`)+ if (!v || typeof v !== 'object') return undefined+ const o = v as Record<string, unknown>+ const at = (path: string[]): unknown => path.reduce<unknown>((acc, k) => (acc && typeof acc === 'object' ? (acc as Record<string, unknown>)[k] : undefined), o)+ for (const p of [['manifest', 'total_row_count'], ['result', 'row_count'], ['row_count'], ['total_row_count'], ['rowCount']]) {+ const c = at(p)+ if (typeof c === 'number') return rows(c)+ }+ for (const p of [['result', 'data_array'], ['data_array'], ['rows'], ['data'], ['results'], ['items']]) {+ const c = at(p)+ if (Array.isArray(c)) return p.includes('items') ? jsonCount(c) : rows(c.length)+ }+ return undefined+}++// A table in text: a box drawn with +---+ (the databricks CLI's, MySQL's), Markdown, or CSV/TSV with+// the same separators on every line as on the header.+function tableRows(lines: string[]): number | undefined {+ if (lines.length < 2) return undefined+ if (/^\+[-+]+\+$/.test(lines[0]!.trim())) {+ const body = lines.filter((l) => /^\|.*\|$/.test(l.trim()))+ return body.length ? body.length - 1 : undefined // the first |…| line is the header+ }+ const markdown = /^\|.*\|$/.test(lines[0]!) && /^\|?[\s:|-]+\|?$/.test(lines[1]!)+ if (markdown) return lines.length - 2+ for (const sep of ['\t', ',', ';', '|']) {+ const count = (l: string): number => l.split(sep).length - 1+ const c = count(lines[0]!)+ if (c > 0 && lines.every((l) => count(l) === c)) return lines.length - 1+ }+ return undefined+}++// A result in a few words: how many rows or items when it's data, how many lines when it's long text,+// the text itself when it's short.+export function resultSummary(text: string): string {+ const t = text.replace(/\n\[… (resultado cortado|result cut)[^\]]*\]$/, '').trim()+ const cut = t.length < text.trim().length ? L(' (cortado)', ' (cut)') : ''+ if (!t) return L('Sem resultado', 'No result')+ if (/^[[{]/.test(t)) {+ try {+ const c = jsonCount(JSON.parse(t))+ if (c) return c + cut+ } catch {+ // not JSON after all+ }+ }+ const footer = /\((\d+) rows?\)\s*$/i.exec(t) // psql's "(3 rows)"+ if (footer) return rows(Number(footer[1])) + cut+ const lines = t.split(/\r?\n/).filter((l) => l.trim())+ const table = tableRows(lines)+ if (table !== undefined) return rows(table) + cut+ if (lines.length > 3) return L(`${n(lines.length)} linhas de texto`, `${n(lines.length)} lines of text`) + cut+ const one = maskSecrets(lines.join(' · '))+ return (one.length > LINE_MAX ? `${one.slice(0, LINE_MAX)}…` : one) + cut+}++// ---------- secrets ----------++// What a step shows never carries a secret: commands and outputs pass through here first. The agent+// still gets the real text; only what the screen (and whoever looks over the shoulder) sees is masked.+export const MASK = '••••'+const SECRET_WORDS = String.raw`(?:token|secret|password|passwd|pwd|api[_-]?key|apikey|access[_-]?key|private[_-]?key|client[_-]?secret|credentials?)`+const SECRET_NAME = new RegExp(`${SECRET_WORDS}|auth|^pat$`, 'i')+const QUOTED_OR_WORD = String.raw`("[^"]*"|'[^']*'|[^\s;&|'"]+)`+const TOKEN_SHAPES = [+ /\bdapi[0-9a-f]{32}(?:-\d+)?\b/g, // Databricks personal access token+ /\bdose[0-9a-f]{32}(?:-\d+)?\b/g, // Databricks OAuth secret+ /\bgh[pousr]_[A-Za-z0-9]{30,}\b/g,+ /\bgithub_pat_[A-Za-z0-9_]{30,}\b/g,+ /\bglpat-[A-Za-z0-9_-]{20,}\b/g,+ /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,+ /\bxox[abprs]-[A-Za-z0-9-]{10,}\b/g,+ /\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}\b/g,+ /\bAIza[0-9A-Za-z_-]{35}\b/g,+ /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g // a JWT+]+const RULES: [RegExp, string | ((...m: string[]) => string)][] = [+ // Authorization: Bearer xyz / Basic xyz, in curl's headers and the like+ [/\b(authorization\s*[:=]\s*)(?:(bearer|basic|token)\s+)?[^\s"',}]+/gi, (_m, head, kind) => `${head}${kind ? `${kind} ` : ''}${MASK}`],+ [/\b(bearer)\s+[A-Za-z0-9._~+/=-]{8,}/gi, `$1 ${MASK}`],+ // --token xyz, --password=xyz, --client-secret "xyz"+ [new RegExp(String.raw`(--?[\w-]{0,40}${SECRET_WORDS})(\s+|=)${QUOTED_OR_WORD}`, 'gi'), `$1$2${MASK}`],+ // DATABRICKS_TOKEN=xyz, export API_KEY="xyz", password=xyz in a connection string+ [new RegExp(String.raw`\b([A-Za-z_][\w.-]{0,40}?${SECRET_WORDS})(\s*=\s*)${QUOTED_OR_WORD}`, 'gi'), `$1$2${MASK}`],+ // "token": "xyz" in JSON, token: xyz in YAML+ [new RegExp(String.raw`(["']?[\w-]{0,40}${SECRET_WORDS}["']?\s*:\s*)("[^"]*"|'[^']*'|[^\s,}\]]+)`, 'gi'), (_m, head, v) => `${head}${v!.startsWith('"') ? `"${MASK}"` : v!.startsWith("'") ? `'${MASK}'` : MASK}`],+ // https://user:password@host+ [/(\b[a-z][a-z0-9+.-]{0,30}:\/\/[^\s:/@]+:)[^\s@/]+@/gi, `$1${MASK}@`],+ // -p is a password only for these (for mkdir, ssh or the databricks CLI it's something else)+ [/\b(mysql|mariadb|mysqldump|mysqladmin|sshpass)\b([^\n|;&]{0,300}?\s)-p(?:\s+|=)?(?![\s-])\S+/g, `$1$2-p${MASK}`]+]++// The rules' prefixes are bounded ({0,40} and the like): unbounded, a long run of word characters (base64, a hash)+// made each rule scan to the end from every position, seconds on 40 KB with the core waiting.+export function maskSecrets(text: string): string {+ let t = text+ for (const [re, to] of RULES) t = t.replace(re, to as never)+ for (const shape of TOKEN_SHAPES) t = t.replace(shape, MASK)+ return t+}++// ---------- shell commands ----------++// The SQL a command runs, when it carries one: --statement, -e/--execute, -c/--command, -q/--query/--sql+// (databricks, psql, mysql, bq, snowsql…), a "statement" in --json, or a heredoc that reads like SQL.+const SQLISH = /^\s*(select|with|insert|update|delete|merge|create|drop|alter|describe|desc|show|explain|optimize|vacuum|copy|truncate|use|refresh|analyze)\b/i+const QUOTED = String.raw`("(?:[^"\\]|\\.)*"|'[^']*'|\$'(?:[^'\\]|\\.)*')`+const SQL_FLAG = new RegExp(String.raw`(?:^|\s)(?:--statement|--sql|--query|--execute|--command|-e|-c|-q)(?:\s+|=)` + QUOTED, 'g')++function unquote(v: string): string {+ if (v.startsWith("$'")) return v.slice(2, -1).replace(/\\n/g, '\n').replace(/\\(.)/g, '$1')+ if (v.startsWith('"')) return v.slice(1, -1).replace(/\\(["\\$`])/g, '$1')+ return v.slice(1, -1)+}++export function sqlIn(command: string): string | undefined {+ for (const m of command.matchAll(SQL_FLAG)) {+ const v = unquote(m[1]!).trim()+ if (SQLISH.test(v)) return v+ }+ const json = /"statement"\s*:\s*"((?:[^"\\]|\\.)*)"/.exec(command)+ if (json) {+ try {+ return (JSON.parse(`"${json[1]}"`) as string).trim()+ } catch {+ return json[1]!.trim()+ }+ }+ const heredoc = /<<-?\s*(['"]?)(\w+)\1[^\n]*\n([\s\S]*?)\n\s*\2\s*(?:\n|$)/.exec(command)+ if (heredoc && SQLISH.test(heredoc[3]!)) return heredoc[3]!.trim()+ return undefined+}++// What a shell command step shows: the SQL it runs when it has one (with the command's first line as the+// detail), the whole command otherwise. Masked.+export function commandStep(command: string): { sql: boolean; input: string; detail: string } {+ const masked = maskSecrets(command.trim())+ const sql = sqlIn(command)+ if (!sql) return { sql: false, input: clipInput(masked), detail: '' }+ // The command's first line with the SQL left out ("--statement "…""): the SQL shows below it.+ const first = (masked.replace(sql, '…').split('\n')[0] ?? '').trim()+ return { sql: true, input: clipInput(maskSecrets(sql)), detail: first.length > LINE_MAX ? `${first.slice(0, LINE_MAX)}…` : first }+}++// The end of a command, from the computer's "exit code N / --- stdout --- / --- stderr ---" text:+// what came out in a few words, or why it failed (the exit code and the last lines of stderr).+export function execSummary(text: string, failed: boolean): { output?: string; error?: string } {+ const code = /^exit code (-?\d+)/m.exec(text)?.[1]+ const part = (name: string): string => new RegExp(String.raw`--- ${name} ---\n([\s\S]*?)(?=\n--- (?:stdout|stderr) ---\n|$)`).exec(text)?.[1]?.trim() ?? ''+ const stdout = part('stdout')+ const stderr = part('stderr')+ if (!failed) return { output: stdout ? resultSummary(stdout) : L('Sem saída', 'No output') }+ if (code === undefined) return { error: maskSecrets(text.trim().split('\n').slice(0, 3).join('\n')) || L('Falhou sem mensagem', 'Failed with no message') }+ const why = maskSecrets((stderr || stdout).split('\n').filter((l) => l.trim()).slice(-3).join('\n'))+ return { error: `exit code ${code}${why ? `: ${why}` : ''}` }+}diff --git a/src/renderer/src/components/Conversation.tsx b/src/renderer/src/components/Conversation.tsxindex bd1da5a..153e4c1 100644--- a/src/renderer/src/components/Conversation.tsx+++ b/src/renderer/src/components/Conversation.tsx@@ -879,8 +879,10 @@ function useNow(on: boolean): number {// steps it took. The steps themselves open on a click.function RunSteps({ message }: { message: Message }): ReactNode {const run = message.run!- const [open, setOpen] = useState(false)+ // Open while the agent works, so its steps read as they go, unless the person closes it; closed after.+ const [toggled, setOpen] = useState<boolean | null>(null)const working = run.status === 'working'+ const open = toggled ?? workingconst now = useNow(working)// Just finished: the pulse turns into a green check for a moment, then the chevron is back.const justDone = useJustEnded(working, 1600) && run.status === 'done'@@ -949,14 +951,22 @@ function RunSteps({ message }: { message: Message }): ReactNode {function StepRow({ step }: { step: Step }): ReactNode {const [whole, setWhole] = useState(false)+ const [allInput, setAllInput] = useState(false)return (- <li className={`step step--${step.status}${step.error ? ' step--why' : ''}`}>+ <li className={`step step--${step.status}${step.error || step.input || step.output ? ' step--why' : ''}`}><span className="step__icon">{step.status === 'running' ? <span className="spinner" /> : <Icon name={step.status === 'done' ? 'check' : 'x'} size={12} />}</span><span className="step__label">{step.label}</span>{step.note ? <span className="step__note">{step.note}</span> : step.detail && <code className="step__detail">{step.detail}</code>}{step.ms !== undefined && <span className="step__ms">{duration(step.ms)}</span>}+ {step.input && (+ // What it asked (the SQL, the path): two lines, the whole of it on a click.+ <code className={`step__input${allInput ? ' is-whole' : ''}`} title={allInput ? undefined : L('Ver tudo', 'See all')} onClick={() => setAllInput(!allInput)}>+ <span className="step__clamp">{step.input}</span>+ </code>+ )}+ {step.output && <span className="step__output">→ {step.output}</span>}{step.error && (// Why it failed, in the tool's words: a few lines, the whole of it on a click.<span className={`step__error${whole ? ' is-whole' : ''}`} title={whole ? undefined : L('Ver tudo', 'See all')} onClick={() => setWhole(!whole)}>diff --git a/src/renderer/src/styles.css b/src/renderer/src/styles.cssindex e790083..72ee31a 100644--- a/src/renderer/src/styles.css+++ b/src/renderer/src/styles.css@@ -1347,6 +1347,38 @@ h3 {-webkit-box-orient: vertical;overflow: hidden;}+.step__input {+ flex-basis: 100%;+ margin-left: 26px;+ padding: 4px 8px;+ border-radius: 6px;+ background: var(--code-bg);+ color: var(--text-2);+ font-size: 11.5px;+ line-height: 1.45;+ white-space: pre-wrap;+ overflow-wrap: anywhere;+ user-select: text;+ cursor: pointer;+}+.step__clamp {+ display: -webkit-box;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+}+.step__input.is-whole {+ cursor: text;+}+.step__input.is-whole .step__clamp {+ display: block;+}+.step__output {+ flex-basis: 100%;+ padding-left: 26px;+ color: var(--text-3);+ font-size: 12px;+}.step__error.is-whole {display: block;cursor: text;diff --git a/src/shared/types.ts b/src/shared/types.tsindex eadc407..3f7fa97 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -139,6 +139,8 @@ export interface Step {detail?: stringnote?: string // what the agent said while working, before this step's tool callerror?: string // why it failed, in the tool's own words+ input?: string // what the call asked, the argument that says it (the SQL, the path), as it was sent+ output?: string // what came back, in a few words ("120 rows")status: StepStatusms?: number}diff --git a/test/connector-errors.test.ts b/test/connector-errors.test.tsindex 7f1fdd3..1ef1e77 100644--- a/test/connector-errors.test.ts+++ b/test/connector-errors.test.ts@@ -10,6 +10,7 @@ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js'import { afterEach, beforeEach, describe, expect, it } from 'vitest'import { setLang } from '../src/shared/lang'+import type { CoreEvent } from '../src/shared/rpc'import type { Agent, Message, Settings } from '../src/shared/types'import { callError, ConnectorManager, errorReason } from '../src/core/connectors'import { Db } from '../src/core/db'@@ -41,6 +42,10 @@ s.setRequestHandler(CallToolRequestSchema, async (r) => {if (q === 'resource') return { isError: true, content: [{ type: 'resource', resource: { uri: 'sql://error', text: 'TABLE_OR_VIEW_NOT_FOUND: main.sales.orders' } }] }if (q === 'throw') throw new McpError(-32603, 'Statement failed', { error_code: 'PERMISSION_DENIED', message: 'User does not have SELECT on main.sales' })if (q === 'slow') await new Promise((ok) => setTimeout(ok, 3000))+ if (q.startsWith('select region')) {+ await new Promise((ok) => setTimeout(ok, 400))+ return { content: [{ type: 'text', text: 'region,total\\nSul,120\\nSudeste,340' }] }+ }return { content: [{ type: 'text', text: 'id\\n1\\n2' }] }})await s.connect(new StdioServerTransport())`@@ -52,6 +57,7 @@ let connectors: ConnectorManagerlet connectorId: stringlet settings: Settingslet results: { text: string; isError?: boolean }[]+let events: CoreEvent[]// A "model" that calls the SQL tool once with the statement in the message, and says what it got.function sqlModel(tool = 'execute_sql_read_only'): Engine {@@ -85,7 +91,7 @@ async function ask(statement: string, tool?: string): Promise<{ step: NonNullabldb,engines: { claude: sqlModel(tool), codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') },settings: async () => settings,- emit: () => {},+ emit: (e) => events.push(e),workDir: join(dir, 'work'),gateway,connectors@@ -102,6 +108,7 @@ beforeEach(async () => {dir = mkdtempSync(join(tmpdir(), 'tucano-conn-errors-'))db = new Db(join(dir, 'test.db'))results = []+ events = []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: 'en' }gateway = new Gateway()await gateway.start()@@ -182,3 +189,23 @@ describe('callError and errorReason', () => {expect(errorReason({ content: [] })).toMatch(/no message/)})})++describe('a connector step reads as it goes', () => {+ it('shows the SQL while it runs, and the result in a few words when it is done', async () => {+ const sql = 'select region, sum(total) from main.sales.orders group by 1'+ const { step } = await ask(sql)+ const running = events+ .flatMap((e) => (e.type === 'message' ? (e.message.run?.steps ?? []) : []))+ .find((s) => s.id === step.id && s.status === 'running')+ expect(running?.input).toBe(sql) // already there before the server answered+ expect(running?.output).toBeUndefined()+ expect(step).toMatchObject({ status: 'done', input: sql, output: '2 rows' })+ }, 20_000)++ it('a failed call keeps what it asked, and its reason instead of a result', async () => {+ const { step } = await ask('structured')+ expect(step).toMatchObject({ status: 'error', input: 'structured' })+ expect(step.output).toBeUndefined()+ expect(step.error).toContain('Warehouse abc123 is stopped')+ }, 20_000)+})diff --git a/test/live-steps.test.ts b/test/live-steps.test.tsnew file mode 100644index 0000000..0c5b09e--- /dev/null+++ b/test/live-steps.test.ts@@ -0,0 +1,112 @@+// An agent that works through a skill and shell commands (a databricks-query skill running the+// databricks CLI on its computer) reads as it goes, like its connector calls: which skill it read,+// the SQL it ran (pulled out of the command), the rows that came back or why it failed, and never a+// secret. Claude Code and Codex run here with their own shells off, so every command comes through+// the gateway's `bash`: the scripted turns below call it the way each CLI does.+import { mkdtempSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'+import { setLang } from '../src/shared/lang'+import type { CoreEvent } from '../src/shared/rpc'+import type { Agent, EngineId, Message, Settings, Skill, Step } from '../src/shared/types'+import { formatExec } from '../src/core/computer'+import { Db } from '../src/core/db'+import { callTool, fakeEngine } from '../src/core/engines/fake'+import type { Engine } from '../src/core/engines/types'+import { Gateway, textResult } from '../src/core/gateway'+import { Runner } from '../src/core/runs'++const ready = { installed: true, loggedIn: true }+const TOKEN = ['dapi', '0123456789abcdef'.repeat(2)].join('') // made up, and built so secret scanners don't take it for a real one+const SQL = 'select region, sum(total) as total from main.sales.daily_revenue group by region'+const BOX = '+--------+-------+\n| region | total |\n+--------+-------+\n| Sul | 120 |\n| Norte | 80 |\n+--------+-------+'++const skill: Skill = { id: 's1', name: 'databricks-query', description: 'Run SQL on Databricks with the CLI', body: 'Run `databricks sql execute --statement "<sql>"`.', agents: [], state: 'active', source: '/home/me/.claude/skills/databricks-query/SKILL.md', createdAt: 0, updatedAt: 0 }++let db: Db+let gateway: Gateway+let settings: Settings+let events: CoreEvent[]++// A turn like a CLI's: reads the skill, runs the SQL through the databricks CLI, then a command that fails.+function scripted(id: EngineId): Engine {+ return {+ id,+ async *run(turn) {+ if (turn.mcpUrl) {+ await callTool(turn.mcpUrl, 'ler_skill', { nome: 'databricks-query' })+ await callTool(turn.mcpUrl, 'bash', { command: `DATABRICKS_TOKEN=${TOKEN} databricks sql execute --warehouse-id w1 --statement "${SQL}"` })+ await callTool(turn.mcpUrl, 'bash', { command: `databricks fs ls dbfs:/missing --token ${TOKEN}` })+ await callTool(turn.mcpUrl, 'read_file', { path: 'out/report.csv' })+ }+ yield { type: 'text', delta: 'feito' }+ yield { type: 'done', text: 'feito', usage: { inputTokens: 10, cacheReadTokens: 0, outputTokens: 2 } }+ }+ }+}++// The agent's computer, as the real one answers: "exit code N / --- stdout --- / --- stderr ---".+const computers = {+ call: async (_a: Agent, name: string, args: Record<string, unknown>) => {+ if (name === 'read_file') return { result: textResult('id,total\n1,10\n2,20\n3,30') }+ const command = String(args['command'])+ if (command.includes('dbfs:/missing')) return { result: textResult(formatExec({ code: 1, stdout: '', stderr: `Error: Invalid access token ${TOKEN}\nError: no such directory: dbfs:/missing` }, 120), true) }+ await new Promise((ok) => setTimeout(ok, 50))+ return { result: textResult(formatExec({ code: 0, stdout: BOX, stderr: '' }, 120)) }+ }+}+const skills = {+ forAgent: () => [skill],+ read: () => ({ reply: `# ${skill.name}\n${skill.body}`, skill }),+ propose: () => ({ reply: 'no', error: true })+}++async function run(engine: EngineId, modelId: string): Promise<Step[]> {+ db.saveAgent({ id: 'theo', name: 'Theo', handle: 'theo', role: '', color: 'sky', instructions: '', modelId, effort: 'low', limit: 1_000_000, used: 0, grants: {}, memory: 'auto', computer: true, computerKind: 'mac', archived: false })+ db.createConversation({ id: 'dm', kind: 'dm', name: 'theo', members: ['theo'] })+ const engines = Object.fromEntries((['claude', 'codex', 'opencode', 'pi', 'gemini', 'cursor'] as EngineId[]).map((e) => [e, e === engine ? scripted(e) : fakeEngine(e)])) as Record<EngineId, Engine>+ const runner = new Runner({ db, engines, settings: async () => settings, emit: (e) => events.push(e), workDir: mkdtempSync(join(tmpdir(), 'ls-w-')), gateway, computers, skills })+ await runner.send('dm', 'quanto vendemos por região?')+ await runner.idle()+ return db.messages().filter((m: Message) => m.author.kind === 'agent').at(-1)!.run!.steps+}++beforeAll(() => setLang('en'))+afterAll(() => setLang('pt'))+beforeEach(async () => {+ db = new Db(join(mkdtempSync(join(tmpdir(), 'ls-db-')), 'test.db'))+ events = []+ 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: 'en' }+ gateway = new Gateway()+ await gateway.start()+})+afterEach(() => gateway.stop())++describe.each([+ ['claude', 'sonnet'],+ ['codex', 'gpt-5.6-luna']+] as [EngineId, string][])('an agent on %s working through a skill and the databricks CLI', (engine, modelId) => {+ it('says which skill it read, the SQL it ran, and the rows that came back', async () => {+ const steps = await run(engine, modelId)+ expect(steps.find((s) => s.label === 'Read the skill')).toMatchObject({ detail: 'databricks-query', status: 'done' })+ const sql = steps.find((s) => s.label === 'Ran SQL')!+ expect(sql).toMatchObject({ status: 'done', input: SQL, output: '2 rows' })+ expect(sql.detail).toBe('DATABRICKS_TOKEN=•••• databricks sql execute --warehouse-id w1 --statement "…"')+ expect(steps.find((s) => s.label === 'Read')).toMatchObject({ detail: 'out/report.csv', output: '3 rows' })+ })++ it('shows the SQL while the command still runs', async () => {+ await run(engine, modelId)+ const running = events.flatMap((e) => (e.type === 'message' ? (e.message.run?.steps ?? []) : [])).find((s) => s.label === 'Ran SQL' && s.status === 'running')+ expect(running?.input).toBe(SQL)+ })++ it('a command that fails gives its exit code and stderr, and no step ever shows the token', async () => {+ const steps = await run(engine, modelId)+ const failed = steps.find((s) => s.status === 'error')!+ expect(failed).toMatchObject({ label: 'Ran', input: 'databricks fs ls dbfs:/missing --token ••••' })+ expect(failed.error).toBe('exit code 1: Error: Invalid access token ••••\nError: no such directory: dbfs:/missing')+ expect(JSON.stringify(events.filter((e) => e.type === 'message'))).not.toContain(TOKEN)+ })+})diff --git a/test/step-text.test.ts b/test/step-text.test.tsnew file mode 100644index 0000000..ed6e423--- /dev/null+++ b/test/step-text.test.ts@@ -0,0 +1,106 @@+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { setLang } from '../src/shared/lang'+import { commandStep, execSummary, keyArg, maskSecrets, resultSummary, sqlIn } from '../src/core/step-text'++beforeAll(() => setLang('en'))+afterAll(() => setLang('pt'))++describe('keyArg: the argument that says what a call did', () => {+ it('picks the SQL, the path or the search over the rest', () => {+ expect(keyArg({ warehouse_id: 'abc', statement: 'select 1' })).toBe('select 1')+ expect(keyArg({ limit: 10, Query: 'tucano' })).toBe('tucano')+ expect(keyArg({ path: '/tmp/a.csv', encoding: 'utf8' })).toBe('/tmp/a.csv')+ })+ it('falls back to the first text argument, never the reason the agent gave', () => {+ expect(keyArg({ _motivo: 'because', catalog: 'main' })).toBe('main')+ expect(keyArg({ flag: true })).toBeUndefined()+ })+ it('keeps a long statement whole up to a cap', () => {+ expect(keyArg({ sql: 'x'.repeat(5000) })!.length).toBe(4001)+ })+})++describe('resultSummary: a result in a few words', () => {+ it('counts rows of CSV, TSV and Markdown tables', () => {+ expect(resultSummary('region,total\nSul,120\nSudeste,340')).toBe('2 rows')+ expect(resultSummary('a\tb\n1\t2')).toBe('1 row')+ expect(resultSummary('| a | b |\n|---|---|\n| 1 | 2 |\n| 3 | 4 |\n| 5 | 6 |')).toBe('3 rows')+ })+ it('counts rows of SQL answers in JSON, Databricks shapes included', () => {+ expect(resultSummary(JSON.stringify({ manifest: { total_row_count: 1200 }, result: { data_array: [[1]] } }))).toBe('1,200 rows')+ expect(resultSummary(JSON.stringify({ result: { data_array: [[1], [2], [3]] } }))).toBe('3 rows')+ expect(resultSummary(JSON.stringify([{ id: 1 }, { id: 2 }]))).toBe('2 items')+ })+ it('says how long a long text is, and shows a short one', () => {+ expect(resultSummary('a\nb\nc\nd\ne')).toBe('5 lines of text')+ expect(resultSummary('Created issue ENG-12')).toBe('Created issue ENG-12')+ expect(resultSummary(' ')).toBe('No result')+ })+ it('says when the result was cut', () => {+ expect(resultSummary('id,name\n1,a\n2,b\n[… result cut at 40 KB: the rest didn\'t come through.]')).toBe('2 rows (cut)')+ })+})++// Made-up tokens, built so secret scanners don't take them for real ones.+const DAPI = ['dapi', '0123456789abcdef'.repeat(2)].join('')++describe('maskSecrets: a step never shows a secret', () => {+ const masked = (t: string): string => maskSecrets(t)+ it('masks token and password flags, headers and variables', () => {+ expect(masked(`databricks api get /api/2.0/clusters/list --token ${DAPI}`)).toBe('databricks api get /api/2.0/clusters/list --token ••••')+ expect(masked('psql --password="hunter2" -h db')).toBe('psql --password=•••• -h db')+ expect(masked('curl -H "Authorization: Bearer abc.def.ghi" https://x.cloud.databricks.com')).toBe('curl -H "Authorization: Bearer ••••" https://x.cloud.databricks.com')+ expect(masked('DATABRICKS_TOKEN=dapiXYZ databricks fs ls')).toBe('DATABRICKS_TOKEN=•••• databricks fs ls')+ expect(masked('export AWS_SECRET_ACCESS_KEY="abc/def"')).toBe('export AWS_SECRET_ACCESS_KEY=••••')+ expect(masked('mysql -u root -phunter2 -e "select 1"')).toBe('mysql -u root -p•••• -e "select 1"')+ expect(masked('psql postgres://app:s3cret@db:5432/main')).toBe('psql postgres://app:••••@db:5432/main')+ })+ it('masks tokens by their shape and in JSON or YAML output', () => {+ expect(masked(`using ${DAPI}-2 now`)).toBe('using •••• now')+ expect(masked('ghp_' + 'a'.repeat(36))).toBe('••••')+ expect(masked('{"host": "x", "token": "abc123"}')).toBe('{"host": "x", "token": "••••"}')+ expect(masked('password: abc123')).toBe('password: ••••')+ })+ it('leaves ordinary commands alone', () => {+ for (const c of ['mkdir -p /tmp/out', 'databricks -p prod fs ls dbfs:/', 'ssh -p 2222 host', 'echo $max_tokens', 'select author from books']) expect(masked(c)).toBe(c)+ })++ // The core waits while a step is masked: a long run of word characters (base64, a hash, a minified+ // line) used to take seconds on 40 KB.+ it('masks a long text in a blink, whatever it is made of', () => {+ for (const s of ['a'.repeat(40_000), 'QUJD'.repeat(10_000), 'a.'.repeat(20_000), 'a-'.repeat(20_000), 'mysql '.repeat(7000), 'x://a:'.repeat(7000)]) {+ const t0 = performance.now()+ maskSecrets(s)+ expect(performance.now() - t0).toBeLessThan(250)+ }+ })+})++describe('sqlIn and commandStep: the SQL inside a command', () => {+ it('finds it after --statement, -e, -c, in --json, and in a heredoc', () => {+ expect(sqlIn('databricks sql execute --warehouse-id abc --statement "select * from main.sales.orders limit 10"')).toBe('select * from main.sales.orders limit 10')+ expect(sqlIn(`psql -h db -c 'SELECT count(*) FROM t'`)).toBe('SELECT count(*) FROM t')+ expect(sqlIn(`databricks api post /api/2.0/sql/statements --json '{"warehouse_id": "w1", "statement": "select 1 as \\"x\\""}'`)).toBe('select 1 as "x"')+ expect(sqlIn("databricks-query <<'SQL'\nselect region, sum(total)\nfrom main.sales.daily\ngroup by 1\nSQL")).toBe('select region, sum(total)\nfrom main.sales.daily\ngroup by 1')+ expect(sqlIn('python -c "print(1)"')).toBeUndefined()+ expect(sqlIn('ls -la')).toBeUndefined()+ })+ it('shows the SQL, masked, with the command line as the detail; or the whole command', () => {+ expect(commandStep('DATABRICKS_TOKEN=dapiX databricks sql execute --statement "select 1"')).toEqual({ sql: true, input: 'select 1', detail: 'DATABRICKS_TOKEN=•••• databricks sql execute --statement "…"' })+ expect(commandStep('cat a.csv | wc -l')).toEqual({ sql: false, input: 'cat a.csv | wc -l', detail: '' })+ })+})++describe('execSummary: how a command ended', () => {+ it('counts the rows a CLI printed, or says it printed nothing', () => {+ const box = '+--------+-------+\n| region | total |\n+--------+-------+\n| Sul | 120 |\n| Norte | 80 |\n+--------+-------+'+ expect(execSummary(`exit code 0\n--- stdout ---\n${box}`, false)).toEqual({ output: '2 rows' })+ expect(execSummary('exit code 0\n--- stdout ---\nid,name\n1,a', false)).toEqual({ output: '1 row' })+ expect(execSummary('exit code 0\n(no output)', false)).toEqual({ output: 'No output' })+ })+ it('gives the exit code and the end of stderr on failure, masked', () => {+ expect(execSummary(`exit code 1\n--- stderr ---\nretrying...\nError: Invalid access token ${DAPI}`, true)).toEqual({+ error: 'exit code 1: retrying...\nError: Invalid access token ••••'+ })+ })+})