mirror of
https://github.com/deepseek-ai/deepseek-harness
synced 2026-08-15 21:04:50 +00:00
feat(web): render a plan review as a decision card, not a quiz
The Web composer now renders a request that declares the `plan-review` intent as its own surface: the waiting-approval card language — amber "Plan review" strip, the plan as the scrolling markdown body, the question as the card's accessible name — over one decision row of Chat about it / Refuse / Approve. Gone from that surface are the 1/1 pager, the numbered radio rows, the custom answer row, and Skip/Submit, which made approving a plan read as sitting an exam. Approve and Refuse answer with the asker's own option labels and keep its descriptions as tooltips; Chat about it cancels the request so the composer returns and the user can simply say what they want. Copy is bilingual under the existing `question` namespace. The shape choice lives inside the single composer entry rather than a second chain registration, so the two surfaces cannot race the same carrier, and `planReviewOf` falls back to the generic flow for any request it cannot render as a card — the client sits downstream of a wire boundary and every request must stay answerable.
This commit is contained in:
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/client/ui-question/README.md
|
||||
README.md: 0700375758774610fcd897b9a3e16484206a871d
|
||||
README.zh.md: d9e5eb22cef13e16ab1ce2cebba9e563bd9d08d9
|
||||
README.md: 6b40c503be61c2458cefceabbb35e16a3befbe66
|
||||
README.zh.md: 7c0c4ee67d1ef8b4507f3899bdb1ae2f76408032
|
||||
|
||||
@@ -6,6 +6,8 @@ Web `ask_user_question` feature plugin. Its host half mounts `dsh-tool-ask-user`
|
||||
|
||||
The component renders one question at a time with progress navigation, single- and multi-select choices, recommendation badges derived from label suffixes, and custom answers. Question detail reuses the assistant-output `MarkdownText` primitive, including its GFM rendering and untrusted-content policy. The capped card keeps its title, navigation, and submission actions fixed while long detail and choices share an internal scroll region. Single-select choices advance immediately, and Enter submits once every question is answered or skipped; Enter during IME composition confirms the input candidate without advancing. It submits one structured answer batch for the whole request: “Skip this question” retains other drafts and emits the existing blank `{ selected: [] }` shape for that item, while close rejects the whole wait as `ASK_CANCELLED`.
|
||||
|
||||
A request whose single question declares a presentation intent renders as that intent's own surface instead. `plan-review` — set by `dsh-plan-mode` on the `exit_plan_mode` review — takes the waiting-approval card shape: a `Plan review` strip, the plan as the scrolling markdown body, the question text as the card's accessible name, and one decision row of `Chat about it` / `Refuse` / `Approve`. Approve and Refuse answer with the asker's own option labels (the intent names which label approves, so the verdict never rides option order) and keep the asker's descriptions as tooltips; `Chat about it` rejects the wait as `ASK_CANCELLED`, returning the composer so the user can say what they want instead. A request that declares no intent, batches more than one question, or fails to offer the named approve label stays on the generic flow — the layout is all an intent changes, never the answer.
|
||||
|
||||
Selection state is local to a component keyed by the request rpcId. A replay with the same id preserves a still-mounted draft, while `question/resolved` from the host removes the composer. The host remains authoritative: successful HTTP delivery does not remove pending state locally.
|
||||
|
||||
Composer chrome copy (pager, buttons, placeholders, validation feedback) is bilingual: the plugin registers zh/en dictionaries under the `question` namespace of `dsh-client-locale` and hands the entry its bound translator plus the locale snapshot source through the inject face, so a locale switch re-renders a mounted composer. Question and option text arrives from the model and renders verbatim; carrier failure messages also display untranslated.
|
||||
|
||||
@@ -6,6 +6,8 @@ Web `ask_user_question` 功能插件。只有选择 Web 功能时,其主机侧
|
||||
|
||||
组件每次渲染一个问题,提供进度导航、单选和多选选项、由标签后缀派生的推荐徽标,以及自定义答案。问题详情复用助手输出的 `MarkdownText` 原语,包括其 GFM 渲染与不受信内容策略。封顶卡片保持标题、导航与提交动作固定,超长的详情与选项共享内部滚动区。单选选项会立即前进;所有问题均已回答或跳过后,Enter 会提交;IME 输入法组合期间按 Enter 只会确认输入候选,不会前进。组件为整个请求提交一批结构化答案:「跳过此问题」会保留其他草稿,并为该项发出既有的空 `{ selected: [] }` 形状;关闭则以 `ASK_CANCELLED` 拒绝整个等待。
|
||||
|
||||
若某个请求的唯一问题声明了呈现意图,则改为渲染该意图自己的界面。`plan-review` —— 由 `dsh-plan-mode` 在 `exit_plan_mode` 审阅上设置 —— 采用等待审批卡片的形状:一条 `Plan review` 条带、计划作为可滚动的 markdown 主体、问题文本作为卡片的无障碍名称,以及一行 `Chat about it` / `Refuse` / `Approve` 的决定操作。Approve 与 Refuse 用提问方自己的选项标签回答(意图指名哪个标签表示批准,因此裁决绝不依赖选项顺序),并把提问方的描述保留为 tooltip;`Chat about it` 以 `ASK_CANCELLED` 拒绝该等待,让编辑器归位,用户可以直接说出他想说的话。未声明意图、一批含多个问题、或未提供被指名的批准标签的请求,一律留在通用流程上 —— 意图改变的只是布局,从不改变答案。
|
||||
|
||||
选择状态只存在于以请求 rpcId 为 key 的组件本地。使用相同 id 回放时,只要组件仍挂载,就会保留草稿;主机发出的 `question/resolved` 则会移除编辑器。主机仍具有最终决定权:HTTP 交付成功不会在本地移除待处理状态。
|
||||
|
||||
编辑器外框文案(翻页器、按钮、占位符、校验提示)是双语的:插件在 `dsh-client-locale` 的 `question` 命名空间下注册 zh/en 词典,并通过 inject face 把绑定的翻译函数和 locale 快照源交给该配置项,因此切换语言会重新渲染已挂载的编辑器。问题与选项文本来自模型并原样渲染;载体失败消息也不经翻译直接显示。
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
/* Plan-review takeover: the waiting-approval card language (amber strip on a
|
||||
floating capsule, right-aligned actions) applied to a reviewed plan. Kept as
|
||||
its own module rather than shared with ui-conversation's ApprovalPanel: the
|
||||
two takeovers agree on tokens and geometry, not on content — this one's body
|
||||
is scrollable markdown, that one's is a headline plus a command line. Warn
|
||||
semantics ride the alias state tokens; no hardcoded colors. */
|
||||
|
||||
/* Mirrors the question card's frame so the takeover is a content swap. */
|
||||
.frame {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding: 6px 24px 10px;
|
||||
}
|
||||
|
||||
.card {
|
||||
display: flex;
|
||||
overflow: hidden;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
max-width: 776px;
|
||||
/* Composer seat sits in a fixed-height conversation column (overflow
|
||||
hidden): cap the card against the viewport and scroll the plan, so the
|
||||
strip and the decision row stay reachable on a long plan. */
|
||||
max-height: min(60vh, 520px);
|
||||
border: 1px solid var(--dsw-alias-state-warn-secondary);
|
||||
border-radius: 20px;
|
||||
background: var(--dsw-specific-input-major);
|
||||
box-shadow: var(--dsw-shadow-lv2);
|
||||
color: var(--dsw-alias-label-primary);
|
||||
/* Elevated surface in dark: the plan body inside scrolls once the card hits
|
||||
the cap above, so the thumb takes the l2 pair (see ui-theme
|
||||
styles/scrollbar.css for the rebinding contract). */
|
||||
--dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2);
|
||||
--dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2);
|
||||
}
|
||||
|
||||
.card,
|
||||
.card * {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
/* Tinted full-width header band, as on the approval takeover. */
|
||||
.strip {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-shrink: 0;
|
||||
gap: 8px;
|
||||
padding: 10px 16px;
|
||||
background: var(--dsw-alias-state-warn-tertiary);
|
||||
color: var(--dsw-alias-state-warn-primary);
|
||||
font-size: 13px;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
.dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--dsw-alias-state-warn-primary);
|
||||
}
|
||||
|
||||
/* The plan is the panel's message: it takes the whole body and the scroll. */
|
||||
.body {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
padding: 12px 16px 4px;
|
||||
font-size: 14px;
|
||||
line-height: 22px;
|
||||
}
|
||||
|
||||
.footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-shrink: 0;
|
||||
gap: 12px;
|
||||
padding: 8px 16px 12px;
|
||||
}
|
||||
|
||||
.feedback {
|
||||
min-height: 16px;
|
||||
color: var(--dsw-alias-state-error-primary);
|
||||
font-size: 11px;
|
||||
line-height: 16px;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-shrink: 0;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.frame {
|
||||
padding: 6px 10px 10px;
|
||||
}
|
||||
|
||||
.card {
|
||||
border-radius: 16px;
|
||||
}
|
||||
|
||||
.body {
|
||||
padding: 10px 12px 4px;
|
||||
}
|
||||
|
||||
.footer {
|
||||
align-items: flex-end;
|
||||
padding: 8px 12px 10px;
|
||||
}
|
||||
}
|
||||
100
packages/client/ui-question/src/client/PlanReviewPanel.tsx
Normal file
100
packages/client/ui-question/src/client/PlanReviewPanel.tsx
Normal file
@@ -0,0 +1,100 @@
|
||||
// PlanReviewPanel: the composer takeover for a question carrying the
|
||||
// `plan-review` presentation intent. A plan under review is one decision over
|
||||
// one body of markdown, so it takes the waiting-approval card shape — tinted
|
||||
// strip, content, right-aligned action row — instead of the generic question
|
||||
// flow's pager, numbered options, skip and custom-answer affordances, which
|
||||
// read as a quiz the user is being graded on.
|
||||
//
|
||||
// The three actions are the whole decision surface: approve and decline answer
|
||||
// the question with the option labels the asker offered (localised copy on the
|
||||
// buttons, the asker's descriptions as their tooltips), while "discuss"
|
||||
// dismisses the request so the composer returns and the user can simply say
|
||||
// what they want. Dismissal is the generic flow's own cancel verb, promoted to
|
||||
// a labelled button because in a two-outcome decision it is the third real
|
||||
// answer, not an escape hatch.
|
||||
|
||||
import { useState } from 'react'
|
||||
import { Button, IconEditOutline16, MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { PendingQuestion, PlanReview, QuestionComposerProps } from './contract/slots.ts'
|
||||
import css from './PlanReviewPanel.module.css'
|
||||
|
||||
/** The panel's own props: the question domain face, the narrowed review, and the locale seat. */
|
||||
export type PlanReviewPanelProps =
|
||||
{ pending: PendingQuestion; review: PlanReview } & Pick<QuestionComposerProps, 't'>
|
||||
|
||||
/**
|
||||
* Optional-prop spread for a decision button's tooltip: `title` is optional on
|
||||
* the DOM props, and exactOptionalPropertyTypes rejects an explicit undefined.
|
||||
*
|
||||
* @param description - the asker's option description, when it carries one.
|
||||
* @returns The `title` prop to spread, or nothing.
|
||||
*/
|
||||
function tooltip(description: string | undefined): { title?: string } {
|
||||
return description === undefined ? {} : { title: description }
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a plan review as a decision card.
|
||||
*
|
||||
* @param props - the question domain face, the narrowed plan review, and `t`.
|
||||
* @returns The plan-review takeover for this request.
|
||||
*/
|
||||
export function PlanReviewPanel({ pending, review, t }: PlanReviewPanelProps) {
|
||||
// One-shot latch shaped like the approval takeover's: the panel leaves only
|
||||
// when the host's resolved frame lands, so until then a second click must
|
||||
// not re-fire. A failed send (rejected receipt / transport) re-arms it and
|
||||
// shows why, since nothing else would tell the user the click was lost.
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const settle = (send: () => Promise<void>): void => {
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
void send().catch((cause: unknown) => {
|
||||
setBusy(false)
|
||||
setError(cause instanceof Error ? cause.message : String(cause))
|
||||
})
|
||||
}
|
||||
const decide = (label: string): void => {
|
||||
settle(() => pending.answer({ answers: [{ id: review.id, selected: [label] }] }))
|
||||
}
|
||||
const decline = review.decline
|
||||
|
||||
return (
|
||||
<div className={css.frame} data-plan-review-key={pending.key}>
|
||||
<section className={css.card} aria-label={review.question}>
|
||||
<div className={css.strip}>
|
||||
<span className={css.dot} />
|
||||
{t('plan.header')}
|
||||
</div>
|
||||
<div className={css.body} data-plan-review-scroll>
|
||||
<MarkdownText text={review.plan} />
|
||||
</div>
|
||||
<div className={css.footer}>
|
||||
<div className={css.feedback} role="status">{error}</div>
|
||||
<div className={css.actions}>
|
||||
<Button
|
||||
size="sm" variant="ghost" icon={<IconEditOutline16 />}
|
||||
disabled={busy} onClick={() => { settle(() => pending.cancel()) }}
|
||||
>
|
||||
{t('plan.discuss')}
|
||||
</Button>
|
||||
{decline !== undefined && (
|
||||
<Button
|
||||
size="sm" variant="outline" {...tooltip(decline.description)}
|
||||
disabled={busy} onClick={() => { decide(decline.label) }}
|
||||
>
|
||||
{t('plan.decline')}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm" variant="primary" {...tooltip(review.approve.description)}
|
||||
disabled={busy} onClick={() => { decide(review.approve.label) }}
|
||||
>
|
||||
{t('plan.approve')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -5,9 +5,10 @@ import {
|
||||
IconCloseOutline16, IconEditOutline16, MarkdownText,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import {
|
||||
PendingQuestion,
|
||||
PendingQuestion, planReviewOf,
|
||||
type QuestionAnswer, type QuestionComposerProps,
|
||||
} from './contract/slots.ts'
|
||||
import { PlanReviewPanel } from './PlanReviewPanel.tsx'
|
||||
import css from './QuestionComposer.module.css'
|
||||
|
||||
interface DraftAnswer {
|
||||
@@ -46,14 +47,24 @@ function isComposing(event: KeyboardEvent<HTMLTextAreaElement | HTMLInputElement
|
||||
/**
|
||||
* Composer takeover boundary; the carrier key keys local drafts, so a
|
||||
* same-request replay (same key, new carrier object) preserves them.
|
||||
*
|
||||
* One takeover, two shapes: a request that declares a presentation intent this
|
||||
* package renders takes that shape (a plan review is one decision over one
|
||||
* plan, not a question set), and every other request takes the generic flow.
|
||||
* The routing lives here, at the one entry that owns the composer seat, so
|
||||
* neither shape can claim a request the other is already rendering.
|
||||
*
|
||||
* @param props - the selector-matched pending question carrier plus the framework standard kit.
|
||||
* @returns The question flow for this request.
|
||||
* @returns The question flow, or the intent's own surface, for this request.
|
||||
*/
|
||||
export function QuestionComposer(props: QuestionComposerProps) {
|
||||
// Domain-face mint rides the carrier's stable identity (never minted in a
|
||||
// select/render dispatch — per-dispatch minting would churn memo identity).
|
||||
const question = useMemo(() => new PendingQuestion(props.matched), [props.matched])
|
||||
return <QuestionFlow key={question.key} pending={question} t={props.t} />
|
||||
const review = useMemo(() => planReviewOf(question.questions), [question])
|
||||
return review === undefined
|
||||
? <QuestionFlow key={question.key} pending={question} t={props.t} />
|
||||
: <PlanReviewPanel key={question.key} pending={question} review={review} t={props.t} />
|
||||
}
|
||||
|
||||
function QuestionFlow({ pending, t }: { pending: PendingQuestion } & Pick<QuestionComposerProps, 't'>) {
|
||||
|
||||
@@ -19,6 +19,65 @@ export type QuestionWait = PendingWait<'question'>
|
||||
/** One structured answer batch covering every question of the request. */
|
||||
export type QuestionAnswer = QuestionResponsePayload['answer']
|
||||
|
||||
/** One question of the request, as the carrier payload carries it. */
|
||||
type QuestionItem = QuestionWait['payload']['questions'][number]
|
||||
|
||||
/** One option the asker offered on a question. */
|
||||
type QuestionOption = NonNullable<QuestionItem['options']>[number]
|
||||
|
||||
/**
|
||||
* A request narrowed to the `plan-review` presentation intent: everything the
|
||||
* decision card renders and answers with, so the panel never re-reads the
|
||||
* request shape. `approve` and `decline` are the asker's own options — an
|
||||
* answer must carry one of those labels verbatim — and `plan` is the markdown
|
||||
* body under review.
|
||||
*/
|
||||
export interface PlanReview {
|
||||
/** The reviewed question's id, echoed in the answer. */
|
||||
id: string
|
||||
/** The question text, kept as the card's accessible name. */
|
||||
question: string
|
||||
/** The plan markdown under review. */
|
||||
plan: string
|
||||
/** The option that approves the plan. */
|
||||
approve: QuestionOption
|
||||
/** The option that declines it; absent when the asker offered no other option. */
|
||||
decline?: QuestionOption
|
||||
}
|
||||
|
||||
/**
|
||||
* Narrow a request to a renderable plan review, or return undefined to leave it
|
||||
* to the generic question flow.
|
||||
*
|
||||
* The card is one decision over one plan, so it claims a request only when the
|
||||
* batch is a single question that declares the intent, carries the plan as its
|
||||
* detail, and offers the approve label the intent names. The asker's own
|
||||
* service validates that label, but this is a wire boundary: a request failing
|
||||
* any part of it still renders and stays answerable as a generic question
|
||||
* rather than reaching a card that cannot express it.
|
||||
*
|
||||
* @param questions - the request's whole question batch.
|
||||
* @returns The narrowed review, or undefined when the generic flow owns it.
|
||||
*/
|
||||
export function planReviewOf(questions: readonly QuestionItem[]): PlanReview | undefined {
|
||||
if (questions.length !== 1) return undefined
|
||||
// Length-checked above; the index read is the narrowing tax, not a guess.
|
||||
const question = questions[0] as QuestionItem
|
||||
const intent = question.intent
|
||||
if (intent?.kind !== 'plan-review' || question.detail === undefined) return undefined
|
||||
const options = question.options ?? []
|
||||
const approve = options.find(option => option.label === intent.approve)
|
||||
if (approve === undefined) return undefined
|
||||
const decline = options.find(option => option.label !== intent.approve)
|
||||
return {
|
||||
id: question.id,
|
||||
question: question.question,
|
||||
plan: question.detail,
|
||||
approve,
|
||||
...(decline === undefined ? {} : { decline }),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Question domain face over the carrier: render identity and questions
|
||||
* transparently forwarded; answer/cancel own the wire encoding (the ok value
|
||||
|
||||
@@ -5,6 +5,12 @@
|
||||
* question carrier (matched prop), and the whole behavior surface rides the
|
||||
* carrier (domain encoding in contract/slots.ts PendingQuestion); copy rides
|
||||
* the standard locale seat. Export discipline: packages/client/AGENTS.md.
|
||||
*
|
||||
* One entry, two shapes: the composer renders a request that declares a
|
||||
* presentation intent as that intent's own surface (`plan-review` → the plan
|
||||
* decision card) and every other request as the generic question flow. A
|
||||
* separate chain entry per shape would race the same carrier, so the shape
|
||||
* choice lives inside this entry — see QuestionComposer.
|
||||
*/
|
||||
import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { ComposerChainProps } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
@@ -14,8 +20,10 @@ import type { QuestionWait } from './contract/slots.ts'
|
||||
import { QuestionComposer } from './QuestionComposer.tsx'
|
||||
import { en, zh, type QuestionKey } from './locales.ts'
|
||||
|
||||
export { PendingQuestion } from './contract/slots.ts'
|
||||
export type { QuestionAnswer, QuestionComposerProps, QuestionWait } from './contract/slots.ts'
|
||||
export { PendingQuestion, planReviewOf } from './contract/slots.ts'
|
||||
export type {
|
||||
PlanReview, QuestionAnswer, QuestionComposerProps, QuestionWait,
|
||||
} from './contract/slots.ts'
|
||||
export type { QuestionKey } from './locales.ts'
|
||||
|
||||
declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
|
||||
@@ -11,6 +11,10 @@ export const zh = {
|
||||
'custom.placeholder': '输入你的答案',
|
||||
'action.skip': '跳过本题',
|
||||
'action.next': '下一题',
|
||||
'plan.header': '计划待审',
|
||||
'plan.approve': '确认执行',
|
||||
'plan.decline': '拒绝',
|
||||
'plan.discuss': '去聊天里说',
|
||||
} satisfies Record<string, string>
|
||||
|
||||
/** The question namespace key union. */
|
||||
@@ -27,4 +31,8 @@ export const en = {
|
||||
'custom.placeholder': 'Type your answer',
|
||||
'action.skip': 'Skip this question',
|
||||
'action.next': 'Next',
|
||||
'plan.header': 'Plan review',
|
||||
'plan.approve': 'Approve',
|
||||
'plan.decline': 'Refuse',
|
||||
'plan.discuss': 'Chat about it',
|
||||
} satisfies Record<QuestionKey, string>
|
||||
|
||||
221
packages/client/ui-question/tests/plan-review-panel.spec.tsx
Normal file
221
packages/client/ui-question/tests/plan-review-panel.spec.tsx
Normal file
@@ -0,0 +1,221 @@
|
||||
// @vitest-environment jsdom
|
||||
// The plan-review takeover, driven through the composer entry that routes to
|
||||
// it: a request carrying the intent must reach the decision card and answer
|
||||
// with the asker's own option labels, and a request that does not (or cannot)
|
||||
// must keep the generic question flow.
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import type {
|
||||
ConversationSnapshot, SessionId, SessionListState, WorkspaceListState,
|
||||
} 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 { SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import { planReviewOf, type QuestionComposerProps, type QuestionWait } from '../src/client/contract/slots.ts'
|
||||
import { QuestionComposer } from '../src/client/QuestionComposer.tsx'
|
||||
import { en, zh } from '../src/client/locales.ts'
|
||||
import { en as commonEn } from '@deepseek-ai/dsh-client-locale/src/locales/en.ts'
|
||||
import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
const SID = 's1' as SessionId
|
||||
|
||||
/** Seat stub over a dictionary pair mirroring the real lookup chain: package dictionary, then common vocabulary, then the key. */
|
||||
const seatOver = (dict: Record<string, string>, common: Record<string, string>): QuestionComposerProps['t'] =>
|
||||
(key => dict[key] ?? common[key] ?? key)
|
||||
|
||||
/** Framework standard-kit stubs: the panel consumes only the locale seat. */
|
||||
const kit = {
|
||||
sessionId: SID,
|
||||
useSession: (() => { throw new Error('unused') }) as unknown as SnapshotSelectorHook<ConversationSnapshot>,
|
||||
useSessions: (() => { throw new Error('unused') }) as unknown as SnapshotSelectorHook<SessionListState>,
|
||||
useWorkspaces: (() => { throw new Error('unused') }) as unknown as SnapshotSelectorHook<WorkspaceListState>,
|
||||
useProjection: (() => undefined) as never,
|
||||
useInput: (() => { throw new Error('unused') }) as never,
|
||||
inputActions: { setDraft: () => { throw new Error('unused') }, submit: () => { throw new Error('unused') } } as never,
|
||||
t: seatOver(zh, commonZh),
|
||||
}
|
||||
|
||||
const PLAN = '# Ship the picker\n\n- read the store\n- render the rows\n'
|
||||
|
||||
/** The plan-mode request shape: one question, the plan as detail, approve named. */
|
||||
const questions = (): QuestionWait['payload']['questions'] => [{
|
||||
id: 'plan-review',
|
||||
header: 'Plan review',
|
||||
question: 'Approve this plan and leave plan mode?',
|
||||
detail: PLAN,
|
||||
options: [
|
||||
{ label: 'Approve', description: 'Leave plan mode; the plan is carried out from the next step.' },
|
||||
{ label: 'Keep planning', description: 'Stay in plan mode; feedback goes back to the model.' },
|
||||
],
|
||||
intent: { kind: 'plan-review', approve: 'Approve' },
|
||||
}]
|
||||
|
||||
/** Carrier fixture over a scripted respond carrier. */
|
||||
function wait(
|
||||
payload: QuestionWait['payload'] = { questions: questions() },
|
||||
respond = vi.fn(() => Promise.resolve<RpcReceipt>({ accepted: true })),
|
||||
) {
|
||||
return { carrier: new PendingWait('question', RpcId('q-1'), SID, payload, respond), respond }
|
||||
}
|
||||
|
||||
/** The client-response envelope respond must have received for a decision. */
|
||||
function decidedEnvelope(label: string) {
|
||||
return {
|
||||
type: 'client-response', rpcId: RpcId('q-1'),
|
||||
result: { ok: true, value: { sessionId: SID, answer: { answers: [{ id: 'plan-review', selected: [label] }] } } },
|
||||
}
|
||||
}
|
||||
|
||||
describe('planReviewOf', () => {
|
||||
it('narrows a plan-review request to its decision, options included', () => {
|
||||
expect(planReviewOf(questions())).toEqual({
|
||||
id: 'plan-review',
|
||||
question: 'Approve this plan and leave plan mode?',
|
||||
plan: PLAN,
|
||||
approve: { label: 'Approve', description: 'Leave plan mode; the plan is carried out from the next step.' },
|
||||
decline: { label: 'Keep planning', description: 'Stay in plan mode; feedback goes back to the model.' },
|
||||
})
|
||||
})
|
||||
|
||||
it('leaves the decline absent when the asker offered approve alone', () => {
|
||||
const [question] = questions()
|
||||
const review = planReviewOf([{ ...question as object, options: [{ label: 'Approve' }] } as never])
|
||||
expect(review?.approve).toEqual({ label: 'Approve' })
|
||||
expect(review === undefined ? true : 'decline' in review).toBe(false)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['a batch of more than one question', () => [...questions(), ...questions()]],
|
||||
['no intent at all', () => [{ ...questions()[0] as object, intent: undefined }]],
|
||||
['an intent without the plan as detail', () => [{ ...questions()[0] as object, detail: undefined }]],
|
||||
['an intent whose approve names no option', () => [{
|
||||
...questions()[0] as object, intent: { kind: 'plan-review', approve: 'Ship it' },
|
||||
}]],
|
||||
['an intent with no options at all', () => [{ ...questions()[0] as object, options: undefined }]],
|
||||
])('declines %s, leaving the request to the generic flow', (_case, build) => {
|
||||
expect(planReviewOf(build() as never)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('declines an empty batch, which the generic flow reports as such', () => {
|
||||
expect(planReviewOf([])).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('PlanReviewPanel', () => {
|
||||
it('renders the plan under a review strip, with none of the quiz affordances', () => {
|
||||
const { carrier } = wait()
|
||||
render(<QuestionComposer matched={carrier} interactions={[carrier]} {...kit} />)
|
||||
|
||||
expect(document.querySelector('[data-plan-review-key="q:q-1"]')).toBeTruthy()
|
||||
expect(screen.getByText(zh['plan.header'])).toBeTruthy()
|
||||
// The plan renders as markdown, so its heading is a heading.
|
||||
expect(screen.getByRole('heading', { name: 'Ship the picker' })).toBeTruthy()
|
||||
expect(screen.getByText('render the rows')).toBeTruthy()
|
||||
// The question text stays as the card's accessible name rather than a title
|
||||
// that reads like a test item.
|
||||
expect(screen.getByLabelText('Approve this plan and leave plan mode?')).toBeTruthy()
|
||||
// No pager, no numbered options, no skip, no custom answer.
|
||||
expect(screen.queryByText('1 / 1')).toBeNull()
|
||||
expect(screen.queryByRole('radio')).toBeNull()
|
||||
expect(screen.queryByText(zh['action.skip'])).toBeNull()
|
||||
expect(screen.queryByRole('textbox')).toBeNull()
|
||||
})
|
||||
|
||||
it('answers with the asker\'s approve label and keeps its description as the tooltip', () => {
|
||||
const { carrier, respond } = wait()
|
||||
render(<QuestionComposer matched={carrier} interactions={[carrier]} {...kit} />)
|
||||
|
||||
const approve = screen.getByRole('button', { name: zh['plan.approve'] })
|
||||
expect(approve.getAttribute('title')).toBe('Leave plan mode; the plan is carried out from the next step.')
|
||||
fireEvent.click(approve)
|
||||
expect(respond).toHaveBeenCalledWith(decidedEnvelope('Approve'))
|
||||
// One-shot: every action locks until the host's resolved frame lands.
|
||||
expect(approve.hasAttribute('disabled')).toBe(true)
|
||||
expect(screen.getByRole('button', { name: zh['plan.decline'] }).hasAttribute('disabled')).toBe(true)
|
||||
fireEvent.click(approve)
|
||||
expect(respond).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('answers with the asker\'s decline label', () => {
|
||||
const { carrier, respond } = wait()
|
||||
render(<QuestionComposer matched={carrier} interactions={[carrier]} {...kit} />)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: zh['plan.decline'] }))
|
||||
expect(respond).toHaveBeenCalledWith(decidedEnvelope('Keep planning'))
|
||||
})
|
||||
|
||||
it('dismisses the request so the composer returns for a plain message', () => {
|
||||
const { carrier, respond } = wait()
|
||||
render(<QuestionComposer matched={carrier} interactions={[carrier]} {...kit} />)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: zh['plan.discuss'] }))
|
||||
expect(respond).toHaveBeenCalledWith({
|
||||
type: 'client-response', rpcId: RpcId('q-1'),
|
||||
result: {
|
||||
ok: false,
|
||||
error: { code: 'cancelled', message: 'the user closed this question request', details: {} },
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('omits the tooltip for an option carrying no description', () => {
|
||||
const { carrier } = wait({ questions: [{
|
||||
...questions()[0] as object,
|
||||
options: [{ label: 'Approve' }, { label: 'Keep planning' }],
|
||||
}] as never })
|
||||
render(<QuestionComposer matched={carrier} interactions={[carrier]} {...kit} />)
|
||||
|
||||
expect(screen.getByRole('button', { name: zh['plan.approve'] }).hasAttribute('title')).toBe(false)
|
||||
expect(screen.getByRole('button', { name: zh['plan.decline'] }).hasAttribute('title')).toBe(false)
|
||||
})
|
||||
|
||||
it('hides the decline action when the asker offered approve alone', () => {
|
||||
const { carrier } = wait({ questions: [{
|
||||
...questions()[0] as object, options: [{ label: 'Approve' }],
|
||||
}] as never })
|
||||
render(<QuestionComposer matched={carrier} interactions={[carrier]} {...kit} />)
|
||||
|
||||
expect(screen.queryByRole('button', { name: zh['plan.decline'] })).toBeNull()
|
||||
expect(screen.getByRole('button', { name: zh['plan.approve'] })).toBeTruthy()
|
||||
})
|
||||
|
||||
it('re-arms the actions and says why when the decision does not land', async () => {
|
||||
const { carrier, respond } = wait(
|
||||
{ questions: questions() },
|
||||
vi.fn(() => Promise.resolve<RpcReceipt>({ accepted: false, reason: 'not-pending' })),
|
||||
)
|
||||
render(<QuestionComposer matched={carrier} interactions={[carrier]} {...kit} />)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: zh['plan.approve'] }))
|
||||
const failure = await screen.findByText('question response rejected: not-pending')
|
||||
expect(failure.getAttribute('role')).toBe('status')
|
||||
// Re-armed for the retry: a lost click must not leave a dead card.
|
||||
expect(screen.getByRole('button', { name: zh['plan.approve'] }).hasAttribute('disabled')).toBe(false)
|
||||
fireEvent.click(screen.getByRole('button', { name: zh['plan.approve'] }))
|
||||
expect(respond).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('reports a non-Error transport failure as its stringified value', async () => {
|
||||
// A non-Error rejection is the case under test: a carrier can reject with
|
||||
// anything, and the panel must still show the user something.
|
||||
// oxlint-disable-next-line typescript/prefer-promise-reject-errors
|
||||
const { carrier } = wait({ questions: questions() }, vi.fn(() => Promise.reject('socket gone')))
|
||||
render(<QuestionComposer matched={carrier} interactions={[carrier]} {...kit} />)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: zh['plan.discuss'] }))
|
||||
expect(await screen.findByText('socket gone')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('carries the same decision surface in English', () => {
|
||||
const { carrier } = wait()
|
||||
render(<QuestionComposer matched={carrier} interactions={[carrier]} {...kit} t={seatOver(en, commonEn)} />)
|
||||
|
||||
expect(screen.getByText('Plan review')).toBeTruthy()
|
||||
expect(screen.getByRole('button', { name: 'Approve' })).toBeTruthy()
|
||||
expect(screen.getByRole('button', { name: 'Refuse' })).toBeTruthy()
|
||||
expect(screen.getByRole('button', { name: 'Chat about it' })).toBeTruthy()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user