From ae6baf333f365bf8e62ae020836264a33f519ceb Mon Sep 17 00:00:00 2001 From: kshitijk4poor <82637225+kshitijk4poor@users.noreply.github.com> Date: Mon, 24 Aug 2026 01:27:56 +0530 Subject: [PATCH 1/4] fix(desktop): drop superseded group-chat turns and dedupe adjacent identical replies (#93127) --- .../desktop/src/plugins/hermes-bots/plugin.js | 67 +++++++++++++ .../tests/group-turn-races.test.mjs | 95 +++++++++++++++++++ 2 files changed, 162 insertions(+) create mode 100644 apps/desktop/src/plugins/hermes-bots/tests/group-turn-races.test.mjs diff --git a/apps/desktop/src/plugins/hermes-bots/plugin.js b/apps/desktop/src/plugins/hermes-bots/plugin.js index 8a7009093e..6887f33fa4 100644 --- a/apps/desktop/src/plugins/hermes-bots/plugin.js +++ b/apps/desktop/src/plugins/hermes-bots/plugin.js @@ -6554,6 +6554,17 @@ function appendGroupChatEntry(group, from, text, thread, images) { entry.images = images } + // #93127 insurance: a residual double-append path (stale loop + fresh + // loop both committing the same member reply) lands back-to-back and + // byte-identical. Drop the echo instead of flooding the room. User + // entries and non-adjacent repeats are never touched. + const priorLog = ($groupChats.get()[group] || {}).log || [] + const lastEntry = priorLog[priorLog.length - 1] + + if (isDuplicateGroupAppend(lastEntry, from, entry.text, entry.thread)) { + return lastEntry + } + updateGroupChat(group, room => { room.log.push(entry) return room @@ -7042,6 +7053,50 @@ async function harvestStrandedGroupReply(group, member) { } } +// --- room-turn decision helpers (#93127) — pure, vm-sliced by tests --- + +/** #93127: whether a finished member turn may still commit (append its reply + * and advance its watermark). A turn dispatched under an older epoch was + * superseded mid-flight by a newer user send — its late result must be + * dropped, because the new send's own loop re-drives this member with the + * full delta and committing both is exactly the double-delivery bug. */ +function shouldCommitMemberTurn(epochAtDispatch, currentEpoch) { + return epochAtDispatch === currentEpoch +} + +/** #93127 insurance: byte-identical member echo detection. TRUE only when + * the immediately-preceding log entry has the same author (kind + name + + * source), same thread, and identical text, within a short recency window — + * a residual double-append fires back-to-back; two legitimately identical + * replies hours apart (or with anything in between) are never dropped. */ +const GROUP_DUPLICATE_APPEND_WINDOW_MS = 10 * 60 * 1000 + +function isDuplicateGroupAppend(lastEntry, from, text, thread, now = Date.now()) { + if (!lastEntry || !from || from.kind !== 'member' || lastEntry.from?.kind !== 'member') { + return false + } + + if (String(lastEntry.from?.name || '') !== String(from.name || '')) { + return false + } + + if (String(lastEntry.from?.source || '') !== String(from.source || '')) { + return false + } + + if (String(lastEntry.thread || 'legacy') !== String(thread || 'legacy')) { + return false + } + + if (now - (lastEntry.at || 0) > GROUP_DUPLICATE_APPEND_WINDOW_MS) { + return false + } + + return String(lastEntry.text || '') === String(text || '').trim() +} + +// --- end room-turn decision helpers --- + /** Drive one bounded round-robin turn for ONE THREAD. Serial — one member at * a time. A newer user send bumps the room epoch; this loop notices at the * next member boundary, bails, and the newest send's own loop takes over. @@ -7143,6 +7198,18 @@ async function runGroupChatRounds(group, members, thread) { reply = null // a failed turn is a pass, never a room error } + // #93127: the turn may have finished AFTER a newer user send bumped + // the room epoch. That newer send's loop re-drives this member with + // the full delta, so committing this stale result (watermark advance + // + append) would double-deliver the same reply. Drop it here — + // BEFORE the watermark advance and BEFORE the append. + const epochNow = ($groupChats.get()[group] || {}).epoch || 0 + + if (!shouldCommitMemberTurn(startEpoch, epochNow)) { + recordGroupActivity(group, { kind: 'cancelled', member: member.name, thread }) + return + } + // The member has now seen everything up to the pre-reply log length. updateGroupChat(group, r => { r.watermarks[markKey] = r.log.length diff --git a/apps/desktop/src/plugins/hermes-bots/tests/group-turn-races.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/group-turn-races.test.mjs new file mode 100644 index 0000000000..fb10f9f977 --- /dev/null +++ b/apps/desktop/src/plugins/hermes-bots/tests/group-turn-races.test.mjs @@ -0,0 +1,95 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import test from 'node:test' +import vm from 'node:vm' + +// #93127: duplicate room delivery. Two raceable paths existed: +// 1. a member turn mid-flight when the room epoch bumps still commits its +// reply + watermark when it returns (the stale loop only noticed +// supersession at the NEXT member boundary), and +// 2. the stale loop and the fresh loop can both append the same reply. +// The fix re-checks the epoch after the turn returns (shouldCommitMemberTurn) +// and drops adjacent byte-identical member echoes (isDuplicateGroupAppend). + +const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8') + +function loadHelpers() { + const start = pluginSource.indexOf('// --- room-turn decision helpers (#93127)') + const end = pluginSource.indexOf('// --- end room-turn decision helpers ---', start) + assert.notEqual(start, -1, 'plugin carries the room-turn helper block') + assert.notEqual(end, -1, 'room-turn helper block has a stable end marker') + const context = {} + vm.runInNewContext( + `${pluginSource.slice(start, end)} +globalThis.shouldCommitMemberTurn = shouldCommitMemberTurn +globalThis.isDuplicateGroupAppend = isDuplicateGroupAppend`, + context + ) + return context +} + +const memberEntry = (name, text, thread = 't1', at = Date.now(), source) => ({ + id: 'x', + at, + from: { kind: 'member', name, ...(source ? { source } : {}) }, + text, + thread +}) + +test('a superseded turn is discarded — epoch moved on while the turn ran', () => { + const { shouldCommitMemberTurn } = loadHelpers() + assert.equal(shouldCommitMemberTurn(3, 4), false) + assert.equal(shouldCommitMemberTurn(3, 7), false) +}) + +test('a current turn commits — epoch unchanged since dispatch', () => { + const { shouldCommitMemberTurn } = loadHelpers() + assert.equal(shouldCommitMemberTurn(3, 3), true) + assert.equal(shouldCommitMemberTurn(0, 0), true) +}) + +test('adjacent identical member reply is a duplicate append', () => { + const { isDuplicateGroupAppend } = loadHelpers() + const last = memberEntry('impl', 'Stopped. Standing by.') + const dup = isDuplicateGroupAppend(last, { kind: 'member', name: 'impl' }, 'Stopped. Standing by.', 't1') + assert.equal(dup, true) +}) + +test('identical text from a DIFFERENT member is not a duplicate', () => { + const { isDuplicateGroupAppend } = loadHelpers() + const last = memberEntry('impl', 'Confirmed.') + assert.equal(isDuplicateGroupAppend(last, { kind: 'member', name: 'reviewer' }, 'Confirmed.', 't1'), false) +}) + +test('identical text from the same member on another SOURCE is not a duplicate', () => { + const { isDuplicateGroupAppend } = loadHelpers() + const last = memberEntry('impl', 'Confirmed.', 't1', Date.now(), 'laptop') + assert.equal(isDuplicateGroupAppend(last, { kind: 'member', name: 'impl' }, 'Confirmed.', 't1'), false) +}) + +test('same text after an intervening entry is not a duplicate — only the LAST entry is checked', () => { + const { isDuplicateGroupAppend } = loadHelpers() + // The helper only ever receives the immediately-preceding entry; an + // intervening entry means lastEntry is the interloper, not the echo. + const intervening = memberEntry('reviewer', 'ack') + assert.equal(isDuplicateGroupAppend(intervening, { kind: 'member', name: 'impl' }, 'Confirmed.', 't1'), false) +}) + +test('identical text in a DIFFERENT thread is not a duplicate', () => { + const { isDuplicateGroupAppend } = loadHelpers() + const last = memberEntry('impl', 'Confirmed.', 'thread-a') + assert.equal(isDuplicateGroupAppend(last, { kind: 'member', name: 'impl' }, 'Confirmed.', 'thread-b'), false) +}) + +test('identical text outside the recency window is not a duplicate', () => { + const { isDuplicateGroupAppend } = loadHelpers() + const hourAgo = Date.now() - 60 * 60 * 1000 + const last = memberEntry('impl', 'Done.', 't1', hourAgo) + assert.equal(isDuplicateGroupAppend(last, { kind: 'member', name: 'impl' }, 'Done.', 't1'), false) +}) + +test('user entries are never deduped', () => { + const { isDuplicateGroupAppend } = loadHelpers() + const last = { id: 'x', at: Date.now(), from: { kind: 'user', name: 'You' }, text: 'stop', thread: 't1' } + assert.equal(isDuplicateGroupAppend(last, { kind: 'user', name: 'You' }, 'stop', 't1'), false) +}) From 0c474d782073266a76528ff98b3a1957714e5d44 Mon Sep 17 00:00:00 2001 From: kshitijk4poor <82637225+kshitijk4poor@users.noreply.github.com> Date: Mon, 24 Aug 2026 01:47:08 +0530 Subject: [PATCH 2/4] =?UTF-8?q?fix(desktop):=20make=20member=20stop=20stic?= =?UTF-8?q?ky=20=E2=80=94=20per-member=20hold=20until=20explicit=20resume?= =?UTF-8?q?=20(#93129)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A user 'stop @member' was just log text: the next room delta (receipt round completing, any later turn) re-dispatched the member and it re-claimed the very task it was told to stop. Holds are now durable room state: set by an explicit user stop mention, checked by the round loop before dispatch (skip consumes the delta exactly once — no spin), released only by an explicit resume, @all resume, or a direct non-stop mention of the held member. Holds persist and rehydrate with the same durability as room watermarks, and the activity feed shows WHY a held bot is silent (⏸ held glyph + hint) the first time it is skipped. Conservative parse documented in-code: any standalone stop/halt/pause next to a mention holds — a wrongly-held bot is one mention away from release; a wrongly-running one keeps doing forbidden work. --- .../desktop/src/plugins/hermes-bots/plugin.js | 129 +++++++++++++++++- .../tests/group-member-hold.test.mjs | 114 ++++++++++++++++ 2 files changed, 240 insertions(+), 3 deletions(-) create mode 100644 apps/desktop/src/plugins/hermes-bots/tests/group-member-hold.test.mjs diff --git a/apps/desktop/src/plugins/hermes-bots/plugin.js b/apps/desktop/src/plugins/hermes-bots/plugin.js index 6887f33fa4..d36f2e6992 100644 --- a/apps/desktop/src/plugins/hermes-bots/plugin.js +++ b/apps/desktop/src/plugins/hermes-bots/plugin.js @@ -503,7 +503,8 @@ const GROUP_ACTIVITY_LABELS = { failed: 'hit an error', cancelled: 'turn interrupted by a newer message', settled: 'turn settled', - delivered: 'delivered a late reply' + delivered: 'delivered a late reply', + held: 'is held (stopped by you) — @mention it or say resume to release' } const GROUP_ACTIVITY_GLYPHS = { @@ -515,7 +516,8 @@ const GROUP_ACTIVITY_GLYPHS = { failed: 'error', cancelled: 'close', settled: 'check-all', - delivered: 'mail-read' + delivered: 'mail-read', + held: 'debug-pause' } /** Text tone for an activity row: quiet for pass/cancel/settle, accent for @@ -6313,6 +6315,10 @@ function updateGroupChat(group, mutate, { sync = true } = {}) { // with the pre-turn message baseline. Survives reloads so finished // work is still harvested after a window restart. stranded: room.stranded || {}, + // #93129: sticky per-member stop holds. Watermarks persist, so holds + // must too — otherwise a window restart silently releases a bot the + // user explicitly stopped. + holds: room.holds || {}, // Source-qualified member descriptors keep the room whole when the // active connection changes and today's local members become remote. members: Array.isArray(room.members) ? room.members : [], @@ -7097,6 +7103,80 @@ function isDuplicateGroupAppend(lastEntry, from, text, thread, now = Date.now()) // --- end room-turn decision helpers --- +// --- member-hold helpers (#93129) — pure, vm-sliced by tests --- + +/** #93129: classify a USER room message's effect on member holds. Only user + * sends ever reach this (bot replies are appended by the round loop, never + * through sendToGroupChat), so a bot saying "stopped working on it" can + * never set a hold. Conservative on purpose: any standalone stop/halt/pause + * word next to a mention holds those members — "don't stop @x" therefore + * also holds, which errs toward the bot staying quiet until re-addressed + * (a wrongly-held bot is one mention away from release; a wrongly-running + * one keeps doing work it was told to stop). A non-stop direct mention + * releases the mentioned members — the user addressing a bot directly + * overrides its hold. */ +function classifyGroupHoldDirective(text, mentionedKeys, everyone) { + const value = String(text || '') + const mentioned = [...(mentionedKeys || [])] + const stop = /\b(stop|halt|pause)\b/i.test(value) + const resume = /\b(resume|continue|go|proceed)\b/i.test(value) + + if (stop) { + return { hold: mentioned, release: [], releaseAll: false } + } + + if (resume) { + return { hold: [], release: mentioned, releaseAll: Boolean(everyone) } + } + + return { hold: [], release: mentioned, releaseAll: false } +} + +/** #93129: next holds map after one user message. Holds are keyed by + * memberKey at ROOM scope (not thread scope): every main-composer send + * mints a NEW thread, so a thread-scoped hold would never block the next + * send's turns and the stop would not stick. Returns the same object when + * nothing changed. */ +function applyGroupHoldDirective(holds, mentions, text, stamp) { + const prior = holds && typeof holds === 'object' ? holds : {} + const action = classifyGroupHoldDirective(text, mentions?.mentioned || [], Boolean(mentions?.everyone)) + + if (action.releaseAll) { + return Object.keys(prior).length ? {} : prior + } + + let next = prior + + for (const key of action.hold) { + if (next === prior) { + next = { ...prior } + } + + next[key] = { at: stamp?.at || Date.now(), byMessageId: stamp?.byMessageId || null, thread: stamp?.thread || null } + } + + for (const key of action.release) { + if (Object.prototype.hasOwnProperty.call(next, key)) { + if (next === prior) { + next = { ...prior } + } + + delete next[key] + } + } + + return next +} + +/** #93129: a held member's skip must consume its delta exactly once — + * advance the watermark past the current log so the same entries never + * re-trigger the skip. Null = nothing to consume (no write, no spin). */ +function heldMemberWatermarkAdvance(seen, logLength) { + return logLength > (seen || 0) ? logLength : null +} + +// --- end member-hold helpers --- + /** Drive one bounded round-robin turn for ONE THREAD. Serial — one member at * a time. A newer user send bumps the room epoch; this loop notices at the * next member boundary, bails, and the newest send's own loop takes over. @@ -7159,6 +7239,35 @@ async function runGroupChatRounds(group, members, thread) { continue } + // #93129: a member the user told to stop is HELD — no turn until an + // explicit release (resume / @all resume / a direct non-stop + // mention). Consume the delta exactly once (watermark past the + // current log) so the same entries never re-trigger this skip, and + // surface WHY the bot is silent in the activity feed the first time. + const heldEntry = (room.holds || {})[memberKey] + + if (heldEntry) { + const advance = heldMemberWatermarkAdvance(seen, room.log.length) + + updateGroupChat(group, r => { + if (advance !== null) { + r.watermarks[markKey] = advance + } + + if (r.holds?.[memberKey] && !r.holds[memberKey].noted) { + r.holds = { ...r.holds, [memberKey]: { ...r.holds[memberKey], noted: true } } + } + + return r + }) + + if (!heldEntry.noted) { + recordGroupActivity(group, { kind: 'held', member: member.name, thread }) + } + + continue + } + const prompt = buildGroupChatTurnPrompt({ groupName: group, members, @@ -7320,13 +7429,23 @@ function sendToGroupChat(group, members, text, thread, images) { room.members = durableGroupChatMembers(members) return room }) - appendGroupChatEntry(group, { kind: 'user', name: 'You' }, trimmed, target, attached) + const sent = appendGroupChatEntry(group, { kind: 'user', name: 'You' }, trimmed, target, attached) const wasRunning = ($groupChats.get()[group] || {}).running === true updateGroupChat(group, room => { room.epoch = (room.epoch || 0) + 1 room.running = true + // #93129: user text is the ONLY input that changes member holds. An + // explicit "stop @member" sets a sticky hold; "@member resume" (or + // @all resume, or any direct non-stop mention of the held member) + // releases it. Bot replies never flow through this function. + room.holds = applyGroupHoldDirective( + room.holds, + parseGroupChatMentions(trimmed, members), + trimmed, + { at: sent?.at, byMessageId: sent?.id, thread: target } + ) return room }) @@ -14177,6 +14296,10 @@ export default { sessions: room.sessions && typeof room.sessions === 'object' ? room.sessions : {}, sessionOwners: room.sessionOwners && typeof room.sessionOwners === 'object' ? room.sessionOwners : {}, stranded: room.stranded && typeof room.stranded === 'object' ? room.stranded : {}, + // #93129: rehydrate sticky stop holds with the same shape + // guard as the other maps — a held bot stays held across + // window restarts until explicitly released. + holds: room.holds && typeof room.holds === 'object' ? room.holds : {}, members: Array.isArray(room.members) ? room.members : [], roomId: typeof room.roomId === 'string' && room.roomId ? room.roomId : null, image: typeof room.image === 'string' && room.image ? room.image : null, diff --git a/apps/desktop/src/plugins/hermes-bots/tests/group-member-hold.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/group-member-hold.test.mjs new file mode 100644 index 0000000000..8216632beb --- /dev/null +++ b/apps/desktop/src/plugins/hermes-bots/tests/group-member-hold.test.mjs @@ -0,0 +1,114 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import test from 'node:test' +import vm from 'node:vm' + +// #93129: a bot told to stop must STAY stopped. The hold helpers are pure and +// vm-sliced out of plugin.js exactly like group-turn-races.test.mjs does for +// the #93127 helpers. NOTE: vm-realm arrays/objects fail strict deepEqual +// against host literals (different realm prototypes) — normalize with spread +// or JSON round-trip before comparing. + +const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8') + +function loadHelpers() { + const start = pluginSource.indexOf('// --- member-hold helpers (#93129)') + const end = pluginSource.indexOf('// --- end member-hold helpers ---', start) + assert.notEqual(start, -1, 'plugin carries the member-hold helper block') + assert.notEqual(end, -1, 'member-hold helper block has a stable end marker') + const context = {} + vm.runInNewContext( + `${pluginSource.slice(start, end)} +globalThis.classifyGroupHoldDirective = classifyGroupHoldDirective +globalThis.applyGroupHoldDirective = applyGroupHoldDirective +globalThis.heldMemberWatermarkAdvance = heldMemberWatermarkAdvance`, + context + ) + return context +} + +// ── stop detection ─────────────────────────────────────────────────────────── + +test('explicit stop with a mention holds the mentioned member', () => { + const { classifyGroupHoldDirective } = loadHelpers() + for (const text of ['stop @impl', '@impl stop', '@impl please halt', 'pause @impl for now']) { + const action = classifyGroupHoldDirective(text, ['impl'], false) + assert.deepEqual([...action.hold], ['impl'], `"${text}" should hold`) + assert.deepEqual([...action.release], []) + } +}) + +test('stop word without any mention holds nobody', () => { + const { classifyGroupHoldDirective } = loadHelpers() + const action = classifyGroupHoldDirective('stop', [], false) + assert.deepEqual([...action.hold], []) +}) + +test('conservative choice: "don\'t stop @x" still holds (documented trade-off)', () => { + const { classifyGroupHoldDirective } = loadHelpers() + const action = classifyGroupHoldDirective("don't stop @impl", ['impl'], false) + assert.deepEqual([...action.hold], ['impl']) +}) + +test('"stopped" as part of another word does not trigger a hold', () => { + const { classifyGroupHoldDirective } = loadHelpers() + // \b(stop|halt|pause)\b — "stopped" is a different token + const action = classifyGroupHoldDirective('@impl unstoppable work ahead', ['impl'], false) + assert.deepEqual([...action.hold], []) + // a plain non-stop mention releases instead (direct address overrides hold) + assert.deepEqual([...action.release], ['impl']) +}) + +// ── hold lifecycle ─────────────────────────────────────────────────────────── + +test('stop sets a hold; resume for the same member clears it', () => { + const { applyGroupHoldDirective } = loadHelpers() + const stamp = { at: 1000, byMessageId: 'm1', thread: 't1' } + const held = applyGroupHoldDirective({}, { mentioned: ['impl'], everyone: false }, 'stop @impl', stamp) + assert.ok(held.impl) + assert.equal(held.impl.at, 1000) + const released = applyGroupHoldDirective(held, { mentioned: ['impl'], everyone: false }, '@impl resume', stamp) + assert.equal(released.impl, undefined) +}) + +test('a direct non-stop mention of a held member releases the hold', () => { + const { applyGroupHoldDirective } = loadHelpers() + const held = { impl: { at: 1, byMessageId: null, thread: null } } + const next = applyGroupHoldDirective(held, { mentioned: ['impl'], everyone: false }, '@impl what is your status?', {}) + assert.equal(next.impl, undefined) +}) + +test('@all resume releases every hold', () => { + const { applyGroupHoldDirective } = loadHelpers() + const held = { impl: { at: 1 }, docs: { at: 2 } } + const next = applyGroupHoldDirective(held, { mentioned: [], everyone: true }, '@all resume', {}) + assert.deepEqual(JSON.parse(JSON.stringify(next)), {}) +}) + +test('an unrelated room message leaves holds untouched (same object back)', () => { + const { applyGroupHoldDirective } = loadHelpers() + const held = { impl: { at: 1 } } + const next = applyGroupHoldDirective(held, { mentioned: [], everyone: false }, 'receipt round complete', {}) + assert.equal(next, held) +}) + +test('holding one member does not disturb another\'s hold', () => { + const { applyGroupHoldDirective } = loadHelpers() + const held = { impl: { at: 1 } } + const next = applyGroupHoldDirective(held, { mentioned: ['docs'], everyone: false }, 'stop @docs', { at: 2 }) + assert.ok(next.impl) + assert.ok(next.docs) +}) + +// ── skip must not spin ─────────────────────────────────────────────────────── + +test('held skip consumes the delta exactly once', () => { + const { heldMemberWatermarkAdvance } = loadHelpers() + // fresh delta → advance to log length + assert.equal(heldMemberWatermarkAdvance(3, 7), 7) + // already consumed → no write, no spin + assert.equal(heldMemberWatermarkAdvance(7, 7), null) + assert.equal(heldMemberWatermarkAdvance(9, 7), null) + // unset watermark treated as 0 + assert.equal(heldMemberWatermarkAdvance(undefined, 2), 2) +}) From 2863e8fb5da4dc47d055c999fa3b0743ae12ce46 Mon Sep 17 00:00:00 2001 From: kshitij <82637225+kshitijk4poor@users.noreply.github.com> Date: Mon, 24 Aug 2026 02:39:11 +0530 Subject: [PATCH 3/4] fix(desktop): review follow-ups for the room-race fixes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Cross-thread supersession no longer discards finished work: an epoch bump from a send in ANOTHER thread doesn't re-drive this thread's members (delta filters are thread-scoped), so dropping the finished reply lost completed work until someone revisited the old thread. shouldCommitMemberTurn now drops only when a newer USER entry landed in the same thread; the caller computes that from the log tail past the pre-turn length. - '@all stop' now holds every member — it parsed to everyone:true with no mentions and silently held nobody, the asymmetric twin of the tested '@all resume'. classifyGroupHoldDirective gains holdAll; the send path passes the room's member keys for expansion. - Tests pin both: cross-thread commit preserved, @all-stop holds all (mutation-checked: reverting either guard fails its test). --- .../desktop/src/plugins/hermes-bots/plugin.js | 46 ++++++++++++++----- .../tests/group-member-hold.test.mjs | 14 ++++++ .../tests/group-turn-races.test.mjs | 10 ++++ 3 files changed, 58 insertions(+), 12 deletions(-) diff --git a/apps/desktop/src/plugins/hermes-bots/plugin.js b/apps/desktop/src/plugins/hermes-bots/plugin.js index d36f2e6992..15d8785772 100644 --- a/apps/desktop/src/plugins/hermes-bots/plugin.js +++ b/apps/desktop/src/plugins/hermes-bots/plugin.js @@ -7065,9 +7065,19 @@ async function harvestStrandedGroupReply(group, member) { * and advance its watermark). A turn dispatched under an older epoch was * superseded mid-flight by a newer user send — its late result must be * dropped, because the new send's own loop re-drives this member with the - * full delta and committing both is exactly the double-delivery bug. */ -function shouldCommitMemberTurn(epochAtDispatch, currentEpoch) { - return epochAtDispatch === currentEpoch + * full delta and committing both is exactly the double-delivery bug. + * + * The re-drive premise is only true for a send in the SAME thread (delta + * filters are thread-scoped): a cross-thread epoch bump must NOT discard + * finished work no fresh loop will regenerate. Callers pass whether a newer + * USER entry landed in this thread since dispatch; the default (true) + * preserves the conservative drop when the caller can't tell. */ +function shouldCommitMemberTurn(epochAtDispatch, currentEpoch, newerUserEntryInThread = true) { + if (epochAtDispatch === currentEpoch) { + return true + } + + return !newerUserEntryInThread } /** #93127 insurance: byte-identical member echo detection. TRUE only when @@ -7122,14 +7132,15 @@ function classifyGroupHoldDirective(text, mentionedKeys, everyone) { const resume = /\b(resume|continue|go|proceed)\b/i.test(value) if (stop) { - return { hold: mentioned, release: [], releaseAll: false } + // "@all stop" holds every member — symmetric with "@all resume". + return { hold: mentioned, holdAll: Boolean(everyone), release: [], releaseAll: false } } if (resume) { - return { hold: [], release: mentioned, releaseAll: Boolean(everyone) } + return { hold: [], holdAll: false, release: mentioned, releaseAll: Boolean(everyone) } } - return { hold: [], release: mentioned, releaseAll: false } + return { hold: [], holdAll: false, release: mentioned, releaseAll: false } } /** #93129: next holds map after one user message. Holds are keyed by @@ -7137,7 +7148,7 @@ function classifyGroupHoldDirective(text, mentionedKeys, everyone) { * mints a NEW thread, so a thread-scoped hold would never block the next * send's turns and the stop would not stick. Returns the same object when * nothing changed. */ -function applyGroupHoldDirective(holds, mentions, text, stamp) { +function applyGroupHoldDirective(holds, mentions, text, stamp, allMemberKeys = []) { const prior = holds && typeof holds === 'object' ? holds : {} const action = classifyGroupHoldDirective(text, mentions?.mentioned || [], Boolean(mentions?.everyone)) @@ -7145,9 +7156,12 @@ function applyGroupHoldDirective(holds, mentions, text, stamp) { return Object.keys(prior).length ? {} : prior } + // "@all stop": expand to every member key the caller knows about. + const toHold = action.holdAll ? [...allMemberKeys] : action.hold + let next = prior - for (const key of action.hold) { + for (const key of toHold) { if (next === prior) { next = { ...prior } } @@ -7311,10 +7325,17 @@ async function runGroupChatRounds(group, members, thread) { // the room epoch. That newer send's loop re-drives this member with // the full delta, so committing this stale result (watermark advance // + append) would double-deliver the same reply. Drop it here — - // BEFORE the watermark advance and BEFORE the append. - const epochNow = ($groupChats.get()[group] || {}).epoch || 0 + // BEFORE the watermark advance and BEFORE the append. Only a newer + // USER entry in THIS thread makes the re-drive premise true: a + // cross-thread send bumps the epoch too, but its loop filters this + // thread out and would never regenerate the finished reply. + const roomNow = $groupChats.get()[group] || { log: [] } + const epochNow = roomNow.epoch || 0 + const newerUserEntryInThread = (roomNow.log || []) + .slice(room.log.length) + .some(e => e.from?.kind === 'user' && groupThreadOf(e) === thread) - if (!shouldCommitMemberTurn(startEpoch, epochNow)) { + if (!shouldCommitMemberTurn(startEpoch, epochNow, newerUserEntryInThread)) { recordGroupActivity(group, { kind: 'cancelled', member: member.name, thread }) return } @@ -7444,7 +7465,8 @@ function sendToGroupChat(group, members, text, thread, images) { room.holds, parseGroupChatMentions(trimmed, members), trimmed, - { at: sent?.at, byMessageId: sent?.id, thread: target } + { at: sent?.at, byMessageId: sent?.id, thread: target }, + members.map(member => groupMemberKey(member)) ) return room }) diff --git a/apps/desktop/src/plugins/hermes-bots/tests/group-member-hold.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/group-member-hold.test.mjs index 8216632beb..490152d8fe 100644 --- a/apps/desktop/src/plugins/hermes-bots/tests/group-member-hold.test.mjs +++ b/apps/desktop/src/plugins/hermes-bots/tests/group-member-hold.test.mjs @@ -85,6 +85,20 @@ test('@all resume releases every hold', () => { assert.deepEqual(JSON.parse(JSON.stringify(next)), {}) }) +test('@all stop holds every member — symmetric with @all resume', () => { + const { applyGroupHoldDirective } = loadHelpers() + const next = applyGroupHoldDirective( + {}, + { mentioned: [], everyone: true }, + '@all stop', + { at: 5 }, + ['impl', 'docs'] + ) + assert.ok(next.impl) + assert.ok(next.docs) + assert.equal(next.impl.at, 5) +}) + test('an unrelated room message leaves holds untouched (same object back)', () => { const { applyGroupHoldDirective } = loadHelpers() const held = { impl: { at: 1 } } diff --git a/apps/desktop/src/plugins/hermes-bots/tests/group-turn-races.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/group-turn-races.test.mjs index fb10f9f977..391da6b7b1 100644 --- a/apps/desktop/src/plugins/hermes-bots/tests/group-turn-races.test.mjs +++ b/apps/desktop/src/plugins/hermes-bots/tests/group-turn-races.test.mjs @@ -40,6 +40,8 @@ test('a superseded turn is discarded — epoch moved on while the turn ran', () const { shouldCommitMemberTurn } = loadHelpers() assert.equal(shouldCommitMemberTurn(3, 4), false) assert.equal(shouldCommitMemberTurn(3, 7), false) + // explicit same-thread supersession + assert.equal(shouldCommitMemberTurn(3, 4, true), false) }) test('a current turn commits — epoch unchanged since dispatch', () => { @@ -48,6 +50,14 @@ test('a current turn commits — epoch unchanged since dispatch', () => { assert.equal(shouldCommitMemberTurn(0, 0), true) }) +test('a cross-thread epoch bump does NOT discard finished work (no fresh loop re-drives it)', () => { + const { shouldCommitMemberTurn } = loadHelpers() + // Epoch moved, but no newer user entry landed in THIS thread: the + // superseding send lives in another thread whose loop filters this one + // out — dropping the reply would lose completed work forever. + assert.equal(shouldCommitMemberTurn(3, 4, false), true) +}) + test('adjacent identical member reply is a duplicate append', () => { const { isDuplicateGroupAppend } = loadHelpers() const last = memberEntry('impl', 'Stopped. Standing by.') From a234e93654d9fa9e6ce1c53ca9b1f0a131d2cb4b Mon Sep 17 00:00:00 2001 From: kshitij <82637225+kshitijk4poor@users.noreply.github.com> Date: Mon, 24 Aug 2026 02:54:57 +0530 Subject: [PATCH 4/4] fix(desktop): anchor the during-turn tail by entry id, not index MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Final-diff pass: trimGroupChatLog drops entries from the FRONT once a room crosses the history cap, so slicing the post-turn log at the pre-turn LENGTH could overshoot after a mid-turn trim, read an empty tail, and silently commit a stale turn — re-opening #93127's double delivery in long-history rooms exactly. Anchor on the last pre-turn entry's id; if the anchor itself was trimmed, every surviving entry is newer, so scanning the whole log stays exact. --- apps/desktop/src/plugins/hermes-bots/plugin.js | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/apps/desktop/src/plugins/hermes-bots/plugin.js b/apps/desktop/src/plugins/hermes-bots/plugin.js index 15d8785772..fbaa5e98ef 100644 --- a/apps/desktop/src/plugins/hermes-bots/plugin.js +++ b/apps/desktop/src/plugins/hermes-bots/plugin.js @@ -7328,12 +7328,20 @@ async function runGroupChatRounds(group, members, thread) { // BEFORE the watermark advance and BEFORE the append. Only a newer // USER entry in THIS thread makes the re-drive premise true: a // cross-thread send bumps the epoch too, but its loop filters this - // thread out and would never regenerate the finished reply. + // thread out and would never regenerate the finished reply. The + // during-turn tail is anchored by entry id, not index — the history + // trim drops entries from the FRONT, so an index slice could + // overshoot after a mid-turn trim and silently commit a stale turn. const roomNow = $groupChats.get()[group] || { log: [] } const epochNow = roomNow.epoch || 0 - const newerUserEntryInThread = (roomNow.log || []) - .slice(room.log.length) - .some(e => e.from?.kind === 'user' && groupThreadOf(e) === thread) + const anchorId = room.log.length ? room.log[room.log.length - 1].id : null + const anchorIdx = anchorId === null ? -1 : roomNow.log.findIndex(e => e.id === anchorId) + // Anchor trimmed away ⇒ every pre-turn entry was dropped, so every + // surviving entry is newer — scanning the whole log stays exact. + const turnTail = anchorIdx >= 0 ? roomNow.log.slice(anchorIdx + 1) : roomNow.log + const newerUserEntryInThread = turnTail.some( + e => e.from?.kind === 'user' && groupThreadOf(e) === thread + ) if (!shouldCommitMemberTurn(startEpoch, epochNow, newerUserEntryInThread)) { recordGroupActivity(group, { kind: 'cancelled', member: member.name, thread })