Skip to content

Commit 03d147e

Browse files
authored
fix(minimax-bot): 台账记下崩掉的那一回合,面板上的数字不再自己写死 (#97)
* fix(minimax-bot): 台账记下崩掉的那一回合,面板上的数字不再自己写死 * Throttle the background job's state writes and say what an aborted row means
1 parent 79ebc4b commit 03d147e

12 files changed

Lines changed: 512 additions & 29 deletions

File tree

‎plugins/minimax-ai/minimax-bot/.minimax-plugin/plugin.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"schemaVersion": 1,
33
"name": "minimax-bot",
44
"displayName": "MiniMax Bot",
5-
"version": "0.7.16",
5+
"version": "0.7.17",
66
"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.",
77
"author": "MiniMax Code",
88
"icon": "icon.png",

‎plugins/minimax-ai/minimax-bot/README.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,14 @@ The MCP tools check the arguments they declare before they run. A value of the w
4444

4545
An avatar may come from the avatar library or from an image uploaded in the page only. A path on the computer is refused, the plugin reads no file outside its own `dataDir` for one, and the refused path is not echoed back — so the field cannot be used to ask what exists on the disk.
4646

47+
## 0.7.17 The panel and the ledger say what happened
48+
49+
The usage ledger is the record of what the model really did. A turn cut off by a crash or a restart is written down as aborted, with no duration — it never reported how long it ran — and with the characters and tool calls it did make; the panel's average is taken over the turns that have a known duration, so a lost turn neither vanishes from the count nor counts as zero seconds. Every row says how many times the model was called for that turn (a retry is still one turn), and the panel adds that count when it is higher than the number of turns. A turn that ran is on the ledger even when a later step of the same turn fails to write.
50+
51+
The note section of the group panel reads the note's limits (6 entries and 1200 characters) from the server, so the numbers it shows are the numbers the plugin uses.
52+
53+
In the usage view an `aborted` row is a turn that was cut off: it counts as a turn and it shows the characters and tool calls it did make, but it has no duration, so it is left out of the average. A turn that was never metered at all is not on the ledger; the panel's turn count is the number of rows.
54+
4755
## 0.7.10 Optional group notes
4856

4957
- 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.

‎plugins/minimax-ai/minimax-bot/miniapp/client/core.js‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,9 @@ export const state = {
6060
user: { name: '', systemName: '' },
6161
/** Effective language resolved by the server. */
6262
locale: systemLocale(),
63+
/** Limits the server applies to a group note; `null` until the server states them. */
64+
/** @type {{ entries: number, chars: number } | null} */
65+
noteLimits: null,
6366
};
6467

6568
/** Navigation callbacks registered by app.js so panels can drive the main view. */
@@ -255,6 +258,19 @@ export async function api(method, path, body) {
255258
return /** @type {any} */ (data);
256259
}
257260

261+
/**
262+
* The note limits as the server states them, or `null` when it does not state a usable pair:
263+
* the panel then says nothing at all rather than half a line.
264+
* @param {any} limits
265+
* @returns {{ entries: number, chars: number } | null}
266+
*/
267+
function noteLimitsOf(limits) {
268+
if (!limits || typeof limits !== 'object') return null;
269+
const { entries, chars } = limits;
270+
if (!Number.isFinite(entries) || !Number.isFinite(chars)) return null;
271+
return { entries, chars };
272+
}
273+
258274
export async function loadState() {
259275
const data = await api('GET', '/api/state');
260276
state.bots = data.bots;
@@ -271,6 +287,9 @@ export async function loadState() {
271287
state.settings = data.settings ?? state.settings;
272288
state.user = data.user ?? state.user;
273289
state.locale = data.locale ?? state.locale;
290+
// The server owns the note limits: the panel states them instead of writing down numbers of
291+
// its own, which would drift from the ones the plugin actually applies.
292+
state.noteLimits = noteLimitsOf(data.noteLimits);
274293
setLocale(state.locale);
275294
if (!state.current || !chatExists(state.current)) {
276295
const remembered = prefs.lastChat && chatExists(prefs.lastChat) ? prefs.lastChat : '';

‎plugins/minimax-ai/minimax-bot/miniapp/client/panels.js‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1473,13 +1473,16 @@ function usagePage(body, o) {
14731473
.then((data) => {
14741474
if (state.overlay?.kind !== 'settings' || state.overlay.page !== 'usage') return;
14751475
const totals = data.totals;
1476+
// A turn that was cut off has no known duration, so the average counts the turns that
1477+
// really ran; the count of model calls says how often the model was really asked.
1478+
const modelCalls = totals.modelCalls ?? totals.turns;
14761479
const kpis = h(
14771480
'div',
14781481
{ class: 'kpis' },
1479-
h('div', { class: 'kpi big' }, h('span', { class: 'k-label' }, days === 1 ? t('panels.usage.last24h') : t('panels.usage.lastDays', { n: days })), h('span', { class: 'k-value' }, fmtNum(totals.turns), h('span', { class: 'k-unit' }, t('panels.usage.turnsUnit', { count: totals.turns })))),
1482+
h('div', { class: 'kpi big' }, h('span', { class: 'k-label' }, days === 1 ? t('panels.usage.last24h') : t('panels.usage.lastDays', { n: days })), h('span', { class: 'k-value' }, fmtNum(totals.turns), h('span', { class: 'k-unit' }, t('panels.usage.turnsUnit', { count: totals.turns }), modelCalls > totals.turns ? ` · ${t('panels.usage.modelCalls', { n: modelCalls, count: modelCalls })}` : ''))),
14801483
h('div', { class: 'kpi' }, h('span', { class: 'k-label' }, t('panels.usage.replyChars')), h('span', { class: 'k-value' }, fmtNum(totals.chars))),
14811484
h('div', { class: 'kpi' }, h('span', { class: 'k-label' }, t('panels.usage.toolCalls')), h('span', { class: 'k-value' }, fmtNum(totals.tools))),
1482-
h('div', { class: 'kpi' }, h('span', { class: 'k-label' }, t('panels.usage.avgDuration')), h('span', { class: 'k-value' }, totals.turns ? fmtDuration(totals.durationMs / totals.turns) : '—')),
1485+
h('div', { class: 'kpi' }, h('span', { class: 'k-label' }, t('panels.usage.avgDuration')), h('span', { class: 'k-value' }, totals.avgDurationMs != null ? fmtDuration(totals.avgDurationMs) : '—'), totals.durationSamples < totals.turns ? h('small', { class: 'muted' }, t('panels.usage.avgDurationNote')) : null),
14831486
);
14841487
holder.replaceChildren(
14851488
kpis,

‎plugins/minimax-ai/minimax-bot/miniapp/client/strings-panels.js‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -346,9 +346,11 @@ export default {
346346
'panels.usage.last24h': '最近 24 小时',
347347
'panels.usage.lastDays': '最近 {n} 天',
348348
'panels.usage.turnsUnit': '轮对话',
349+
'panels.usage.modelCalls': '{n} 次模型调用',
349350
'panels.usage.replyChars': '回复字数',
350351
'panels.usage.toolCalls': '工具调用',
351352
'panels.usage.avgDuration': '平均耗时',
353+
'panels.usage.avgDurationNote': '仅统计有已知耗时的轮次',
352354
'panels.usage.turnsTitle': '对话轮次',
353355
'panels.usage.hourly': '按小时',
354356
'panels.usage.daily': '按天',
@@ -709,9 +711,11 @@ export default {
709711
'panels.usage.last24h': 'Last 24 hours',
710712
'panels.usage.lastDays': 'Last {n} days',
711713
'panels.usage.turnsUnit': (p) => pl(p.count, 'turn', 'turns'),
714+
'panels.usage.modelCalls': '{n} model calls',
712715
'panels.usage.replyChars': 'Reply characters',
713716
'panels.usage.toolCalls': 'Tool calls',
714717
'panels.usage.avgDuration': 'Avg. duration',
718+
'panels.usage.avgDurationNote': 'Turns with a known duration only',
715719
'panels.usage.turnsTitle': 'Chat turns',
716720
'panels.usage.hourly': 'Hourly',
717721
'panels.usage.daily': 'Daily',

‎plugins/minimax-ai/minimax-bot/miniapp/node/engine.mjs‎

Lines changed: 61 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,11 @@ const HELPER_ACTIVE = new Set(['queued', 'running']);
4747
* Model capacity errors (429/529) and timeouts usually clear within a minute.
4848
*/
4949
export const TURN_RETRY_DELAYS_MS = Object.freeze([8000, 20000]);
50+
/**
51+
* How often a running turn writes its progress to disk. A crash must leave the work the model
52+
* already did in the ledger, so the turn's known state cannot live only in memory.
53+
*/
54+
const LIVE_PERSIST_MS = 2000;
5055
/** Failure reasons a retry cannot fix; anything else (or no reason from an older Host) may be retried. */
5156
export const NO_RETRY_REASONS = new Set(['auth', 'quota', 'context_too_long', 'blocked', 'invalid_request']);
5257
/** The turn may already have run, so resending it could repeat a reply or an action. */
@@ -578,11 +583,14 @@ export class Engine {
578583

579584
const startedAt = Date.now();
580585
let lastFlush = 0;
586+
let lastPersist = 0;
581587
let rootSessionId = this.store.getSession(chatId, bot.id)?.sessionId;
582588
let toolStarted = false;
583589
/** Whether any attempt started a turn, i.e. the session already holds this input. */
584590
let reachedHost = false;
585591
let invoked = false;
592+
/** How many times the model was called for this turn, retries included. */
593+
let modelCalls = 0;
586594
let preparedInput = input;
587595
let acceptedGroupCursor;
588596
/** @type {{ type: 'text', text: string, live?: boolean } | undefined} */
@@ -593,6 +601,13 @@ export class Engine {
593601
lastFlush = now;
594602
message.text = textOf(message.parts);
595603
this.broadcast({ type: 'message.upsert', chatId, message });
604+
// Keep the turn's progress on disk: a crash must leave the work the model already did
605+
// in the ledger, not just a message that says it was still running.
606+
if (now - lastPersist >= LIVE_PERSIST_MS) {
607+
lastPersist = now;
608+
void this.store.persistMessages(chatId).catch((error) =>
609+
this.logger.warn('minimax_bot.turn_persist_failed', { code: error?.code ?? 'unknown' }));
610+
}
596611
};
597612
const ensureLiveText = () => {
598613
if (!liveText || message.parts.at(-1) !== liveText) {
@@ -709,13 +724,17 @@ export class Engine {
709724
if (attempt === 0) preparedInput = await this.prepareGroupInput(input);
710725
const attemptInput = attempt === 0 || !reachedHost ? preparedInput : { ...preparedInput, text: t('retry.continue') };
711726
invoked = true;
727+
modelCalls += 1;
728+
message.modelCalls = modelCalls;
712729
result = await this.invoke(attemptInput, rootSessionId, controller.signal, onEvent) ?? skippedTurn();
713730
} catch (error) {
714731
if (errorCode(error) === 'SESSION_NOT_FOUND' && !input.answer && attempt === 0) {
715732
// The Agent session was deleted; start a fresh one and resend the Bot's context.
716733
await this.store.clearSession(chatId, bot.id);
717734
try {
718735
preparedInput = await this.prepareGroupInput(input);
736+
modelCalls += 1;
737+
message.modelCalls = modelCalls;
719738
result = await this.invoke(preparedInput, undefined, controller.signal, onEvent) ?? skippedTurn();
720739
} catch (retryError) {
721740
failure = describeAgentError(retryError);
@@ -814,31 +833,37 @@ export class Engine {
814833
request: result.pendingQuestion.request,
815834
};
816835
}
817-
await this.store.updateMessage(chatId, message.id, {});
818-
if (result?.sessionId) {
819-
await this.store.setSession(chatId, bot.id, { sessionId: result.sessionId });
820-
}
821-
if (acceptedGroupCursor !== undefined) {
822-
const previous = this.store.getSession(chatId, bot.id)?.lastSeenSeq ?? 0;
823-
await this.store.setSession(chatId, bot.id, { lastSeenSeq: Math.max(previous, acceptedGroupCursor) });
836+
const tools = message.parts.filter((part) => part.type === 'tool').length;
837+
try {
838+
await this.store.updateMessage(chatId, message.id, {});
839+
if (result?.sessionId) {
840+
await this.store.setSession(chatId, bot.id, { sessionId: result.sessionId });
841+
}
842+
if (acceptedGroupCursor !== undefined) {
843+
const previous = this.store.getSession(chatId, bot.id)?.lastSeenSeq ?? 0;
844+
await this.store.setSession(chatId, bot.id, { lastSeenSeq: Math.max(previous, acceptedGroupCursor) });
845+
}
846+
} finally {
847+
// The model ran: the ledger must say so even when a later step of this turn fails.
848+
await this.store.recordUsage({
849+
ts: Date.now(),
850+
turnId: message.id,
851+
botId: bot.id,
852+
botName: bot.name,
853+
chatId,
854+
kind: input.kind,
855+
status,
856+
durationMs: message.durationMs,
857+
chars: finalText.length,
858+
tools,
859+
// One turn, but the model may have been called more than once to finish it.
860+
attempts: modelCalls,
861+
});
862+
this.broadcast({ type: 'usage.changed' });
824863
}
825864
this.broadcast({ type: 'message.upsert', chatId, message });
826865
this.emitBusy(chatId);
827866
this.broadcastSummary(chatId);
828-
829-
const tools = message.parts.filter((part) => part.type === 'tool').length;
830-
await this.store.recordUsage({
831-
ts: Date.now(),
832-
botId: bot.id,
833-
botName: bot.name,
834-
chatId,
835-
kind: input.kind,
836-
status,
837-
durationMs: message.durationMs,
838-
chars: finalText.length,
839-
tools,
840-
});
841-
this.broadcast({ type: 'usage.changed' });
842867
return {
843868
status,
844869
text: finalText,
@@ -1732,6 +1757,10 @@ export class Engine {
17321757
let turnStartedAt = 0;
17331758
let turnMs = 0;
17341759
let turnTools = 0;
1760+
// A background job can call many tools in a row, and every save rewrites the whole state
1761+
// file. The count is written as it goes, but not on every call: a crash may lose the last
1762+
// second of it, and the end of the turn writes the final number anyway.
1763+
let lastHelperPersist = 0;
17351764
let turnText = '';
17361765
let turnBotName = '';
17371766
try {
@@ -1757,6 +1786,14 @@ export class Engine {
17571786
// A background job calls the same tools a Bot's own turn does. Count them, or the
17581787
// turn it spends looks like it cost nothing.
17591788
turnTools += 1;
1789+
// Keep the count on disk: a job cut off by a restart must still show the tools it
1790+
// really called in the ledger.
1791+
helper.turnTools = turnTools;
1792+
const now = Date.now();
1793+
if (now - lastHelperPersist >= LIVE_PERSIST_MS) {
1794+
lastHelperPersist = now;
1795+
void this.store.save().catch((error) => this.logger.warn('minimax_bot.helper_save_failed', { helperId: helper.id, code: error?.code ?? 'unknown' }));
1796+
}
17601797
} else if (event.type === 'permission.requested') {
17611798
// The user approves a helper's tool call in its Bot's chat, like the Bot's own.
17621799
const approval = {
@@ -1835,6 +1872,7 @@ export class Engine {
18351872
// counts fewer turns than the model actually ran.
18361873
await this.store.recordUsage({
18371874
ts: Date.now(),
1875+
turnId: helper.id,
18381876
botId: helper.botId,
18391877
botName: turnBotName,
18401878
chatId: helper.chatId,
@@ -1843,6 +1881,8 @@ export class Engine {
18431881
durationMs: turnMs,
18441882
chars: turnText.length,
18451883
tools: turnTools,
1884+
// A background job runs the model once; it has no retry loop of its own.
1885+
attempts: 1,
18461886
});
18471887
this.broadcast({ type: 'usage.changed' });
18481888
}

‎plugins/minimax-ai/minimax-bot/miniapp/node/mcp.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -662,7 +662,7 @@ export function createMcpHandler({ team, engine }) {
662662
result = {
663663
protocolVersion: PROTOCOL_VERSIONS.includes(requested) ? requested : PROTOCOL_VERSIONS[0],
664664
capabilities: { tools: { listChanged: false } },
665-
serverInfo: { name: 'minimax-bot', version: '0.7.16' },
665+
serverInfo: { name: 'minimax-bot', version: '0.7.17' },
666666
instructions: t('mcp.instructions'),
667667
};
668668
break;

‎plugins/minimax-ai/minimax-bot/miniapp/node/server.mjs‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,7 @@ export async function start(context) {
229229
}
230230
/** @type {Record<string, any>} */
231231
const byBot = {};
232-
const totals = { turns: 0, chars: 0, tools: 0, durationMs: 0, errors: 0 };
232+
const totals = { turns: 0, chars: 0, tools: 0, durationMs: 0, durationSamples: 0, modelCalls: 0, errors: 0 };
233233
for (const row of rows) {
234234
const bucket = buckets[keyOf(row.ts)];
235235
const live = store.getBot(row.botId);
@@ -244,6 +244,8 @@ export async function start(context) {
244244
chars: 0,
245245
tools: 0,
246246
durationMs: 0,
247+
durationSamples: 0,
248+
modelCalls: 0,
247249
errors: 0,
248250
});
249251
if (bucket) {
@@ -254,13 +256,24 @@ export async function start(context) {
254256
target.turns += 1;
255257
target.chars += row.chars ?? 0;
256258
target.tools += row.tools ?? 0;
257-
target.durationMs += row.durationMs ?? 0;
259+
// A turn that was cut off has no known duration: it must not pull the average down,
260+
// so only the turns that really ran are counted.
261+
if (Number.isFinite(row.durationMs)) {
262+
target.durationMs += row.durationMs;
263+
target.durationSamples += 1;
264+
}
265+
// How many times the model really ran for this turn; a row without the field is one call.
266+
target.modelCalls += row.attempts ?? 1;
258267
}
259268
if (row.status === 'error') {
260269
bot.errors += 1;
261270
totals.errors += 1;
262271
}
263272
}
273+
// The average covers the turns whose duration is known; a turn that was cut off has none.
274+
for (const target of [totals, ...Object.values(byBot)]) {
275+
target.avgDurationMs = target.durationSamples ? target.durationMs / target.durationSamples : null;
276+
}
264277
return {
265278
days: hourly ? 1 : span,
266279
hourly,

0 commit comments

Comments
 (0)