From df23e549d312d4f33dd476ff5215569b7f273e27 Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:55:10 +0000 Subject: [PATCH] fix(native-chat): refresh the /mcp tray when the chat starts or /mcp is run again (#43188) The tray read the chat's MCP servers once when it opened. Opened while the agent was at rest, it said "Connect when you send your next message" and kept saying it after the agent started, and running /mcp again on the open tray did nothing. The tray now re-reads when the host reports the agent starting or stopping and each time /mcp runs, on desktop and mobile. A read asked for while one is in flight now runs after it instead of being dropped. --- .../use-mobile-structured-agent-session.ts | 2 +- ...obile-structured-session-host-execution.ts | 39 +++++++++++++++++++ ...mobile-structured-session-host-stopping.ts | 24 ------------ .../mcp/MobileNativeChatMcpTray.tsx | 2 +- .../mcp/use-mobile-structured-mcp-panel.ts | 20 ++++++++-- .../native-chat/mcp/NativeChatMcpTray.tsx | 7 +++- .../mcp/use-native-chat-mcp-tray.ts | 16 ++++++-- .../NativeChatStructuredComposerTabStrips.tsx | 1 + .../view/use-agent-session-mcp-panel.test.ts | 38 ++++++++++++++++++ .../view/use-agent-session-mcp-panel.ts | 32 +++++++++------ 10 files changed, 136 insertions(+), 45 deletions(-) create mode 100644 mobile/src/session/native-chat/agent-session/use-mobile-structured-session-host-execution.ts delete mode 100644 mobile/src/session/native-chat/agent-session/use-mobile-structured-session-host-stopping.ts create mode 100644 src/shared/agent-session/view/use-agent-session-mcp-panel.test.ts diff --git a/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session.ts b/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session.ts index b3919e7365e..28181b07a1e 100644 --- a/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session.ts +++ b/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session.ts @@ -23,7 +23,7 @@ import type { import type { MobileNativeChatVisualSource } from '../visual/mobile-native-chat-visual-read' import { useMobileStructuredAgentState } from './use-mobile-structured-agent-state' import { useMobileStructuredStopPress } from '../composer/delivery/use-mobile-structured-stop-press' -import { useMobileStructuredSessionHostStopping } from './use-mobile-structured-session-host-stopping' +import { useMobileStructuredSessionHostStopping } from './use-mobile-structured-session-host-execution' import { useMobileStructuredPromptResponses } from '../input/prompts/use-mobile-structured-prompt-responses' import { useMobileStructuredAgentOptions } from '../input/session-options/use-mobile-structured-agent-options' import { useHostModelCatalogCache } from '../input/session-options/mobile-host-model-catalog-query' diff --git a/mobile/src/session/native-chat/agent-session/use-mobile-structured-session-host-execution.ts b/mobile/src/session/native-chat/agent-session/use-mobile-structured-session-host-execution.ts new file mode 100644 index 00000000000..5560139141c --- /dev/null +++ b/mobile/src/session/native-chat/agent-session/use-mobile-structured-session-host-execution.ts @@ -0,0 +1,39 @@ +import { useCallback, useSyncExternalStore } from 'react' +import type { AgentSessionStatusSummary } from '../../../../../src/shared/agent-session/agent-session-wire' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' +import { mobileStructuredSessionStatusFeed } from './mobile-structured-session-status-feed' + +type HostExecutionArgs = { + client: RpcClient | null + sessionId: string | null + enabled: boolean +} + +const noSubscription = (): (() => void) => () => {} + +// Only trust the host's report while its status-feed capability and transport are live. +function useHostSummaryValue( + { client, sessionId, enabled }: HostExecutionArgs, + pick: (summary: AgentSessionStatusSummary | undefined) => T +): T { + const feed = enabled && client && sessionId ? mobileStructuredSessionStatusFeed(client) : null + const subscribe = useCallback( + (listener: () => void) => (feed ? feed.subscribe(listener) : noSubscription()), + [feed] + ) + const read = (): T => pick(feed && sessionId ? feed.getSnapshot().get(sessionId) : undefined) + return useSyncExternalStore(subscribe, read, read) +} + +export function useMobileStructuredSessionHostStopping(args: HostExecutionArgs): boolean { + return useHostSummaryValue( + args, + (summary) => summary?.status === 'working' && summary.stopping === true + ) +} + +export function useMobileStructuredSessionHostExecutionPhase( + args: HostExecutionArgs +): AgentSessionStatusSummary['hostExecutionPhase'] { + return useHostSummaryValue(args, (summary) => summary?.hostExecutionPhase) +} diff --git a/mobile/src/session/native-chat/agent-session/use-mobile-structured-session-host-stopping.ts b/mobile/src/session/native-chat/agent-session/use-mobile-structured-session-host-stopping.ts deleted file mode 100644 index 866b1873358..00000000000 --- a/mobile/src/session/native-chat/agent-session/use-mobile-structured-session-host-stopping.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { useCallback, useSyncExternalStore } from 'react' -import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' -import { mobileStructuredSessionStatusFeed } from './mobile-structured-session-status-feed' - -const noSubscription = (): (() => void) => () => {} - -// Only trust host Stopping while its status-feed capability and transport are live. -export function useMobileStructuredSessionHostStopping(args: { - client: RpcClient | null - sessionId: string | null - enabled: boolean -}): boolean { - const { client, sessionId, enabled } = args - const feed = enabled && client && sessionId ? mobileStructuredSessionStatusFeed(client) : null - const subscribe = useCallback( - (listener: () => void) => (feed ? feed.subscribe(listener) : noSubscription()), - [feed] - ) - const readStopping = (): boolean => { - const summary = feed && sessionId ? feed.getSnapshot().get(sessionId) : undefined - return summary?.status === 'working' && summary.stopping === true - } - return useSyncExternalStore(subscribe, readStopping, readStopping) -} diff --git a/mobile/src/session/native-chat/mcp/MobileNativeChatMcpTray.tsx b/mobile/src/session/native-chat/mcp/MobileNativeChatMcpTray.tsx index 07d3883a516..9ec892370db 100644 --- a/mobile/src/session/native-chat/mcp/MobileNativeChatMcpTray.tsx +++ b/mobile/src/session/native-chat/mcp/MobileNativeChatMcpTray.tsx @@ -26,7 +26,7 @@ export function MobileNativeChatMcpTray({ } function McpTrayContent({ panel }: { panel: MobileStructuredMcpPanel }) { - const state = useAgentSessionMcpPanel(panel.request, openExternalLink) + const state = useAgentSessionMcpPanel(panel.request, openExternalLink, panel.refreshKey) const window = useWindowDimensions() const { allocationHeight } = useMobileNativeChatLowerGeometry() const visibleHeight = allocationHeight ? Math.min(window.height, allocationHeight) : window.height diff --git a/mobile/src/session/native-chat/mcp/use-mobile-structured-mcp-panel.ts b/mobile/src/session/native-chat/mcp/use-mobile-structured-mcp-panel.ts index 8f46f474a7d..9d29d45a14a 100644 --- a/mobile/src/session/native-chat/mcp/use-mobile-structured-mcp-panel.ts +++ b/mobile/src/session/native-chat/mcp/use-mobile-structured-mcp-panel.ts @@ -10,6 +10,7 @@ import { useRouteRelaysCapability } from '../../../worktree/execution-hosts/work import type { MobileStructuredAgentSessionArgs } from '../agent-session/mobile-structured-agent-session-contract' import { callAgentSession } from '../agent-session/mobile-structured-agent-session-rpc' import { useMobileRegisteredAgent } from '../agent-session/use-mobile-registered-agent' +import { useMobileStructuredSessionHostExecutionPhase } from '../agent-session/use-mobile-structured-session-host-execution' // A cold Codex read or a Claude sign-in finish (exchange, reconnect, re-read) can run long. const MCP_TIMEOUT_MS = 90_000 @@ -18,6 +19,8 @@ export type MobileStructuredMcpPanel = { open: boolean close: () => void request: AgentSessionMcpRequest + /** Changes when `/mcp` runs again or the agent starts or stops, so the tray re-reads. */ + refreshKey: string } type McpCommands = Pick @@ -35,7 +38,14 @@ export function useMobileStructuredMcpPanel( const relayed = useRouteRelaysCapability(AGENT_SESSION_MCP_RUNTIME_CAPABILITY) // One hook serves every chat tab, so the tray belongs to the conversation that opened it. const [openFor, setOpenFor] = useState(null) + const [opens, setOpens] = useState(0) const trayOpen = openFor === sessionKey + // An agent at rest has no servers to list; the tray re-reads once it starts or stops. + const phase = useMobileStructuredSessionHostExecutionPhase({ + client, + sessionId, + enabled: trayOpen && session.enabled && session.hostSupport?.statusFeed === true + }) // A reconnect clears host support until it is read again; an open tray mid sign-in must keep // its paste box through that gap. const hostReported = session.hostSupport ? session.hostSupport.mcp === true && relayed : undefined @@ -55,7 +65,10 @@ export function useMobileStructuredMcpPanel( const agentManages = reported ?? (sameChat && known.mcp) const offered = hostManages && agentManages && !!client && !!sessionId const open = offered && trayOpen - const show = useCallback(() => setOpenFor(sessionKey), [sessionKey]) + const show = useCallback(() => { + setOpenFor(sessionKey) + setOpens((count) => count + 1) + }, [sessionKey]) const close = useCallback(() => setOpenFor(null), []) const request = useCallback( async (operation: AgentSessionMcpOperation): Promise => { @@ -73,9 +86,10 @@ export function useMobileStructuredMcpPanel( }, [client, sessionId] ) + const refreshKey = `${opens}:${phase}` const mcpPanel = useMemo( - () => (offered ? { open, close, request } : null), - [close, offered, open, request] + () => (offered ? { open, close, request, refreshKey } : null), + [close, offered, open, refreshKey, request] ) const mcpCommands = useMemo( () => ({ ...commands, openMcpPanel: offered ? show : undefined }), diff --git a/src/renderer/src/components/native-chat/mcp/NativeChatMcpTray.tsx b/src/renderer/src/components/native-chat/mcp/NativeChatMcpTray.tsx index 5812c74ed69..9f849e0a469 100644 --- a/src/renderer/src/components/native-chat/mcp/NativeChatMcpTray.tsx +++ b/src/renderer/src/components/native-chat/mcp/NativeChatMcpTray.tsx @@ -18,6 +18,7 @@ import { } from '../../../../../shared/agent-session/view/use-agent-session-mcp-panel' import { groupAgentSessionMcpServers } from '../../../../../shared/agent-session/view/agent-session-mcp-server-presentation' import { NativeChatComposerTabStrip } from '../composer/controls/NativeChatComposerTabStrip' +import { useStructuredAgentSessionHostExecutionPhase } from '../session/status/structured-agent-session-status-hooks' import { mcpSourceLabel, mcpTraySummary } from './native-chat-mcp-server-text' import { NativeChatMcpServerRow, type McpServerAction } from './NativeChatMcpServerRow' import { useDeferredPending } from './use-deferred-pending' @@ -38,10 +39,12 @@ const openSignInPage = (url: string): void => { export function NativeChatMcpTray({ sessionId, target, + opens, onClose }: { sessionId: string target: RuntimeClientTarget + opens: number onClose: () => void }): React.JSX.Element { const call = useCallback( @@ -52,7 +55,9 @@ export function NativeChatMcpTray({ }), [sessionId, target] ) - const panel = useAgentSessionMcpPanel(call, openSignInPage) + // An agent at rest has no servers to list; re-read once it starts or stops. + const phase = useStructuredAgentSessionHostExecutionPhase(sessionId, target) + const panel = useAgentSessionMcpPanel(call, openSignInPage, `${opens}:${phase}`) const readAgain = panel.retry const [retrying, setRetrying] = useState(false) const retry = useCallback(() => { diff --git a/src/renderer/src/components/native-chat/mcp/use-native-chat-mcp-tray.ts b/src/renderer/src/components/native-chat/mcp/use-native-chat-mcp-tray.ts index 649c094922c..4cc8f411144 100644 --- a/src/renderer/src/components/native-chat/mcp/use-native-chat-mcp-tray.ts +++ b/src/renderer/src/components/native-chat/mcp/use-native-chat-mcp-tray.ts @@ -1,6 +1,12 @@ import { useCallback, useEffect, useMemo, useState } from 'react' -export type NativeChatMcpTrayState = { isOpen: boolean; open: () => void; close: () => void } +export type NativeChatMcpTrayState = { + isOpen: boolean + /** Counts `/mcp` runs, so running it on an open tray re-reads the servers. */ + opens: number + open: () => void + close: () => void +} /** Whether `/mcp`'s tray is open on this chat; another chat, or leaving this one, closes it. */ export function useNativeChatMcpTray( @@ -8,7 +14,11 @@ export function useNativeChatMcpTray( isVisible: boolean ): NativeChatMcpTrayState { const [openFor, setOpenFor] = useState(null) - const open = useCallback(() => setOpenFor(sessionId), [sessionId]) + const [opens, setOpens] = useState(0) + const open = useCallback(() => { + setOpenFor(sessionId) + setOpens((count) => count + 1) + }, [sessionId]) const close = useCallback(() => setOpenFor(null), []) // Hiding the pane (switching tabs) closes it; the tray isn't there to come back to. useEffect(() => { @@ -18,5 +28,5 @@ export function useNativeChatMcpTray( return () => setOpenFor(null) }, [isVisible]) const isOpen = isVisible && openFor === sessionId - return useMemo(() => ({ isOpen, open, close }), [isOpen, open, close]) + return useMemo(() => ({ isOpen, opens, open, close }), [isOpen, opens, open, close]) } diff --git a/src/renderer/src/components/native-chat/pane/actions/NativeChatStructuredComposerTabStrips.tsx b/src/renderer/src/components/native-chat/pane/actions/NativeChatStructuredComposerTabStrips.tsx index aa2179a55ad..4b4abbd83bb 100644 --- a/src/renderer/src/components/native-chat/pane/actions/NativeChatStructuredComposerTabStrips.tsx +++ b/src/renderer/src/components/native-chat/pane/actions/NativeChatStructuredComposerTabStrips.tsx @@ -33,6 +33,7 @@ export function NativeChatStructuredComposerTabStrips(props: { { mcpPanel.close() props.focusComposer() diff --git a/src/shared/agent-session/view/use-agent-session-mcp-panel.test.ts b/src/shared/agent-session/view/use-agent-session-mcp-panel.test.ts new file mode 100644 index 00000000000..a7aa18bd341 --- /dev/null +++ b/src/shared/agent-session/view/use-agent-session-mcp-panel.test.ts @@ -0,0 +1,38 @@ +// @vitest-environment happy-dom +import * as React from 'react' +import { act, renderHook, waitFor } from '@testing-library/react' +import { describe, expect, it, vi } from 'vitest' +import type { AgentSessionMcpResult, AgentSessionMcpServer } from '../agent-session-mcp' +import { createAgentSessionMcpPanelHook } from './use-agent-session-mcp-panel' + +const useAgentSessionMcpPanel = createAgentSessionMcpPanelHook(React) + +const server: AgentSessionMcpServer = { + name: 'probe', + status: 'connected', + source: 'project', + toolCount: 1, + error: null, + canSignIn: false, + canReconnect: true, + canToggle: true +} + +describe('useAgentSessionMcpPanel', () => { + it('re-reads when the refresh key changes, even while a read is in flight', async () => { + let finishFirst: (reply: AgentSessionMcpResult) => void = () => {} + const request = vi + .fn<() => Promise>() + .mockImplementationOnce(() => new Promise((resolve) => (finishFirst = resolve))) + .mockResolvedValueOnce({ status: 'ok', servers: [server] }) + const { result, rerender } = renderHook( + ({ refreshKey }) => useAgentSessionMcpPanel(request, () => {}, refreshKey), + { initialProps: { refreshKey: 'at-rest' } } + ) + // The agent starts while the first read, made at rest, is still out. + rerender({ refreshKey: 'running' }) + await act(async () => finishFirst({ status: 'not-running' })) + await waitFor(() => expect(result.current.result).toEqual({ status: 'ok' })) + expect(result.current.servers).toEqual([server]) + }) +}) diff --git a/src/shared/agent-session/view/use-agent-session-mcp-panel.ts b/src/shared/agent-session/view/use-agent-session-mcp-panel.ts index 6d932698aa4..13580f83081 100644 --- a/src/shared/agent-session/view/use-agent-session-mcp-panel.ts +++ b/src/shared/agent-session/view/use-agent-session-mcp-panel.ts @@ -26,7 +26,8 @@ const MAX_POLL_MS = 15_000 // Agents close their sign-in callback after five minutes. const SIGN_IN_WINDOW_MS = 5 * 60_000 -/** State for the `/mcp` panel; `openUrl` opens a sign-in page in the device's browser. */ +/** State for the `/mcp` panel; `openUrl` opens a sign-in page in the device's browser, and a new + * `refreshKey` (the agent starting or stopping, `/mcp` run again) re-reads the servers. */ export function createAgentSessionMcpPanelHook({ useCallback, useEffect, @@ -35,7 +36,8 @@ export function createAgentSessionMcpPanelHook({ }: Pick) { return function useAgentSessionMcpPanel( request: AgentSessionMcpRequest, - openUrl: (url: string) => void + openUrl: (url: string) => void, + refreshKey?: unknown ) { const [state, setState] = useState({ result: null, @@ -46,6 +48,8 @@ export function createAgentSessionMcpPanelHook({ }) const busy = useRef(false) const reading = useRef(false) + // A read asked for mid-read may follow a change the one in flight missed. + const readAgain = useRef(false) // Bumped as each action starts and ends, so a read that overlapped one can't show older state. const actions = useRef(0) const mounted = useRef(true) @@ -97,19 +101,23 @@ export function createAgentSessionMcpPanelHook({ const read = useCallback(async () => { if (reading.current) { + readAgain.current = true return } reading.current = true - const operation = { action: 'status' } as const - const started = actions.current - const reply = await request(operation).catch((): AgentSessionMcpResult => ({ - status: 'failed', - message: null - })) + do { + readAgain.current = false + const operation = { action: 'status' } as const + const started = actions.current + const reply = await request(operation).catch((): AgentSessionMcpResult => ({ + status: 'failed', + message: null + })) + if (actions.current === started) { + apply(reply, operation) + } + } while (readAgain.current && mounted.current) reading.current = false - if (actions.current === started) { - apply(reply, operation) - } }, [apply, request]) const run = useCallback( @@ -146,7 +154,7 @@ export function createAgentSessionMcpPanelHook({ useEffect(() => { void read() - }, [read]) + }, [read, refreshKey]) // Nothing reports when an agent finishes a callback sign-in or a server settles from // connecting; re-read with backoff, and stop at the agents' own five-minute window.