The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): subscribe the bot-chat flag to every store it reads
Brooklyn Nicholson0f4d4d4d8bf5
diff --git a/apps/desktop/src/app/chat/composer/index.tsx b/apps/desktop/src/app/chat/composer/index.tsxindex a291a892e3d..3764633db6d 100644--- a/apps/desktop/src/app/chat/composer/index.tsx+++ b/apps/desktop/src/app/chat/composer/index.tsx@@ -13,7 +13,7 @@ import { PR_COMMENT_URL_RE } from '@/lib/chat-runtime'import { sanitizeComposerInput } from '@/lib/composer-input-sanitize'import { DATA_IMAGE_URL_RE } from '@/lib/embedded-images'import { triggerHaptic } from '@/lib/haptics'-import { useStoreSelector } from '@/lib/use-session-slice'+import { useStoresSelector } from '@/lib/use-session-slice'import { cn } from '@/lib/utils'import { interceptsTypedVoiceStop } from '@/lib/voice-stop-word'import { sessionCompacting } from '@/store/compaction'@@ -24,7 +24,7 @@ import { $hudMode } from '@/store/hud'import { sessionBlockingPrompt } from '@/store/prompts'import { toggleReview } from '@/store/review'import { $gatewayState } from '@/store/session'-import { $sessionStates, isBotChatSession } from '@/store/session-states'+import { $botChatSessionIds, $sessionStates, $sessionTiles, isBotChatSession } from '@/store/session-states'import { $threadScrolledUp } from '@/store/thread-scroll'import { $autoSpeakReplies } from '@/store/voice-prefs'import { useTheme } from '@/themes'@@ -949,7 +949,11 @@ export function ChatBar({// A bot chat is a companion conversation, not a working session, so it has no// repo to speak of — see the blank repoPath handed to CodingStatusRow below.- const botChat = useStoreSelector($sessionStates, () => isBotChatSession(sessionId))+ // Three stores: the scope set records the answer, and resolving this runtime+ // id to the stored one it is filed under reads the other two.+ const botChat = useStoresSelector([$botChatSessionIds, $sessionStates, $sessionTiles], () =>+ isBotChatSession(sessionId)+ )// Branch / worktree hand-offs (CodingStatusRow). Owns the worktree open +// branch-off/convert/list/switch actions; draft travels into the new session.diff --git a/apps/desktop/src/lib/use-session-slice.ts b/apps/desktop/src/lib/use-session-slice.tsindex f96d0017420..a7399f588b3 100644--- a/apps/desktop/src/lib/use-session-slice.ts+++ b/apps/desktop/src/lib/use-session-slice.ts@@ -61,3 +61,42 @@ export function useStoreSelector<T, S>(store: ReadableStore<T>, select: (value:return useSyncExternalStore(subscribe, () => selectRef.current(store.get()))}++/**+ * `useStoreSelector` for a scalar whose inputs span SEVERAL stores: recomputes+ * when any of them notifies, still re-rendering only when the scalar changes.+ *+ * Subscribing to one store while the selector reads others is the failure this+ * exists to prevent — it looks correct for as long as the subscribed store+ * happens to churn on its own, then silently goes stale when it doesn't. If a+ * selector reads it, list it.+ */+export function useStoresSelector<S>(stores: readonly ReadableStore<unknown>[], select: () => S): S {+ const selectRef = useRef(select)+ selectRef.current = select++ // Hold the array identity steady: call sites pass an inline literal of+ // module-level singletons, so only a genuine store swap should resubscribe.+ const storesRef = useRef(stores)++ if (storesRef.current.length !== stores.length || storesRef.current.some((store, i) => store !== stores[i])) {+ storesRef.current = stores+ }++ const stable = storesRef.current++ const subscribe = useCallback(+ (onChange: () => void) => {+ const stops = stable.map(store => store.listen(onChange))++ return () => {+ for (const stop of stops) {+ stop()+ }+ }+ },+ [stable]+ )++ return useSyncExternalStore(subscribe, () => selectRef.current())+}diff --git a/apps/desktop/src/lib/use-stores-selector.test.tsx b/apps/desktop/src/lib/use-stores-selector.test.tsxnew file mode 100644index 00000000000..c50aff16db4--- /dev/null+++ b/apps/desktop/src/lib/use-stores-selector.test.tsx@@ -0,0 +1,109 @@+/**+ * `useStoresSelector` — the multi-store form of `useStoreSelector`.+ *+ * It exists because subscribing to one store while the selector reads another+ * looks correct for exactly as long as the subscribed store happens to churn+ * on its own. The composer's bot-chat flag was written that way and rode+ * `$sessionStates`' per-token republish to stay roughly right.+ */++import { render, screen } from '@testing-library/react'+import { atom } from 'nanostores'+import { act } from 'react'+import { describe, expect, it, vi } from 'vitest'++import { useStoresSelector } from './use-session-slice'++describe('a selector recomputes for every store it was given', () => {+ it('follows a change in any of them', () => {+ const left = atom(0)+ const right = atom(0)++ function Probe() {+ const total = useStoresSelector([left, right], () => left.get() + right.get())++ return <span data-testid="total">{total}</span>+ }++ render(<Probe />)++ expect(screen.getByTestId('total').textContent).toBe('0')++ act(() => left.set(2))++ expect(screen.getByTestId('total').textContent).toBe('2')++ // The store a single-subscription version would have missed.+ act(() => right.set(5))++ expect(screen.getByTestId('total').textContent).toBe('7')+ })++ it('re-renders only when the derived scalar actually changes', () => {+ const source = atom(1)+ const renders = vi.fn()++ function Probe() {+ const even = useStoresSelector([source], () => source.get() % 2 === 0)+ renders()++ return <span data-testid="even">{String(even)}</span>+ }++ render(<Probe />)+ const baseline = renders.mock.calls.length++ // 1 -> 3: the store moved, the scalar did not.+ act(() => source.set(3))++ expect(renders.mock.calls.length).toBe(baseline)++ act(() => source.set(4))++ expect(renders.mock.calls.length).toBeGreaterThan(baseline)+ expect(screen.getByTestId('even').textContent).toBe('true')+ })++ it('keeps its subscriptions across renders that pass a fresh array literal', () => {+ const source = atom(0)+ const listen = vi.spyOn(source, 'listen')++ function Probe({ label }: { label: string }) {+ const value = useStoresSelector([source], () => source.get())++ return (+ <span data-testid="value">+ {label}+ {value}+ </span>+ )+ }++ const view = render(<Probe label="a" />)+ const initial = listen.mock.calls.length++ view.rerender(<Probe label="b" />)+ view.rerender(<Probe label="c" />)++ expect(listen.mock.calls.length).toBe(initial)+ })++ it('drops every subscription on unmount', () => {+ const left = atom(0)+ const right = atom(0)++ function Probe() {+ return <span>{useStoresSelector([left, right], () => left.get() + right.get())}</span>+ }++ const view = render(<Probe />)++ expect(left.lc).toBeGreaterThan(0)+ expect(right.lc).toBeGreaterThan(0)++ view.unmount()++ expect(left.lc).toBe(0)+ expect(right.lc).toBe(0)+ })+})diff --git a/apps/desktop/src/store/bot-chat-scope.test.ts b/apps/desktop/src/store/bot-chat-scope.test.tsnew file mode 100644index 00000000000..9098c2a7427--- /dev/null+++ b/apps/desktop/src/store/bot-chat-scope.test.ts@@ -0,0 +1,88 @@+/**+ * `$botChatSessionIds` is the store a surface must SUBSCRIBE to when it asks+ * `isBotChatSession`.+ *+ * The composer originally subscribed to `$sessionStates` while reading this+ * set. It looked fine because `$sessionStates` churns constantly — busy flags,+ * stream ticks — so the stale answer was overwritten within a frame or two.+ * The assertion that matters is the one that made that wrong: this set moves on+ * its own, with no `$sessionStates` write anywhere near it, so a subscriber to+ * the other store can miss the transition entirely.+ */++import { beforeEach, describe, expect, it } from 'vitest'++const { $botChatSessionIds, $sessionStates, $sessionTiles, isBotChatSession, setSessionTileWorkspaceScope } =+ await import('./session-states')++const botScope = { workspaceMode: 'bots' as const, workspaceOwnerKey: 'bot:alpha' }++beforeEach(() => {+ $botChatSessionIds.set(new Set())+ // isBotChatSession takes a LIVE session id and files the answer under the+ // stored one, so a binding has to exist for the lookup to resolve at all.+ $sessionTiles.set([{ runtimeId: 'runtime-1', storedSessionId: 'stored-1' } as never])+})++describe('the bot-chat set moves independently of session state', () => {+ it('notifies its own listeners without touching $sessionStates', () => {+ const seen: number[] = []+ const statesBefore = $sessionStates.get()+ const stop = $botChatSessionIds.listen(ids => seen.push(ids.size))++ try {+ setSessionTileWorkspaceScope('stored-1', botScope)+ } finally {+ stop()+ }++ expect(seen).toEqual([1])+ // The store a stale subscriber would have been waiting on never moved.+ expect($sessionStates.get()).toBe(statesBefore)+ })++ it('answers for the live id behind a marked stored one, and stops when cleared', () => {+ setSessionTileWorkspaceScope('stored-1', botScope)++ expect(isBotChatSession('runtime-1')).toBe(true)+ expect(isBotChatSession('stored-1')).toBe(true)++ setSessionTileWorkspaceScope('stored-1', { workspaceMode: 'sessions', workspaceOwnerKey: '' })++ expect(isBotChatSession('runtime-1')).toBe(false)+ })++ it('is silent for an id it never marked, and for no id at all', () => {+ expect(isBotChatSession('never-seen')).toBe(false)+ expect(isBotChatSession(null)).toBe(false)+ expect(isBotChatSession(undefined)).toBe(false)+ })++ it('resolves a marked chat only once the binding that names it exists', () => {+ // The reason a subscriber cannot watch the scope set alone: with the set+ // already marked, the answer still flips when the BINDING arrives.+ $sessionTiles.set([])+ setSessionTileWorkspaceScope('stored-1', botScope)++ expect(isBotChatSession('runtime-1')).toBe(false)++ $sessionTiles.set([{ runtimeId: 'runtime-1', storedSessionId: 'stored-1' } as never])++ expect(isBotChatSession('runtime-1')).toBe(true)+ })++ it('does not re-notify when the same scope is recorded twice', () => {+ setSessionTileWorkspaceScope('stored-1', botScope)++ const seen: number[] = []+ const stop = $botChatSessionIds.listen(ids => seen.push(ids.size))++ try {+ setSessionTileWorkspaceScope('stored-1', botScope)+ } finally {+ stop()+ }++ expect(seen).toEqual([])+ })+})