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.
This commit is contained in:
Kelvin Amoaba
2026-11-16 16:55:10 +00:00
committed by GitHub
parent 3ae47e0464
commit df23e549d3
10 changed files with 136 additions and 45 deletions
@@ -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'
@@ -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<T>(
{ 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)
}
@@ -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)
}
@@ -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
@@ -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<StructuredAgentSessionComposerOptions, 'openMcpPanel'>
@@ -35,7 +38,14 @@ export function useMobileStructuredMcpPanel<TCommands extends object>(
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<string | null>(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<TCommands extends object>(
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<AgentSessionMcpResult> => {
@@ -73,9 +86,10 @@ export function useMobileStructuredMcpPanel<TCommands extends object>(
},
[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 }),
@@ -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(() => {
@@ -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<string | null>(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])
}
@@ -33,6 +33,7 @@ export function NativeChatStructuredComposerTabStrips(props: {
<NativeChatMcpTray
sessionId={props.transport.sessionId}
target={props.target}
opens={mcpPanel.opens}
onClose={() => {
mcpPanel.close()
props.focusComposer()
@@ -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<AgentSessionMcpResult>>()
.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])
})
})
@@ -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<typeof React, 'useCallback' | 'useEffect' | 'useRef' | 'useState'>) {
return function useAgentSessionMcpPanel(
request: AgentSessionMcpRequest,
openUrl: (url: string) => void
openUrl: (url: string) => void,
refreshKey?: unknown
) {
const [state, setState] = useState<AgentSessionMcpPanelState>({
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.