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
[Enhancement] Answer an agent's decisions one at a time, with options to pick (#145)
Cleiton Salvagnideeeed66d5f1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4fd8e38..33b11d1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,7 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht### Added- **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))## [0.2.17] - 2026-11-07diff --git a/scripts/screens.mjs b/scripts/screens.mjsindex 2f8d2a0..acf216f 100644--- a/scripts/screens.mjs+++ b/scripts/screens.mjs@@ -55,10 +55,22 @@ await shot('03-router-escolheu')await send('@lia antes de sugerir qualquer coisa, use a ferramenta de pergunta pra me perguntar qual é o meu prazo.')await settle()await shot('04-pergunta')-await send('Até sexta.')+await send('Até sexta.') // the message box still answers, as beforeawait settle()await shot('05-respondeu-pergunta')+// Several decisions: a card under the reply, one at a time, then a review before sending.+await send('@lia me ajuda a decidir')+await settle()+await win.waitForSelector('.ask--answer')+await shot('05a-decisoes')+await win.locator('.ask-option').first().click()+await win.fill('.ask__text', 'Até sexta.')+await win.keyboard.press('Enter')+await shot('05b-decisoes-revisao')+await win.locator('.ask .btn--primary').click()+await settle()+// Handoff: Lia mentions Theo, who answers next.await send('@lia peça pro Theo calcular a mediana de 3, 9 e 4, mencionando ele com arroba. Você não calcula.')await settle()diff --git a/src/core/context.ts b/src/core/context.tsindex 88b35cd..99f1066 100644--- a/src/core/context.ts+++ b/src/core/context.ts@@ -8,6 +8,7 @@ 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 type { ToolDef } from './gateway'+import { describeQuestions, questionsOf } from '../shared/questions'import { osOf, shellCommand, systemName } from './platform'export const HISTORY_LIMIT = 30@@ -411,7 +412,7 @@ export function transcriptBlocks(opts: TranscriptOpts): { blocks: string[]; bloc[m.text.trim(),...(images?.get(m.id) ?? []).map((n) => L(`[imagem anexada: ${n}]`, `[attached image: ${n}]`)),- m.run?.question && L(`(pergunta enviada a ${m.run.askedTo ? personName(m.run.askedTo) : me} pela ferramenta ask_user: ${m.run.question})`, `(question sent to ${m.run.askedTo ? personName(m.run.askedTo) : me} with the ask_user tool: ${m.run.question})`)+ questionsOf(m.run).length > 0 && L(`(pergunta enviada a ${m.run?.askedTo ? personName(m.run.askedTo) : me} pela ferramenta ask_user: ${describeQuestions(questionsOf(m.run))})`, `(question sent to ${m.run?.askedTo ? personName(m.run.askedTo) : me} with the ask_user tool: ${describeQuestions(questionsOf(m.run))})`)].filter(Boolean).join('\n\n')diff --git a/src/core/db.ts b/src/core/db.tsindex 5e02b67..6520556 100644--- a/src/core/db.ts+++ b/src/core/db.ts@@ -954,6 +954,14 @@ export class Db {return (this.db.prepare('SELECT * FROM messages ORDER BY at').all() as Row[]).map((r) => this.toMessage(r))}+ // The latest question waiting for me, however much was said after it. `threadId`: in that thread; null: outside threads.+ waitingQuestion(conversationId: string, threadId: string | null): Message | undefined {+ const where = threadId === null ? 'thread_id IS NULL' : 'thread_id = ?'+ const args = threadId === null ? [conversationId] : [conversationId, threadId]+ const row = this.db.prepare(`SELECT * FROM messages WHERE conversation_id = ? AND ${where} AND json_extract(run, '$.status') = 'waiting_input' ORDER BY at DESC LIMIT 1`).get(...args) as Row | undefined+ return row ? this.toMessage(row) : undefined+ }+// `threadId`: only that thread's replies; null: only what's outside threads; left out: everything.recentMessages(conversationId: string, limit: number, threadId?: string | null): Message[] {const where = threadId === undefined ? '' : threadId === null ? ' AND thread_id IS NULL' : ' AND thread_id = ?'diff --git a/src/core/engines/fake.ts b/src/core/engines/fake.tsindex 935e567..ff698ec 100644--- a/src/core/engines/fake.ts+++ b/src/core/engines/fake.ts@@ -120,6 +120,21 @@ export function fakeEngine(id: Engine['id'], opts: { delayMs?: number; reply?: (await new Promise((r) => setTimeout(r, Number(/pergunte em (\d+) ?s/i.exec(last)![1]) * 1000))await callTool(turn.mcpUrl, 'ask_user', { question: 'Pra quando você precisa disso?' })reply = 'Te mandei uma pergunta.'+ } else if (/decis(õ|o)es demais/i.test(last) && turn.mcpUrl) {+ await callTool(turn.mcpUrl, 'ask_user', { questions: Array.from({ length: 5 }, (_, i) => ({ question: `Decisão ${i + 1}?`, kind: 'text' })) })+ reply = 'Tentei perguntar demais.'+ } else if (/ajuda a decidir|decida com/i.test(last) && turn.mcpUrl) {+ // "me ajuda a decidir": decisions with options. "decida com a Bia": the same, to someone in+ // particular (a Tucano with people). Not any "decidimos", which other tests say as a fact.+ const para = /decida com (?:a |o )?(\p{L}+)/iu.exec(last)?.[1]+ const r = await callTool(turn.mcpUrl, 'ask_user', {+ questions: [+ { question: 'Paginação no menu?', kind: 'single', options: [{ label: 'Busca remota' }, { label: 'Scroll infinito' }] },+ { question: 'Pra quando?', kind: 'text' }+ ],+ ...(para ? { para } : {})+ })+ reply = textOf(r).includes('autorizar') || textOf(r).includes('allow') ? 'Vou perguntar se deixarem.' : 'Te mandei duas decisões.'} else if (turn.mcpUrl && /pergunte (?:a|à|pra|para) (\p{L}+)/iu.test(last)) {// "pergunte a Bia": a question to someone in particular (a Tucano with people).const r = await callTool(turn.mcpUrl, 'ask_user', { question: 'Pra quando você precisa disso?', para: /pergunte (?:a|à|pra|para) (\p{L}+)/iu.exec(last)![1]! })diff --git a/src/core/index.ts b/src/core/index.tsindex 9aff340..09ee12d 100644--- a/src/core/index.ts+++ b/src/core/index.ts@@ -66,6 +66,7 @@ import { agentFromDraft, availableModels, tucaAgent, tucaHello, tucaUpToDate } fimport { initializeWorkspace } from './seed'import { workspacePorts } from './ports'import { isTheme, workspaceLabel, workspaceParts } from '../shared/workspaces'+import { isNewQuestion } from '../shared/questions'const dataDir = process.env['TUCANO_DATA'] ?? join(process.cwd(), '.tucano')const fake = process.env['TUCANO_FAKE_ENGINES'] === '1'@@ -310,7 +311,7 @@ function toPhone(e: CoreEvent): void {if (e.type === 'approval' && e.approval.state === 'pending' && !sentToPhone.has(e.approval.id)) {sentToPhone.add(e.approval.id)void telegram.approvalAsked(e.approval, name(e.approval.agentId))- } else if (e.type === 'message' && e.message.run?.status === 'waiting_input' && e.message.run.question && e.message.author.kind === 'agent' && !sentToPhone.has(e.message.id) && forOwner(e.message.id)) {+ } else if (e.type === 'message' && e.message.author.kind === 'agent' && isNewQuestion(e.message) && !sentToPhone.has(e.message.id) && forOwner(e.message.id)) {sentToPhone.add(e.message.id)const conv = db.conversation(e.message.conversationId)void telegram.questionAsked(e.message, name(e.message.author.id), conv?.kind === 'channel' ? `#${conv.name}` : L('na DM', 'in the DM'))@@ -1850,6 +1851,9 @@ const api: Handlers = {inbox: (_, ctx) => people.inbox(ctx.person),answerQuestion: ({ id, text }, ctx) => runner.answer(id, text, ctx.person),confirmQuestion: ({ id, ok }, ctx) => runner.confirm(id, ok, ctx.person),+ // A question's decisions, answered on the card one at a time and then sent: by whoever may answer it (Runner.decidable).+ answerDecision: ({ messageId, index, answer }, ctx) => runner.answerDecision(messageId, index, answer, ctx.person),+ submitDecisions: ({ messageId }, ctx) => runner.submitDecisions(messageId, ctx.person),runRoutine: ({ id }, ctx) => {const r = db.routine(id)if (!r) throw new Error(L('Essa rotina não existe mais.', 'That routine no longer exists.'))diff --git a/src/core/people.ts b/src/core/people.tsindex 5f13064..bc62c6a 100644--- a/src/core/people.ts+++ b/src/core/people.ts@@ -451,7 +451,10 @@ export class People {q.confirm === 'pending'? q.requestedBy === person.id: q.askedTo === person.id || delegating(this.db.person(q.askedTo), person.id, now) || (now >= q.deadlineAt && q.requestedBy === person.id)- return waiting ? [shown(q)] : []+ if (!waiting) return []+ // Its decisions, to answer them on the card from here too (the question only, as its text is).+ const run = this.db.message(q.id)?.run+ return [{ ...shown(q), ...(run?.questions?.length ? { decisions: run.questions, ...(run.answers ? { answers: run.answers } : {}) } : {}) }]})// Asked to them and answered a moment ago by someone else (an admin, whoever covers for them).const answered = this.db.answeredQuestions(now - ANSWERED_SHOWN_MS).filter((q) => q.askedTo === person.id && q.answeredBy !== person.id).map(shown)diff --git a/src/core/policy-people.ts b/src/core/policy-people.tsindex c225b2d..636ee10 100644--- a/src/core/policy-people.ts+++ b/src/core/policy-people.ts@@ -166,6 +166,8 @@ export const NEEDS: Record<Method, Need> = {inbox: 'anyone',answerQuestion: 'target',confirmQuestion: 'target',+ answerDecision: 'target', // who may answer the question (Runner.decidable)+ submitDecisions: 'target',// agents, skills and the teamsaveAgent: 'admin',archiveAgent: 'admin',diff --git a/src/core/routines.ts b/src/core/routines.tsindex a9e3665..7c187df 100644--- a/src/core/routines.ts+++ b/src/core/routines.ts@@ -11,6 +11,7 @@ import type { Db } from './db'import { errorReason } from './connectors'import type { ToolDef } from './gateway'import type { RoutineEvent } from './runs'+import { questionHeadline, questionsOf } from '../shared/questions'export { MAX_AGENT_ROUTINES } // the default; each agent's own is agent.maxRoutines@@ -462,7 +463,7 @@ export function outcome(reply: Message): string {case 'waiting_approval':return L('Pediu aprovação pra continuar.', 'Asked for approval to go on.')case 'waiting_input':- return `${L('Perguntou', 'Asked')}: ${reply.run.question ?? ''}`.trim()+ return `${L('Perguntou', 'Asked')}: ${questionHeadline(questionsOf(reply.run))}`.trim()case 'limit_reached':return L('Parou: chegou no limite de tokens do mês.', "Stopped: hit the month's token limit.")case 'paused':diff --git a/src/core/runs.ts b/src/core/runs.tsindex 8a73c80..8535812 100644--- a/src/core/runs.ts+++ b/src/core/runs.ts@@ -24,6 +24,7 @@ import { outOfQuota } from './engines/cli'import { ALWAYS_LOAD, textResult, type Gateway, type Session, type ToolDef } from './gateway'import { Followups, replyKey } from './followups'import { sessionConfig, Sessions, type SessionPlan, type Shown } from './sessions'+import { formatAnswers, MAX_DESCRIPTION_LENGTH, MAX_LABEL_LENGTH, MAX_OPTIONS, MAX_QUESTION_LENGTH, MAX_QUESTIONS, MIN_OPTIONS, parseQuestions, questionHeadline, questionsAsText, questionsOf, type Answer, type Decision } from '../shared/questions'import { JEV_MODEL, routeJev } from './jev'import { ROUTER_HISTORY, route, routerTurn, screenHandoff } from './router'import { allowed, approvalHash, callClass, canonical, permits, runnerAllowed, runnerRules } from './policy'@@ -69,15 +70,43 @@ export const ASK_USER: ToolDef = {name: 'ask_user',get description() {return L(- 'Faz uma pergunta curta ao usuário quando falta uma informação pra continuar. Depois de chamar, encerre a resposta: a resposta do usuário chega na próxima mensagem.',- "Asks the user a short question when a piece of information is missing to go on. After calling it, end your reply: the user's answer comes in the next message."+ 'Pede ao usuário as decisões que faltam pra continuar. Escreva a análise e a proposta no texto da sua resposta, antes de chamar; aqui vão só as decisões, cada uma com uma pergunta curta e, quando der, opções curtas (detalhe em description). Tipos: single (uma opção), multiple (várias), text (resposta livre). De 1 a 4 decisões; de 1 a 3 opções por decisão, as mais prováveis: o app sempre acrescenta "Outra coisa", com resposta livre, então não inclua essa opção. Depois de chamar, encerre a resposta: as respostas chegam na próxima mensagem.',+ "Asks the user for the decisions missing to go on. Write your analysis and proposal in your reply's text, before calling; here go only the decisions, each with a short question and, when possible, short options (detail in description). Kinds: single (one option), multiple (several), text (free answer). 1 to 4 decisions; 1 to 3 options per decision, the likeliest ones: the app always adds \"Something else\", with a free answer, so don't include that option. After calling it, end your reply: the answers come in the next message.")},get inputSchema() {return {type: 'object' as const,- properties: { question: { type: 'string', description: L('A pergunta, curta e direta.', 'The question, short and direct.') } },- required: ['question']+ properties: {+ questions: {+ type: 'array',+ minItems: 1,+ maxItems: MAX_QUESTIONS,+ items: {+ type: 'object',+ properties: {+ question: { type: 'string', maxLength: MAX_QUESTION_LENGTH, description: L('A pergunta, curta e direta.', 'The question, short and direct.') },+ kind: { type: 'string', enum: ['single', 'multiple', 'text'] },+ options: {+ type: 'array',+ minItems: MIN_OPTIONS,+ maxItems: MAX_OPTIONS,+ description: L('Pra single e multiple.', 'For single and multiple.'),+ items: {+ type: 'object',+ properties: {+ label: { type: 'string', maxLength: MAX_LABEL_LENGTH, description: L('Curto: o que aparece no botão.', 'Short: what shows on the button.') },+ description: { type: 'string', maxLength: MAX_DESCRIPTION_LENGTH, description: L('Opcional: o que essa opção implica.', 'Optional: what this option implies.') }+ },+ required: ['label']+ }+ }+ },+ required: ['question', 'kind']+ }+ },+ question: { type: 'string', description: L('Forma antiga: uma pergunta de texto. Prefira questions.', 'Old form: one text question. Prefer questions.') }+ }}}}@@ -94,14 +123,33 @@ export const askUserFor = (names: string[]): ToolDef =>),inputSchema: {type: 'object' as const,- properties: { ...ASK_USER.inputSchema.properties, para: { type: 'string', description: L('O nome da pessoa a quem perguntar (opcional).', 'The name of the person to ask (optional).') } },- required: ['question']+ // Every decision of the call goes to that one person.+ properties: { ...ASK_USER.inputSchema.properties, para: { type: 'string', description: L('O nome da pessoa a quem perguntar (opcional): todas as decisões vão pra ela.', 'The name of the person to ask (optional): every decision goes to them.') } }}}// A DM's person saying the agent may ask someone else ("sim", "pode", "yes"); anything else is a no.const YES = /^\s*(sim|s|pode( sim)?|ok(ay)?|claro|autorizo|yes|y|sure|go ahead)\b/i+// What the card sent for one decision, as kept: only what that kind of decision takes, options that+// exist, text cut short. Anything else (not an answer at all): undefined.+const ANSWER_TEXT_MAX = 10_000+function cleanAnswer(question: Decision, raw: Answer): Answer | undefined {+ if (typeof raw !== 'object' || raw === null) return undefined+ if (raw.skipped === true) return { skipped: true }+ const str = (v: unknown): string => (typeof v === 'string' ? v.trim().slice(0, ANSWER_TEXT_MAX) : '')+ if (question.kind === 'text') {+ const text = str(raw.text)+ return text ? { text } : undefined+ }+ const count = question.options?.length ?? 0+ const chosen = Array.isArray(raw.chosen) ? [...new Set(raw.chosen)] : []+ if (chosen.some((i) => !Number.isInteger(i) || i < 0 || i >= count) || (question.kind === 'single' && chosen.length > 1)) return undefined+ const other = str(raw.other)+ if (!chosen.length && !other) return undefined+ return { ...(chosen.length ? { chosen: chosen.sort((a, b) => a - b) } : {}), ...(other ? { other } : {}) }+}+// How long a question to someone else waits before the requester is told (settings may say otherwise).export const QUESTION_DEADLINE_HOURS = 4@@ -327,13 +375,14 @@ export class Runner {// everything else it sets off, go in its thread (`threadId`, or its own when// the conversation answers in threads) or else in the conversation.// `by`: the person writing (the Tucano's owner when left out: the phone, older callers).- // `answers`: the question this answers, from the inbox (its asker answers, wherever the person writes from).+ // `answers`: the question this answers, from the inbox or the decisions card (its asker answers,+ // wherever the person writes from). The caller checked that they may answer it.async send(conversationId: string, text: string, images: ImageUpload[] = [], threadId?: string, by?: string, opts: { answers?: string } = {}): Promise<void> {const { db, emit } = this.depsconst conv = db.conversation(conversationId)- const body = text.trim()+ const typed = text.trim()const pictures = this.deps.dataDir ? images.filter((i) => IMAGE_MIMES.includes(i.mime)).slice(0, MAX_IMAGES_PER_MESSAGE) : []- if (!conv || (!body && pictures.length === 0)) return+ if (!conv) returnconst writer = (by ? db.person(by) : undefined) ?? db.owner()// Threads are one level deep: replying to a reply goes in its thread. A root that isn't// in this conversation (or is gone) doesn't make one: the message goes to the conversation.@@ -343,17 +392,22 @@ export class Runner {// write outside threads stays outside: it only answers a question that is outside too.// A question to someone answers only with their message (or an admin's, or whoever covers// for them; past its deadline, the requester's). One waiting on a DM's yes takes a yes or a no.- const named = opts.answers ? db.question(opts.answers) : undefined- let asked = named ? db.message(named.id) : this.pendingQuestion(conv.id, thread)+ const named = opts.answers ? db.message(opts.answers) : undefined+ let asked = opts.answers ? (named?.conversationId === conv.id ? named : undefined) : this.pendingQuestion(conv.id, thread)if (asked?.run?.status !== 'waiting_input') asked = undefinedconst q = asked ? db.question(asked.id) : undefinedlet confirmed: boolean | undefinedif (q && !named) {if (q.state === 'open' && q.confirm === 'pending') {- if (writer.id === q.requestedBy) confirmed = YES.test(body)+ if (writer.id === q.requestedBy) confirmed = YES.test(typed)asked = undefined} else if (q.state === 'open' && !new People(db).canAnswer(writer, q)) asked = undefined}+ // The decisions answered on the card go first, whether they're sent from it or with a reply+ // written in the field. Only by whoever answers the question: anyone else's message is just theirs.+ const fromCard = asked ? formatAnswers(questionsOf(asked.run), asked.run?.answers) : ''+ const body = [fromCard, typed].filter(Boolean).join('\n\n')+ if (!body && pictures.length === 0) returnconst mine: Message = { id: randomUUID(), conversationId, author: { kind: 'person', id: writer.id }, text: body, at: Date.now(), ...(thread ? { threadId: thread } : {}) }// An answer goes in the thread of what it answers. A message of mine outside one opens it@@ -362,11 +416,11 @@ export class Runner {for (const img of pictures) this.keepImage(mine, img)db.saveMessage(mine)emit({ type: 'message', message: mine })- const calledPeople = this.callPeople(conv, mine, writer.name, writer.id)+ const calledPeople = this.callPeople(conv, mine, writer.name, writer.id, typed) // what they wrote: an option's label never calls anyoneif (confirmed !== undefined && q) return this.confirm(q.id, confirmed, writer)const members = this.members(conv)- let responders = mentioned(body, members).slice(0, MAX_MENTIONS)+ let responders = mentioned(typed, members).slice(0, MAX_MENTIONS) // what I wrote: an option's label never calls anyone// Answered for the person it was asked (by an admin, whoever covers for them, the requester past// the deadline): the agent is told so in so many words.@@ -376,7 +430,10 @@ export class Runner {db.saveQuestion({ ...q, state: 'answered', answeredBy: writer.id, answeredAt: Date.now() })emit({ type: 'inbox' })}- this.update(asked, { run: { ...asked.run!, status: 'done', ...(q ? { answeredBy: writer.id } : {}) } })+ // The message keeps the answers for the agent; the card, which shows them, says which one it is (and+ // what it had beyond them), so the conversation shows them once. With images, it shows whole.+ const link = fromCard && pictures.length === 0 ? { answerMessage: mine.id, ...(typed ? { answerTyped: typed } : {}) } : {}+ this.update(asked, { run: { ...asked.run!, status: 'done', ...(q ? { answeredBy: writer.id } : {}), ...(typed ? { answeredInText: true as const } : {}), ...link } })const asker = members.find((a) => asked.author.kind === 'agent' && a.id === asked.author.id)if (asker && responders.length === 0) responders = [asker]const target = q && q.askedTo !== writer.id ? db.people({ removed: true }).find((p) => p.id === q.askedTo) : undefined@@ -400,7 +457,7 @@ export class Runner {}// Written to a person (@Ana) and to no agent: it's for them, not the agents. No router, no// reply; a line says who heard about it. So with one who left, or yourself: no one to tell.- const toPeople = calledPeople.length > 0 || (db.people().length > 1 && toPeopleOnly(body, db.people({ removed: true }), db.agents()))+ const toPeople = calledPeople.length > 0 || (db.people().length > 1 && toPeopleOnly(typed, db.people({ removed: true }), db.agents()))if (responders.length === 0 && toPeople && conv.kind !== 'dm') {const names = calledPeople.map((p) => `**${p.name}**`).join(L(' e ', ' and '))// Someone who left, yourself, or a name two people share: whoever wrote it learns no one heard.@@ -583,10 +640,7 @@ export class Runner {// The question waiting for me where I write: in a thread, that thread's; outside, one outside threads.private pendingQuestion(conversationId: string, threadId?: string): Message | undefined {- return this.deps.db- .recentMessages(conversationId, 50, threadId ?? null)- .reverse()- .find((m) => m.run?.status === 'waiting_input')+ return this.deps.db.waitingQuestion(conversationId, threadId ?? null)}private post(conversationId: string, threadId: string | undefined, text: string, run?: Run): Message {@@ -968,7 +1022,8 @@ export class Runner {// Tools for this turn, served by the gateway under a URL only this turn knows:// ask_user plus the connector tools this agent's grants allow.- let question: string | undefined+ let question: string | undefined // what ask_user asked, as text (every decision)+ let questions: Decision[] | undefined // the same, structuredlet askedTo: Person = requester // whom the question is forlet confirming = false // in a DM, a question to someone else waits for the DM's person's yes firstlet approval: Approval | undefined@@ -1068,13 +1123,15 @@ export class Runner {const runTool = async (name: string, args: Record<string, unknown>): Promise<CallToolResult> => {if (name === ASK_USER.name) {- const q = typeof args['question'] === 'string' ? args['question'].trim() : ''- if (!q) return textResult(L('Faltou a pergunta.', 'Missing the question.'), true)+ const parsed = parseQuestions(args)+ if ('error' in parsed) return textResult(parsed.error, true)if (question || approval) return textResult(L('Você já está esperando uma resposta nesta mensagem. Encerre agora.', "You're already waiting for an answer in this message. End now."), true)const para = typeof args['para'] === 'string' ? args['para'].trim() : ''const target = para ? personNamed(para, others) : requesterif (!target) return textResult(L(`Não há ninguém chamado "${para}" no Tucano. As pessoas: ${others.map((p) => p.name).join(', ')}.`, `There's no one called "${para}" in this Tucano. The people: ${others.map((p) => p.name).join(', ')}.`), true)- question = q+ questions = parsed.questions+ question = questionsAsText(questions)+ const q = questionHeadline(questions)askedTo = targetif (target.id !== requester.id) {// Someone else: in a DM, its person says yes first; then only the question reaches them.@@ -1326,7 +1383,7 @@ export class Runner {if (out.artifact) artifactIds.push(out.artifact.id)const close = (status: Step['status'], patch: Partial<Step> = {}): Step[] => msg.run!.steps.map((s) => (s.id === step.id ? { ...s, ...patch, status, ms: Date.now() - t0 } : s))if (out.approval) {- if (question || approval) {+ if (questions || approval) {msg.run = { ...msg.run!, steps: [...close('error'), thinking()] }save()return textResult(L('Já existe um pedido esperando decisão nesta mensagem. Encerre agora.', 'There is already a request waiting for a decision in this message. End now.'), true)@@ -1390,7 +1447,7 @@ export class Runner {const out = await apps.call(current, name, args)const close = (status: Step['status'], patch: Partial<Step> = {}): Step[] => msg.run!.steps.map((s) => (s.id === step.id ? { ...s, ...patch, status, ms: Date.now() - t0 } : s))if (out.approval) {- if (question || approval) {+ if (questions || approval) {msg.run = { ...msg.run!, steps: [...close('error'), thinking()] }save()return textResult(L('Já existe um pedido esperando decisão nesta mensagem. Encerre agora.', 'There is already a request waiting for a decision in this message. End now.'), true)@@ -1436,7 +1493,7 @@ export class Runner {const c = this.deps.connectors?.list().find((x) => x.name === args['conector'])const nivel = args['nivel'] === 'read_write' ? 'read_write' : 'read'if (!c) return textResult(L('Esse conector não existe. Use um da lista.', "That connector doesn't exist. Use one from the list."), true)- if (question || approval) return textResult(L('Já existe um pedido esperando decisão nesta mensagem. Encerre agora.', 'There is already a request waiting for a decision in this message. End now.'), true)+ if (questions || approval) return textResult(L('Já existe um pedido esperando decisão nesta mensagem. Encerre agora.', 'There is already a request waiting for a decision in this message. End now.'), true)const why = typeof args['motivo'] === 'string' ? args['motivo'].trim() : ''approval = {id: randomUUID(),@@ -1760,7 +1817,7 @@ export class Runner {}// The main model's subscription is out before it did anything: the same reply goes to the reserve, once.// After a tool call it doesn't, since that would run the call again; the next reply starts on the main model.- const reserve = !onReserve && !result && error && !control.reason && !acted && !question && !approval && (!msg.text.trim() || outOfQuota(msg.text)) && outOfQuota(error) ? this.reserveFor(agent, settings, account) : undefined+ const reserve = !onReserve && !result && error && !control.reason && !acted && !questions && !approval && (!msg.text.trim() || outOfQuota(msg.text)) && outOfQuota(error) ? this.reserveFor(agent, settings, account) : undefinedif (!reserve) breakconst from = `${engineLabel}${account ? ` (${account.name})` : ''}`flush()@@ -1818,7 +1875,7 @@ export class Runner {)}- const base = { endedAt, depth: opts.depth, work, receipt, question, ...(question && (askedTo.id !== requester.id || db.people().length > 1) ? { askedTo: askedTo.id } : {}), approvalId: approval?.id, memoryIds: memoryIds.length ? memoryIds : undefined, artifactIds: artifactIds.length ? artifactIds : undefined, services: services.length ? services : undefined, routineIds: routineIds.length ? routineIds : undefined, browser: msg.run?.browser, agentDraft: msg.run?.agentDraft, proposal: msg.run?.proposal, ...(replyTo ? { replyTo } : {}) }+ const base = { endedAt, depth: opts.depth, work, receipt, question, questions, ...(question && (askedTo.id !== requester.id || db.people().length > 1) ? { askedTo: askedTo.id } : {}), approvalId: approval?.id, memoryIds: memoryIds.length ? memoryIds : undefined, artifactIds: artifactIds.length ? artifactIds : undefined, services: services.length ? services : undefined, routineIds: routineIds.length ? routineIds : undefined, browser: msg.run?.browser, agentDraft: msg.run?.agentDraft, proposal: msg.run?.proposal, ...(replyTo ? { replyTo } : {}) }if (control.reason === 'stopped') {save({ run: { ...base, ...again, status: 'stopped', steps: closeThinking('error', L('Parado', 'Stopped')) } })} else if (control.reason === 'loop' || control.reason === 'errors' || control.reason === 'stall' || control.reason === 'sleeping') {@@ -1862,8 +1919,10 @@ export class Runner {// Streamed text keeps every model call of the turn; the final result may hold only the last one.save({text: msg.text.trim() ? msg.text.trim() : result.text.trim() ? result.text : (narration ?? ''), // said it all before its last tool- run: { ...base, status: question ? 'waiting_input' : waiting ? 'waiting_approval' : 'done', steps: closeThinking('done', L('Respondeu', 'Replied')) }+ run: { ...base, status: questions ? 'waiting_input' : waiting ? 'waiting_approval' : 'done', steps: closeThinking('done', L('Respondeu', 'Replied')) }})+ // The inbox shows a question's decisions from its message, which has them only now.+ if (question) emit({ type: 'inbox' })// The Mac tells you when it's your turn: a question, or the end of the work (once, when no other agent takes it on).if (!question && !approval) {const finished = (): void => {@@ -2159,11 +2218,12 @@ export class Runner {// People a message calls with @name hear about it: whoever can see it, not who wrote it.// Returns who was called.- private callPeople(conv: Conversation, msg: Message, authorName: string, except?: string): Person[] {+ // `text`: what calls them, when it isn't the whole message (the decisions answered on a card don't).+ private callPeople(conv: Conversation, msg: Message, authorName: string, except?: string, text = msg.text): Person[] {const { db } = this.depsif (db.people().length < 2) return [] // alone, no one to call: a desktop hears only what it always didconst people = new People(db)- const called = mentionedPeople(msg.text, db.people(), db.agents()).filter((p) => p.id !== except && people.canSeeConversation(p, conv))+ const called = mentionedPeople(text, db.people(), db.agents()).filter((p) => p.id !== except && people.canSeeConversation(p, conv))if (called.length) this.deps.notify?.(L(`${authorName} te mencionou`, `${authorName} mentioned you`), snip(msg.text, 140), conv.id, undefined, msg.threadId, called.map((p) => p.id))return called}@@ -2172,6 +2232,40 @@ export class Runner {for (const ap of this.deps.db.expiredApprovals()) await this.decide(ap.id, 'expired')}+ // A question whose decisions `by` may answer on the card now: theirs (or one they may answer for+ // someone, as a typed reply would: an admin, whoever covers, the requester past the deadline), never+ // one still waiting on a DM's yes. One from before questions to people: whoever sees the conversation.+ private decidable(messageId: string, by: Person): Message {+ const { db } = this.deps+ const asked = db.message(messageId)+ const q = db.question(messageId)+ if (q && q.state !== 'open') throw new Error(L('Essa pergunta já foi respondida.', 'That question was already answered.'))+ const mayAnswer = q ? q.confirm !== 'pending' && new People(db).canAnswer(by, q) : !!asked && !new People(db).conversationError(by, asked.conversationId)+ if (!asked || !mayAnswer) throw new Error(L('Essa pergunta não é pra você.', "That question isn't for you."))+ if (asked.author.kind !== 'agent' || asked.run?.status !== 'waiting_input') throw new Error(L('Essa pergunta já foi respondida.', 'That question was already answered.'))+ return asked+ }++ // One decision answered on the card (null clears it): kept on the question until it's sent.+ answerDecision(messageId: string, index: number, answer: Answer | null, by: Person): void {+ const asked = this.decidable(messageId, by)+ const questions = questionsOf(asked.run)+ const question = questions[index]+ if (!question) return+ const clean = answer === null ? null : cleanAnswer(question, answer)+ if (clean === undefined) return+ const answers = Array.from({ length: questions.length }, (_, i) => asked.run!.answers?.[i] ?? null)+ answers[index] = clean+ this.update(asked, { run: { ...asked.run!, answers } })+ if (this.deps.db.question(messageId)) this.deps.emit({ type: 'inbox' }) // the card in For you, on another device+ }++ // Sends the decisions answered on the card as the person's message, as if they wrote them.+ async submitDecisions(messageId: string, by: Person): Promise<void> {+ const asked = this.decidable(messageId, by)+ await this.send(asked.conversationId, '', [], asked.threadId, by.id, { answers: asked.id })+ }+// The user took over the agent's browser ("Assumir") and handed it back// ("Devolver" or closing the window) — exactly what the agent asked for with// ask_user, so it goes on by itself instead of waiting for a message.diff --git a/src/core/telegram.ts b/src/core/telegram.tsindex 9d80497..07003c1 100644--- a/src/core/telegram.ts+++ b/src/core/telegram.ts@@ -7,6 +7,7 @@ import { L } from '../shared/lang'import { offline, UserError } from '../shared/errors'import type { Approval, Message, TelegramInfo } from '../shared/types'import type { Secrets } from './secrets'+import { questionsAsText, questionsOf } from '../shared/questions'const API = 'https://api.telegram.org'const TOKEN = 'telegram:token'@@ -234,9 +235,11 @@ export class Telegram {}async questionAsked(msg: Message, agentName: string, where: string): Promise<void> {- if (!msg.run?.question) return+ const questions = questionsOf(msg.run)+ if (!questions.length) return+ const text = questionsAsText(questions)const id = await this.send(- L(`${agentName} pergunta (${where}):\n\n${msg.run.question}\n\nResponda a esta mensagem.`, `${agentName} asks (${where}):\n\n${msg.run.question}\n\nReply to this message.`),+ L(`${agentName} pergunta (${where}):\n\n${text}\n\nResponda a esta mensagem.`, `${agentName} asks (${where}):\n\n${text}\n\nReply to this message.`),{ reply_markup: { force_reply: true, input_field_placeholder: L('Sua resposta', 'Your answer') } })if (id) this.questions.set(id, { conversationId: msg.conversationId, ...(msg.threadId ? { threadId: msg.threadId } : {}) })diff --git a/src/renderer/src/components/Conversation.tsx b/src/renderer/src/components/Conversation.tsxindex b9c10bd..f0515a2 100644--- a/src/renderer/src/components/Conversation.tsx+++ b/src/renderer/src/components/Conversation.tsx@@ -13,6 +13,7 @@ import { KeepInWiki, WikiChip, WikiLink, wikiLinks } from './Wiki'import { canEditChannel,agentById,askerIn,+ messagesIn,attachedTo,conversationIndex,initials,@@ -86,6 +87,8 @@ import { ArtifactCard, BrowserCard, ServiceCard, SidePanel } from './Panel'import { when } from './Routines'import { AgentProposal, ProposalCard } from './Tuca'import { FoldToggle } from './Fold'+import { AnswersSummary, AskCard, asShown, cardAnswers } from './Decisions'+import { questionsOf, type Answer, type Decision } from '../../../shared/questions'import { AgentCardButton } from './AgentCard'// Something exact a person may want to check (the raw error, a tool's arguments), folded until asked.@@ -240,7 +243,10 @@ const NO_REPLIES: Message[] = []// `replies`: a timeline with threads, where each message can start one (its replies by its id).// `older`: there's more before the first message, loaded as the scroll gets near the top.-export function MessageList({ messages, replies, older, conversationId, empty, focus, lead }: { messages: Message[]; replies?: Map<string, Message[]>; older?: boolean; conversationId: string; empty?: boolean; focus?: string; lead?: ReactNode }): ReactNode {+export function MessageList({ messages: all, replies, older, conversationId, empty, focus, lead }: { messages: Message[]; replies?: Map<string, Message[]>; older?: boolean; conversationId: string; empty?: boolean; focus?: string; lead?: ReactNode }): ReactNode {+ // An answer sent from a decisions card shows on the card, not again as a message (Decisions.asShown).+ const everything = useStore((s) => messagesIn(s, conversationId)) // a list: the store compares a Map as always equal+ const messages = useMemo(() => asShown(all, cardAnswers(everything)), [all, everything])const editsChannel = useStore((s) => {const c = s.conversations.find((x) => x.id === conversationId)return !!c && canEditChannel(s, c)@@ -417,6 +423,7 @@ const MessageRow = memo(function MessageRow({ message, grouped, replies }: { mesconst threadOpen = useStore((s) => !!replies && s.panel?.kind === 'thread' && s.panel.id === message.id)const agent = useStore((s) => (message.author.kind === 'agent' ? agentById(s, message.author.id) : undefined))const approval = useStore((s) => (message.run?.approvalId ? s.approvals.find((a) => a.id === message.run!.approvalId) : undefined))+ const team = useStore(teamMode)// Someone else's message reads with their name and initials; mine, as always.const other = useStore((s) => (message.author.kind === 'person' && !isMine(s, message.author) ? personName(s, message.author.id) : undefined))const attached = useStore((s) => (message.author.kind === 'person' ? attachedTo(s, message.id) : NO_ATTACHED))@@ -496,7 +503,14 @@ const MessageRow = memo(function MessageRow({ message, grouped, replies }: { mes))}</div>)}- {message.run?.question && <QuestionCard id={message.id} agentName={agent?.name} askedTo={message.run.askedTo} question={message.run.question} answered={message.run.status !== 'waiting_input'} answeredBy={message.run.answeredBy} />}+ {/* The question, as a card under the reply: alone, mine to answer there; with a team, it says whom it's for, and who+ may answer it does it there. One from before decisions, with a team, is the question card it was. */}+ {questionsOf(message.run).length > 0 &&+ (team && message.run?.askedTo ? (+ <QuestionCard id={message.id} agentName={agent?.name} askedTo={message.run.askedTo} question={message.run.question ?? ''} {...(message.run.questions?.length ? { decisions: message.run.questions } : {})} answers={message.run.answers} answeredInText={message.run.answeredInText} answered={message.run.status !== 'waiting_input'} answeredBy={message.run.answeredBy} />+ ) : (+ <AnswersSummary message={message} />+ ))}{approval && <ApprovalCard approval={approval} />}{message.run?.agentDraft && <AgentProposal message={message} />}{message.run?.proposal && <ProposalCard message={message} />}@@ -962,12 +976,17 @@ function RoutineChip({ id }: { id: string }): ReactNode {// A question an agent asked (ask_user). Alone (a desktop), it's mine: my next message answers it.// With a team it says whom it's for; who may answer it (the person, whoever covers for them, an// admin, or past the deadline the requester) gets a field; in my DM, a question to someone else-// first asks me whether it may go.+// first asks me whether it may go. With decisions (ask_user's options), it's their card+// (TeamAsk): answered on it by whoever may answer the question.// What someone was typing to answer a question, kept by question: if someone else answers first,// or the card moves (Pra você drops it), it's still there, with who answered.export const questionDrafts = new Map<string, string>()-export function QuestionCard({ id, agentName, askedTo, question, answered, answeredBy, inbox }: { id: string; agentName?: string; askedTo?: string; question: string; answered: boolean; answeredBy?: string; inbox?: boolean }): ReactNode {+export function QuestionCard(props: { id: string; agentName?: string; askedTo?: string; question: string; decisions?: Decision[]; answers?: (Answer | null)[]; answeredInText?: boolean; answered: boolean; answeredBy?: string; inbox?: boolean }): ReactNode {+ return props.decisions?.length ? <TeamAsk {...props} decisions={props.decisions} /> : <TextQuestion {...props} />+}++function TextQuestion({ id, agentName, askedTo, question, answered, answeredBy, inbox }: { id: string; agentName?: string; askedTo?: string; question: string; answered: boolean; answeredBy?: string; inbox?: boolean }): ReactNode {const team = useStore(teamMode)const you = useStore((s) => s.you)const admin = useStore(amAdmin)@@ -1055,6 +1074,53 @@ export function QuestionCard({ id, agentName, askedTo, question, answered, answe)}++// A question with decisions, with a team: whom it's for and who asked; answered on the card by+// whoever may (the person, whoever covers for them or, past the deadline, the requester: those+// who have it in For you; an admin, after choosing to answer for them); for anyone else, to read.+function TeamAsk({ id, agentName, askedTo, decisions, answers, answeredInText, answered, answeredBy, inbox }: { id: string; agentName?: string; askedTo?: string; decisions: Decision[]; answers?: (Answer | null)[]; answeredInText?: boolean; answered: boolean; answeredBy?: string; inbox?: boolean }): ReactNode {+ const team = useStore(teamMode)+ const you = useStore((s) => s.you)+ const admin = useStore(amAdmin)+ const waiting = useStore((s) => s.inbox.questions.find((q) => q.id === id))+ const target = useStore((s) => personById(s, askedTo ?? waiting?.askedTo))+ const answerer = useStore((s) => (answeredBy && answeredBy !== s.you ? personById(s, answeredBy) : undefined))+ const [answering, setAnswering] = useState(false)+ const who = agentName ?? L('O agente', 'The agent')+ const card = { id, questions: decisions, saved: answers }+ if (!team || !target) return <AskCard {...card} mode={answered ? 'done' : 'answer'} badge={answered ? L('Respondida', 'Answered') : L('Esperando você', 'Waiting for you')} answeredInText={!!answeredInText} />+ const toMe = target.id === you+ const asked = toMe ? L(`${who} pergunta a você`, `${who} asks you`) : L(`${who} pergunta a ${target.name}`, `${who} asks ${target.name}`)+ if (answered)+ return <AskCard {...card} mode="done" badge={answerer ? L(`Respondida por ${answerer.name}`, `Answered by ${answerer.name}`) : L('Respondida', 'Answered')} byline={toMe ? L(`${who} perguntou a você`, `${who} asked you`) : L(`${who} perguntou a ${target.name}`, `${who} asked ${target.name}`)} answeredInText={!!answeredInText} />+ if (waiting?.confirm === 'pending')+ return (+ <AskCard {...card} mode="view" badge={L(`${who} quer perguntar a ${target.name}`, `${who} wants to ask ${target.name}`)}>+ <p className="ask__note">{L(`${target.name} vê só a pergunta, nunca esta conversa.`, `${target.name} sees the question only, never this conversation.`)}</p>+ <div className="ask__foot">+ <button className="btn btn--sm" onClick={() => confirmQuestion(id, false)}>+ {L('Não pergunte', "Don't ask")}+ </button>+ <button className="btn btn--primary btn--sm" onClick={() => confirmQuestion(id, true)}>+ {L(`Pode perguntar a ${target.name}`, `Go ahead and ask ${target.name}`)}+ </button>+ </div>+ </AskCard>+ )+ if (waiting || (admin && answering)) return <AskCard {...card} mode="answer" badge={waiting ? L('Esperando você', 'Waiting for you') : L(`Respondendo no lugar de ${target.name}`, `Answering for ${target.name}`)} byline={asked} />+ return (+ <AskCard {...card} mode="view" badge={L(`Esperando ${target.name}`, `Waiting for ${target.name}`)} byline={asked}>+ {admin && !inbox && (+ <div className="ask__foot">+ <button className="btn btn--sm" onClick={() => setAnswering(true)}>+ {L(`Responder no lugar de ${target.name}`, `Answer for ${target.name}`)}+ </button>+ </div>+ )}+ </AskCard>+ )+}+// What remarkMentions marked: an agent's @handle becomes its chip, which opens its profile. A handle// no agent has stays as it was written, in bold, as any @ always was.function MentionSpan({ node: _, ...props }: ComponentProps<'span'> & ExtraProps): ReactNode {diff --git a/src/renderer/src/components/Decisions.tsx b/src/renderer/src/components/Decisions.tsxnew file mode 100644index 0000000..d66af0e--- /dev/null+++ b/src/renderer/src/components/Decisions.tsx@@ -0,0 +1,390 @@+// The decisions an agent asked with ask_user, as a card under its reply. Whoever may answer+// goes through them one at a time (the agent's options, then "Something else"), checks them and+// sends them as their message; anyone else sees what's asked. Answered, the card keeps what+// was chosen, so the conversation still reads when scrolling back. The message box below stays+// as it is: writing there is a free answer, with what was picked here going along.+import { useEffect, useRef, useState, type KeyboardEvent, type ReactNode } from 'react'+import Markdown from 'react-markdown'+import remarkGfm from 'remark-gfm'+import { L } from '../../../shared/lang'+import { answerLabel, draftAnswer, firstUnanswered, isAnswered, MAX_QUESTION_LENGTH, questionsOf, type Answer, type AnswerDraft, type Decision } from '../../../shared/questions'+import { answerDecision, submitDecisions, type Message } from '../store'+import { Icon } from './ui'+import { decisionKey } from './decision-keys'++type Step = number | 'review'++// Only a message from before the length limit has a question this long: it reads as text, not as a title.+const isLong = (q: Decision): boolean => q.question.length > MAX_QUESTION_LENGTH || q.question.includes('\n')+const Prose = ({ text, className }: { text: string; className: string }): ReactNode => (+ <div className={className}>+ <Markdown remarkPlugins={[remarkGfm]}>{text}</Markdown>+ </div>+)+const Title = ({ q }: { q: Decision }): ReactNode => (isLong(q) ? <Prose className="ask__prose" text={q.question} /> : <div className="ask__title">{q.question}</div>)++// What's ticked or typed but not confirmed, by message and decision, so moving around or+// scrolling away keeps it (like the message box's drafts). In memory: closing the app drops them.+const drafts = new Map<string, AnswerDraft>()+const draftKey = (messageId: string, index: number): string => `${messageId}:${index}`++const inField = (e: KeyboardEvent): boolean => e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement++export type AskMode = 'answer' | 'view' | 'done'++// `answer`: this person may answer it now. `view`: someone else's to answer (or not yet asked).+// `done`: answered. `badge`: the state, as the head says it; `byline`: who asked whom (a team).+// `children`: what goes under it (a hint, buttons).+export function AskCard({+ id,+ questions,+ saved,+ mode,+ badge,+ byline,+ answeredInText,+ children+}: {+ id: string+ questions: Decision[]+ saved?: (Answer | null)[]+ mode: AskMode+ badge: string+ byline?: string+ answeredInText?: boolean+ children?: ReactNode+}): ReactNode {+ if (mode === 'answer') return <Answering id={id} questions={questions} saved={saved} badge={badge} byline={byline} extra={children} />+ return (+ <section className={`ask ask--${mode}`} aria-label={badge}>+ <Head badge={badge} byline={byline} done={mode === 'done'} />+ {mode === 'done' ? <Summary questions={questions} answers={saved} answeredInText={answeredInText} /> : <Asked questions={questions} />}+ {children}+ </section>+ )+}++function Head({ badge, byline, done, nav }: { badge: string; byline?: string | undefined; done?: boolean; nav?: ReactNode }): ReactNode {+ return (+ <div className="ask__head">+ <span className="ask__badge">+ <Icon name={done ? 'check' : 'ask'} size={13} />+ {badge}+ </span>+ {byline && <span className="ask__byline">{byline}</span>}+ {nav}+ </div>+ )+}++// Someone else's question, waiting: each decision with its options, to read.+function Asked({ questions }: { questions: Decision[] }): ReactNode {+ return (+ <ol className="ask-list">+ {questions.map((q, i) => (+ <li key={i} className="ask-list__row">+ {isLong(q) ? <Prose className="ask__prose" text={q.question} /> : <span className="ask-list__q">{q.question}</span>}+ {q.options && (+ <span className="ask-list__options">+ {q.options.map((o, j) => (+ <span key={j} className="ask-chip">+ {o.label}+ </span>+ ))}+ </span>+ )}+ </li>+ ))}+ </ol>+ )+}++// Answered: each decision and what was chosen. Answered in writing: the questions, and a note.+function Summary({ questions, answers, answeredInText }: { questions: Decision[]; answers?: (Answer | null)[] | undefined; answeredInText?: boolean | undefined }): ReactNode {+ const any = !!answers?.some(isAnswered)+ return (+ <>+ <dl className="ask-summary">+ {questions.map((q, i) => {+ const a = answers?.[i]+ return (+ <div key={i} className="ask-summary__row">+ <dt>{isLong(q) ? <Prose className="ask__prose" text={q.question} /> : q.question}</dt>+ <dd className={!a || !isAnswered(a) || a.skipped ? 'is-muted' : ''}>{a && isAnswered(a) ? answerLabel(q, a) : any ? L('respondida em texto', 'answered in text') : L('respondida na mensagem abaixo', 'answered in the message below')}</dd>+ </div>+ )+ })}+ </dl>+ {answeredInText && any && <p className="ask__note">{L('Com uma resposta escrita, logo abaixo.', 'With a written answer, just below.')}</p>}+ </>+ )+}++function Answering({ id, questions, saved, badge, byline, extra }: { id: string; questions: Decision[]; saved?: (Answer | null)[] | undefined; badge: string; byline?: string | undefined; extra?: ReactNode }): ReactNode {+ // Answers given here show at once, before the core echoes them back.+ const [answers, setAnswers] = useState<(Answer | null)[]>(() => questions.map((_, i) => saved?.[i] ?? null))+ useEffect(() => setAnswers(questions.map((_, i) => saved?.[i] ?? null)), [saved])+ const allAnswered = (list: (Answer | null)[]): boolean => firstUnanswered(questions, list) === -1+ const [step, setStep] = useState<Step>(() => {+ const unfinished = questions.findIndex((_, i) => drafts.has(draftKey(id, i))) // back where I was typing+ if (unfinished !== -1) return unfinished+ const first = firstUnanswered(questions, saved)+ return first === -1 ? (questions.length > 1 ? 'review' : 0) : first+ })+ const [sending, setSending] = useState(false)+ // Once used, moving to the next decision keeps the keyboard on the card.+ const [engaged, setEngaged] = useState(false)++ const send = (): void => {+ if (sending) return+ setSending(true)+ void submitDecisions(id).finally(() => setSending(false)) // it failed if the card is still here: it can go again+ }++ const commit = (index: number, answer: Answer | null): void => {+ setEngaged(true)+ drafts.delete(draftKey(id, index))+ const next = answers.map((a, i) => (i === index ? answer : a))+ setAnswers(next)+ answerDecision(id, index, answer)+ if (!answer) return+ if (questions.length === 1) return send()+ const after = questions.findIndex((_, i) => i > index && !isAnswered(next[i]))+ setStep(after !== -1 ? after : allAnswered(next) ? 'review' : firstUnanswered(questions, next))+ }++ // Leaving a decision with the arrows keeps what's on it, as its answer if it is one.+ const settle = (): (Answer | null)[] => {+ if (step === 'review') return answers+ const key = draftKey(id, step)+ const draft = drafts.get(key)+ if (!draft) return answers+ drafts.delete(key)+ const answer = draftAnswer(questions[step]!, draft)+ const next = answers.map((a, i) => (i === step ? answer : a))+ setAnswers(next)+ answerDecision(id, step, answer)+ return next+ }++ const go = (to: Step): void => {+ const settled = settle()+ if (to === 'review' && !allAnswered(settled)) return+ setEngaged(true)+ setStep(to)+ }+ const position = step === 'review' ? questions.length : step+ const canGoNext = step !== 'review' && (step < questions.length - 1 || allAnswered(answers))+ const nav =+ questions.length > 1 ? (+ <div className="ask__nav">+ <button className="icon-btn icon-btn--sm" disabled={position === 0} title={L('Anterior', 'Previous')} aria-label={L('Anterior', 'Previous')} onClick={() => go(position - 1)}>+ <Icon name="back" size={13} />+ </button>+ <span className="ask__count">{step === 'review' ? L('Revisão', 'Review') : L(`${position + 1} de ${questions.length}`, `${position + 1} of ${questions.length}`)}</span>+ <button className="icon-btn icon-btn--sm ask__next" disabled={!canGoNext} title={L('Próxima', 'Next')} aria-label={L('Próxima', 'Next')} onClick={() => go(position + 1 < questions.length ? position + 1 : 'review')}>+ <Icon name="back" size={13} />+ </button>+ </div>+ ) : undefined++ return (+ <section className="ask ask--answer" aria-label={badge}>+ <Head badge={badge} byline={byline} nav={nav} />+ {questions.length > 1 && (+ <div className="ask__progress" aria-hidden>+ {questions.map((_, i) => (+ <span key={i} className={`ask__segment ${isAnswered(answers[i]) ? 'is-done' : ''} ${i === step ? 'is-current' : ''}`} />+ ))}+ </div>+ )}+ {step === 'review' ? (+ <Review takeFocus={engaged} questions={questions} answers={answers} onEdit={(i) => (setEngaged(true), setStep(i))} onSend={send} sending={sending} />+ ) : (+ <DecisionStep key={step} draftId={draftKey(id, step)} question={questions[step]!} answer={answers[step] ?? null} last={questions.length === 1} takeFocus={engaged} onAnswer={(a) => commit(step, a)} />+ )}+ {extra}+ </section>+ )+}++function DecisionStep({ draftId, question, answer, last, takeFocus, onAnswer }: { draftId: string; question: Decision; answer: Answer | null; last: boolean; takeFocus: boolean; onAnswer: (a: Answer) => void }): ReactNode {+ const options = question.options ?? []+ const [draft, setDraft] = useState<AnswerDraft>(() => drafts.get(draftId) ?? { chosen: answer?.chosen ?? [], other: answer?.other ?? '', text: answer?.text ?? '' })+ const { chosen, other, text } = draft+ const edit = (patch: Partial<AnswerDraft>): void => {+ const next = { ...draft, ...patch }+ drafts.set(draftId, next)+ setDraft(next)+ }+ const [focus, setFocus] = useState<number | null>(null)+ // "Something else" opens a field in its row; open from the start when it already has an answer.+ const [writing, setWriting] = useState(() => !!(drafts.get(draftId)?.other ?? answer?.other))+ const otherField = useRef<HTMLInputElement>(null)+ const textField = useRef<HTMLTextAreaElement>(null)+ const body = useRef<HTMLDivElement>(null)+ // Moving on from a decision I just answered keeps the keyboard here; the card never takes it from the message box by itself.+ useEffect(() => {+ if (takeFocus) (textField.current ?? body.current)?.focus({ preventScroll: true })+ }, [])++ const multiple = question.kind === 'multiple'+ const pick = (i: number): void => {+ if (!multiple) return onAnswer({ chosen: [i] })+ edit({ chosen: chosen.includes(i) ? chosen.filter((x) => x !== i) : [...chosen, i] })+ }+ const openOther = (): void => {+ setFocus(options.length) // the field takes the focus as it opens (autoFocus)+ setWriting(true)+ }+ const typed = draftAnswer(question, draft)+ const confirm = (): void => {+ if (typed) onAnswer(typed)+ }+ const skip = (): void => onAnswer({ skipped: true })++ const keys = (e: KeyboardEvent): void => {+ const action = decisionKey(+ { key: e.key, shift: e.shiftKey, modifier: e.metaKey || e.ctrlKey || e.altKey, composing: e.nativeEvent.isComposing, inField: inField(e), onBody: e.target === e.currentTarget },+ focus,+ options.length+ )+ if (!action) return+ e.preventDefault()+ if (action.kind === 'dismiss') {+ // Esc: out of "Something else" (closed when empty), then off the card.+ if (e.target === otherField.current) {+ if (!other.trim()) setWriting(false)+ body.current?.focus()+ } else (e.target as HTMLElement).blur()+ return+ }+ if (action.kind === 'confirm') return confirm()+ if (action.kind === 'pick') return pick(action.index)+ if (action.kind === 'other') return openOther()+ setFocus(action.index)+ if (action.index === options.length && writing) otherField.current?.focus()+ else body.current?.focus()+ }++ const keyHint =+ question.kind === 'text'+ ? L('Enter confirma · Shift+Enter quebra a linha', 'Enter confirms · Shift+Enter for a new line')+ : multiple+ ? L(`Marque quantas quiser com 1 a ${options.length + 1}`, `Tick as many as you like with 1 to ${options.length + 1}`)+ : L(`Escolha com 1 a ${options.length + 1}`, `Pick with 1 to ${options.length + 1}`)++ return (+ <div className="ask__body" ref={body} tabIndex={-1} onKeyDown={keys}>+ <Title q={question} />+ {question.kind === 'text' ? (+ <textarea ref={textField} className="ask__text" rows={2} value={text} placeholder={L('Sua resposta', 'Your answer')} onChange={(e) => edit({ text: e.target.value })} />+ ) : (+ <div className="ask-options" role={multiple ? 'group' : 'radiogroup'} aria-label={question.question}>+ {options.map((o, i) => {+ const on = chosen.includes(i) || (!multiple && !!answer?.chosen?.includes(i))+ return (+ <button key={i} role={multiple ? 'checkbox' : 'radio'} aria-checked={on} className={`ask-option ${on ? 'is-on' : ''} ${focus === i ? 'is-focus' : ''}`} onMouseEnter={() => setFocus(i)} onClick={() => pick(i)}>+ <span className="ask-option__key">{i + 1}</span>+ <span className="ask-option__text">+ <span className="ask-option__label">{o.label}</span>+ {o.description && <span className="ask-option__detail">{o.description}</span>}+ </span>+ <span className={`ask-option__mark ${multiple ? 'is-box' : ''}`} aria-hidden>+ {on && <Icon name="check" size={12} />}+ </span>+ </button>+ )+ })}+ {writing ? (+ <label className={`ask-option ask-option--other is-open ${other.trim() ? 'is-on' : ''}`} onMouseEnter={() => setFocus(options.length)}>+ <span className="ask-option__key">{options.length + 1}</span>+ <input ref={otherField} className="ask-option__input" autoFocus={focus === options.length} value={other} placeholder={L('Escreva sua resposta…', 'Write your answer…')} onChange={(e) => edit({ other: e.target.value })} />+ </label>+ ) : (+ <button className={`ask-option ask-option--other ${focus === options.length ? 'is-focus' : ''}`} onMouseEnter={() => setFocus(options.length)} onClick={openOther}>+ <span className="ask-option__key">{options.length + 1}</span>+ <span className="ask-option__text">+ <span className="ask-option__label">{L('Outra coisa…', 'Something else…')}</span>+ </span>+ <span className="ask-option__mark" aria-hidden>+ <Icon name="edit" size={12} />+ </span>+ </button>+ )}+ </div>+ )}+ <div className="ask__foot">+ <span className="ask__hint">{keyHint}</span>+ <button className="btn btn--ghost btn--sm" onClick={skip}>+ {L('Pular', 'Skip')}+ </button>+ {(question.kind !== 'single' || writing) && (+ <button className="btn btn--primary btn--sm" disabled={!typed} onClick={confirm}>+ {last ? L('Enviar', 'Send') : L('Próxima', 'Next')}+ </button>+ )}+ </div>+ </div>+ )+}++function Review({ takeFocus, questions, answers, onEdit, onSend, sending }: { takeFocus: boolean; questions: Decision[]; answers: (Answer | null)[]; onEdit: (i: number) => void; onSend: () => void; sending: boolean }): ReactNode {+ // Reached from the last decision, Send has the keyboard; on a card that just showed up, nothing does.+ const sendButton = useRef<HTMLButtonElement>(null)+ useEffect(() => {+ if (takeFocus) sendButton.current?.focus({ preventScroll: true })+ }, [])+ return (+ <div className="ask__body">+ <div className="ask__title">{L('Confira antes de enviar', 'Check before sending')}</div>+ <ol className="ask-review">+ {questions.map((q, i) => (+ <li key={i}>+ <button className="ask-review__row" title={L('Mudar esta resposta', 'Change this answer')} onClick={() => onEdit(i)}>+ <span className="ask-review__q">{isLong(q) ? L('Pergunta', 'Question') : q.question}</span>+ <span className={`ask-review__a ${answers[i]?.skipped ? 'is-muted' : ''}`}>{answers[i] ? answerLabel(q, answers[i]) : ''}</span>+ <Icon name="edit" size={12} />+ </button>+ </li>+ ))}+ </ol>+ <div className="ask__foot">+ <span className="ask__hint">{L('Clique numa resposta pra mudar', 'Click an answer to change it')}</span>+ <button ref={sendButton} className="btn btn--primary btn--sm" disabled={sending} onClick={onSend}>+ <Icon name="send" size={12} /> {L('Enviar', 'Send')}+ </button>+ </div>+ </div>+ )+}++// Alone, on the agent's message: my question, to answer here, or what I chose.+export function AnswersSummary({ message }: { message: Message }): ReactNode {+ const questions = questionsOf(message.run)+ if (!questions.length) return null+ const waiting = message.run?.status === 'waiting_input'+ return <AskCard id={message.id} questions={questions} saved={message.run?.answers} mode={waiting ? 'answer' : 'done'} badge={waiting ? L('Esperando você', 'Waiting for you') : L('Respondida', 'Answered')} answeredInText={!!message.run?.answeredInText} />+}++// The message that sent a card's answers says nothing the card doesn't: in the conversation it+// shows only what was written beyond them, or not at all. It stays as it is everywhere else (the+// agent, the wiki, search, Telegram). Found by the link the card keeps, never by the text.+const linked = new WeakMap<Message[], Map<string, string>>()+export function cardAnswers(all: Message[]): Map<string, string> {+ const had = linked.get(all)+ if (had) return had+ const map = new Map<string, string>()+ for (const m of all) if (m.run?.answerMessage) map.set(m.run.answerMessage, m.run.answerTyped ?? '')+ linked.set(all, map)+ return map+}++export function asShown(messages: Message[], answers: Map<string, string>): Message[] {+ if (!answers.size || !messages.some((m) => answers.has(m.id))) return messages+ return messages.flatMap((m) => {+ if (m.author.kind !== 'person' || !answers.has(m.id)) return [m]+ const typed = answers.get(m.id)!+ return typed ? [{ ...m, text: typed }] : []+ })+}diff --git a/src/renderer/src/components/Pages.tsx b/src/renderer/src/components/Pages.tsxindex 2f75987..b342e63 100644--- a/src/renderer/src/components/Pages.tsx+++ b/src/renderer/src/components/Pages.tsx@@ -1174,7 +1174,7 @@ export function InboxPage(): ReactNode {{questions.map(({ q, done }) => (<div key={q.id}>{meta(q.conversationId, q.agentId, q.createdAt)}- <QuestionCard id={q.id} agentName={agents.find((x) => x.id === q.agentId)?.name} askedTo={q.askedTo} question={q.text} answered={done} {...(q.answeredBy ? { answeredBy: q.answeredBy } : {})} inbox />+ <QuestionCard id={q.id} agentName={agents.find((x) => x.id === q.agentId)?.name} askedTo={q.askedTo} question={q.text} {...(q.decisions ? { decisions: q.decisions, ...(q.answers ? { answers: q.answers } : {}) } : {})} answered={done} {...(q.answeredBy ? { answeredBy: q.answeredBy } : {})} inbox /></div>))}</div>diff --git a/src/renderer/src/components/Sidebar.tsx b/src/renderer/src/components/Sidebar.tsxindex f79d39f..3d17c0e 100644--- a/src/renderer/src/components/Sidebar.tsx+++ b/src/renderer/src/components/Sidebar.tsx@@ -1,9 +1,11 @@import { L } from '../../../shared/lang'-import { memo, useCallback, useRef, useState, type HTMLAttributes, type ReactNode } from 'react'+import { isWaiting, mineIn, waitingIn, waitingTitle, type Waiting } from './waiting'+import { memo, useCallback, useId, useRef, useState, type HTMLAttributes, type ReactNode } from 'react'import {agentById,archiveAgent,isWorking,+ messagesIn,openTuca,isTeam,deleteConversation,@@ -27,6 +29,7 @@ import {teamMode,youPerson,type Agent,+ type State,type View} from '../store'import { addGroup, arrange, moveChannel, nudgeChannel, removeGroup, renameGroup, type ChannelLayout } from '../../../shared/channel-layout'@@ -67,7 +70,7 @@ function TucaItem(): ReactNode {)}-function Section({ id, label, unread = 0, action, children }: { id: string; label: string; unread?: number; action?: ReactNode; children: ReactNode }): ReactNode {+function Section({ id, label, unread = 0, waiting, action, children }: { id: string; label: string; unread?: number; waiting?: boolean; action?: ReactNode; children: ReactNode }): ReactNode {const { open, toggle } = useFold(`section:${id}`)return (<div className={`section ${open ? '' : 'is-folded'}`}>@@ -76,6 +79,7 @@ function Section({ id, label, unread = 0, action, children }: { id: string; labe{label}</FoldToggle>{/* A closed section still says when something in it is waiting. */}+ {!open && waiting && <WaitingMark title={L('Um agente está esperando você aqui', 'An agent is waiting for you in here')} />}{!open && unread > 0 && (<span key={unread} className="badge badge--soft">{unread}@@ -89,7 +93,7 @@ function Section({ id, label, unread = 0, action, children }: { id: string; labe}// A group folds like the sections, in the same list (Fold.tsx), and keeps showing the channel you're in.-function GroupFold({ id, label, unread, head, naming, children }: { id: string; label: string; unread: number; head: HTMLAttributes<HTMLDivElement>; naming?: ReactNode; children: ReactNode }): ReactNode {+function GroupFold({ id, label, unread, waiting, head, naming, children }: { id: string; label: string; unread: number; waiting?: boolean; head: HTMLAttributes<HTMLDivElement>; naming?: ReactNode; children: ReactNode }): ReactNode {const { open, toggle } = useFold(`group:${id}`)return (<div className={`channel-group ${open ? '' : 'is-folded'}`}>@@ -98,6 +102,7 @@ function GroupFold({ id, label, unread, head, naming, children }: { id: string;<FoldToggle open={open} onToggle={toggle}>{label}</FoldToggle>+ {!open && waiting && <WaitingMark title={L('Um agente está esperando você aqui', 'An agent is waiting for you in here')} />}{!open && unread > 0 && <span className="badge badge--soft">{unread}</span>}</div>)}@@ -108,6 +113,31 @@ function GroupFold({ id, label, unread, head, naming, children }: { id: string;const unreadIn = (conversations: { unread?: number }[]): number => conversations.reduce((sum, c) => sum + (c.unread ?? 0), 0)+// An agent waits on me there (a question, an approval): it shows instead of the working dot, since it's my turn.+// A solid speech bubble with the "?" cut out of it, so it reads on any row (hovered, active).+function WaitingMark({ title }: { title: string }): ReactNode {+ const mask = `waiting-${useId().replace(/[^a-zA-Z0-9]/g, '')}`+ return (+ <span className="waiting-mark" title={title} aria-label={title}>+ <svg width="16" height="16" viewBox="0 0 24 24" aria-hidden>+ <mask id={mask}>+ <rect width="24" height="24" fill="white" />+ <path d="M9.6 9.2a2.5 2.5 0 0 1 4.8.9c0 1.7-2.4 2.1-2.4 3.7" fill="none" stroke="black" strokeWidth="2.1" strokeLinecap="round" />+ <circle cx="12" cy="16.3" r="1.2" fill="black" />+ </mask>+ <path mask={`url(#${mask})`} fill="currentColor" d="M12 2.5c5.5 0 9.5 3.9 9.5 8.8s-4 8.8-9.5 8.8c-1.2 0-2.4-.2-3.5-.5L3.5 21.5l1.4-4.3C3.4 15.7 2.5 13.6 2.5 11.3 2.5 6.4 6.5 2.5 12 2.5Z" />+ </svg>+ </span>+ )+}++// Who waits on me in a conversation, as the hint says it: a string, so the sidebar redraws only when it changes.+// With a team, only what waits on me (my inbox), not a question to someone else or an approval for them.+const waitsIn = (s: State, conversationId: string): Waiting => waitingIn(messagesIn(s, conversationId), conversationId, teamMode(s) ? { key: s.inbox, test: mineIn(s.inbox) } : undefined)+const anyWaiting = (s: State, ids: string[]): boolean => ids.some((id) => isWaiting(waitsIn(s, id)))+const useWaitingTitle = (conversationId: string): string =>+ useStore((s) => waitingTitle(waitsIn(s, conversationId), (agentId) => agentById(s, agentId)?.name ?? L('Um agente', 'An agent')))+export function Sidebar(): ReactNode {// Only what it draws: the whole state changes with every step an agent takes.const conversations = useStore((s) => s.conversations)@@ -136,6 +166,10 @@ export function Sidebar(): ReactNode {// The order and groups are the person's: the core only keeps them.const layout = settings.channelLayoutconst arranged = arrange(channels, layout)+ // Folded, a section or group still says an agent waits on me in it: values, so only a change redraws.+ const channelsWaiting = useStore((s) => anyWaiting(s, channels.map((c) => c.id)))+ const waitingGroups = useStore((s) => arranged.groups.filter((g) => anyWaiting(s, g.channels.map((c) => c.id))).map((g) => g.id).join(' ')).split(' ')+ const dmsWaiting = useStore((s) => anyWaiting(s, dms.map((c) => c.id)))const whole: ChannelLayout = { loose: arranged.loose.map((c) => c.id), groups: arranged.groups.map((g) => ({ ...g, channels: g.channels.map((c) => c.id) })) }const saveLayout = (next: ChannelLayout): void => updateSettings({ channelLayout: next })const [naming, setNaming] = useState<string | null>(null)@@ -308,6 +342,7 @@ export function Sidebar(): ReactNode {id="channels"label={L('Canais', 'Channels')}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} />@@ -323,6 +358,7 @@ export function Sidebar(): ReactNode {id={g.id}label={g.name}unread={g.channels.reduce((n, c) => n + (c.unread ?? 0), 0)}+ waiting={waitingGroups.includes(g.id)}head={{...dropOn({ group: g.id }),onContextMenu: (e) =>@@ -357,7 +393,7 @@ export function Sidebar(): ReactNode {</Section>{dms.length > 0 && (- <Section id="dms" label={team ? L('Suas mensagens diretas', 'Your direct messages') : L('Mensagens diretas', 'Direct messages')} unread={unreadIn(dms)}>+ <Section id="dms" label={team ? L('Suas mensagens diretas', 'Your direct messages') : L('Mensagens diretas', 'Direct messages')} unread={unreadIn(dms)} waiting={dmsWaiting}>{dms.map((c) => {const agent = agentOf(c.name)if (!agent) return null@@ -414,11 +450,12 @@ export function Sidebar(): ReactNode {const ChannelItem = memo(function ChannelItem({ id, name, unread }: { id: string; name: string; unread?: number }): ReactNode {const active = useStore((s) => s.view?.kind === 'conversation' && s.view.id === id)const working = useStore((s) => isWorking(s, id))+ const waiting = useWaitingTitle(id)return (<button className={`nav-item ${active ? 'is-active' : ''} ${unread ? 'is-unread' : ''}`} onClick={() => navigate({ kind: 'conversation', id })}><Icon name="hash" /><span className="nav-item__label">{name}</span>- <LiveDot working={working} />+ {waiting ? <WaitingMark title={waiting} /> : <LiveDot working={working} />}{unread ? <span key={unread} className="badge badge--soft">{unread}</span> : null}</button>)@@ -435,11 +472,12 @@ const DmItem = memo(function DmItem({ id, agent, unread }: { id: string; agent:const name = agent.nameconst active = useStore((s) => s.view?.kind === 'conversation' && s.view.id === id)const working = useStore((s) => isWorking(s, id))+ const waiting = useWaitingTitle(id)return (<button className={`nav-item ${active ? 'is-active' : ''} ${unread ? 'is-unread' : ''}`} onClick={() => navigate({ kind: 'conversation', id })}><AgentAvatar agent={agent} size={18} busy={working} /><span className="nav-item__label">{name}</span>- <LiveDot working={working} />+ {waiting ? <WaitingMark title={waiting} /> : <LiveDot working={working} />}{unread ? <span key={unread} className="badge badge--soft">{unread}</span> : null}</button>)diff --git a/src/renderer/src/components/decision-keys.ts b/src/renderer/src/components/decision-keys.tsnew file mode 100644index 0000000..da1ac56--- /dev/null+++ b/src/renderer/src/components/decision-keys.ts@@ -0,0 +1,32 @@+// What a key does on a decision's card. `focus` is the option pointed at (by an arrow or the+// mouse), `optionCount` is the options before "Something else", which sits at that index.+export interface DecisionKeyPress {+ key: string+ shift: boolean+ modifier: boolean // ⌘, Ctrl or Alt: a shortcut of the app, never an answer+ composing: boolean // an IME is still composing the text+ inField: boolean // typing in the text answer or in "Something else"+ onBody: boolean // the card itself has the focus, not one of its buttons+}++export type DecisionKeyAction = { kind: 'pick'; index: number } | { kind: 'focus'; index: number } | { kind: 'other' } | { kind: 'confirm' } | { kind: 'dismiss' } | null++export function decisionKey(press: DecisionKeyPress, focus: number | null, optionCount: number): DecisionKeyAction {+ if (press.modifier) return null+ if (press.key === 'Escape') return { kind: 'dismiss' }+ const stops = optionCount + 1+ const move = (by: 1 | -1): DecisionKeyAction => ({ kind: 'focus', index: focus === null ? (by === 1 ? 0 : optionCount) : (focus + by + stops) % stops })+ if (press.inField) {+ if (press.key === 'Enter' && !press.shift && !press.composing) return { kind: 'confirm' }+ if (optionCount > 0 && press.key === 'ArrowUp') return move(-1)+ if (optionCount > 0 && press.key === 'ArrowDown') return move(1)+ return null+ }+ const n = Number(press.key)+ if (Number.isInteger(n) && n >= 1 && n <= optionCount) return { kind: 'pick', index: n - 1 }+ if (optionCount > 0 && n === optionCount + 1) return { kind: 'other' }+ if (press.key === 'ArrowDown') return move(1)+ if (press.key === 'ArrowUp') return move(-1)+ if (press.key === 'Enter' && press.onBody && focus !== null) return focus === optionCount ? { kind: 'other' } : { kind: 'pick', index: focus }+ return null+}diff --git a/src/renderer/src/components/ui.tsx b/src/renderer/src/components/ui.tsxindex df48760..609d993 100644--- a/src/renderer/src/components/ui.tsx+++ b/src/renderer/src/components/ui.tsx@@ -120,7 +120,8 @@ const PATHS: Record<string, ReactNode> = {volume: <path d="M4 9v6h4l5 4V5L8 9H4ZM16.5 8.5a5 5 0 0 1 0 7M19 6a8.5 8.5 0 0 1 0 12" />,trash: <path d="M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13M10 11v6M14 11v6" />,archive: <path d="M3 4h18v4H3V4ZM5 8v11a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8M10 12h4" />,- thread: <path d="M4 5h16v11H10l-4 4v-4H4V5ZM8 9h8M8 12h5" />+ thread: <path d="M4 5h16v11H10l-4 4v-4H4V5ZM8 9h8M8 12h5" />,+ ask: <path d="M4 5h16v11H10l-4 4v-4H4V5ZM10 8.6a2 2 0 0 1 3.9.6c0 1.4-1.9 1.7-1.9 3M12 14.2h.01" />}export type IconName = keyof typeof PATHSdiff --git a/src/renderer/src/components/waiting.ts b/src/renderer/src/components/waiting.tsnew file mode 100644index 0000000..8a4ce3c--- /dev/null+++ b/src/renderer/src/components/waiting.ts@@ -0,0 +1,47 @@+// What a conversation is waiting on me for: agents that asked something, and agents that ask+// for approval. The sidebar marks the conversation, and says who, until I answer.+import { L } from '../../../shared/lang'+import type { Inbox, Message } from '../../../shared/types'++export interface Waiting {+ asked: string[] // agent ids, each once+ approval: string[]+}++// With a team, only what waits on me: a question in my inbox (to me, to someone I cover for, past+// its deadline for me, or waiting on my yes), an approval I can decide. Alone, everything does.+export const mineIn =+ (inbox: Inbox) =>+ (m: Message): boolean =>+ m.run?.status === 'waiting_input' ? inbox.questions.some((q) => q.id === m.id) : inbox.approvals.some((a) => a.id === m.run?.approvalId)++// Every row of the sidebar asks on every change, and a reply streaming changes the messages at each+// word: a conversation's are read once per change (of them, or of what's mine).+const read = new WeakMap<Message[], { conversationId: string; mine: unknown; waiting: Waiting }>()++export function waitingIn(messages: Message[], conversationId: string, mine?: { key: unknown; test: (m: Message) => boolean }): Waiting {+ const had = read.get(messages)+ if (had && had.conversationId === conversationId && had.mine === mine?.key) return had.waiting+ const waiting: Waiting = { asked: [], approval: [] }+ for (const m of messages) {+ if (m.conversationId !== conversationId || m.author.kind !== 'agent' || (m.run?.status !== 'waiting_input' && m.run?.status !== 'waiting_approval')) continue+ if (mine && !mine.test(m)) continue+ const who = m.run.status === 'waiting_input' ? waiting.asked : waiting.approval+ if (!who.includes(m.author.id)) who.push(m.author.id)+ }+ read.set(messages, { conversationId, mine: mine?.key, waiting })+ return waiting+}++export const isWaiting = (waiting: Waiting): boolean => waiting.asked.length > 0 || waiting.approval.length > 0++export function waitingTitle(waiting: Waiting, nameOf: (agentId: string) => string): string {+ const names = (ids: string[]): string => {+ const all = ids.map(nameOf)+ return all.length > 1 ? `${all.slice(0, -1).join(', ')} ${L('e', 'and')} ${all.at(-1)}` : (all[0] ?? '')+ }+ const parts: string[] = []+ if (waiting.asked.length) parts.push(waiting.asked.length > 1 ? L(`${names(waiting.asked)} te perguntaram algo`, `${names(waiting.asked)} asked you something`) : L(`${names(waiting.asked)} te perguntou algo`, `${names(waiting.asked)} asked you something`))+ if (waiting.approval.length) parts.push(waiting.approval.length > 1 ? L(`${names(waiting.approval)} pedem aprovação`, `${names(waiting.approval)} ask for approval`) : L(`${names(waiting.approval)} pede aprovação`, `${names(waiting.approval)} asks for approval`))+ return parts.join(' · ')+}diff --git a/src/renderer/src/store.ts b/src/renderer/src/store.tsindex 31a2da2..02bc1c7 100644--- a/src/renderer/src/store.ts+++ b/src/renderer/src/store.ts@@ -2,6 +2,7 @@// is kept in sync by its events; actions go to the core over RPC.import { useCallback, useRef, useSyncExternalStore } from 'react'import { L, setLang } from '../../shared/lang'+import type { Answer } from '../../shared/questions'import type { CoreEvent, Method, Params } from '../../shared/rpc'import type { AppProvider } from '../../shared/connector-catalog'import {@@ -853,6 +854,10 @@ export const sendMessage = (conversationId: string, text: string, images: ImageUif (text.trim() || images.length) void fire(L('Não consegui enviar a mensagem.', "I couldn't send the message."), 'sendMessage', { conversationId, text, ...(images.length ? { images } : {}), ...(threadId ? { threadId } : {}) })}+export const answerDecision = (messageId: string, index: number, answer: Answer | null): void =>+ void fire(L('Não consegui guardar a resposta.', "I couldn't save the answer."), 'answerDecision', { messageId, index, answer })+export const submitDecisions = (messageId: string): Promise<void> => fire(L('Não consegui enviar as respostas.', "I couldn't send the answers."), 'submitDecisions', { messageId })+// The person is writing: the core gets what will answer ready. Once in a while per place, and// nobody needs to hear if it didn't work. `opened`: they only opened it (the agent's kept session// starts again, while they read; the router waits for them to type).diff --git a/src/renderer/src/styles.css b/src/renderer/src/styles.cssindex d16cd24..999148a 100644--- a/src/renderer/src/styles.css+++ b/src/renderer/src/styles.css@@ -614,6 +614,23 @@ h3 {background: var(--ok);animation: fade var(--dur-enter) var(--ease-in) 1.2s reverse forwards;}+/* An agent waits on me in that conversation: it arrives with a short pop, then stays still. */+.waiting-mark {+ flex: none;+ display: grid;+ place-items: center;+ color: var(--accent);+ animation: rise var(--dur-enter) var(--ease-spring) backwards;+}+.section__head .waiting-mark,+.channel-group__head .waiting-mark {+ margin-left: auto;+}+@media (prefers-reduced-motion: reduce) {+ .waiting-mark {+ animation: none;+ }+}.inline-form {display: flex;align-items: center;@@ -1550,12 +1567,14 @@ h3 {}/* A request (or a question) arriving: it rises in, rings twice to be seen, and goes quiet. */.approval--pending,-.question:not(.is-answered) {+.question:not(.is-answered),+.ask--answer {--rise: 6px;animation: rise 280ms var(--ease-out) backwards;}.approval--pending::after,-.question:not(.is-answered)::after {+.question:not(.is-answered)::after,+.ask--answer::after {content: '';position: absolute;inset: -1px;@@ -2314,6 +2333,395 @@ h3 {.question.is-answered .question__label {color: var(--text-3);}+/* The decisions an agent asked (ask_user), as a card under its reply: the approval card's+ build (a left accent, a badge with an icon, buttons at the foot) in the orange of what's+ asked of you. One decision at a time, its options as rows to pick (number, label, tick), then+ "Something else"; answered, the card keeps what was chosen. */+.ask {+ position: relative;+ --ring: var(--accent-soft);+ margin: 10px 0 4px;+ max-width: 560px;+ border: 1px solid var(--border-strong);+ border-left: 3px solid var(--accent);+ border-radius: var(--radius-lg);+ padding: 12px 14px;+ background: var(--panel);+ box-shadow: var(--shadow);+ transition: border-left-color var(--dur-base) var(--ease-out), box-shadow var(--dur-base) var(--ease-out);+}+.ask--answer::after {+ inset: -1px -1px -1px -3px;+}+.ask--view {+ box-shadow: none;+ border-left-color: color-mix(in srgb, var(--accent) 45%, var(--border-strong));+}+.ask--done {+ box-shadow: none;+ border-color: var(--border);+ border-left-color: var(--border-strong);+}+.ask__head {+ display: flex;+ align-items: center;+ flex-wrap: wrap;+ gap: 4px 8px;+ min-height: 24px;+ margin-bottom: 8px;+}+.ask__badge {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ font-size: 11.5px;+ font-weight: 600;+ color: var(--accent);+}+.ask--done .ask__badge {+ color: var(--text-3);+}+.ask__byline {+ font-size: 12px;+ color: var(--text-3);+}+.ask__byline::before {+ content: '·';+ margin-right: 8px;+}+.ask__nav {+ margin-left: auto;+ display: inline-flex;+ align-items: center;+ gap: 2px;+}+.ask__next .icon {+ transform: scaleX(-1);+}+.ask__count {+ min-width: 44px;+ text-align: center;+ font-size: 12px;+ color: var(--text-3);+ font-variant-numeric: tabular-nums;+}+.ask__progress {+ display: flex;+ gap: 4px;+ margin: -2px 0 10px;+}+.ask__segment {+ flex: 1;+ height: 3px;+ border-radius: 2px;+ background: var(--border);+ transition: background-color var(--dur-base) var(--ease-out);+}+.ask__segment.is-done {+ background: color-mix(in srgb, var(--accent) 55%, var(--border));+}+.ask__segment.is-current {+ background: var(--accent);+}+.ask__body {+ outline: none;+}+.ask__title {+ font-weight: 600;+ font-size: 14.5px;+ line-height: 1.4;+ margin-bottom: 10px;+ overflow-wrap: anywhere;+}+.ask__prose {+ max-height: 220px;+ overflow-y: auto;+ margin-bottom: 10px;+ padding-right: 6px;+ font-size: 13.5px;+ line-height: 1.55;+ color: var(--text-2);+ overflow-wrap: anywhere;+}+.ask-summary .ask__prose,+.ask-list .ask__prose {+ max-height: none;+ margin: 0;+}+.ask__prose > :first-child {+ margin-top: 0;+}+.ask__prose > :last-child {+ margin-bottom: 0;+}+.ask__prose code {+ font: 0.92em var(--mono);+ background: var(--code-bg);+ padding: 1px 4px;+ border-radius: 4px;+}+/* An option: a row to pick, with its number (the key), its label and a tick when chosen. */+.ask-options {+ display: flex;+ flex-direction: column;+ gap: 4px;+}+.ask-option {+ display: flex;+ align-items: center;+ gap: 10px;+ width: 100%;+ min-height: 38px;+ padding: 7px 10px;+ border: 1px solid var(--border);+ border-radius: var(--radius);+ background: var(--panel);+ color: var(--text);+ font: inherit;+ text-align: left;+ cursor: pointer;+ transition: var(--transition-ui);+}+.ask-option:hover,+.ask-option.is-focus {+ background: var(--hover);+ border-color: var(--border-strong);+}+.ask-option:focus-visible,+.ask-option:focus-within {+ outline: none;+ border-color: var(--accent);+ box-shadow: 0 0 0 3px var(--accent-soft);+}+.ask-option.is-on {+ border-color: var(--accent);+ background: var(--accent-soft);+}+.ask-option__key {+ flex: none;+ width: 22px;+ height: 22px;+ border-radius: 6px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ border: 1px solid var(--border-strong);+ background: var(--bg);+ font-size: 11.5px;+ font-weight: 600;+ color: var(--text-2);+ font-variant-numeric: tabular-nums;+ transition: var(--transition-ui);+}+.ask-option.is-on .ask-option__key {+ background: var(--accent);+ border-color: var(--accent);+ color: var(--accent-text);+}+.ask-option__text {+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+ gap: 1px;+}+.ask-option__label {+ font-size: 13.5px;+ font-weight: 500;+ overflow-wrap: anywhere;+}+.ask-option__detail {+ font-size: 12px;+ color: var(--text-3);+ overflow-wrap: anywhere;+}+.ask-option__mark {+ flex: none;+ width: 16px;+ height: 16px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ color: var(--accent);+}+.ask-option__mark.is-box {+ border: 1px solid var(--border-strong);+ border-radius: 4px;+}+.ask-option.is-on .ask-option__mark.is-box {+ border-color: var(--accent);+ background: var(--accent);+ color: var(--accent-text);+}+.ask-option--other .ask-option__label {+ font-weight: 400;+ color: var(--text-2);+}+.ask-option--other .ask-option__mark {+ color: var(--text-3);+}+.ask-option--other.is-open {+ cursor: text;+}+.ask-option .ask-option__input,+.ask-option .ask-option__input:focus {+ flex: 1;+ min-width: 0;+ width: auto;+ height: auto;+ border: 0;+ border-radius: 0;+ outline: none;+ box-shadow: none;+ background: transparent;+ padding: 0;+ font: inherit;+ font-size: 13.5px;+ color: var(--text);+}+.ask__text {+ width: 100%;+ resize: vertical;+ min-height: 60px;+}+.ask__foot {+ display: flex;+ align-items: center;+ justify-content: flex-end;+ flex-wrap: wrap;+ gap: 8px;+ margin-top: 10px;+}+.ask__hint {+ margin-right: auto;+ font-size: 11.5px;+ color: var(--text-3);+}+.ask__note {+ margin: 8px 0 0;+ font-size: 12px;+ color: var(--text-3);+}+/* Before sending: each decision and its answer, a click away from changing it. */+.ask-review {+ list-style: none;+ margin: 0;+ padding: 0;+ border: 1px solid var(--border);+ border-radius: var(--radius);+ overflow: hidden;+}+.ask-review li + li {+ border-top: 1px solid var(--border);+}+.ask-review__row {+ display: grid;+ grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto;+ align-items: center;+ gap: 10px;+ width: 100%;+ padding: 8px 10px;+ border: 0;+ background: transparent;+ font: inherit;+ text-align: left;+ color: var(--text);+ cursor: pointer;+ transition: var(--transition-ui);+}+.ask-review__row:hover {+ background: var(--hover);+}+.ask-review__row:focus-visible {+ outline: none;+ box-shadow: inset 0 0 0 2px var(--accent-soft);+}+.ask-review__row .icon {+ color: var(--text-3);+}+.ask-review__q {+ font-size: 12.5px;+ color: var(--text-2);+ overflow-wrap: anywhere;+}+.ask-review__a {+ font-size: 13.5px;+ font-weight: 500;+ overflow-wrap: anywhere;+}+.ask .is-muted {+ color: var(--text-3);+ font-weight: 400;+ font-style: italic;+}+/* To read: someone else's question, with its options. */+.ask-list {+ margin: 0;+ padding-left: 18px;+ display: flex;+ flex-direction: column;+ gap: 8px;+ font-size: 13.5px;+}+.ask-list__q {+ font-weight: 500;+}+.ask-list__options {+ display: flex;+ flex-wrap: wrap;+ gap: 4px;+ margin-top: 4px;+}+.ask-chip {+ padding: 1px 8px;+ border: 1px solid var(--border);+ border-radius: 999px;+ font-size: 12px;+ color: var(--text-2);+ background: var(--bg);+}+/* Answered: each decision over what was chosen. */+.ask-summary {+ margin: 0;+ display: flex;+ flex-direction: column;+ gap: 8px;+}+.ask-summary__row {+ display: grid;+ gap: 1px;+ padding-left: 10px;+ border-left: 2px solid var(--border);+}+.ask-summary dt {+ font-size: 12px;+ color: var(--text-3);+}+.ask-summary dd {+ margin: 0;+ font-size: 13.5px;+ font-weight: 500;+ color: var(--text);+ overflow-wrap: anywhere;+}+@media (max-width: 640px) {+ .ask {+ padding: 10px 12px;+ }+ .ask-review__row {+ grid-template-columns: minmax(0, 1fr) auto;+ }+ .ask-review__a {+ grid-column: 1;+ }+ .ask-review__row .icon {+ grid-row: 1 / span 2;+ grid-column: 2;+ }+ .ask__hint {+ display: none;+ }+}.retry {margin-top: 6px;}diff --git a/src/shared/questions.ts b/src/shared/questions.tsnew file mode 100644index 0000000..c05d126--- /dev/null+++ b/src/shared/questions.ts@@ -0,0 +1,157 @@+// What an agent asks with ask_user: one to four decisions, each a single choice, a multiple+// choice or a free text. The answers are kept on the asking message, one per decision, and+// go to the agent as my next message, one line each.+import { L } from './lang'+import type { Message, Run } from './types'++export type DecisionKind = 'single' | 'multiple' | 'text'+export interface DecisionOption {+ label: string+ description?: string+}+export interface Decision {+ question: string+ kind: DecisionKind+ options?: DecisionOption[]+}+export interface Answer {+ chosen?: number[] // indexes into the options+ other?: string // "Something else", in a single or multiple choice+ text?: string // the answer to a text decision+ skipped?: true+}+// What's on a decision's card before it's confirmed.+export interface AnswerDraft {+ chosen: number[]+ other: string+ text: string+}++export const MAX_QUESTIONS = 4+export const MIN_OPTIONS = 1+// The card always adds "Something else" (a free answer) after the agent's options: 4 rows at most.+export const MAX_OPTIONS = 3+// A decision is read at a glance: the context goes in the reply's text, not here.+export const MAX_QUESTION_LENGTH = 200+export const MAX_LABEL_LENGTH = 80+export const MAX_DESCRIPTION_LENGTH = 200++const KINDS: DecisionKind[] = ['single', 'multiple', 'text']++// Messages saved before decisions existed have a question string: it reads as one text decision.+export function questionsOf(run: Run | undefined): Decision[] {+ if (run?.questions?.length) return run.questions+ return run?.question ? [{ question: run.question, kind: 'text' }] : []+}++// A question that was just asked. Answering part of it saves the message again, which asks nothing new.+export function isNewQuestion(message: Message): boolean {+ return message.run?.status === 'waiting_input' && !message.run.answers && questionsOf(message.run).length > 0+}++const trimmed = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')+const tooLong = (question: string): string =>+ L(+ `Pergunta longa demais (${question.length} caracteres, o máximo é ${MAX_QUESTION_LENGTH}): coloque o contexto e a proposta no texto da sua resposta e deixe aqui só a decisão.`,+ `Question too long (${question.length} characters, at most ${MAX_QUESTION_LENGTH}): put the context and the proposal in your reply's text and leave only the decision here.`+ )++export function parseQuestions(args: Record<string, unknown>): { questions: Decision[] } | { error: string } {+ if (args['questions'] === undefined && typeof args['question'] === 'string') {+ const question = trimmed(args['question'])+ if (!question) return { error: L('Faltou a pergunta.', 'Missing the question.') }+ return question.length > MAX_QUESTION_LENGTH ? { error: tooLong(question) } : { questions: [{ question, kind: 'text' }] }+ }+ const list = args['questions']+ if (!Array.isArray(list) || list.length === 0) return { error: L('Faltou a pergunta: mande ao menos uma decisão em questions.', 'Missing the question: send at least one decision in questions.') }+ if (list.length > MAX_QUESTIONS) return { error: L(`No máximo ${MAX_QUESTIONS} decisões por pergunta: divida em mais de uma.`, `At most ${MAX_QUESTIONS} decisions per question: split them up.`) }+ const questions: Decision[] = []+ for (const item of list as Record<string, unknown>[]) {+ const question = trimmed(item?.['question'])+ if (!question) return { error: L('Toda decisão precisa de uma pergunta.', 'Every decision needs a question.') }+ if (question.length > MAX_QUESTION_LENGTH) return { error: tooLong(question) }+ const kind = item['kind'] as DecisionKind+ if (!KINDS.includes(kind)) return { error: L(`"${question}": kind tem que ser single, multiple ou text.`, `"${question}": kind must be single, multiple or text.`) }+ if (kind === 'text') {+ questions.push({ question, kind })+ continue+ }+ // Past the limit, the first ones are kept: "Something else" covers the rest.+ const raw = (Array.isArray(item['options']) ? (item['options'] as Record<string, unknown>[]) : []).slice(0, MAX_OPTIONS)+ if (raw.length < MIN_OPTIONS) return { error: L(`"${question}": de ${MIN_OPTIONS} a ${MAX_OPTIONS} opções.`, `"${question}": ${MIN_OPTIONS} to ${MAX_OPTIONS} options.`) }+ const options: DecisionOption[] = []+ for (const o of raw) {+ const label = trimmed(o?.['label'])+ if (!label) return { error: L(`"${question}": toda opção precisa de um label.`, `"${question}": every option needs a label.`) }+ const description = trimmed(o['description'])+ if (label.length > MAX_LABEL_LENGTH || description.length > MAX_DESCRIPTION_LENGTH)+ return {+ error: L(+ `"${question}": label de até ${MAX_LABEL_LENGTH} caracteres e description de até ${MAX_DESCRIPTION_LENGTH}; o detalhe vai no texto da sua resposta.`,+ `"${question}": label up to ${MAX_LABEL_LENGTH} characters and description up to ${MAX_DESCRIPTION_LENGTH}; the detail goes in your reply's text.`+ )+ }+ options.push(description ? { label, description } : { label })+ }+ questions.push({ question, kind, options })+ }+ return { questions }+}++export function isAnswered(answer: Answer | null | undefined): boolean {+ return !!answer && (!!answer.chosen?.length || !!answer.other || !!answer.text || !!answer.skipped)+}++export function draftAnswer(question: Decision, draft: AnswerDraft): Answer | null {+ if (question.kind === 'text') return draft.text.trim() ? { text: draft.text.trim() } : null+ const other = draft.other.trim()+ if (question.kind === 'single') return other ? { other } : draft.chosen.length ? { chosen: draft.chosen } : null+ if (!draft.chosen.length && !other) return null+ return { ...(draft.chosen.length ? { chosen: [...draft.chosen].sort((a, b) => a - b) } : {}), ...(other ? { other } : {}) }+}++export function firstUnanswered(questions: Decision[], answers: (Answer | null)[] | undefined): number {+ return questions.findIndex((_, i) => !isAnswered(answers?.[i]))+}++export function answerLabel(question: Decision, answer: Answer): string {+ if (answer.skipped) return L('(pulou)', '(skipped)')+ if (question.kind === 'text') return answer.text ?? ''+ const chosen = [...(answer.chosen ?? [])].sort((a, b) => a - b).map((i) => question.options?.[i]?.label).filter(Boolean)+ if (answer.other) chosen.push(`${L('Outra coisa', 'Something else')}: ${answer.other}`)+ return chosen.join(', ')+}++// A Markdown list: one line each, in my message bubble as well as for the agent.+export function formatAnswers(questions: Decision[], answers: (Answer | null)[] | undefined): string {+ // One text question reads as a reply, as it did before decisions: the agent knows what it asked.+ const lone = questions.length === 1 && questions[0]!.kind === 'text' ? answers?.[0] : undefined+ if (lone && isAnswered(lone)) return answerLabel(questions[0]!, lone)+ return questions+ .map((q, i) => {+ const answer = answers?.[i]+ return answer && isAnswered(answer) ? `- ${q.question} → ${answerLabel(q, answer)}` : ''+ })+ .filter(Boolean)+ .join('\n')+}++export function questionHeadline(questions: Decision[]): string {+ const first = questions[0]?.question ?? ''+ return questions.length > 1 ? `${first} (+${questions.length - 1})` : first+}++// For the agent's context: a lone text question reads exactly as a question did before.+export function describeQuestions(questions: Decision[]): string {+ return numberedQuestions(questions, '; ')+}++// For a text-only place (the phone): the question alone, or one numbered line per decision.+export function questionsAsText(questions: Decision[]): string {+ return numberedQuestions(questions, '\n')+}++function numberedQuestions(questions: Decision[], separator: string): string {+ if (questions.length === 1 && !questions[0]!.options) return questions[0]!.question+ return questions.map((q, i) => `${i + 1}. ${q.question}${q.options ? ` (${q.options.map((o) => o.label).join(' | ')})` : ''}`).join(separator)+}diff --git a/src/shared/rpc-shapes.ts b/src/shared/rpc-shapes.tsindex efa12be..be994fb 100644--- a/src/shared/rpc-shapes.ts+++ b/src/shared/rpc-shapes.ts@@ -152,6 +152,8 @@ export const SHAPES: Record<Method, Record<string, string>> = {inbox: {},answerQuestion: { id: 's', text: 's' },confirmQuestion: { id: 's', ok: 'b' },+ answerDecision: { messageId: 's', index: 'n', answer: 'o|null' },+ submitDecisions: { messageId: 's' },watchRoutine: { id: 's', on: 'b' },}diff --git a/src/shared/rpc.ts b/src/shared/rpc.tsindex 5f69a3c..4b92929 100644--- a/src/shared/rpc.ts+++ b/src/shared/rpc.ts@@ -1,4 +1,5 @@// The contract between the renderer and the core, carried over a MessagePort.+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, 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'@@ -179,6 +180,8 @@ export interface Api {inbox(): InboxanswerQuestion(p: { id: string; text: string }): void // a question an agent asked me (or someone I cover for)confirmQuestion(p: { id: string; ok: boolean }): void // in my DM: may the agent ask that person?+ answerDecision(p: { messageId: string; index: number; answer: Answer | null }): void // one of a question's decisions answered on the card (null clears it), kept until sent+ submitDecisions(p: { messageId: string }): void // sends the decisions answered on the card, as my messagewatchRoutine(p: { id: string; on: boolean }): void // "me avise": told of a channel routine's runs}diff --git a/src/shared/types.ts b/src/shared/types.tsindex 536c831..a136f33 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -1,6 +1,7 @@// Domain types shared by the core (utility process) and the renderer.import type { AvatarDefinition } from 'open-bot-avatar'import type { ChannelLayout } from './channel-layout'+import type { Answer, Decision } from './questions'import { L, lang, type Lang } from './lang'export type AgentColor = 'sky' | 'indigo' | 'violet' | 'rose' | 'amber' | 'green' | 'teal' | 'graphite'@@ -171,7 +172,12 @@ export interface Run {depth?: number // 1 when a human message triggered it, +1 for each agent-to-agent hopreplyTo?: string // the message (a person's) it answers, when one didansweredBy?: string // who answered its question (another person than the one asked, maybe)- question?: string // asked with ask_user; answered by the next human message here+ question?: string // asked with ask_user, as plain text (every decision, numbered); answered by the next human message here+ questions?: Decision[] // the same decisions, structured (one to four, with options): read them with questionsOf+ answers?: (Answer | null)[] // what was answered on the card so far, by decision, before sending+ answeredInText?: true // the reply had text of its own, beyond the decisions answered+ answerMessage?: string // the message that sent the decisions answered on the card (the agent reads it; the card shows it)+ answerTyped?: string // what that message had beyond them, written in the message boxaskedTo?: string // the person the question is for (unset with one person: whoever asked the agent)memoryIds?: string[] // memories saved or proposed with `lembrar` in this replywikiChanges?: string[] // what the wiki's curator kept from this exchange (change packages)@@ -262,8 +268,9 @@ export interface Question {// A question from someone else's DM comes without where it was asked (they see the question only).export interface Inbox {approvals: Approval[]- questions: (Omit<Question, 'conversationId' | 'threadId'> & { conversationId?: string; threadId?: string })[]- answered?: (Omit<Question, 'conversationId' | 'threadId'> & { conversationId?: string; threadId?: string })[] // to me, answered by someone else a moment ago (the page keeps what I was typing)+ // With the decisions asked (ask_user's options) and what was answered on the card so far.+ questions: (Omit<Question, 'conversationId' | 'threadId'> & { conversationId?: string; threadId?: string; decisions?: Decision[]; answers?: (Answer | null)[] })[]+ answered?: (Omit<Question, 'conversationId' | 'threadId'> & { conversationId?: string; threadId?: string; decisions?: Decision[]; answers?: (Answer | null)[] })[] // to me, answered by someone else a moment ago (the page keeps what I was typing)proposals?: InboxProposal[] // admins: what a member asked to apply (agents and teams are theirs)}diff --git a/test/ask-card.test.tsx b/test/ask-card.test.tsxnew file mode 100644index 0000000..33de076--- /dev/null+++ b/test/ask-card.test.tsx@@ -0,0 +1,91 @@+// The decisions card (ask_user) under an agent's reply: who gets to answer it, what it shows+// while waiting, and what it keeps once answered.+import { renderToStaticMarkup } from 'react-dom/server'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import type { Agent, Person } from '../src/shared/types'+import type { State } from '../src/renderer/src/store'+import type { Decision } from '../src/shared/questions'++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) }+})+const { getState } = await import('../src/renderer/src/store')+const { AskCard, asShown, cardAnswers } = await import('../src/renderer/src/components/Decisions')+const { QuestionCard } = await import('../src/renderer/src/components/Conversation')++const ana: Person = { id: 'ana', name: 'Ana', role: 'owner', about: '' }+const bia: Person = { id: 'bia', name: 'Bia', role: 'member', about: '' }+const carl: Person = { id: 'carl', name: 'Carl', role: 'member', about: '' }+const lia: 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, owner: 'ana' }+const decisions: Decision[] = [+ { question: 'Paginação no menu?', kind: 'single', options: [{ label: 'Busca remota' }, { label: 'Scroll infinito' }, { label: 'Paginar' }] },+ { question: 'Pra quando?', kind: 'text' }+]+const open = { id: 'q1', conversationId: 'ch', agentId: 'a1', text: '1. …', askedTo: 'bia', requestedBy: 'ana', state: 'open' as const, deadlineAt: Date.now() + 3_600_000, createdAt: 1 }+const card = (extra: Record<string, unknown> = {}): string => renderToStaticMarkup(<QuestionCard id="q1" agentName="Lia" askedTo="bia" question="1. …" decisions={decisions} answered={false} {...extra} />)++beforeEach(() => {+ fake = { ...getState(), ready: true, people: [ana, bia, carl], agents: [lia], you: 'bia', inbox: { approvals: [], questions: [] } }+})++describe('the decisions card', () => {+ it("shows the agent's options (3 at most) and always Something else after them, one decision at a time", () => {+ const html = renderToStaticMarkup(<AskCard id="m1" questions={decisions} mode="answer" badge="Esperando você" />)+ expect(html.match(/class="ask-option[ "]/g)).toHaveLength(4)+ expect(html).toContain('Outra coisa…')+ expect(html).toContain('1 de 2')+ expect(html).not.toContain('Pra quando?') // the next decision comes after this one+ })++ it('answered, keeps each decision with what was chosen', () => {+ const html = renderToStaticMarkup(<AskCard id="m1" questions={decisions} saved={[{ chosen: [1] }, { text: 'sexta' }]} mode="done" badge="Respondida por Bia" />)+ expect(html).toContain('Respondida por Bia')+ expect(html).toMatch(/Paginação no menu\?<\/dt><dd[^>]*>Scroll infinito</)+ expect(html).toMatch(/Pra quando\?<\/dt><dd[^>]*>sexta</)+ })++ it('with a team: Bia answers it there; Carl only reads it; an admin answers for her when choosing to', () => {+ fake = { ...fake, inbox: { approvals: [], questions: [open] } }+ expect(card()).toContain('ask--answer')+ fake = { ...fake, you: 'carl', inbox: { approvals: [], questions: [] } }+ expect(card()).toContain('ask--view')+ expect(card()).toContain('Esperando Bia')+ expect(card()).not.toContain('Responder no lugar de Bia')+ fake = { ...fake, you: 'ana' }+ expect(card()).toContain('ask--view')+ expect(card()).toContain('Responder no lugar de Bia')+ })++ it('with a team, answered, says by whom', () => {+ fake = { ...fake, you: 'ana' }+ const html = card({ answered: true, answeredBy: 'bia', answers: [{ chosen: [0] }, { skipped: true }] })+ expect(html).toContain('Respondida por Bia')+ expect(html).toContain('Busca remota')+ })++ it("in a DM, waiting on its person's yes: no one answers it yet", () => {+ fake = { ...fake, you: 'ana', inbox: { approvals: [], questions: [{ ...open, confirm: 'pending' }] } }+ const html = card()+ expect(html).toContain('Lia quer perguntar a Bia')+ expect(html).not.toContain('ask--answer')+ })+})++describe('the message that sent the answers', () => {+ const asked = (run: Record<string, unknown>) => ({ id: 'q', conversationId: 'ch', author: { kind: 'agent' as const, id: 'a1' }, text: 'Te mandei duas decisões.', at: 1, run: { status: 'done' as const, steps: [], questions: decisions, ...run } })+ const answer = { id: 'ans', conversationId: 'ch', author: { kind: 'person' as const, id: 'bia' }, text: '- Paginação no menu? → Busca remota\n\nE mais uma coisa', at: 2 }+ const other = { id: 'x', conversationId: 'ch', author: { kind: 'person' as const, id: 'bia' }, text: '- Paginação no menu? → Busca remota', at: 3 }++ it("isn't shown again under the card that shows it; one typed by hand (the same text, unlinked) is", () => {+ const list = [asked({ answerMessage: 'ans' }), answer, other]+ expect(asShown(list, cardAnswers(list)).map((m) => m.id)).toEqual(['q', 'x'])+ })+ it('shows only what was written beyond the answers', () => {+ const list = [asked({ answerMessage: 'ans', answerTyped: 'E mais uma coisa' }), answer]+ const shown = asShown(list, cardAnswers(list))+ expect(shown.map((m) => m.text)).toEqual(['Te mandei duas decisões.', 'E mais uma coisa'])+ expect(list[1]!.text).toContain('Busca remota') // the message itself is untouched+ })+})diff --git a/test/decision-keys.test.ts b/test/decision-keys.test.tsnew file mode 100644index 0000000..1420a67--- /dev/null+++ b/test/decision-keys.test.ts@@ -0,0 +1,42 @@+import { describe, expect, it } from 'vitest'+import { decisionKey, type DecisionKeyPress } from '../src/renderer/src/components/decision-keys'++const press = (key: string, extra: Partial<DecisionKeyPress> = {}): DecisionKeyPress => ({ key, shift: false, modifier: false, composing: false, inField: false, onBody: true, ...extra })++describe('decisionKey', () => {+ it('a number picks that option', () => {+ expect(decisionKey(press('2'), null, 3)).toEqual({ kind: 'pick', index: 1 })+ expect(decisionKey(press('4'), null, 3)).toEqual({ kind: 'other' }) // the one after the options: Something else+ expect(decisionKey(press('5'), null, 3)).toBeNull()+ expect(decisionKey(press('1'), null, 0)).toBeNull() // a text decision has no options+ })+ it('a number with ⌘, Ctrl or Alt is not an answer', () => {+ expect(decisionKey(press('2', { modifier: true }), null, 3)).toBeNull()+ })+ it('Enter on a focused button is left to the button', () => {+ expect(decisionKey(press('Enter', { onBody: false }), 0, 3)).toBeNull()+ expect(decisionKey(press('1', { onBody: false }), 0, 3)).toEqual({ kind: 'pick', index: 0 })+ })+ it('Enter picks nothing until an option was pointed at', () => {+ expect(decisionKey(press('Enter'), null, 3)).toBeNull()+ expect(decisionKey(press('Enter'), 1, 3)).toEqual({ kind: 'pick', index: 1 })+ expect(decisionKey(press('Enter'), 3, 3)).toEqual({ kind: 'other' })+ })+ it('arrows move through the options and Something else', () => {+ expect(decisionKey(press('ArrowDown'), null, 3)).toEqual({ kind: 'focus', index: 0 })+ expect(decisionKey(press('ArrowDown'), 3, 3)).toEqual({ kind: 'focus', index: 0 })+ expect(decisionKey(press('ArrowUp'), null, 3)).toEqual({ kind: 'focus', index: 3 })+ expect(decisionKey(press('ArrowUp'), 0, 3)).toEqual({ kind: 'focus', index: 3 })+ })+ it('Esc leaves Something else, or the card, instead of answering', () => {+ expect(decisionKey(press('Escape'), 0, 3)).toEqual({ kind: 'dismiss' })+ expect(decisionKey(press('Escape', { inField: true }), 0, 3)).toEqual({ kind: 'dismiss' })+ })+ it('in a field, Enter confirms, Shift+Enter and composing do not, and the arrows leave Something else', () => {+ expect(decisionKey(press('Enter', { inField: true }), null, 0)).toEqual({ kind: 'confirm' })+ expect(decisionKey(press('Enter', { inField: true, shift: true }), null, 0)).toBeNull()+ expect(decisionKey(press('Enter', { inField: true, composing: true }), null, 0)).toBeNull()+ expect(decisionKey(press('2', { inField: true }), null, 3)).toBeNull()+ expect(decisionKey(press('ArrowUp', { inField: true }), 3, 3)).toEqual({ kind: 'focus', index: 2 })+ })+})diff --git a/test/people-roles.test.ts b/test/people-roles.test.tsindex dfb9186..73e5b27 100644--- a/test/people-roles.test.ts+++ b/test/people-roles.test.ts@@ -286,7 +286,7 @@ describe('questions, mentions and memory between people', () => {let gateway: Gatewaylet db: Dblet people: People- let ana: Person, bia: Person, carl: Person+ let ana: Person, bia: Person, carl: Person, dani: Personlet runner: Runnerlet turns: Turn[]let notes: { title: string; conversationId?: string; to?: string[] }[]@@ -295,7 +295,7 @@ describe('questions, mentions and memory between people', () => {beforeEach(async () => {gateway = new Gateway()await gateway.start()- ;({ db, people, ana, bia, carl } = team())+ ;({ db, people, ana, bia, carl, dani } = team())turns = []notes = []events = []@@ -419,6 +419,70 @@ describe('questions, mentions and memory between people', () => {expect(notes.find((n) => n.title === 'Lia te mencionou')).toMatchObject({ to: [bia.id] })})+ // ask_user with options (decisions): answered on the card, one at a time, only by who may answer the question.+ it('decisions to Bia: only she (or an admin) answers them on the card; anyone else is refused, and their message stays theirs', async () => {+ await runner.send('ch', '@lia me ajuda a decidir, decida com a Bia', [], undefined, ana.id)+ await runner.idle()+ const [asked] = lia()+ expect(asked?.run).toMatchObject({ status: 'waiting_input', askedTo: bia.id, questions: [{ kind: 'single' }, { kind: 'text' }] })+ expect(db.question(asked!.id)?.text).toBe('1. Paginação no menu? (Busca remota | Scroll infinito)\n2. Pra quando?')+ expect(people.inbox(bia).questions[0]).toMatchObject({ id: asked!.id, decisions: [{ question: 'Paginação no menu?' }, { question: 'Pra quando?' }] })++ expect(() => runner.answerDecision(asked!.id, 0, { chosen: [1] }, carl)).toThrow('Essa pergunta não é pra você.')+ await expect(runner.submitDecisions(asked!.id, carl)).rejects.toThrow('Essa pergunta não é pra você.')+ runner.answerDecision(asked!.id, 0, { chosen: [1] }, bia)+ expect(people.inbox(bia).questions[0]?.answers).toEqual([{ chosen: [1] }, null])+ // Carl writing there neither answers it nor carries Bia's choices.+ await runner.send('ch', 'eu acho sexta', [], asked!.threadId, carl.id)+ await runner.idle()+ expect(db.messages().find((m) => m.text.includes('eu acho sexta'))?.text).toBe('eu acho sexta')+ expect(db.message(asked!.id)?.run?.status).toBe('waiting_input')++ runner.answerDecision(asked!.id, 1, { text: 'sexta' }, bia)+ await runner.submitDecisions(asked!.id, bia)+ await runner.idle()+ const sent = db.messages().find((m) => m.text.startsWith('- Paginação'))+ expect(sent).toMatchObject({ author: { kind: 'person', id: bia.id }, text: '- Paginação no menu? → Scroll infinito\n- Pra quando? → sexta' })+ expect(db.question(asked!.id)).toMatchObject({ state: 'answered', answeredBy: bia.id })+ expect(turns.at(-1)?.prompt).toContain('Scroll infinito')+ expect(() => runner.answerDecision(asked!.id, 0, { chosen: [0] }, bia)).toThrow('Essa pergunta já foi respondida.')+ })++ it("decisions to Bia: an admin and whoever covers for her may answer them for her, and the agent hears so", async () => {+ await runner.send('ch', '@lia me ajuda a decidir, decida com a Bia', [], undefined, ana.id)+ await runner.idle()+ const [asked] = lia()+ people.setDelegation(bia, carl.id, Date.now() + 3_600_000)+ runner.answerDecision(asked!.id, 0, { chosen: [0] }, carl) // covering+ runner.answerDecision(asked!.id, 1, { skipped: true }, dani) // an admin+ await runner.submitDecisions(asked!.id, dani)+ await runner.idle()+ expect(db.question(asked!.id)).toMatchObject({ state: 'answered', answeredBy: dani.id })+ expect(db.messages().find((m) => m.author.kind === 'person' && m.author.id === dani.id)?.text).toBe('- Paginação no menu? → Busca remota\n- Pra quando? → (pulou)')+ expect(turns.at(-1)?.prompt).toContain('Dani (admin) respondeu no lugar de Bia')+ })++ it("decisions from a DM to someone else wait for the DM's person's yes; then Bia answers them from her inbox", async () => {+ await runner.send('ana-dm', 'decida com a Bia', [], undefined, ana.id)+ await runner.idle()+ const [asked] = lia()+ expect(db.question(asked!.id)).toMatchObject({ confirm: 'pending', askedTo: bia.id })+ // Before the yes, no one answers them on the card: not Bia (who hasn't seen it), not Ana (who says yes or no).+ expect(() => runner.answerDecision(asked!.id, 0, { chosen: [0] }, bia)).toThrow()+ expect(() => runner.answerDecision(asked!.id, 0, { chosen: [0] }, ana)).toThrow()+ await runner.send('ana-dm', 'sim', [], undefined, ana.id)+ await runner.idle()+ const [forBia] = people.inbox(bia).questions+ expect(forBia).toMatchObject({ id: asked!.id, decisions: [{ question: 'Paginação no menu?' }, { question: 'Pra quando?' }] })+ expect(forBia).not.toHaveProperty('conversationId')+ runner.answerDecision(asked!.id, 0, { chosen: [1] }, bia)+ runner.answerDecision(asked!.id, 1, { text: 'sexta' }, bia)+ await runner.submitDecisions(asked!.id, bia)+ await runner.idle()+ expect(db.question(asked!.id)).toMatchObject({ state: 'answered', answeredBy: bia.id })+ expect(db.messages().find((m) => m.author.kind === 'person' && m.author.id === bia.id)).toMatchObject({ conversationId: 'ana-dm', text: '- Paginação no menu? → Scroll infinito\n- Pra quando? → sexta' })+ })+it("memories: each person's words make their own; an agent in a channel gets those of who wrote there", async () => {const memory = new Memories({ db, engines: { claude: fakeEngine('claude', { delayMs: 1 }) } as Record<EngineId, Engine>, settings: async () => settings, emit: () => {}, workDir: dir() })// A thread's own consolidation reads all of it (a conversation's only what leaves its window).diff --git a/test/questions.test.ts b/test/questions.test.tsnew file mode 100644index 0000000..8a7ddb0--- /dev/null+++ b/test/questions.test.ts@@ -0,0 +1,184 @@+import { describe, expect, it } from 'vitest'+import {+ answerLabel,+ describeQuestions,+ draftAnswer,+ firstUnanswered,+ formatAnswers,+ isAnswered,+ isNewQuestion,+ parseQuestions,+ questionHeadline,+ questionsAsText,+ questionsOf,+ type AnswerDraft,+ type Decision+} from '../src/shared/questions'+import type { Message, Run } from '../src/shared/types'++const pagination: Decision = { question: 'Paginação no menu?', kind: 'single', options: [{ label: 'Busca remota' }, { label: 'Scroll infinito' }] }+const parts: Decision = { question: 'O que remover?', kind: 'multiple', options: [{ label: 'Nó tag' }, { label: 'getUsedTags' }, { label: 'declaredTagIds' }] }+const deadline: Decision = { question: 'Pra quando?', kind: 'text' }++const refused = (args: Record<string, unknown>): boolean => 'error' in parseQuestions(args)++describe('draftAnswer', () => {+ const single: Decision = { question: 'Qual?', kind: 'single', options: [{ label: 'A' }, { label: 'B' }] }+ const multiple: Decision = { ...single, kind: 'multiple' }+ const text: Decision = { question: 'Qual?', kind: 'text' }+ const draft = (patch: Partial<AnswerDraft>): AnswerDraft => ({ chosen: [], other: '', text: '', ...patch })++ it('is the text, trimmed, or nothing', () => {+ expect(draftAnswer(text, draft({ text: ' sexta ' }))).toEqual({ text: 'sexta' })+ expect(draftAnswer(text, draft({ text: ' ' }))).toBeNull()+ })++ it('keeps every option ticked, in order, and something else with them', () => {+ expect(draftAnswer(multiple, draft({ chosen: [1, 0], other: ' C ' }))).toEqual({ chosen: [0, 1], other: 'C' })+ expect(draftAnswer(multiple, draft({}))).toBeNull()+ })++ it('in a single choice, something else takes the place of the option', () => {+ expect(draftAnswer(single, draft({ chosen: [1], other: 'C' }))).toEqual({ other: 'C' })+ expect(draftAnswer(single, draft({ chosen: [1] }))).toEqual({ chosen: [1] })+ })+})++describe('isNewQuestion', () => {+ const asked = (run: Partial<Run>): Message => ({ id: 'm', conversationId: 'c', author: { kind: 'agent', id: 'a' }, text: '', at: 0, run: { status: 'waiting_input', steps: [], questions: [{ question: 'Qual?', kind: 'text' }], ...run } })++ it('is a question waiting, before any answer', () => {+ expect(isNewQuestion(asked({}))).toBe(true)+ expect(isNewQuestion(asked({ questions: undefined, question: 'Qual?' }))).toBe(true)+ })++ it('is not a question saved again with an answer on it', () => {+ expect(isNewQuestion(asked({ answers: [null] }))).toBe(false)+ })++ it('is not anything else', () => {+ expect(isNewQuestion(asked({ status: 'done' }))).toBe(false)+ expect(isNewQuestion(asked({ questions: undefined }))).toBe(false)+ })+})++describe('questionsOf', () => {+ it('reads an old run with a question string as one text decision', () => {+ expect(questionsOf({ status: 'done', steps: [], question: 'Pra quando?' })).toEqual([deadline])+ })+ it('prefers run.questions over the old string', () => {+ expect(questionsOf({ status: 'done', steps: [], question: 'velha', questions: [pagination] })).toEqual([pagination])+ })+ it('is empty without a question', () => {+ expect(questionsOf(undefined)).toEqual([])+ expect(questionsOf({ status: 'done', steps: [] })).toEqual([])+ })+})++describe('parseQuestions', () => {+ it('accepts the old { question } form', () => {+ expect(parseQuestions({ question: ' Pra quando? ' })).toEqual({ questions: [deadline] })+ })+ it('accepts a list of decisions and trims labels', () => {+ const args = {+ questions: [+ { question: ' Paginação no menu? ', kind: 'single', options: [{ label: ' Busca remota ' }, { label: 'Scroll infinito', description: ' dá mais trabalho ' }] },+ { question: 'Pra quando?', kind: 'text' }+ ]+ }+ expect(parseQuestions(args)).toEqual({+ questions: [+ { question: 'Paginação no menu?', kind: 'single', options: [{ label: 'Busca remota' }, { label: 'Scroll infinito', description: 'dá mais trabalho' }] },+ deadline+ ]+ })+ })+ it('refuses no decisions, more than 4, bad option counts, empty text and unknown kinds', () => {+ const two = [{ label: 'a' }, { label: 'b' }]+ expect(refused({})).toBe(true)+ expect(refused({ questions: [] })).toBe(true)+ expect(refused({ questions: Array.from({ length: 5 }, () => deadline) })).toBe(true)+ expect(refused({ questions: [{ question: 'x', kind: 'single', options: [] }] })).toBe(true)+ expect(refused({ questions: [{ question: 'x', kind: 'single', options: [{ label: 'a' }] }] })).toBe(false) // one suggestion, and Something else+ expect(refused({ questions: [{ question: ' ', kind: 'text' }] })).toBe(true)+ expect(refused({ questions: [{ question: 'x', kind: 'single', options: [{ label: 'a' }, { label: ' ' }] }] })).toBe(true)+ expect(refused({ questions: [{ question: 'x', kind: 'dropdown', options: two }] })).toBe(true)+ expect(refused({ question: ' ' })).toBe(true)+ })+ it('keeps the first 3 options of a longer list: the card adds Something else', () => {+ const r = parseQuestions({ questions: [{ question: 'x', kind: 'multiple', options: ['a', 'b', 'c', 'd', 'e'].map((label) => ({ label })) }] })+ expect(r).toEqual({ questions: [{ question: 'x', kind: 'multiple', options: [{ label: 'a' }, { label: 'b' }, { label: 'c' }] }] })+ })++ it('drops options from a text decision', () => {+ expect(parseQuestions({ questions: [{ question: 'Pra quando?', kind: 'text', options: [{ label: 'a' }, { label: 'b' }] }] })).toEqual({ questions: [deadline] })+ })+})++describe('answers', () => {+ it('knows an answered decision', () => {+ expect(isAnswered(undefined)).toBe(false)+ expect(isAnswered(null)).toBe(false)+ expect(isAnswered({})).toBe(false)+ expect(isAnswered({ chosen: [] })).toBe(false)+ expect(isAnswered({ chosen: [0] })).toBe(true)+ expect(isAnswered({ other: 'x' })).toBe(true)+ expect(isAnswered({ text: 'x' })).toBe(true)+ expect(isAnswered({ skipped: true })).toBe(true)+ })+ it('finds the first unanswered decision, -1 when all are', () => {+ expect(firstUnanswered([pagination, parts], undefined)).toBe(0)+ expect(firstUnanswered([pagination, parts], [{ chosen: [0] }])).toBe(1)+ expect(firstUnanswered([pagination, parts], [{ chosen: [0] }, { skipped: true }])).toBe(-1)+ })+ it('labels each kind of answer', () => {+ expect(answerLabel(pagination, { chosen: [1] })).toBe('Scroll infinito')+ expect(answerLabel(parts, { chosen: [2, 0] })).toBe('Nó tag, declaredTagIds')+ expect(answerLabel(parts, { chosen: [0], other: 'o chip' })).toBe('Nó tag, Outra coisa: o chip')+ expect(answerLabel(pagination, { other: 'os dois' })).toBe('Outra coisa: os dois')+ expect(answerLabel(deadline, { text: 'sexta' })).toBe('sexta')+ expect(answerLabel(deadline, { skipped: true })).toBe('(pulou)')+ })+ it('formats one line per answered decision and leaves the unanswered out', () => {+ expect(formatAnswers([pagination, parts, deadline], [{ chosen: [0] }, null, { skipped: true }])).toBe('- Paginação no menu? → Busca remota\n- Pra quando? → (pulou)')+ expect(formatAnswers([pagination], undefined)).toBe('')+ })+})++describe('headline and description', () => {+ it('headlines the first question, with how many more', () => {+ expect(questionHeadline([deadline])).toBe('Pra quando?')+ expect(questionHeadline([pagination, parts, deadline])).toBe('Paginação no menu? (+2)')+ })+ it('describes the decisions for the agent context, a lone text question exactly as before', () => {+ expect(describeQuestions([deadline])).toBe('Pra quando?')+ expect(describeQuestions([pagination, deadline])).toBe('1. Paginação no menu? (Busca remota | Scroll infinito); 2. Pra quando?')+ })+})++describe('questionsAsText', () => {+ it('is the question alone for one decision, and a numbered line each for more', () => {+ expect(questionsAsText([deadline])).toBe('Pra quando?')+ expect(questionsAsText([pagination, deadline])).toBe('1. Paginação no menu? (Busca remota | Scroll infinito)\n2. Pra quando?')+ })+})++describe('lengths', () => {+ it('refuses a long question, a long label or a long description, and says where the context goes', () => {+ const long = (n: number): string => 'x'.repeat(n)+ const result = parseQuestions({ questions: [{ question: long(201), kind: 'text' }] })+ expect('error' in result && result.error).toMatch(/texto da (sua )?resposta/)+ expect('error' in parseQuestions({ question: long(201) })).toBe(true)+ expect('error' in parseQuestions({ questions: [{ question: 'x', kind: 'single', options: [{ label: long(81) }, { label: 'b' }] }] })).toBe(true)+ expect('error' in parseQuestions({ questions: [{ question: 'x', kind: 'single', options: [{ label: 'a', description: long(201) }, { label: 'b' }] }] })).toBe(true)+ expect('error' in parseQuestions({ questions: [{ question: long(200), kind: 'single', options: [{ label: long(80), description: long(200) }, { label: 'b' }] }] })).toBe(false)+ })+})++describe('a lone text question', () => {+ it('is answered with the answer alone, as before decisions', () => {+ expect(formatAnswers([deadline], [{ text: 'sexta' }])).toBe('sexta')+ expect(formatAnswers([deadline], [{ skipped: true }])).toBe('(pulou)')+ expect(formatAnswers([pagination], [{ chosen: [0] }])).toBe('- Paginação no menu? → Busca remota')+ })+})diff --git a/test/routines.test.ts b/test/routines.test.tsindex 528374a..29a2687 100644--- a/test/routines.test.ts+++ b/test/routines.test.ts@@ -187,6 +187,10 @@ describe('routines', () => {const base = { id: 'm', conversationId: 'c1', author: { kind: 'agent' as const, id: 'a1' }, at: 0 }expect(outcome({ ...base, text: '## Resumo\n\n**3 issues** vencidas: [ENG-1](https://x.y/1)', run: { status: 'done', steps: [] } })).toBe('Resumo 3 issues vencidas: ENG-1')expect(outcome({ ...base, text: '', run: { status: 'waiting_approval', steps: [] } })).toBe('Pediu aprovação pra continuar.')+ expect(outcome({ ...base, text: '', run: { status: 'waiting_input', steps: [], question: 'Pra quando?' } })).toBe('Perguntou: Pra quando?')+ expect(+ outcome({ ...base, text: '', run: { status: 'waiting_input', steps: [], questions: [{ question: 'Paginação no menu?', kind: 'single', options: [{ label: 'a' }, { label: 'b' }] }, { question: 'Pra quando?', kind: 'text' }] } })+ ).toBe('Perguntou: Paginação no menu? (+1)')})it('a one-off routine runs once and turns itself off', async () => {diff --git a/test/runner.test.ts b/test/runner.test.tsindex f89df7d..5460264 100644--- a/test/runner.test.ts+++ b/test/runner.test.ts@@ -8,6 +8,7 @@ import { Db } from '../src/core/db'import { fakeEngine } from '../src/core/engines/fake'import type { Engine, Turn } from '../src/core/engines/types'import { Gateway } from '../src/core/gateway'+import type { Answer } from '../src/shared/questions'import { Runner } from '../src/core/runs'const ready = { installed: true, loggedIn: true }@@ -418,7 +419,7 @@ describe('ask_user through the gateway', () => {await r.send('c1', '@lia me pergunta o que faltar')await r.idle()const [asked] = agentMessages()- expect(asked?.run).toMatchObject({ status: 'waiting_input', question: 'Pra quando você precisa disso?' })+ expect(asked?.run).toMatchObject({ status: 'waiting_input', questions: [{ question: 'Pra quando você precisa disso?', kind: 'text' }] })expect(asked?.run?.steps.map((s) => s.label)).toEqual(['Pensou', 'Perguntou a você', 'Respondeu'])expect(claude.turns[0]?.mcpUrl).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/mcp\/[a-f0-9]{48}$/)@@ -432,6 +433,140 @@ describe('ask_user through the gateway', () => {expect(claude.turns[1]?.prompt).toContain('pergunta enviada a Edu pela ferramenta ask_user: Pra quando você precisa disso?')expect(db.messages().some((m) => m.text.startsWith('Chamei'))).toBe(false)})+ const askingRunner = (): Runner =>+ new Runner({+ db,+ engines: { claude, codex: fakeEngine('codex', { delayMs: 1 }), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') },+ settings: async () => settings,+ emit: (e) => events.push(e),+ workDir: mkdtempSync(join(tmpdir(), 'ad-work-')),+ gateway+ })++ it('asks a list of decisions', async () => {+ claude = counted(fakeEngine('claude', { delayMs: 1 }))+ const r = askingRunner()+ await r.send('c1', '@lia me ajuda a decidir')+ await r.idle()+ const [asked] = agentMessages()+ expect(asked?.run).toMatchObject({+ status: 'waiting_input',+ questions: [+ { question: 'Paginação no menu?', kind: 'single', options: [{ label: 'Busca remota' }, { label: 'Scroll infinito' }] },+ { question: 'Pra quando?', kind: 'text' }+ ]+ })+ // The same decisions as text, for what reads text only (a team's inbox, the phone, a notification).+ expect(asked?.run?.question).toBe('1. Paginação no menu? (Busca remota | Scroll infinito)\n2. Pra quando?')+ expect(asked?.run?.steps.find((s) => s.label === 'Perguntou a você')?.detail).toBe('Paginação no menu? (+1)')+ })++ it('gives the agent the error when the decisions are invalid', async () => {+ claude = counted(fakeEngine('claude', { delayMs: 1 }))+ const r = askingRunner()+ await r.send('c1', '@lia decisões demais')+ await r.idle()+ const [asked] = agentMessages()+ expect(asked?.run?.status).not.toBe('waiting_input')+ expect(asked?.run?.questions).toBeUndefined()+ })++ const askDecisions = async (): Promise<{ r: Runner; asked: Message }> => {+ claude = counted(fakeEngine('claude', { delayMs: 1 }))+ const r = askingRunner()+ await r.send('c1', '@lia me ajuda a decidir')+ await r.idle()+ return { r, asked: agentMessages()[0]! }+ }+ const mine = (): Message[] => db.messages().filter((m) => m.author.kind === 'person')++ it('sends the answers of a question older than the last 50 messages', async () => {+ const { r, asked } = await askDecisions()+ for (let i = 0; i < 60; i++) db.saveMessage({ id: `routine-${i}`, conversationId: asked.conversationId, author: { kind: 'system' }, text: `Rotina ${i}`, at: asked.at + 1000 + i, ...(asked.threadId ? { threadId: asked.threadId } : {}) })+ r.answerDecision(asked.id, 0, { chosen: [1] }, db.owner())+ r.answerDecision(asked.id, 1, { text: 'até sexta' }, db.owner())+ await r.submitDecisions(asked.id, db.owner())+ expect(db.message(asked.id)?.run?.status).toBe('done')+ expect(mine().at(-1)?.text).toContain('Scroll infinito')+ })++ it('answers the question on the card, not a newer one waiting in the same place', async () => {+ const { r, asked } = await askDecisions()+ const newer: Message = { ...asked, id: 'newer', author: { kind: 'agent', id: 'a2' }, at: asked.at + 1000, run: { status: 'waiting_input', steps: [], questions: [{ question: 'Outra?', kind: 'text' }] } }+ db.saveMessage(newer)+ r.answerDecision(asked.id, 0, { skipped: true }, db.owner())+ r.answerDecision(asked.id, 1, { text: 'até sexta' }, db.owner())+ await r.submitDecisions(asked.id, db.owner())+ expect(db.message(asked.id)?.run?.status).toBe('done')+ expect(db.message('newer')?.run?.status).toBe('waiting_input')+ })++ it('keeps partial answers on the question and sends them as my message', async () => {+ const { r, asked } = await askDecisions()+ r.answerDecision(asked.id, 0, { chosen: [1] }, db.owner())+ expect(db.message(asked.id)?.run?.answers).toEqual([{ chosen: [1] }, null])+ r.answerDecision(asked.id, 1, { text: 'sexta' }, db.owner())+ await r.submitDecisions(asked.id, db.owner())+ await r.idle()+ expect(mine().at(-1)?.text).toBe('- Paginação no menu? → Scroll infinito\n- Pra quando? → sexta')+ expect(db.message(asked.id)?.run?.status).toBe('done')+ expect(db.message(asked.id)?.run?.answeredInText).toBeUndefined()+ // The card knows which message carried its answers: the conversation shows them once, on the card.+ expect(db.message(asked.id)?.run).toMatchObject({ answerMessage: mine().at(-1)?.id })+ expect(db.message(asked.id)?.run?.answerTyped).toBeUndefined()+ expect(claude.turns[1]?.prompt).toContain('- Paginação no menu? → Scroll infinito\n- Pra quando? → sexta')+ })++ it('sends the partial answers along with a free reply', async () => {+ const { r, asked } = await askDecisions()+ r.answerDecision(asked.id, 0, { chosen: [0] }, db.owner())+ await r.send('c1', 'o resto eu explico: depois do deploy', [], asked.threadId)+ await r.idle()+ expect(mine().at(-1)?.text).toBe('- Paginação no menu? → Busca remota\n\no resto eu explico: depois do deploy')+ expect(db.message(asked.id)?.run).toMatchObject({ status: 'done', answeredInText: true, answerMessage: mine().at(-1)?.id, answerTyped: 'o resto eu explico: depois do deploy' })+ })++ it('an answer typed with nothing picked on the card is not linked to it: it shows as the message it is', async () => {+ const { r, asked } = await askDecisions()+ await r.send('c1', 'busca remota, até sexta', [], asked.threadId)+ await r.idle()+ expect(db.message(asked.id)?.run?.status).toBe('done')+ expect(db.message(asked.id)?.run?.answerMessage).toBeUndefined()+ })++ it('ignores answers to a question already sent, out of range, or to an unknown option', async () => {+ const { r, asked } = await askDecisions()+ r.answerDecision(asked.id, 9, { text: 'x' }, db.owner())+ r.answerDecision(asked.id, 0, { chosen: [7] }, db.owner())+ r.answerDecision(asked.id, 0, { chosen: [0, 1] }, db.owner()) // a single choice takes one+ r.answerDecision(asked.id, 1, { chosen: [0] }, db.owner()) // a text decision takes text+ r.answerDecision(asked.id, -1, { text: 'x' }, db.owner())+ expect(() => r.answerDecision('nope', 0, { chosen: [0] }, db.owner())).toThrow()+ expect(db.message(asked.id)?.run?.answers).toBeUndefined()+ r.answerDecision(asked.id, 0, { chosen: [0], text: 'ignored', extra: 1 } as Answer, db.owner())+ expect(db.message(asked.id)?.run?.answers).toEqual([{ chosen: [0] }, null])+ await r.submitDecisions(asked.id, db.owner())+ await r.idle()+ expect(() => r.answerDecision(asked.id, 0, { chosen: [1] }, db.owner())).toThrow()+ expect(db.message(asked.id)?.run?.answers).toEqual([{ chosen: [0] }, null])+ })++ it('sends only once', async () => {+ const { r, asked } = await askDecisions()+ r.answerDecision(asked.id, 0, { skipped: true }, db.owner())+ const sent = await Promise.allSettled([r.submitDecisions(asked.id, db.owner()), r.submitDecisions(asked.id, db.owner())])+ expect(sent.map((x) => x.status)).toEqual(['fulfilled', 'rejected'])+ await r.idle()+ expect(mine()).toHaveLength(2)+ })++ it('clears an answer with null', async () => {+ const { r, asked } = await askDecisions()+ r.answerDecision(asked.id, 0, { chosen: [0] }, db.owner())+ r.answerDecision(asked.id, 1, { text: 'sexta' }, db.owner())+ r.answerDecision(asked.id, 0, null, db.owner())+ expect(db.message(asked.id)?.run?.answers).toEqual([null, { text: 'sexta' }])+ })})describe('browser handback', () => {diff --git a/test/telegram.test.ts b/test/telegram.test.tsindex e478832..44fc18a 100644--- a/test/telegram.test.ts+++ b/test/telegram.test.ts@@ -129,6 +129,18 @@ describe('Telegram', () => {expect(answered).toEqual([['c1', 'Sexta que vem']])})+ it('shows every decision as text, and a reply still answers', async () => {+ await pair()+ const questions = [{ question: 'Paginação no menu?', kind: 'single' as const, options: [{ label: 'Busca remota' }, { label: 'Scroll infinito' }] }, { question: 'Pra quando?', kind: 'text' as const }]+ const question: Message = { id: 'm3', conversationId: 'c1', author: { kind: 'agent', id: 'a1' }, text: '', at: 0, run: { status: 'waiting_input', steps: [], questions } }+ await tg.questionAsked(question, 'PM', '#simula-oab')+ const asked = api.sent.at(-1)!+ expect(asked.body['text']).toContain('PM pergunta (#simula-oab):\n\n1. Paginação no menu? (Busca remota | Scroll infinito)\n2. Pra quando?')+ api.push({ message: { message_id: 8, chat: me, text: 'busca remota, sexta', reply_to_message: { message_id: asked.id } } })+ await settle()+ expect(answered).toEqual([['c1', 'busca remota, sexta']])+ })+it("a reply to a question asked in a thread goes back to that thread", async () => {await pair()const question: Message = { id: 'm2', conversationId: 'c1', threadId: 'root', author: { kind: 'agent', id: 'a1' }, text: '', at: 0, run: { status: 'waiting_input', steps: [], question: 'Qual o prazo?' } }diff --git a/test/waiting.test.ts b/test/waiting.test.tsnew file mode 100644index 0000000..9b805d6--- /dev/null+++ b/test/waiting.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from 'vitest'+import { mineIn, waitingIn, waitingTitle } from '../src/renderer/src/components/waiting'+import type { Approval, Inbox, Message, RunStatus } from '../src/shared/types'++const msg = (id: string, conversationId: string, agentId: string, status: RunStatus): Message => ({ id, conversationId, author: { kind: 'agent', id: agentId }, text: '', at: 0, run: { status, steps: [] } })+const names: Record<string, string> = { leo: 'Leo', bia: 'Bia', nina: 'Nina' }+const nameOf = (id: string): string => names[id] ?? id++describe('waitingIn', () => {+ it('reads the messages it is given, not the ones it read before', () => {+ const before = [msg('1', 'c1', 'leo', 'waiting_input')]+ expect(waitingIn(before, 'c1').asked).toEqual(['leo'])+ expect(waitingIn([msg('1', 'c1', 'leo', 'done')], 'c1').asked).toEqual([])+ expect(waitingIn(before, 'c1').asked).toEqual(['leo'])+ })++ it('lists who asked and who asks for approval in a conversation, each once', () => {+ const messages = [msg('1', 'c1', 'leo', 'waiting_input'), msg('2', 'c1', 'bia', 'waiting_approval'), msg('3', 'c1', 'leo', 'waiting_input'), msg('4', 'c2', 'nina', 'waiting_input'), msg('5', 'c1', 'nina', 'working')]+ expect(waitingIn(messages, 'c1')).toEqual({ asked: ['leo'], approval: ['bia'] })+ expect(waitingIn(messages, 'c3')).toEqual({ asked: [], approval: [] })+ })+ it('counts threads too, and nothing that is done', () => {+ const inThread = { ...msg('1', 'c1', 'leo', 'waiting_input'), threadId: 'root' }+ expect(waitingIn([inThread, msg('2', 'c1', 'bia', 'done')], 'c1')).toEqual({ asked: ['leo'], approval: [] })+ })+})++describe('waitingIn with a team', () => {+ it('marks only what waits on me: a question in my inbox, an approval I can decide', () => {+ const toBia = msg('1', 'c1', 'leo', 'waiting_input')+ const toMe = msg('2', 'c1', 'nina', 'waiting_input')+ const approval = { ...msg('3', 'c1', 'bia', 'waiting_approval'), run: { status: 'waiting_approval' as const, steps: [], approvalId: 'ap1' } }+ const messages = [toBia, toMe, approval]+ const inbox: Inbox = { approvals: [], questions: [{ id: '2', agentId: 'nina', text: 'Qual?', askedTo: 'me', requestedBy: 'me', state: 'open', deadlineAt: 0, createdAt: 0 }] }+ expect(waitingIn(messages, 'c1', { key: inbox, test: mineIn(inbox) })).toEqual({ asked: ['nina'], approval: [] })+ const mine: Inbox = { ...inbox, approvals: [{ id: 'ap1' } as Approval] }+ expect(waitingIn(messages, 'c1', { key: mine, test: mineIn(mine) })).toEqual({ asked: ['nina'], approval: ['bia'] })+ expect(waitingIn(messages, 'c1')).toEqual({ asked: ['leo', 'nina'], approval: ['bia'] }) // alone: everything is mine+ })+})++describe('waitingTitle', () => {+ it('says who is waiting and for what', () => {+ expect(waitingTitle({ asked: ['leo'], approval: [] }, nameOf)).toBe('Leo te perguntou algo')+ expect(waitingTitle({ asked: ['leo', 'nina'], approval: [] }, nameOf)).toBe('Leo e Nina te perguntaram algo')+ expect(waitingTitle({ asked: [], approval: ['bia'] }, nameOf)).toBe('Bia pede aprovação')+ expect(waitingTitle({ asked: [], approval: ['bia', 'leo'] }, nameOf)).toBe('Bia e Leo pedem aprovação')+ expect(waitingTitle({ asked: ['leo'], approval: ['bia'] }, nameOf)).toBe('Leo te perguntou algo · Bia pede aprovação')+ expect(waitingTitle({ asked: [], approval: [] }, nameOf)).toBe('')+ })+})