refactor(gui): route the composer chain on PendingWait currency

This commit is contained in:
imccyu
2026-07-23 17:23:17 +08:00
parent de36006956
commit 07bdfbce9b
16 changed files with 314 additions and 275 deletions

View File

@@ -1,101 +1,60 @@
/**
* apply wiring on a real cordis Context + SlotsService (terminal register
* form): QuestionComposer registered as the `question` entry of the
* conversation-declared keyed composer slot, the thin inject surface (two
* receipt-checked session callbacks closed over the plugin ctx — no hooks, no
* store lines), load-order fail-loud, and fiber-teardown unregistration.
* Component behavior is covered props-direct in question-composer.spec.tsx;
* apply wiring on a real cordis Context + SlotsService: QuestionComposer
* registered as the `question` entry of the conversation-declared composer
* slot with ZERO business face (data and verbs ride the dispatched carrier),
* load-order fail-loud, and fiber-teardown unregistration. Component and
* domain-face behavior is covered props-direct in question-composer.spec.tsx;
* no renderer machinery here.
*/
import { Context } from 'cordis'
import { describe, expect, it, vi } from 'vitest'
import { RpcId } from '@deepseek-ai/dsh-client-connection/client'
import type { SessionId } from '@deepseek-ai/dsh-client-runtime/client'
import { describe, expect, it } from 'vitest'
import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client'
import type { QuestionComposerInjected, QuestionInteraction } from '../src/client/contract/slots.ts'
import { QuestionComposer } from '../src/client/QuestionComposer.tsx'
import { apply, inject } from '../src/client/index.ts'
function interaction(): QuestionInteraction {
return {
kind: 'question', rpcId: RpcId('question-1'),
questions: [{ id: 'mode', question: 'Choose?', options: [{ label: 'Fast' }] }],
}
}
async function bench() {
const ctx = new Context()
await ctx.plugin(SlotsService).await()
const answerQuestion = vi.fn()
.mockResolvedValueOnce({ accepted: true })
.mockResolvedValueOnce({ accepted: false, reason: 'not-pending' })
const cancelQuestion = vi.fn()
.mockResolvedValueOnce({ accepted: true })
.mockResolvedValueOnce({ accepted: false, reason: 'bad-response' })
const get = vi.fn(() => ({ answerQuestion, cancelQuestion }))
ctx.provide('sessions', { manager: { get } })
const slots = ctx.get('slots') as SlotsService
// Stand-in for ui-conversation's conversation entry: the composer slot only
// exists while a live entry declares it in children (declaration account:
// design §2.2).
slots.register(
{ name: 'root', children: { 'conversation.composer': { kind: 'keyed', scope: 'session' } } } as never,
{ name: 'root', children: { 'conversation.composer': { kind: 'chain', scope: 'session' } } } as never,
() => null,
)
return { ctx, slots, get, answerQuestion, cancelQuestion }
}
/** The question entry's injected share, resolved for one session id. */
function injectedOf(slots: SlotsService, sessionId: SessionId): QuestionComposerInjected {
const entries = slots.entries('conversation.composer')
expect(entries).toHaveLength(1)
// The typed StoredEntry.inject is declaration-derived ((...args: never[])
// shape); the question factory takes the framework-resolved sessionId.
const inject = entries[0]!.inject as ((id: SessionId) => QuestionComposerInjected) | undefined
return inject!(sessionId)
return { ctx, slots }
}
describe('apply', () => {
it('declares the services it binds', () => {
expect(inject).toEqual(['slots', 'sessions'])
expect(inject).toEqual(['slots'])
})
it('fails loud when its services are missing', () => {
// apply resolves both services through the strict need() reader (the
// program's host-side Context merge shadows typed property access).
it('fails loud when the slots service is missing', () => {
expect(() => { apply(new Context()) }).toThrow(/slots service unavailable/)
})
it('fails loud when no live entry has declared the composer slot', async () => {
const ctx = new Context()
await ctx.plugin(SlotsService).await()
ctx.provide('sessions', {})
await expect(ctx.plugin({ inject: [...inject], apply }))
.rejects.toThrow(/slot "conversation.composer" is not declared/)
})
it('registers the question entry with the thin two-callback inject surface', async () => {
const { ctx, slots, get } = await bench()
it('registers the question entry: routing selector, no inject face', async () => {
const { ctx, slots } = await bench()
await ctx.plugin({ inject: [...inject], apply }).await()
expect(slots.entries('conversation.composer')[0]!.options.key).toBe('question')
const injected = injectedOf(slots, 'session-1' as SessionId)
// The whole business face: two plain callbacks, no hooks, no store lines.
expect(Object.keys(injected).sort()).toEqual(['answer', 'cancel'])
expect(get).toHaveBeenCalledWith('session-1')
})
it('routes answer/cancel through the session and surfaces rejected receipts', async () => {
const { ctx, slots, answerQuestion, cancelQuestion } = await bench()
await ctx.plugin({ inject: [...inject], apply }).await()
const { answer, cancel } = injectedOf(slots, 'session-1' as SessionId)
const item = interaction()
const batch = { answers: [{ id: 'mode', selected: ['Fast'] }] }
await expect(answer(item, batch)).resolves.toBeUndefined()
await expect(answer(item, batch)).rejects.toThrow(/not-pending/)
await expect(cancel(item)).resolves.toBeUndefined()
await expect(cancel(item)).rejects.toThrow(/bad-response/)
expect(answerQuestion).toHaveBeenCalledWith(item.rpcId, batch)
expect(cancelQuestion).toHaveBeenCalledWith(item.rpcId)
const entry = slots.entries('conversation.composer')[0]!
expect(entry.component).toBe(QuestionComposer)
// The whole behavior surface rides the matched carrier: no business face.
expect(entry.inject).toBeUndefined()
// The selector narrows the chain currency: question wait in → that wait; none → null.
const select = entry.select as (owner: { interactions: readonly { kind: string }[] }) => unknown
const question = { kind: 'question' }
expect(select({ interactions: [{ kind: 'approval' }, question] })).toBe(question)
expect(select({ interactions: [{ kind: 'approval' }] })).toBeNull()
expect(select({ interactions: [] })).toBeNull()
})
it('teardown unregisters the slot entry', async () => {

View File

@@ -1,60 +1,71 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from 'vitest'
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import type { PendingInteraction, SessionId } from '@deepseek-ai/dsh-client-runtime/client'
import type { ConversationSnapshot, SessionId, SessionListState } from '@deepseek-ai/dsh-client-runtime/client'
import { PendingWait } from '@deepseek-ai/dsh-client-runtime/client'
import type { RpcReceipt } from '@deepseek-ai/dsh-client-connection/client'
import { RpcId } from '@deepseek-ai/dsh-client-connection/client'
import type { QuestionComposerProps } from '../src/client/contract/slots.ts'
import type { SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots'
import { PendingQuestion } from '../src/client/contract/slots.ts'
import {
QuestionComposer, parseQuestionTitle, parseRecommendedLabel,
} from '../src/client/QuestionComposer.tsx'
afterEach(cleanup)
type Interaction = Extract<PendingInteraction, { kind: 'question' }>
const SID = 's1' as SessionId
/** Framework standard-kit stubs: the composer consumes none of them, the
* composed props type mandates their delivery (framework hooks are plain
* stubs per the client testing discipline). */
const kit: Pick<QuestionComposerProps, 'sessionId' | 'useSession' | 'useSessions'> = {
sessionId: 's1' as SessionId,
useSession: (() => { throw new Error('unused') }) as unknown as QuestionComposerProps['useSession'],
useSessions: (() => { throw new Error('unused') }) as unknown as QuestionComposerProps['useSessions'],
const kit = {
sessionId: SID,
useSession: (() => { throw new Error('unused') }) as unknown as SnapshotSelectorHook<ConversationSnapshot>,
useSessions: (() => { throw new Error('unused') }) as unknown as SnapshotSelectorHook<SessionListState>,
}
function interaction(rpcId = 'question-1'): Interaction {
return {
kind: 'question',
rpcId: RpcId(rpcId),
questions: [
{
id: 'profile', header: '偏好', question: '选择候选人类型',
options: [
{ label: '工程落地型 (Recommended)', description: '优先工程交付。' },
{ label: '研究潜力型', description: '优先研究能力。' },
],
},
{
id: 'detail', question: '补充你的要求',
},
{
id: 'signals', question: '选择重要信号(可多选)', multiSelect: true,
options: [{ label: '系统设计' }, { label: '代码质量' }, { label: '产品判断' }],
},
const QUESTIONS = [
{
id: 'profile', header: '偏好', question: '选择候选人类型',
options: [
{ label: '工程落地型 (Recommended)', description: '优先工程交付。' },
{ label: '研究潜力型', description: '优先研究能力。' },
],
},
{
id: 'detail', question: '补充你的要求',
},
{
id: 'signals', question: '选择重要信号(可多选)', multiSelect: true,
options: [{ label: '系统设计' }, { label: '代码质量' }, { label: '产品判断' }],
},
]
/** Carrier fixture: a real PendingWait over a scripted respond carrier. */
function wait(rpcId = 'question-1', respond = vi.fn(() => Promise.resolve<RpcReceipt>({ accepted: true }))) {
const carrier = new PendingWait(
'question', RpcId(rpcId), SID, { questions: QUESTIONS } as PendingWait<'question'>['payload'], respond)
return { carrier, respond }
}
/** The client-response envelope respond must have received for an answer batch. */
function answeredEnvelope(rpcId: string, answers: object[]) {
return {
type: 'client-response', rpcId: RpcId(rpcId),
result: { ok: true, value: { sessionId: SID, answer: { answers } } },
}
}
describe('QuestionComposer', () => {
it('collects single, custom, and multi-select answers before one batch submit', () => {
const answer = vi.fn(() => Promise.resolve())
const cancel = vi.fn(() => Promise.resolve())
render(<QuestionComposer interaction={interaction()} answer={answer} cancel={cancel} {...kit} />)
const { carrier, respond } = wait()
render(<QuestionComposer matched={carrier} interactions={[carrier]} {...kit} />)
expect(screen.getByText('1 / 3')).toBeTruthy()
expect(screen.getByText('推荐')).toBeTruthy()
expect(screen.getByText('工程落地型')).toBeTruthy()
fireEvent.keyDown(screen.getByRole('radio', { name: /工程落地型/ }), { key: 'Enter' })
expect(answer).not.toHaveBeenCalled()
expect(respond).not.toHaveBeenCalled()
fireEvent.click(screen.getByRole('radio', { name: /工程落地型/ }))
expect(screen.getByText('2 / 3')).toBeTruthy()
@@ -73,20 +84,18 @@ describe('QuestionComposer', () => {
fireEvent.click(screen.getByRole('checkbox', { name: '代码质量' }))
fireEvent.keyDown(screen.getByRole('checkbox', { name: '代码质量' }), { key: 'Enter' })
expect(answer).toHaveBeenCalledWith(interaction(), {
answers: [
{ id: 'profile', selected: ['工程落地型 (Recommended)'] },
{ id: 'detail', selected: [], custom: '要能独立排查线上问题' },
{ id: 'signals', selected: ['系统设计', '代码质量'] },
],
})
// The domain face encoded the whole batch into one carrier envelope.
expect(respond).toHaveBeenCalledWith(answeredEnvelope('question-1', [
{ id: 'profile', selected: ['工程落地型 (Recommended)'] },
{ id: 'detail', selected: [], custom: '要能独立排查线上问题' },
{ id: 'signals', selected: ['系统设计', '代码质量'] },
]))
expect((screen.getByRole('button', { name: '正在提交…' }) as HTMLButtonElement).disabled).toBe(true)
})
it('skips individual questions without discarding earlier answers', () => {
const answer = vi.fn(() => Promise.resolve())
const cancel = vi.fn(() => Promise.resolve())
render(<QuestionComposer interaction={interaction()} answer={answer} cancel={cancel} {...kit} />)
const { carrier, respond } = wait()
render(<QuestionComposer matched={carrier} interactions={[carrier]} {...kit} />)
expect((screen.getByText('下一题').closest('button') as HTMLButtonElement).disabled).toBe(true)
fireEvent.click(screen.getByRole('radio', { name: '研究潜力型' }))
@@ -95,20 +104,16 @@ describe('QuestionComposer', () => {
expect(screen.getByText('3 / 3')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: '跳过本题' }))
expect(cancel).not.toHaveBeenCalled()
expect(answer).toHaveBeenCalledWith(interaction(), {
answers: [
{ id: 'profile', selected: ['研究潜力型'] },
{ id: 'detail', selected: [] },
{ id: 'signals', selected: [] },
],
})
expect(respond).toHaveBeenCalledWith(answeredEnvelope('question-1', [
{ id: 'profile', selected: ['研究潜力型'] },
{ id: 'detail', selected: [] },
{ id: 'signals', selected: [] },
]))
})
it('keeps IME Enter inside the custom input until composition finishes', () => {
const answer = vi.fn(() => Promise.resolve())
const cancel = vi.fn(() => Promise.resolve())
render(<QuestionComposer interaction={interaction()} answer={answer} cancel={cancel} {...kit} />)
const { carrier, respond } = wait()
render(<QuestionComposer matched={carrier} interactions={[carrier]} {...kit} />)
fireEvent.click(screen.getByRole('radio', { name: '研究潜力型' }))
const custom = screen.getByPlaceholderText('输入你的答案')
@@ -116,20 +121,19 @@ describe('QuestionComposer', () => {
fireEvent.keyDown(custom, { key: 'Enter', isComposing: true })
expect(screen.getByText('2 / 3')).toBeTruthy()
expect(answer).not.toHaveBeenCalled()
expect(respond).not.toHaveBeenCalled()
fireEvent.keyDown(custom, { key: 'Enter', keyCode: 229 })
expect(screen.getByText('2 / 3')).toBeTruthy()
expect(answer).not.toHaveBeenCalled()
expect(respond).not.toHaveBeenCalled()
fireEvent.keyDown(custom, { key: 'Enter' })
expect(screen.getByText('3 / 3')).toBeTruthy()
})
it('opens custom input, reports missing skipped answers, and supports header navigation', () => {
const answer = vi.fn(() => Promise.resolve())
const cancel = vi.fn(() => Promise.resolve())
render(<QuestionComposer interaction={interaction()} answer={answer} cancel={cancel} {...kit} />)
const { carrier, respond } = wait()
render(<QuestionComposer matched={carrier} interactions={[carrier]} {...kit} />)
fireEvent.click(screen.getByRole('button', { name: '其他,请填写自定义答案' }))
expect(screen.getByPlaceholderText('输入你的答案')).toBeTruthy()
@@ -147,32 +151,36 @@ describe('QuestionComposer', () => {
expect(screen.getByText('2 / 3')).toBeTruthy()
fireEvent.click(screen.getByLabelText('上一题'))
expect(screen.getByText('1 / 3')).toBeTruthy()
expect(answer).not.toHaveBeenCalled()
expect(respond).not.toHaveBeenCalled()
})
it('surfaces explicit cancellation rejection', async () => {
const answer = vi.fn(() => Promise.resolve())
const cancel = vi.fn(() => Promise.reject('取消请求失败'))
render(<QuestionComposer interaction={interaction()} answer={answer} cancel={cancel} {...kit} />)
it('surfaces cancellation failures: rejected receipt text and raw transport reasons', async () => {
const respond = vi.fn()
.mockResolvedValueOnce({ accepted: false, reason: 'bad-response' })
.mockRejectedValueOnce(new Error('第二次取消失败'))
const { carrier } = wait('question-1', respond)
render(<QuestionComposer matched={carrier} interactions={[carrier]} {...kit} />)
// Receipt rejection surfaces through the domain face's thrown message.
fireEvent.click(screen.getByRole('button', { name: '放弃整组问题' }))
expect(await screen.findByText('取消请求失败')).toBeTruthy()
expect(await screen.findByText('question cancellation rejected: bad-response')).toBeTruthy()
expect((screen.getByRole('button', { name: '跳过本题' }) as HTMLButtonElement).disabled).toBe(false)
cancel.mockRejectedValueOnce(new Error('第二次取消失败'))
fireEvent.click(screen.getByRole('button', { name: '放弃整组问题' }))
expect(await screen.findByText('第二次取消失败')).toBeTruthy()
})
it('surfaces transport rejection and resets local drafts for a different rpcId', async () => {
const answer = vi.fn(() => Promise.reject(new Error('网络中断')))
const cancel = vi.fn(() => Promise.resolve())
const first = interaction('first')
const view = render(<QuestionComposer interaction={first} answer={answer} cancel={cancel} {...kit} />)
it('surfaces transport rejection and resets local drafts for a different request', async () => {
const respond = vi.fn()
.mockRejectedValueOnce(new Error('网络中断'))
.mockRejectedValueOnce('字符串错误')
const first = wait('first', respond)
const view = render(<QuestionComposer matched={first.carrier} interactions={[first.carrier]} {...kit} />)
fireEvent.click(screen.getByRole('radio', { name: /研究潜力型/ }))
expect(screen.getByText('2 / 3')).toBeTruthy()
view.rerender(<QuestionComposer interaction={interaction('second')} answer={answer} cancel={cancel} {...kit} />)
const second = wait('second', respond)
view.rerender(<QuestionComposer matched={second.carrier} interactions={[second.carrier]} {...kit} />)
expect(screen.getByRole('radio', { name: /研究潜力型/ }).getAttribute('aria-checked')).toBe('false')
fireEvent.click(screen.getByRole('radio', { name: /工程落地型/ }))
@@ -184,10 +192,55 @@ describe('QuestionComposer', () => {
expect(await screen.findByText('网络中断')).toBeTruthy()
expect((screen.getByRole('button', { name: '提交' }) as HTMLButtonElement).disabled).toBe(false)
answer.mockRejectedValueOnce('字符串错误')
fireEvent.click(screen.getByRole('button', { name: '提交' }))
expect(await screen.findByText('字符串错误')).toBeTruthy()
})
it('same-key carrier replacement (baseline replay) keeps drafts', () => {
const first = wait('same-id')
const view = render(<QuestionComposer matched={first.carrier} interactions={[first.carrier]} {...kit} />)
fireEvent.click(screen.getByRole('radio', { name: /研究潜力型/ }))
expect(screen.getByText('2 / 3')).toBeTruthy()
// Replay mints a NEW carrier for the same request; same key = no remount.
const replayed = wait('same-id')
view.rerender(<QuestionComposer matched={replayed.carrier} interactions={[replayed.carrier]} {...kit} />)
expect(screen.getByText('2 / 3')).toBeTruthy()
})
})
describe('PendingQuestion domain face', () => {
it('encodes the answer batch into the ok envelope and throws on a rejected receipt', async () => {
const respond = vi.fn()
.mockResolvedValueOnce({ accepted: true })
.mockResolvedValueOnce({ accepted: false, reason: 'not-pending' })
const question = new PendingQuestion(wait('rq', respond).carrier)
const batch = { answers: [{ id: 'mode', selected: ['Fast'] }] }
await expect(question.answer(batch)).resolves.toBeUndefined()
expect(respond).toHaveBeenCalledWith(answeredEnvelope('rq', batch.answers))
await expect(question.answer(batch)).rejects.toThrow(/question response rejected: not-pending/)
})
it('encodes cancellation as the cancelled error envelope and throws on a rejected receipt', async () => {
const respond = vi.fn()
.mockResolvedValueOnce({ accepted: true })
.mockResolvedValueOnce({ accepted: false, reason: 'bad-response' })
const question = new PendingQuestion(wait('rc', respond).carrier)
await expect(question.cancel()).resolves.toBeUndefined()
expect(respond).toHaveBeenCalledWith({
type: 'client-response', rpcId: RpcId('rc'),
result: {
ok: false,
error: { code: 'cancelled', message: 'the user closed this question request', details: {} },
},
})
await expect(question.cancel()).rejects.toThrow(/question cancellation rejected: bad-response/)
})
it('forwards key and questions from the carrier', () => {
const question = new PendingQuestion(wait('rk').carrier)
expect(question.key).toBe('q:rk')
expect(question.questions).toBe(wait('rk').carrier.payload.questions)
})
})
describe('parseRecommendedLabel', () => {