The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): gate the live reaction paint on the active source and scope its overlay by it
Brooklyn Nicholsonaf394176e623
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/desktop-bridge.reaction.test.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/desktop-bridge.reaction.test.tsindex 8c4fe90b2e9..8427499f8b9 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/desktop-bridge.reaction.test.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/desktop-bridge.reaction.test.ts@@ -9,7 +9,17 @@ import type { GatewayEventContext } from './types'vi.mock('@/app/right-sidebar/terminal/agent-terminal-stream', () => ({ writeAgentTerminalChunk: vi.fn() }))vi.mock('@/app/right-sidebar/terminal/terminals', () => ({ closeAgentTerminalByProc: vi.fn() }))vi.mock('@/store/pane-focus', () => ({ applyDesktopLayoutPreset: vi.fn(), revealDesktopPane: vi.fn() }))-vi.mock('@/store/reactions-local', () => ({ recordAgentReaction: vi.fn() }))+vi.mock('@/store/reactions-local', async () => {+ const { registryBackendScopeKey } = await import('@hermes/shared')++ return {+ recordAgentReaction: vi.fn(),+ // Same derivation the real store exports, so the scope asserted below is+ // the scope the handler produces in the app.+ reactionOverlayScope: (event: { connectionId?: string; profile?: string }) =>+ registryBackendScopeKey(event.connectionId ?? null, event.profile ?? null)+ }+})vi.mock('@/store/session', () => ({ setMessages: vi.fn() }))vi.mock('@/store/tips', () => ({$tipsEnabled: { get: () => false },@@ -17,15 +27,17 @@ vi.mock('@/store/tips', () => ({showTip: vi.fn()}))-const reactionEvent = (isActiveEvent: boolean): GatewayEventContext =>+const AGENT_THUMBS_UP = [{ emoji: 'π', author: 'agent' }]++const reactionEvent = (overrides: Partial<GatewayEventContext> = {}): GatewayEventContext =>({- event: { type: 'message.reaction' },- isActiveEvent,- payload: {- row_id: 4242,- role: 'assistant',- reactions: [{ emoji: 'π', author: 'agent' }]- }+ // A registry-tagged event from connection "conn-a" β the shape the+ // gateway registry stamps before fan-in.+ event: { connectionId: 'conn-a', profile: 'default', type: 'message.reaction' },+ isActiveEvent: true,+ fromActiveSource: () => true,+ payload: { row_id: 4242, role: 'assistant', reactions: AGENT_THUMBS_UP },+ ...overrides}) as unknown as GatewayEventContextdescribe('message.reaction bridge session scope', () => {@@ -35,13 +47,23 @@ describe('message.reaction bridge session scope', () => {})it('a background session event never mutates the visible transcript or the overlay', () => {- expect(handleDesktopBridgeEvent(reactionEvent(false))).toBe(true)+ expect(handleDesktopBridgeEvent(reactionEvent({ isActiveEvent: false }))).toBe(true)+ expect(setMessages).not.toHaveBeenCalled()+ expect(recordAgentReaction).not.toHaveBeenCalled()+ })++ it('an active event from a non-active source is dropped, not painted onto the visible transcript', () => {+ // isActiveEvent only proves the runtime id matches; two connections can+ // report the same session id. A reaction from source B must not mutate+ // the transcript source A is showing β the owning session paints it+ // from the persisted write on its next load.+ expect(handleDesktopBridgeEvent(reactionEvent({ fromActiveSource: () => false }))).toBe(true)expect(setMessages).not.toHaveBeenCalled()expect(recordAgentReaction).not.toHaveBeenCalled()})it('an active event stamps row id and reactions onto the optimistic bubble', () => {- expect(handleDesktopBridgeEvent(reactionEvent(true))).toBe(true)+ expect(handleDesktopBridgeEvent(reactionEvent())).toBe(true)expect(setMessages).toHaveBeenCalledTimes(1)const updater = vi.mocked(setMessages).mock.calls[0][0]@@ -51,13 +73,13 @@ describe('message.reaction bridge session scope', () => {const next = updater([optimistic] as never)expect(next).toEqual([- { ...optimistic, rowId: 4242, reactions: [{ emoji: 'π', author: 'agent' }] }+ { ...optimistic, rowId: 4242, reactions: AGENT_THUMBS_UP }])- expect(recordAgentReaction).toHaveBeenCalledWith(4242, [{ emoji: 'π', author: 'agent' }])+ expect(recordAgentReaction).toHaveBeenCalledWith(4242, AGENT_THUMBS_UP, 'conn:conn-a::default')})it('an active event matches the byRowId leg without touching optimistic rows', () => {- expect(handleDesktopBridgeEvent(reactionEvent(true))).toBe(true)+ expect(handleDesktopBridgeEvent(reactionEvent())).toBe(true)const updater = vi.mocked(setMessages).mock.calls[0][0]@@ -66,8 +88,8 @@ describe('message.reaction bridge session scope', () => {const optimistic = { id: 'm2', role: 'assistant', rowId: undefined }const next = updater([durable, optimistic] as never)- expect(next[0]).toEqual({ ...durable, reactions: [{ emoji: 'π', author: 'agent' }] })+ expect(next[0]).toEqual({ ...durable, reactions: AGENT_THUMBS_UP })expect(next[1]).toBe(optimistic)- expect(recordAgentReaction).toHaveBeenCalledWith(4242, [{ emoji: 'π', author: 'agent' }])+ expect(recordAgentReaction).toHaveBeenCalledWith(4242, AGENT_THUMBS_UP, 'conn:conn-a::default')})})diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/desktop-bridge.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/desktop-bridge.tsindex 1f70fe4dbb0..3ec64ca7cab 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/desktop-bridge.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/desktop-bridge.ts@@ -1,7 +1,7 @@import { writeAgentTerminalChunk } from '@/app/right-sidebar/terminal/agent-terminal-stream'import { closeAgentTerminalByProc } from '@/app/right-sidebar/terminal/terminals'import { applyDesktopLayoutPreset, revealDesktopPane } from '@/store/pane-focus'-import { recordAgentReaction } from '@/store/reactions-local'+import { recordAgentReaction, reactionOverlayScope } from '@/store/reactions-local'import { setMessages } from '@/store/session'import { $tipsEnabled, type ActiveTip, agentTipId, showTip } from '@/store/tips'@@ -64,7 +64,7 @@ const DESKTOP_BRIDGE_HANDLERS: Record<string, (ctx: GatewayEventContext) => void}},- 'message.reaction': ({ payload, isActiveEvent }) => {+ 'message.reaction': ({ payload, isActiveEvent, fromActiveSource, event }) => {// The agent reacted to a message via the desktop-gated// react_to_message tool. Already persisted β this only paints it now// instead of at the next resume. Fresh ChatMessage object per change:@@ -76,11 +76,23 @@ const DESKTOP_BRIDGE_HANDLERS: Record<string, (ctx: GatewayEventContext) => void// optimistic bubble, or onto a coincidental same-rowid message from a// different profile's DB. The owning session paints it from the// persisted write on its next load.+ //+ // `isActiveEvent` alone proves the RUNTIME id matches, not the SOURCE:+ // two connections can report the same session id, and a reaction from+ // source B would mutate the transcript source A is showing. The+ // dispatcher's `fromActiveSource()` compares the composite+ // (connectionId, profile) scope β same gate as the setup.ready /+ // skin.changed broadcasts β so only the source that owns the visible+ // session paints. The overlay entry carries that scope, and a read+ // keys the displayed session's own source (see agentLiveReactions), so+ // a stale entry can never outrank a different source's persisted+ // reaction at the same row id.const reactedRowId = payload?.row_id- if (isActiveEvent && typeof reactedRowId === 'number') {+ if (isActiveEvent && fromActiveSource() && typeof reactedRowId === 'number') {const nextReactions = Array.isArray(payload?.reactions) ? payload.reactions : []const reactedRole = payload?.role === 'assistant' ? 'assistant' : 'user'+ const overlayScope = reactionOverlayScope(event)setMessages(messages => {// Preferred leg: the message already knows its durable row id@@ -90,7 +102,7 @@ const DESKTOP_BRIDGE_HANDLERS: Record<string, (ctx: GatewayEventContext) => voidif (byRowId) {// Overlay survives the end-of-turn resume, which rebuilds from// in-memory history that doesn't carry this mid-turn DB write.- recordAgentReaction(reactedRowId, nextReactions)+ recordAgentReaction(reactedRowId, nextReactions, overlayScope)return messages.map(message =>message.rowId === reactedRowId ? { ...message, reactions: nextReactions } : message@@ -108,7 +120,7 @@ const DESKTOP_BRIDGE_HANDLERS: Record<string, (ctx: GatewayEventContext) => voidreturn messages}- recordAgentReaction(reactedRowId, nextReactions)+ recordAgentReaction(reactedRowId, nextReactions, overlayScope)return messages.map((message, index) =>index === lastIndex ? { ...message, rowId: reactedRowId, reactions: nextReactions } : messagediff --git a/apps/desktop/src/components/assistant-ui/thread/use-message-reactions.ts b/apps/desktop/src/components/assistant-ui/thread/use-message-reactions.tsindex 6fe52bb23df..2ec788e8774 100644--- a/apps/desktop/src/components/assistant-ui/thread/use-message-reactions.ts+++ b/apps/desktop/src/components/assistant-ui/thread/use-message-reactions.ts@@ -1,3 +1,4 @@+import { registryBackendScopeKey } from '@hermes/shared'import { useAuiState, useMessageRuntime } from '@assistant-ui/react'import { useStore } from '@nanostores/react'import { type MouseEvent, useCallback } from 'react'@@ -5,9 +6,18 @@ import { type MouseEvent, useCallback } from 'react'import { useSessionView } from '@/app/chat/session-view'import type { ChatMessage } from '@/lib/chat-messages'import { triggerHaptic } from '@/lib/haptics'+import { activeGatewayConnectionId } from '@/store/gateway'+import { $activeGatewayProfile } from '@/store/profile'import { QUICK_REACTIONS, toggleMessageReaction } from '@/store/reactions'import { $reactionsEnabled } from '@/store/reactions-enabled'-import { $agentReactions, $localReactions, mergeReactions, setLocalReaction } from '@/store/reactions-local'+import {+ $agentReactions,+ $localReactions,+ agentLiveReactions,+ mergeReactions,+ setLocalReaction+} from '@/store/reactions-local'+import { sessionEventScopeFor } from '@/store/session-states'import type { MessageReaction } from '@/types/hermes'// Stable empty identity β a fresh [] per render would re-run every consumer.@@ -82,19 +92,31 @@ export function useMessageReactions(const enabled = useStore($reactionsEnabled)const localAll = useStore($localReactions)- const agentLive = useStore($agentReactions)+ const agentAll = useStore($agentReactions)const sessionView = useSessionView()const runtimeSessionId = useStore(sessionView.$runtimeId)const storedSessionId = useStore(sessionView.$storedId)const sessionId = runtimeSessionId ?? storedSessionId+ // The agent overlay is keyed by bare DB row id, and row ids are only+ // meaningful within ONE source's database. Resolve the source this+ // displayed session actually belongs to β the scope its own events+ // proved, falling back to the actively served source when the runtime's+ // events arrived untagged (local legacy primary) β so an overlay recorded+ // on source A can never repaint a coincidental same-numbered row on+ // source B (a tile from another connection, a cross-source resume).+ const activeProfile = useStore($activeGatewayProfile)+ const viewScope =+ sessionEventScopeFor(runtimeSessionId) ?? registryBackendScopeKey(activeGatewayConnectionId(), activeProfile)+ const agentLive = rowId === undefined ? undefined : agentLiveReactions(agentAll, rowId, viewScope)+return {enabled,react: useCallback((emoji: null | string) => commitReaction(messageId, role, rowId, reactions, emoji, sessionId),[messageId, reactions, role, rowId, sessionId]),- reactions: mergeReactions(reactions, localAll[messageId], rowId === undefined ? undefined : agentLive[rowId])+ reactions: mergeReactions(reactions, localAll[messageId], agentLive)}}diff --git a/apps/desktop/src/store/reactions-local.test.ts b/apps/desktop/src/store/reactions-local.test.tsindex cbb2b4158e2..ac4517011c6 100644--- a/apps/desktop/src/store/reactions-local.test.ts+++ b/apps/desktop/src/store/reactions-local.test.ts@@ -7,6 +7,7 @@ import { $activeGatewayProfile } from '@/store/profile'import {$agentReactions,$localReactions,+ agentLiveReactions,clearLiveReactionOverlays,mergeReactions,recordAgentReaction,@@ -88,11 +89,14 @@ vi.mock('@/store/transcript-tail', () => ({ clearTranscriptTailPaging: vi.fn() }vi.mock('@/store/transcript-tail-cache', () => ({ clearTranscriptTails: vi.fn() }))const AGENT_THUMBS_UP: MessageReaction[] = [{ at: 1, author: 'agent', emoji: 'π' }]+const SOURCE_A = 'conn:source-a::default'+const SOURCE_B = 'conn:source-b::default'-const reactionEvent = (isActiveEvent: boolean): GatewayEventContext =>+const reactionEvent = (overrides: Partial<GatewayEventContext> = {}): GatewayEventContext =>({- event: { type: 'message.reaction' },- isActiveEvent,+ event: { connectionId: 'source-a', profile: 'default', type: 'message.reaction' },+ isActiveEvent: true,+ fromActiveSource: () => true,payload: { row_id: 4242, reactions: AGENT_THUMBS_UP, role: 'assistant' }}) as unknown as GatewayEventContext@@ -101,20 +105,46 @@ describe('live reaction overlay scope', () => {clearLiveReactionOverlays()})- it('a real message.reaction event records into the overlay, and merge prefers it over persisted', () => {+ it('a real message.reaction event records into the overlay scoped to its source, and merge prefers it over persisted', () => {// An optimistic bubble awaiting its durable row id is the stamping target.$messages.set([{ id: 'm1', role: 'assistant' }] as never)- expect(handleDesktopBridgeEvent(reactionEvent(true))).toBe(true)- expect($agentReactions.get()[4242]).toEqual(AGENT_THUMBS_UP)+ expect(handleDesktopBridgeEvent(reactionEvent())).toBe(true)++ const overlay = $agentReactions.get()[4242]++ expect(overlay?.scope).toBe(SOURCE_A)+ expect(overlay?.reactions).toEqual(AGENT_THUMBS_UP)expect($messages.get()).toEqual([{ id: 'm1', reactions: AGENT_THUMBS_UP, role: 'assistant', rowId: 4242 }])expect(- mergeReactions([{ at: 0, author: 'agent', emoji: 'π΄' }], undefined, $agentReactions.get()[4242])+ mergeReactions(+ [{ at: 0, author: 'agent', emoji: 'π΄' }],+ undefined,+ agentLiveReactions($agentReactions.get(), 4242, SOURCE_A)+ )).toEqual(AGENT_THUMBS_UP)})+ it('a foreign source never sees the overlay: its persisted reaction at the same row id wins', () => {+ // Focusing a session tile from connection B does not change the ambient+ // profile, so an overlay recorded while source A was on screen used to+ // override B's persisted reaction at the coincidental same row id. The+ // read keys the displayed session's own source (connection + profile),+ // so B falls back to what its transcript carried.+ recordAgentReaction(4242, AGENT_THUMBS_UP, SOURCE_A)++ const persistedForB: MessageReaction[] = [{ at: 0, author: 'agent', emoji: 'π΄' }]++ expect(agentLiveReactions($agentReactions.get(), 4242, SOURCE_B)).toBeUndefined()+ expect(+ mergeReactions(persistedForB, undefined, agentLiveReactions($agentReactions.get(), 4242, SOURCE_B))+ ).toEqual(persistedForB)+ // The owning source still sees its live overlay.+ expect(agentLiveReactions($agentReactions.get(), 4242, SOURCE_A)).toEqual(AGENT_THUMBS_UP)+ })+it('a profile swap clears the overlay so a foreign row id cannot repaint', () => {- recordAgentReaction(4242, AGENT_THUMBS_UP)+ recordAgentReaction(4242, AGENT_THUMBS_UP, 'default')setLocalReaction('msg-1', 'β€οΈ')expect($agentReactions.get()[4242]).toBeDefined()@@ -124,20 +154,24 @@ describe('live reaction overlay scope', () => {expect($localReactions.get()).toEqual({})// The durable reaction survives the wipe: merge falls back to persisted.expect(- mergeReactions([{ at: 0, author: 'agent', emoji: 'π΄' }], undefined, $agentReactions.get()[4242])+ mergeReactions(+ [{ at: 0, author: 'agent', emoji: 'π΄' }],+ undefined,+ agentLiveReactions($agentReactions.get(), 4242, 'work')+ )).toEqual([{ at: 0, author: 'agent', emoji: 'π΄' }])})it('a same-profile set is not a swap and keeps live overlays', () => {- recordAgentReaction(4242, AGENT_THUMBS_UP)+ recordAgentReaction(4242, AGENT_THUMBS_UP, 'default')$activeGatewayProfile.set($activeGatewayProfile.get())- expect($agentReactions.get()[4242]).toEqual(AGENT_THUMBS_UP)+ expect(agentLiveReactions($agentReactions.get(), 4242, 'default')).toEqual(AGENT_THUMBS_UP)})it('a connection switch wipes the overlays along with the rest of the outgoing transcript', () => {- recordAgentReaction(4242, AGENT_THUMBS_UP)+ recordAgentReaction(4242, AGENT_THUMBS_UP, SOURCE_A)setLocalReaction('msg-1', 'β€οΈ')wipeSessionListsForGatewaySwitch()diff --git a/apps/desktop/src/store/reactions-local.ts b/apps/desktop/src/store/reactions-local.tsindex e6829d8d33e..35ca03a6fc2 100644--- a/apps/desktop/src/store/reactions-local.ts+++ b/apps/desktop/src/store/reactions-local.ts@@ -1,5 +1,7 @@import { atom } from 'nanostores'+import { registryBackendScopeKey } from '@hermes/shared'+import { $activeGatewayProfile } from '@/store/profile'import { applyReaction } from '@/store/reactions'import type { MessageReaction } from '@/types/hermes'@@ -24,16 +26,52 @@ export const $localReactions = atom<Record<string, MessageReaction[]>>({})* carry a reaction written to the DB mid-turn β this overlay outlives that* clobber and a real reload hydrates the same reaction from disk.*/-export const $agentReactions = atom<Record<number, MessageReaction[]>>({})+export interface AgentReactionOverlay {+ /** Composite source identity (connection + profile) the recording event+ * came from β see the overlay-scope note below. */+ scope: string+ reactions: MessageReaction[]+}++/**+ * Row ids are per-DATABASE, so a bare row id only names a message within ONE+ * source's state.db. Each entry therefore carries the full source identity+ * (`registryBackendScopeKey(connectionId, profile)`) of the event that+ * recorded it, and a reader only sees an entry whose scope matches the+ * session it is displaying: an overlay recorded while source A was on screen+ * can never repaint source B's row 42, because B's read keys B's own scope+ * and falls back to B's persisted reactions. Clearing on profile/connection+ * swaps remains as memory hygiene; correctness comes from the scope key.+ */+export const $agentReactions = atom<Record<number, AgentReactionOverlay>>({})++/** The live overlay for `rowId` when it was recorded by `scope`'s source. */+export function agentLiveReactions(+ overlays: Record<number, AgentReactionOverlay>,+ rowId: number,+ scope: string+): MessageReaction[] | undefined {+ const overlay = overlays[rowId]-/** Record an agent reaction painted from a live gateway event. */-export function recordAgentReaction(rowId: number, reactions: MessageReaction[]): void {+ return overlay && overlay.scope === scope ? overlay.reactions : undefined+}++/** Record an agent reaction painted from a live gateway event. `scope` is the+ * event's composite source identity (connection + profile). */+export function recordAgentReaction(rowId: number, reactions: MessageReaction[], scope: string): void {$agentReactions.set({...$agentReactions.get(),- [rowId]: reactions.filter(reaction => reaction.author === 'agent')+ [rowId]: { reactions: reactions.filter(reaction => reaction.author === 'agent'), scope }})}+/** The composite source identity a gateway event carries. Pool secondaries+ * and the legacy primary have no registry connection, so their scope is the+ * bare profile name β exactly how `session-states.ts` records event scopes. */+export function reactionOverlayScope(event: { connectionId?: string; profile?: string }): string {+ return registryBackendScopeKey(event.connectionId ?? null, event.profile ?? null)+}+/*** Drop both overlays, called when the row-id space they describe changes.*@@ -44,6 +82,10 @@ export function recordAgentReaction(rowId: number, reactions: MessageReaction[])* regenerated when the transcript reloads; both maps describe messages that* no longer exist, so they go together.*+ * Correctness no longer depends on this wipe β entries are scope-keyed and a+ * different source's read never claims them β but the wipe keeps the maps from+ * describing a backend this window may never show again.+ ** Two boundaries: the $activeGatewayProfile subscribe below covers the* profile swap (same backend, different home/DB); wipeSessionListsForGatewaySwitch* calls this for the connection switch, where the profile name can stay the@@ -58,11 +100,11 @@ export function clearLiveReactionOverlays(): void {// Guard on a real change: a same-value set (reconnect re-asserts the profile)// notifies listeners too, and wiping live overlays mid-turn would drop the// reactions it exists to survive.-let reactionOverlayScope = $activeGatewayProfile.get()+let wipedProfileScope = $activeGatewayProfile.get()$activeGatewayProfile.subscribe(value => {- if (value !== reactionOverlayScope) {- reactionOverlayScope = value+ if (value !== wipedProfileScope) {+ wipedProfileScope = valueclearLiveReactionOverlays()}})diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.tsindex b487a46e8bc..353122e053b 100644--- a/apps/desktop/src/store/session-states.ts+++ b/apps/desktop/src/store/session-states.ts@@ -156,6 +156,19 @@ export function runtimeSessionOwner(sessionId: null | string | undefined): Sessireturn id ? sessionOwnerByRuntimeId.get(id) : undefined}+/** The composite source scope (connection + profile) a runtime's own events+ * proved β `registryBackendScopeKey` of the socket that delivered them.+ * Undefined for a runtime whose events arrived untagged (the local legacy+ * primary), whose source is then whatever gateway is actively serving this+ * window. Reaction-overlay reads key the displayed session's scope with+ * this, so an overlay recorded on one source never paints another+ * source's same-numbered row. */+export function sessionEventScopeFor(runtimeId: null | string | undefined): string | undefined {+ const id = String(runtimeId ?? '').trim()++ return id ? sessionScopeByRuntimeId.get(id) : undefined+}+/** Forget only profile-pool runtime owners during permanent LOCAL profile* teardown. These string routes came exclusively from the legacy secondary* producer; exact connection descriptors must survive a same-named remote