refactor(cua): own approval presentation and preserve shared UI defaults

This commit is contained in:
creatixchu committed 2026-10-17 17:12:49 +08:00
1 parent 72047d6ecd
commit b4d5ccc416
37 files changed
+237 -143

No files matched your search

+11
View File
@@ -112,6 +112,17 @@ describe.each(MODE === 'record' ? ['button'] as const : ['button', 'keyboard'] a
await panel.waitFor({ timeout: MODE === 'record' ? 180_000 : 60_000 })
const scroll = panel.locator('[data-approval-scroll]')
await expect.poll(() => scroll.getByText(/tok/).count(), { timeout: 15_000 }).toBeGreaterThan(0)
const defaults = await panel.evaluate((root: HTMLElement) => {
const before = root.style.textAlign
root.style.textAlign = 'center'
try {
return {
alignment: getComputedStyle(root.querySelector('[data-approval-scroll]')!).textAlign,
wrapping: getComputedStyle(root.querySelector('button')!.parentElement!).flexWrap,
}
} finally { root.style.textAlign = before }
})
expect(defaults).toEqual({ alignment: 'center', wrapping: 'nowrap' })
if (MODE !== 'record') {
const snapshot = await captureStableAria(page, '[data-approval-key]', scaffold.workspaceCwd)
+8
View File
@@ -44,6 +44,14 @@ it.skipIf(process.platform !== 'darwin').each([undefined, 'minimal'] as const)('
expect(await card.textContent()).toContain('请切换到 PTC 模式')
expect(await card.textContent()).toContain('Windows 支持正在开发中')
expect(await card.textContent()).not.toContain('Swift')
const description = await card.getByRole('button', { name: '查看 Computer Use', exact: true }).evaluate((button) => {
const element = document.getElementById(button.getAttribute('aria-describedby')!)!
const style = getComputedStyle(element)
return { lines: style.webkitLineClamp, height: element.getBoundingClientRect().height,
lineHeight: Number.parseFloat(style.lineHeight) }
})
expect(description.lines).toBe('1')
expect(description.height).toBeLessThanOrEqual(description.lineHeight + 1)
const originalAgent = scaffold.ctx.agents.list()[0]!
const ptcAgent = (await scaffold.ctx.agents.create({
sessionId: SessionId('cua-existing-ptc'),
+3
View File
@@ -65,6 +65,9 @@ it.skipIf(process.platform !== 'darwin')('keeps system requests pending until fr
})])
expect(await approval.getByText('Fixture', { exact: true }).count()).toBe(1)
expect(await approval.getByRole('textbox').count()).toBe(0)
expect(await approval.locator('[data-approval-scroll]').evaluate(element => getComputedStyle(element).textAlign)).toBe('left')
expect(await approval.getByRole('button', { name: 'Always allow', exact: true })
.evaluate(button => getComputedStyle(button.parentElement!).flexWrap)).toBe('wrap')
await expect.poll(() => approval.locator('img').evaluate((image: HTMLImageElement) => image.naturalWidth)).toBe(1)
expect(await approval.getByText('/Applications/Fixture.app', { exact: true }).count()).toBe(0)
await compareOrRefreshGolden(fileURLToPath(new URL('./expected/cua-permissions/application-approval.expected.md', import.meta.url)),
+2 -2
View File
@@ -9,8 +9,8 @@
en: 88cceb3cf383248e
zh: 8e1d2627823b1ffc
/user-interaction/presentation-intent:
en: 6605b0582b4ecd5a
zh: 01491d5470146a74
en: 9aa9b7fb16455a6e
zh: d820978a3f652e92
/user-interaction/question-item:
en: 1ad4373e6fdfe4c7
zh: efb8d41ebe7224f8
+1 -1
View File
@@ -22,7 +22,7 @@ interface AskUserQuestionOption {
## Presentation intent
`AskUserQuestionIntent` changes presentation while preserving option labels and the caller’s decision policy. `plan-review` names the approve option and requires plan detail. `approval` requires one blocking question with detail and distinct reject, approve and optional always-allow labels covering exactly the offered options. It rejects multi-select and timed waits. An unrecognized intent remains a generic option list.
`AskUserQuestionIntent` changes presentation while preserving option labels and the caller’s decision policy. `plan-review` names the approve option and requires plan detail. `approval` requires one blocking question with detail and distinct reject, approve and optional always-allow labels covering exactly the offered options. It rejects multi-select and timed waits. The CUA frontend renders its fixed approvals through the existing composer chain; ordinary questions and plan review keep their existing renderers.
```ts type-equiv
/**
+1 -1
View File
@@ -22,7 +22,7 @@ interface AskUserQuestionOption {
## 呈现意图
`AskUserQuestionIntent` 改变呈现方式,保留选项标签和调用方的决策规则。`plan-review` 指定批准选项,并要求提供计划正文。`approval` 要求只有一个阻塞式问题,带有说明以及互不相同的拒绝、允许和可选的始终允许标签,完整对应已提供的选项,不支持多选或计时等待。未识别的意图仍显示为通用选项列表。
`AskUserQuestionIntent` 改变呈现方式,保留选项标签和调用方的决策规则。`plan-review` 指定批准选项,并要求提供计划正文。`approval` 要求只有一个阻塞式问题,带有说明以及互不相同的拒绝、允许和可选的始终允许标签,完整对应已提供的选项,不支持多选或计时等待。CUA 前端通过现有 composer 呈现自己的固定审批;普通问答和计划审阅继续使用原有呈现。
```ts type-equiv
/**
+2 -2
View File
@@ -21,8 +21,8 @@
en: adf7112e0691b89e
zh: 14eeddcff985119f
/deepseek-ai-dsh-client-ui-approval/known-limitations-and-deferred-work:
en: 96d9b96df10e88eb
zh: cdeab788ad08bb33
en: 23588a4cd32f363c
zh: 19402f024f0f926a
/deepseek-ai-dsh-client-ui-approval/known-limitations-and-deferred-work/dev-note:
en: e67f633dc6fe7773
zh: e88aeb617ffb74ea
+1 -1
View File
@@ -35,7 +35,7 @@ None; approval request and response rendering does not alter a model request.
<a id="known-limitations-and-deferred-work"></a>
- The shared `conversation.approval.card` Factory presents reject, allow and an optional always-allow action, with caller-owned scope, subject metadata and answer callbacks. Tool approvals retain their two outcomes. Application consent can reuse the card without adopting tool-approval policy. Icons and labels identify the subject visually; the caller owns identity verification and saved grants.
- The shared `conversation.approval.card` Factory presents reject, allow and an optional always-allow action, with caller-owned scope, subject metadata and answer callbacks. Tool approvals retain their two outcomes. Application consent can reuse the card without adopting tool-approval policy. Subject metadata enables left-aligned content and wrapping actions; callers that omit it retain inherited alignment and a single action row. Icons and labels identify the subject visually; the caller owns identity verification and saved grants.
<a id="dev-note"></a>
+1 -1
View File
@@ -35,7 +35,7 @@ kind: "package-reference"
<a id="known-limitations-and-deferred-work"></a>
- 共用的 `conversation.approval.card` Factory 展示拒绝、允许和可选的始终允许操作,授权范围、对象信息和回答回调由调用方提供。工具审批保留原来的两种选择。应用授权可以复用卡片,同时保留独立的授权规则。图标和名称用于识别对象,身份校验和授权保存由调用方负责。
- 共用的 `conversation.approval.card` Factory 展示拒绝、允许和可选的始终允许操作,授权范围、对象信息和回答回调由调用方提供。工具审批保留原来的两种选择。应用授权可以复用卡片,同时保留独立的授权规则。传入对象信息时,内容左对齐,按钮允许换行;未传入时沿用继承的对齐方式和单排按钮。图标和名称用于识别对象,身份校验和授权保存由调用方负责。
<a id="dev-note"></a>
@@ -55,7 +55,7 @@ function ApprovalFlow(props: FactoryComponentPropsOf<'conversation.approval.card
onKeyUpCapture={() => { compositionEnded.current = false }}
onCompositionStartCapture={() => { composing.current = true }}
onCompositionEndCapture={() => { composing.current = false; compositionEnded.current = true }}>
<div className={css.card}>
<div className={subject === undefined ? css.card : `${css.card} ${css.withSubject}`}>
<div className={css.strip}><StateDot state={answered ? 'ongoing' : 'warning'} />{t('waiting')}</div>
<div
className={css.body}
@@ -34,7 +34,6 @@
gap: 6px;
box-sizing: border-box;
max-height: var(--dsh-composer-text-max-height);
text-align: left;
overflow-y: auto;
padding: 12px 16px 0;
}
@@ -57,7 +56,6 @@
.actionRow {
display: flex;
justify-content: flex-end;
flex-wrap: wrap;
gap: 8px;
padding: 14px 16px;
}
@@ -87,3 +85,6 @@
font-size: 13px;
line-height: 20px;
}
.withSubject .body { text-align: left; }
.withSubject .actionRow { flex-wrap: wrap; }
@@ -346,13 +346,12 @@
}
.cardDesc {
min-height: 2lh;
font-size: 13px;
line-height: 18px;
color: var(--dsw-alias-label-tertiary);
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
-webkit-line-clamp: 1;
overflow: hidden;
}
@@ -12,8 +12,8 @@
en: 1aa6291852d48a08
zh: 414eed268fb2cf1f
/deepseek-ai-dsh-client-ui-user-questions/table-of-contents:
en: 9a599485cc9f47b9
zh: 17a17d7a943fb1b7
en: d152484eb41ac6b4
zh: 09388d293f9be9cb
/deepseek-ai-dsh-client-ui-user-questions/use-this-package:
en: 8d3815c19858ac85
zh: 94fc905fa202d334
@@ -21,8 +21,8 @@
en: cc19c065d0aeac1e
zh: 91c8cbe08b438e7f
/deepseek-ai-dsh-client-ui-user-questions/use-this-package/reading-a-settled-question-back:
en: 10975f68ff9c6fcc
zh: 92246aadc363f0eb
en: 8e8449ab411b9916
zh: 0129d68b84458e8e
/deepseek-ai-dsh-client-ui-user-questions/use-this-package/the-plan-review-card:
en: 6b12f1362c614a39
zh: 27d9cf54d4cbd5d2
+2 -2
View File
@@ -20,8 +20,6 @@ The Web client shows an agent's question beside the chat input. Users choose opt
- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
- [Dev Note](#dev-note)
An `approval` intent reuses the shared approval card for fixed choices. It displays caller-supplied subject metadata and localized copy, with no text field or question pager; the existing question channel still delivers the selected label.
-----
<a id="use-this-package"></a>
@@ -39,6 +37,8 @@ Each late reply is shown once, including when it opens a new Turn. Replies follo
A question that already settled opens as a read-only card: the same pager over the recorded answers, marked `Answered`. Every option and text field is disabled, Skip and the submit action are gone, a question the user skipped says so in place of its empty answer, and a free-text field appears only where the recorded answer used one. Closing it removes the card, and the tool call row builds another from the same record.
Fixed approval questions use the same pending-question and answer channel. Their feature plugin supplies the composer presentation; the generic question form leaves these requests to that contribution.
### The plan-review card
A `plan-review` intent — set by `dsh-plan-mode` on the `exit_plan_mode` review — renders a compact approval card: a `Plan review` strip with a `View full plan` link, the plan title and a two-line plain-text summary, and `Request changes` / `Approve` actions. The strip uses the shared warning dot and changes it to the ongoing loader while either action settles. The complete plan opens in the sidebar through the link or its permanent Chat card. Approve answers with the asker's approval label; `Request changes` rejects the wait as `ASK_CANCELLED`, returning the composer for the user's feedback without submitting an approval. The card has no separate refusal button.
@@ -20,8 +20,6 @@ Web 客户端在聊天输入框旁显示 agent(智能体)的提问。用户
- [已知限制与延期工作](#known-limitations-and-deferred-work)
- [开发备注](#dev-note)
`approval` 意图复用共用审批卡片展示固定选项,显示调用方提供的对象信息和本地化文案,不提供文本输入或问题翻页,仍通过现有问答通道返回选中的标签。
-----
<a id="use-this-package"></a>
@@ -39,6 +37,8 @@ Web 客户端在聊天输入框旁显示 agent(智能体)的提问。用户
已经结束的问题以只读卡片打开:同一个翻页器走过已记录的回答,并标注「已回答」。所有选项与文本框都被禁用,跳过与提交动作消失,用户当时跳过的问题会在空回答处说明这一点,自由文本框只出现在当时确实用过它的回答上。关闭它会移除该卡片,工具调用行会用同一份记录再建一个。
固定审批问题沿用同一个待答问题和回答通道,由功能插件提供 composer 呈现;通用问答表单将这类请求留给该呈现处理。
### plan-review 卡片
`plan-review` 意图——由 `dsh-plan-mode` 在 `exit_plan_mode` 审阅上设置——渲染紧凑审批卡片:顶部为带“查看全文”链接的“计划待审”条带,正文显示计划标题和两行纯文本摘要,底部提供“要求修改”和“同意执行”。条带使用共享 warning 状态点,并在任一操作结算期间切换为 ongoing loading。通过链接或聊天历史中的常驻卡片可在侧边栏阅读完整计划。“同意执行”用提问方的批准标签回答;“要求修改”以 `ASK_CANCELLED` 拒绝等待,让编辑器归位供用户输入反馈,不会提交批准。卡片不单列拒绝按钮。
@@ -35,8 +35,7 @@
"@deepseek-ai/dsh-client-ui-conversation",
"@deepseek-ai/dsh-client-ui-renderer",
"@deepseek-ai/dsh-client-ui-session",
"@deepseek-ai/dsh-client-ui-chat",
"@deepseek-ai/dsh-client-ui-approval"
"@deepseek-ai/dsh-client-ui-chat"
],
"platform": "web"
}
@@ -72,8 +71,7 @@
"clsx": "^2.0.0",
"@deepseek-ai/dsh-llm": "workspace:*",
"@deepseek-ai/dsh-client-ui-chat": "workspace:*",
"@deepseek-ai/dsh-client-ui-tool": "workspace:*",
"@deepseek-ai/dsh-client-ui-approval": "workspace:*"
"@deepseek-ai/dsh-client-ui-tool": "workspace:*"
},
"files": [
"locale/*.json",
@@ -1,31 +0,0 @@
/** Fixed-action question presentation using the shared approval card. */
import type { AskUserQuestionItem, AskUserQuestionIntent } from '@deepseek-ai/dsh-user-questions/types'
import type {} from '@deepseek-ai/dsh-client-ui-approval/client'
import type { QuestionComposerProps } from './contract/slots.ts'
/**
* Keep the question answer channel while rendering permission choices without a text field.
* @param props Blocking question, its approval presentation and renderer bindings.
* @returns The shared approval card with exactly the caller's offered actions.
*/
export function QuestionApproval(props: QuestionComposerProps & {
item: AskUserQuestionItem
intent: Extract<AskUserQuestionIntent, { kind: 'approval' }>
}) {
const { matched: pending, item, intent, resolveText } = props
const always = intent.always
const answer = (label: string) => pending.answer({ answers: [{ id: item.id, selected: [label] }] })
return props.renderFactorySlot('conversation.approval.card', {
requestKey: pending.key,
title: intent.display === undefined ? item.question : resolveText(intent.display.question),
...(item.detail === undefined ? {} : {
description: intent.display?.detail === undefined ? item.detail : resolveText(intent.display.detail),
}),
...(intent.subject === undefined ? {} : { subject: intent.subject }),
allowLabel: intent.display?.approve === undefined ? intent.approve : resolveText(intent.display.approve),
canAnswer: () => pending.snapshot().channel !== 'none' && !pending.snapshot().closed,
onAllow: () => answer(intent.approve),
onReject: () => answer(intent.reject),
...(always === undefined ? {} : { onAlways: () => answer(always) }),
})
}
@@ -11,7 +11,6 @@ import {
import { planReviewOf, type QuestionAnswer, type QuestionCardSnapshot, type QuestionComposerProps } from './contract/slots.ts'
import type { PendingQuestion } from './contract/slots.ts'
import type { QuestionDraftAnswer, QuestionDraftProgress } from './draft-store.ts'
import { QuestionApproval } from './QuestionApproval.tsx'
import { PlanReviewPanel } from './PlanReviewPanel.tsx'
import css from './QuestionComposer.module.css'
@@ -140,8 +139,6 @@ function AnswerField(props: AnswerFieldProps) {
export function QuestionComposer(props: QuestionComposerProps) {
const question = props.matched
const review = useMemo(() => planReviewOf(question.questions), [question])
const item = question.questions[0]
if (item?.intent?.kind === 'approval') return <QuestionApproval {...props} item={item} intent={item.intent} />
return review === undefined
? (
<QuestionFlow
@@ -1,5 +1,5 @@
/** Question composer props and one pending Remote waterfall response. */
import type { InjectFace, PropsLocale, PropsRenderFactories, PropsRenderSlots, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots'
import type { InjectFace, PropsLocale, PropsRenderSlots, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots'
// The client module declares the conversation.composer SlotMap entry required by PropsRuntime.
import type { ToolCallId } from '@deepseek-ai/dsh-llm/brand'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
@@ -569,8 +569,6 @@ export type QuestionComposerProps =
PropsRuntime<'conversation.composer'>
& PropsStore<ReturnType<typeof createQuestionDraftStore>>
& PropsRenderSlots<'conversation.plan-review.actions'>
& PropsRenderFactories
& { resolveText: (text: { en: string; [locale: string]: string }) => string }
& InjectFace<{ keyedHooks: { questionCard: (key: string) => PendingQuestion | undefined } }>
& { matched: QuestionWait }
& PropsLocale<'question'>
@@ -15,7 +15,6 @@ import type { InboxWireState } from '@deepseek-ai/dsh-agent/types'
import type {} from '@deepseek-ai/dsh-api-remotes/client'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import type {} from '@deepseek-ai/dsh-client-ui-chat/client'
import type {} from '@deepseek-ai/dsh-client-ui-approval/client'
import type { ComposerChainProps } from '@deepseek-ai/dsh-client-ui-conversation/client'
import type {} from '@deepseek-ai/dsh-client-ui-renderer/client'
import type { PendingInteractionPublisher } from '@deepseek-ai/dsh-client-ui-session/client'
@@ -384,12 +383,11 @@ export function apply(ctx: ClientContext): void {
{
name: 'conversation.composer',
select: ({ pendingInteraction }: ComposerChainProps): PendingQuestion | null =>
pendingInteraction instanceof PendingQuestion ? pendingInteraction : null,
pendingInteraction instanceof PendingQuestion && pendingInteraction.questions[0]?.intent?.kind !== 'approval'
? pendingInteraction : null,
locale: NS,
store: questionDraftStore,
inject: () => ({ keyedHooks: { questionCard: (key: string) => cards.source(key) },
resolveText: (text: { en: string; [locale: string]: string }) => ctx.locale.resolveText(text),
}),
inject: () => ({ keyedHooks: { questionCard: (key: string) => cards.source(key) } }),
children: { 'conversation.plan-review.actions': { kind: 'list', scope: 'session' } },
},
QuestionComposer,
@@ -370,14 +370,7 @@ describe('apply', () => {
const store = entry.store as ReturnType<typeof createQuestionDraftStore>
expect(store.create(SESSION_ID).getSnapshot()).toEqual({ progressByRequest: {} })
const pending = b.pending.getSnapshot()[0]!
const face = (entry.inject as () => {
keyedHooks: { questionCard: (key: string) => PendingQuestion | undefined }
resolveText: (text: { en: string; zh: string }) => string
})()
b.locale.setLocale('zh')
expect(face.resolveText({ en: 'Allow for this session', zh: '本会话允许' })).toBe('本会话允许')
b.locale.setLocale('en')
expect(face.resolveText({ en: 'Allow for this session', zh: '本会话允许' })).toBe('Allow for this session')
const face = (entry.inject as () => { keyedHooks: { questionCard: (key: string) => PendingQuestion | undefined } })()
expect(face.keyedHooks.questionCard(pending.key)).toBe(pending)
expect(face.keyedHooks.questionCard('question:missing')).toBeUndefined()
const select = entry.select as (
@@ -385,6 +378,9 @@ describe('apply', () => {
) => PendingQuestion | null
expect(select({ pendingInteraction: undefined })).toBeNull()
expect(select({ pendingInteraction: pending })).toBe(pending)
expect(select({ pendingInteraction: new PendingQuestion(SESSION_ID, PLAN_QUESTIONS) })?.kind).toBe('plan-review')
expect(select({ pendingInteraction: new PendingQuestion(SESSION_ID, [{ id: 'cua-app-access', question: 'Allow?',
intent: { kind: 'approval', approve: 'Allow', reject: 'Deny' } }]) })).toBeNull()
expect(pending).toMatchObject({ kind: 'question', sessionId: SESSION_ID, questions: QUESTIONS, callId: undefined })
expect(pending.snapshot()).toEqual({
state: 'open', waitState: 'counting', countdown: undefined,
@@ -114,8 +114,6 @@ const questionDraftStore = createQuestionDraftStore().create(SID)
const kit: Omit<QuestionComposerProps, 'matched'> = {
useQuestionCard: () => { throw new Error('plan review does not read question card state') },
renderSlot: () => null,
renderFactorySlot: () => null,
resolveText: text => text.en,
SessionProvider: ({ children }) => children,
sessionId: SID,
session: undefined,
@@ -1,50 +0,0 @@
// @vitest-environment jsdom
/** Fixed decisions retain the caller's answer labels and pending-question lifetime. */
import { cleanup, render } from '@testing-library/react'
import { afterEach, expect, it, vi } from 'vitest'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import type { AskUserQuestionItem, AskUserQuestionIntent } from '@deepseek-ai/dsh-user-questions/types'
import type { ApprovalCardInput } from '@deepseek-ai/dsh-client-ui-approval/client'
import { PendingQuestion, createWaterfallRequest, type QuestionComposerProps } from '../src/client/contract/slots.ts'
import { QuestionComposer } from '../src/client/QuestionComposer.tsx'
afterEach(cleanup)
it.each(['allow', 'reject', 'always'] as const)('returns the exact %s option from the shared card', async (choice) => {
const intent: Extract<AskUserQuestionIntent, { kind: 'approval' }> = {
kind: 'approval', approve: 'task-value', reject: 'deny-value', always: 'saved-value',
subject: { name: 'Calculator' }, display: { question: { en: 'Allow?', zh: '允许吗?' },
detail: { en: 'Scope', zh: '本次任务' }, approve: { en: 'Task', zh: '本次任务允许' } },
}
const item: AskUserQuestionItem = { id: 'access', question: 'English question', detail: 'English detail', intent }
const pending = new PendingQuestion('s1' as SessionId, [item])
const request = createWaterfallRequest(undefined, undefined, () => {})
pending.attachWaterfall(request.channel)
const factory = vi.fn((_name: string, _input: ApprovalCardInput) => null)
render(<QuestionComposer {...{ matched: pending, renderFactorySlot: factory,
resolveText: text => text.zh ?? text.en } as QuestionComposerProps} />)
const [name, card] = factory.mock.calls[0]!
expect(name).toBe('conversation.approval.card')
expect(card).toMatchObject({ title: '允许吗?', description: '本次任务', allowLabel: '本次任务允许', subject: { name: 'Calculator' } })
expect(card.canAnswer()).toBe(true)
await ({ allow: card.onAllow, reject: card.onReject, always: card.onAlways! })[choice]()
expect(await request.result).toEqual({ answers: [{ id: 'access', selected: [{ allow: 'task-value', reject: 'deny-value', always: 'saved-value' }[choice]] }] })
pending.close()
expect(card.canAnswer()).toBe(false)
})
it('keeps unsupported persistence absent and uses caller text when no localized metadata exists', () => {
const item: AskUserQuestionItem = { id: 'access', question: 'Allow?',
intent: { kind: 'approval', approve: 'Task', reject: 'Deny' } }
const pending = new PendingQuestion('s1' as SessionId, [item])
const factory = vi.fn((_name: string, _input: ApprovalCardInput) => null)
const props = { matched: pending, renderFactorySlot: factory, resolveText: text => text.en } as QuestionComposerProps
const view = render(<QuestionComposer {...props} />)
expect(factory.mock.calls[0]?.[1]).toMatchObject({ title: 'Allow?', allowLabel: 'Task' })
expect(factory.mock.calls[0]?.[1]).not.toHaveProperty('onAlways')
expect(factory.mock.calls[0]?.[1]).not.toHaveProperty('subject')
expect(factory.mock.calls[0]?.[1]).not.toHaveProperty('description')
expect(factory.mock.calls[0]?.[1].canAnswer()).toBe(false)
view.rerender(<QuestionComposer {...props} matched={new PendingQuestion('s1' as SessionId, [{ ...item, detail: 'Scope' }])} />)
expect(factory.mock.calls.at(-1)?.[1].description).toBe('Scope')
})
@@ -113,8 +113,6 @@ const inputState: InputState = {
* plain stubs per the client testing discipline). */
const kitBase: Omit<QuestionComposerProps, 'matched' | 'useStore' | 'useQuestionCard' | 'actions'> = {
renderSlot: () => null,
renderFactorySlot: () => null,
resolveText: text => text.en,
SessionProvider: ({ children }) => children,
session: undefined,
sessionId: SID,
@@ -58,9 +58,6 @@
},
{
"path": "../../util/brand"
},
{
"path": "../ui-approval"
}
]
}
@@ -12,8 +12,8 @@
en: 4e62e511b5d14986
zh: 1fce04dbad7515f7
/deepseek-ai-dsh-client-ui-cua/table-of-contents:
en: c606f8af967e93e9
zh: c569e0decbd74353
en: 1a1d0bf8154bf602
zh: c6d8b33e1bac3206
/deepseek-ai-dsh-client-ui-cua/use-this-package:
en: ecf4a8b23d6f976d
zh: 46793f29118b4eff
@@ -20,7 +20,7 @@ Open Computer Use in Plugins to check Accessibility and Screen Recording, reques
- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
- [Dev Note](#dev-note)
Application permission prompts and permission-page lists show native icons and application names. Paths remain available on hover. Icons are presentation metadata and are never saved with grants. The prompt offers session access, refusal and, for verifiable applications with writable settings, persistent access through the shared approval card.
Application permission prompts and permission-page lists show native icons and application names. Paths remain available on hover. Icons are presentation metadata and are never saved with grants. This plugin registers the application-approval presentation in the existing composer chain and reuses the shared approval card. The pending question still owns waiting, cancellation and answers. The prompt offers session access, refusal and, for verifiable applications with writable settings, persistent access.
-----
@@ -20,7 +20,7 @@ kind: "package-reference"
- [已知限制与后续工作](#known-limitations-and-deferred-work)
- [开发备注](#dev-note)
应用授权提示和权限页列表显示本机图标与应用名称,悬停可查看列表中的路径。图标仅用于展示,不随授权保存。提示复用共用审批卡片,提供本会话允许和拒绝;应用签名可验证且配置可写时,还提供始终允许。
应用授权提示和权限页列表显示本机图标与应用名称,悬停可查看列表中的路径。图标仅用于展示,不随授权保存。本插件通过现有 composer 注册应用审批呈现,复用共用审批卡片,等待、取消和回答仍由原待答问题负责。提示提供本会话允许和拒绝;应用签名可验证且配置可写时,还提供始终允许。
-----
@@ -32,7 +32,10 @@
"@deepseek-ai/dsh-client-locale",
"@deepseek-ai/dsh-client-ui-plugin-manager",
"@deepseek-ai/dsh-client-ui-settings",
"@deepseek-ai/dsh-client-ui-layout"
"@deepseek-ai/dsh-client-ui-layout",
"@deepseek-ai/dsh-client-ui-user-questions",
"@deepseek-ai/dsh-client-ui-approval",
"@deepseek-ai/dsh-client-ui-conversation"
],
"platform": "web"
}
@@ -62,7 +65,10 @@
"react": "^18.2.0",
"react-dom": "^18.2.0",
"@testing-library/react": "^16.1.0",
"@deepseek-ai/dsh-typert-protocol": "workspace:*"
"@deepseek-ai/dsh-typert-protocol": "workspace:*",
"@deepseek-ai/dsh-client-ui-user-questions": "workspace:*",
"@deepseek-ai/dsh-client-ui-approval": "workspace:*",
"@deepseek-ai/dsh-client-ui-conversation": "workspace:*"
},
"files": [
"lib/index.js",
@@ -0,0 +1,46 @@
/** Computer Use presentation over the existing pending-question answer channel. */
import type { PropsRenderFactories, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
import type { ComposerChainProps } from '@deepseek-ai/dsh-client-ui-conversation/client'
import type {} from '@deepseek-ai/dsh-client-ui-user-questions/client'
import type {} from '@deepseek-ai/dsh-client-ui-approval/client'
/**
* Select only the provider's fixed application question; other interactions keep their renderer.
* @param pending The session's currently elected interaction.
* @returns Its application decision, or null for another interaction.
*/
export function selectApplicationApproval(pending: ComposerChainProps['pendingInteraction']) {
if (pending?.kind !== 'question' || pending.questions.length !== 1) return null
const item = pending.questions[0] as (typeof pending.questions)[number]
if (item.id !== 'cua-app-access' || item.intent?.kind !== 'approval') return null
return { pending, item, intent: item.intent }
}
/** Composer bindings for an application decision and caller-owned localized copy. */
export type ApplicationApprovalProps = PropsRuntime<'conversation.composer'> & PropsRenderFactories & {
matched: NonNullable<ReturnType<typeof selectApplicationApproval>>
resolveText: (text: { en: string; [locale: string]: string }) => string
}
/**
* Render the shared approval card without creating another request or answer lifetime.
* @param props The existing pending question and renderer bindings.
* @returns Fixed actions with the provider's original answer labels.
*/
export function ApplicationApproval({ matched: { pending, item, intent }, resolveText, renderFactorySlot }: ApplicationApprovalProps) {
const always = intent.always
const answer = (label: string) => pending.answer({ answers: [{ id: item.id, selected: [label] }] })
return renderFactorySlot('conversation.approval.card', {
requestKey: pending.key,
title: intent.display === undefined ? item.question : resolveText(intent.display.question),
...(item.detail === undefined ? {} : {
description: intent.display?.detail === undefined ? item.detail : resolveText(intent.display.detail),
}),
...(intent.subject === undefined ? {} : { subject: intent.subject }),
allowLabel: intent.display?.approve === undefined ? intent.approve : resolveText(intent.display.approve),
canAnswer: () => pending.snapshot().channel !== 'none' && !pending.snapshot().closed,
onAllow: () => answer(intent.approve),
onReject: () => answer(intent.reject),
...(always === undefined ? {} : { onAlways: () => answer(always) }),
})
}
@@ -8,7 +8,9 @@ import type {} from '@deepseek-ai/dsh-client-ui-renderer/client'
import type {} from '@deepseek-ai/dsh-client-ui-layout/client'
import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client'
import type {} from '@deepseek-ai/dsh-client-ui-settings/client'
import type { ComposerChainProps } from '@deepseek-ai/dsh-client-ui-conversation/client'
import { PermissionController } from './controller.ts'
import { ApplicationApproval, selectApplicationApproval } from './ApplicationApproval.tsx'
import { PermissionPanel, PermissionSetup, PermissionToast } from './PermissionPanel.tsx'
import { en, NS, zh, type CuaPermissionLocaleKey } from './locales.ts'
@@ -52,6 +54,11 @@ export async function mountCuaPermissions(ctx: Context, contribution: TypertRemo
retryApproval: async (id) => { const result = await ctx.remote.cuaAccess.retryApproval(id); if (!result.ok) throw result.error },
})
const face = controller.face()
ctx.slots.inject('conversation.composer', () => ctx.slots.register({
name: 'conversation.composer', priority: -1, locale: NS,
select: ({ pendingInteraction }: ComposerChainProps) => selectApplicationApproval(pendingInteraction),
inject: () => ({ resolveText: (text: { en: string; [locale: string]: string }) => ctx.locale.resolveText(text) }),
}, ApplicationApproval))
const preset = ctx.configForms.get<{ default: string; selectedDefault?: string }>('agent-preset-registry')
const settings = {
...face,
@@ -0,0 +1,83 @@
// @vitest-environment jsdom
/** Fixed decisions retain the caller's answer labels and pending-question lifetime. */
import { cleanup, render } from '@testing-library/react'
import { afterEach, expect, it, vi } from 'vitest'
import type { ApprovalCardInput } from '@deepseek-ai/dsh-client-ui-approval/client'
import { PendingQuestion, createWaterfallRequest } from '../../../client/ui-user-questions/src/client/contract/slots.ts'
import { ApplicationApproval, selectApplicationApproval, type ApplicationApprovalProps } from '../src/client/ApplicationApproval.tsx'
type AskUserQuestionItem = PendingQuestion['questions'][number]
type ApprovalIntent = Extract<NonNullable<AskUserQuestionItem['intent']>, { kind: 'approval' }>
type SessionId = ConstructorParameters<typeof PendingQuestion>[0]
afterEach(cleanup)
it('leaves ordinary questions, plan reviews and other approval intents to their existing renderers', () => {
const application: AskUserQuestionItem = { id: 'cua-app-access', question: 'Allow?', detail: 'Scope',
options: [{ label: 'Allow' }, { label: 'Deny' }], intent: { kind: 'approval', approve: 'Allow', reject: 'Deny' } }
expect(selectApplicationApproval(undefined)).toBeNull()
for (const questions of [[], [application, application], [{ ...application, id: 'another-feature' }],
[{ id: 'cua-app-access', question: 'Plain question' }],
[{ ...application, intent: { kind: 'plan-review' as const, approve: 'Allow' } }],
]) {
expect(selectApplicationApproval(new PendingQuestion('s1' as SessionId, questions))).toBeNull()
}
})
it.each(['allow', 'reject', 'always'] as const)('returns the exact %s option from the shared card', async (choice) => {
const intent: ApprovalIntent = {
kind: 'approval', approve: 'task-value', reject: 'deny-value', always: 'saved-value',
subject: { name: 'Calculator' }, display: { question: { en: 'Allow?', zh: '允许吗?' },
detail: { en: 'Scope', zh: '本次任务' }, approve: { en: 'Task', zh: '本次任务允许' } },
}
const item: AskUserQuestionItem = { id: 'cua-app-access', question: 'English question', detail: 'English detail', intent }
const pending = new PendingQuestion('s1' as SessionId, [item])
const request = createWaterfallRequest(undefined, undefined, () => {})
pending.attachWaterfall(request.channel)
const factory = vi.fn((_name: string, _input: ApprovalCardInput) => null)
render(<ApplicationApproval {...{ matched: selectApplicationApproval(pending)!, renderFactorySlot: factory,
resolveText: text => text.zh ?? text.en } as ApplicationApprovalProps} />)
const [name, card] = factory.mock.calls[0]!
expect(name).toBe('conversation.approval.card')
expect(card).toMatchObject({ title: '允许吗?', description: '本次任务', allowLabel: '本次任务允许', subject: { name: 'Calculator' } })
expect(card.canAnswer()).toBe(true)
await ({ allow: card.onAllow, reject: card.onReject, always: card.onAlways! })[choice]()
expect(await request.result).toEqual({ answers: [{ id: 'cua-app-access', selected: [{ allow: 'task-value', reject: 'deny-value', always: 'saved-value' }[choice]] }] })
pending.close()
expect(card.canAnswer()).toBe(false)
})
it('keeps unsupported persistence absent and uses caller text when no localized metadata exists', () => {
const item: AskUserQuestionItem = { id: 'cua-app-access', question: 'Allow?',
intent: { kind: 'approval', approve: 'Task', reject: 'Deny' } }
const pending = new PendingQuestion('s1' as SessionId, [item])
const factory = vi.fn((_name: string, _input: ApprovalCardInput) => null)
const props = { matched: selectApplicationApproval(pending)!, renderFactorySlot: factory,
resolveText: text => text.en } as ApplicationApprovalProps
const view = render(<ApplicationApproval {...props} />)
expect(factory.mock.calls[0]?.[1]).toMatchObject({ title: 'Allow?', allowLabel: 'Task' })
expect(factory.mock.calls[0]?.[1]).not.toHaveProperty('onAlways')
expect(factory.mock.calls[0]?.[1]).not.toHaveProperty('subject')
expect(factory.mock.calls[0]?.[1]).not.toHaveProperty('description')
expect(factory.mock.calls[0]?.[1].canAnswer()).toBe(false)
const detailed = new PendingQuestion('s1' as SessionId, [{ ...item, detail: 'Scope' }])
view.rerender(<ApplicationApproval {...props} matched={selectApplicationApproval(detailed)!} />)
expect(factory.mock.calls.at(-1)?.[1].description).toBe('Scope')
})
it('uses the original question cancellation and refuses late approval', async () => {
const pending = new PendingQuestion('s1' as SessionId, [{ id: 'cua-app-access', question: 'Allow?',
intent: { kind: 'approval', approve: 'Allow', reject: 'Deny' } }])
const controller = new AbortController()
const request = createWaterfallRequest(undefined, controller.signal, channel => pending.detachWaterfall(channel))
pending.attachWaterfall(request.channel)
const factory = vi.fn((_name: string, _input: ApprovalCardInput) => null)
render(<ApplicationApproval {...{ matched: selectApplicationApproval(pending)!, renderFactorySlot: factory,
resolveText: text => text.en } as ApplicationApprovalProps} />)
const card = factory.mock.calls[0]![1]
const rejected = expect(request.result).rejects.toMatchObject({ code: 'ASK_ABORTED' })
controller.abort()
await rejected
expect(card.canAnswer()).toBe(false)
await expect(card.onAllow()).rejects.toThrow('no channel accepts an answer yet')
})
@@ -59,6 +59,7 @@ async function fixture(fail = false) {
ctx.slots.register({ name: 'root', children: {
'plugins.bundle.activation': { kind: 'keyed', scope: 'root' },
'plugins.bundle.config': { kind: 'keyed', scope: 'root' }, 'shell.overlay': { kind: 'list', scope: 'root' },
'conversation.composer': { kind: 'chain', scope: 'session' },
} } as never, () => null)
if (fail) vi.spyOn(ctx.slots, 'inject').mockImplementationOnce(() => { throw new Error('slot unavailable') })
return { ctx, unmount, unsubscribe, status, systemStatus, applicationIcons,
@@ -73,6 +74,12 @@ it('withdraws the permission Remote and all controls with the optional plugin',
try {
const fiber = f.ctx.plugin({ inject: [...inject], apply: ctx => mountCuaPermissions(ctx, contribution) })
await fiber
const approval = f.ctx.slots.entries('conversation.composer')[0]!
const select = approval.select as (owner: { pendingInteraction: undefined }) => unknown
expect(select({ pendingInteraction: undefined })).toBeNull()
const presentation = approval.inject!()
assert(typeof presentation.resolveText === 'function')
expect(presentation.resolveText({ en: 'Localized', zh: 'Localized' })).toBe('Localized')
const entry = f.ctx.slots.entries('plugins.bundle.config')[0]!
const actions = entry.inject!()
actionsOf(actions)
@@ -117,6 +124,7 @@ it('withdraws the permission Remote and all controls with the optional plugin',
await (settings.setPtcDefault as () => Promise<boolean>)()
expect(f.setDefault).toHaveBeenCalledExactlyOnceWith('selectedDefault', 'ptc')
await fiber.dispose()
expect(f.ctx.slots.entries('conversation.composer')).toHaveLength(0)
expect(f.ctx.slots.entries('plugins.bundle.config')).toHaveLength(0)
expect(f.ctx.slots.entries('shell.overlay')).toHaveLength(0)
expect(f.unsubscribe).toHaveBeenCalledOnce()
@@ -46,6 +46,15 @@
},
{
"path": "../../typert/protocol"
},
{
"path": "../../client/ui-user-questions/tsconfig.json"
},
{
"path": "../../client/ui-approval/tsconfig.json"
},
{
"path": "../../client/ui-conversation/tsconfig.client.json"
}
]
}
@@ -301,6 +301,12 @@ export class UserQuestionService extends TypertRemoteService {
: [intent.approve]
const options = question.options ?? []
if (labels.some(label => !options.some(option => option.label === label))) {
if (intent.kind === 'plan-review') {
throw new UserQuestionError(
`question ${question.id} declares intent ${intent.kind} whose approve label `
+ `${JSON.stringify(intent.approve)} names none of its options`,
'BAD_INTENT')
}
throw new UserQuestionError(`question ${question.id} declares intent ${intent.kind} with an unoffered action`, 'BAD_INTENT')
}
if (question.detail === undefined) {
@@ -309,7 +309,8 @@ describe('UserQuestionService', () => {
...(options === undefined ? {} : { options }),
intent: { kind: 'plan-review', approve: 'Ship it' },
}],
})).rejects.toMatchObject({ name: 'UserQuestionError', code: 'BAD_INTENT' })
})).rejects.toMatchObject({ name: 'UserQuestionError', code: 'BAD_INTENT',
message: 'question plan-review declares intent plan-review whose approve label "Ship it" names none of its options' })
}
expect(p.ask).not.toHaveBeenCalled()
})
@@ -328,7 +329,8 @@ describe('UserQuestionService', () => {
options: [{ label: 'Approve' }, { label: 'Keep planning' }],
intent: { kind: 'plan-review', approve: 'Approve' },
}],
})).rejects.toMatchObject({ name: 'UserQuestionError', code: 'BAD_INTENT' })
})).rejects.toMatchObject({ name: 'UserQuestionError', code: 'BAD_INTENT',
message: 'question plan-review declares intent plan-review without the detail it reviews' })
expect(p.ask).not.toHaveBeenCalled()
})
+9 -3
View File
@@ -6377,9 +6377,6 @@ importers:
'@deepseek-ai/dsh-client-store':
specifier: workspace:*
version: link:../store
'@deepseek-ai/dsh-client-ui-approval':
specifier: workspace:*
version: link:../ui-approval
'@deepseek-ai/dsh-client-ui-chat':
specifier: workspace:*
version: link:../ui-chat
@@ -8308,6 +8305,12 @@ importers:
'@deepseek-ai/dsh-client-test-runtime':
specifier: workspace:*
version: link:../../test-support/client-runtime
'@deepseek-ai/dsh-client-ui-approval':
specifier: workspace:*
version: link:../../client/ui-approval
'@deepseek-ai/dsh-client-ui-conversation':
specifier: workspace:*
version: link:../../client/ui-conversation
'@deepseek-ai/dsh-client-ui-layout':
specifier: workspace:*
version: link:../../client/ui-layout
@@ -8326,6 +8329,9 @@ importers:
'@deepseek-ai/dsh-client-ui-slots':
specifier: workspace:*
version: link:../../client/ui-slots
'@deepseek-ai/dsh-client-ui-user-questions':
specifier: workspace:*
version: link:../../client/ui-user-questions
'@deepseek-ai/dsh-cua':
specifier: workspace:*
version: link:../cua