The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): tool media ownership refreshes when MCP servers connect
Teknium434649a6bbe8
diff --git a/apps/desktop/src/components/assistant-ui/tool-media-slot.test.tsx b/apps/desktop/src/components/assistant-ui/tool-media-slot.test.tsxindex 57a6da866f9..9228968843e 100644--- a/apps/desktop/src/components/assistant-ui/tool-media-slot.test.tsx+++ b/apps/desktop/src/components/assistant-ui/tool-media-slot.test.tsx@@ -190,6 +190,13 @@ describe('tool media renderers', () => {await waitFor(() => expect(container.querySelectorAll('audio[controls]')).toHaveLength(3))})+ it('keeps the built-in player when the plugin renderer draws nothing (null)', async () => {+ disposers.push(claim('sfx', ['sfx_make'], () => null))+ const { container } = renderTurn()++ await waitFor(() => expect(container.querySelectorAll('audio[controls]')).toHaveLength(3))+ })+it('keeps the built-in player once the plugin is disabled (its contributions are gone)', async () => {const dispose = claim('sfx', ['sfx_make'])const { container } = renderTurn()diff --git a/apps/desktop/src/components/assistant-ui/tool-media-slot.tsx b/apps/desktop/src/components/assistant-ui/tool-media-slot.tsxindex 47a1d44a511..9ea6643f40d 100644--- a/apps/desktop/src/components/assistant-ui/tool-media-slot.tsx+++ b/apps/desktop/src/components/assistant-ui/tool-media-slot.tsx@@ -2,12 +2,14 @@ import { useAuiState } from '@assistant-ui/react'import { useStore } from '@nanostores/react'import { type FC, type ReactNode, useEffect, useMemo } from 'react'+import { useComposerScope } from '@/app/chat/composer/scope'import { useSessionView } from '@/app/chat/session-view'import { ErrorBoundary } from '@/components/error-boundary'import { type Contribution, useContributions } from '@/contrib'import { $pluginRecords } from '@/contrib/plugins-store'-import { mediaKind, mediaMime, mediaName, resolveMediaPlaybackSrc } from '@/lib/media'+import { mediaKind, mediaMime, mediaName, resolveMediaDisplaySrc, resolveMediaPlaybackSrc } from '@/lib/media'import {+ claimPatternMatches,effectiveToolCall,findProducingToolCall,refusedClaimPatterns,@@ -18,10 +20,13 @@ import {type ToolMediaRendererContribution,type ToolMediaRendererProps} from '@/lib/tool-media-renderers'+import { $gateway } from '@/store/gateway'+import { $connection } from '@/store/session'import {$toolMediaOwners,ensureToolMediaOwners,packageOfContributionSource,+ revalidateToolMediaOwners,toolMediaOwnerKey} from '@/store/tool-media-owners'@@ -49,9 +54,9 @@ function warnRefused(claim: Pick<Contribution, 'id' | 'source'>, tool: string) {)}-// The turn's producer, read straight from the thread store so the selector-// returns the store's own part object (a stable reference across deltas).-// Outside a message (a Bot group room, a preview) there is no turn: no producer.+// The producer, read straight from the thread store so the selector returns+// the store's own part object (a stable reference across deltas). Outside a+// message (a Bot group room, a preview) there is no transcript: no producer.function useProducingToolCall(path: string): ToolCallLike | null {return useAuiState(state => {try {@@ -88,6 +93,8 @@ const ClaimedToolMediaSlot: FC<{ children: ReactNode; claims: readonly Contributconst runtimeId = useStore(view.$runtimeId)const sessionId = storedId || runtimeId || nullconst entries = useStore($toolMediaOwners)+ // A transcript painted before the socket is up fetches once it is.+ const gateway = useStore($gateway)const entry = entries[toolMediaOwnerKey(sessionId)]// Re-resolve when a plugin record (enable state, package) changes.useStore($pluginRecords)@@ -96,7 +103,7 @@ const ClaimedToolMediaSlot: FC<{ children: ReactNode; claims: readonly Contributif (producer) {ensureToolMediaOwners(sessionId)}- }, [producer, sessionId, entry])+ }, [producer, sessionId, entry, gateway])const ready = entry?.status === 'ready' ? entry.owners : null@@ -119,6 +126,16 @@ const ClaimedToolMediaSlot: FC<{ children: ReactNode; claims: readonly Contribut}): null+ // A claimed tool nobody owns yet may belong to an MCP server that has not+ // connected: re-read ownership on a bounded backoff, keeping this answer.+ const unowned = Boolean(ready && producer?.toolName && !claim && claimsTool(claims, producer.toolName))++ useEffect(() => {+ if (unowned) {+ revalidateToolMediaOwners(sessionId)+ }+ }, [unowned, sessionId, entry])+if (!claim || !producer?.toolName) {return <>{children}</>}@@ -138,6 +155,7 @@ const ToolMediaLeaf: FC<{sessionId: null | string}> = ({ contribution, fallback, path, producer, sessionId }) => {const render = (contribution.data as ToolMediaRendererContribution).render+ const owner = useMediaOwner()const file = useMemo<ToolMediaFile>(() => ({@@ -145,9 +163,14 @@ const ToolMediaLeaf: FC<{mime: mediaMime(path),name: mediaName(path),path,- resolveUrl: () => resolveMediaPlaybackSrc(path)+ // Read from the backend that owns this chat, like the built-in image:+ // a split-view tile can belong to another connection than the foreground.+ resolveUrl: () =>+ ['audio', 'video'].includes(mediaKind(path))+ ? resolveMediaPlaybackSrc(path)+ : resolveMediaDisplaySrc(path, owner)}),- [path]+ [owner, path])const args = useMemo(@@ -156,10 +179,11 @@ const ToolMediaLeaf: FC<{)// Stable component identity per renderer, so a re-render never remounts the widget.+ // Nothing drawn (null/undefined) keeps the built-in player.const Leaf = useMemo(() =>function ToolMediaRendererHost(props: ToolMediaRendererProps) {- return <>{render(props)}</>+ return <>{render(props) ?? props.fallback}</>},[render])@@ -176,3 +200,27 @@ const ToolMediaLeaf: FC<{/>)}++function claimsTool(claims: readonly Contribution[], toolName: string): boolean {+ return claims.some(claim => {+ const tools = (claim.data as Partial<ToolMediaRendererContribution> | undefined)?.tools++ return (+ Array.isArray(tools) &&+ tools.some(pattern => typeof pattern === 'string' && claimPatternMatches(pattern, toolName))+ )+ })+}++/** The chat's owning connection/profile, as the built-in image reads it. */+function useMediaOwner() {+ const connection = useStore($connection)+ const scope = useComposerScope()+ const connectionId = scope.connectionId || connection?.connectionId+ const profile = scope.profile ?? connection?.profile++ return useMemo(+ () => (scope.connectionId || scope.profile ? { connectionId, profile } : undefined),+ [scope.connectionId, scope.profile, connectionId, profile]+ )+}diff --git a/apps/desktop/src/lib/mcp-reload.ts b/apps/desktop/src/lib/mcp-reload.tsindex 71de064f407..ad6b46b0815 100644--- a/apps/desktop/src/lib/mcp-reload.ts+++ b/apps/desktop/src/lib/mcp-reload.ts@@ -4,6 +4,7 @@ import { translateNow } from '@/i18n'import { notify } from '@/store/notifications'import { ambientRequestFor } from '@/store/session-gone-latch'import { requestForOwnedSession } from '@/store/session-states'+import { refreshToolMediaOwners } from '@/store/tool-media-owners'/*** What `reload.mcp` did for the chat that asked. The gateway decides and commits; Desktop only reads its@@ -30,6 +31,9 @@ export async function reloadMcp(session_id: sessionId ?? undefined})+ // Reconnected servers can register tools a package's renderer was waiting on.+ refreshToolMediaOwners()+return {deferred: result?.session === 'busy',sessionServers: result?.session_servers ?? null,diff --git a/apps/desktop/src/store/tool-media-owners.test.ts b/apps/desktop/src/store/tool-media-owners.test.tsindex 91139c8b838..ff676d78bc1 100644--- a/apps/desktop/src/store/tool-media-owners.test.ts+++ b/apps/desktop/src/store/tool-media-owners.test.ts@@ -36,6 +36,7 @@ vi.mock('@/store/session-states', () => ({}))vi.mock('@/store/session-request-router', () => ({+ isSessionOwnerRoute: (owner: SessionOwnerScope) => Boolean(owner && typeof owner === 'object'),requestForSessionProfile: vi.fn((owner: SessionOwnerScope, _ambient: unknown, method: string, params: Record<string, unknown>) =>new Promise((resolve, reject) => {@@ -257,7 +258,9 @@ describe('retry backoff', () => {await failNext()await vi.advanceTimersByTimeAsync(4_000)owners.ensureToolMediaOwners('s1')- pending().at(-1)?.resolve(listWith('pkg', ['draw']))+ pending()+ .at(-1)+ ?.resolve(listWith('pkg', ['draw']))await flush()expect(ownedTools('s1', 'pkg')).toEqual(['draw'])@@ -299,3 +302,131 @@ describe('retry backoff', () => {expect(entryFor('s1')).toBeUndefined()})})++describe('re-reads keep the previous answer drawing', () => {+ const loadReady = async (sessionId: string, tools: string[]) => {+ owners.ensureToolMediaOwners(sessionId)+ pending().at(-1)?.resolve(listWith('meshy', tools))+ await flush()+ }++ it('a plugin-list change keeps the loaded owners until the re-read lands, then takes the new answer', async () => {+ await loadReady('s1', ['mcp__meshy__download'])+ const before = entryFor('s1')++ invalidatePlugins()+ expect(entryFor('s1')).toMatchObject({ refresh: 'due', status: 'ready' })+ expect(ownedTools('s1', 'meshy')).toEqual(['mcp__meshy__download'])++ owners.ensureToolMediaOwners('s1')+ owners.ensureToolMediaOwners('s1')+ expect(pending()).toHaveLength(2) // one re-read, however many attachments ask+ expect(entryFor('s1')).toMatchObject({ refresh: 'pending', status: 'ready' })++ pending()[1].resolve(listWith('meshy', []))+ await flush()+ expect(ownedTools('s1', 'meshy')).toBeUndefined()+ expect(entryFor('s1')?.request).not.toBe(before?.request)+ })++ it('an unchanged re-read keeps the same owners object (nothing re-resolves)', async () => {+ await loadReady('s1', ['t'])+ const before = entryFor('s1')++ owners.refreshToolMediaOwners()+ owners.ensureToolMediaOwners('s1')+ pending()[1].resolve(listWith('meshy', ['t']))+ await flush()++ const after = entryFor('s1')++ expect(after?.status === 'ready' && before?.status === 'ready' && after.owners === before.owners).toBe(true)+ })++ it('a re-read that fails drops to the built-in player and backs off', async () => {+ await loadReady('s1', ['t'])+ owners.refreshToolMediaOwners()+ owners.ensureToolMediaOwners('s1')+ pending()[1].reject(new Error('down'))+ await flush()++ expect(entryFor('s1')?.status).toBe('error')+ })+})++describe('a claimed tool nobody owns yet re-reads ownership', () => {+ it('re-reads after 1s, then 5s doubling, and picks up a server that connected meanwhile', async () => {+ owners.ensureToolMediaOwners('s1')+ pending()[0].resolve(listWith('meshy', []))+ await flush()++ const delays = [1_000, 5_000, 10_000]++ for (const [index, delay] of delays.entries()) {+ owners.revalidateToolMediaOwners('s1')+ owners.revalidateToolMediaOwners('s1') // one timer at a time+ vi.advanceTimersByTime(delay - 1)+ expect(entryFor('s1')).not.toHaveProperty('refresh')+ vi.advanceTimersByTime(1)+ expect(entryFor('s1')).toMatchObject({ refresh: 'due' })++ owners.ensureToolMediaOwners('s1')+ const last = index === delays.length - 1+ pending()+ .at(-1)+ ?.resolve(listWith('meshy', last ? ['mcp__meshy__download'] : []))+ await flush()+ }++ expect(ownedTools('s1', 'meshy')).toEqual(['mcp__meshy__download'])+ })++ it('stops after a bounded number of re-reads', async () => {+ owners.ensureToolMediaOwners('s1')+ pending()[0].resolve(listWith('meshy', []))+ await flush()++ for (let i = 0; i < owners.MAX_OWNERSHIP_REVALIDATIONS + 2; i += 1) {+ owners.revalidateToolMediaOwners('s1')+ vi.advanceTimersByTime(60_000)+ owners.ensureToolMediaOwners('s1')+ pending().at(-1)?.resolve(listWith('meshy', []))+ await flush()+ }++ expect(pending()).toHaveLength(1 + owners.MAX_OWNERSHIP_REVALIDATIONS)+ })++ it('MCP reconnecting (reload.mcp) marks every loaded answer due at once', async () => {+ owners.ensureToolMediaOwners('s1')+ pending()[0].resolve(listWith('meshy', []))+ await flush()++ owners.refreshToolMediaOwners()+ expect(entryFor('s1')).toMatchObject({ refresh: 'due' })+ })+})++describe('cache hygiene', () => {+ it('drops answers for an earlier activation of the active route', async () => {+ owners.ensureToolMediaOwners(null)+ pending()[0].resolve(listWith('meshy', ['t']))+ await flush()+ const oldKey = owners.toolMediaOwnerKey(null)++ env.epoch = 2+ owners.ensureToolMediaOwners(null)++ expect(owners.$toolMediaOwners.get()).not.toHaveProperty(oldKey)+ })++ it('a routed owner fetches over its own connection with no active gateway', () => {+ env.gateway = null+ env.owners.set('s1', { connectionId: 'remote-1', profile: 'coder' })+ owners.ensureToolMediaOwners('s1')+ owners.ensureToolMediaOwners(null)++ expect(pending()).toHaveLength(1)+ expect(pending()[0].owner).toEqual({ connectionId: 'remote-1', profile: 'coder' })+ })+})diff --git a/apps/desktop/src/store/tool-media-owners.ts b/apps/desktop/src/store/tool-media-owners.tsindex 98a1e81c82e..bfd5c42af4f 100644--- a/apps/desktop/src/store/tool-media-owners.ts+++ b/apps/desktop/src/store/tool-media-owners.ts@@ -166,15 +166,17 @@ export function ensureToolMediaOwners(sessionId: null | string): void {const previous = existing?.status === 'ready' ? existing.owners : null// A re-read keeps drawing with the previous answer until the new one lands.- setEntry(key, previous ? { owners: previous, refresh: 'pending', request, status: 'ready' } : { request, status: 'loading' })+ setEntry(+ key,+ previous ? { owners: previous, refresh: 'pending', request, status: 'ready' } : { request, status: 'loading' }+ )// Only the newest request for a key may write it: an invalidation (plugin// toggle) mid-flight re-stamps the entry, and the older answer is dropped.const stillCurrent = () => $toolMediaOwners.get()[key]?.request === requestrequestForSessionProfile<{ plugins?: OwnershipRow[] }>(owner,- (method, params) =>- gateway ? gateway.request(method, params) : Promise.reject(new Error('No active gateway')),+ (method, params) => (gateway ? gateway.request(method, params) : Promise.reject(new Error('No active gateway'))),'plugins.manage',profile ? { action: 'list', profile } : { action: 'list' })