import assert from 'node:assert/strict'; import { test } from 'vitest'; import type { ChatConversationViewNode } from '@deepseek-ai/dsh-client-ui-chat/client'; import type { TurnLocation } from '@deepseek-ai/dsh-client-ui-conversation/client'; import type { SessionPendingInteraction } from '@deepseek-ai/dsh-client-ui-session/client'; import type { ReaderGroup } from '../src/client/projection.js'; import { distributeBubbleQuestions, type FlowWave } from '../src/client/fold-choreography.js'; import type { LiveTurnItem } from '../src/client/live-turn.js'; import { extractGroupQuestions, findHostedPendingGroupKey, findOffWindowActiveQuestions, formatQuestionFollowUpReply, isPendingToolResult, parseAnswerBatch, parseQuestionItems, queuedQuestionRepliesFromInbox, type QuestionItem, type UserQuestionsProjectionView, } from '../src/client/turn-questions.js'; function toolResultNode( key: string, callId: string, argsRaw: string, result: { content?: Array<{ type: string; text?: string }>; isError?: boolean; error?: { code?: string }; subCalls?: unknown[]; } = {}, toolName = 'ask_user_question', ): ChatConversationViewNode { return { key, kind: 'tool-call', anchorSeq: 1, visibility: 'visible', location: { kind: 'turn', turn: { turn: 1 } }, data: { root: { kind: 'tool-result', callId, call: { name: toolName, argsRaw }, content: result.content ?? [], isError: result.isError ?? false, ...(result.error ? { error: result.error } : {}), subCalls: result.subCalls ?? [], }, }, } as unknown as ChatConversationViewNode; } function runningToolNode(key: string, callId: string, argsRaw: string): ChatConversationViewNode { return { key, kind: 'tool-call', anchorSeq: 1, visibility: 'visible', location: { kind: 'turn', turn: { turn: 1 } }, data: { root: { callId, name: 'ask_user_question', argsRaw, phase: 'running', }, }, } as unknown as ChatConversationViewNode; } const sampleArgs = JSON.stringify({ questions: [ { id: 'q1', header: '数据库', question: '要使用哪种数据库?', multi_select: false, options: [ { label: 'SQLite', description: '本地单文件轻量存储' }, { label: 'PostgreSQL', description: '服务端关系型数据库' }, ], }, { id: 'q2', question: '需要包含哪些能力?', multiSelect: true, options: [ { label: '全文检索' }, { label: '迁移脚本' }, ], }, ], }); test('parseQuestionItems normalizes multi_select/multiSelect, options, and rejects invalid/partial JSON', () => { const parsed = parseQuestionItems(sampleArgs); assert.equal(parsed.length, 2); assert.deepEqual(parsed[0], { id: 'q1', header: '数据库', question: '要使用哪种数据库?', multiSelect: false, options: [ { label: 'SQLite', description: '本地单文件轻量存储' }, { label: 'PostgreSQL', description: '服务端关系型数据库' }, ], }); assert.equal(parsed[1]?.multiSelect, true); assert.equal(parsed[1]?.options?.[0]?.label, '全文检索'); assert.deepEqual(parseQuestionItems(undefined), []); assert.deepEqual(parseQuestionItems('{"questions":[{"id":"q1"'), []); assert.deepEqual(parseQuestionItems('{"other":true}'), []); assert.deepEqual(parseQuestionItems('{"questions":[{"id":"","question":"x"}]}'), []); }); test('parseAnswerBatch, isPendingToolResult, and queuedQuestionRepliesFromInbox parse payloads accurately', () => { assert.equal(isPendingToolResult(JSON.stringify({ pending: true, callId: 'c1' })), true); assert.equal(isPendingToolResult(JSON.stringify({ answers: [] })), false); assert.equal(isPendingToolResult('not json'), false); const batch = parseAnswerBatch(JSON.stringify({ kind: 'answer_to_pending_question', answers: [{ id: 'q1', selected: ['SQLite'], custom: 'WAL 模式' }], })); assert.deepEqual(batch, [{ id: 'q1', selected: ['SQLite'], custom: 'WAL 模式' }]); assert.equal(parseAnswerBatch('{"answers":[{"id":123}]}'), null); const queued = queuedQuestionRepliesFromInbox({ 'next-step': [ { source: { kind: 'user-question-reply', callId: 'c-queued' }, content: [{ type: 'text', text: JSON.stringify({ answers: [{ id: 'q1', selected: ['PostgreSQL'] }] }), }], }, ], 'next-turn': [ { source: { kind: 'user', rpcId: 'u1' }, content: [{ type: 'text', text: 'hi' }] }, ], }); assert.equal(queued.size, 1); assert.deepEqual(queued.get('c-queued'), [{ id: 'q1', selected: ['PostgreSQL'] }]); }); test('extractGroupQuestions resolves all 7 statuses and deduplicates draft + tool-call node by callId', () => { const group: ReaderGroup = { key: 'turn:3', turn: 3, keys: [ 'n-open', 'n-continued', 'n-queued', 'n-answered-proj', 'n-answered-res', 'n-cancelled', 'n-interrupted', 'n-closed', ], }; const map = new Map([ ['n-open', runningToolNode('n-open', 'c-open', sampleArgs)], ['n-continued', toolResultNode('n-continued', 'c-continued', sampleArgs, { content: [{ type: 'text', text: JSON.stringify({ pending: true, callId: 'c-continued' }) }], })], ['n-queued', toolResultNode('n-queued', 'c-queued', sampleArgs, { content: [{ type: 'text', text: JSON.stringify({ pending: true, callId: 'c-queued' }) }], })], ['n-answered-proj', toolResultNode('n-answered-proj', 'c-answered-proj', sampleArgs, { content: [{ type: 'text', text: JSON.stringify({ pending: true, callId: 'c-answered-proj' }) }], })], ['n-answered-res', toolResultNode('n-answered-res', 'c-answered-res', sampleArgs, { content: [{ type: 'text', text: JSON.stringify({ answers: [{ id: 'q1', selected: ['PostgreSQL'] }] }) }], })], ['n-cancelled', toolResultNode('n-cancelled', 'c-cancelled', sampleArgs, { isError: true, error: { code: 'ASK_CANCELLED' }, })], ['n-interrupted', toolResultNode('n-interrupted', 'c-interrupted', sampleArgs, { isError: true, error: { code: 'ASK_ABORTED' }, })], ['n-closed', toolResultNode('n-closed', 'c-closed', sampleArgs, { content: [{ type: 'text', text: JSON.stringify({ pending: true, callId: 'c-closed' }) }], })], ]); // Also include a draft for c-open and an extra draft-only call c-draft-only on turn.steps. const turn = { steps: [ { data: { get(kind: string) { if (kind !== 'assistant-step') return undefined; return { blocks: [ { kind: 'tool-call', callId: 'c-open', name: 'ask_user_question', argsRaw: sampleArgs }, { kind: 'tool-call', callId: 'c-draft-only', name: 'ask_user_question', argsRaw: sampleArgs }, ], }; }, }, }, ], } as unknown as TurnLocation; const parsedSample = parseQuestionItems(sampleArgs); const projection: UserQuestionsProjectionView = { active: [ { callId: 'c-continued', state: 'continued', questions: parsedSample }, { callId: 'c-queued', state: 'continued', questions: parsedSample }, ], settled: [ { callId: 'c-answered-proj', answers: [{ id: 'q1', selected: ['SQLite'] }, { id: 'q2', selected: ['全文检索'] }] }, ], }; const queued = new Map([['c-queued', [{ id: 'q1', selected: ['SQLite'] }]]]); const entries = extractGroupQuestions({ group, turn, getNode: key => map.get(key), userQuestions: projection, queuedReplies: queued, }); const byCall = new Map(entries.map(item => [item.callId, item])); assert.equal(entries.length, 9); assert.equal(byCall.get('c-open')?.status, 'open'); assert.equal(byCall.get('c-draft-only')?.status, 'open'); assert.equal(byCall.get('c-continued')?.status, 'continued'); assert.equal(byCall.get('c-queued')?.status, 'queued'); assert.equal(byCall.get('c-answered-proj')?.status, 'answered'); assert.ok(byCall.get('c-answered-proj')?.reviewRecord); assert.equal(byCall.get('c-answered-res')?.status, 'answered'); assert.ok(byCall.get('c-answered-res')?.reviewRecord); assert.equal(byCall.get('c-cancelled')?.status, 'cancelled'); assert.equal(byCall.get('c-interrupted')?.status, 'interrupted'); assert.equal(byCall.get('c-closed')?.status, 'closed'); }); test('findHostedPendingGroupKey and findOffWindowActiveQuestions enforce in-turn hosting vs off-window reachability', () => { const g1: ReaderGroup = { key: 'turn:1', turn: 1, keys: [] }; const g2: ReaderGroup = { key: 'turn:2', turn: 2, keys: [] }; const qItem: QuestionItem = { id: 'q1', question: '选一个方案?' }; const questionsByGroup = new Map([ ['turn:2', [{ callId: 'call-t2', status: 'continued' as const, questions: [qItem], answers: [], turn: 2, groupKey: 'turn:2' }]], ]); const questionPending = { key: 'question:s:call-t2', kind: 'question', sessionId: 's', callId: 'call-t2' } as unknown as SessionPendingInteraction; const planPending = { key: 'question:s:call-t2', kind: 'plan-review', sessionId: 's', callId: 'call-t2' } as unknown as SessionPendingInteraction; const approvalPending = { key: 'approval:1', kind: 'approval', sessionId: 's', callId: 'call-t2' } as unknown as SessionPendingInteraction; const missingCallPending = { key: 'question:s:call-off', kind: 'question', sessionId: 's', callId: 'call-off' } as unknown as SessionPendingInteraction; assert.equal(findHostedPendingGroupKey(questionPending, [g1, g2], questionsByGroup), 'turn:2'); assert.equal(findHostedPendingGroupKey(planPending, [g1, g2], questionsByGroup), null); assert.equal(findHostedPendingGroupKey(approvalPending, [g1, g2], questionsByGroup), null); assert.equal(findHostedPendingGroupKey(missingCallPending, [g1, g2], questionsByGroup), null); const projection: UserQuestionsProjectionView = { active: [ { callId: 'call-t2', state: 'continued', questions: [qItem] }, { callId: 'call-old-queued', state: 'continued', questions: [qItem] }, { callId: 'call-old-open', state: 'continued', questions: [qItem] }, { callId: 'call-old-pending', state: 'open', questions: [qItem] }, ], }; const offWindow = findOffWindowActiveQuestions( projection, new Map([['call-old-queued', []]]), new Set(['call-t2']), 'call-old-pending', ); assert.deepEqual(offWindow.map(item => item.callId), ['call-old-open']); }); test('formatQuestionFollowUpReply formats both revise and answer modes clearly', () => { const questions: QuestionItem[] = [ { id: 'q1', header: '数据库', question: '选择哪种存储?' }, { id: 'q2', question: '是否开启审计?' }, { id: 'q3', question: '补充备注' }, ]; const answers = [ { id: 'q1', selected: ['SQLite', 'FTS5'], custom: '启用 WAL' }, { id: 'q2', selected: ['是'] }, { id: 'q3', selected: [] }, ]; const revised = formatQuestionFollowUpReply(questions, answers, 'revise'); assert.match(revised, /^关于之前的问题,更新我的回答:/u); assert.match(revised, /- 数据库 — 选择哪种存储?:SQLite;FTS5;启用 WAL/u); assert.match(revised, /- 是否开启审计?:是/u); assert.match(revised, /- 补充备注:(跳过)/u); const answered = formatQuestionFollowUpReply(questions, answers, 'answer'); assert.match(answered, /^关于之前未完成的问题,我的回答如下:/u); }); test('distributeBubbleQuestions matches question callIds to owning assistant wave bubbles and synthesizes tail when no wave exists', () => { const waves: FlowWave<{ key: string; row: { kind: 'step'; key: string; step: { kind: 'tool'; key: string; entry: { callId: string } } } | { kind: 'summary'; key: string; item: Extract } }>[] = [ { key: 'initial', body: [], other: [], process: [ { key: 'tool:c1', row: { kind: 'step', key: 'tool:c1', step: { kind: 'tool', key: 'tool:c1', entry: { callId: 'c1' } }, }, }, ], }, { key: 'user:1', user: { key: 'user:1', row: { kind: 'summary', key: 'user:1', item: { kind: 'fold', key: 'user:1', steps: [], summary: '' } }, }, body: [], other: [], process: [], }, { key: 'after:user:1', body: [], other: [], process: [ { key: 'fold:after', row: { kind: 'summary', key: 'fold:after', item: { kind: 'fold', key: 'fold:after', summary: '工具×1', steps: [{ kind: 'tool', key: 'tool:c2', entry: { callId: 'c2' } as never }], }, }, }, ], }, ]; const { byWaveKey, tailOnly } = distributeBubbleQuestions(waves, [ { callId: 'c1', node: 'n1' }, { callId: 'c2', node: 'n2' }, { callId: 'unmatched', node: 'n3' }, ]); assert.deepEqual(byWaveKey.get('initial')?.map(x => x.callId), ['c1']); assert.deepEqual(byWaveKey.get('after:user:1')?.map(x => x.callId), ['c2', 'unmatched']); assert.deepEqual(tailOnly, []); const userOnlyResult = distributeBubbleQuestions(waves.filter(w => !!w.user), [{ callId: 'c1', node: 'n1' }]); assert.deepEqual(userOnlyResult.tailOnly.map(x => x.callId), ['c1']); });