Skip to content

The agent that grows with you

fix(desktop): scope message.reaction events to the active session transcript

beardthelion18628e689c7e
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.ts
new file mode 100644
index 00000000000..8c4fe90b2e9
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/desktop-bridge.reaction.test.ts
@@ -0,0 +1,73 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { recordAgentReaction } from '@/store/reactions-local'
+import { setMessages } from '@/store/session'
+
+import { handleDesktopBridgeEvent } from './desktop-bridge'
+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/session', () => ({ setMessages: vi.fn() }))
+vi.mock('@/store/tips', () => ({
+ $tipsEnabled: { get: () => false },
+ agentTipId: vi.fn(),
+ showTip: vi.fn()
+}))
+
+const reactionEvent = (isActiveEvent: boolean): GatewayEventContext =>
+ ({
+ event: { type: 'message.reaction' },
+ isActiveEvent,
+ payload: {
+ row_id: 4242,
+ role: 'assistant',
+ reactions: [{ emoji: 'πŸ‘', author: 'agent' }]
+ }
+ }) as unknown as GatewayEventContext
+
+describe('message.reaction bridge session scope', () => {
+ beforeEach(() => {
+ vi.mocked(setMessages).mockClear()
+ vi.mocked(recordAgentReaction).mockClear()
+ })
+
+ it('a background session event never mutates the visible transcript or the overlay', () => {
+ expect(handleDesktopBridgeEvent(reactionEvent(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(setMessages).toHaveBeenCalledTimes(1)
+
+ const updater = vi.mocked(setMessages).mock.calls[0][0]
+
+ if (typeof updater !== 'function') {throw new Error('expected an updater function')}
+ const optimistic = { id: 'm1', role: 'assistant', rowId: undefined }
+ const next = updater([optimistic] as never)
+
+ expect(next).toEqual([
+ { ...optimistic, rowId: 4242, reactions: [{ emoji: 'πŸ‘', author: 'agent' }] }
+ ])
+ expect(recordAgentReaction).toHaveBeenCalledWith(4242, [{ emoji: 'πŸ‘', author: 'agent' }])
+ })
+
+ it('an active event matches the byRowId leg without touching optimistic rows', () => {
+ expect(handleDesktopBridgeEvent(reactionEvent(true))).toBe(true)
+
+ const updater = vi.mocked(setMessages).mock.calls[0][0]
+
+ if (typeof updater !== 'function') {throw new Error('expected an updater function')}
+ const durable = { id: 'm1', role: 'assistant', rowId: 4242 }
+ 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[1]).toBe(optimistic)
+ expect(recordAgentReaction).toHaveBeenCalledWith(4242, [{ emoji: 'πŸ‘', author: 'agent' }])
+ })
+})
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.ts
index 20c87c7f748..1f70fe4dbb0 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
@@ -64,15 +64,21 @@ const DESKTOP_BRIDGE_HANDLERS: Record<string, (ctx: GatewayEventContext) => void
}
},
- 'message.reaction': ({ payload }) => {
+ 'message.reaction': ({ payload, isActiveEvent }) => {
// 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:
// the runtime repository caches normalized ThreadMessages in a WeakMap
- // keyed by ChatMessage identity.
+ // keyed by ChatMessage identity. Active session only (same gate as
+ // tip.show/pane.reveal): $messages is the visible transcript and the
+ // reaction overlay is keyed by bare row id, so a background session's
+ // event would stamp its row id and reactions onto this session's
+ // 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.
const reactedRowId = payload?.row_id
- if (typeof reactedRowId === 'number') {
+ if (isActiveEvent && typeof reactedRowId === 'number') {
const nextReactions = Array.isArray(payload?.reactions) ? payload.reactions : []
const reactedRole = payload?.role === 'assistant' ? 'assistant' : 'user'
diff --git a/apps/desktop/src/store/gateway-switch.ts b/apps/desktop/src/store/gateway-switch.ts
index be6a0d6ab8c..c4d73d07535 100644
--- a/apps/desktop/src/store/gateway-switch.ts
+++ b/apps/desktop/src/store/gateway-switch.ts
@@ -10,6 +10,7 @@ import { resetSessionsLimit } from '@/store/layout'
import { resetLiveSync } from '@/store/live-sync'
import { invalidateProfileListFetches } from '@/store/profile'
import { exitProjectScope } from '@/store/project-scope'
+import { clearLiveReactionOverlays } from '@/store/reactions-local'
import {
$unreadFinishedSessionIds,
setActiveSessionId,
@@ -252,6 +253,14 @@ export function wipeSessionListsForGatewaySwitch(): void {
setCurrentCwdTransient('')
setCurrentBranch('')
+ // Reaction overlays describe the outgoing backend's messages: $agentReactions
+ // is keyed by bare DB row id (per-database, so the next backend's row ids name
+ // different messages) and $localReactions by renderer ids the next transcript
+ // regenerates. The profile-swap boundary is covered by the subscribe inside
+ // reactions-local; a connection switch can keep the profile name, so it needs
+ // this explicit wipe.
+ clearLiveReactionOverlays()
+
// Artifacts are keyed by sessions on the previous backend, so both the
// registry and any rail tab pointing into it go with them.
clearArtifactRegistry()
diff --git a/apps/desktop/src/store/reactions-local.test.ts b/apps/desktop/src/store/reactions-local.test.ts
new file mode 100644
index 00000000000..cbb2b4158e2
--- /dev/null
+++ b/apps/desktop/src/store/reactions-local.test.ts
@@ -0,0 +1,148 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { handleDesktopBridgeEvent } from '@/app/session/hooks/use-message-stream/gateway-event/desktop-bridge'
+import type { GatewayEventContext } from '@/app/session/hooks/use-message-stream/gateway-event/types'
+import { wipeSessionListsForGatewaySwitch } from '@/store/gateway-switch'
+import { $activeGatewayProfile } from '@/store/profile'
+import {
+ $agentReactions,
+ $localReactions,
+ clearLiveReactionOverlays,
+ mergeReactions,
+ recordAgentReaction,
+ setLocalReaction
+} from '@/store/reactions-local'
+import { $messages } from '@/store/session'
+import type { MessageReaction } from '@/types/hermes'
+
+vi.mock('@/store/profile', async () => {
+ const { atom: nanoAtom } = await import('nanostores')
+
+ return {
+ $activeGatewayProfile: nanoAtom('default'),
+ invalidateProfileListFetches: vi.fn(),
+ normalizeProfileKey: (value: string | null | undefined) => (value ?? '').trim() || 'default'
+ }
+})
+
+vi.mock('@/store/reactions', () => ({
+ QUICK_REACTIONS: ['❀️'],
+ applyReaction: (_list: unknown, emoji: null | string, author: string) =>
+ emoji ? [{ author, emoji }] : []
+}))
+
+vi.mock('@/store/session', async () => {
+ const { atom: nanoAtom } = await import('nanostores')
+ const $messages = nanoAtom<unknown[]>([])
+
+ return {
+ $messages,
+ $sessions: nanoAtom<unknown[]>([]),
+ $unreadFinishedSessionIds: nanoAtom<string[]>([]),
+ setActiveSessionId: vi.fn(),
+ setCronSessions: vi.fn(),
+ setCurrentBranch: vi.fn(),
+ setCurrentCwdTransient: vi.fn(),
+ setFreshDraftReady: vi.fn(),
+ // Apply the updater for real: recordAgentReaction runs inside it.
+ setMessages: (next: unknown) => {
+ $messages.set(
+ typeof next === 'function' ? (next as (m: unknown[]) => unknown[])($messages.get()) : (next as unknown[])
+ )
+ },
+ setMessagingListServer: vi.fn(),
+ setMessagingPlatformTotals: vi.fn(),
+ setMessagingSessions: vi.fn(),
+ setMessagingTruncated: vi.fn(),
+ setSelectedStoredSessionId: vi.fn(),
+ setSessionProfilesTruncated: vi.fn(),
+ setSessionProfilesUsage: vi.fn(),
+ setSessions: vi.fn(),
+ setSessionsLoadError: vi.fn(),
+ setSessionsLoading: vi.fn()
+ }
+})
+
+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/tips', () => ({ $tipsEnabled: { get: () => false }, agentTipId: vi.fn(), showTip: vi.fn() }))
+vi.mock('@/app/contrib/hooks/use-background-sync', () => ({ resetLiveRuntimeTracking: vi.fn() }))
+vi.mock('@/hermes', () => ({ resetSidebarBatchCapability: vi.fn() }))
+vi.mock('@/lib/query-client', () => ({ invalidateProfileScopedQueries: vi.fn() }))
+vi.mock('@/store/artifacts', () => ({ clearArtifactRegistry: vi.fn() }))
+vi.mock('@/store/cron', () => ({ invalidateCronJobsRequests: vi.fn(), setCronJobs: vi.fn() }))
+vi.mock('@/store/layout', () => ({ resetSessionsLimit: vi.fn() }))
+vi.mock('@/store/live-sync', () => ({ resetLiveSync: vi.fn() }))
+vi.mock('@/store/session-control', () => ({ clearAllSessionControl: vi.fn() }))
+vi.mock('@/store/session-pin-sync', () => ({ resetSessionPinMirror: vi.fn() }))
+vi.mock('@/store/session-states', async () => {
+ const { atom: nanoAtom } = await import('nanostores')
+
+ return {
+ $sessionStates: nanoAtom({}),
+ clearAllSessionStates: vi.fn()
+ }
+})
+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 reactionEvent = (isActiveEvent: boolean): GatewayEventContext =>
+ ({
+ event: { type: 'message.reaction' },
+ isActiveEvent,
+ payload: { row_id: 4242, reactions: AGENT_THUMBS_UP, role: 'assistant' }
+ }) as unknown as GatewayEventContext
+
+describe('live reaction overlay scope', () => {
+ beforeEach(() => {
+ clearLiveReactionOverlays()
+ })
+
+ it('a real message.reaction event records into the overlay, 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($messages.get()).toEqual([{ id: 'm1', reactions: AGENT_THUMBS_UP, role: 'assistant', rowId: 4242 }])
+ expect(
+ mergeReactions([{ at: 0, author: 'agent', emoji: '😴' }], undefined, $agentReactions.get()[4242])
+ ).toEqual(AGENT_THUMBS_UP)
+ })
+
+ it('a profile swap clears the overlay so a foreign row id cannot repaint', () => {
+ recordAgentReaction(4242, AGENT_THUMBS_UP)
+ setLocalReaction('msg-1', '❀️')
+ expect($agentReactions.get()[4242]).toBeDefined()
+
+ $activeGatewayProfile.set('work')
+
+ expect($agentReactions.get()).toEqual({})
+ 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])
+ ).toEqual([{ at: 0, author: 'agent', emoji: '😴' }])
+ })
+
+ it('a same-profile set is not a swap and keeps live overlays', () => {
+ recordAgentReaction(4242, AGENT_THUMBS_UP)
+
+ $activeGatewayProfile.set($activeGatewayProfile.get())
+
+ expect($agentReactions.get()[4242]).toEqual(AGENT_THUMBS_UP)
+ })
+
+ it('a connection switch wipes the overlays along with the rest of the outgoing transcript', () => {
+ recordAgentReaction(4242, AGENT_THUMBS_UP)
+ setLocalReaction('msg-1', '❀️')
+
+ wipeSessionListsForGatewaySwitch()
+
+ expect($agentReactions.get()).toEqual({})
+ expect($localReactions.get()).toEqual({})
+ })
+})
diff --git a/apps/desktop/src/store/reactions-local.ts b/apps/desktop/src/store/reactions-local.ts
index ec04526abb8..e6829d8d33e 100644
--- a/apps/desktop/src/store/reactions-local.ts
+++ b/apps/desktop/src/store/reactions-local.ts
@@ -1,5 +1,6 @@
import { atom } from 'nanostores'
+import { $activeGatewayProfile } from '@/store/profile'
import { applyReaction } from '@/store/reactions'
import type { MessageReaction } from '@/types/hermes'
@@ -33,6 +34,39 @@ export function recordAgentReaction(rowId: number, reactions: MessageReaction[])
})
}
+/**
+ * Drop both overlays, called when the row-id space they describe changes.
+ *
+ * $agentReactions is keyed by bare DB row id and row ids are per-database, so
+ * after a profile swap or a gateway switch every entry could stamp onto a
+ * DIFFERENT message that happens to share the row id in the new backend's
+ * state.db. $localReactions is keyed by renderer message id, which is
+ * regenerated when the transcript reloads; both maps describe messages that
+ * no longer exist, so they go together.
+ *
+ * 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
+ * same while the backend (and its row ids) changes. A same-backend reconnect
+ * keeps the entries: the DB is unchanged and the overlay is still true.
+ */
+export function clearLiveReactionOverlays(): void {
+ $agentReactions.set({})
+ $localReactions.set({})
+}
+
+// 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()
+
+$activeGatewayProfile.subscribe(value => {
+ if (value !== reactionOverlayScope) {
+ reactionOverlayScope = value
+ clearLiveReactionOverlays()
+ }
+})
+
/**
* Merge the durable reaction list with anything this window knows live.
*