diff --git a/apps/desktop/src/plugins/hermes-bots/plugin.js b/apps/desktop/src/plugins/hermes-bots/plugin.js index 8a7009093e..fbaa5e98ef 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 : [], @@ -6554,6 +6560,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 +7059,138 @@ 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. + * + * 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 + * 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 --- + +// --- 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) { + // "@all stop" holds every member — symmetric with "@all resume". + return { hold: mentioned, holdAll: Boolean(everyone), release: [], releaseAll: false } + } + + if (resume) { + return { hold: [], holdAll: false, release: mentioned, releaseAll: Boolean(everyone) } + } + + return { hold: [], holdAll: false, 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, allMemberKeys = []) { + 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 + } + + // "@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 toHold) { + 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. @@ -7104,6 +7253,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, @@ -7143,6 +7321,33 @@ 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. 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. 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 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 }) + return + } + // The member has now seen everything up to the pre-reply log length. updateGroupChat(group, r => { r.watermarks[markKey] = r.log.length @@ -7253,13 +7458,24 @@ 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 }, + members.map(member => groupMemberKey(member)) + ) return room }) @@ -14110,6 +14326,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..490152d8fe --- /dev/null +++ b/apps/desktop/src/plugins/hermes-bots/tests/group-member-hold.test.mjs @@ -0,0 +1,128 @@ +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('@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 } } + 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) +}) 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..391da6b7b1 --- /dev/null +++ b/apps/desktop/src/plugins/hermes-bots/tests/group-turn-races.test.mjs @@ -0,0 +1,105 @@ +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) + // explicit same-thread supersession + assert.equal(shouldCommitMemberTurn(3, 4, true), 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('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.') + 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) +})