diff --git a/plugins/minimax-ai/minimax-bot/.minimax-plugin/plugin.json b/plugins/minimax-ai/minimax-bot/.minimax-plugin/plugin.json index b6cfa02e..27ecf749 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.30", + "version": "0.7.31", "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 98632125..5e74fbf3 100644 --- a/plugins/minimax-ai/minimax-bot/README.md +++ b/plugins/minimax-ai/minimax-bot/README.md @@ -105,6 +105,12 @@ The hand-over between two Bots of a group carried the tail of the previous reply - Creating a Bot, a group or a scheduled task writes into the live state and then saves it. When that save failed, the new object stayed in memory: the request reported a failure while the Bot, group or task was already there, and the next unrelated save — changing a setting, any other write — published it to disk. After a restart the thing the user was told had failed was in the team. - A failed save now puts the state back: a new object is removed and a changed schedule returns to the values still on disk, so a refusal leaves nothing for a later save to publish. This is the rule `updateBot` already followed; the three create paths now do the same. +## 0.7.31 A request the plugin already accepted is still sendable after a restart + +- MiniMax Code may stop the plugin's Node process while no page is visible, and it does so without a callback. A request that was already accepted and had produced no reply used to come back as waiting for a queue that no longer existed: it stayed in the chat with no answer, the page offered no way to send it again, and the resume route refused it. The request was unreachable for good. +- The page now offers the same **Continue with follow-ups** button for it, and the resume route accepts it, so the request can be sent again. Nothing is replayed on its own: the turn may already have run tools before the process stopped, so sending it again stays the user's decision. +- A request whose reply had already started is unchanged, and a request this page has just sent never offers to resume itself. + ## 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/client/app.js b/plugins/minimax-ai/minimax-bot/miniapp/client/app.js index 35518904..75f2d0e2 100644 --- a/plugins/minimax-ai/minimax-bot/miniapp/client/app.js +++ b/plugins/minimax-ai/minimax-bot/miniapp/client/app.js @@ -248,6 +248,9 @@ function rowMenu(event, chatId) { const ui = {}; const drafts = new Map(); const submissions = new Map(); +// Message ids this page sent in this session. A request the composer just created is `pending` with +// no reply, exactly like one a restart stranded, and only this set tells them apart. +const sentHere = new Set(); let mounted = ''; let mountRevision = 0; let revealRevision = 0; @@ -695,7 +698,9 @@ function presentationKey() { function messageView(message, prev, presentation) { return { key: message.id, - signature: JSON.stringify([message, prev?.ts, presentation, deliveryActions.has(`${message.chatId}:${message.id}`)]), + // `busy` decides whether the delivery line offers a resume, and the message itself does not + // carry it: without it here a busy event would leave the button in place. + signature: JSON.stringify([message, prev?.ts, presentation, deliveryActions.has(`${message.chatId}:${message.id}`), state.busy.has(message.chatId)]), create: () => renderItem(message, prev), update: (node) => renderItem(message, prev, node), }; @@ -792,7 +797,14 @@ function userDelivery(message) { const status = message.dispatchState; if (!status || status === 'processing' || status === 'delivered') return null; const key = `${message.chatId}:${message.id}`; - const button = status === 'held' ? h('button', { + // A restart leaves an accepted request pending with no queue left to send it and nothing running. + // Offer the same resume on the proof the server uses: nothing was ever written back for it. The + // server does not look at `dispatchRevision` either — a request that reached the disk and then + // lost the process before any state change is recoverable too, and it carries no revision. + const stranded = status === 'pending' && !sentHere.has(message.id) && !state.busy.has(message.chatId) + && !(state.messages.get(message.chatId) ?? []).some( + (item) => item.sourceMessageId === message.id || item.sourceMessageIds?.includes(message.id)); + const button = status === 'held' || stranded ? h('button', { type: 'button', class: 'btn sm', disabled: deliveryActions.has(key), onclick: async (event) => { if (deliveryActions.has(key)) return; @@ -1432,7 +1444,10 @@ async function submit() { const stillHere = () => mounted === chatId && ui.input; try { const result = await api('POST', `/api/chats/${chatId}/messages`, { ...body, clientMessageId: submission.clientMessageId }); - if (result.message?.id && result.message.chatId === chatId) upsertMessage(cacheMessage(result.message)); + if (result.message?.id && result.message.chatId === chatId) { + sentHere.add(result.message.id); + upsertMessage(cacheMessage(result.message)); + } submissions.delete(chatId); // A file added while the POST was pending belongs to the next send. const sentKeys = new Set(ready.map((file) => file.key)); @@ -1638,6 +1653,10 @@ function handleEvent(event) { if (mounted) { renderPill(); syncSend(); + // The delivery line depends on whether this chat is busy, and the event that flips it does + // not carry a message: re-render the feed so a resume button disappears the moment the chat + // starts answering, or comes back when it stops. + if (mounted === event.chatId) renderFeed(state.messages.get(event.chatId) ?? [], false); } if (state.drawer.open && state.drawer.view === 'overview') nav.renderDrawer(); break; diff --git a/plugins/minimax-ai/minimax-bot/miniapp/node/mcp.mjs b/plugins/minimax-ai/minimax-bot/miniapp/node/mcp.mjs index 768cfd99..aa693a48 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.30' }, + serverInfo: { name: 'minimax-bot', version: '0.7.31' }, 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 1c93afbd..7eae5c30 100644 --- a/plugins/minimax-ai/minimax-bot/miniapp/node/store.mjs +++ b/plugins/minimax-ai/minimax-bot/miniapp/node/store.mjs @@ -574,15 +574,18 @@ export class Store { } /** Commit one inbox batch atomically, preserving streaming message object identity. */ - async updateMessages(chatId, messageIds, patch) { + async updateMessages(chatId, messageIds, patch, options = {}) { await this.getMessages(chatId); const ids = new Set(messageIds); return this.enqueue(async () => { const list = this.messageCache.get(chatId) ?? []; - const selected = list.filter((message) => ids.has(message.id)); + // `when` keeps the selection to messages still in the state the caller reached them in: a + // resume that read `held` must not overwrite a state another path wrote while it waited. + const selected = list.filter((message) => ids.has(message.id) && (!options.when || options.when(message))); + const touched = new Set(selected.map((message) => message.id)); const patches = new Map(selected.map((message) => [message.id, Object.hasOwn(patch, 'dispatchState') ? { ...patch, dispatchRevision: (message.dispatchRevision ?? 0) + 1 } : patch])); - await writeJsonAtomic(this.messagePath(chatId), list.map((message) => ids.has(message.id) ? { ...message, ...patches.get(message.id) } : message)); + await writeJsonAtomic(this.messagePath(chatId), list.map((message) => touched.has(message.id) ? { ...message, ...patches.get(message.id) } : message)); for (const message of selected) Object.assign(message, patches.get(message.id)); return selected; }); 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 61706491..e1ec8f1b 100644 --- a/plugins/minimax-ai/minimax-bot/miniapp/node/user-inbox.mjs +++ b/plugins/minimax-ai/minimax-bot/miniapp/node/user-inbox.mjs @@ -29,6 +29,10 @@ export class UserInbox { } enqueue(chatId, message, bot, group) { + // One message joins the queue once. The resume route computes its list before an awaited write, + // so a retry carrying the same clientMessageId can enqueue the message first; without this the + // same request runs twice and answers twice. + if (this.has(message.id)) return; const queued = [...this.batches].filter((batch) => batch.chatId === chatId && !batch.started && !batch.cancelled); // Append only to the tail so a smaller message cannot overtake an overflow batch. // Supplements arriving during cancellation join this same continuation. @@ -149,7 +153,15 @@ export class UserInbox { async resumeHeld(chatId) { // Only resend supplements that never started; an uncertain original request is never replayed. const history = await this.engine.store.getMessages(chatId); - const held = history.filter((message) => message.role === 'user' && message.dispatchState === 'held' && !this.has(message.id)); + const held = history.filter((message) => { + if (message.role !== 'user' || this.has(message.id)) return false; + if (message.dispatchState === 'held') return true; + // A restart leaves an accepted request `pending` with the queue that owned it gone. It is + // recoverable on the same proof the retry path uses: no reply and no durable assistant + // placeholder means the request never reached the Host. + return message.dispatchState === 'pending' + && !history.some((item) => item.sourceMessageId === message.id || item.sourceMessageIds?.includes(message.id)); + }); if (!held.length || this.busy(chatId) || [...this.engine.tickets].some((ticket) => ticket.chatId === chatId)) { throw new this.ErrorType('busy', t('err.messageAlreadyProcessing')); } @@ -158,12 +170,17 @@ export class UserInbox { if (!bot && !group) throw new this.ErrorType('not_found', t('err.chatMissing')); const uncertainIds = history.filter((message) => message.role === 'user' && message.dispatchState === 'uncertain').map((message) => message.id); await this.engine.store.updateMessages(chatId, uncertainIds, { continuationAcknowledged: true }); - const messages = await this.engine.store.updateMessages(chatId, held.map((message) => message.id), { dispatchState: 'pending' }); + const heldIds = new Set(held.map((message) => message.id)); + // Re-check inside the write: a retry carrying the same clientMessageId can enqueue the message + // while this call waits for the disk, and a message that moved on must not be sent a second + // time. Only the state this call actually reached is still recoverable. + const messages = await this.engine.store.updateMessages(chatId, [...heldIds], { dispatchState: 'pending' }, + { when: (message) => heldIds.has(message.id) && (message.dispatchState === 'held' || message.dispatchState === 'pending') }); for (const message of messages) { + if (this.has(message.id)) continue; this.engine.broadcast({ type: 'message.upsert', chatId, message }); this.enqueue(chatId, message, bot, group); - } - return { ok: true }; + } return { ok: true }; } cancel(chatId, { persist = true } = {}) { diff --git a/plugins/minimax-ai/minimax-bot/package.json b/plugins/minimax-ai/minimax-bot/package.json index aa7d48cd..1b8fad54 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.30", + "version": "0.7.31", "private": true, "type": "module", "mcode": { diff --git a/plugins/minimax-ai/minimax-bot/tests/client-reliability.test.mjs b/plugins/minimax-ai/minimax-bot/tests/client-reliability.test.mjs index 4063caa4..3f410e9e 100644 --- a/plugins/minimax-ai/minimax-bot/tests/client-reliability.test.mjs +++ b/plugins/minimax-ai/minimax-bot/tests/client-reliability.test.mjs @@ -570,6 +570,38 @@ test('held supplements require an explicit continuation and a failed action leav assert.equal(calls.filter((call) => call.path.endsWith('/resume-pending')).length, 1); }); +test('a request stranded by a restart offers to send it again, and one this page just sent does not', async () => { + // A request that reached the disk and then lost the process before any state change carries no + // dispatchRevision; it is still recoverable, and the server says so too. + const stranded = message('msg_stranded', 'Ship the hotfix', { role: 'user', dispatchState: 'pending' }); + await reset([stranded]); + const button = document.querySelector('.message-delivery button'); + assert.equal(button.textContent, 'Continue with follow-ups'); + route = ({ path }) => path.endsWith('/resume-pending') ? response({ ok: true }) : undefined; + button.click(); await settle(); + assert.equal(calls.filter((call) => call.path.endsWith('/resume-pending')).length, 1); + + // The busy event carries no message, but it changes whether this line offers a resume. + const late = message('msg_late', 'Held back', { role: 'user', dispatchState: 'pending' }); + await reset([late]); + assert.notEqual(document.querySelector('.message-delivery button'), null); + emit({ type: 'chat.busy', chatId: late.chatId, busy: true, turns: [] }); + await settle(); + assert.equal(document.querySelector('.message-delivery button'), null); + emit({ type: 'chat.busy', chatId: late.chatId, busy: false, turns: [] }); + await settle(); + assert.notEqual(document.querySelector('.message-delivery button'), null); + + // A request this page just sent is pending with no reply too; it must not offer to resume itself. + await reset(); + const fresh = message('msg_fresh', 'Just typed', { role: 'user', dispatchState: 'pending' }); + route = ({ path, options }) => path.endsWith('/messages') && options.method === 'POST' + ? response({ message: fresh }) : undefined; + type('Just typed'); enter(); await settle(); + assert.equal(document.querySelector('.message-delivery button'), null); + assert.equal(document.querySelector('.message-delivery button'), null); +}); + test('a delayed send receipt cannot restore an obsolete pending state after the live processing event', async () => { await reset(); const user = message('msg_receipt', 'Request', { role: 'user', dispatchState: 'pending', dispatchRevision: 0 }); 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 4de0eb3d..37a22584 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,44 @@ test('an interrupted associated assistant is reported as uncertain, and legacy m 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]; + const chatId = `bot:${bot.id}`; + // The process died after the inbox marked the batch processing and before any reply existed. + const user = await store.appendMessage(chatId, { + role: 'user', text: 'Ship the hotfix', clientMessageId: 'orphan-1', + clientMessageHash: engine.userMessageFingerprint('Ship the hotfix', []), dispatchState: 'processing', + }); + await store.writeChain; + + const restored = new Store(dir); + await restored.init(); + let runs = 0; + const reopened = new Engine({ store: restored, memory, logger: { warn() {} }, broadcast() {}, retryDelaysMs: [], agent: { + async run(input, options) { runs += 1; return { ...started(input, options, 'resumed'), status: 'finished', text: 'Shipped' }; }, + } }); + reopened.startScheduler(); + reopened.tasks.start(); + + // The load-time mapping keeps `pending`, which the client retry path needs. The queue that owned + // it is gone, so the resume route has to recognise it too or the request is stranded for good. + const afterRestart = (await restored.getMessages(chatId)).find((message) => message.id === user.id); + assert.equal(afterRestart.dispatchState, 'pending'); + await until(() => idle(reopened)); + // Nothing replays it on its own: the turn may already have run tools before the process died. + assert.equal(runs, 0); + + await reopened.inbox.resume(chatId); + await until(() => idle(reopened)); + assert.equal(runs, 1); + const messages = await restored.getMessages(chatId); + assert.equal(messages.find((message) => message.id === user.id).dispatchState, 'delivered'); + assert.equal(messages.filter((message) => message.sourceMessageId === user.id).length, 1); + reopened.dispose(); + await restored.writeChain; +}); + test('repeated pending submissions do not duplicate queued turns or revive a deliberately cancelled queue', async (t) => { const { store, engine } = await fixture(t); const bot = store.state.bots[0]; @@ -1237,3 +1275,47 @@ test('sending after Stop does not restore an explicitly cancelled request that n assert.equal(original.dispatchState, 'cancelled'); assert.equal(replacement.dispatchState, 'delivered'); }); + +test('a resume that loses the race to a same-id retry does not send the request twice', async (t) => { + const { dir, store, memory, engine } = await fixture(t); + const bot = store.state.bots[0]; + const chatId = `bot:${bot.id}`; + const text = 'Ship the hotfix'; + // A request the restart left pending, with no reply. + const user = await store.appendMessage(chatId, { + role: 'user', text, clientMessageId: 'race-1', + clientMessageHash: engine.userMessageFingerprint(text, []), dispatchState: 'pending', + }); + await store.writeChain; + + let runs = 0; + engine.agent = { async run(input, options) { + runs += 1; + return { ...started(input, options, 'reply'), status: 'finished', text: 'Reply' }; + } }; + + // Hold the resume's write, so the retry gets in first. + let release; + const gate = new Promise((resolve) => { release = resolve; }); + const realUpdate = store.updateMessages.bind(store); + let held = false; + store.updateMessages = async (id, ids, patch, options) => { + if (!held && patch?.dispatchState === 'pending') { held = true; await gate; } + return realUpdate(id, ids, patch, options); + }; + + const resuming = engine.inbox.resume(chatId).catch((error) => error); + await new Promise((resolve) => setTimeout(resolve, 30)); + await engine.sendUserMessage(chatId, text, [], 'race-1').catch(() => {}); + await new Promise((resolve) => setTimeout(resolve, 60)); + release(); + await resuming; + await until(() => idle(engine)); + + // One request, one turn, one reply that answers it. + assert.equal(runs, 1); + const messages = await store.getMessages(chatId); + assert.equal(messages.filter((message) => message.role === 'bot' && message.sourceMessageId === user.id).length, 1); + engine.dispose(); + await store.writeChain; +});