The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(hermes-bots): add a collapsible group activity view
amanning33908e5f55f83b61
diff --git a/apps/desktop/src/plugins/hermes-bots/plugin.js b/apps/desktop/src/plugins/hermes-bots/plugin.jsindex e620e41f9cf..9446ebc1b3e 100644--- a/apps/desktop/src/plugins/hermes-bots/plugin.js+++ b/apps/desktop/src/plugins/hermes-bots/plugin.js@@ -206,6 +206,92 @@ const $groupChatWorkspace = atom(null)/** Groups whose latest room activity mentions @user — the needs-you badge. */const $groupNeedsYou = atom({})+// ── group activity feed ─────────────────────────────────────────────────────+// Runtime-only, bounded per-room record of turn events that feeds the+// collapsible Activity view. Never persisted — it is presentation state like+// running/epoch, and the room transcript (log) stays the only durable record.+// Every event is tagged with the room epoch it belongs to, so the view shows+// only the CURRENT run: a newer send bumps the epoch (old-run events drop+// away), and a rename re-keys the room (the feed starts clean under the new+// name — stale events under the old key simply have no room to attach to).+const GROUP_ACTIVITY_LIMIT = 50+const $groupActivity = atom({})++function recordGroupActivity(group, event) {+ const room = $groupChats.get()[group]++ if (!room) {+ return null+ }++ const current = $groupActivity.get()[group] || { events: [] }+ const entry = { at: Date.now(), epoch: room.epoch || 0, ...event }+ const events = [...current.events, entry].slice(-GROUP_ACTIVITY_LIMIT)+ $groupActivity.set({ ...$groupActivity.get(), [group]: { ...current, events } })++ return entry+}++/** Events for the room's CURRENT run — superseded runs (epoch moved on)+ * are dropped from view instead of describing work that already ended. */+function currentGroupActivity(group) {+ const epoch = ($groupChats.get()[group] || {}).epoch || 0+ return ($groupActivity.get()[group] || {}).events?.filter(event => (event.epoch || 0) === epoch) || []+}++/** Human label for one activity event, used by the collapsed summary and+ * the expanded rows. */+function groupActivityLabel(event) {+ const kind = event?.kind+ const base = GROUP_ACTIVITY_LABELS[kind] || kind || 'did something'++ if (kind === 'cancelled' || kind === 'settled') {+ return base+ }++ const who = event?.member === 'You' ? 'You' : groupSpeakerLabel(event?.member || 'A bot')++ return `${who} ${base}`+}++const GROUP_ACTIVITY_LABELS = {+ queued: 'sent a message',+ working: 'is working…',+ replied: 'replied',+ passed: 'passed',+ 'timed-out': 'took too long',+ failed: 'hit an error',+ cancelled: 'turn interrupted by a newer message',+ settled: 'turn settled',+ delivered: 'delivered a late reply'+}++const GROUP_ACTIVITY_GLYPHS = {+ queued: 'comment',+ working: 'sync',+ replied: 'check',+ passed: 'circle-outline',+ 'timed-out': 'clock',+ failed: 'error',+ cancelled: 'close',+ settled: 'check-all',+ delivered: 'mail-read'+}++/** Text tone for an activity row: quiet for pass/cancel/settle, accent for+ * work and real replies, destructive for failures and timeouts. */+function groupActivityTone(kind) {+ if (kind === 'failed' || kind === 'timed-out') {+ return 'text-destructive'+ }++ if (kind === 'working' || kind === 'replied' || kind === 'delivered') {+ return 'text-(--ui-accent,#4f9cf9)'+ }++ return 'text-(--ui-text-tertiary)'+}+function handleSessionsGatewayTransition() {$sessionsGatewayGeneration.set($sessionsGatewayGeneration.get() + 1)$botSelectedSessions.set({})@@ -4072,6 +4158,8 @@ async function runGroupChatMemberTurn(group, member, prompt, thread, images) {return null}+ recordGroupActivity(group, { kind: 'working', member: member.name, thread })+// Baseline: how many messages exist before our submit.let before = 0@@ -4167,11 +4255,20 @@ async function runGroupChatMemberTurn(group, member, prompt, thread, images) {: Array.isArray(msg.content)? msg.content.map(p => (typeof p === 'string' ? p : p?.text || '')).join(''): msg?.text || ''+ const replyText = String(text).trim()++ recordGroupActivity(group, {+ kind: isGroupPassText(replyText) ? 'passed' : 'replied',+ member: member.name,+ thread+ })- return String(text).trim()+ return replyText}}+ recordGroupActivity(group, { kind: 'passed', member: member.name, thread })+return null}@@ -4184,6 +4281,7 @@ async function runGroupChatMemberTurn(group, member, prompt, thread, images) {// Timeout — reads as a pass, but remember the baseline + thread// (runtime-only) so the finished reply can be posted late into the RIGHT// thread instead of vanishing.+ recordGroupActivity(group, { kind: 'timed-out', member: member.name, thread })updateGroupChat(group, r => {r.stranded = { ...(r.stranded || {}), [groupMemberKey(member)]: { before, thread } }return r@@ -4249,6 +4347,7 @@ async function harvestStrandedGroupReply(group, member) {const reply = String(text).trim()if (reply && !isGroupPassText(reply)) {+ recordGroupActivity(group, { kind: 'delivered', member: member.name, thread: strandedThread })appendGroupChatEntry(group,{ kind: 'member', name: member.name, ...(member.remoteSource ? { source: member.connectionLabel || member.connectionId } : {}) },@@ -4283,6 +4382,7 @@ async function runGroupChatRounds(group, members, thread) {// late, never lost.for (const member of members) {if (!isCurrent()) {+ recordGroupActivity(group, { kind: 'cancelled', member: null, thread })return}@@ -4309,6 +4409,9 @@ async function runGroupChatRounds(group, members, thread) {for (const member of responders) {if (!isCurrent() || posted >= GROUP_CHAT_MAX_MESSAGES) {+ if (!isCurrent()) {+ recordGroupActivity(group, { kind: 'cancelled', member: null, thread })+ }return}@@ -4350,6 +4453,7 @@ async function runGroupChatRounds(group, members, thread) {try {reply = await runGroupChatMemberTurn(group, member, prompt, thread, deltaImages)} catch {+ recordGroupActivity(group, { kind: 'failed', member: member.name, thread })reply = null // a failed turn is a pass, never a room error}@@ -4382,6 +4486,7 @@ async function runGroupChatRounds(group, members, thread) {}} finally {if (isCurrent()) {+ recordGroupActivity(group, { kind: 'settled', member: null, thread })updateGroupChat(group, r => {r.running = falser.turn = null@@ -4417,6 +4522,8 @@ function sendToGroupChat(group, members, text, thread, images) {return room})+ recordGroupActivity(group, { kind: 'queued', member: 'You', thread: target })+if (!wasRunning) {void runGroupChatRounds(group, members, target).catch(() => {updateGroupChat(group, r => {@@ -8616,6 +8723,12 @@ function GroupChatWorkspace({ group, members, onBack }) {void filesToGroupAttachments(files).then(picked => addImages(replyThread, picked))}+ // Collapsible Activity view: collapsed by default — opening it is always an+ // explicit user action, it never steals focus, and it never auto-scrolls.+ const [activityOpen, setActivityOpen] = useState(false)+ // Subscribe: activity rows re-render as turn events land.+ useValue($groupActivity)+const header = jsxs('div', {className: 'flex items-center gap-2 px-2.5 pt-2.5 pb-2',children: [@@ -8682,6 +8795,71 @@ function GroupChatWorkspace({ group, members, onBack }) {title: (b.remoteSource ? '' : allMeta[b.name]?.title) || b.title || ''}))+ // Activity disclosure: quiet, collapsed by default. The collapsed row shows+ // the latest event; expanding lists the current run's events newest-first.+ // Events are epoch-tagged, so a superseded run's history drops out of view.+ const activityEvents = currentGroupActivity(group)+ const latestActivity = activityEvents.length ? activityEvents[activityEvents.length - 1] : null+ const activityPanel = jsxs('div', {+ className: 'border-b border-(--ui-stroke-secondary)',+ children: [+ jsxs('button', {+ type: 'button',+ 'aria-expanded': activityOpen,+ 'aria-controls': `group-activity:${group}`,+ title: activityOpen ? 'Hide room activity' : 'Show room activity',+ className:+ 'flex w-full items-center gap-1.5 px-2.5 py-1 text-left text-[0.7rem] text-(--ui-text-quaternary) transition-colors hover:text-foreground',+ onClick: () => setActivityOpen(prev => !prev),+ children: [+ jsx(Codicon, {+ name: activityOpen ? 'chevron-down' : 'chevron-right',+ className: 'shrink-0 text-[0.65rem]'+ }),+ jsx('span', { className: 'shrink-0 font-medium', children: 'Activity' }),+ latestActivity+ ? jsx('span', {+ className: 'min-w-0 flex-1 truncate',+ children: `${groupActivityLabel(latestActivity)} · ${relativeTime(latestActivity.at)}`+ })+ : null+ ]+ }),+ activityOpen+ ? jsx('div', {+ id: `group-activity:${group}`,+ className: 'grid gap-0.5 px-2.5 pb-1.5',+ children: activityEvents.length+ ? [...activityEvents]+ .reverse()+ .map((event, i) =>+ jsxs('div', {+ className: 'flex items-center gap-1.5 text-[0.7rem]',+ children: [+ jsx(Codicon, {+ name: GROUP_ACTIVITY_GLYPHS[event.kind] || 'circle-outline',+ className: cn('shrink-0 text-[0.65rem]', groupActivityTone(event.kind))+ }),+ jsx('span', {+ className: cn('min-w-0 flex-1 truncate', groupActivityTone(event.kind)),+ children: groupActivityLabel(event)+ }),+ jsx('span', {+ className: 'shrink-0 text-[0.625rem] text-(--ui-text-quaternary)',+ children: relativeTime(event.at)+ })+ ]+ }, `${event.at}:${i}`)+ )+ : jsx('div', {+ className: 'px-0.5 pb-0.5 text-[0.625rem] text-(--ui-text-quaternary)',+ children: 'No activity in this turn yet.'+ })+ })+ : null+ ]+ })+const submit = () => {const text = draft.trim()const images = imagesFor(null)@@ -9056,6 +9234,7 @@ function GroupChatWorkspace({ group, members, onBack }) {}, 'dropzone'): null,header,+ activityPanel,jsx(ScrollArea, {className: 'min-h-0 flex-1',children: jsxs('div', {diff --git a/apps/desktop/src/plugins/hermes-bots/tests/group-activity.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/group-activity.test.mjsnew file mode 100644index 00000000000..8cb8d30df51--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/tests/group-activity.test.mjs@@ -0,0 +1,269 @@+import assert from 'node:assert/strict'+import { readFileSync } from 'node:fs'+import test from 'node:test'+import vm from 'node:vm'++// Collapsible group Activity view: a runtime-only, bounded feed of truthful+// turn events (queued / working / replied / passed / timed-out / failed /+// cancelled / settled / delivered) that the room shows in a quiet disclosure.+// The transcript stays the only durable record — activity is never persisted.++const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')++/** Load the plugin in a vm with a scripted gateway so member turns are+ * deterministic. `turnScript(profile, prompt, n, session)` returns the+ * member's reply text, a promise of it, or throws for a failed turn. */+function load(turnScript = () => '(pass)') {+ const values = new Map()+ const atom = initial => {+ const slot = { get: () => values.get(slot), set: value => values.set(slot, value) }+ values.set(slot, initial)+ return slot+ }+ const calls = []+ const sessions = new Map()+ const runtimeToStored = new Map()+ const titleToStored = new Map()+ let sessionSequence = 0++ const resolveSession = (profile, target) => {+ const stored = runtimeToStored.get(target) || (sessions.has(target) ? target : titleToStored.get(`${profile}::${target}`))+ return stored ? sessions.get(stored) : null+ }+ const context = {+ atom,+ setTimeout: fn => {+ fn()+ return 0+ },+ clearTimeout: () => undefined,+ PALETTE_AREA: 'palette',+ COMPOSER_AREAS: { middleware: 'middleware' },+ document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },+ host: {+ request: async (method, params) => {+ if (method === 'session.create') {+ sessionSequence += 1+ const stored = `sid-${params.profile}-${sessionSequence}`+ const runtime = `rt-${params.profile}-${sessionSequence}`+ const session = { stored, runtime, profile: params.profile, title: params.title, messages: [] }+ sessions.set(stored, session)+ runtimeToStored.set(runtime, stored)+ titleToStored.set(`${params.profile}::${params.title}`, stored)+ return { session_id: runtime, stored_session_id: stored, message_count: 0, messages: [] }+ }+ if (method === 'session.resume') {+ const session = resolveSession(params.profile, params.session_id)+ if (!session) {+ throw new Error(`session not found: ${params.session_id}`)+ }+ return {+ session_id: session.runtime,+ session_key: session.stored,+ message_count: session.messages.length,+ messages: [...session.messages],+ inflight: false,+ running: false+ }+ }+ if (method === 'prompt.submit') {+ const session = resolveSession(null, params.session_id)+ if (!session) {+ throw new Error(`runtime session not found: ${params.session_id}`)+ }+ session.messages.push({ role: 'user', content: params.text })+ calls.push({+ profile: session.profile,+ prompt: params.text,+ runtime: session.runtime,+ stored: session.stored,+ title: session.title+ })+ const reply = await turnScript(session.profile, params.text, calls.length, session)+ session.messages.push({ role: 'assistant', content: reply })+ return {}+ }+ return {}+ },+ state: { profile: { get: () => 'default', listen: () => undefined }, gateway: { listen: () => undefined } },+ notify: () => undefined,+ notifyError: () => undefined+ }+ }+ const source = pluginSource+ .replace(/^import\s+\*\s+as\s+sdk\s+from '@hermes\/plugin-sdk'\r?\n/m, '')+ .replace(/^import\s+\{[\s\S]*?\}\s+from '@hermes\/plugin-sdk'\r?\n/m, '')+ .replace(/^const \{ McpTab, ToolsetConfigPanel \} = sdk\r?\n/m, '')+ .replace(/^import .* from 'react'\r?\n/m, '')+ .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')+ .replace('export default {', 'globalThis.plugin = {')+ .concat(+ '\nglobalThis.__ga = { sendToGroupChat, recordGroupActivity, currentGroupActivity, groupActivityLabel, updateGroupChat, $groupChats, $groupActivity, GROUP_ACTIVITY_LIMIT };\n'+ )+ vm.runInNewContext(source, context, { filename: 'plugin.js' })+ const storageWrites = new Map()+ context.plugin.register({+ storage: { get: () => null, set: (key, value) => storageWrites.set(key, value) },+ register: () => undefined+ })+ return { ...context.__ga, calls, sessions, storageWrites }+}++const MEMBERS = [{ name: 'research', title: '' }, { name: 'builder', title: '' }, { name: 'ops', title: 'The Ops' }]++async function drain(gc, group) {+ for (let i = 0; i < 200 && (gc.$groupChats.get()[group] || {}).running; i++) {+ await new Promise(resolve => setImmediate(resolve))+ }+}++function feed(gc, group) {+ return gc.$groupActivity.get()[group]?.events || []+}++test('a settled turn records the full truthful arc: queued, working, replies and passes, settled', async () => {+ const gc = load((profile, prompt) => {+ if (profile === 'research' && !prompt.includes('(you)')) {+ return 'I looked into it — ship it.'+ }+ return '(pass)'+ })++ gc.sendToGroupChat('Room', MEMBERS, 'please review')+ await drain(gc, 'Room')++ const events = feed(gc, 'Room')+ const kinds = events.map(e => e.kind)+ assert.equal(kinds[0], 'queued', 'the send lands first')+ assert.equal(kinds[kinds.length - 1], 'settled', 'the run ends with a settle')+ assert.equal(kinds.filter(k => k === 'working').length >= 3, true, 'every member on turn shows working')+ assert.equal(kinds.includes('replied'), true, 'a real reply records replied')+ assert.equal(kinds.filter(k => k === 'passed').length >= 2, true, 'silent members record passed')+ const replied = events.find(e => e.kind === 'replied')+ assert.equal(replied.member, 'research')+})++test('a failed member turn records failed instead of a phantom reply', async () => {+ const gc = load(profile => {+ if (profile === 'builder') {+ throw new Error('gateway hiccup')+ }+ return '(pass)'+ })++ gc.sendToGroupChat('Flaky', MEMBERS, 'anyone around?')+ await drain(gc, 'Flaky')++ const events = feed(gc, 'Flaky')+ assert.equal(events.some(e => e.kind === 'failed' && e.member === 'builder'), true)+})++test('a newer send interrupts the previous run and records cancelled in the CURRENT epoch', async () => {+ const gates = [null, null]+ const gate = n => {+ gates[n] = gates[n] || { promise: null, resolve: null }+ if (!gates[n].promise) {+ gates[n].promise = new Promise(resolve => {+ gates[n].resolve = resolve+ })+ }+ return gates[n].promise+ }+ const gc = load((profile, prompt, n) => gate(n))+ const member = [{ name: 'research', title: '' }]++ gc.sendToGroupChat('Busy', member, 'first ask')+ for (let i = 0; i < 50 && gc.calls.length < 1; i++) {+ await new Promise(resolve => setImmediate(resolve))+ }+ gc.sendToGroupChat('Busy', member, 'second ask, supersede')+ for (let i = 0; i < 50 && gc.calls.length < 2; i++) {+ await new Promise(resolve => setImmediate(resolve))+ }++ gates[2].resolve('from the new run')+ await drain(gc, 'Busy')+ gates[1].resolve('late from the old run')+ await new Promise(resolve => setImmediate(resolve))+ await new Promise(resolve => setImmediate(resolve))++ const epoch = (gc.$groupChats.get().Busy || {}).epoch || 0+ const events = feed(gc, 'Busy')+ assert.equal(events.some(e => e.kind === 'cancelled'), true, 'the superseded loop reports its own interruption')+ // The view shows only the current run: every visible event is this epoch.+ assert.equal(gc.currentGroupActivity('Busy').every(e => (e.epoch || 0) === epoch), true)+ assert.equal(gc.currentGroupActivity('Busy').some(e => e.kind === 'cancelled'), true)+})++test('epoch filtering drops events from a superseded run', () => {+ const gc = load()+ gc.updateGroupChat('Epoch', r => {+ r.log = []+ r.epoch = 5+ return r+ })+ gc.recordGroupActivity('Epoch', { kind: 'queued', member: 'You' })+ gc.recordGroupActivity('Epoch', { kind: 'working', member: 'research' })++ gc.updateGroupChat('Epoch', r => {+ r.epoch = 6+ return r+ })++ assert.equal(gc.currentGroupActivity('Epoch').length, 0, 'old-run events drop out of view')++ gc.recordGroupActivity('Epoch', { kind: 'working', member: 'research' })+ const current = gc.currentGroupActivity('Epoch')+ assert.equal(current.length, 1)+ assert.equal(current[0].kind, 'working')+})++test('the feed is bounded and never grows past GROUP_ACTIVITY_LIMIT', () => {+ const gc = load()+ gc.updateGroupChat('Cap', r => {+ r.log = []+ return r+ })++ for (let i = 0; i < gc.GROUP_ACTIVITY_LIMIT + 25; i++) {+ gc.recordGroupActivity('Cap', { kind: 'working', member: 'research' })+ }++ assert.equal(feed(gc, 'Cap').length, gc.GROUP_ACTIVITY_LIMIT)+})++test('activity is runtime-only: never persisted, never hydrated', async () => {+ const gc = load()+ gc.sendToGroupChat('Volatile', MEMBERS, 'hello')+ await drain(gc, 'Volatile')++ assert.equal(gc.storageWrites.has('group-activity'), false, 'no activity storage key is ever written')+ assert.doesNotMatch(pluginSource, /['"]group-activity['"]/, 'the plugin never reads or writes an activity key')+})++test('labels read like a person wrote them, with settled/cancelled as room-level lines', () => {+ const gc = load()+ assert.equal(gc.groupActivityLabel({ kind: 'queued', member: 'You' }), 'You sent a message')+ assert.equal(gc.groupActivityLabel({ kind: 'replied', member: 'research' }), 'research replied')+ assert.equal(gc.groupActivityLabel({ kind: 'timed-out', member: 'ops' }), 'ops took too long')+ assert.equal(gc.groupActivityLabel({ kind: 'cancelled', member: null }), 'turn interrupted by a newer message')+ assert.equal(gc.groupActivityLabel({ kind: 'settled', member: null }), 'turn settled')+})++test('source contract: the workspace mounts a quiet, collapsed-by-default disclosure', () => {+ // Collapsed default — opening is always an explicit user action.+ assert.match(pluginSource, /const \[activityOpen, setActivityOpen\] = useState\(false\)/)+ // Accessible disclosure pattern.+ assert.match(pluginSource, /'aria-expanded': activityOpen/)+ assert.match(pluginSource, /'aria-controls': `group-activity:\$\{group\}`/)+ // The panel body never steals focus and never auto-scrolls.+ const panel = pluginSource.slice(pluginSource.indexOf('// Activity disclosure:'), pluginSource.indexOf('const submit = () => {'))+ assert.doesNotMatch(panel, /autoFocus/)+ assert.doesNotMatch(panel, /autoScroll|scrollIntoView/)+ // Truthful event vocabulary is wired.+ assert.match(pluginSource, /'timed-out': 'took too long'/)+ assert.match(pluginSource, /cancelled: 'turn interrupted by a newer message'/)+ // The panel sits inside the workspace between the header and the log.+ const workspace = pluginSource.slice(pluginSource.indexOf('function GroupChatWorkspace('), pluginSource.indexOf('function GroupChatMainView('))+ assert.match(workspace, /header,\s*\n\s*activityPanel,/s)+})