From 56b35f038a06a8896c7818d16042d27459b4e7bc Mon Sep 17 00:00:00 2001 From: Evander Date: Fri, 4 Dec 2026 04:27:46 -0500 Subject: [PATCH] =?UTF-8?q?fix(minimax-bot):=20=E9=87=8D=E5=90=AF=E6=81=A2?= =?UTF-8?q?=E5=A4=8D=E6=8C=89=E5=9B=9E=E5=A4=8D=E8=87=AA=E5=B7=B1=E7=9A=84?= =?UTF-8?q?=E7=8A=B6=E6=80=81=E5=88=A4=E6=8A=95=E9=80=92=EF=BC=8C=E4=B8=8E?= =?UTF-8?q?=E6=B4=BB=E8=B7=AF=E5=BE=84=E8=AF=BB=E5=90=8C=E4=B8=80=E5=A5=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 请求在回合开始前被标成 processing。如果进程在回复已经落盘、但 inbox 还没写下 投递结果时退出,重启恢复只看「有没有关联回复」,有就标成 uncertain,不看回复 到底是什么状态。于是一条已经正常完成的回复也会把请求标成待确认,后续消息被这个 uncertain 闸门挡住,永远停在 held。 判据统一到 miniapp/node/delivery.mjs,恢复路径、重试路径和活路径的 safeToContinue 读同一份(CLEAN_FAILURE_CODES 只有一处定义): - 回复 status 是 done / pass -> delivered。pass 是 Bot 明确表示没有补充, 那一轮结束了,活路径写的也是 delivered。 - 回复 status 是 error / interrupted -> uncertain。宿主可能已经接手才失败的, 没人能说清有没有答过,后续消息继续等。 - 回复带 retryInput 且失败码在宿主背书的那张表里(BUSY / NOT_PERMITTED / INVALID_ARGUMENTS / AGENT_UNAVAILABLE / SESSION_NOT_FOUND)-> failed。 retryInput 只是必要条件不是充分条件:ETIMEDOUT 这类不在表里的, 那一轮可能已经跑了,只能判 uncertain。 - 没有回复 -> pending。 同一请求上有多条回复时,未知优先于已送达:一条没人能背书的回复就足以把请求 按住,不能因为另一条 done 就先标 delivered。 实测(改前):processing + error/ETIMEDOUT 被标成 delivered, processing + 无回复 也被标成 delivered。改后分别回到 uncertain 和 pending。 测试五条:完成回复 delivers 后续能跑;失败回复 uncertain 后续继续等;带 retryInput 的失败可重发;带 retryInput 的 ETIMEDOUT 仍是 uncertain; done 与未知回复并存时是 uncertain。全量测试通过。 版本号 0.7.46。 --- .../minimax-bot/.minimax-plugin/plugin.json | 2 +- plugins/minimax-ai/minimax-bot/README.md | 8 + .../minimax-bot/miniapp/node/delivery.mjs | 115 ++++++++++++ .../minimax-bot/miniapp/node/engine.mjs | 8 +- .../minimax-bot/miniapp/node/mcp.mjs | 2 +- .../minimax-bot/miniapp/node/store.mjs | 10 +- .../minimax-bot/miniapp/node/user-inbox.mjs | 4 +- plugins/minimax-ai/minimax-bot/package.json | 2 +- .../tests/engine-reliability.test.mjs | 165 ++++++++++++++++++ 9 files changed, 305 insertions(+), 11 deletions(-) create mode 100644 plugins/minimax-ai/minimax-bot/miniapp/node/delivery.mjs diff --git a/plugins/minimax-ai/minimax-bot/.minimax-plugin/plugin.json b/plugins/minimax-ai/minimax-bot/.minimax-plugin/plugin.json index 5f3402c7..67ce19d7 100644 --- a/plugins/minimax-ai/minimax-bot/.minimax-plugin/plugin.json +++ b/plugins/minimax-ai/minimax-bot/.minimax-plugin/plugin.json @@ -2,7 +2,7 @@ "schemaVersion": 1, "name": "minimax-bot", "displayName": "MiniMax Bot", - "version": "0.7.42", + "version": "0.7.46", "description": "Turn MiniMax Code into an always-on team of Bots. A Chief Bot helps you build the team; in group chats the admin answers and @mentions hand work to other members. Every Bot has its own octopus avatar and memory, with scheduled tasks and usage stats.", "author": "MiniMax Code", "icon": "icon.png", diff --git a/plugins/minimax-ai/minimax-bot/README.md b/plugins/minimax-ai/minimax-bot/README.md index 81de93e3..09862ada 100644 --- a/plugins/minimax-ai/minimax-bot/README.md +++ b/plugins/minimax-ai/minimax-bot/README.md @@ -181,6 +181,14 @@ The hand-over between two Bots of a group carried the tail of the previous reply - `brief.tool.schedule` answers the other half of the same question. A user who asks whether something is running on a timer, or why their usage keeps going, gets an answer from `list_schedules`, and `delete_schedule` stops it. The line also states the limit: only this team's scheduled tasks are in that list. A schedule the Host runs elsewhere is not in it and is not under the Bot's control — a cron attached to a session from the host side showed as zero rows in the Bot's own list while it kept spending the session's quota. - Only the wording changed. No tool, no state and no limit moved: the same calls with the same arguments do the same things. +## 0.7.46 A finished reply is not left uncertain after a restart + +- A request is marked `processing` before its turn runs. If the process stops after the reply is written but before the inbox writes the delivery verdict, restart used to see the reply and mark the request `uncertain` — without looking at the reply's status. A finished reply therefore left the chat held, and every later request waited behind it. +- Restart recovery now reads the reply's own status, and it decides the same way the live path does. A reply that finished — or that only passed, which is a finished turn with nothing to add — means the request was delivered. A reply that failed after the Host had taken the turn means nobody can say whether it was answered, so it stays uncertain and the later requests wait. A reply that failed before the Host took the turn at all carries the words to send again, so the request stays the user's to send, and no reply still means it never reached the Host. +- A failure the Host vouches for is the exception: the turn certainly did not happen. Those are the codes the live path lets the chat continue after, and the recovery reads the same list. A timeout is not one of them — the turn may have run anyway — so a timed-out reply leaves the request uncertain even when it carries the words to send again. +- When one request has several replies, a reply nobody can vouch for decides: the request may not be called delivered while a turn of it is unaccounted for. +- The rules live in exported predicates, so the retry path and restart recovery cannot drift apart again. + ## 0.7.10 Optional group notes - A group can keep a note of what it said. After every round the group records the closing lines of the replies, and every Bot of the group gets that record in its standing brief. diff --git a/plugins/minimax-ai/minimax-bot/miniapp/node/delivery.mjs b/plugins/minimax-ai/minimax-bot/miniapp/node/delivery.mjs new file mode 100644 index 00000000..5e79236a --- /dev/null +++ b/plugins/minimax-ai/minimax-bot/miniapp/node/delivery.mjs @@ -0,0 +1,115 @@ +// @ts-check + +/** + * The failure codes the Host vouches for: the turn certainly did not happen, so the chat may go + * on and the request stays the user's to send again. + * + * The live path and the restart recovery read the same list, so a failure one of them calls + * clean is clean for the other as well. + */ +export const CLEAN_FAILURE_CODES = new Set([ + 'BUSY', 'NOT_PERMITTED', 'INVALID_ARGUMENTS', 'AGENT_UNAVAILABLE', 'SESSION_NOT_FOUND', +]); + +/** + * A reply nobody can vouch for. + * + * The Host may have taken the turn before it failed, so nobody can say whether the request was + * answered. A reply that never finished is such a reply, and so is a failure the Host does not + * vouch for: a timeout says the turn may have run, while the codes in `CLEAN_FAILURE_CODES` say + * it did not. + * + * @param {any} reply + * @returns {boolean} + */ +export function replyOutcomeUnknown(reply) { + return replyDeliveryState(reply) === 'uncertain'; +} + +/** + * A reply that answers the request: the turn finished and it produced an answer. + * + * A reply that failed is not one — the Host may have taken the turn before the failure, so the + * outcome is unknown and the request must not be declared delivered. A pass is one: the Bot + * finished the turn and had nothing to add, which is what the live path records as delivered. + * + * @param {any} reply + * @returns {boolean} + */ +export function replyDelivered(reply) { + return reply?.status === 'done' || reply?.status === 'pass'; +} + +/** + * A reply that failed before the Host ever took the turn: the work was never done, so the + * request is still the user's to send again. + * + * The reply carries the words to resend only when the Host never took the turn, so its presence + * is the proof. A reply that never reached a session says the same thing: a thrown failure has + * no session unless the Host had already started the turn. + * + * @param {any} reply + * @returns {boolean} + */ +export function replyNeverReachedHost(reply) { + if (reply?.status !== 'error') return false; + if (!CLEAN_FAILURE_CODES.has(reply?.errorCode)) return false; + if (typeof reply?.retryInput === 'string' && reply.retryInput.length > 0) return true; + return !reply?.sessionId; +} + +/** + * The state a user's line carries after a turn. + * + * The live path writes this onto the line; the restart recovery arrives at the same state by + * reading the replies of that turn. + * + * @param {{errorCode?: string, safeToContinue?: boolean, pendingQuestion?: boolean, skipped?: boolean, accepted?: boolean} | undefined} result + * @returns {'uncertain' | 'cancelled' | 'delivered' | 'failed'} + */ +export function deliveryState(result) { + if (result?.errorCode === 'AGENT_OUTCOME_UNKNOWN' || (result?.safeToContinue === false && !result?.pendingQuestion)) { + return 'uncertain'; + } + if (result?.skipped) return 'cancelled'; + if (result?.accepted) return 'delivered'; + return 'failed'; +} + +/** + * What one reply says about the request it answers. + * + * The live path writes the same states onto the user's line when the turn ends; the restart + * recovery reads them off the reply, because the reply is written before that verdict lands and + * a process that stops in between leaves the request in flight. + * + * @param {any} reply + * @returns {'delivered' | 'uncertain' | 'failed' | 'cancelled'} + */ +export function replyDeliveryState(reply) { + // The Host answered with an error of its own: the turn happened and the answer was a failure. + // The request was delivered, which is what the live path records for it. + if (reply?.status === 'error' && reply?.errorReason !== undefined) return 'delivered'; + if (replyDelivered(reply)) return 'delivered'; + // The turn was dropped before it reached the Agent: nobody was asked anything. + if (reply?.status === 'aborted') return 'cancelled'; + if (replyNeverReachedHost(reply)) return 'failed'; + return 'uncertain'; +} + +/** + * What several replies say about one request. + * + * An unknown outcome outranks the rest: one reply nobody can vouch for is enough to hold the + * request back, even when another reply says the turn finished. + * + * @param {Array<'delivered' | 'uncertain' | 'failed' | 'cancelled'>} states + * @returns {'delivered' | 'uncertain' | 'failed' | 'cancelled' | 'pending'} + */ +export function mergeDeliveryStates(states) { + if (states.includes('uncertain')) return 'uncertain'; + if (states.includes('delivered')) return 'delivered'; + if (states.includes('failed')) return 'failed'; + if (states.includes('cancelled')) return 'cancelled'; + return 'pending'; +} diff --git a/plugins/minimax-ai/minimax-bot/miniapp/node/engine.mjs b/plugins/minimax-ai/minimax-bot/miniapp/node/engine.mjs index 4ba1e30b..de7317b5 100644 --- a/plugins/minimax-ai/minimax-bot/miniapp/node/engine.mjs +++ b/plugins/minimax-ai/minimax-bot/miniapp/node/engine.mjs @@ -8,6 +8,7 @@ import { MemoryError, storageBudget } from './memory.mjs'; import { selectMemoryContext } from './memory-context.mjs'; import { UserInbox } from './user-inbox.mjs'; import { TaskDispatcher } from './task-dispatcher.mjs'; +import { CLEAN_FAILURE_CODES, replyOutcomeUnknown } from './delivery.mjs'; import { modelKey, newId, withEffort } from './store.mjs'; import { CONVERGE_MARK, CONTEXT_BLOCK_END, CONTEXT_BLOCK_MARK, handoverRequested, handoverSummary, hopLimit, neutralizeMarks, renderHandover, roundEntries } from './relay-guard.mjs'; import { appendNote, notesEnabled, renderNote } from './group-note.mjs'; @@ -928,9 +929,7 @@ export class Engine { toolCount: tools, accepted: reachedHost || Boolean(result && !result.skipped), // A returned terminal result is known; exceptions after admission may have lost observation. - safeToContinue: Boolean(result && !result.pendingQuestion) || (!reachedHost && (!invoked || [ - 'BUSY', 'NOT_PERMITTED', 'INVALID_ARGUMENTS', 'AGENT_UNAVAILABLE', 'SESSION_NOT_FOUND', - ].includes(failureCode))), + safeToContinue: Boolean(result && !result.pendingQuestion) || (!reachedHost && (!invoked || CLEAN_FAILURE_CODES.has(failureCode))), skipped: Boolean(result?.skipped), // The turn ended waiting for the user: its text is not the Bot's final answer. pendingQuestion: Boolean(result?.pendingQuestion), @@ -1187,8 +1186,7 @@ export class Engine { if (fingerprint !== request.fingerprint) throw new EngineError('invalid', t('err.messageIdConflict')); const admitted = this.inbox.has(existing.id) || [...this.tickets].some((ticket) => ticket.chatId === chatId && ticket.sourceMessageId === existing.id); const replies = messages.filter((message) => message.sourceMessageId === existing.id || message.sourceMessageIds?.includes(existing.id)); - if (!admitted && (existing.dispatchState === 'uncertain' || replies.some((message) => - message.status === 'interrupted' || message.status === 'streaming' || message.errorCode === 'AGENT_OUTCOME_UNKNOWN'))) { + if (!admitted && (existing.dispatchState === 'uncertain' || replies.some(replyOutcomeUnknown))) { await this.store.updateMessage(chatId, existing.id, { dispatchState: 'uncertain' }); this.broadcast({ type: 'message.upsert', chatId, message: existing }); throw new EngineError('delivery_uncertain', t('err.messageDeliveryUncertain')); diff --git a/plugins/minimax-ai/minimax-bot/miniapp/node/mcp.mjs b/plugins/minimax-ai/minimax-bot/miniapp/node/mcp.mjs index 63e7bd6d..2959b5ff 100644 --- a/plugins/minimax-ai/minimax-bot/miniapp/node/mcp.mjs +++ b/plugins/minimax-ai/minimax-bot/miniapp/node/mcp.mjs @@ -662,7 +662,7 @@ export function createMcpHandler({ team, engine }) { result = { protocolVersion: PROTOCOL_VERSIONS.includes(requested) ? requested : PROTOCOL_VERSIONS[0], capabilities: { tools: { listChanged: false } }, - serverInfo: { name: 'minimax-bot', version: '0.7.42' }, + serverInfo: { name: 'minimax-bot', version: '0.7.46' }, instructions: t('mcp.instructions'), }; break; diff --git a/plugins/minimax-ai/minimax-bot/miniapp/node/store.mjs b/plugins/minimax-ai/minimax-bot/miniapp/node/store.mjs index be21039d..0c48cc7e 100644 --- a/plugins/minimax-ai/minimax-bot/miniapp/node/store.mjs +++ b/plugins/minimax-ai/minimax-bot/miniapp/node/store.mjs @@ -4,11 +4,13 @@ import { appendFile, copyFile, mkdir, open, readFile, rename, rm } from 'node:fs import { basename, dirname, join } from 'node:path'; import { userReaction } from '../client/emoji-data.js'; +import { mergeDeliveryStates, replyDeliveryState } from './delivery.mjs'; import { resolveLocale, setLocale, t } from './i18n.mjs'; import { ReactionError, validateReaction } from './reactions.mjs'; export const DEFAULT_MESSAGE_PAGE_SIZE = 100; export const MAX_MESSAGE_PAGE_SIZE = 500; + /** Octopus gradient palettes; the client owns the actual colors. */ export const BOT_COLORS = [ 'ocean', 'sky', 'teal', 'green', 'lime', 'yellow', 'orange', 'red', 'pink', 'violet', 'indigo', 'graphite', @@ -511,8 +513,14 @@ export class Store { } } if (message.role === 'user' && ['adjusting', 'processing'].includes(message.dispatchState)) { + const replies = list.filter((reply) => reply.sourceMessageId === message.id || reply.sourceMessageIds?.includes(message.id)); + // The reply is written before the inbox writes the verdict onto the user's line, so a + // process that stops in between leaves the request in flight. The replies say what the + // turn was: one that finished proves the request was delivered, one nobody can vouch for + // leaves it undecided, and one that failed before the Host took the turn means the work + // was never done, so the request is still the user's to send again. message.dispatchState = message.dispatchState === 'adjusting' ? 'held' - : list.some((reply) => reply.sourceMessageId === message.id || reply.sourceMessageIds?.includes(message.id)) ? 'uncertain' : 'pending'; + : mergeDeliveryStates(replies.map(replyDeliveryState)); message.dispatchRevision = (message.dispatchRevision ?? 0) + 1; dirty = true; } diff --git a/plugins/minimax-ai/minimax-bot/miniapp/node/user-inbox.mjs b/plugins/minimax-ai/minimax-bot/miniapp/node/user-inbox.mjs index e9eac1d0..88f83a60 100644 --- a/plugins/minimax-ai/minimax-bot/miniapp/node/user-inbox.mjs +++ b/plugins/minimax-ai/minimax-bot/miniapp/node/user-inbox.mjs @@ -1,4 +1,5 @@ // @ts-check +import { deliveryState } from './delivery.mjs'; import { t } from './i18n.mjs'; const MAX_BATCH_CHARS = 60000; @@ -75,8 +76,7 @@ export class UserInbox { return { safeToContinue: true, accepted: false }; } const result = await this.engine.runUserBatch(batch); - await this.setDeliveryState(batch, result?.errorCode === 'AGENT_OUTCOME_UNKNOWN' || (result?.safeToContinue === false && !result?.pendingQuestion) - ? 'uncertain' : result?.skipped ? 'cancelled' : result?.accepted ? 'delivered' : 'failed'); + await this.setDeliveryState(batch, deliveryState(result)); if (result?.safeToContinue === false || result?.pendingQuestion) { // Pending supplements must not silently bypass an unresolved turn or questionnaire. for (const next of this.batches) if (next.chatId === chatId && !next.started) await this.setDeliveryState(next, 'held'); diff --git a/plugins/minimax-ai/minimax-bot/package.json b/plugins/minimax-ai/minimax-bot/package.json index 56a3a5ed..dc9df08e 100644 --- a/plugins/minimax-ai/minimax-bot/package.json +++ b/plugins/minimax-ai/minimax-bot/package.json @@ -1,6 +1,6 @@ { "name": "minimax-bot", - "version": "0.7.42", + "version": "0.7.46", "private": true, "type": "module", "mcode": { diff --git a/plugins/minimax-ai/minimax-bot/tests/engine-reliability.test.mjs b/plugins/minimax-ai/minimax-bot/tests/engine-reliability.test.mjs index c7e82e3b..852324ba 100644 --- a/plugins/minimax-ai/minimax-bot/tests/engine-reliability.test.mjs +++ b/plugins/minimax-ai/minimax-bot/tests/engine-reliability.test.mjs @@ -648,6 +648,171 @@ test('an interrupted associated assistant is reported as uncertain, and legacy m await restored.writeChain; }); +test('a finished associated assistant is delivered after restart, so later requests run', async (t) => { + const { dir, store, memory, engine } = await fixture(t); + const bot = store.state.bots[0]; + const chatId = `bot:${bot.id}`; + const user = await store.appendMessage(chatId, { + role: 'user', text: 'Finish this', clientMessageId: 'finished-1', + clientMessageHash: engine.userMessageFingerprint('Finish this', []), dispatchState: 'processing', + }); + await store.appendMessage(chatId, { + role: 'bot', botId: bot.id, sourceMessageId: user.id, status: 'done', text: 'Finished answer', + }); + await store.writeChain; + engine.dispose(); + + // The process died after the reply was written but before the inbox could mark the request + // delivered. The finished reply is proof that the request made it to the Host. + const restored = new Store(dir); + await restored.init(); + assert.equal((await restored.getMessages(chatId)).find((message) => message.id === user.id).dispatchState, 'delivered'); + + let runs = 0; + const reopened = new Engine({ store: restored, memory, logger: { warn() {} }, broadcast() {}, agent: { + async run(input, options) { runs += 1; return { ...started(input, options, 'after-finished'), status: 'finished', text: 'Later answer' }; }, + } }); + await reopened.sendUserMessage(chatId, 'A later request', [], 'later-1'); + await until(() => idle(reopened)); + assert.equal(runs, 1, 'the later request is not held behind a finished turn'); + assert.equal((await restored.getMessages(chatId)).find((message) => message.text === 'A later request').dispatchState, 'delivered'); + reopened.dispose(); + await restored.writeChain; +}); + +test('a failed associated assistant stays uncertain after restart, so later requests wait', async (t) => { + const { dir, store, memory, engine } = await fixture(t); + const bot = store.state.bots[0]; + const chatId = `bot:${bot.id}`; + const user = await store.appendMessage(chatId, { + role: 'user', text: 'Time out', clientMessageId: 'failed-1', + clientMessageHash: engine.userMessageFingerprint('Time out', []), dispatchState: 'processing', + }); + // The Host took the turn and then it failed. Nobody can say whether it was answered, so the + // request stays uncertain — a reply that failed is not a delivery. + await store.appendMessage(chatId, { + role: 'bot', botId: bot.id, sourceMessageId: user.id, status: 'error', text: '', + errorCode: 'ETIMEDOUT', error: 'The Agent turn timed out.', + }); + await store.writeChain; + engine.dispose(); + + const restored = new Store(dir); + await restored.init(); + assert.equal((await restored.getMessages(chatId)).find((message) => message.id === user.id).dispatchState, 'uncertain'); + + let runs = 0; + const reopened = new Engine({ store: restored, memory, logger: { warn() {} }, broadcast() {}, agent: { + async run(input, options) { runs += 1; return { ...started(input, options, 'after-failed'), status: 'finished', text: 'Later answer' }; }, + } }); + await reopened.sendUserMessage(chatId, 'A later request', [], 'later-2'); + await until(() => idle(reopened)); + assert.equal(runs, 0, 'the later request waits behind the unknown outcome'); + assert.equal((await restored.getMessages(chatId)).find((message) => message.text === 'A later request').dispatchState, 'held'); + reopened.dispose(); + await restored.writeChain; +}); + +test('a reply that failed before the Host took the turn leaves the request sendable', async (t) => { + const { dir, store, memory, engine } = await fixture(t); + const bot = store.state.bots[0]; + const chatId = `bot:${bot.id}`; + const user = await store.appendMessage(chatId, { + role: 'user', text: 'Try again later', clientMessageId: 'never-1', + clientMessageHash: engine.userMessageFingerprint('Try again later', []), dispatchState: 'processing', + }); + // The Host never took the turn, so the reply carries the words to send again. The work was never + // done, so the request is not uncertain — it is the user's to send again. + await store.appendMessage(chatId, { + role: 'bot', botId: bot.id, sourceMessageId: user.id, status: 'error', text: '', + errorCode: 'BUSY', error: 'The Host is busy.', retryable: true, retryInput: 'Try again later', + }); + await store.writeChain; + engine.dispose(); + + const restored = new Store(dir); + await restored.init(); + assert.equal((await restored.getMessages(chatId)).find((message) => message.id === user.id).dispatchState, 'failed'); + + let runs = 0; + const reopened = new Engine({ store: restored, memory, logger: { warn() {} }, broadcast() {}, agent: { + async run(input, options) { runs += 1; return { ...started(input, options, 'after-never'), status: 'finished', text: 'Later answer' }; }, + } }); + await reopened.sendUserMessage(chatId, 'A later request', [], 'later-3'); + await until(() => idle(reopened)); + assert.equal(runs, 1, 'a later request is not held behind work that never started'); + reopened.dispose(); + await restored.writeChain; +}); + +test('a timed-out reply that carries the words to resend still leaves the request uncertain', async (t) => { + const { dir, store, memory, engine } = await fixture(t); + const bot = store.state.bots[0]; + const chatId = `bot:${bot.id}`; + const user = await store.appendMessage(chatId, { + role: 'user', text: 'Time out', clientMessageId: 'timeout-1', + clientMessageHash: engine.userMessageFingerprint('Time out', []), dispatchState: 'processing', + }); + // The Host never took the turn, and the call timed out. The turn may have run anyway, so nobody + // can say whether the request was answered: the live path writes uncertain for this, and the + // recovery has to write the same. + await store.appendMessage(chatId, { + role: 'bot', botId: bot.id, sourceMessageId: user.id, status: 'error', text: '', + errorCode: 'ETIMEDOUT', error: 'The Agent turn timed out.', retryable: true, retryInput: 'Time out', + }); + await store.writeChain; + engine.dispose(); + + const restored = new Store(dir); + await restored.init(); + assert.equal((await restored.getMessages(chatId)).find((message) => message.id === user.id).dispatchState, 'uncertain'); + + let runs = 0; + const reopened = new Engine({ store: restored, memory, logger: { warn() {} }, broadcast() {}, agent: { + async run(input, options) { runs += 1; return { ...started(input, options, 'after-timeout'), status: 'finished', text: 'Later answer' }; }, + } }); + await reopened.sendUserMessage(chatId, 'A later request', [], 'later-4'); + await until(() => idle(reopened)); + assert.equal(runs, 0, 'the later request waits behind the unknown outcome'); + reopened.dispose(); + await restored.writeChain; +}); + +test('a finished reply next to an unknown one leaves the request uncertain', async (t) => { + const { dir, store, memory, engine } = await fixture(t); + const bot = store.state.bots[0]; + const chatId = `bot:${bot.id}`; + const user = await store.appendMessage(chatId, { + role: 'user', text: 'Answer twice', clientMessageId: 'mixed-1', + clientMessageHash: engine.userMessageFingerprint('Answer twice', []), dispatchState: 'processing', + }); + // One reply says the turn finished, the other says nobody can say. The unknown one decides: + // the request may not be declared delivered while a turn of it is unaccounted for. + await store.appendMessage(chatId, { + role: 'bot', botId: bot.id, sourceMessageId: user.id, status: 'done', text: 'One answer', + }); + await store.appendMessage(chatId, { + role: 'bot', botId: bot.id, sourceMessageId: user.id, status: 'error', text: '', + errorCode: 'ETIMEDOUT', error: 'The Agent turn timed out.', + }); + await store.writeChain; + engine.dispose(); + + const restored = new Store(dir); + await restored.init(); + assert.equal((await restored.getMessages(chatId)).find((message) => message.id === user.id).dispatchState, 'uncertain'); + + let runs = 0; + const reopened = new Engine({ store: restored, memory, logger: { warn() {} }, broadcast() {}, agent: { + async run(input, options) { runs += 1; return { ...started(input, options, 'after-mixed'), status: 'finished', text: 'Later answer' }; }, + } }); + await reopened.sendUserMessage(chatId, 'A later request', [], 'later-5'); + await until(() => idle(reopened)); + assert.equal(runs, 0, 'the later request waits behind the unknown outcome'); + reopened.dispose(); + await restored.writeChain; +}); + test('a request whose queue died with the process is still sendable from the page', async (t) => { const { dir, store, memory, engine } = await fixture(t); const bot = store.state.bots[0];