fix(web): collect and dismiss optional async questions above composer (#2322)

This commit is contained in:
peter-yy
2026-11-09 12:04:20 +08:00
committed by GitHub
parent 5ed3d14f88
commit 89eb8868dd
12 changed files with 304 additions and 2 deletions
@@ -0,0 +1,104 @@
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import type { ApiClient } from '@/api/client'
import type { AgentState } from '@/types/api'
import { AsyncQuestionsPanel } from './AsyncQuestionsPanel'
vi.mock('@/hooks/usePlatform', () => ({
usePlatform: () => ({ haptic: { notification: vi.fn(), selection: vi.fn() } })
}))
vi.mock('@/lib/use-translation', () => ({
useTranslation: () => ({ t: (key: string) => key })
}))
function question(text: string, createdAt: number, isBlocking: unknown = false) {
return {
tool: 'request_user_input', toolCallId: `tool-${text}`, createdAt,
arguments: { isBlocking, questions: [{ id: 'answer', question: text, options: [] }] }
}
}
function setup(requests: AgentState['requests']) {
const approvePermission = vi.fn().mockResolvedValue(undefined)
const denyPermission = vi.fn().mockResolvedValue(undefined)
const props = {
api: { approvePermission, denyPermission } as unknown as ApiClient,
sessionId: 'session-1', requests, disabled: false, onRefresh: vi.fn()
}
return { ...render(<AsyncQuestionsPanel {...props} />), props, approvePermission, denyPermission }
}
function expand() {
fireEvent.click(screen.getByRole('button', { name: /chat.asyncQuestions.title/ }))
}
describe('AsyncQuestionsPanel', () => {
it('lists every optional question in time order without requiring transcript messages', () => {
setup({
later: question('Later question', 20),
earlier: question('Earlier question', 10),
blocking: question('Blocking question', 1, true),
unknown: { tool: 'request_user_input', arguments: { questions: [] } },
permission: { tool: 'Bash', arguments: { isBlocking: false } }
})
expect(screen.getByRole('button', { name: /chat.asyncQuestions.title/ })).toHaveTextContent('2')
expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
expand()
expect(screen.getAllByText(/^(Earlier|Later) question$/, { selector: 'summary' }).map((node) => node.textContent))
.toEqual(['Earlier question', 'Later question'])
expect(screen.queryByText('Blocking question')).not.toBeInTheDocument()
fireEvent.click(screen.getByText('Earlier question', { selector: 'summary' }))
fireEvent.click(screen.getByText('Later question', { selector: 'summary' }))
expect(screen.getAllByRole('button', { name: 'button.dismiss' })).toHaveLength(2)
})
it('preserves drafts across collapse and SSE updates, and answers using the request key', async () => {
const { props, rerender, approvePermission } = setup({ request: question('Question', 1) })
expand()
fireEvent.click(screen.getByText('Question', { selector: 'summary' }))
fireEvent.change(screen.getByRole('textbox'), { target: { value: 'My answer' } })
expand()
expect(screen.getByRole('button', { name: /chat.asyncQuestions.title/ })).toHaveAttribute('aria-expanded', 'false')
expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
rerender(<AsyncQuestionsPanel {...props} requests={structuredClone(props.requests)} />)
expand()
expect(screen.getByRole('textbox')).toHaveValue('My answer')
fireEvent.click(screen.getByRole('button', { name: 'tool.submit' }))
await waitFor(() => expect(approvePermission).toHaveBeenCalledExactlyOnceWith('session-1', 'request', {
answers: { answer: { answers: ['user_note: My answer'] } }
}))
expect(props.onRefresh).toHaveBeenCalledOnce()
})
it('dismisses one request and follows authoritative updates, including replies elsewhere', async () => {
const { props, rerender, denyPermission } = setup({ first: question('First', 1), second: question('Second', 2) })
expand()
fireEvent.click(screen.getByText('First', { selector: 'summary' }))
fireEvent.click(within(screen.getByText('First', { selector: 'summary' }).parentElement!).getByRole('button', { name: 'button.dismiss' }))
await waitFor(() => expect(props.onRefresh).toHaveBeenCalledOnce())
expect(denyPermission).toHaveBeenCalledExactlyOnceWith('session-1', 'first')
rerender(<AsyncQuestionsPanel {...props} requests={{ second: question('Second', 2) }} />)
expect(screen.queryByText('First')).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: /chat.asyncQuestions.title/ })).toHaveTextContent('1')
rerender(<AsyncQuestionsPanel {...props} requests={{}} />)
expect(screen.queryByRole('region')).not.toBeInTheDocument()
})
it('disables actions for inactive sessions and does not carry answers into another session', () => {
const { props, rerender } = setup({ request: question('Question', 1) })
expand()
fireEvent.click(screen.getByText('Question', { selector: 'summary' }))
fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Session one draft' } })
rerender(<AsyncQuestionsPanel {...props} disabled />)
expect(screen.getByRole('button', { name: 'tool.submit' })).toBeDisabled()
expect(screen.getByRole('button', { name: 'button.dismiss' })).toBeDisabled()
rerender(<AsyncQuestionsPanel {...props} sessionId="session-2" />)
fireEvent.click(screen.getByText('Question', { selector: 'summary' }))
expect(screen.getByRole('textbox')).toHaveValue('')
})
it.each([null, undefined, {}])('renders nothing with no optional requests (%s)', (requests) => {
setup(requests)
expect(screen.queryByRole('region')).not.toBeInTheDocument()
})
})
@@ -0,0 +1,78 @@
import { useId, useState } from 'react'
import type { ApiClient } from '@/api/client'
import type { AgentState } from '@/types/api'
import type { ChatToolCall } from '@/chat/types'
import { RequestUserInputFooter } from '@/components/ToolCard/RequestUserInputFooter'
import { isAsyncRequestUserInput, parseRequestUserInputInput } from '@/components/ToolCard/requestUserInput'
import { useTranslation } from '@/lib/use-translation'
/** Read live requests, not the paginated transcript: old questions remain reachable. */
export function AsyncQuestionsPanel(props: {
api: ApiClient
sessionId: string
requests: AgentState['requests']
disabled: boolean
onRefresh: () => void
}) {
const { t } = useTranslation()
const [expanded, setExpanded] = useState(false)
const contentId = useId()
const requests = Object.entries(props.requests ?? {})
.filter(([, request]) => isAsyncRequestUserInput(request.tool, request.arguments))
.sort(([aId, a], [bId, b]) => (a.createdAt ?? 0) - (b.createdAt ?? 0) || aId.localeCompare(bId))
if (requests.length === 0) return null
return (
<section className="mx-auto mb-2 w-full max-w-content rounded-xl border border-[var(--app-border)] bg-[var(--app-bg)]" aria-label={t('chat.asyncQuestions.title')}>
<button
type="button"
className="flex w-full items-center gap-2 rounded-xl px-3 py-2 text-left text-sm hover:bg-[var(--app-subtle-bg)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--app-link)]"
aria-expanded={expanded}
aria-controls={contentId}
onClick={() => setExpanded((value) => !value)}
>
<span aria-hidden="true">{expanded ? '▾' : '▸'}</span>
<span className="min-w-0 flex-1 font-medium">{t('chat.asyncQuestions.title')}</span>
<span className="rounded-full bg-[var(--app-subtle-bg)] px-2 text-xs tabular-nums">{requests.length}</span>
</button>
{/* Keep forms mounted so collapsing never discards a draft. */}
<div id={contentId} hidden={!expanded} className="max-h-[35dvh] overflow-y-auto overscroll-contain px-3 pb-3">
<p className="text-xs text-[var(--app-hint)]">{t('chat.asyncQuestions.hint')}</p>
{requests.map(([id, request]) => {
const tool: ChatToolCall = {
id,
name: request.tool,
input: request.arguments,
state: 'pending',
createdAt: request.createdAt ?? 0,
startedAt: null,
completedAt: null,
execStartedAt: null,
execCompletedAt: null,
description: null,
// Replies must use the request key, not the correlated toolCallId.
permission: { id, status: 'pending' }
}
return (
<details
key={`${props.sessionId}:${id}`}
className="mt-2 rounded-lg border border-[var(--app-border)] p-2"
>
<summary className="cursor-pointer break-words text-sm font-medium">
{parseRequestUserInputInput(request.arguments).questions.map((question) => question.question).filter(Boolean).join(' · ') || t('tool.question')}
</summary>
<RequestUserInputFooter
api={props.api}
sessionId={props.sessionId}
tool={tool}
disabled={props.disabled}
onDone={props.onRefresh}
/>
</details>
)
})}
</div>
</section>
)
}
+9
View File
@@ -48,6 +48,7 @@ import type { PendingSchedule } from '@/components/AssistantChat/ScheduleTimePic
import { resolvePendingSchedule } from '@/components/AssistantChat/ScheduleTimePicker'
import { HappyThread } from '@/components/AssistantChat/HappyThread'
import { QueuedMessagesBar } from '@/components/AssistantChat/QueuedMessagesBar'
import { AsyncQuestionsPanel } from '@/components/AssistantChat/AsyncQuestionsPanel'
import { ScratchlistDrawer } from '@/components/AssistantChat/ScratchlistPanel'
import { useHubScratchlist } from '@/lib/use-hub-scratchlist'
import { useSessions } from '@/hooks/queries/useSessions'
@@ -2230,6 +2231,14 @@ function SessionChatInner(props: SessionChatProps) {
/>
<div className="px-3">
<AsyncQuestionsPanel
key={`questions-${props.session.id}`}
api={props.api}
sessionId={props.session.id}
requests={props.session.agentState?.requests}
disabled={sessionInactive}
onRefresh={props.onRefresh}
/>
{/*
* Scratchlist drawer - composer-controlled. Only
* mounted when the operator clicks the notepad icon
@@ -22,11 +22,12 @@ const choice = { id: 'choice', question: 'Choose', isOther: true, options: [{ la
function renderFooter(input: unknown = { questions: [choice] }) {
const approvePermission = vi.fn().mockResolvedValue(undefined)
const denyPermission = vi.fn().mockResolvedValue(undefined)
const props = {
api: { approvePermission } as unknown as ApiClient,
api: { approvePermission, denyPermission } as unknown as ApiClient,
sessionId: 'session-1', tool: makeTool(input), disabled: false, onDone: vi.fn()
}
return { ...render(<RequestUserInputFooter {...props} />), props, approvePermission }
return { ...render(<RequestUserInputFooter {...props} />), props, approvePermission, denyPermission }
}
function makeTool(input: unknown): ChatToolCall {
@@ -49,6 +50,39 @@ function makeTool(input: unknown): ChatToolCall {
}
describe('RequestUserInputFooter', () => {
it('dismisses only the optional request without validating or submitting answers', async () => {
const { props, denyPermission, approvePermission } = renderFooter({ isBlocking: false, questions: [choice] })
fireEvent.click(screen.getByRole('button', { name: 'button.dismiss' }))
await waitFor(() => expect(props.onDone).toHaveBeenCalledOnce())
expect(denyPermission).toHaveBeenCalledExactlyOnceWith('session-1', 'permission-1')
expect(approvePermission).not.toHaveBeenCalled()
expect(screen.queryByText('tool.selectOption')).not.toBeInTheDocument()
})
it.each([true, undefined, 'false'])('does not offer dismissal without explicit non-blocking status (%s)', (isBlocking) => {
renderFooter({ isBlocking, questions: [choice] })
expect(screen.queryByRole('button', { name: 'button.dismiss' })).not.toBeInTheDocument()
})
it('prevents concurrent actions during dismissal and keeps the draft on failure', async () => {
const { props, rerender, denyPermission, approvePermission } = renderFooter({ isBlocking: false, questions: [choice] })
let fail!: (reason: Error) => void
denyPermission.mockImplementationOnce(() => new Promise((_, reject) => { fail = reject }))
fireEvent.change(screen.getByRole('textbox'), { target: { value: 'keep my draft' } })
fireEvent.click(screen.getByRole('button', { name: 'button.dismiss' }))
expect(screen.getByRole('button', { name: 'button.dismiss' })).toBeDisabled()
expect(screen.getByRole('button', { name: 'tool.submitting' })).toBeDisabled()
fail(new Error('Connection lost'))
await screen.findByText('Connection lost')
expect(props.onDone).not.toHaveBeenCalled()
expect(screen.getByRole('textbox')).toHaveValue('keep my draft')
expect(screen.getByRole('button', { name: 'button.dismiss' })).toBeEnabled()
rerender(<RequestUserInputFooter {...props} disabled />)
fireEvent.click(screen.getByRole('button', { name: 'button.dismiss' }))
expect(denyPermission).toHaveBeenCalledOnce()
expect(approvePermission).not.toHaveBeenCalled()
})
it.each(['', ' \n ', ' 自定义\n说明 '])('focuses notes without submitting and posts canonical values (%j)', async (note) => {
const { approvePermission } = renderFooter()
fireEvent.click(screen.getByRole('button', { name: /Alpha/ }))
@@ -6,6 +6,7 @@ import { Button } from '@/components/ui/button'
import { MarkdownRenderer } from '@/components/MarkdownRenderer'
import {
isRequestUserInputToolName,
isAsyncRequestUserInput,
parseRequestUserInputInput,
formatRequestUserInputAnswers,
isRequestUserInputQuestionAnswered,
@@ -80,6 +81,7 @@ export function RequestUserInputFooter(props: {
const permission = props.tool.permission
const parsed = useMemo(() => parseRequestUserInputInput(props.tool.input), [props.tool.input])
const questions = parsed.questions
const isAsync = isAsyncRequestUserInput(props.tool.name, props.tool.input)
const [step, setStep] = useState(0)
const [stateByQuestion, setStateByQuestion] = useState<Record<string, QuestionState>>({})
@@ -166,6 +168,13 @@ export function RequestUserInputFooter(props: {
setStep((s) => Math.min(s + 1, questions.length - 1))
}
const dismiss = async () => {
if (!isAsync || loading) return
setLoading(true)
await run(() => props.api.denyPermission(props.sessionId, permission.id), 'success')
setLoading(false)
}
const prev = () => {
setError(null)
setStep((s) => Math.max(s - 1, 0))
@@ -276,6 +285,18 @@ export function RequestUserInputFooter(props: {
<div className="mt-3 flex items-center justify-between gap-2">
<div className="flex items-center gap-2">
{isAsync ? (
<Button
type="button"
variant="outline"
size="sm"
disabled={props.disabled || loading}
onClick={dismiss}
title={t('tool.requestUserInput.dismissHint')}
>
{t('button.dismiss')}
</Button>
) : null}
{questions.length > 1 ? (
<Button
type="button"
@@ -43,6 +43,10 @@ export function isRequestUserInputToolName(toolName: string): boolean {
return toolName === 'request_user_input'
}
export function isAsyncRequestUserInput(toolName: string, input: unknown): boolean {
return isRequestUserInputToolName(toolName) && isObject(input) && input.isBlocking === false
}
export function openRequestUserInputUrl(url: string): boolean {
const opened = window.open('about:blank', '_blank')
if (!opened) return false