diff --git a/CHANGELOG.md b/CHANGELOG.md index 3ada64ac49..c0808adb4a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,14 @@ All notable changes to DS Bot are listed here. The format follows [Keep a Change ## [Unreleased] +### Changed + +- A question card closes when its Bot finishes a later turn you can see that asks nothing, so a stale card no longer stays on screen until you answer it. A hidden turn that only answers another Bot leaves the card open. A click on a closed card is refused. + +### Added + +- `void_question` lets a Main Bot withdraw another Bot's open question card. The Bot is told, and a late click on the card is refused. + ## [0.2.4] - 2026-10-29 ### Added diff --git a/ds-bot/README.md b/ds-bot/README.md index 97cad49ae6..1c7cef2fa2 100644 --- a/ds-bot/README.md +++ b/ds-bot/README.md @@ -11,7 +11,7 @@ Tested with dsh `0.2.1-rc.4` (Web) and `0.2.0-rc.2` (Web and Desktop). - **Long-lived Bots**: each Bot is a dsh Session in the "DS Bot" workspace, with its own name, role, instructions and model. - **Working folders**: a Bot can work in a folder you choose instead of the team workspace, and a group chat can set one folder for all its members there. Pick it in the Bot's settings or details panel or in the group's settings, or ask a Bot (`update_bot`, `update_group`). After a change, the chat goes on in a fresh part that starts in the new folder. When a Bot sets a folder outside the team workspace, or adds a Bot to a group that works in one, it asks for your approval if those Bots can only write in their folder. Folders that hold dsh data (`$DSH_HOME`, the team's data) are refused. The team workspace itself moves in Settings > General > Locations; Bots and groups that work there go on in a fresh part in the new folder, and the old folder keeps its files. - **Permission presets**: each Bot runs with its own dsh permission preset (Read only, Workspace or Full access), set in its details panel. A group chat can run all its members with one preset there, in place of their own: turn on **Same for every member** under Permissions in the group's settings. Only you set permissions; Bots cannot change them. -- **Bots work together**: `message_bot` sends a message to another Bot, `create_bot` and `update_bot` add and set up Bots (including a profile photo from a local image file or a data URL), and `ask_user` asks you a question without blocking the other Bots. `show_view` draws a card in a Bot's own chat — text, metrics, tables, progress, choices, confirmations and short forms; an interactive card waits for your answer. +- **Bots work together**: `message_bot` sends a message to another Bot, `create_bot` and `update_bot` add and set up Bots (including a profile photo from a local image file or a data URL), and `ask_user` asks you a question without blocking the other Bots. A question card closes when the Bot finishes a later turn you can see that asks nothing, or when a Main Bot withdraws it with `void_question`; a turn that only answers another Bot leaves it open, and a late click on a closed card is refused. `show_view` draws a card in a Bot's own chat: text, metrics, tables, progress, choices, confirmations and short forms; an interactive card waits for your answer. - **Group chats**: members speak one at a time, and each one reads the latest messages first. A message can `@Name` a member to pass the turn on; type `@` to pick one from a list. **+ → Reference a chat** adds another Bot's chat to a message as context, and in a group the members who answer get it. A member with nothing new to add stays quiet (`[PASS]`). Each member has its own hidden Session per group, so a group never reads a Bot's private chat. - **Roles and permissions**: diff --git a/ds-bot/src/host/constants.js b/ds-bot/src/host/constants.js index 0df0d7d6c9..ff2edcc939 100644 --- a/ds-bot/src/host/constants.js +++ b/ds-bot/src/host/constants.js @@ -63,7 +63,7 @@ export const AGENT_SESSION_TITLE_MAX = 80 // Desktop profile, so a restriction filters this list down to registered names. export const TEAM_TOOLS = [ 'list_bots', 'message_bot', 'stop_bot', 'create_bot', 'update_bot', 'list_bot_models', - 'create_group', 'update_group', 'delete_group', 'post_to_group', 'ask_user', 'show_view', + 'create_group', 'update_group', 'delete_group', 'post_to_group', 'ask_user', 'void_question', 'show_view', 'request_secret', 'list_secrets', 'group_relay', 'read_own_chat', 'read_group_chat', 'remember', 'forget', 'recall', 'read_browser', 'list_capabilities', 'save_capability', 'delete_capability', diff --git a/ds-bot/src/host/delivery.js b/ds-bot/src/host/delivery.js index 7d30008dda..baf4ecb21b 100644 --- a/ds-bot/src/host/delivery.js +++ b/ds-bot/src/host/delivery.js @@ -25,6 +25,7 @@ export function install(rt) { if (resumed && role !== 'room') return `[Message from ${fromName} · DeepSeek Harness restarted while you were working on it]` if (role === 'reply') return `[Reply from ${fromName}${goesOn}]` if (role === 'stopped') return `[Stopped by ${fromName}]` + if (role === 'voided') return `[Question voided by ${fromName}]` if (role === 'room') return `[Group chat "${roomName}" · ${note}]` if (role === 'report') return `[Group chat "${roomName}" · replies to your post${goesOn}]` if (role === 'kickoff') return '[Bot team setup]' diff --git a/ds-bot/src/host/privacy.js b/ds-bot/src/host/privacy.js index af080718b3..c2f2ee98d2 100644 --- a/ds-bot/src/host/privacy.js +++ b/ds-bot/src/host/privacy.js @@ -195,6 +195,11 @@ export function install(rt) { if (bot) throw closed(bot, 'turns') return } + case 'void_question': { + const bot = target(args.bot) + if (bot) throw closed(bot, 'questions') + return + } case 'attach_capability': case 'detach_capability': { const bot = target(args.bot) diff --git a/ds-bot/src/host/prompt.js b/ds-bot/src/host/prompt.js index 682b53d54b..5c594001c0 100644 --- a/ds-bot/src/host/prompt.js +++ b/ds-bot/src/host/prompt.js @@ -14,7 +14,7 @@ const TEAM_RULES = [ '- Only for a direct user request in your own chat that needs several steps: write one short sentence of normal reply text before your first tool call, and make that tool call in the same response. Never start such a task with tools alone or end it with a promise. On long tasks, give brief factual updates only at meaningful milestones, then keep working.', '- For "[Message from …]" or "[Reply from …]" messages, do not write plans or progress updates: use tools silently, then reply with the answer. Simple answers do not need progress messages.', '- In a group chat, the group sees what you write while you work, not only your final reply. For work that takes more than a quick look, start with one short sentence on what you will do, in the same response as your first tool call. After that, write only when you find something the group should know or finish a part of the work, in a sentence or two, not at every step. End with the result. Simple answers need no updates.', - '- Offer choices with ask_user (a tap-to-answer card) instead of long option lists in text. Calling it ends your turn at once, so write everything you want to say before the call, in the same reply. The answer arrives as the user\'s next message.', + '- Offer choices with ask_user (a tap-to-answer card) instead of long option lists in text. Calling it ends your turn at once, so write everything you want to say before the call, in the same reply. The answer arrives as the user\'s next message. The card stays open only until your next finished turn the user can see: a turn in your own chat that asks nothing closes it and a later click on it is refused, so ask again if you still need the answer. A turn that answers another Bot leaves it open.', '- show_view draws a view inside your reply: a chart, key numbers, a table, a calculator whose inputs the user can change, or a choice, confirmation or short form. Use it when it shows something better than text, not for every answer. A view that asks for an answer ends your turn at once, like ask_user, so write everything you want to say before the call, in the same reply; the answer arrives as the user\'s next message. It only works in your own chat, not in a group. Never collect a key, token, or password with it; call request_secret. The view argument is limited to 8 KB.', '- update_bot changes your own settings: name, role label, color, model, thinking level, working folder, or instructions. Leave out bot to change yourself. Use it when the user asks you to change how you are set up, for example to work in a project folder (work_dir, a full path). Only a Main Bot can change other Bots; when another Bot needs changing, ask a Main Bot.', '- You may be in group chats with the user and other Bots. You speak in each group from a separate conversation of yours, apart from your own chat with the user. There your turn arrives as a "[Group chat …]" message that shows the speaking order, and your reply is posted to the group. When someone there asks you to do something, do the work in that turn: the group goes on without waiting and sees what you write as you go. Any member can hand work to another with @Name, and the one that asked answers the result. Work for a group stays in it: there message_bot reaches only members of that group, as @Name does. In a group, read_own_chat shows your own chat (the group sees that you looked; share only what the group needs). In your own chat, read_group_chat shows what was said in a group. A group may have an admin, who steers it: the admin can call members with @Name and change the group with update_group. From outside a group (your own chat or another group), post_to_group posts into a group you are in: the admin\'s post starts a new discussion there; another member\'s post calls only the members it names with @Name.', @@ -31,6 +31,7 @@ const MAIN_RULES = [ '- After creating a Bot, tell the user in one line that it is ready, using its exact name.', '- Route work to the right Bot: one Bot\'s task with message_bot, a group\'s task with post_to_group (or @Name when you speak in that group). Send each task one way only, then tell the user what you asked and that you will report back.', '- If a Bot does not heed your message and must not finish what it is doing, stop_bot ends its turn at once and tells it why; the reply comes back to you.', + '- When a question card another Bot left open no longer applies, void_question withdraws it and tells that Bot; a late click on it is refused.', '- Every Bot runs on one model of its own (list_bots shows it). Pass model or a thinking level (effort) to create_bot or update_bot only when the user names one; list_bot_models gives the provider/model refs and, for a model in use, the thinking levels it serves.', '- Use update_bot to rename a Bot, change its role, color, model, thinking level, working folder, or instructions when the user asks.', '- You run the group chats too. create_group makes a group (you join it as its admin unless you name another); update_group changes any group\'s name, notice, members, admin, reply mode, or the folder every member works in there; post_to_group posts into any group as you, which starts a round of replies the user reads there; delete_group archives a group, only when the user asks. list_bots shows every group.', diff --git a/ds-bot/src/host/tools.js b/ds-bot/src/host/tools.js index da3bd8252c..21a92a784e 100644 --- a/ds-bot/src/host/tools.js +++ b/ds-bot/src/host/tools.js @@ -665,6 +665,39 @@ export function install(rt) { }, })) + ctx.tools.register(defineTool({ + name: 'void_question', + description: 'Main Bot only. Withdraw the question card another Bot left open for the user, when it no longer applies. The card leaves the screen, a late click on it is refused, and the Bot is told in a new turn.', + parameters: { + bot: { type: 'string', required: true, description: 'Exact Bot name from list_bots' }, + reason: { type: 'string', description: 'Why it was voided; the Bot reads this' }, + }, + output, + async execute(args, exec) { + await rt.load() + const sender = callerBot(exec) + if (sender === undefined || !rt.isMain(sender.id)) refuse('Only a Main Bot can void a question.') + const target = rt.findBot(args.bot) + if (target === undefined) refuse(`No Bot named ${args.bot}. Team: ${Object.values(state.bots).map(bot => bot.name).join(', ')}`) + const chat = rt.chatOf(target.id) + const question = rt.own(state.questions, chat) + if (question === undefined) refuse(`${target.name} has no open question.`) + delete state.questions[chat] + await rt.save() + if (target.id === sender.id) return 'Your question is voided.' + const why = String(args.reason ?? '').trim() + const text = `Your question "${question.question}" is withdrawn, so no answer to it will reach you. Do not act on it.${why ? ` +Reason: ${why}` : ''}` + try { + await rt.deliver({ fromId: sender.id, toId: target.id, text, role: 'voided', ...callerRoom(exec) }) + } catch (error) { + rt.warn('ds-bot: telling %s its question was voided failed: %s', target.name, error) + return `The question of ${target.name} is voided, but ${target.name} could not be told. Tell it with message_bot.` + } + return `The question of ${target.name} is voided and it has been told.` + }, + })) + // Scoped per Bot session, not global: another plugin's global show_view serves // the sessions ds-bot does not own, while this one shadows it inside them. const showViewTool = defineTool({ diff --git a/ds-bot/src/host/turns.js b/ds-bot/src/host/turns.js index a7106b52f4..268c1451fd 100644 --- a/ds-bot/src/host/turns.js +++ b/ds-bot/src/host/turns.js @@ -131,7 +131,7 @@ export function install(rt) { /** @type {Record} */ let activity = {} const activityOf = (tool) => { - if (/^(message_bot|stop_bot|create_bot|update_bot|create_group|update_group|delete_group|post_to_group)$/.test(tool)) return 'sending' + if (/^(message_bot|stop_bot|void_question|create_bot|update_bot|create_group|update_group|delete_group|post_to_group)$/.test(tool)) return 'sending' if (tool === 'group_relay') return 'orbit' if (/search|fetch|browse|browser|read|grep|glob|list/i.test(tool)) return 'searching' return 'working' @@ -408,6 +408,7 @@ export function install(rt) { entry.joined = [] entry.later = [] entry.steeredAt = undefined + entry.card = state.questions[id]?.id if (entry.pending !== undefined) { claimTrigger(id, entry, entry.pending) entry.pending = undefined @@ -539,6 +540,7 @@ export function install(rt) { case 'turn/end': { setActivity(id, undefined) const info = entry.info + const turn = entry.turn const joined = entry.joined ?? [] // What the group already saw of the turn is not posted again. const texts = entry.texts.slice(entry.shown) @@ -561,6 +563,8 @@ export function install(rt) { entry.lastCalled = undefined const later = entry.later ?? [] entry.later = [] + const card = entry.card + entry.card = undefined for (const result of later) { void rt.deliver({ fromId: result.info.senderSessionId, @@ -586,6 +590,16 @@ export function install(rt) { const wroteCall = failure === undefined && reason?.kind === 'completed' && lastCalled !== true && writesToolCall(lastText) const retry = wroteCall && info?.retried !== true && !(info?.role === 'room' && stoppedRoomTurns.has(info.exchangeId)) if (retry) void retryWrittenCall(id, info).catch(error => rt.warn('ds-bot: asking %s to run its written tool call failed: %s', id, error)) + // A finished turn the user could see that asked nothing has moved on, so the card + // it left standing is stale. `card` is the card this turn opened on: a turn that + // asked has another id, or none here at all. A hidden Bot-to-Bot turn shows the user + // nothing, so its card still waits for them. A fresh part's handoff turn carries its + // card over; a failed or stopped turn said nothing about it. + const hidden = (state.exchangeTurns[id] ?? []).includes(turn) + if (card !== undefined && state.questions[id]?.id === card && reason?.kind === 'completed' && !retry && !hidden && info?.handoff !== true) { + delete state.questions[id] + void rt.save().catch(() => {}) + } const replyText = () => { const reply = (wroteCall ? texts.map(stripWrittenCalls) : texts).join('\n\n').trim() return wroteCall && reply === '' ? 'Tried to run a tool but wrote the call as text, so it did not run.' : reply diff --git a/ds-bot/test/install.test.js b/ds-bot/test/install.test.js index 172aa4c1bd..4e34878c79 100644 --- a/ds-bot/test/install.test.js +++ b/ds-bot/test/install.test.js @@ -58,6 +58,7 @@ test('apply registers listeners, tools, and effects in a fixed order', (t) => { 'tool delete_group', 'tool post_to_group', 'tool ask_user', + 'tool void_question', // show_view is scoped per Bot agent, not a global registration. 'tools guard', diff --git a/ds-bot/test/question-lifecycle.test.js b/ds-bot/test/question-lifecycle.test.js new file mode 100644 index 0000000000..ce18df2d62 --- /dev/null +++ b/ds-bot/test/question-lifecycle.test.js @@ -0,0 +1,271 @@ +// How a question card ends: answered, overtaken by a finished turn the user can see that +// asks nothing, or voided by a Main Bot. Whatever ended it, a late click is refused. +import assert from 'node:assert/strict' +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { test } from 'node:test' +import { apply } from '../index.js' +import { fakeContext } from './fake-ctx.js' + +function team() { + return { + version: 1, + mainBotIds: ['a'], + bots: { + a: { id: 'a', name: 'Chief', role: 'Boss', sessionId: 'a', createdAt: 1 }, + b: { id: 'b', name: 'Writer', role: 'Write', sessionId: 'b', createdAt: 2 }, + c: { id: 'c', name: 'Scout', role: 'Find', sessionId: 'c', createdAt: 3 }, + }, + rooms: {}, + agents: {}, + exchanges: [], + exchangeTurns: {}, + questions: {}, + prefs: {}, + revision: 0, + } +} + +async function start() { + const home = mkdtempSync(join(tmpdir(), 'ds-bot-questions-')) + writeFileSync(join(home, 'state.json'), JSON.stringify(team())) + const ctx = fakeContext() + const agents = new Map() + const agentOf = (sessionId) => { + if (!agents.has(sessionId)) { + const calls = [] + agents.set(sessionId, { + session: { id: sessionId, requestHeader: () => undefined }, + id: sessionId, + calls, + status: 'idle', + followup(message) { calls.push(['followup', message]) }, + steer(message) { calls.push(['steer', message]) }, + inject() {}, + cancel() {}, + async whenIdle() {}, + async runMaintenance(fn) { return fn(AbortSignal.timeout(60_000)) }, + inbox: { nextStep: [], nextTurn: [], remove: () => false }, + }) + } + return agents.get(sessionId) + } + Object.assign(ctx, { + llm: { listProviders: () => [], listModels: async () => [], resolveModelInfo: async () => ({}) }, + workspaceRegistry: { + get: () => undefined, + resolveByPath: async () => undefined, + create: async path => ({ id: 'w1', path }), + archiveSession: async () => {}, + }, + sessionController: { + create: async () => ({ sessionId: 's1' }), + resolveAgent: async sessionId => ({ agent: agentOf(sessionId) }), + selectModel: async () => {}, + page: async () => ({ records: [], hasMore: false }), + }, + sessionTitle: { rename: async () => {} }, + sessions: { flush: async () => {} }, + }) + let route + const register = ctx.connection.fetch.register + ctx.connection.fetch.register = (options) => { + route = options + return register(options) + } + apply(ctx, { home }) + let seq = 0 + const emit = (id, type, data) => { + for (const listener of ctx.listeners.get('session/event') ?? []) { + if (listener.length >= 2) listener({ id }, { type, seq: ++seq, data }) + } + } + const tool = (name, args, sessionId) => ctx.registeredTools.get(name).execute(args, { agent: { id: sessionId }, callId: 'call-1', concludeTurn() {} }) + const call = async (endpoint, payload) => (await route.fetch(new Request('http://localhost/api/bot', { + method: 'POST', body: JSON.stringify({ endpoint, payload }), + }))).json() + const pending = async sessionId => (await call('state', {})).value.questions[sessionId] + const stop = async () => { + await ctx.dispose() + rmSync(home, { recursive: true, force: true, maxRetries: 5 }) + } + await tool('list_bots', {}, 'a') + return { ctx, agentOf, emit, tool, call, pending, stop } +} + +const card = { question: 'Which one?', options: [{ label: 'Left' }, { label: 'Right' }] } + +// One turn of the Bot: it may call `during`, then ends for `reason`. +async function turn(team, id, number, during, reason = { kind: 'completed' }) { + team.emit(id, 'turn/start', { turn: number }) + await during?.() + team.emit(id, 'assistant/message', { message: { content: [{ type: 'text', text: 'Done.' }] } }) + team.emit(id, 'turn/end', { turn: number, reason }) +} + +// One turn another Bot started, on the message delivery really handed over. +async function botTurn(team, id, number, args) { + await team.tool('message_bot', args, 'a') + const [, message] = team.agentOf(id).calls.at(-1) + team.emit(id, 'turn/start', { turn: number }) + team.emit(id, 'user/message', { content: message.content, source: message.source }) + team.emit(id, 'assistant/message', { message: { content: [{ type: 'text', text: 'Done.' }] } }) + team.emit(id, 'turn/end', { turn: number, reason: { kind: 'completed' } }) +} + +test('the turn that asks keeps its card', async (t) => { + const team = await start() + t.after(team.stop) + await turn(team, 'b', 1, () => team.tool('ask_user', card, 'b')) + assert.equal((await team.pending('b')).question, 'Which one?') +}) + +test('a card followed by a plain turn leaves nothing pending', async (t) => { + const team = await start() + t.after(team.stop) + await turn(team, 'b', 1, () => team.tool('ask_user', card, 'b')) + await turn(team, 'b', 2) + assert.equal(await team.pending('b'), undefined) +}) + +test('a hidden Bot-to-Bot turn leaves a waiting card for the user, who can still answer it', async (t) => { + const team = await start() + t.after(team.stop) + await turn(team, 'b', 1, () => team.tool('ask_user', card, 'b')) + const { id } = await team.pending('b') + await botTurn(team, 'b', 2, { to: 'Writer', message: 'Status?' }) + const waiting = await team.pending('b') + assert.equal(waiting?.id, id) + const answered = await team.call('answer-question', { sessionId: 'b', questionId: id, answer: { selected: ['Left'] } }) + assert.equal(answered.ok, true) +}) + +test('a card that outlived a hidden turn closes at the next turn the user sees', async (t) => { + const team = await start() + t.after(team.stop) + await turn(team, 'b', 1, () => team.tool('ask_user', card, 'b')) + await botTurn(team, 'b', 2, { to: 'Writer', message: 'Status?' }) + await turn(team, 'b', 3) + assert.equal(await team.pending('b'), undefined) +}) + +test('a Bot-started turn that answers the user in its own chat clears the card', async (t) => { + const team = await start() + t.after(team.stop) + await turn(team, 'b', 1, () => team.tool('ask_user', card, 'b')) + await botTurn(team, 'b', 2, { to: 'Writer', message: 'Say hello.', reply_to: 'user' }) + assert.equal(await team.pending('b'), undefined) +}) + +test('a turn that asks again leaves only its own card', async (t) => { + const team = await start() + t.after(team.stop) + await turn(team, 'b', 1, () => team.tool('ask_user', card, 'b')) + const first = await team.pending('b') + await turn(team, 'b', 2, () => team.tool('ask_user', { ...card, question: 'And now?' }, 'b')) + const second = await team.pending('b') + assert.notEqual(second.id, first.id) + assert.equal(second.question, 'And now?') +}) + +test('a turn that failed or was stopped asked nothing, so the card stays', async (t) => { + const team = await start() + t.after(team.stop) + await turn(team, 'b', 1, () => team.tool('ask_user', card, 'b')) + await turn(team, 'b', 2, undefined, { kind: 'aborted' }) + assert.notEqual(await team.pending('b'), undefined) + await turn(team, 'b', 3, undefined, { kind: 'error', error: { code: 'NETWORK', message: 'down' } }) + assert.notEqual(await team.pending('b'), undefined) +}) + +test('the handoff turn of a fresh part keeps the card it carried over', async (t) => { + const team = await start() + t.after(team.stop) + await turn(team, 'b', 1, () => team.tool('ask_user', card, 'b')) + team.emit('b', 'turn/start', { turn: 2 }) + team.emit('b', 'user/message', { content: [{ type: 'text', text: 'note' }], source: { kind: 'bot', role: 'handoff', handoff: true } }) + team.emit('b', 'turn/end', { turn: 2, reason: { kind: 'completed' } }) + assert.notEqual(await team.pending('b'), undefined) +}) + +test('a card followed by a Main Bot void leaves nothing pending, and the Bot is told', async (t) => { + const team = await start() + t.after(team.stop) + await turn(team, 'b', 1, () => team.tool('ask_user', card, 'b')) + const said = await team.tool('void_question', { bot: 'Writer', reason: 'Steve changed his mind' }, 'a') + assert.match(said, /Writer/) + assert.equal(await team.pending('b'), undefined) + const [kind, message] = team.agentOf('b').calls.at(-1) + assert.equal(kind, 'followup') + assert.equal(message.source.role, 'voided') + const text = message.content.map(block => block.text).join('\n') + assert.match(text, /Question voided by Chief/) + assert.match(text, /Which one\?/) + assert.match(text, /Steve changed his mind/) +}) + +test('voiding belongs to a Main Bot', async (t) => { + const team = await start() + t.after(team.stop) + await turn(team, 'b', 1, () => team.tool('ask_user', card, 'b')) + await assert.rejects(team.tool('void_question', { bot: 'Writer' }, 'c'), { message: 'Only a Main Bot can void a question.' }) + assert.notEqual(await team.pending('b'), undefined) +}) + +test('voiding says so when the Bot has no open question', async (t) => { + const team = await start() + t.after(team.stop) + await assert.rejects(team.tool('void_question', { bot: 'Writer' }, 'a'), { message: 'Writer has no open question.' }) + await assert.rejects(team.tool('void_question', { bot: 'Nobody' }, 'a'), /No Bot named Nobody/) +}) + +test('a void reaches the card even when telling the Bot fails', async (t) => { + const team = await start() + t.after(team.stop) + await turn(team, 'b', 1, () => team.tool('ask_user', card, 'b')) + team.agentOf('b').followup = () => { throw new Error('Session gone') } + const said = await team.tool('void_question', { bot: 'Writer' }, 'a') + assert.match(said, /could not be told/) + assert.equal(await team.pending('b'), undefined) +}) + +test('a late answer to a voided card is refused and reaches nobody', async (t) => { + const team = await start() + t.after(team.stop) + await turn(team, 'b', 1, () => team.tool('ask_user', card, 'b')) + const { id } = await team.pending('b') + await team.tool('void_question', { bot: 'Writer' }, 'a') + const before = team.agentOf('b').calls.length + const late = await team.call('answer-question', { sessionId: 'b', questionId: id, answer: { selected: ['Left'] } }) + assert.equal(late.ok, false) + assert.equal(late.error.code, 'bot/stale') + assert.equal(team.agentOf('b').calls.length, before) +}) + +test('a late answer to a card a plain turn cleared is refused and reaches nobody', async (t) => { + const team = await start() + t.after(team.stop) + await turn(team, 'b', 1, () => team.tool('ask_user', card, 'b')) + const { id } = await team.pending('b') + await turn(team, 'b', 2) + const late = await team.call('answer-question', { sessionId: 'b', questionId: id, answer: { selected: ['Left'] } }) + assert.equal(late.ok, false) + assert.equal(late.error.code, 'bot/stale') + assert.deepEqual(team.agentOf('b').calls, []) +}) + +test('a normal card answered by the user behaves as it always did', async (t) => { + const team = await start() + t.after(team.stop) + await turn(team, 'b', 1, () => team.tool('ask_user', card, 'b')) + const { id } = await team.pending('b') + const answered = await team.call('answer-question', { sessionId: 'b', questionId: id, answer: { selected: ['Left'] } }) + assert.equal(answered.ok, true) + assert.equal(await team.pending('b'), undefined) + const [kind, message] = team.agentOf('b').calls.at(-1) + assert.equal(kind, 'followup') + assert.equal(message.source.kind, 'user-question-reply') + const twice = await team.call('answer-question', { sessionId: 'b', questionId: id, answer: { selected: ['Left'] } }) + assert.equal(twice.error.code, 'bot/stale') +})