Merge origin/master into xtr/agent-setup-hook

This commit is contained in:
_Kerman committed 2026-09-09 17:31:17 +08:00
commit 2f7a02022a
243 files changed
+3931 -2186

No files matched your search

+2 -1
View File
@@ -84,6 +84,7 @@
"@deepseek-ai/dsh-scope": "workspace:^",
"@deepseek-ai/dsh-api-session-controller": "workspace:^",
"@deepseek-ai/dsh-api-workspace-files": "workspace:^",
"zod": "^4.4.3"
"zod": "^4.4.3",
"@deepseek-ai/dsh-command-feedback": "workspace:^"
}
}
+3 -1
View File
@@ -9,6 +9,7 @@ import llmRemote from '@deepseek-ai/dsh-llm/remote'
import dynamicRemote from '@deepseek-ai/dsh-cordis-host-runner/remote'
import pluginInventoryRemote from '@deepseek-ai/dsh-host-plugin-inventory/remote'
import messageFeedbackRemote from '@deepseek-ai/dsh-message-feedback/remote'
import sessionFeedbackRemote from '@deepseek-ai/dsh-command-feedback/remote'
import fileUploadsRemote from '@deepseek-ai/dsh-client-file-upload/remote'
import sessionReferencesRemote from '@deepseek-ai/dsh-session-reference/remote'
import subagentsRemote from '@deepseek-ai/dsh-subagent/remote'
@@ -26,6 +27,7 @@ export type {} from '@deepseek-ai/dsh-goal/remote'
export type {} from '@deepseek-ai/dsh-llm/remote'
export type {} from '@deepseek-ai/dsh-host-plugin-inventory/remote'
export type {} from '@deepseek-ai/dsh-message-feedback/remote'
export type {} from '@deepseek-ai/dsh-command-feedback/remote'
export type {} from '@deepseek-ai/dsh-client-file-upload/remote'
export type {} from '@deepseek-ai/dsh-session-reference/remote'
export type {} from '@deepseek-ai/dsh-subagent/remote'
@@ -150,7 +152,7 @@ export async function apply(ctx: Context): Promise<() => Promise<void>> {
try {
for (const contribution of [
agentPresetsRemote, commandsRemote, settingsControllerRemote, goalsRemote, llmRemote, dynamicRemote,
pluginInventoryRemote, messageFeedbackRemote, fileUploadsRemote, sessionReferencesRemote,
pluginInventoryRemote, messageFeedbackRemote, sessionFeedbackRemote, fileUploadsRemote, sessionReferencesRemote,
subagentsRemote, sessionRemote, workspaceRemote, workspaceFilesRemote,
]) {
disposers.push(await ctx.remote.$mount(contribution))
@@ -79,6 +79,9 @@
},
{
"path": "../../typert/protocol"
},
{
"path": "../../feedback/command-feedback"
}
]
}
+3 -2
View File
@@ -315,8 +315,9 @@
- id: ui-goal
name: '@deepseek-ai/dsh-client-ui-goal'
# Per-message feedback: Like/Dislike plus an optional note in the
# assistant-message action strip, over the messageFeedback Remote.
# The feedback surface: Like/Dislike in the assistant-message action
# strip, the feedback dialog behind Dislike and /feedback with its
# acknowledgement toast, over the messageFeedback and sessionFeedback Remotes.
- id: ui-message-feedback
name: '@deepseek-ai/dsh-client-ui-message-feedback'
+2 -2
View File
@@ -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/README.md
README.md: 6bb433b8411fa9db3d6de981a24895e3c7b674c4
README.zh.md: c04292b86becba404e5dbb58ca924833ee88f58b
README.md: cf4b6aceb320d942d695fb1dce53c2e67e53a969
README.zh.md: 1f895de009e82688ede9b3a83807bae9689ccb80
+1 -1
View File
@@ -71,7 +71,7 @@ The kernel packages boot and serve the page; the UI feature packages present it.
| [`ui-settings-models/`](ui-settings-models/README.md) | Provides model-provider configuration and DeepSeek onboarding | — |
| [`ui-settings-plugin-inventory/`](ui-settings-plugin-inventory/README.md) | Contributes the read-only Host Loader inventory tab to Plugins settings | — |
| [`ui-deliverables/`](ui-deliverables/README.md) | Produces the produced-files turn tail and clickable final-response file references | — |
| [`ui-message-feedback/`](ui-message-feedback/README.md) | Contributes per-message feedback controls to the assistant-message action strip | — |
| [`ui-message-feedback/`](ui-message-feedback/README.md) | The feedback surface: per-message Like/Dislike in the assistant-message action strip, and the feedback dialog behind Dislike and `/feedback` | — |
| [`ui-directory-picker-browse/`](ui-directory-picker-browse/README.md) | In-app directory browsing surface for the workspace directory flow | — |
| [`ui-directory-picker-native/`](ui-directory-picker-native/README.md) | Native directory-picker surface driving the host's OS chooser | — |
| [`ui-open-in-app/`](ui-open-in-app/README.md) | Session-header split button opening the workspace directory in an installed application | — |
+1 -1
View File
@@ -71,7 +71,7 @@ kind: "package-group"
| [`ui-settings-models/`](ui-settings-models/README.zh.md) | 提供模型提供方配置与 DeepSeek 引导 | — |
| [`ui-settings-plugin-inventory/`](ui-settings-plugin-inventory/README.zh.md) | 向“插件”设置贡献只读的 Host Loader 清单标签页 | — |
| [`ui-deliverables/`](ui-deliverables/README.zh.md) | 生成已产出文件的轮次尾部与可点击的最终响应文件引用 | — |
| [`ui-message-feedback/`](ui-message-feedback/README.zh.md) | 向助手消息操作条贡献逐消息反馈控件 | — |
| [`ui-message-feedback/`](ui-message-feedback/README.zh.md) | 反馈界面:助手消息操作条中的逐消息赞踩,以及点踩与 `/feedback` 背后的反馈弹窗 | — |
| [`ui-directory-picker-browse/`](ui-directory-picker-browse/README.zh.md) | 面向工作区目录流程的应用内目录浏览界面 | — |
| [`ui-directory-picker-native/`](ui-directory-picker-native/README.zh.md) | 驱动宿主 OS 选择器的原生目录选择界面 | — |
| [`ui-open-in-app/`](ui-open-in-app/README.zh.md) | 在已安装应用中打开 workspace 目录的会话头部分体按钮 | — |
+2 -2
View File
@@ -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-commands/README.md
README.md: e1264d10bd8ff807d8f348339e0c055607579407
README.zh.md: c5323149aea1e38ff09262db9bd2aacad7b284ea
README.md: c5f3c55c08a6df8e6c3f122d0c5e341721c2b41a
README.zh.md: f728c03e067f74ba5142464adc17531225034aad
+2 -2
View File
@@ -1,5 +1,5 @@
---
description: "Client command API for the Web GUI: the / command source, three dispatch kinds, the per-session command directory, and popupSelect registration for business packages; for users and maintainers of slash commands."
description: "Client command API for the Web GUI: the / command source, three dispatch kinds, the per-session command directory, and popupSelect and action registration for business packages; for users and maintainers of slash commands."
kind: "package-reference"
---
@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
## Summary
Typing a `/` command in the composer opens the matching surface — a registered popup, a host command's input, or a direct execution — and a command line is never silently downgraded to a plain prompt. Business packages contribute command surfaces through `ctx.commandUi`, registering a popupSelect spec (`/model`, `/permission`) or decorating an existing host command with a picker while the host keeps its catalog row and argument claim. Space and Enter resolve the line against the session's directory: a host descriptor with `input` is `leadingInput`, a registered `CommandUiSpec` is `popupSelect`, and everything else is `execute`.
Typing a `/` command in the composer opens the matching surface — a registered popup, a host command's input, or a direct execution — and a command line is never silently downgraded to a plain prompt. Business packages contribute command surfaces through `ctx.commandUi`: a popupSelect spec (`/model`, `/permission`) or an action (`/feedback`), registered as a command or decorating an existing host command while the host keeps its catalog row and argument claim. Space and Enter resolve the line against the session's directory: a host descriptor with `input` is `leadingInput`, a registered `CommandUiSpec` is its kind, and everything else is `execute`.
## Table of Contents
+2 -2
View File
@@ -1,5 +1,5 @@
---
description: "Web GUI 的客户端命令 API:/ 命令 source、三类派发、会话级命令目录,以及面向业务包的 popupSelect 注册;供斜杠命令的用户与维护者阅读。"
description: "Web GUI 的客户端命令 API:/ 命令 source、三类派发、会话级命令目录,以及面向业务包的 popupSelect 与 action 注册;供斜杠命令的用户与维护者阅读。"
kind: "package-reference"
---
@@ -9,7 +9,7 @@ kind: "package-reference"
## 概述
在 composer 中键入 `/` 命令会打开匹配的表面——已注册的弹窗、宿主命令的输入或直接执行——命令行绝不会被静默降级为普通提示词。业务包经 `ctx.commandUi` 贡献命令表面:注册 popupSelect 贡献项(`/model`、`/permission`),或用选择器装饰既有宿主命令,宿主保留其目录行与参数声明。空格与回车对照会话目录解析命令行:带 `input` 的宿主描述符是 `leadingInput`,注册了 `CommandUiSpec` 的是 `popupSelect`,其余全部是 `execute`。
在 composer 中键入 `/` 命令会打开匹配的表面——已注册的弹窗、宿主命令的输入或直接执行——命令行绝不会被静默降级为普通提示词。业务包经 `ctx.commandUi` 贡献命令表面:popupSelect 贡献项(`/model`、`/permission`)或 action(`/feedback`),既可注册为命令,也可装饰既有宿主命令,宿主保留其目录行与参数声明。空格与回车对照会话目录解析命令行:带 `input` 的宿主描述符是 `leadingInput`,注册了 `CommandUiSpec` 的按其种类派发,其余全部是 `execute`。
## 目录
@@ -31,12 +31,30 @@ export interface SelectOption {
* The shell component is owned by ui-commands; business never sees it. Both
* callbacks receive the ClientSessionContext captured at popup open.
*/
export type CommandUiSpec = {
export interface PopupSelectSpec {
readonly kind: 'popupSelect'
options(session: ClientSessionContext, signal: AbortSignal): Promise<readonly SelectOption[]>
onSelect(option: SelectOption, session: ClientSessionContext): void | Promise<void>
}
/**
* Business registration for the action command kind: a bare invocation
* consumes the trigger token and runs one client-side callback (the Feedback
* row opens the feedback dialog). It submits nothing, so an
* attachment-carrying draft never refuses it.
*/
export interface ActionSpec {
readonly kind: 'action'
/**
* Run the action for one session.
* @param session - the ClientSessionContext captured at invocation.
*/
run(session: ClientSessionContext): void
}
/** The UI behavior of a contribution or decoration. */
export type CommandUiSpec = PopupSelectSpec | ActionSpec
/**
* One client-owned command contribution: a slash-menu entry whose behavior
* lives entirely on the client (no host descriptor). Merged with the host
@@ -50,7 +68,7 @@ export interface CommandContribution {
readonly description: () => string
/** Capability filter, called with a fresh projection per candidate pass. */
available(session: ClientSessionContext): boolean
/** The command's UI behavior (this phase: popupSelect only). */
/** The command's UI behavior. */
readonly ui: CommandUiSpec
}
@@ -68,7 +86,7 @@ export interface CommandDecoration {
readonly name: string
/** Capability filter, called with a fresh projection per bare invocation. */
available(session: ClientSessionContext): boolean
/** The bare-invocation UI (this phase: popupSelect only). */
/** The bare-invocation UI. */
readonly ui: CommandUiSpec
}
@@ -27,7 +27,8 @@ export { filterOptions, PopupSelectController } from './popup.ts'
export type { PopupSelectDeps, PopupSpec, PopupState, TokenSegment } from './popup.ts'
export type { PopupSelectInjected, PopupSelectViewProps } from './PopupSelectView.tsx'
export type {
CommandContribution, CommandDecoration, CommandUiContract, CommandUiSpec, SelectConfirmation, SelectOption,
ActionSpec, CommandContribution, CommandDecoration, CommandUiContract, CommandUiSpec, PopupSelectSpec,
SelectConfirmation, SelectOption,
} from './contract.ts'
export type { CommandKey } from './locales.ts'
@@ -228,22 +228,22 @@ export class CommandUiRuntime extends Service implements CommandUiContract {
return key !== undefined && command.description === en[key] ? this.t(key) : command.description
}
/** Decision table, menu column: contribution/decorated-host → popup; host input → claim; host bare → detached execute. */
/** Decision table, menu column: contribution/decorated-host → popup or action; host input → claim; host bare → detached execute. */
private dispatch(pick: InputTriggerPick): PickOutcome {
const name = pick.candidate.name
const contribution = this.live.contributions.get(name)
if (contribution !== undefined && contribution.available(pick.session)) {
this.openPopup(name, contribution.ui, pick.session, { via: 'menu', span: pick.span })
this.invoke(name, contribution.ui, pick.session, { via: 'menu', span: pick.span })
return 'handled'
}
const desc = this.directory.resolve(pick.session.sessionId, name)
if (desc === undefined) return undefined // snapshot swapped between menu and pick → miss
// A decoration replaces the HOST row's bare invocation with its popup;
// it decorates only a resolvable host command (checked above), never
// manufactures one, and never touches the argument claim below.
// A decoration replaces the HOST row's bare invocation with its popup or
// action; it decorates only a resolvable host command (checked above),
// never manufactures one, and never touches the argument claim below.
const decoration = this.live.decorations.get(name)
if (decoration !== undefined && decoration.available(pick.session)) {
this.openPopup(name, decoration.ui, pick.session, { via: 'menu', span: pick.span })
this.invoke(name, decoration.ui, pick.session, { via: 'menu', span: pick.span })
return 'handled'
}
if (desc.input !== undefined) return { claim: this.leadingClaim(desc, pick.session) }
@@ -258,7 +258,7 @@ export class CommandUiRuntime extends Service implements CommandUiContract {
private matchSpace(session: ClientSessionContext, token: string): PickOutcome {
if (!token.startsWith('/')) return undefined
const name = token.slice(1)
if (this.live.contributions.has(name)) return undefined // popup kinds never claim on space
if (this.live.contributions.has(name)) return undefined // popup and action kinds never claim on space
const desc = this.directory.resolve(session.sessionId, name)
if (desc === undefined || desc.input === undefined) return undefined
return { claim: this.leadingClaim(desc, session) }
@@ -271,10 +271,11 @@ export class CommandUiRuntime extends Service implements CommandUiContract {
* args-tolerant.
*
* Envelope policy: an enter submission carrying attachments resolves only
* through a command declaring attachment acceptance. Every other command route —
* popup, non-accepting claim, bare detached execute — throws the refusal
* so the machine surfaces one composer notice and the draft and attachments
* stay in place; nothing executes and nothing is dropped.
* through a command declaring attachment acceptance. Every other submitting
* route — popup, non-accepting claim, bare detached execute — throws the
* refusal so the machine surfaces one composer notice and the draft and
* attachments stay in place; nothing executes and nothing is dropped. An
* action submits nothing and runs regardless.
*/
private async matchEnter(
session: ClientSessionContext,
@@ -295,8 +296,8 @@ export class CommandUiRuntime extends Service implements CommandUiContract {
const contribution = this.live.contributions.get(name)
if (contribution !== undefined && contribution.available(session)) {
if (!bare) return undefined
if (envelope.attachments > 0) refuseAttachments()
this.openPopup(name, contribution.ui, session, { via: 'enter', token })
if (envelope.attachments > 0 && contribution.ui.kind !== 'action') refuseAttachments()
this.invoke(name, contribution.ui, session, { via: 'enter', token })
return 'handled'
}
await this.directory.ensureReady(session.sessionId, signal)
@@ -307,8 +308,8 @@ export class CommandUiRuntime extends Service implements CommandUiContract {
if (bare) {
const decoration = this.live.decorations.get(name)
if (decoration !== undefined && decoration.available(session)) {
if (envelope.attachments > 0) refuseAttachments()
this.openPopup(name, decoration.ui, session, { via: 'enter', token })
if (envelope.attachments > 0 && decoration.ui.kind !== 'action') refuseAttachments()
this.invoke(name, decoration.ui, session, { via: 'enter', token })
return 'handled'
}
}
@@ -323,13 +324,21 @@ export class CommandUiRuntime extends Service implements CommandUiContract {
return 'handled'
}
/** Open the session's popup for one contribution or decoration (menu pick / bare enter). */
private openPopup(
/**
* Invoke one contribution or decoration (menu pick / bare enter): open the
* session's popup, or consume the token and run the action.
*/
private invoke(
name: string,
ui: CommandContribution['ui'],
session: ClientSessionContext,
segment: TokenSegment,
): void {
if (ui.kind === 'action') {
this.consumeVia(session.sessionId, segment)
ui.run(session)
return
}
const actx = this.scopeFor(session.sessionId)
if (actx === undefined) return
this.popupFor(actx).open(name, ui, session, segment)
@@ -14,7 +14,7 @@ import { createScope, scopeOf } from '@deepseek-ai/dsh-api-session-controller/cl
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import { RemoteError, TestRemote } from '@deepseek-ai/dsh-client-test-runtime'
import type { ClientSessionContext, ConsumeTokenRequest, InputTriggerPick, InputTriggerSource, SubmitAttachment } from '@deepseek-ai/dsh-client-ui-input-trigger/client'
import type { CommandContribution, CommandDecoration, CommandUiSpec, SelectOption } from '../src/client/contract.ts'
import type { CommandContribution, CommandDecoration, PopupSelectSpec, SelectOption } from '../src/client/contract.ts'
import type { CommandDescriptor } from '../src/client/directory.ts'
import { CommandUiRuntime } from '../src/client/service.ts'
@@ -157,7 +157,7 @@ function menuPick(source: InputTriggerSource, name: string, session: ClientSessi
return source.onPick(pick)
}
const themeUi = (over: Partial<CommandUiSpec> = {}): CommandUiSpec => ({
const themeUi = (over: Partial<PopupSelectSpec> = {}): PopupSelectSpec => ({
kind: 'popupSelect',
options: () => Promise.resolve([{ id: 'dark', label: 'Dark' }]),
onSelect: () => undefined,
@@ -384,6 +384,43 @@ describe('dispatch (menu column)', () => {
expect(executeCalls).toEqual([])
})
it('action decoration: a menu pick consumes the span and runs the callback without executing', async () => {
const { command, source, mint, warm, executeCalls } = await bench()
const scope = mint('s1')
const consumes: ConsumeTokenRequest[] = []
scope.ctx.on('slash/input-consume-token', (r) => {
consumes.push(r)
return true
})
const run = vi.fn()
command.decorate({ name: 'plan', available: () => true, ui: { kind: 'action', run } })
await warm(proj('s1'))
expect(menuPick(source, 'plan', proj('s1'), 5)).toBe('handled')
expect(consumes).toEqual([{ guard: { kind: 'span', span: { start: 0, end: 5, draftRev: 3 } } }])
expect(run).toHaveBeenCalledWith(proj('s1'))
expect(executeCalls).toEqual([])
expect(command.popupFor(scope.ctx).state.getSnapshot().open).toBe(false)
})
it('action decoration: a bare enter runs even with attachments; an argued line bypasses it', async () => {
const { command, source, mint, warm } = await bench()
const scope = mint('s1')
const consumes: ConsumeTokenRequest[] = []
scope.ctx.on('slash/input-consume-token', (r) => {
consumes.push(r)
return true
})
const run = vi.fn()
command.decorate({ name: 'plan', available: () => true, ui: { kind: 'action', run } })
await warm(proj('s1'))
await expect(source.matchEnter!(proj('s1'), '/plan', new AbortController().signal, { attachments: 1 })).resolves.toBe('handled')
expect(consumes).toEqual([{ guard: { kind: 'bare-token', token: '/plan' } }])
expect(run).toHaveBeenCalledTimes(1)
// An argued line never consults the decoration.
await expect(source.matchEnter!(proj('s1'), '/plan later', new AbortController().signal, { attachments: 0 })).resolves.not.toBe('handled')
expect(run).toHaveBeenCalledTimes(1)
})
it('host bare → consume-token span guard on the session scope + detached execute', async () => {
const { source, mint, warm, executeCalls, executions } = await bench()
const scope = mint('s1')
@@ -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-conversation/README.md
README.md: 19a210bb200dae359920e85ff944b68242f45b4b
README.zh.md: c5a56871eb99607c924b2b2e048de72d918e6a8b
README.md: 7d5f370644f90f57ce1c27c59becf47c4cf2e684
README.zh.md: e7c5204b763aad92dc057d122537d592952afcd5
+1 -1
View File
@@ -44,7 +44,7 @@ View selection is deterministic: a registered persisted selection wins, otherwis
The shell reads the persisted View preference before rendering when a Session first binds or a cached Session becomes current, activates the registered preferred View or Chat fallback, and activates later tab or focus selections before committing them to the store. A blank Session still omits the `conversation.view` slot; no unselected target is activated.
The resident composer survives no-Session and Session transitions. The no-Session state keeps the same composer surface mounted but inert while the Workspace picker connects a blank Session. The surface is a shell-owned Lexical editor: reference chips are atomic decorator nodes carrying the owner's serialization identity (submission expands them through the owner codec), claimed slash commands stay styled leading text, folder text references carry the folder glyph as an icon prefix, and the draft's clipboard projection is mirrored into the per-Session Conversation store. Queue operations address exact queue occurrences through the scoped `ctx.conversation` service; queue previews render sent text through the shared inline reference projection from `ui-primitives` (wire session forms fold to their label) and show local or durable images and files in original attachment order. Images use thumbnails; files use compact name-and-size cards. An edit exposes the literal sent text, and durable thumbnails resolve through the session image URL cache. Busy Enter behavior is stored in the Host-backed `ui-conversation` settings namespace.
The resident composer survives no-Session and Session transitions. Whitespace hides its placeholder; a whitespace-only draft without attachments cannot be sent. The no-Session state keeps the same composer surface mounted but inert while the Workspace picker connects a blank Session. The surface is a shell-owned Lexical editor: reference chips are atomic decorator nodes carrying the owner's serialization identity (submission expands them through the owner codec), claimed slash commands stay styled leading text, folder text references carry the folder glyph as an icon prefix, and the draft's clipboard projection is mirrored into the per-Session Conversation store. Queue operations address exact queue occurrences through the scoped `ctx.conversation` service; queue previews render sent text through the shared inline reference projection from `ui-primitives` (wire session forms fold to their label) and show local or durable images and files in original attachment order. Images use thumbnails; files use compact name-and-size cards. An edit exposes the literal sent text, and durable thumbnails resolve through the session image URL cache. Busy Enter behavior is stored in the Host-backed `ui-conversation` settings namespace.
Default sends commit optimistically: Enter clears the draft, occurrence table, and undo history in the same transaction, keeps the composer in `plain`, and runs the send as a detached attempt, so typing and further sends continue during the flight. `sendSession` registers a Session submission echo (`session.beginSubmission`) with the delivery mode before serializing, preserving selected image and file order in `pendingSubmissions`; Session derives the placement from that mode and its current running state, so idle sends use the transcript, busy Queue sends use QueueDock, and busy Steer sends use the pending-steering surface. It then yields one paint, encodes images through the browser's native `FileReader` data-URL path, and cites staged file receipts. Command submissions use the same receipts for generic files, so sending `/goal` or `/plan` never reads those browser files again. The prompt reuses the submission `requestId`; queue and history observation by that `rpcId` retires the echo once. Concurrent failures are restored together in submission order until the user edits the restored content; command submissions keep the frozen `submitting` phase. Detached attempts retain their attachment ids through admission and Session scope disposal. An observed retirement immediately exposes each image preview through the durable cache, replaces it with the canonical URL after fetching the admitted attachment, revokes each URL after its use ends, and releases file cards. Selected generic files enter one FIFO background-upload queue; `maxConcurrentFileUploads` defaults to two active Worker transports, the Conversation service retains queued and active operations plus byte progress across Session navigation, and removing a draft skips its queued transfer or aborts its active transport. Continuable subagents disable attachment intake and skip local echoes because their transport does not preserve the browser request id.
+1 -1
View File
@@ -44,7 +44,7 @@ View 选择规则固定:有效且已注册的持久化选择优先,其次是
Session 首次绑定或缓存的 Session 成为 current 时,shell 会在渲染前读取持久化 View 偏好,激活已注册的偏好 View 或 Chat fallback,并在后续 tab 或 focus 选择写入 store 前先激活对应 target。blank Session 仍不渲染 `conversation.view` slot;未选中的 target 不会激活。
常驻 composer 在无 Session 与有 Session 之间保持挂载。无 Session 时,同一个编辑器表面保持 inert,Workspace picker 连接 blank Session。该表面是 shell 所有的 Lexical 编辑器:引用 chip 是携带 owner 序列化身份的原子 decorator 节点(提交时经 owner codec 展开),已认领的 slash command 保持为带样式的行首文本,文件夹文本引用以图标前缀携带文件夹图形,草稿的剪贴板投影镜像到逐 Session Conversation store。Queue 操作通过 scoped `ctx.conversation` service 寻址准确的 queue occurrence;queue 预览经 `ui-primitives` 的共享行内引用投影渲染已发送文本(wire 会话形式折叠为其标签),并按原始附件顺序展示本地或持久化的图片和文件。图片使用缩略图,文件使用紧凑的名称与大小卡片。编辑态展示字面发送文本,持久化缩略图通过会话图片 URL 缓存解析。繁忙时 Enter 行为保存在 Host-backed `ui-conversation` settings namespace。
常驻 composer 在无 Session 与有 Session 之间保持挂载。输入空白字符会隐藏占位提示;没有附件的纯空白草稿无法发送。无 Session 时,同一个编辑器表面保持 inert,Workspace picker 连接 blank Session。该表面是 shell 所有的 Lexical 编辑器:引用 chip 是携带 owner 序列化身份的原子 decorator 节点(提交时经 owner codec 展开),已认领的 slash command 保持为带样式的行首文本,文件夹文本引用以图标前缀携带文件夹图形,草稿的剪贴板投影镜像到逐 Session Conversation store。Queue 操作通过 scoped `ctx.conversation` service 寻址准确的 queue occurrence;queue 预览经 `ui-primitives` 的共享行内引用投影渲染已发送文本(wire 会话形式折叠为其标签),并按原始附件顺序展示本地或持久化的图片和文件。图片使用缩略图,文件使用紧凑的名称与大小卡片。编辑态展示字面发送文本,持久化缩略图通过会话图片 URL 缓存解析。繁忙时 Enter 行为保存在 Host-backed `ui-conversation` settings namespace。
默认发送采用乐观提交:Enter 在同一事务里清空草稿、occurrence 表和撤销历史,composer 保持 `plain`,发送作为 detached attempt 运行,发送期间可以继续输入和提交。`sendSession` 在序列化之前用投递模式注册 Session 提交回显(`session.beginSubmission`),并在 `pendingSubmissions` 中保留图片与文件的选择顺序;Session 根据该模式与当前运行状态推导位置,因此空闲发送进入 transcript,繁忙时 Queue 进入 QueueDock,繁忙时 Steer 进入 pending-steering 区域。随后让出一帧,图片经浏览器原生 `FileReader` data-URL 路径编码,文件则引用已暂存凭证。命令提交也用同一凭证表示通用文件,因此发送 `/goal` 或 `/plan` 时不会再次读取这些浏览器文件。prompt 复用提交 `requestId`;queue 或历史以同一 `rpcId` 被观察后,回显只退休一次。多个并发发送失败时,在用户编辑还原内容之前按提交顺序合并还原;命令提交保持冻结的 `submitting` 阶段。Detached attempt 持有附件 id,直到 admission 完成或 Session scope 销毁。回显以 observed 退休时,durable 图片缓存立即公开每个预览 URL,读取 admitted 附件后用规范化 URL 替换预览,并在各 URL 停止使用后撤销,同时释放文件卡。选中的通用文件进入同一个先进先出的后台上传队列;`maxConcurrentFileUploads` 默认允许两个 Worker transport 同时运行,Conversation service 在切换 Session 时继续持有排队和运行中的传输操作及字节进度,移除草稿会跳过排队中的传输或中止正在运行的传输。continuable 子代理禁用附件入口,也不创建本地回显,因为其 transport 不保留浏览器 request id。
@@ -469,7 +469,7 @@ export const InputBar = memo(function InputBar({
onKeyDown={workspaceTrigger ? onWorkspaceKeyDown : undefined}
style={hint === null ? undefined : { '--dsh-composer-hint': JSON.stringify(hint) } as CSSProperties}
/>
{empty && !claimActive && (
{draft === '' && attachments.length === 0 && !claimActive && (
<div aria-hidden className={css.placeholder} data-composer-placeholder>
{placeholderText}
</div>
@@ -270,6 +270,49 @@ function writeDraft(shell: SessionInputShell, text: string): void {
act(() => { shell.setDraft(text) })
}
describe('composer placeholder visibility', () => {
it.each([' ', ' ', '\t', '\n'])('hides for whitespace %j and returns after deletion', async (draft) => {
const { view, shell, textarea, button, sink, props } = bench()
const placeholder = () => view.container.querySelector('[data-composer-placeholder]')
expect(placeholder()).not.toBeNull()
writeDraft(shell, draft)
expect(placeholder()).toBeNull()
expect(button.disabled).toBe(true)
fireEvent.keyDown(textarea, { key: 'Enter', keyCode: 13 })
await act(async () => {})
expect(sink).not.toHaveBeenCalled()
fireEvent.blur(textarea)
view.rerender(<InputBar {...props} />)
fireEvent.focus(textarea)
expect(placeholder()).toBeNull()
writeDraft(shell, '')
expect(placeholder()).not.toBeNull()
})
it('hides for pasted spaces and restores after clearing', async () => {
const { view, shell, textarea } = bench()
fireEvent.paste(textarea, {
clipboardData: { items: [], getData: () => ' ' },
})
await vi.waitFor(() => { expect(shell.snapshot.draft).toBe(' ') })
expect(view.container.querySelector('[data-composer-placeholder]')).toBeNull()
writeDraft(shell, '')
expect(view.container.querySelector('[data-composer-placeholder]')).not.toBeNull()
})
it('keeps whitespace hidden through composition and rerender', () => {
const { view, shell, textarea, props } = bench()
fireEvent.compositionStart(textarea)
writeDraft(shell, ' ')
expect(view.container.querySelector('[data-composer-placeholder]')).toBeNull()
view.rerender(<InputBar {...props} />)
fireEvent.compositionEnd(textarea, { data: ' ' })
expect(view.container.querySelector('[data-composer-placeholder]')).toBeNull()
writeDraft(shell, '')
expect(view.container.querySelector('[data-composer-placeholder]')).not.toBeNull()
})
})
describe('image draft rail', () => {
it('collects clipboard files while preserving text from a mixed paste', async () => {
const addFiles = vi.fn(() => null)
@@ -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-deliverables/README.md
README.md: ae42abb5a69d29332bd7cfd6d2d2a1191381e79a
README.zh.md: 664dfa3cd2e0d526b43464a80290604a8ecf958c
README.md: 4886a5817e6118ef76d5e7b49ed7fe3ed319650f
README.zh.md: 43c68d4563f9ec32bb15fdd3df9a2e21225ebc13
+1 -1
View File
@@ -36,7 +36,7 @@ The `present` tool row shows running, delivered, failed, or interrupted status;
### The row
The row uses CSS container-width bands to show a responsive prefix of up to six file chips. Flexbox shrinks and ellipsizes basename text, while CSS selects the matching localized `+ N files` label for omitted paths; the full path remains available as the title, and the row performs no JavaScript layout observation or horizontal scrolling.
The “Files changed” row lists successful file-tool mutations; final file deliveries require `present`. It uses CSS container-width bands to show a responsive prefix of up to six file chips. Flexbox shrinks and ellipsizes basename text, while CSS selects the matching localized `+ N files` label for omitted paths; the full path remains available as the title, and the row performs no JavaScript layout observation or horizontal scrolling.
### Inline-code links
+1 -1
View File
@@ -36,7 +36,7 @@ Web 的 `standard`、`ptc` 与 `cordis` preset 提供 `present` 用于声明交
### 该行
该行通过 CSS 容器宽度档位响应式展示至多六个文件标签项。Flexbox 负责收缩文件名并用 ellipsis 省略,CSS 为未展示路径选择匹配的本地化 `+ N 个文件` 标签;完整路径仍保留在 `title` 中,该行不执行 JavaScript 布局观察,也不提供横向滚动。
“本轮文件改动”行列出成功的文件工具修改;最终文件交付需要调用 `present`。该行通过 CSS 容器宽度档位响应式展示至多六个文件标签项。Flexbox 负责收缩文件名并用 ellipsis 省略,CSS 为未展示路径选择匹配的本地化 `+ N 个文件` 标签;完整路径仍保留在 `title` 中,该行不执行 JavaScript 布局观察,也不提供横向滚动。
### 行内代码链接
@@ -18,7 +18,7 @@ export const zh = {
'row.stopped': '已中断',
'row.inspect': '查看调用',
'presented.open': '在默认程序中打开 {name}',
'produced.label': '产物',
'produced.label': '本轮文件改动',
'produced.moreOne': '+ 1 个文件',
'produced.more': '+ {count} 个文件',
'produced.open': '打开 {name}',
@@ -39,7 +39,7 @@ export const en: Record<DeliverablesKey, string> = {
'row.stopped': 'Interrupted',
'row.inspect': 'Inspect call',
'presented.open': 'Open {name} in default app',
'produced.label': 'Produced',
'produced.label': 'Files changed',
'produced.moreOne': '+ 1 file',
'produced.more': '+ {count} files',
'produced.open': 'Open {name}',
@@ -426,7 +426,7 @@ describe('ProducedFiles row', () => {
const openFile = vi.fn<(path: string) => void>()
const view = render(<ProducedFiles matched={paths} openFile={openFile} t={t} />)
expect(view.getByText('产物')).toBeTruthy()
expect(view.getByText('本轮文件改动')).toBeTruthy()
const row = view.container.querySelector('[data-produced-files-row]')
if (!(row instanceof HTMLElement)) throw new Error('produced row missing')
expect(within(row).getAllByRole('button')).toHaveLength(6)
@@ -595,7 +595,7 @@ describe('presented files', () => {
expect(view.queryByRole('link')).toBeNull()
fireEvent.click(view.getByRole('button', { name: 'Open report-0.docx in default app' }))
expect(props.openPresented).toHaveBeenCalledWith('child-session', 2, 0)
expect(view.queryByText('Produced')).toBeNull()
expect(view.queryByText('Files changed')).toBeNull()
})
})
@@ -617,7 +617,7 @@ it.each([{}, { turn: '1', callId: 'bad', files: [] },
const owner = tailOwner(deliverablesOf(value), 5)
const matched = selectDeliverables(owner)!
const view = render(<Deliverables {...openProps()} matched={matched} openFile={owner.openFile} sessionId={SessionId('session')} t={makeTranslate(en)} />)
expect(view.getByText('Produced')).toBeTruthy()
expect(view.getByText('Files changed')).toBeTruthy()
expect(view.queryByText('Deliverables')).toBeNull()
})
@@ -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-message-feedback/README.md
README.md: 171a812acc836eec243eb9f596270359c0a3aa9c
README.zh.md: e34eba9014779fc27bbd5a7ef071a086e8982f45
README.md: 8ffcf87a59ec95fe783a0379423b93d4bf965a3e
README.zh.md: a29448eaaddf0f089d8fc12c1315732fd13fc304
+15 -10
View File
@@ -1,5 +1,5 @@
---
description: "Per-message feedback for the Web GUI: the Like/Dislike pair and optional note in the finalized assistant message's action row; for users and maintainers of the feedback experience."
description: "The Web feedback surface: the Like/Dislike pair in the finalized assistant message's action row, the feedback dialog behind Dislike and `/feedback`, and the acknowledgement toast; for users and maintainers of the feedback experience."
kind: "package-reference"
---
@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
## Summary
This package adds per-message feedback to the Web GUI: a Like/Dislike pair plus an optional note, contributed as the `feedback` entry of the finalized assistant message's action strip. It renders on the closing assistant message of each turn — earlier steps of a multi-step turn produce tool rows rather than a rateable body. One controller per Session backs every message control in that Session, so a single list read seeds the whole transcript. Ratings and notes are log-only Session events: they never enter model context. Deletion retracts the current item without erasing its earlier log entries.
This package is the Web GUI's feedback surface: the Like/Dislike pair in the finalized assistant message's action strip, the feedback dialog with its acknowledgement toast in the composer overlay, and a decoration that opens the dialog from a bare `/feedback`. Like records at once and shows the toast; Dislike opens the dialog, which collects a category and an optional description. One surface per Session backs every entry, so a single list read seeds the whole transcript and one dialog serves the Session and its messages. Ratings, categories, and notes are log-only Session events that never enter model context.
## Table of Contents
@@ -25,11 +25,11 @@ This package adds per-message feedback to the Web GUI: a Like/Dislike pair plus
<a id="use-this-package"></a>
## Use this package
Mount this plugin alongside `ui-conversation`; the Like/Dislike pair then appears in the action row of each turn's closing assistant message, between copy and branch. Clicking the recorded rating retracts the feedback; switching sides carries the existing note forward. The note editor is a dialog popover anchored under its trigger, so the row keeps its single line whether the editor is open or closed.
Mount this plugin alongside `ui-conversation` and `ui-commands`; the Like/Dislike pair then appears in the action row of each turn's closing assistant message, between copy and branch, and the Feedback row of the composer menu opens the dialog. A recorded rating shows the filled glyph and stays visible without hover. Like records immediately and the toast thanks the user for the feedback. Dislike opens the dialog: seven category chips and a detail box, both optional; Submit records a negative judgment carrying whatever was filled in, and the conversation log travels with every feedback event. Clicking the recorded rating retracts it. A bare `/feedback`, picked from the menu or typed and sent without text, opens the same dialog for the Session; `/feedback <text>` keeps the Host command path and its acknowledgement row.
### Failures
A rating or list-load failure shows inline in the row; a note-save failure shows inside the popover, which stays open so the draft can be corrected. Only finalized messages reach the slot — an interruption-frozen partial carries no `messageId` and therefore no feedback controls.
A rating or list-load failure shows inline in the row; a submission failure shows inside the dialog, which stays open so the draft can be corrected. Only finalized messages reach the message entry — an interruption-frozen partial carries no `messageId` and therefore no feedback controls.
-----
@@ -39,7 +39,9 @@ A rating or list-load failure shows inline in the row; a note-save failure shows
<details>
<summary>Implementation internals — click to expand</summary>
The package contributes the `feedback` entry (order 10) of `conversation.chat.assistant-actions`, declared by ui-conversation and rendered inside the finalized assistant message's IconActions row. One `MessageFeedbackController` per Session backs every message control in that Session, so a single `messageFeedback.list` read seeds the whole transcript; the read is deferred to the first hover or focus rather than fired on mount. Mutations go through `ctx.remote.messageFeedback`; the Host owns per-item compare-and-set. Every `put` and `delete` carries the `version` this controller last observed, and a `version-conflict` reply carries the authoritative item, so a lost race reconciles from the reply itself instead of refetching. Mutations serialize per Session, so a queued operation always compares against the committed version.
The package contributes the `feedback` entry (order 10) of `conversation.chat.assistant-actions`, declared by ui-conversation and rendered inside the finalized assistant message's IconActions row, and the `feedback-dialog` entry (order 2) of `conversation.input.overlay`, which renders the Modal and Toast primitives through body portals and centers the toast over the composer card it mounts inside. The `/feedback` decoration is an `action` registered through `ctx.commandUi.decorate`, so a menu pick or a bare Enter consumes the trigger token and opens the dialog while an argued line still reaches the Host command.
Per Session, one `MessageFeedbackController` backs every message control and one `FeedbackDialogController` owns the dialog draft, the submission, and the toast sequence. The message controller reads `messageFeedback.list` once, deferred to the first hover or focus rather than fired on mount, and serializes mutations so each carries the version last observed; a `version-conflict` reply carries the authoritative item and reconciles the view without refetching. `toggle` reports the rating now committed, so the row acknowledges a recorded Like and not a retraction. The dialog controller submits by target: a message target puts a negative judgment with the dialog's note and category through the message controller, and the Session target records through `ctx.remote.sessionFeedback`. Success closes the draft and raises the toast; a late success from a superseded draft raises the toast without closing the new draft; a failure keeps the draft open with its code.
</details>
@@ -48,10 +50,12 @@ The package contributes the `feedback` entry (order 10) of `conversation.chat.as
<a id="further-exploration"></a>
## Further Exploration
Read these pages when the feedback surface is not enough. They move from the browser strip to the Session-log backend and the conversation shell.
Read these pages when the feedback surface is not enough. They move from the browser strip to the Session-log backends and the conversation shell.
- [dsh-message-feedback](../../feedback/message-feedback/README.md) — the Session-log backend that owns per-item compare-and-set and persistence.
- [ui-conversation](../ui-conversation/README.md) — declares the assistant-actions strip and renders the action row.
- [dsh-command-feedback](../../feedback/command-feedback/README.md) — the `/feedback` command, the `sessionFeedback` Remote, and the category taxonomy.
- [ui-commands](../ui-commands/README.md) — the command decoration contract the `/feedback` row goes through.
- [ui-conversation](../ui-conversation/README.md) — declares the assistant-actions strip and the composer overlay.
- [Client package map](../README.md) — adjacent browser UI packages.
-----
@@ -59,7 +63,7 @@ Read these pages when the feedback surface is not enough. They move from the bro
<a id="model-experience"></a>
## Model Experience
None, as ratings and notes are log-only events, not model input. Optional Session-log delivery uses request metadata rather than model context.
None, as ratings, categories, and notes are log-only events, not model input. Optional Session-log delivery uses request metadata rather than model context.
#### KV Cache effect
@@ -72,7 +76,8 @@ None; feedback mutations leave the model-visible history unchanged.
These limits define the current feedback surface. They are current package constraints, not a general rating comparison or a task backlog.
- **Note size is a Host policy** — the deployment configures `maxNoteBytes` (8192 in the Web bundle) and the Host rejects an oversized note with `note-too-large`. The editor does not pre-check the limit, so an oversized note fails on save rather than while typing.
- **Note size is a Host policy** — the deployment configures `maxNoteBytes` (8192 in the Web bundle) and the Host rejects an oversized note with `note-too-large`. The dialog does not pre-check the limit, so an oversized description for a message fails on submit rather than while typing; a Session remark has no bound.
- **No note on a Like** — only the Dislike dialog collects a category and description; a Like records the bare judgment.
- **No cross-tab push** — a second tab's rating becomes visible on reconnect or on the next conflict reply, not immediately; the controller does not consume feedback log events.
- **Chat view only** — the trajectory and waterfall views render no feedback controls even though their assistant nodes carry the same `messageId`.
@@ -86,4 +91,4 @@ None.
</details>
**Runtime invariant:** No companion is published. The plugin owns one slot registration and one per-session controller map, both released by the same effect disposer. The lifecycle spec proves the registration is withdrawn and every controller is dropped when the owning fiber is disposed, so no second authority exists to check at runtime.
**Runtime invariant:** No companion is published. The plugin owns two slot registrations, one command decoration, and one per-session controller-pair map, all released by the plugin fiber's effect disposers. The lifecycle spec proves the registrations are withdrawn and every controller pair is dropped when the owning fiber is disposed, so no second authority exists to check at runtime.
@@ -1,5 +1,5 @@
---
description: "Web GUI 的逐消息反馈:已定稿助手消息动作行中的 Like/Dislike 对与可选备注;供反馈体验的用户与维护者阅读。"
description: "Web 反馈界面:已定稿助手消息动作行中的 Like/Dislike 对、点踩与 `/feedback` 背后的反馈弹窗,以及确认 toast;供反馈体验的用户与维护者阅读。"
kind: "package-reference"
---
@@ -9,7 +9,7 @@ kind: "package-reference"
## 概述
本包为 Web GUI 增加逐消息反馈:一对 Like/Dislike 按钮加一个可选备注,作为已定稿助手消息动作条的 `feedback` 条目贡献。它渲染在每个轮次的收尾助手消息上——多步骤轮次中较早的步骤产出工具行而非可评分正文。每个 Session 一个控制器支撑该 Session 内所有消息的控件,因此一次列表读取即可填充整段对话。评分与备注是仅写日志的 Session 事件:它们绝不进入模型上下文。删除会撤回当前条目,但不会抹除早先的日志记录。
本包是 Web GUI 的反馈界面:已定稿助手消息动作条中的 Like/Dislike 对、输入框浮层中的反馈弹窗及其确认 toast,以及让不带文本的 `/feedback` 打开弹窗的装饰。点赞立即记录并显示 toast;点踩打开弹窗,弹窗收集分类与可选描述。每个 Session 一个 surface 支撑所有条目,因此一次列表读取即可填充整段对话,一个弹窗同时服务 Session 与其消息。评分、分类与备注是仅写日志的 Session 事件,绝不进入模型上下文。
## 目录
@@ -25,11 +25,11 @@ kind: "package-reference"
<a id="use-this-package"></a>
## 使用本包
与 `ui-conversation` 一起挂载本插件;Like/Dislike 对随即出现在每个轮次收尾助手消息的动作行中,位于复制与分支之间。再次点击已记录的评分会撤回反馈;切换到另一侧会保留既有备注。备注编辑器是一个锚定在其触发按钮下方的对话框浮层,因此无论编辑器是否打开,该行都保持单行。
与 `ui-conversation`、`ui-commands` 一起挂载本插件;Like/Dislike 对随即出现在每个轮次收尾助手消息的动作行中,位于复制与分支之间,输入框菜单里的「反馈」行则打开弹窗。已记录的评分显示实心图标,不需要悬停也一直可见。点赞立即记录,toast 显示感谢反馈。点踩打开弹窗:七个分类标签和一个详情框,都可不填;提交会记录一条带上所填内容的差评,对话日志随每个反馈事件一起投递。再次点击已记录的评分会撤回它。不带文本的 `/feedback`,无论是从菜单选中还是直接输入后发送,都会为 Session 打开同一个弹窗;`/feedback <text>` 仍走宿主命令路径并显示确认行。
### 失败
评分或列表加载失败在行内展示;备注保存失败在浮层内展示,面板保持打开以便修正草稿。只有已定稿的消息能到达该槽位——被中断冻结的部分输出不带 `messageId`,因此没有反馈控件。
评分或列表加载失败在行内展示;提交失败在弹窗内展示,弹窗保持打开以便修正草稿。只有已定稿的消息能到达消息条目——被中断冻结的部分输出不带 `messageId`,因此没有反馈控件。
-----
@@ -39,7 +39,9 @@ kind: "package-reference"
<details>
<summary>实现细节——点击展开</summary>
本包贡献 `conversation.chat.assistant-actions` 的 `feedback` 条目(order 10),由 ui-conversation 声明并渲染在已定稿助手消息的 IconActions 行内。每个 Session 一个 `MessageFeedbackController` 支撑该 Session 内所有消息的控件,因此一次 `messageFeedback.list` 读取即可填充整段对话;该读取延迟到首次 hover 或 focus 才发起,而非挂载时触发。变更经 `ctx.remote.messageFeedback` 提交,按条目的比较并交换由宿主负责。每次 `put` 与 `delete` 都携带本控制器最后观察到的 `version`;`version-conflict` 响应带回权威条目,因此竞争失败时直接用该响应本身对账,无需重新拉取。变更按 Session 串行,排队中的操作总是与已提交的版本比较。
本包贡献 `conversation.chat.assistant-actions` 的 `feedback` 条目(order 10),由 ui-conversation 声明并渲染在已定稿助手消息的 IconActions 行内;同时贡献 `conversation.input.overlay` 的 `feedback-dialog` 条目(order 2),它通过 body portal 渲染 Modal 与 Toast 基元,并让 toast 以其所在的输入框卡片为中心。`/feedback` 装饰是经 `ctx.commandUi.decorate` 注册的 `action`,因此菜单选中或不带参数的回车会消费触发 token 并打开弹窗,而带参数的命令行仍到达宿主命令。
每个 Session 有一个 `MessageFeedbackController` 支撑所有消息控件,以及一个 `FeedbackDialogController` 拥有弹窗草稿、提交与 toast 序号。消息控制器只读取一次 `messageFeedback.list`,且延迟到首次 hover 或 focus 才发起,而非挂载时触发;变更串行执行,每次都携带最后观察到的版本,`version-conflict` 响应带回权威条目,据此对账视图而不重新拉取。`toggle` 会报告提交后的评分,因此该行只对记录成功的点赞做确认,撤回不做。弹窗控制器按目标提交:消息目标通过消息控制器 put 一条带弹窗备注与分类的差评,Session 目标通过 `ctx.remote.sessionFeedback` 记录。成功会关闭草稿并弹出 toast;被替换的旧草稿迟到的成功只弹 toast、不关闭新草稿;失败让草稿保持打开并带上失败码。
</details>
@@ -48,10 +50,12 @@ kind: "package-reference"
<a id="further-exploration"></a>
## 进一步探索
当反馈面不够用时阅读以下页面。它们从浏览器条带进入 Session 日志后端与会话外壳。
当反馈界面不够用时阅读以下页面。它们从浏览器条带进入 Session 日志后端与会话外壳。
- [dsh-message-feedback](../../feedback/message-feedback/README.zh.md)——拥有按条目比较并交换与持久化的 Session 日志后端。
- [ui-conversation](../ui-conversation/README.zh.md)——声明助手动作条并渲染动作行。
- [dsh-command-feedback](../../feedback/command-feedback/README.zh.md)——`/feedback` 命令、`sessionFeedback` Remote 与分类表。
- [ui-commands](../ui-commands/README.zh.md)——`/feedback` 行所经过的命令装饰约定。
- [ui-conversation](../ui-conversation/README.zh.md)——声明助手动作条与输入框浮层。
- [客户端包映射](../README.zh.md)——相邻的浏览器 UI 包。
-----
@@ -59,7 +63,7 @@ kind: "package-reference"
<a id="model-experience"></a>
## 模型体验
无。评分与备注是仅写日志的事件,不是模型输入。可选的 Session 日志投递使用请求元数据,而非模型上下文。
无。评分、分类与备注是仅写日志的事件,不是模型输入。可选的 Session 日志投递使用请求元数据,而非模型上下文。
#### KV Cache 影响
@@ -70,9 +74,10 @@ kind: "package-reference"
<a id="known-limitations-and-deferred-work"></a>
这些限制界定了当前反馈表面。它们是当前包约束,不是通用评分对比或任务积压。
这些限制界定了当前反馈界面。它们是当前包约束,不是通用评分对比或任务积压。
- **备注大小是宿主策略**——部署方配置 `maxNoteBytes`(Web bundle 中为 8192),超长备注由宿主以 `note-too-large` 拒绝。编辑器不预先校验该上限,因此超长备注在保存时才失败,而不是在输入过程中。
- **备注大小是宿主策略**——部署方配置 `maxNoteBytes`(Web bundle 中为 8192),超长备注由宿主以 `note-too-large` 拒绝。弹窗不预先校验该上限,因此针对消息的超长描述在提交时才失败,而不是在输入过程中;Session 级备注没有上限。
- **点赞不带备注**——只有点踩弹窗收集分类与描述;点赞只记录判断本身。
- **无跨标签页推送**——另一个标签页的评分要等到重连或下一次冲突响应才可见,不会立即出现;控制器不消费反馈日志事件。
- **仅限对话视图**——trajectory 与 waterfall 视图不渲染反馈控件,尽管它们的助手节点也带有相同的 `messageId`。
@@ -86,4 +91,4 @@ kind: "package-reference"
</details>
**运行时不变式:** 不发布伴生入口。插件持有一个 slot 注册和按 Session 的 controller map,两者由同一 effect disposer 释放;生命周期测试已直接观察该关系。
**运行时不变式:** 不发布伴生入口。插件持有两个 slot 注册、一个命令装饰和一个按 Session 的控制器对 map,全部由插件 fiber 的 effect disposer 释放;生命周期测试已直接观察注册被撤销、每对控制器被丢弃,因此运行时没有第二个可核对的权威。
@@ -1,6 +1,6 @@
{
"name": "@deepseek-ai/dsh-client-ui-message-feedback",
"description": "Per-message feedback controls contributed to the assistant-message action strip, backed by the messageFeedback Host Remote",
"description": "The Web feedback surface: per-message Like/Dislike in the assistant-message action strip and the feedback dialog behind Dislike and /feedback, backed by the messageFeedback and sessionFeedback Host Remotes",
"version": "0.1.5-alpha.1",
"publishConfig": {
"access": "public"
@@ -31,7 +31,8 @@
"@deepseek-ai/dsh-api-remotes",
"@deepseek-ai/dsh-client-locale",
"@deepseek-ai/dsh-client-ui-conversation",
"@deepseek-ai/dsh-client-ui-renderer"
"@deepseek-ai/dsh-client-ui-renderer",
"@deepseek-ai/dsh-client-ui-commands"
],
"platform": "web"
}
@@ -63,7 +64,10 @@
"react": "^18.2.0",
"react-dom": "^18.2.0",
"@deepseek-ai/dsh-client-ui-chat": "workspace:^",
"@deepseek-ai/dsh-client-ui-session": "workspace:^"
"@deepseek-ai/dsh-client-ui-session": "workspace:^",
"@deepseek-ai/dsh-client-ui-commands": "workspace:^",
"@deepseek-ai/dsh-command-feedback": "workspace:^",
"@deepseek-ai/dsh-client-store": "workspace:^"
},
"files": [
"lib/index.js",
@@ -0,0 +1,118 @@
/* The card width leaves four categories on the first row and three on the
second. The doubled selector overrides the Modal card geometry. */
.dialog.dialog {
gap: 38px;
width: min(488px, 100%);
border-radius: 18px;
}
.categories {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: -14px;
}
.chip {
height: 28px;
padding: 0 12px;
border: 0.5px solid var(--dsw-alias-border-l4);
border-radius: 14px;
corner-shape: round;
background: transparent;
color: var(--dsw-alias-label-primary);
font: inherit;
font-size: 13px;
line-height: 18px;
cursor: pointer;
transition: background-color 120ms ease, border-color 120ms ease, color 120ms ease;
}
.chip:hover:not(:disabled) {
background: var(--dsw-alias-interactive-bg-hover);
color: var(--dsw-alias-label-primary);
}
.chip:disabled {
cursor: default;
opacity: 0.4;
}
.chip:focus-visible {
outline: 2px solid var(--dsw-alias-button-primary-fill);
outline-offset: 2px;
}
.chipActive,
.chipActive:hover:not(:disabled) {
border-color: var(--dsw-alias-button-primary-fill);
background: var(--dsw-alias-button-primary-fill);
color: var(--dsw-alias-label-primary-foreground);
}
/* The field starts at three short lines, grows with its text where supported,
and scrolls after the cap. */
.detail {
display: block;
width: 100%;
min-height: 116px;
max-height: 280px;
box-sizing: border-box;
margin-top: 18px;
padding: 12px 14px;
border: 0.5px solid var(--dsw-alias-border-l4);
border-radius: 16px;
background: var(--dsw-alias-bg-layer-1);
color: var(--dsw-alias-label-primary);
font: inherit;
font-size: 14px;
line-height: 22px;
field-sizing: content;
resize: none;
transition: border-color 120ms ease, box-shadow 120ms ease;
}
.detail::placeholder {
color: var(--dsw-alias-label-caption);
}
.detail:focus {
outline: none;
border-color: var(--dsw-alias-border-l3);
box-shadow: 0 0 0 1px var(--dsw-alias-border-l3);
}
.failure {
display: block;
margin-top: 8px;
color: var(--dsw-alias-label-tertiary);
font-size: 13px;
line-height: 20px;
}
.submit {
width: 100%;
height: 44px;
border-radius: 18px;
font-size: 14px;
font-weight: 500;
}
/* The design's ringed green check, not the warning tint the Toast icon seat defaults to. */
.toastIcon {
display: grid;
place-items: center;
width: 18px;
height: 18px;
border: 1.5px solid var(--dsw-alias-state-success-primary);
border-radius: 50%;
corner-shape: round;
color: var(--dsw-alias-state-success-primary);
}
@media (prefers-reduced-motion: reduce) {
.chip,
.detail {
transition: none;
}
}
@@ -0,0 +1,113 @@
/**
* The feedback dialog and its acknowledgement toast, rendered as one entry
* of `conversation.input.overlay` so each Session owns exactly one of each.
* The Modal and the Toast both portal to `document.body`; the overlay slot
* only supplies the per-session controller and the composer card the toast
* centers over.
* @module @deepseek-ai/dsh-client-ui-message-feedback/client/FeedbackDialog
*/
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
import { Button, IconCheckOutline16, Modal, Toast } from '@deepseek-ai/dsh-client-ui-primitives'
import type { FeedbackCategory } from '@deepseek-ai/dsh-command-feedback/types'
import type { FeedbackDialogProps } from './slots.ts'
import css from './FeedbackDialog.module.css'
/**
* The chips in presentation order. A client bundle may not import a Host
* package's values, so the taxonomy is restated as a complete record of the
* `FeedbackCategory` union: a missing or foreign id is a compile error.
*/
const CATEGORY_CHIPS = {
'task-result': true,
'instruction-following': true,
'product-interaction': true,
'service-stability': true,
'resource-cost': true,
'security-privacy-permission': true,
'other': true,
} satisfies Record<FeedbackCategory, true>
const CATEGORIES = Object.keys(CATEGORY_CHIPS) as FeedbackCategory[]
/** Failure codes with their own copy; every other code reads the generic line. */
const FAILURE_COPY: Partial<Record<string, 'error.conflict' | 'error.noteTooLarge'>> = {
'version-conflict': 'error.conflict',
'note-too-large': 'error.noteTooLarge',
}
/**
* Render one Session's feedback dialog and toast.
* @param props - the dialog hook, the draft verbs, and the locale seat.
* @returns the modal while a target is open, the toast while one is showing.
*/
export function FeedbackDialog({ useDialog, edit, submit, dismiss, dismissToast, t }: FeedbackDialogProps) {
const state = useDialog(s => s)
// The toast centers over the composer card this entry renders inside of.
const probeRef = useRef<HTMLSpanElement>(null)
const [card, setCard] = useState<HTMLElement | null>(null)
useLayoutEffect(() => {
setCard(probeRef.current?.closest<HTMLElement>('[data-composer-card]') ?? null)
}, [])
const toast = state.toast
const onToastDone = useCallback(() => { dismissToast(toast) }, [dismissToast, toast])
// A toast retires with the entry that showed it: the Toast's own timer dies
// on unmount, and the Session's controller must not replay it on return.
useEffect(() => () => { dismissToast(toast) }, [dismissToast, toast])
const failure = state.failure === null ? null : t(FAILURE_COPY[state.failure] ?? 'error.generic')
return (
<>
<span ref={probeRef} hidden />
{toast > 0 && (
<Toast
key={toast}
text={t('toast.recorded')}
icon={<span className={css.toastIcon}><IconCheckOutline16 size={12} /></span>}
anchor={card}
onDone={onToastDone}
/>
)}
<Modal
open={state.target !== null}
title={t('dialog.title')}
closeLabel={t('close')}
onClose={dismiss}
className={css.dialog as string}
footer={(
<Button
variant="primary"
className={css.submit}
disabled={state.submitting}
onClick={() => { void submit() }}
>
{state.submitting ? t('submitting') : t('submit')}
</Button>
)}
>
<div className={css.categories} role="group" aria-label={t('dialog.categories')}>
{CATEGORIES.map(category => (
<button
key={category}
type="button"
className={state.category === category ? `${css.chip} ${css.chipActive}` : css.chip}
aria-pressed={state.category === category}
disabled={state.submitting}
onClick={() => { edit({ category: state.category === category ? null : category }) }}
>
{t(`category.${category}`)}
</button>
))}
</div>
<textarea
className={css.detail}
aria-label={t('dialog.detail')}
placeholder={t('dialog.hint')}
value={state.text}
readOnly={state.submitting}
onChange={(event) => { edit({ text: event.target.value }) }}
/>
{failure !== null && <span className={css.failure} role="status">{failure}</span>}
</Modal>
</>
)
}
@@ -35,109 +35,7 @@
/* A recorded rating stays legible without hover, so the signal survives a
pointer leaving the row. */
.action[data-active] {
color: var(--dsw-alias-label-primary);
}
.noteOpen {
max-width: 220px;
overflow: hidden;
padding: 0 8px;
border: none;
border-radius: 14px;
background: transparent;
color: var(--dsw-alias-label-tertiary);
font-size: var(--dsh-content-font-size-secondary, 13px);
line-height: calc(28px + var(--dsh-content-font-delta, 0px));
white-space: nowrap;
text-overflow: ellipsis;
cursor: pointer;
}
.noteOpen:hover,
.noteOpen[aria-expanded='true'] {
background: var(--dsw-alias-interactive-bg-hover);
color: var(--dsw-alias-label-secondary);
}
/* Portal surface: fixed in the viewport, left/top supplied inline from the
trigger rect. Portaled panels must layer above modal overlays (z 1000). */
.notePanel {
position: fixed;
z-index: 1100;
box-sizing: border-box;
width: 320px;
max-width: min(360px, calc(100vw - 24px));
/* The width bound's counterpart. `resize: vertical` on the textarea lets the
panel be dragged taller, and a panel taller than the viewport would push
the placement clamp's upper bound below its own margin, so `top` would go
negative and cut off the panel's head. Both bounds keep the 12px margin
the clamp uses. */
max-height: calc(100vh - 24px);
overflow-y: auto;
padding: 8px;
display: flex;
flex-direction: column;
gap: 8px;
border: 0;
border-radius: 12px;
background: var(--dsw-specific-menu);
--dsw-elevation-stroke-color: var(--dsw-alias-border-l1);
box-shadow: var(--dsw-elevation-prominent);
--dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2);
--dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2);
}
.noteInput {
width: 100%;
box-sizing: border-box;
padding: 6px 8px;
border: 0.5px solid var(--dsw-alias-border-l4);
border-radius: 8px;
background: var(--dsw-alias-bg-layer-1);
color: var(--dsw-alias-label-primary);
font: inherit;
font-size: 13px;
resize: vertical;
}
.noteActions {
display: flex;
justify-content: flex-end;
gap: 6px;
}
.noteSave,
.noteCancel {
height: 28px;
padding: 0 10px;
border: none;
border-radius: 14px;
font-size: 13px;
cursor: pointer;
}
.noteSave {
background: var(--dsw-alias-button-primary-fill);
color: var(--dsw-alias-label-primary-foreground);
}
.noteSave:hover:not(:disabled) {
background: var(--dsw-alias-button-primary-hover);
}
.noteSave:disabled {
cursor: default;
opacity: 0.4;
}
.noteCancel {
background: transparent;
color: var(--dsw-alias-label-tertiary);
}
.noteCancel:hover {
background: var(--dsw-alias-interactive-bg-hover);
color: var(--dsw-alias-label-secondary);
}
.failure {
@@ -1,64 +1,36 @@
/**
* Per-message feedback controls: a Like/Dislike pair plus an optional note.
* The buttons render inside the assistant message's IconActions row, so they
* reuse that row's chrome and sit between copy and branch. The note editor is
* a popover (portaled to `document.body`) anchored to the note trigger, not an
* inline expansion: a 260px textarea plus buttons cannot fit the row at any
* viewport, and an inline element pushed the branch action and clock out of the
* conversation column. Portaling out of the column also escapes its `overflow`
* clip, so the panel cannot be cropped or detached from the message it annotates.
* Per-message feedback controls: the Like/Dislike pair inside the assistant
* message's IconActions row, between copy and branch. Like records at once
* and raises the Session's acknowledgement toast; Dislike opens the Session's
* feedback dialog, whose submission records the negative judgment with its
* category and text. Clicking the recorded rating retracts it. A recorded
* rating shows the filled glyph so the signal survives a pointer leaving the row.
* @module @deepseek-ai/dsh-client-ui-message-feedback/client/MessageFeedbackActions
*/
import { useCallback, useEffect, useRef, useState } from 'react'
import {
useCallback, useEffect, useRef, useState,
type CSSProperties,
} from 'react'
import { createPortal } from 'react-dom'
import {
IconDislikeOutline16, IconLikeOutline16, Tooltip, useAnchoredPosition,
IconDislikeFill16, IconDislikeOutline16, IconLikeFill16, IconLikeOutline16, Tooltip,
} from '@deepseek-ai/dsh-client-ui-primitives'
import type { MessageFeedbackRating } from '@deepseek-ai/dsh-message-feedback/types'
import type { MessageFeedbackActionFailure } from './controller.ts'
import type { MessageFeedbackActionProps } from './slots.ts'
import css from './MessageFeedbackActions.module.css'
/** Safe distance kept between the panel and the viewport edges (the Menu portal margin). */
const PANEL_MARGIN = 12
/** Distance between the trigger's bottom edge and the panel's top. */
const PANEL_GAP = 4
/**
* Unplaced portal panel: hidden but laid out so `offsetWidth` is real for the
* clamp. The explicit insets match `Menu`'s measure style — a `position: fixed`
* element with auto insets otherwise sits at its static position, a different
* origin than the one the first placement measures from.
*/
const MEASURE_STYLE: CSSProperties = { visibility: 'hidden', left: 0, top: 0 }
/**
* One message's feedback controls.
* @param props - the owner's message identity, the injected verbs, and the
* shared feedback hook.
* @returns the rating buttons and the note trigger, with the note editor
* portal-open beneath the trigger while it is open.
* @returns the rating buttons with any failure notice beside them.
*/
export function MessageFeedbackActions({ messageId, ensure, rate, toggle, clearNote, useFeedback, t }: MessageFeedbackActionProps) {
export function MessageFeedbackActions({
messageId, ensure, current, toggle, openDialog, acknowledge, useFeedback, t,
}: MessageFeedbackActionProps) {
const item = useFeedback(view => view.items.get(messageId))
const loadFailed = useFeedback(view => view.status === 'error')
const rating = item?.rating
const [noteOpen, setNoteOpen] = useState(false)
const [draft, setDraft] = useState('')
const [pending, setPending] = useState(false)
// A rating or load failure surfaces beside the rating buttons, always legible
// whether or not the note popover is open.
const [rowFailure, setRowFailure] = useState<string | null>(null)
// A note save failure surfaces inside the note popover, where the human is
// looking; it stays open so the draft survives to be corrected.
const [noteFailure, setNoteFailure] = useState<string | null>(null)
const triggerRef = useRef<HTMLButtonElement>(null)
const panelRef = useRef<HTMLDivElement>(null)
const inputRef = useRef<HTMLTextAreaElement>(null)
// A rating or load failure surfaces beside the rating buttons.
const [failure, setFailure] = useState<string | null>(null)
// The controls mount for every settled message in the transcript, so the
// Session's feedback is read once on first hover/focus rather than on mount.
const seeded = useRef(false)
@@ -71,158 +43,47 @@ export function MessageFeedbackActions({ messageId, ensure, rate, toggle, clearN
const alive = useRef(true)
useEffect(() => () => { alive.current = false }, [])
/** Bumped whenever an editing session ends, so a late save can tell it is stale. */
const noteGeneration = useRef(0)
/** Current panel open-state, readable from a stale closure via a ref. */
const noteOpenRef = useRef(false)
useEffect(() => { noteOpenRef.current = noteOpen }, [noteOpen])
const errorCopy = useCallback((result: { ok: boolean; error?: { code: string } }) => {
return result.error?.code === 'version-conflict' ? t('error.conflict') : t('error.generic')
const errorCopy = useCallback((result: MessageFeedbackActionFailure) => {
return result.error.code === 'version-conflict' ? t('error.conflict') : t('error.generic')
}, [t])
const settleRating = useCallback((result: { ok: boolean; error?: { code: string } }) => {
if (!alive.current) return
setPending(false)
setRowFailure(result.ok ? null : errorCopy(result))
}, [errorCopy])
const closeNote = useCallback(() => {
// Ends the editing session, so any save still in flight becomes stale.
noteGeneration.current += 1
setNoteOpen(false)
}, [])
const onRate = useCallback((next: MessageFeedbackRating) => {
// The controller decides record-vs-retract from the committed item, so a
// click that lands before the first list read still toggles the stored
// value; the reply says which happened, and only a recording is acknowledged.
const onLike = useCallback(() => {
setPending(true)
setRowFailure(null)
// The controller decides retract-vs-replace from the committed item, so a
// click that lands before the first list read still toggles the stored
// value instead of this render's empty view.
closeNote()
void toggle(messageId, next).then(settleRating)
}, [closeNote, messageId, settleRating, toggle])
// The rating is a parameter because only the note editor's render site can
// prove one is recorded; that removes an unreachable undefined guard here.
const onSaveNote = useCallback((current: MessageFeedbackRating) => {
const trimmed = draft.trim()
setPending(true)
setNoteFailure(null)
// A save belongs to the editing session that started it. Closing and
// reopening the panel begins a new one, and a late reply from the old
// session must not act on it: a stale success would shut the panel the
// human just opened, and a stale failure would describe a draft this
// session never sent.
const generation = noteGeneration.current
// What a session reopened before this save commits would be seeded with.
const staleSeed = item?.note ?? ''
// An emptied editor removes the note explicitly; `rate` alone preserves a
// stored note, so it cannot express deletion.
const settled = trimmed.length === 0
? clearNote(messageId)
: rate(messageId, current, trimmed)
void settled.then((result) => {
setFailure(null)
void toggle(messageId, 'positive').then((result) => {
if (!alive.current) return
// `pending` tracks the request in flight, not the editing session, so it
// is released either way; all three of like, dislike and Save read
// `disabled={pending}`, and holding it would lock the row until remount.
// Releasing it unconditionally is safe because those three are the only
// mutation entries and each is gated by it, so at most one request is ever
// in flight. A future entry that bypasses the gate would have to bind
// `pending` to the generation instead of clearing it here.
setPending(false)
if (result.ok) {
// Only the session that is still open may act on a success: closing it
// already discarded the draft, and reopening seeded a new one.
if (generation === noteGeneration.current) {
setNoteFailure(null)
setNoteOpen(false)
return
}
// A newer session is open, seeded from the note as it read before this
// save committed. Resync it so the editor shows what is stored and the
// next save cannot overwrite the text that just landed. An edited draft
// is the human's, so it is left alone.
setDraft(draftNow => (draftNow === staleSeed ? trimmed : draftNow))
if (!result.ok) {
setFailure(errorCopy(result))
return
}
// A failure from the session still on screen belongs in its panel. One
// from an abandoned session is reported only when no new session has
// taken over: the row then carries it, so a save that failed after the
// human walked away is not silently dropped. Writing it into a reopened
// panel instead would label the new draft with the old attempt's error.
// `noteOpenRef` — not the `noteOpen` this closure was created from — is
// read here, because a close+reopen between the save and resolution
// leaves this closure with the panel state from when the save started.
if (generation === noteGeneration.current || !noteOpenRef.current) {
setNoteFailure(errorCopy(result))
}
if (result.rating === 'positive') acknowledge()
})
}, [clearNote, draft, errorCopy, item?.note, messageId, noteOpenRef, rate])
}, [acknowledge, errorCopy, messageId, toggle])
// The trigger toggles: while closed it opens the popover (seeding the draft
// with the recorded note), while open it closes it. Toggling closed via the
// trigger also fires the outside/within logic correctly because the trigger
// is inside the panel's "inside" region.
const toggleNote = useCallback(() => {
if (noteOpen) {
closeNote()
return
}
setDraft(item?.note ?? '')
// A note-save failure belongs to the editing session that produced it. The
// panel stays open on failure so the draft can be corrected, but once it is
// closed and reopened the draft is reseeded from the stored note, so a
// carried-over error would describe an attempt the new draft never made.
// A failure that arrives after the panel closed is reported in the row, and
// clearing it here is what retires that notice when a new session starts.
setNoteFailure(null)
setNoteOpen(true)
}, [noteOpen, closeNote, item?.note])
// Place the portaled panel from the trigger rect before paint and keep it
// with the trigger on scroll/resize, the same anchoring `Menu` uses for its
// portal mode.
const pos = useAnchoredPosition({
open: noteOpen,
anchorRef: triggerRef,
panelRef,
gap: PANEL_GAP,
margin: PANEL_MARGIN,
})
// Focus the input and close on Escape or outside pointer-down while open.
useEffect(() => {
if (!noteOpen) return
inputRef.current?.focus()
const onPointerDown = (e: PointerEvent) => {
if (!(e.target instanceof Node)) return
if (triggerRef.current?.contains(e.target) === true) return
if (panelRef.current?.contains(e.target) === true) return
closeNote()
}
const onKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') closeNote()
}
document.addEventListener('pointerdown', onPointerDown)
document.addEventListener('keydown', onKeyDown)
return () => {
document.removeEventListener('pointerdown', onPointerDown)
document.removeEventListener('keydown', onKeyDown)
}
}, [noteOpen, closeNote])
// Return focus to the trigger only when the panel actually closes, not on the
// initial mount (a freshly rendered message with a recorded rating must not
// pull focus into its action row).
const wasOpen = useRef(false)
useEffect(() => {
if (noteOpen) { wasOpen.current = true; return }
if (wasOpen.current) triggerRef.current?.focus()
wasOpen.current = false
}, [noteOpen])
// A recorded Dislike retracts on click; otherwise the dialog collects the
// reason and records the judgment on submit. The decision waits for the
// seeding read, so a click on a cold row still sees the stored judgment.
const onDislike = useCallback(() => {
setPending(true)
setFailure(null)
void ensure().then((loaded) => {
if (!alive.current) return
if (!loaded.ok || current(messageId)?.rating !== 'negative') {
setPending(false)
openDialog(messageId)
return
}
void toggle(messageId, 'negative').then((result) => {
if (!alive.current) return
setPending(false)
if (!result.ok) setFailure(errorCopy(result))
})
})
}, [current, ensure, errorCopy, messageId, openDialog, toggle])
const likeLabel = rating === 'positive' ? t('action.likeActive') : t('action.like')
const dislikeLabel = rating === 'negative' ? t('action.dislikeActive') : t('action.dislike')
@@ -239,9 +100,9 @@ export function MessageFeedbackActions({ messageId, ensure, rate, toggle, clearN
disabled={pending}
onFocus={seed}
onPointerEnter={seed}
onClick={() => { onRate('positive') }}
onClick={onLike}
>
<IconLikeOutline16 />
{rating === 'positive' ? <IconLikeFill16 /> : <IconLikeOutline16 />}
</button>
</Tooltip>
<Tooltip label={dislikeLabel} side="bottom">
@@ -254,71 +115,15 @@ export function MessageFeedbackActions({ messageId, ensure, rate, toggle, clearN
disabled={pending}
onFocus={seed}
onPointerEnter={seed}
onClick={() => { onRate('negative') }}
onClick={onDislike}
>
<IconDislikeOutline16 />
{rating === 'negative' ? <IconDislikeFill16 /> : <IconDislikeOutline16 />}
</button>
</Tooltip>
{rating !== undefined && (
<button
ref={triggerRef}
type="button"
className={css.noteOpen}
aria-haspopup="dialog"
aria-expanded={noteOpen}
onClick={toggleNote}
>
{item?.note === undefined ? t('note.open') : item.note}
</button>
)}
{rowFailure === null && loadFailed && (
{failure === null && loadFailed && (
<span className={css.failure} role="status">{t('error.load')}</span>
)}
{rowFailure !== null && <span className={css.failure} role="status">{rowFailure}</span>}
{/* A note-save failure normally lives inside the panel, beside the buttons
that produced it. Whenever the panel is not on screen it falls back to
the row instead: the rating may have disappeared underneath an open
editor (another client retracts the feedback, a `version-conflict`
reply commits `current: null`, the item goes away), or the human may
have closed the panel before a slow save came back. Either way the row
reports that the save did not land rather than dropping it. */}
{!(rating !== undefined && noteOpen) && noteFailure !== null && (
<span className={css.failure} role="status">{noteFailure}</span>
)}
{rating !== undefined && noteOpen && createPortal(
<div
ref={panelRef}
className={css.notePanel}
role="dialog"
aria-label={t('note.dialog')}
style={pos ?? MEASURE_STYLE}
>
<textarea
ref={inputRef}
className={css.noteInput}
aria-label={t('note.aria')}
placeholder={t('note.placeholder')}
value={draft}
rows={3}
onChange={(event) => { setDraft(event.target.value) }}
/>
<div className={css.noteActions}>
<button
type="button"
className={css.noteSave}
disabled={pending}
onClick={() => { onSaveNote(rating) }}
>
{t('note.save')}
</button>
<button type="button" className={css.noteCancel} onClick={closeNote}>
{t('note.cancel')}
</button>
</div>
{noteFailure !== null && <span className={css.failure} role="status">{noteFailure}</span>}
</div>,
document.body,
)}
{failure !== null && <span className={css.failure} role="status">{failure}</span>}
</>
)
}
@@ -11,6 +11,7 @@ import type { Context as ClientContext } from '@deepseek-ai/cordis'
import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots'
import type { MessageId } from '@deepseek-ai/dsh-api-remotes/client'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import type { FeedbackRecord } from '@deepseek-ai/dsh-command-feedback/types'
import type {
MessageFeedbackItem,
MessageFeedbackRating,
@@ -28,10 +29,19 @@ export interface MessageFeedbackView {
error: string | null
}
/** Rejected branch shared by every settled action. */
export interface MessageFeedbackActionFailure {
ok: false
error: { code: string; message: string }
}
/** Settled action shape rendered by the message-level controls. */
export type MessageFeedbackActionResult =
| { ok: true }
| { ok: false; error: { code: string; message: string } }
export type MessageFeedbackActionResult = { ok: true } | MessageFeedbackActionFailure
/** A settled toggle, carrying the rating now committed so the control can tell a record from a retraction. */
export type MessageFeedbackToggleResult =
| { ok: true; rating: MessageFeedbackRating | null }
| MessageFeedbackActionFailure
// `Object.freeze` does not protect a Map: `set`/`delete` write internal slots,
// not properties. Immutability here is by discipline instead — the view type is
@@ -47,13 +57,17 @@ const INITIAL_VIEW: MessageFeedbackView = Object.freeze({
const OK: MessageFeedbackActionResult = Object.freeze({ ok: true })
const DISPOSED: MessageFeedbackActionResult = Object.freeze({
const DISPOSED: MessageFeedbackActionFailure = Object.freeze({
ok: false,
error: Object.freeze({ code: 'disposed', message: 'feedback controller is disposed' }),
})
/** Human-readable text for one business failure code. */
function describe(code: string): string {
/**
* Human-readable text for one business failure code.
* @param code - the Host's business failure code.
* @returns the developer-facing description carried in the failure branch.
*/
export function describe(code: string): string {
switch (code) {
case 'session-not-found': return 'this session is no longer persisted'
case 'target-not-found': return 'this message is not a persisted assistant message'
@@ -65,12 +79,12 @@ function describe(code: string): string {
}
/** Build the rejected branch for one business failure code. */
function fail(code: string): MessageFeedbackActionResult {
function fail(code: string): MessageFeedbackActionFailure {
return { ok: false, error: { code, message: describe(code) } }
}
/** Carrier failure rendered with the Host-supplied code and message. */
function carrierFailure(error: { code: string; message: string }): MessageFeedbackActionResult {
function carrierFailure(error: { code: string; message: string }): MessageFeedbackActionFailure {
return { ok: false, error: { code: error.code, message: error.message } }
}
@@ -143,26 +157,21 @@ export class MessageFeedbackController implements HostObservable<MessageFeedback
/**
* Create or replace feedback for one message, comparing against the version
* this controller last observed.
*
* The note is resolved here rather than by the caller: `mutate` awaits the
* one list read first, so this body always sees the committed item, while a
* control that rendered before that read completed would still be holding
* `undefined`. Omitting `note` therefore keeps whatever is stored; only
* {@link clearNote} removes one.
* this controller last observed. The item stores exactly `entry`: an entry
* without a note or category replaces whatever the stored item carried.
* @param messageId - target assistant message.
* @param rating - desired judgment.
* @param note - replacement explanation; omitted keeps the stored note.
* @param entry - explanation and category to store with the judgment.
* @returns the settled mutation result.
*/
rate(
messageId: MessageId,
rating: MessageFeedbackRating,
note?: string,
entry: FeedbackRecord = {},
): Promise<MessageFeedbackActionResult> {
return this.mutate(async () => {
const observed = this.view.items.get(messageId)
return await this.putCommitted(messageId, rating, note ?? observed?.note, observed)
return await this.putCommitted(messageId, rating, entry, observed)
})
}
@@ -171,43 +180,20 @@ export class MessageFeedbackController implements HostObservable<MessageFeedback
* the committed rating already matches. The decision reads the committed item
* inside the serialized mutation, so a click that lands before the first list
* read still toggles against the stored value rather than the empty view a
* cold control rendered.
* cold control rendered. A replacement stores the bare judgment; the note
* and category of the judgment it replaces do not carry over.
* @param messageId - target assistant message.
* @param rating - the judgment the human asked for.
* @returns the settled mutation result.
* @returns the settled mutation result with the rating now committed.
*/
toggle(messageId: MessageId, rating: MessageFeedbackRating): Promise<MessageFeedbackActionResult> {
toggle(messageId: MessageId, rating: MessageFeedbackRating): Promise<MessageFeedbackToggleResult> {
return this.mutate(async () => {
const observed = this.view.items.get(messageId)
if (observed?.rating === rating) return await this.deleteCommitted(messageId, observed)
return await this.putCommitted(messageId, rating, observed?.note, observed)
})
}
/**
* Drop the note while keeping the rating. Absent feedback needs no call.
* @param messageId - target assistant message.
* @returns the settled mutation result.
*/
clearNote(messageId: MessageId): Promise<MessageFeedbackActionResult> {
return this.mutate(async () => {
const observed = this.view.items.get(messageId)
if (observed === undefined || observed.note === undefined) return OK
return await this.putCommitted(messageId, observed.rating, undefined, observed)
})
}
/**
* Remove feedback for one message. A message with no known item is already
* in the requested state, so no call is made.
* @param messageId - target assistant message.
* @returns the settled mutation result.
*/
clear(messageId: MessageId): Promise<MessageFeedbackActionResult> {
return this.mutate(async () => {
const observed = this.view.items.get(messageId)
if (observed === undefined) return OK
return await this.deleteCommitted(messageId, observed)
const retract = observed?.rating === rating
const result = retract
? await this.deleteCommitted(messageId, observed)
: await this.putCommitted(messageId, rating, {}, observed)
return result.ok ? { ok: true, rating: retract ? null : rating } : result
})
}
@@ -215,14 +201,15 @@ export class MessageFeedbackController implements HostObservable<MessageFeedback
private async putCommitted(
messageId: MessageId,
rating: MessageFeedbackRating,
note: string | undefined,
entry: FeedbackRecord,
observed: MessageFeedbackItem | undefined,
): Promise<MessageFeedbackActionResult> {
const carried = await this.ctx.remote.messageFeedback.put({
sessionId: this.sessionId,
messageId,
rating,
...(note === undefined ? {} : { note }),
...(entry.text === undefined ? {} : { note: entry.text }),
...(entry.category === undefined ? {} : { category: entry.category }),
ifVersion: observed?.version ?? null,
})
if (!carried.ok) return carrierFailure(carried.error)
@@ -284,11 +271,11 @@ export class MessageFeedbackController implements HostObservable<MessageFeedback
* Serialize one mutation behind this Session's prior mutation so queued
* operations always compare against the committed version.
*/
private mutate(
operation: () => Promise<MessageFeedbackActionResult>,
private mutate<T>(
operation: () => Promise<T>,
options: { readonly seed?: boolean } = {},
): Promise<MessageFeedbackActionResult> {
const guarded = async (): Promise<MessageFeedbackActionResult> => {
): Promise<T | MessageFeedbackActionFailure> {
const guarded = async (): Promise<T | MessageFeedbackActionFailure> => {
if (this.disposed) return DISPOSED
if (options.seed !== false) {
const loaded = await this.ensure()
@@ -0,0 +1,129 @@
/**
* Headless state of one Session's feedback dialog and its acknowledgement
* toast. One form serves two targets: the Session itself (a bare `/feedback`)
* and one assistant message (Dislike). The overlay view renders from the
* store; the message controls raise the toast after a Like through
* {@link FeedbackDialogController.acknowledge}.
* @module @deepseek-ai/dsh-client-ui-message-feedback/client/dialog
*/
import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store'
import type { MessageId } from '@deepseek-ai/dsh-api-remotes/client'
import type { FeedbackCategory, FeedbackRecord } from '@deepseek-ai/dsh-command-feedback/types'
import type { MessageFeedbackActionResult } from './controller.ts'
/** What one open dialog submits to. */
export type FeedbackDialogTarget =
| { readonly kind: 'session' }
| { readonly kind: 'message'; readonly messageId: MessageId }
/** Dialog and toast state the overlay view renders from. */
export interface FeedbackDialogState {
/** Target the dialog is open for; null while closed. */
readonly target: FeedbackDialogTarget | null
readonly category: FeedbackCategory | null
readonly text: string
/** A submission is in flight; the form ignores edits and submits until it settles. */
readonly submitting: boolean
/** Failure code of the last submission from this open; null when none. */
readonly failure: string | null
/** Sequence of the acknowledgement toast on screen; 0 while none. */
readonly toast: number
}
/**
* Record one submission against its target.
* @param target - the open target.
* @param entry - the trimmed text and the category, each present only when given.
*/
export type FeedbackSubmit = (target: FeedbackDialogTarget, entry: FeedbackRecord) => Promise<MessageFeedbackActionResult>
const CLOSED: Omit<FeedbackDialogState, 'toast'> = {
target: null, category: null, text: '', submitting: false, failure: null,
}
/** Per-session dialog controller; one instance backs the overlay entry and every message control. */
export class FeedbackDialogController {
/** Dialog state store (the overlay entry subscribes here). */
readonly state: SnapshotStore<FeedbackDialogState> = createSnapshotStore<FeedbackDialogState>({ ...CLOSED, toast: 0 })
/** Bumped by every open, dismiss, and dispose so a late settlement can tell its draft is gone. */
private generation = 0
private toastSeq = 0
/**
* @param submit - records one submission; the owner routes it by target.
*/
constructor(private readonly submit: FeedbackSubmit) {}
/**
* Open the dialog with an empty draft, replacing any open draft.
* @param target - what the submission records against.
*/
open(target: FeedbackDialogTarget): void {
this.generation += 1
this.state.set({ ...CLOSED, target, toast: this.state.getSnapshot().toast })
}
/** Close the dialog and discard the draft; a toast on screen stays. */
dismiss(): void {
this.generation += 1
this.state.set({ ...CLOSED, toast: this.state.getSnapshot().toast })
}
/**
* Replace part of the draft while it is editable.
* @param draft - the category (null clears it) or the text as typed.
*/
edit(draft: Partial<Pick<FeedbackDialogState, 'category' | 'text'>>): void {
const s = this.state.getSnapshot()
if (s.target === null || s.submitting) return
this.state.set({ ...s, ...draft })
}
/**
* Submit the draft; an empty draft is a valid submission. Success closes the
* dialog and raises the toast; a failure keeps the dialog open with its code.
* @returns after the submission settles.
*/
async submitDraft(): Promise<void> {
const s = this.state.getSnapshot()
if (s.target === null || s.submitting) return
const generation = this.generation
this.state.set({ ...s, submitting: true, failure: null })
const text = s.text.trim()
const result = await this.submit(s.target, {
...(text.length === 0 ? {} : { text }),
...(s.category === null ? {} : { category: s.category }),
})
if (result.ok) {
// The remark is recorded whichever draft is on screen now, so the toast
// always shows; only the draft that produced it closes.
if (generation === this.generation) this.dismiss()
this.acknowledge()
return
}
if (generation !== this.generation) return
this.state.set({ ...this.state.getSnapshot(), submitting: false, failure: result.error.code })
}
/** Show the acknowledgement toast; a toast already on screen restarts. */
acknowledge(): void {
this.toastSeq += 1
this.state.set({ ...this.state.getSnapshot(), toast: this.toastSeq })
}
/**
* Retire one toast after its fade; a newer toast is left alone.
* @param seq - the toast sequence the view finished showing.
*/
dismissToast(seq: number): void {
const s = this.state.getSnapshot()
if (s.toast === seq) this.state.set({ ...s, toast: 0 })
}
/** Scope-teardown disposer: drop the draft and the toast, orphan in-flight work. */
dispose(): void {
this.generation += 1
this.state.set({ ...CLOSED, toast: 0 })
}
}
@@ -1,9 +1,9 @@
/**
* Message feedback plugin, browser half: the Like/Dislike entry in the
* conversation.chat.assistant-actions strip. One MessageFeedbackController per
* Session backs every message control in that Session, so a single list read
* seeds the whole transcript. Mutations go through the generated
* messageFeedback Remote; the Host owns per-item compare-and-set.
* Feedback surface plugin, browser half: the Like/Dislike entry in the
* conversation.chat.assistant-actions strip, the feedback dialog and its
* acknowledgement toast in conversation.input.overlay, and the `/feedback`
* decoration that opens the dialog from the composer menu or a bare typed
* command. One FeedbackSurface per Session backs every entry in that Session.
* @module @deepseek-ai/dsh-client-ui-message-feedback/client
*/
@@ -11,79 +11,110 @@ import type { Context as ClientContext } from '@deepseek-ai/cordis'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
// Type-only: pulls the generated Remote API and ctx.remote merge through the Client assembly boundary.
import type {} from '@deepseek-ai/dsh-api-remotes/client'
// Type-only: pulls the ui-conversation SlotMap merge (the assistant-actions entry).
// Type-only: pulls the ui-conversation SlotMap merge (the assistant-actions and overlay entries).
import type {} from '@deepseek-ai/dsh-client-ui-conversation/client'
// Type-only: pulls the command UI's Context merge (ctx.commandUi).
import type {} from '@deepseek-ai/dsh-client-ui-commands/client'
// Type-only: pulls the locale plugin's Context merge (ctx.locale).
import type {} from '@deepseek-ai/dsh-client-locale/client'
// Type-only: pulls the SlotRegistry service merge (ctx.slots).
import type {} from '@deepseek-ai/dsh-client-ui-renderer/client'
import type {} from '@deepseek-ai/dsh-client-ui-chat/client'
import type {} from '@deepseek-ai/dsh-client-ui-session/client'
import { MessageFeedbackController } from './controller.ts'
import { FeedbackDialog } from './FeedbackDialog.tsx'
import { MessageFeedbackActions } from './MessageFeedbackActions.tsx'
import type { MessageFeedbackInjected } from './slots.ts'
import type { FeedbackDialogInjected, MessageFeedbackInjected } from './slots.ts'
import { FeedbackSurface } from './surface.ts'
import { en, zh } from './locales.ts'
export type {
MessageFeedbackActionResult, MessageFeedbackStatus, MessageFeedbackView,
MessageFeedbackActionFailure, MessageFeedbackActionResult, MessageFeedbackStatus,
MessageFeedbackToggleResult, MessageFeedbackView,
} from './controller.ts'
export type { MessageFeedbackActionProps, MessageFeedbackInjected } from './slots.ts'
export type { FeedbackDialogState, FeedbackDialogTarget, FeedbackSubmit } from './dialog.ts'
export type {
FeedbackDialogInjected, FeedbackDialogProps, MessageFeedbackActionProps, MessageFeedbackInjected,
} from './slots.ts'
export type { MessageFeedbackKey } from './locales.ts'
/** Dictionary namespace owned by this plugin. */
const NS = 'feedback'
/** Required services: the slot registry, the Remote namespace, and the copy. */
export const inject = ['slots', 'remote', 'remote.messageFeedback', 'locale']
/** Required services: the slot registry, the two Remote namespaces, and the copy. */
export const inject = ['slots', 'remote', 'remote.messageFeedback', 'remote.sessionFeedback', 'locale']
/**
* Client plugin body: the per-message feedback entry and its per-session
* object layer.
* Client plugin body: the per-message feedback entry, the Session's dialog
* entry, the `/feedback` decoration, and their per-session surfaces.
* @param ctx - client root context.
*/
export function apply(ctx: ClientContext): void {
ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'ui-message-feedback: dictionaries')
const controllers = new Map<SessionId, MessageFeedbackController>()
const controllerFor = (sessionId: SessionId): MessageFeedbackController => {
let controller = controllers.get(sessionId)
if (controller === undefined) {
controller = new MessageFeedbackController(ctx, sessionId)
controllers.set(sessionId, controller)
const surfaces = new Map<SessionId, FeedbackSurface>()
const surfaceFor = (sessionId: SessionId): FeedbackSurface => {
let surface = surfaces.get(sessionId)
if (surface === undefined) {
surface = new FeedbackSurface(ctx, sessionId)
surfaces.set(sessionId, surface)
}
return controller
return surface
}
ctx.effect(() => () => {
for (const surface of surfaces.values()) surface.dispose()
surfaces.clear()
}, 'ui-message-feedback: per-session surfaces')
// A reconnect can only invalidate what was already read; a cold Session
// stays cold until something asks for it.
ctx.on('connection/reset', () => {
for (const controller of controllers.values()) {
if (controller.getSnapshot().status !== 'cold') void controller.resync()
for (const { feedback } of surfaces.values()) {
if (feedback.getSnapshot().status !== 'cold') void feedback.resync()
}
})
ctx.slots.inject('conversation.chat.assistant-actions', () => {
const dispose = ctx.slots.register({
name: 'conversation.chat.assistant-actions',
id: 'feedback',
order: 10,
locale: NS,
inject: (sessionId): MessageFeedbackInjected => {
const controller = controllerFor(sessionId)
return {
hooks: { feedback: controller },
ensure: () => controller.ensure(),
rate: (messageId, rating, note) => controller.rate(messageId, rating, note),
toggle: (messageId, rating) => controller.toggle(messageId, rating),
clearNote: messageId => controller.clearNote(messageId),
clear: messageId => controller.clear(messageId),
}
},
}, MessageFeedbackActions)
return () => {
dispose()
for (const controller of controllers.values()) controller.dispose()
controllers.clear()
}
ctx.slots.inject('conversation.chat.assistant-actions', () => ctx.slots.register({
name: 'conversation.chat.assistant-actions',
id: 'feedback',
order: 10,
locale: NS,
inject: (sessionId): MessageFeedbackInjected => {
const { feedback, dialog } = surfaceFor(sessionId)
return {
hooks: { feedback },
ensure: () => feedback.ensure(),
current: messageId => feedback.getSnapshot().items.get(messageId),
toggle: (messageId, rating) => feedback.toggle(messageId, rating),
openDialog: (messageId) => { dialog.open({ kind: 'message', messageId }) },
acknowledge: () => { dialog.acknowledge() },
}
},
}, MessageFeedbackActions))
ctx.slots.inject('conversation.input.overlay', () => ctx.slots.register({
name: 'conversation.input.overlay',
id: 'feedback-dialog',
order: 2,
locale: NS,
inject: (sessionId): FeedbackDialogInjected => {
const { dialog } = surfaceFor(sessionId)
return {
hooks: { dialog: dialog.state },
edit: (draft) => { dialog.edit(draft) },
submit: () => dialog.submitDraft(),
dismiss: () => { dialog.dismiss() },
dismissToast: (seq) => { dialog.dismissToast(seq) },
}
},
}, FeedbackDialog))
// The Host keeps `/feedback <text>` for a typed remark; a bare invocation
// from the menu or the composer opens the dialog instead.
ctx.inject(['commandUi'], (scope: ClientContext) => {
scope.effect(() => scope.commandUi.decorate({
name: 'feedback',
available: () => true,
ui: { kind: 'action', run: (session) => { surfaceFor(session.sessionId).dialog.open({ kind: 'session' }) } },
}), 'ui-message-feedback: /feedback decoration')
})
}
@@ -6,15 +6,22 @@ export const zh = {
'action.likeActive': '取消标记',
'action.dislike': '有问题的回答',
'action.dislikeActive': '取消标记',
'note.open': '补充说明',
'note.dialog': '反馈',
'note.placeholder': '这条回答哪里好,或哪里有问题?(可选)',
'note.save': '保存',
'note.cancel': '取消',
'note.aria': '反馈说明',
'dialog.title': '提交反馈',
'dialog.categories': '反馈分类',
'dialog.detail': '反馈详情',
'dialog.hint': '填写详情以帮助我们改进体验,提交内容会包括当前对话的日志',
'category.task-result': '任务结果',
'category.instruction-following': '指令理解与遵循',
'category.product-interaction': '产品功能与交互',
'category.service-stability': '服务稳定性',
'category.resource-cost': '资源使用与费用',
'category.security-privacy-permission': '安全隐私与权限',
'category.other': '其他',
'toast.recorded': '感谢你的反馈',
'error.conflict': '这条反馈已在别处改动,已显示最新状态',
'error.load': '反馈状态加载失败',
'error.generic': '反馈保存失败',
'error.noteTooLarge': '描述太长,请缩短后再提交',
} satisfies Record<string, string>
/** The feedback namespace key union. */
@@ -22,7 +29,7 @@ export type MessageFeedbackKey = keyof typeof zh
declare module '@deepseek-ai/dsh-client-ui-slots' {
interface LocaleNamespaceMap {
/** The per-message feedback controls' copy. */
/** The feedback surface's copy: the message controls, the dialog, and the acknowledgement. */
feedback: MessageFeedbackKey
}
}
@@ -33,13 +40,20 @@ export const en = {
'action.likeActive': 'Remove rating',
'action.dislike': 'Bad response',
'action.dislikeActive': 'Remove rating',
'note.open': 'Add a note',
'note.dialog': 'Feedback',
'note.placeholder': 'What was good, or what went wrong? (optional)',
'note.save': 'Save',
'note.cancel': 'Cancel',
'note.aria': 'Feedback note',
'dialog.title': 'Submit feedback',
'dialog.categories': 'Feedback category',
'dialog.detail': 'Feedback details',
'dialog.hint': 'Add details to help us improve. Your submission will include the current conversation log.',
'category.task-result': 'Task result',
'category.instruction-following': 'Instruction understanding and following',
'category.product-interaction': 'Product features and interaction',
'category.service-stability': 'Service stability',
'category.resource-cost': 'Resource usage and cost',
'category.security-privacy-permission': 'Security, privacy, and permissions',
'category.other': 'Other',
'toast.recorded': 'Thanks for your feedback',
'error.conflict': 'This feedback changed elsewhere; the latest state is shown',
'error.load': 'Could not load feedback',
'error.generic': 'Could not save feedback',
'error.noteTooLarge': 'The description is too long; shorten it and submit again',
} satisfies Record<MessageFeedbackKey, string>
@@ -1,10 +1,10 @@
/**
* The feedback entry's injected face. The target
* 'conversation.chat.assistant-actions' slot is declared and typed by
* ui-conversation; this package only contributes the entry, so no SlotMap
* merge lives here. Live per-message state arrives through the `feedback`
* hook (the framework standard kit binds it into `useFeedback`); inject
* carries the two mutation verbs plus the lazy loader.
* The injected faces of this package's two entries. The
* 'conversation.chat.assistant-actions' and 'conversation.input.overlay'
* slots are declared and typed by ui-chat and ui-conversation; this package
* only contributes entries, so no SlotMap merge lives here. Live state
* arrives through the `hooks` compartment (the framework standard kit binds
* `feedback` into `useFeedback` and `dialog` into `useDialog`).
* @module @deepseek-ai/dsh-client-ui-message-feedback/client/slots
*/
@@ -13,10 +13,11 @@ import type {
} from '@deepseek-ai/dsh-client-ui-slots'
import type {} from '@deepseek-ai/dsh-client-ui-conversation/client'
import type { MessageId } from '@deepseek-ai/dsh-api-remotes/client'
import type { MessageFeedbackRating } from '@deepseek-ai/dsh-message-feedback/types'
import type { MessageFeedbackItem, MessageFeedbackRating } from '@deepseek-ai/dsh-message-feedback/types'
// Type-only: pulls this package's LocaleNamespaceMap merge (the 'feedback' seat).
import type {} from './locales.ts'
import type { MessageFeedbackActionResult, MessageFeedbackView } from './controller.ts'
import type { MessageFeedbackActionResult, MessageFeedbackToggleResult, MessageFeedbackView } from './controller.ts'
import type { FeedbackDialogState } from './dialog.ts'
/** Injected business face of one assistant-message feedback entry. */
export interface MessageFeedbackInjected {
@@ -27,16 +28,10 @@ export interface MessageFeedbackInjected {
/** Load the Session's feedback once, on first interaction. */
ensure: () => Promise<MessageFeedbackActionResult>
/**
* Create or replace this Session's feedback for one message.
* The committed item as this Session's controller last observed it.
* @param messageId - target assistant message.
* @param rating - desired judgment.
* @param note - optional explanation.
*/
rate: (
messageId: MessageId,
rating: MessageFeedbackRating,
note?: string,
) => Promise<MessageFeedbackActionResult>
current: (messageId: MessageId) => MessageFeedbackItem | undefined
/**
* Apply the requested judgment, retracting instead when the committed rating
* already matches. The controller decides from the committed item, so a click
@@ -44,17 +39,15 @@ export interface MessageFeedbackInjected {
* @param messageId - target assistant message.
* @param rating - the judgment the human asked for.
*/
toggle: (messageId: MessageId, rating: MessageFeedbackRating) => Promise<MessageFeedbackActionResult>
toggle: (messageId: MessageId, rating: MessageFeedbackRating) => Promise<MessageFeedbackToggleResult>
/**
* Drop the note while keeping the rating.
* Open the Session's feedback dialog for one message; its submission
* records a negative judgment with the dialog's category and text.
* @param messageId - target assistant message.
*/
clearNote: (messageId: MessageId) => Promise<MessageFeedbackActionResult>
/**
* Remove this Session's feedback for one message.
* @param messageId - target assistant message.
*/
clear: (messageId: MessageId) => Promise<MessageFeedbackActionResult>
openDialog: (messageId: MessageId) => void
/** Show the Session's acknowledgement toast. */
acknowledge: () => void
}
/** Full props of one assistant-message feedback entry. */
@@ -62,3 +55,30 @@ export type MessageFeedbackActionProps =
PropsRuntime<'conversation.chat.assistant-actions'>
& InjectFace<MessageFeedbackInjected>
& PropsLocale<'feedback'>
/** Injected business face of the Session's feedback dialog entry. */
export interface FeedbackDialogInjected {
hooks: {
/** The Session's dialog and toast state. */
dialog: HostObservable<FeedbackDialogState>
}
/**
* Replace part of the draft: the category (null clears it) or the text.
* @param draft - the members to replace.
*/
edit: (draft: Partial<Pick<FeedbackDialogState, 'category' | 'text'>>) => void
/** Submit the draft to the open target. */
submit: () => Promise<void>
/** Close the dialog and discard the draft. */
dismiss: () => void
/**
* Retire the toast the view finished showing.
* @param seq - the toast sequence.
*/
dismissToast: (seq: number) => void
}
/** Full props of the feedback dialog overlay entry. */
export type FeedbackDialogProps =
InjectFace<FeedbackDialogInjected>
& PropsLocale<'feedback'>
@@ -0,0 +1,46 @@
/**
* One Session's feedback surface: the message-feedback object layer and the
* dialog controller, plus the routing between them. A message target puts a
* negative judgment through the message controller; the Session target
* records through the `sessionFeedback` Remote.
* @module @deepseek-ai/dsh-client-ui-message-feedback/client/surface
*/
import type { Context as ClientContext } from '@deepseek-ai/cordis'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import type { FeedbackRecord } from '@deepseek-ai/dsh-command-feedback/types'
import { MessageFeedbackController, describe, type MessageFeedbackActionResult } from './controller.ts'
import { FeedbackDialogController } from './dialog.ts'
/** The per-session pair behind every entry of one Session. */
export class FeedbackSurface {
/** The Session's message-feedback object layer, shared by every message control. */
readonly feedback: MessageFeedbackController
/** The Session's dialog and toast state, shared by the overlay entry and the message controls. */
readonly dialog: FeedbackDialogController
/**
* @param ctx - the browser plugin context carrying both feedback Remotes.
* @param sessionId - Session owning the transcript and the remark.
*/
constructor(private readonly ctx: ClientContext, private readonly sessionId: SessionId) {
this.feedback = new MessageFeedbackController(ctx, sessionId)
this.dialog = new FeedbackDialogController((target, entry) => target.kind === 'message'
? this.feedback.rate(target.messageId, 'negative', entry)
: this.recordSession(entry))
}
/** Record one Session-level remark through the sessionFeedback Remote. */
private async recordSession(entry: FeedbackRecord): Promise<MessageFeedbackActionResult> {
const carried = await this.ctx.remote.sessionFeedback.record({ sessionId: this.sessionId, ...entry })
if (!carried.ok) return { ok: false, error: { code: carried.error.code, message: carried.error.message } }
if (carried.value.ok) return { ok: true }
return { ok: false, error: { code: carried.value.error.code, message: describe(carried.value.error.code) } }
}
/** Drop both controllers when the owning fiber unloads. */
dispose(): void {
this.feedback.dispose()
this.dialog.dispose()
}
}
@@ -2,10 +2,12 @@
/**
* ui-message-feedback browser half on a real cordis Context with fake slots/remote
* faces: the plugin registers the feedback entry at
* conversation.chat.assistant-actions, one controller per Session backs every
* message in that Session, a reconnect refreshes only Sessions that were
* already read, and registration plus controller disposal ride the plugin
* fiber (HMR safety). The node half stays inert.
* conversation.chat.assistant-actions and the dialog entry at
* conversation.input.overlay, decorates the Host's /feedback command with an
* action that opens the dialog, one surface per Session backs every entry in
* that Session, a reconnect refreshes only Sessions that were already read,
* and registration plus surface disposal ride the plugin fiber (HMR safety).
* The node half stays inert.
*/
import { Context, Service } from '@deepseek-ai/cordis'
import { afterEach, describe, expect, it } from 'vitest'
@@ -15,7 +17,8 @@ import type { SessionId } from '@deepseek-ai/dsh-session/types'
import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
import type { MessageId } from '@deepseek-ai/dsh-api-remotes/client'
import type { MessageFeedbackItem, MessageFeedbackVersion } from '@deepseek-ai/dsh-message-feedback/types'
import type { MessageFeedbackInjected } from '../src/client/slots.ts'
import type { CommandDecoration } from '@deepseek-ai/dsh-client-ui-commands/client'
import type { FeedbackDialogInjected, MessageFeedbackInjected } from '../src/client/slots.ts'
import { apply, inject } from '../src/client/index.ts'
import { apply as nodeApply } from '../src/index.ts'
@@ -32,8 +35,8 @@ const seeded: MessageFeedbackItem = {
updatedAt: 1,
}
/** Boot the plugin over fake faces; the Remote namespace records every call. */
async function bench() {
/** Boot the plugin over fake faces; the Remote namespaces record every call. */
async function bench(options: { recordResult?: unknown; recordCarrier?: unknown } = {}) {
const ctx = new Context()
const calls: { method: string; request: unknown }[] = []
// The generated face wraps every business result in the carrier envelope.
@@ -57,19 +60,38 @@ async function bench() {
super(serviceCtx, 'remote')
}
}
const sessionFeedback = {
record: (request: unknown) => {
calls.push({ method: 'record', request })
if (options.recordCarrier !== undefined) return Promise.resolve(options.recordCarrier)
return carried(options.recordResult ?? { ok: true as const, value: { recorded: true as const } })
},
}
new RemoteService(ctx)
ctx.provide('remote.messageFeedback', messageFeedback)
ctx.provide('remote.sessionFeedback', sessionFeedback)
await ctx.plugin(SlotRegistry).await()
ctx.slots.register({
name: 'root',
children: { 'conversation.chat.assistant-actions': { kind: 'list', scope: 'session' } },
children: {
'conversation.chat.assistant-actions': { kind: 'list', scope: 'session' },
'conversation.input.overlay': { kind: 'list', scope: 'session' },
},
} as never, (() => null) as never)
ctx.provide('locale', new LocaleRuntime(ctx))
const decorations = new Map<string, CommandDecoration>()
ctx.provide('commandUi', {
decorate: (decoration: CommandDecoration) => {
decorations.set(decoration.name, decoration)
return () => { decorations.delete(decoration.name) }
},
})
const fiber = ctx.plugin({ inject: [...inject], apply })
return {
ctx,
fiber,
calls,
decorations,
entry: () => {
const entry = ctx.slots.entries('conversation.chat.assistant-actions')[0]
if (entry === undefined) return undefined
@@ -79,6 +101,15 @@ async function bench() {
inject: entry.inject as unknown as ((sessionId: SessionId) => MessageFeedbackInjected) | undefined,
}
},
dialogEntry: () => {
const entry = ctx.slots.entries('conversation.input.overlay')[0]
if (entry === undefined) return undefined
return {
...entry.options,
locale: entry.locale,
inject: entry.inject as unknown as ((sessionId: SessionId) => FeedbackDialogInjected) | undefined,
}
},
}
}
@@ -91,15 +122,104 @@ describe('ui-message-feedback browser plugin', () => {
expect(b.entry()?.inject).toBeTypeOf('function')
})
it('exposes the feedback hook plus the ensure/rate/clear verbs', async () => {
it('exposes the feedback hook plus the ensure/toggle/openDialog/acknowledge verbs', async () => {
const b = await bench()
await b.fiber.await()
const face = b.entry()!.inject!(sid('s1'))
expect(face.hooks.feedback.getSnapshot()).toMatchObject({ status: 'cold' })
expect(face.ensure).toBeTypeOf('function')
expect(face.rate).toBeTypeOf('function')
expect(face.clear).toBeTypeOf('function')
expect(face.current(MSG)).toBeUndefined()
await face.ensure()
expect(face.current(MSG)).toMatchObject({ messageId: MSG, rating: 'positive' })
expect(face.toggle).toBeTypeOf('function')
expect(face.openDialog).toBeTypeOf('function')
expect(face.acknowledge).toBeTypeOf('function')
})
it('registers the dialog entry with the documented id, order, and locale', async () => {
const b = await bench()
await b.fiber.await()
expect(b.dialogEntry()).toMatchObject({ id: 'feedback-dialog', order: 2, locale: 'feedback' })
const face = b.dialogEntry()!.inject!(sid('s1'))
expect(face.hooks.dialog.getSnapshot()).toMatchObject({ target: null, toast: 0 })
})
it('opens one dialog per Session from the message entry, the decoration, and acknowledges from Like', async () => {
const b = await bench()
await b.fiber.await()
const message = b.entry()!.inject!(sid('s1'))
const dialog = b.dialogEntry()!.inject!(sid('s1'))
message.openDialog(MSG)
expect(dialog.hooks.dialog.getSnapshot().target).toEqual({ kind: 'message', messageId: MSG })
const decoration = b.decorations.get('feedback')
expect(decoration?.available({ sessionId: sid('s1') })).toBe(true)
if (decoration?.ui.kind !== 'action') throw new Error('the /feedback decoration is not an action')
decoration.ui.run({ sessionId: sid('s1') })
expect(dialog.hooks.dialog.getSnapshot().target).toEqual({ kind: 'session' })
message.acknowledge()
expect(dialog.hooks.dialog.getSnapshot().toast).toBe(1)
expect(b.dialogEntry()!.inject!(sid('s2')).hooks.dialog.getSnapshot()).toMatchObject({ target: null, toast: 0 })
})
it('records a Session remark through the sessionFeedback Remote and a message judgment through put', async () => {
const b = await bench()
await b.fiber.await()
const message = b.entry()!.inject!(sid('s1'))
const dialog = b.dialogEntry()!.inject!(sid('s1'))
const decoration = b.decorations.get('feedback')
if (decoration?.ui.kind !== 'action') throw new Error('the /feedback decoration is not an action')
decoration.ui.run({ sessionId: sid('s1') })
dialog.edit({ category: 'service-stability', text: 'timed out' })
await dialog.submit()
expect(b.calls.filter(call => call.method === 'record')[0]?.request)
.toEqual({ sessionId: 's1', text: 'timed out', category: 'service-stability' })
expect(dialog.hooks.dialog.getSnapshot()).toMatchObject({ target: null, toast: 1 })
message.openDialog(MSG)
dialog.edit({ category: 'task-result' })
await dialog.submit()
expect(b.calls.filter(call => call.method === 'put')[0]?.request).toMatchObject({
sessionId: 's1', messageId: MSG, rating: 'negative', category: 'task-result', ifVersion: 'v1',
})
expect(dialog.hooks.dialog.getSnapshot().toast).toBe(2)
dialog.dismissToast(2)
expect(dialog.hooks.dialog.getSnapshot().toast).toBe(0)
})
it('keeps the dialog open with the carrier code when the record call itself fails', async () => {
const b = await bench({ recordCarrier: { ok: false as const, error: { code: 'gateway/internal', message: 'socket closed', details: {} } } })
await b.fiber.await()
const dialog = b.dialogEntry()!.inject!(sid('s1'))
const decoration = b.decorations.get('feedback')
if (decoration?.ui.kind !== 'action') throw new Error('the /feedback decoration is not an action')
decoration.ui.run({ sessionId: sid('s1') })
await dialog.submit()
expect(dialog.hooks.dialog.getSnapshot()).toMatchObject({ target: { kind: 'session' }, failure: 'gateway/internal', toast: 0 })
})
it('keeps the dialog open with the failure code when the Host rejects the remark', async () => {
const b = await bench({
recordResult: { ok: false as const, error: { code: 'session-not-found', sessionId: 'gone' } },
})
await b.fiber.await()
const dialog = b.dialogEntry()!.inject!(sid('gone'))
const decoration = b.decorations.get('feedback')
if (decoration?.ui.kind !== 'action') throw new Error('the /feedback decoration is not an action')
decoration.ui.run({ sessionId: sid('gone') })
await dialog.submit()
expect(dialog.hooks.dialog.getSnapshot()).toMatchObject({ target: { kind: 'session' }, failure: 'session-not-found' })
dialog.dismiss()
expect(dialog.hooks.dialog.getSnapshot().target).toBeNull()
})
it('shares one controller across every message in the same Session', async () => {
@@ -131,37 +251,24 @@ describe('ui-message-feedback browser plugin', () => {
])
})
it('routes rate and clear to the Remote with the addressed message', async () => {
it('routes toggle to the Remote with the addressed message', async () => {
const b = await bench()
await b.fiber.await()
const face = b.entry()!.inject!(sid('s1'))
expect(await face.rate(MSG, 'negative', 'wrong answer')).toEqual({ ok: true })
expect(await face.clear(MSG)).toEqual({ ok: true })
// The seeded item is positive, so a negative toggle replaces it through
// put and a positive one retracts it through delete.
expect(await face.toggle(MSG, 'negative')).toEqual({ ok: true, rating: 'negative' })
expect(await face.toggle(MSG, 'positive')).toEqual({ ok: true, rating: null })
expect(b.calls.filter(call => call.method === 'put')[0]?.request).toMatchObject({
sessionId: 's1', messageId: MSG, rating: 'negative', note: 'wrong answer',
sessionId: 's1', messageId: MSG, rating: 'negative',
})
expect(b.calls.filter(call => call.method === 'delete')[0]?.request).toMatchObject({
sessionId: 's1', messageId: MSG,
})
})
it('routes toggle and clearNote to the controller', async () => {
const b = await bench()
await b.fiber.await()
const face = b.entry()!.inject!(sid('s1'))
expect(await face.toggle(MSG, 'negative')).toEqual({ ok: true })
expect(await face.clearNote(MSG)).toEqual({ ok: true })
// The seeded item is positive with no note, so a negative toggle replaces it
// through put, and clearNote has nothing to drop and touches no wire.
const puts = b.calls.filter(call => call.method === 'put').map(call => call.request)
expect(puts).toHaveLength(1)
expect(puts[0]).toMatchObject({ messageId: MSG, rating: 'negative' })
})
it('refreshes only Sessions already read when the connection resets', async () => {
const b = await bench()
await b.fiber.await()
@@ -179,18 +286,23 @@ describe('ui-message-feedback browser plugin', () => {
expect(reads.at(-1)?.request).toEqual({ sessionId: 'warm' })
})
it('withdraws the registration and disposes controllers with the plugin fiber', async () => {
it('withdraws the registrations and disposes surfaces with the plugin fiber', async () => {
const b = await bench()
await b.fiber.await()
const face = b.entry()!.inject!(sid('s1'))
const dialog = b.dialogEntry()!.inject!(sid('s1'))
await face.ensure()
face.openDialog(MSG)
await b.fiber.dispose()
expect(b.ctx.slots.entries('conversation.chat.assistant-actions')).toHaveLength(0)
expect(b.ctx.slots.entries('conversation.input.overlay')).toHaveLength(0)
expect(b.decorations.size).toBe(0)
expect(dialog.hooks.dialog.getSnapshot().target).toBeNull()
// A disposed controller refuses further mutations, so no request outlives the fiber.
const before = b.calls.length
expect(await face.rate(MSG, 'positive')).toMatchObject({ ok: false, error: { code: 'disposed' } })
expect(await face.toggle(MSG, 'negative')).toMatchObject({ ok: false, error: { code: 'disposed' } })
expect(b.calls).toHaveLength(before)
})
@@ -113,16 +113,37 @@ describe('MessageFeedbackController', () => {
expect(controller.getSnapshot().items.get(MSG)).toEqual(second)
})
it('forwards an optional note and omits the field when absent', async () => {
it('forwards the entry as note and category and omits absent members', async () => {
const { ctx, calls } = fakeRemote()
const controller = new MessageFeedbackController(ctx, SESSION)
await controller.rate(MSG, 'positive', 'helpful')
await controller.rate(MSG, 'negative', { text: 'helpful', category: 'task-result' })
await controller.rate(OTHER, 'negative')
const puts = calls.filter(call => call.method === 'put').map(call => call.request as Record<string, unknown>)
expect(puts[0]?.note).toBe('helpful')
expect(puts[0]).toMatchObject({ note: 'helpful', category: 'task-result' })
expect(puts[1]).not.toHaveProperty('note')
expect(puts[1]).not.toHaveProperty('category')
})
it('toggle retracts a matching rating, records an absent one, and reports the committed rating', async () => {
const { ctx, calls } = fakeRemote({
list: () => Promise.resolve({ ok: true, value: { items: [item({ note: 'stored', category: 'other' })] } }),
put: () => Promise.resolve({ ok: true, value: item({ rating: 'negative', version: version('v2') }) }),
})
const controller = new MessageFeedbackController(ctx, SESSION)
expect(await controller.toggle(MSG, 'positive')).toEqual({ ok: true, rating: null })
expect(await controller.toggle(MSG, 'negative')).toEqual({ ok: true, rating: 'negative' })
expect(calls.filter(call => call.method === 'delete')[0]?.request)
.toEqual({ sessionId: SESSION, messageId: MSG, ifVersion: version('v1') })
// A replacement stores the bare judgment: the retracted item's note and
// category do not carry over.
const put = calls.filter(call => call.method === 'put')[0]?.request as Record<string, unknown>
expect(put).toMatchObject({ rating: 'negative', ifVersion: null })
expect(put).not.toHaveProperty('note')
expect(put).not.toHaveProperty('category')
})
it('reconciles a version conflict from the authoritative item without refetching', async () => {
@@ -155,7 +176,7 @@ describe('MessageFeedbackController', () => {
const controller = new MessageFeedbackController(ctx, SESSION)
await controller.ensure()
expect(await controller.clear(MSG)).toMatchObject({ ok: false, error: { code: 'version-conflict' } })
expect(await controller.toggle(MSG, 'positive')).toMatchObject({ ok: false, error: { code: 'version-conflict' } })
expect(controller.getSnapshot().items.has(MSG)).toBe(false)
})
@@ -166,21 +187,13 @@ describe('MessageFeedbackController', () => {
const controller = new MessageFeedbackController(ctx, SESSION)
await controller.ensure()
expect(await controller.clear(MSG)).toEqual({ ok: true })
expect(await controller.toggle(MSG, 'positive')).toEqual({ ok: true, rating: null })
expect(calls.filter(call => call.method === 'delete')[0]?.request)
.toEqual({ sessionId: SESSION, messageId: MSG, ifVersion: version('v7') })
expect(controller.getSnapshot().items.has(MSG)).toBe(false)
})
it('treats clearing an unrated message as already satisfied without a call', async () => {
const { ctx, calls } = fakeRemote()
const controller = new MessageFeedbackController(ctx, SESSION)
expect(await controller.clear(MSG)).toEqual({ ok: true })
expect(calls.filter(call => call.method === 'delete')).toHaveLength(0)
})
it('serializes mutations so each one compares against the committed version', async () => {
let inFlight = 0
let overlapped = false
@@ -389,7 +402,7 @@ describe('MessageFeedbackController', () => {
})
const controller = new MessageFeedbackController(ctx, SESSION)
await controller.ensure()
const pending = controller.clear(MSG)
const pending = controller.toggle(MSG, 'positive')
const listener = vi.fn()
controller.subscribe(listener)
@@ -410,7 +423,7 @@ describe('MessageFeedbackController', () => {
const controller = new MessageFeedbackController(ctx, SESSION)
await controller.ensure()
expect(await controller.rate(MSG, 'negative', 'far too long')).toMatchObject({
expect(await controller.rate(MSG, 'negative', { text: 'far too long' })).toMatchObject({
ok: false,
error: { code: 'note-too-large' },
})
@@ -426,95 +439,13 @@ describe('MessageFeedbackController', () => {
const controller = new MessageFeedbackController(ctx, SESSION)
await controller.ensure()
expect(await controller.clear(MSG)).toMatchObject({
expect(await controller.toggle(MSG, 'positive')).toMatchObject({
ok: false,
error: { code: 'session-not-found' },
})
expect(controller.getSnapshot().items.get(MSG)).toEqual(existing)
})
it('preserves a stored note when a rating switch omits one', async () => {
// Regression: a control that rendered before the first list read holds no
// item, so it passes note=undefined; that must not erase the stored note.
const stored = item({ version: version('v1'), rating: 'positive', note: 'keep me' })
const { ctx, calls } = fakeRemote({
list: () => Promise.resolve({ ok: true, value: { items: [stored] } }),
})
const controller = new MessageFeedbackController(ctx, SESSION)
expect(await controller.rate(MSG, 'negative')).toEqual({ ok: true })
const put = calls.filter(c => c.method === 'put')[0]?.request as Record<string, unknown>
expect(put.note).toBe('keep me')
expect(put.rating).toBe('negative')
})
it('toggle retracts when the committed rating already matches', async () => {
const stored = item({ version: version('v1'), rating: 'positive' })
const { ctx, calls } = fakeRemote({
list: () => Promise.resolve({ ok: true, value: { items: [stored] } }),
})
const controller = new MessageFeedbackController(ctx, SESSION)
expect(await controller.toggle(MSG, 'positive')).toEqual({ ok: true })
expect(calls.filter(c => c.method === 'delete')).toHaveLength(1)
expect(calls.filter(c => c.method === 'put')).toHaveLength(0)
expect(controller.getSnapshot().items.has(MSG)).toBe(false)
})
it('toggle decides from the committed item, not a cold view', async () => {
// The click lands before any list read: the cold view knows no item, yet the
// stored rating matches, so the toggle must retract rather than re-put.
const stored = item({ version: version('v1'), rating: 'positive', note: 'kept' })
const { ctx, calls } = fakeRemote({
list: () => Promise.resolve({ ok: true, value: { items: [stored] } }),
})
const controller = new MessageFeedbackController(ctx, SESSION)
expect(controller.getSnapshot().status).toBe('cold')
expect(await controller.toggle(MSG, 'positive')).toEqual({ ok: true })
expect(calls.filter(c => c.method === 'delete')).toHaveLength(1)
})
it('toggle replaces the opposite rating and carries the note forward', async () => {
const stored = item({ version: version('v1'), rating: 'positive', note: 'kept' })
const { ctx, calls } = fakeRemote({
list: () => Promise.resolve({ ok: true, value: { items: [stored] } }),
})
const controller = new MessageFeedbackController(ctx, SESSION)
expect(await controller.toggle(MSG, 'negative')).toEqual({ ok: true })
const put = calls.filter(c => c.method === 'put')[0]?.request as Record<string, unknown>
expect(put).toMatchObject({ rating: 'negative', note: 'kept', ifVersion: version('v1') })
})
it('clearNote drops the note and keeps the rating', async () => {
const stored = item({ version: version('v1'), rating: 'negative', note: 'remove me' })
const { ctx, calls } = fakeRemote({
list: () => Promise.resolve({ ok: true, value: { items: [stored] } }),
})
const controller = new MessageFeedbackController(ctx, SESSION)
expect(await controller.clearNote(MSG)).toEqual({ ok: true })
const put = calls.filter(c => c.method === 'put')[0]?.request as Record<string, unknown>
expect(put.rating).toBe('negative')
expect(put).not.toHaveProperty('note')
})
it('clearNote is a no-op when there is no note to drop', async () => {
const { ctx, calls } = fakeRemote({
list: () => Promise.resolve({ ok: true, value: { items: [item()] } }),
})
const controller = new MessageFeedbackController(ctx, SESSION)
expect(await controller.clearNote(MSG)).toEqual({ ok: true })
expect(calls.filter(c => c.method === 'put')).toHaveLength(0)
})
it('resync serializes behind an in-flight mutation', async () => {
// Regression: an unserialized reconnect read could land after a newer put
// and resurrect the version that put had already replaced.
@@ -616,7 +547,7 @@ describe('MessageFeedbackController', () => {
const controller = new MessageFeedbackController(ctx, SESSION)
await controller.ensure()
expect(await controller.clear(MSG)).toMatchObject({ ok: false, error: { code: 'gateway/internal' } })
expect(await controller.toggle(MSG, 'positive')).toMatchObject({ ok: false, error: { code: 'gateway/internal' } })
expect(controller.getSnapshot().items.has(MSG)).toBe(true)
})
})
@@ -0,0 +1,182 @@
/**
* FeedbackDialogController: one draft per open, submission routed by target,
* success closes and acknowledges, failure keeps the draft with its code, a
* settlement from a superseded open closes nothing, and the toast sequence
* retires only the toast the view finished showing.
*/
import { describe, expect, it, vi } from 'vitest'
import type { MessageId } from '@deepseek-ai/dsh-api-remotes/client'
import type { MessageFeedbackActionResult } from '../src/client/controller.ts'
import { FeedbackDialogController, type FeedbackSubmit } from '../src/client/dialog.ts'
const MSG = 'm-1' as MessageId
function bench(result: () => Promise<MessageFeedbackActionResult> = () => Promise.resolve({ ok: true })) {
const submit = vi.fn<FeedbackSubmit>(() => result())
return { submit, controller: new FeedbackDialogController(submit) }
}
describe('FeedbackDialogController', () => {
it('starts closed with no toast', () => {
const { controller } = bench()
expect(controller.state.getSnapshot()).toEqual({
target: null, category: null, text: '', submitting: false, failure: null, toast: 0,
})
})
it('opens with an empty draft and drops the draft on dismiss', () => {
const { controller } = bench()
controller.open({ kind: 'session' })
controller.edit({ category: 'task-result' })
controller.edit({ text: 'slow' })
expect(controller.state.getSnapshot()).toMatchObject({
target: { kind: 'session' }, category: 'task-result', text: 'slow',
})
controller.dismiss()
controller.open({ kind: 'message', messageId: MSG })
expect(controller.state.getSnapshot()).toMatchObject({
target: { kind: 'message', messageId: MSG }, category: null, text: '',
})
})
it('ignores draft edits and submits while closed', async () => {
const { controller, submit } = bench()
controller.edit({ category: 'other' })
controller.edit({ text: 'x' })
await controller.submitDraft()
expect(controller.state.getSnapshot()).toMatchObject({ category: null, text: '', toast: 0 })
expect(submit).not.toHaveBeenCalled()
})
it('submits the Session target with the trimmed text and the category', async () => {
const { controller, submit } = bench()
controller.open({ kind: 'session' })
controller.edit({ category: 'service-stability' })
controller.edit({ text: ' timed out twice ' })
await controller.submitDraft()
expect(submit).toHaveBeenCalledWith({ kind: 'session' }, { text: 'timed out twice', category: 'service-stability' })
expect(controller.state.getSnapshot()).toMatchObject({ target: null, toast: 1 })
})
it('submits an empty draft as an entry with neither text nor category', async () => {
const { controller, submit } = bench()
controller.open({ kind: 'session' })
controller.edit({ text: ' ' })
await controller.submitDraft()
expect(submit).toHaveBeenCalledWith({ kind: 'session' }, {})
})
it('submits the message target with the entry', async () => {
const { controller, submit } = bench()
controller.open({ kind: 'message', messageId: MSG })
controller.edit({ category: 'task-result' })
controller.edit({ text: 'wrong file' })
await controller.submitDraft()
expect(submit).toHaveBeenCalledWith({ kind: 'message', messageId: MSG }, { text: 'wrong file', category: 'task-result' })
expect(controller.state.getSnapshot()).toMatchObject({ target: null, toast: 1 })
})
it('keeps the draft open with the failure code when the submission is rejected', async () => {
const { controller } = bench(() => Promise.resolve({ ok: false, error: { code: 'version-conflict', message: 'changed' } }))
controller.open({ kind: 'message', messageId: MSG })
controller.edit({ text: 'draft' })
await controller.submitDraft()
expect(controller.state.getSnapshot()).toMatchObject({
target: { kind: 'message', messageId: MSG }, text: 'draft', submitting: false,
failure: 'version-conflict', toast: 0,
})
})
it('freezes the draft and refuses a second submit while one is in flight', async () => {
let release = (): void => {}
const gate = new Promise<MessageFeedbackActionResult>((resolve) => { release = () => { resolve({ ok: true }) } })
const { controller, submit } = bench(() => gate)
controller.open({ kind: 'session' })
controller.edit({ text: 'first' })
const first = controller.submitDraft()
controller.edit({ text: 'second' })
controller.edit({ category: 'other' })
await controller.submitDraft()
expect(controller.state.getSnapshot()).toMatchObject({ submitting: true, text: 'first', category: null })
release()
await first
expect(submit).toHaveBeenCalledTimes(1)
expect(controller.state.getSnapshot()).toMatchObject({ target: null, toast: 1 })
})
it('acknowledges a success that lands after a reopen without closing the new draft', async () => {
let release = (): void => {}
const gate = new Promise<MessageFeedbackActionResult>((resolve) => { release = () => { resolve({ ok: true }) } })
const { controller } = bench(() => gate)
controller.open({ kind: 'session' })
const pending = controller.submitDraft()
controller.open({ kind: 'message', messageId: MSG })
controller.edit({ text: 'new draft' })
release()
await pending
expect(controller.state.getSnapshot()).toMatchObject({
target: { kind: 'message', messageId: MSG }, text: 'new draft', toast: 1,
})
})
it('drops a failure that lands after the draft was dismissed', async () => {
let release = (): void => {}
const gate = new Promise<MessageFeedbackActionResult>((resolve) => {
release = () => { resolve({ ok: false, error: { code: 'gateway/internal', message: 'boom' } }) }
})
const { controller } = bench(() => gate)
controller.open({ kind: 'session' })
const pending = controller.submitDraft()
controller.dismiss()
release()
await pending
expect(controller.state.getSnapshot()).toMatchObject({ target: null, failure: null, submitting: false, toast: 0 })
})
it('retires only the toast the view finished showing', () => {
const { controller } = bench()
controller.acknowledge()
controller.acknowledge()
expect(controller.state.getSnapshot().toast).toBe(2)
controller.dismissToast(1)
expect(controller.state.getSnapshot().toast).toBe(2)
controller.dismissToast(2)
expect(controller.state.getSnapshot().toast).toBe(0)
})
it('keeps a toast on screen across a dismiss and drops everything on dispose', () => {
const { controller } = bench()
controller.acknowledge()
controller.open({ kind: 'session' })
controller.dismiss()
expect(controller.state.getSnapshot()).toMatchObject({ target: null, toast: 1 })
controller.open({ kind: 'session' })
controller.dispose()
expect(controller.state.getSnapshot()).toEqual({
target: null, category: null, text: '', submitting: false, failure: null, toast: 0,
})
})
})
@@ -0,0 +1,135 @@
// @vitest-environment jsdom
/**
* FeedbackDialog rendering: the modal shows the seven category chips, the
* detail box, and the hint while a target is open; a chip toggles the
* category through the injected verb; Submit routes to the controller and
* stays enabled with an empty draft; a failure code renders its copy; and the
* acknowledgement toast mounts from the toast sequence and retires through
* dismissToast once its fade completes.
*/
import { useSyncExternalStore } from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render } from '@testing-library/react'
import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts'
import { FEEDBACK_CATEGORIES } from '@deepseek-ai/dsh-command-feedback'
import { FeedbackDialog } from '../src/client/FeedbackDialog.tsx'
import type { FeedbackDialogState } from '../src/client/dialog.ts'
import { en, zh } from '../src/client/locales.ts'
afterEach(cleanup)
const t = makeTranslate(zh, commonZh)
/** Render the entry over a fixed state and recording verbs. */
function mount(overrides: Partial<FeedbackDialogState> = {}) {
const state: FeedbackDialogState = {
target: { kind: 'session' }, category: null, text: '', submitting: false, failure: null, toast: 0,
...overrides,
}
const verbs = {
edit: vi.fn(),
submit: vi.fn(() => Promise.resolve()),
dismiss: vi.fn(),
dismissToast: vi.fn(),
}
const useDialog = (<T,>(select: (v: FeedbackDialogState) => T): T =>
useSyncExternalStore(() => () => {}, () => select(state))) as never
const props = { useDialog, ...verbs, t } as unknown as Parameters<typeof FeedbackDialog>[0]
return { ...render(<FeedbackDialog {...props} />), ...verbs }
}
describe('FeedbackDialog', () => {
it('discloses conversation-log inclusion in both supported locales', () => {
expect(zh['dialog.hint']).toBe('填写详情以帮助我们改进体验,提交内容会包括当前对话的日志')
expect(en['dialog.hint']).toBe('Add details to help us improve. Your submission will include the current conversation log.')
})
it('renders nothing but the probe while closed with no toast', () => {
const ui = mount({ target: null })
expect(ui.queryByRole('dialog')).toBeNull()
expect(ui.queryByRole('alert')).toBeNull()
})
it('shows every category, the detail box with the hint, and an enabled Submit for an empty draft', () => {
const ui = mount()
const dialog = ui.getByRole('dialog', { name: zh['dialog.title'] })
expect(dialog).toBeTruthy()
const chips = ui.getByRole('group', { name: zh['dialog.categories'] }).querySelectorAll('button')
expect([...chips].map(chip => chip.textContent)).toEqual(
FEEDBACK_CATEGORIES.map(category => zh[`category.${category}`]),
)
expect(ui.getByLabelText(zh['dialog.detail']).getAttribute('placeholder')).toBe(zh['dialog.hint'])
expect(ui.getByRole('button', { name: commonZh.submit }).hasAttribute('disabled')).toBe(false)
})
it('selects a chip, and clears it when the selected chip is clicked again', () => {
const ui = mount({ category: 'task-result' })
const chips = ui.getByRole('group', { name: zh['dialog.categories'] }).querySelectorAll('button')
expect(chips[0]?.getAttribute('aria-pressed')).toBe('true')
expect(chips[1]?.getAttribute('aria-pressed')).toBe('false')
fireEvent.click(chips[1]!)
expect(ui.edit).toHaveBeenLastCalledWith({ category: 'instruction-following' })
fireEvent.click(chips[0]!)
expect(ui.edit).toHaveBeenLastCalledWith({ category: null })
})
it('forwards typing, submits, and closes through the injected verbs', () => {
const ui = mount({ text: 'draft' })
fireEvent.change(ui.getByLabelText(zh['dialog.detail']), { target: { value: 'draft more' } })
expect(ui.edit).toHaveBeenCalledWith({ text: 'draft more' })
fireEvent.click(ui.getByRole('button', { name: commonZh.submit }))
expect(ui.submit).toHaveBeenCalledTimes(1)
fireEvent.click(ui.getByRole('button', { name: commonZh.close }))
expect(ui.dismiss).toHaveBeenCalledTimes(1)
})
it('disables Submit and the chips while a submission is in flight', () => {
const ui = mount({ submitting: true })
expect(ui.getByRole('button', { name: commonZh.submitting }).hasAttribute('disabled')).toBe(true)
const chips = ui.getByRole('group', { name: zh['dialog.categories'] }).querySelectorAll('button')
expect([...chips].every(chip => chip.hasAttribute('disabled'))).toBe(true)
})
it('renders the conflict and size copy for their codes and the generic copy otherwise', () => {
const conflict = mount({ failure: 'version-conflict' })
expect(conflict.getByRole('status').textContent).toBe(zh['error.conflict'])
cleanup()
const oversized = mount({ failure: 'note-too-large' })
expect(oversized.getByRole('status').textContent).toBe(zh['error.noteTooLarge'])
cleanup()
const other = mount({ failure: 'session-not-found' })
expect(other.getByRole('status').textContent).toBe(zh['error.generic'])
})
it('retires the toast when the entry unmounts, so a Session switch does not replay it', () => {
const ui = mount({ target: null, toast: 3 })
ui.unmount()
expect(ui.dismissToast).toHaveBeenCalledWith(3)
})
it('shows the acknowledgement toast and retires it after the fade', () => {
vi.useFakeTimers()
try {
const ui = mount({ target: null, toast: 3 })
expect(ui.getByRole('alert').textContent).toBe(zh['toast.recorded'])
act(() => { vi.advanceTimersByTime(4000) })
expect(ui.dismissToast).toHaveBeenCalledWith(3)
} finally {
vi.useRealTimers()
}
})
})
@@ -1,14 +1,15 @@
// @vitest-environment jsdom
/**
* MessageFeedbackActions rendering and gestures: the rating buttons reflect the
* shared view, re-clicking the active rating retracts it, the note editor
* saves through the same rate verb, the Session's feedback is read on first
* interaction rather than on mount, and a rejected mutation surfaces inline
* without losing the authoritative state.
* shared view with the filled glyph for a recorded rating, Like records at once
* and raises the acknowledgement only when a rating was recorded, Dislike opens
* the Session's dialog unless it retracts a recorded Dislike, the Session's
* feedback is read on first interaction rather than on mount, and a rejected
* mutation surfaces inline without losing the authoritative state.
*/
import { useSyncExternalStore } from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react'
import { cleanup, fireEvent, render, waitFor } from '@testing-library/react'
import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts'
import type { MessageId } from '@deepseek-ai/dsh-api-remotes/client'
@@ -16,7 +17,9 @@ import type {
MessageFeedbackItem, MessageFeedbackRating, MessageFeedbackVersion,
} from '@deepseek-ai/dsh-message-feedback/types'
import { MessageFeedbackActions } from '../src/client/MessageFeedbackActions.tsx'
import type { MessageFeedbackActionResult, MessageFeedbackView } from '../src/client/controller.ts'
import type {
MessageFeedbackActionResult, MessageFeedbackToggleResult, MessageFeedbackView,
} from '../src/client/controller.ts'
import { zh } from '../src/client/locales.ts'
afterEach(cleanup)
@@ -38,8 +41,10 @@ function item(overrides: Partial<MessageFeedbackItem> = {}): MessageFeedbackItem
/** Render the controls over a fixed view and recording verbs. */
function mount(options: {
current?: MessageFeedbackItem | undefined
rateResult?: MessageFeedbackActionResult
clearResult?: MessageFeedbackActionResult
/** The controller's committed item when it differs from the rendered view (a cold row). */
committed?: MessageFeedbackItem
ensureResult?: MessageFeedbackActionResult
toggleResult?: MessageFeedbackToggleResult
status?: MessageFeedbackView['status']
} = {}) {
const view: MessageFeedbackView = {
@@ -47,22 +52,20 @@ function mount(options: {
items: new Map(options.current === undefined ? [] : [[MSG, options.current]]),
error: null,
}
const ensure = vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true }))
const rate = vi.fn((_id: MessageId, _rating: MessageFeedbackRating, _note?: string) =>
Promise.resolve(options.rateResult ?? { ok: true as const }))
const clear = vi.fn((_id: MessageId) =>
Promise.resolve(options.clearResult ?? { ok: true as const }))
// The controller owns retract-vs-replace, so the double stands in for it:
// matching the shown rating retracts, anything else replaces.
const toggle = vi.fn((id: MessageId, next: MessageFeedbackRating) =>
(options.current?.rating === next ? clear(id) : rate(id, next)))
const clearNote = vi.fn((_id: MessageId) =>
Promise.resolve(options.rateResult ?? { ok: true as const }))
const ensure = vi.fn(() => Promise.resolve<MessageFeedbackActionResult>(options.ensureResult ?? { ok: true }))
// The controller owns record-vs-retract, so the double stands in for it:
// matching the shown rating retracts, anything else records.
const toggle = vi.fn((_id: MessageId, next: MessageFeedbackRating) =>
Promise.resolve<MessageFeedbackToggleResult>(options.toggleResult
?? { ok: true, rating: options.current?.rating === next ? null : next }))
const openDialog = vi.fn((_id: MessageId) => {})
const acknowledge = vi.fn(() => {})
const current = vi.fn((_id: MessageId) => options.committed ?? options.current)
const useFeedback = (<T,>(select: (v: MessageFeedbackView) => T): T =>
useSyncExternalStore(() => () => {}, () => select(view))) as never
const props = { messageId: MSG, ensure, rate, toggle, clearNote, clear, useFeedback, t } as unknown as
const props = { messageId: MSG, ensure, current, toggle, openDialog, acknowledge, useFeedback, t } as unknown as
Parameters<typeof MessageFeedbackActions>[0]
return { ...render(<MessageFeedbackActions {...props} />), ensure, rate, clear, toggle, clearNote }
return { ...render(<MessageFeedbackActions {...props} />), ensure, toggle, openDialog, acknowledge }
}
describe('MessageFeedbackActions', () => {
@@ -73,11 +76,14 @@ describe('MessageFeedbackActions', () => {
expect(ui.getByLabelText(zh['action.dislike']).getAttribute('aria-pressed')).toBe('false')
})
it('marks the recorded rating pressed and offers to retract it', () => {
it('marks the recorded rating pressed, fills its glyph, and offers to retract it', () => {
const ui = mount({ current: item({ rating: 'negative' }) })
expect(ui.getByLabelText(zh['action.dislikeActive']).getAttribute('aria-pressed')).toBe('true')
const dislike = ui.getByLabelText(zh['action.dislikeActive'])
expect(dislike.getAttribute('aria-pressed')).toBe('true')
expect(dislike.hasAttribute('data-active')).toBe(true)
expect(ui.getByLabelText(zh['action.like']).getAttribute('aria-pressed')).toBe('false')
expect(ui.getByLabelText(zh['action.like']).hasAttribute('data-active')).toBe(false)
})
it('reads the Session feedback on first interaction, once', () => {
@@ -97,84 +103,86 @@ describe('MessageFeedbackActions', () => {
expect(ui.ensure).not.toHaveBeenCalled()
})
it('rates a message that has no feedback yet', async () => {
it('records a Like at once and acknowledges it', async () => {
const ui = mount()
fireEvent.click(ui.getByLabelText(zh['action.like']))
await waitFor(() => { expect(ui.toggle).toHaveBeenCalledWith(MSG, 'positive') })
expect(ui.clear).not.toHaveBeenCalled()
await waitFor(() => { expect(ui.acknowledge).toHaveBeenCalledTimes(1) })
expect(ui.openDialog).not.toHaveBeenCalled()
})
it('replaces the opposite rating and carries the existing note forward', async () => {
const ui = mount({ current: item({ rating: 'positive', note: 'keep me' }) })
fireEvent.click(ui.getByLabelText(zh['action.dislike']))
await waitFor(() => { expect(ui.toggle).toHaveBeenCalledWith(MSG, 'negative') })
})
it('retracts the feedback when the active rating is clicked again', async () => {
it('retracts a recorded Like on click without acknowledging', async () => {
const ui = mount({ current: item({ rating: 'positive' }) })
fireEvent.click(ui.getByLabelText(zh['action.likeActive']))
await waitFor(() => { expect(ui.toggle).toHaveBeenCalledWith(MSG, 'positive') })
// The double routes a matching rating to clear(), mirroring the controller.
await waitFor(() => { expect(ui.clear).toHaveBeenCalledWith(MSG) })
await waitFor(() => { expect(ui.getByLabelText(zh['action.likeActive']).hasAttribute('disabled')).toBe(false) })
expect(ui.acknowledge).not.toHaveBeenCalled()
})
it('saves a typed note through the rate verb and closes the editor', async () => {
const ui = mount({ current: item({ rating: 'positive' }) })
fireEvent.click(ui.getByText(zh['note.open']))
fireEvent.change(ui.getByLabelText(zh['note.aria']), { target: { value: ' precise and short ' } })
fireEvent.click(ui.getByText(zh['note.save']))
await waitFor(() => { expect(ui.rate).toHaveBeenCalledWith(MSG, 'positive', 'precise and short') })
await waitFor(() => { expect(ui.queryByLabelText(zh['note.aria'])).toBeNull() })
})
it('clears the note when the editor is emptied', async () => {
const ui = mount({ current: item({ rating: 'positive', note: 'old note' }) })
fireEvent.click(ui.getByText('old note'))
fireEvent.change(ui.getByLabelText(zh['note.aria']), { target: { value: ' ' } })
fireEvent.click(ui.getByText(zh['note.save']))
await waitFor(() => { expect(ui.clearNote).toHaveBeenCalledWith(MSG) })
})
it('seeds the editor with the recorded note and abandons it on cancel', () => {
const ui = mount({ current: item({ rating: 'positive', note: 'old note' }) })
fireEvent.click(ui.getByText('old note'))
expect((ui.getByLabelText(zh['note.aria']) as HTMLTextAreaElement).value).toBe('old note')
fireEvent.click(ui.getByText(zh['note.cancel']))
expect(ui.queryByLabelText(zh['note.aria'])).toBeNull()
expect(ui.rate).not.toHaveBeenCalled()
})
it('offers no note editor before a rating is recorded', () => {
it('opens the dialog for a Dislike instead of recording it', async () => {
const ui = mount()
expect(ui.queryByText(zh['note.open'])).toBeNull()
fireEvent.click(ui.getByLabelText(zh['action.dislike']))
await waitFor(() => { expect(ui.openDialog).toHaveBeenCalledWith(MSG) })
expect(ui.toggle).not.toHaveBeenCalled()
})
it('opens the dialog for a Dislike that replaces a recorded Like', async () => {
const ui = mount({ current: item({ rating: 'positive' }) })
fireEvent.click(ui.getByLabelText(zh['action.dislike']))
await waitFor(() => { expect(ui.openDialog).toHaveBeenCalledWith(MSG) })
expect(ui.toggle).not.toHaveBeenCalled()
})
it('opens the dialog for a Dislike when the seeding read fails, leaving the put to decide', async () => {
const ui = mount({ ensureResult: { ok: false, error: { code: 'session-not-found', message: 'gone' } } })
fireEvent.click(ui.getByLabelText(zh['action.dislike']))
await waitFor(() => { expect(ui.openDialog).toHaveBeenCalledWith(MSG) })
expect(ui.toggle).not.toHaveBeenCalled()
})
it('decides a Dislike from the committed item, so a cold row retracts a stored Dislike', async () => {
const ui = mount({ committed: item({ rating: 'negative' }) })
fireEvent.click(ui.getByLabelText(zh['action.dislike']))
await waitFor(() => { expect(ui.toggle).toHaveBeenCalledWith(MSG, 'negative') })
expect(ui.openDialog).not.toHaveBeenCalled()
})
it('retracts a recorded Dislike on click without the dialog', async () => {
const ui = mount({ current: item({ rating: 'negative' }) })
fireEvent.click(ui.getByLabelText(zh['action.dislikeActive']))
await waitFor(() => { expect(ui.toggle).toHaveBeenCalledWith(MSG, 'negative') })
expect(ui.openDialog).not.toHaveBeenCalled()
expect(ui.acknowledge).not.toHaveBeenCalled()
})
it('reports a lost race with the conflict copy', async () => {
const ui = mount({
rateResult: { ok: false, error: { code: 'version-conflict', message: 'feedback changed elsewhere' } },
toggleResult: { ok: false, error: { code: 'version-conflict', message: 'feedback changed elsewhere' } },
})
fireEvent.click(ui.getByLabelText(zh['action.like']))
await waitFor(() => { expect(ui.getByText(zh['error.conflict'])).toBeTruthy() })
expect(ui.acknowledge).not.toHaveBeenCalled()
})
it('reports any other failure with the generic copy', async () => {
const ui = mount({
rateResult: { ok: false, error: { code: 'target-not-found', message: 'no such message' } },
toggleResult: { ok: false, error: { code: 'target-not-found', message: 'no such message' } },
})
fireEvent.click(ui.getByLabelText(zh['action.like']))
@@ -182,24 +190,20 @@ describe('MessageFeedbackActions', () => {
await waitFor(() => { expect(ui.getByText(zh['error.generic'])).toBeTruthy() })
})
it('keeps the editor open when the note fails to save', async () => {
it('reports a failed retraction of a recorded Dislike', async () => {
const ui = mount({
current: item({ rating: 'positive' }),
rateResult: { ok: false, error: { code: 'note-too-large', message: 'too long' } },
current: item({ rating: 'negative' }),
toggleResult: { ok: false, error: { code: 'version-conflict', message: 'feedback changed elsewhere' } },
})
fireEvent.click(ui.getByText(zh['note.open']))
fireEvent.change(ui.getByLabelText(zh['note.aria']), { target: { value: 'x'.repeat(20) } })
fireEvent.click(ui.getByText(zh['note.save']))
fireEvent.click(ui.getByLabelText(zh['action.dislikeActive']))
await waitFor(() => { expect(ui.getByText(zh['error.generic'])).toBeTruthy() })
// The draft survives so the human can shorten it instead of retyping.
expect(ui.getByLabelText(zh['note.aria'])).toBeTruthy()
await waitFor(() => { expect(ui.getByText(zh['error.conflict'])).toBeTruthy() })
})
it('publishes no state after the row unmounts mid-flight', async () => {
let release = (): void => {}
const gate = new Promise<MessageFeedbackActionResult>((resolve) => {
const gate = new Promise<MessageFeedbackToggleResult>((resolve) => {
release = () => { resolve({ ok: false, error: { code: 'target-not-found', message: 'gone' } }) }
})
const view: MessageFeedbackView = { status: 'ready', items: new Map(), error: null }
@@ -208,10 +212,9 @@ describe('MessageFeedbackActions', () => {
const props = {
messageId: MSG,
ensure: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
rate: vi.fn(() => gate),
toggle: vi.fn(() => gate),
clearNote: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
clear: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
openDialog: vi.fn(),
acknowledge: vi.fn(),
useFeedback,
t,
} as unknown as Parameters<typeof MessageFeedbackActions>[0]
@@ -229,7 +232,76 @@ describe('MessageFeedbackActions', () => {
expect(errors).toEqual([])
})
it('surfaces a failed list load next to the controls', async () => {
it('publishes no state after the row unmounts before the seeding read settles', async () => {
let release = (): void => {}
const gate = new Promise<MessageFeedbackActionResult>((resolve) => { release = () => { resolve({ ok: true }) } })
const view: MessageFeedbackView = { status: 'cold', items: new Map(), error: null }
const useFeedback = (<T,>(select: (v: MessageFeedbackView) => T): T =>
useSyncExternalStore(() => () => {}, () => select(view))) as never
const openDialog = vi.fn()
const props = {
messageId: MSG,
ensure: vi.fn(() => gate),
current: () => undefined,
toggle: vi.fn(),
openDialog,
acknowledge: vi.fn(),
useFeedback,
t,
} as unknown as Parameters<typeof MessageFeedbackActions>[0]
const ui = render(<MessageFeedbackActions {...props} />)
const errors: unknown[] = []
const onError = (event: ErrorEvent): void => { errors.push(event.error) }
window.addEventListener('error', onError)
fireEvent.click(ui.getByLabelText(zh['action.dislike']))
ui.unmount()
release()
await gate
window.removeEventListener('error', onError)
expect(errors).toEqual([])
expect(openDialog).not.toHaveBeenCalled()
})
it('publishes no state after the row unmounts mid-retraction', async () => {
let release = (): void => {}
const gate = new Promise<MessageFeedbackToggleResult>((resolve) => {
release = () => { resolve({ ok: false, error: { code: 'target-not-found', message: 'gone' } }) }
})
const view: MessageFeedbackView = {
status: 'ready', items: new Map([[MSG, item({ rating: 'negative' })]]), error: null,
}
const useFeedback = (<T,>(select: (v: MessageFeedbackView) => T): T =>
useSyncExternalStore(() => () => {}, () => select(view))) as never
const props = {
messageId: MSG,
ensure: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
current: () => item({ rating: 'negative' }),
toggle: vi.fn(() => gate),
openDialog: vi.fn(),
acknowledge: vi.fn(),
useFeedback,
t,
} as unknown as Parameters<typeof MessageFeedbackActions>[0]
const ui = render(<MessageFeedbackActions {...props} />)
const errors: unknown[] = []
const onError = (event: ErrorEvent): void => { errors.push(event.error) }
window.addEventListener('error', onError)
fireEvent.click(ui.getByLabelText(zh['action.dislikeActive']))
// The retraction starts only after the seeding read settles; unmount
// while that retraction is in flight.
await waitFor(() => { expect(props.toggle).toHaveBeenCalledWith(MSG, 'negative') })
ui.unmount()
release()
await gate
window.removeEventListener('error', onError)
expect(errors).toEqual([])
})
it('surfaces a failed list load next to the controls', () => {
const ui = mount({ status: 'error' })
expect(ui.getByText(zh['error.load'])).toBeTruthy()
@@ -238,7 +310,7 @@ describe('MessageFeedbackActions', () => {
it('prefers the action failure over the load notice', async () => {
const ui = mount({
status: 'error',
rateResult: { ok: false, error: { code: 'target-not-found', message: 'gone' } },
toggleResult: { ok: false, error: { code: 'target-not-found', message: 'gone' } },
})
fireEvent.click(ui.getByLabelText(zh['action.like']))
@@ -246,494 +318,4 @@ describe('MessageFeedbackActions', () => {
await waitFor(() => { expect(ui.getByText(zh['error.generic'])).toBeTruthy() })
expect(ui.queryByText(zh['error.load'])).toBeNull()
})
it('portals the note editor to the document body, not into the actions row', () => {
const ui = mount({ current: item({ rating: 'positive' }) })
fireEvent.click(ui.getByText(zh['note.open']))
// The editor must float above the transcript (escaping the conversation
// column's overflow clip), so it renders through a portal to document.body
// rather than inline inside the component's own container.
const panel = ui.getByRole('dialog')
expect(panel).toBeTruthy()
expect(ui.container.querySelector('[role="dialog"]')).toBeNull()
expect(document.body.contains(panel)).toBe(true)
})
it('closes the note popover on Escape', () => {
const ui = mount({ current: item({ rating: 'positive' }) })
fireEvent.click(ui.getByText(zh['note.open']))
expect(ui.getByRole('dialog')).toBeTruthy()
fireEvent.keyDown(document, { key: 'Escape' })
expect(ui.queryByRole('dialog')).toBeNull()
})
it('closes the note popover on an outside pointer-down', () => {
const ui = mount({ current: item({ rating: 'positive' }) })
fireEvent.click(ui.getByText(zh['note.open']))
expect(ui.getByRole('dialog')).toBeTruthy()
fireEvent.pointerDown(document.body)
expect(ui.queryByRole('dialog')).toBeNull()
})
it('keeps the note popover open on a pointer-down inside it', () => {
const ui = mount({ current: item({ rating: 'positive' }) })
fireEvent.click(ui.getByText(zh['note.open']))
const panel = ui.getByRole('dialog')
expect(panel).toBeTruthy()
fireEvent.pointerDown(panel)
expect(ui.getByRole('dialog')).toBeTruthy()
})
it('does not close the note popover on a pointer-down on its trigger', () => {
const ui = mount({ current: item({ rating: 'positive' }) })
fireEvent.click(ui.getByText(zh['note.open']))
expect(ui.getByRole('dialog')).toBeTruthy()
// The trigger is inside the panel's own region, so pressing it must not be
// treated as an outside click; the toggle click below then closes it.
fireEvent.pointerDown(ui.getByText(zh['note.open']))
expect(ui.getByRole('dialog')).toBeTruthy()
})
it('toggles the note popover closed and open from its trigger', () => {
const ui = mount({ current: item({ rating: 'positive' }) })
fireEvent.click(ui.getByText(zh['note.open']))
expect(ui.getByRole('dialog')).toBeTruthy()
expect(ui.getByLabelText(zh['note.aria'])).toBeTruthy()
fireEvent.click(ui.getByText(zh['note.open']))
expect(ui.queryByRole('dialog')).toBeNull()
fireEvent.click(ui.getByText(zh['note.open']))
expect(ui.getByRole('dialog')).toBeTruthy()
})
it('ignores keys other than Escape while the popover is open', () => {
const ui = mount({ current: item({ rating: 'positive' }) })
fireEvent.click(ui.getByText(zh['note.open']))
expect(ui.getByRole('dialog')).toBeTruthy()
fireEvent.keyDown(document, { key: 'Enter' })
expect(ui.getByRole('dialog')).toBeTruthy()
})
it('publishes no rating-state after the row unmounts mid-flight', async () => {
// Directly exercise the early-return of a rating settle once the control has
// unmounted: the promise resolution must not touch React state.
let release = (): void => {}
const gate = new Promise<MessageFeedbackActionResult>((resolve) => {
release = () => { resolve({ ok: true as const }) }
})
const view: MessageFeedbackView = { status: 'ready', items: new Map(), error: null }
const useFeedback = (<T,>(select: (v: MessageFeedbackView) => T): T =>
useSyncExternalStore(() => () => {}, () => select(view))) as never
const props = {
messageId: MSG,
ensure: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
rate: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
toggle: vi.fn(() => gate),
clearNote: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
clear: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
useFeedback,
t,
} as unknown as Parameters<typeof MessageFeedbackActions>[0]
const ui = render(<MessageFeedbackActions {...props} />)
const errors: unknown[] = []
const onError = (event: ErrorEvent): void => { errors.push(event.error) }
window.addEventListener('error', onError)
fireEvent.click(ui.getByLabelText(zh['action.like']))
ui.unmount()
release()
await gate
window.removeEventListener('error', onError)
expect(errors).toEqual([])
})
it('publishes no note-state after the row unmounts mid-save', async () => {
// Same unmount early-return for the note-save settle path: resolving the
// save promise after unmount must not touch React state.
let release = (): void => {}
const gate = new Promise<MessageFeedbackActionResult>((resolve) => {
release = () => { resolve({ ok: true as const }) }
})
const view: MessageFeedbackView = { status: 'ready', items: new Map([[MSG, item({ rating: 'positive' })]]), error: null }
const useFeedback = (<T,>(select: (v: MessageFeedbackView) => T): T =>
useSyncExternalStore(() => () => {}, () => select(view))) as never
const props = {
messageId: MSG,
ensure: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
rate: vi.fn(() => gate),
toggle: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
clearNote: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
clear: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
useFeedback,
t,
} as unknown as Parameters<typeof MessageFeedbackActions>[0]
const errors: unknown[] = []
const onError = (event: ErrorEvent): void => { errors.push(event.error) }
window.addEventListener('error', onError)
const ui = render(<MessageFeedbackActions {...props} />)
fireEvent.click(ui.getByText(zh['note.open']))
fireEvent.change(ui.getByLabelText(zh['note.aria']), { target: { value: 'hi' } })
fireEvent.click(ui.getByText(zh['note.save']))
ui.unmount()
release()
await gate
window.removeEventListener('error', onError)
expect(errors).toEqual([])
})
it('ignores a pointer-down whose target is not a DOM node', () => {
const ui = mount({ current: item({ rating: 'positive' }) })
fireEvent.click(ui.getByText(zh['note.open']))
expect(ui.getByRole('dialog')).toBeTruthy()
// The outside-click guard returns without closing when the event target is
// not a DOM node. `document.dispatchEvent` delivers straight to the
// document listener, and a non-Node target is not `instanceof Node`.
const event = new MouseEvent('pointerdown', { bubbles: true })
Object.defineProperty(event, 'target', { configurable: true, value: { notANode: true } })
document.dispatchEvent(event)
expect(ui.getByRole('dialog')).toBeTruthy()
})
it('returns focus to the trigger when the popover closes', () => {
const ui = mount({ current: item({ rating: 'positive' }) })
const trigger = ui.getByText(zh['note.open'])
fireEvent.click(trigger)
expect(ui.getByRole('dialog')).toBeTruthy()
fireEvent.keyDown(document, { key: 'Escape' })
// Closing hands focus back, so a keyboard user resumes on the row they
// came from rather than at the document root.
expect(ui.queryByRole('dialog')).toBeNull()
expect(document.activeElement).toBe(trigger)
})
it('does not pull focus when an already-rated message mounts', () => {
// The `wasOpen` guard exists for this: a transcript of already-rated
// messages must not drag focus into an action row as each one mounts.
// Only a real open-then-close returns focus.
const elsewhere = document.createElement('button')
document.body.append(elsewhere)
elsewhere.focus()
mount({ current: item({ rating: 'positive' }) })
expect(document.activeElement).toBe(elsewhere)
elsewhere.remove()
})
it('drops a stale save failure when the popover is reopened', async () => {
// The failure belongs to the editing session that produced it: reopening
// reseeds the draft from the stored note, so a carried-over error would
// describe an attempt the new draft never made.
const ui = mount({
current: item({ rating: 'positive' }),
rateResult: { ok: false, error: { code: 'note-too-large', message: 'too long' } },
})
fireEvent.click(ui.getByText(zh['note.open']))
fireEvent.change(ui.getByLabelText(zh['note.aria']), { target: { value: 'x'.repeat(20) } })
fireEvent.click(ui.getByText(zh['note.save']))
await waitFor(() => { expect(ui.getByText(zh['error.generic'])).toBeTruthy() })
fireEvent.keyDown(document, { key: 'Escape' })
fireEvent.click(ui.getByText(zh['note.open']))
expect(ui.queryByText(zh['error.generic'])).toBeNull()
})
it('keeps a save failure visible when the rating disappears underneath it', async () => {
// Another client retracts the feedback while the editor is open: the
// controller commits `current: null`, the item goes away, and the panel
// unmounts. The failure must not vanish with it, so it falls back to the row.
let release = (): void => {}
const gate = new Promise<MessageFeedbackActionResult>((resolve) => {
release = () => { resolve({ ok: false, error: { code: 'target-not-found', message: 'gone' } }) }
})
const view: MessageFeedbackView = {
status: 'ready',
items: new Map([[MSG, item({ rating: 'positive' })]]),
error: null,
}
let notify = (): void => {}
const useFeedback = (<T,>(select: (v: MessageFeedbackView) => T): T =>
useSyncExternalStore((cb) => { notify = cb; return () => {} }, () => select(view))) as never
const props = {
messageId: MSG,
ensure: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
rate: vi.fn(() => gate),
toggle: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
clearNote: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
clear: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
useFeedback,
t,
} as unknown as Parameters<typeof MessageFeedbackActions>[0]
const ui = render(<MessageFeedbackActions {...props} />)
fireEvent.click(ui.getByText(zh['note.open']))
fireEvent.change(ui.getByLabelText(zh['note.aria']), { target: { value: 'hi' } })
fireEvent.click(ui.getByText(zh['note.save']))
// The retract lands first, then the save rejects.
view.items = new Map()
notify()
release()
await gate
await waitFor(() => { expect(ui.getByText(zh['error.generic'])).toBeTruthy() })
expect(ui.queryByRole('dialog')).toBeNull()
})
it('ignores a save that resolves after its editing session ended', async () => {
// Closing and reopening starts a new session. A late success from the old
// one must not shut the panel the human just opened.
let release = (): void => {}
const gate = new Promise<MessageFeedbackActionResult>((resolve) => {
release = () => { resolve({ ok: true as const }) }
})
const view: MessageFeedbackView = {
status: 'ready',
items: new Map([[MSG, item({ rating: 'positive' })]]),
error: null,
}
const useFeedback = (<T,>(select: (v: MessageFeedbackView) => T): T =>
useSyncExternalStore(() => () => {}, () => select(view))) as never
const props = {
messageId: MSG,
ensure: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
rate: vi.fn(() => gate),
toggle: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
clearNote: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
clear: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
useFeedback,
t,
} as unknown as Parameters<typeof MessageFeedbackActions>[0]
const ui = render(<MessageFeedbackActions {...props} />)
fireEvent.click(ui.getByText(zh['note.open']))
fireEvent.change(ui.getByLabelText(zh['note.aria']), { target: { value: 'first' } })
fireEvent.click(ui.getByText(zh['note.save']))
// Abandon that session and start another before the save lands.
fireEvent.keyDown(document, { key: 'Escape' })
fireEvent.click(ui.getByText(zh['note.open']))
expect(ui.getByRole('dialog')).toBeTruthy()
release()
await gate
// Flush the `.then` continuation and the render it would cause. Asserted
// directly rather than through `waitFor`, which would retry past a panel
// that the stale result closed.
await act(async () => { await Promise.resolve() })
expect(ui.getByRole('dialog')).toBeTruthy()
// The reply is discarded, but the request is no longer in flight, so the
// controls must not stay disabled: `pending` gates the rating buttons and
// Save, and leaving it set locks this message's row until it remounts.
expect(ui.getByLabelText(zh['action.likeActive']).hasAttribute('disabled')).toBe(false)
expect(ui.getByLabelText(zh['action.dislike']).hasAttribute('disabled')).toBe(false)
expect(ui.getByText(zh['note.save']).hasAttribute('disabled')).toBe(false)
})
it('reports a save that fails after the human closed the panel', async () => {
// A slow save that rejects once the panel is gone must not be swallowed:
// the human would otherwise believe the note was stored. With no panel to
// show it in, the row carries the notice.
let release = (): void => {}
const gate = new Promise<MessageFeedbackActionResult>((resolve) => {
release = () => {
resolve({ ok: false, error: { code: 'target-not-found', message: 'gone' } })
}
})
const view: MessageFeedbackView = {
status: 'ready',
items: new Map([[MSG, item({ rating: 'positive' })]]),
error: null,
}
const useFeedback = (<T,>(select: (v: MessageFeedbackView) => T): T =>
useSyncExternalStore(() => () => {}, () => select(view))) as never
const props = {
messageId: MSG,
ensure: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
rate: vi.fn(() => gate),
toggle: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
clearNote: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
clear: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
useFeedback,
t,
} as unknown as Parameters<typeof MessageFeedbackActions>[0]
const ui = render(<MessageFeedbackActions {...props} />)
fireEvent.click(ui.getByText(zh['note.open']))
fireEvent.change(ui.getByLabelText(zh['note.aria']), { target: { value: 'hi' } })
fireEvent.click(ui.getByText(zh['note.save']))
// Walk away before the reply lands, and leave it closed.
fireEvent.keyDown(document, { key: 'Escape' })
expect(ui.queryByRole('dialog')).toBeNull()
release()
await gate
await act(async () => { await Promise.resolve() })
expect(ui.getByText(zh['error.generic'])).toBeTruthy()
})
it('does not write an abandoned session\'s failure into a reopened panel', async () => {
// The old request rejects after the panel was closed and reopened, so the
// new session owns the panel. Its draft was not the one that failed, so the
// stale error must not be shown there; it belongs to the abandoned session.
let release = (): void => {}
const gate = new Promise<MessageFeedbackActionResult>((resolve) => {
release = () => {
resolve({ ok: false, error: { code: 'target-not-found', message: 'gone' } })
}
})
const view: MessageFeedbackView = {
status: 'ready',
items: new Map([[MSG, item({ rating: 'positive' })]]),
error: null,
}
const useFeedback = (<T,>(select: (v: MessageFeedbackView) => T): T =>
useSyncExternalStore(() => () => {}, () => select(view))) as never
const props = {
messageId: MSG,
ensure: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
rate: vi.fn(() => gate),
toggle: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
clearNote: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
clear: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
useFeedback,
t,
} as unknown as Parameters<typeof MessageFeedbackActions>[0]
const ui = render(<MessageFeedbackActions {...props} />)
fireEvent.click(ui.getByText(zh['note.open']))
fireEvent.change(ui.getByLabelText(zh['note.aria']), { target: { value: 'first' } })
fireEvent.click(ui.getByText(zh['note.save']))
// Abandon that session and start another before the save rejects; unlike
// the closed-and-left case, a new panel is now on screen.
fireEvent.keyDown(document, { key: 'Escape' })
fireEvent.click(ui.getByText(zh['note.open']))
expect(ui.getByRole('dialog')).toBeTruthy()
release()
await gate
await act(async () => { await Promise.resolve() })
// The stale failure names a draft the new session never sent, so it stays
// out of the reopened panel's status area.
expect(ui.queryByText(zh['error.generic'])).toBeNull()
expect(ui.getByRole('dialog')).toBeTruthy()
})
it('resyncs an untouched reopened draft to the note that just committed', async () => {
// The reopened session seeded from the note as it read before the save
// committed, so an untouched draft would show stale text and the next save
// could overwrite what just landed.
let release = (): void => {}
const gate = new Promise<MessageFeedbackActionResult>((resolve) => {
release = () => { resolve({ ok: true as const }) }
})
const view: MessageFeedbackView = {
status: 'ready',
items: new Map([[MSG, item({ rating: 'positive', note: 'old' })]]),
error: null,
}
const useFeedback = (<T,>(select: (v: MessageFeedbackView) => T): T =>
useSyncExternalStore(() => () => {}, () => select(view))) as never
const props = {
messageId: MSG,
ensure: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
rate: vi.fn(() => gate),
toggle: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
clearNote: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
clear: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
useFeedback,
t,
} as unknown as Parameters<typeof MessageFeedbackActions>[0]
const ui = render(<MessageFeedbackActions {...props} />)
fireEvent.click(ui.getByText('old'))
fireEvent.change(ui.getByLabelText(zh['note.aria']), { target: { value: 'saved text' } })
fireEvent.click(ui.getByText(zh['note.save']))
// Close and reopen before the save lands: the new draft is seeded from the
// still-stale stored note.
fireEvent.keyDown(document, { key: 'Escape' })
fireEvent.click(ui.getByText('old'))
expect((ui.getByLabelText(zh['note.aria']) as HTMLTextAreaElement).value).toBe('old')
release()
await gate
await act(async () => { await Promise.resolve() })
expect((ui.getByLabelText(zh['note.aria']) as HTMLTextAreaElement).value).toBe('saved text')
})
it('leaves a reopened draft alone once the human has edited it', async () => {
// The opposite arm: an edited draft belongs to the human, so a late save
// must not overwrite what they are typing.
let release = (): void => {}
const gate = new Promise<MessageFeedbackActionResult>((resolve) => {
release = () => { resolve({ ok: true as const }) }
})
const view: MessageFeedbackView = {
status: 'ready',
items: new Map([[MSG, item({ rating: 'positive', note: 'old' })]]),
error: null,
}
const useFeedback = (<T,>(select: (v: MessageFeedbackView) => T): T =>
useSyncExternalStore(() => () => {}, () => select(view))) as never
const props = {
messageId: MSG,
ensure: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
rate: vi.fn(() => gate),
toggle: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
clearNote: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
clear: vi.fn(() => Promise.resolve<MessageFeedbackActionResult>({ ok: true })),
useFeedback,
t,
} as unknown as Parameters<typeof MessageFeedbackActions>[0]
const ui = render(<MessageFeedbackActions {...props} />)
fireEvent.click(ui.getByText('old'))
fireEvent.change(ui.getByLabelText(zh['note.aria']), { target: { value: 'saved text' } })
fireEvent.click(ui.getByText(zh['note.save']))
fireEvent.keyDown(document, { key: 'Escape' })
fireEvent.click(ui.getByText('old'))
fireEvent.change(ui.getByLabelText(zh['note.aria']), { target: { value: 'my new words' } })
release()
await gate
await act(async () => { await Promise.resolve() })
expect((ui.getByLabelText(zh['note.aria']) as HTMLTextAreaElement).value).toBe('my new words')
})
})
@@ -1,30 +1,29 @@
/**
* Feedback controls stylesheet contract, asserted against the CSS text on disk.
* Feedback stylesheet contract, asserted against the CSS text on disk for the
* message controls and the dialog.
*
* A `--dsw-*` name the theme never declares fails silently, and for this sheet
* it failed loudly in the product: `border`, `background`, and the primary
* button's fill and label each named a token that does not exist, so every one
* of those declarations was invalid at computed-value time and dropped. The
* note editor shipped with no border and no surface, and its Save button with
* neither fill nor readable label. Nothing downstream reports this — the sheet
* parses, the classes attach, and the DOM snapshots are unchanged.
* A `--dsw-*` name the theme never declares fails silently, and for the
* controls' sheet it failed loudly in the product: `border`, `background`, and
* the primary button's fill and label each named a token that does not exist,
* so every one of those declarations was invalid at computed-value time and
* dropped. The note editor of the time shipped with no border and no surface,
* and its Save button with neither fill nor readable label. Nothing downstream
* reports this — the sheet parses, the classes attach, and the DOM snapshots
* are unchanged.
*
* The editor is a popover portaled to `document.body` and fixed-positioned
* from the note trigger's rect, so it never enters the IconActions row's flex
* layout at all — the row keeps its single 28px line of icons and the note
* trigger, and no wrapping (`flex-wrap`) or `order` is needed for it. The
* width-independent half of that contract is asserted here (the panel is a
* fixed portal, not an inline flex item); the resulting geometry is measured
* in a real engine by `apps/web/tests/message-feedback-layout`.
* The dialog is the body-portaled Modal primitive, so nothing this package
* renders enters the IconActions row's flex layout beyond the two 28px
* buttons and the failure notice.
*/
import { readdirSync, readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
const css = readFileSync(
fileURLToPath(new URL('../src/client/MessageFeedbackActions.module.css', import.meta.url)),
const SHEETS = ['MessageFeedbackActions', 'FeedbackDialog'] as const
const sheets = Object.fromEntries(SHEETS.map(name => [name, readFileSync(
fileURLToPath(new URL(`../src/client/${name}.module.css`, import.meta.url)),
'utf8',
)
)])) as Record<(typeof SHEETS)[number], string>
// The theme package maps `./styles/*` to `./src/styles/*`, so the declarations
// stay on the source plane rather than needing a build. Every theme sheet, not
// just the platform tokens: font and scrollbar variables are declared in
@@ -36,16 +35,20 @@ const tokens = readdirSync(fileURLToPath(new URL('../../ui-theme/src/styles/', i
/**
* The declarations of one top-level rule, by selector.
* @param sheetName - the stylesheet containing the rule.
* @param selector - the class selector to read, including its leading dot.
* @returns the rule's declaration text.
*/
function block(selector: string): string {
const match = new RegExp(`^\\${selector} \\{([^}]*)\\}`, 'm').exec(css)
if (match === null) throw new Error(`MessageFeedbackActions.module.css has no \`${selector}\` rule`)
function block(sheetName: (typeof SHEETS)[number], selector: string): string {
const escapedSelector = selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const match = new RegExp(`^${escapedSelector} \\{([^}]*)\\}`, 'm').exec(sheets[sheetName])
if (match === null) throw new Error(`${sheetName}.module.css has no \`${selector}\` rule`)
return match[1] ?? ''
}
describe('MessageFeedbackActions theme styles', () => {
describe.each(SHEETS)('%s theme styles', (name) => {
const sheet = sheets[name]
it('names only theme variables the token sheet defines', () => {
// The regression that motivated this file. An undeclared custom property
// has no fallback and does not inherit a usable value: the entire
@@ -53,51 +56,52 @@ describe('MessageFeedbackActions theme styles', () => {
// never been written. Every theme-variable prefix the sheets actually use,
// not just `--dsw-`: a `--dsh-` name reads as a plausible sibling and would
// otherwise slip past into an invalid declaration.
const named = [...css.matchAll(/var\((--(?:dsw|dsh|ds)-[a-z0-9-]+)/g)].map(match => match[1])
const named = [...sheet.matchAll(/var\((--(?:dsw|dsh|ds)-[a-z0-9-]+)/g)].map(match => match[1])
// Vacuity guard: the sheet has to actually name tokens, or the filter below
// is satisfied by an empty list and this test proves nothing.
expect(named.length).toBeGreaterThan(5)
const undeclared = [...new Set(named)].filter(name => !tokens.includes(` ${String(name)}:`))
expect(named.length).toBeGreaterThan(3)
const undeclared = [...new Set(named)].filter(token => !tokens.includes(` ${String(token)}:`))
expect(undeclared).toEqual([])
})
it('never falls back to a literal colour', () => {
// A token that resolves is never the problem; an undeclared one takes this
// branch, and a literal here is a single colour for both themes.
expect(css).not.toMatch(/var\(--dsw-[a-z0-9-]+\s*,\s*(?:#|rgb|rgba|hsl|hsla)/)
})
it('keeps the note editor out of the row as a fixed portal, not a flex item', () => {
// The editor is a popover portaled to document.body, so the IconActions row
// never has to grow or wrap around it. Fixed positioning comes from the
// placement code (inline `left`/`top`), not a class, so only `position:
// fixed` and the elevated surface live in the sheet — plus the absence of a
// flex rule on the panel, which would resurrect the row-overflow defect an
// inline editor had. The row stays one 28px line, so a fixed `width` on the
// panel is fine (it floats, it does not compete for row space).
expect(block('.notePanel')).toMatch(/position:\s*fixed/)
// The panel flex-sets its own children (textarea over buttons), which is
// fine. What must be absent is the flex-SIZING that made an inline editor a
// row item: grow/shrink/basis (or the `flex:` shorthand) would let it rejoin
// the IconActions layout, resurrecting the overflow defect.
expect(block('.notePanel')).not.toMatch(/flex-(?:grow|shrink|basis)\s*:/)
expect(block('.notePanel')).not.toMatch(/^\s*flex\s*:/m)
expect(sheet).not.toMatch(/var\(--dsw-[a-z0-9-]+\s*,\s*(?:#|rgb|rgba|hsl|hsla)/)
})
it('closes every block, so no rule is swallowed by the one above it', () => {
// A missing `}` is not a parse error: every rule after it silently becomes
// part of the block above, and the controls would paint unstyled.
const bare = css.replace(/\/\*[\s\S]*?\*\//g, '')
const bare = sheet.replace(/\/\*[\s\S]*?\*\//g, '')
expect((bare.match(/\}/g) ?? []).length).toBe((bare.match(/\{/g) ?? []).length)
})
})
describe('MessageFeedbackActions row styles', () => {
it('slot-injected actions ride the content font-size axis like their host row', () => {
// These buttons render inside ui-chat's MessageIconActions row; a fixed
// 28px would leave them undersized (or overflowing) once the Settings
// font size moves the row.
expect(block('.action')).toMatch(/width:\s*calc\(28px \+ var\(--dsh-content-font-delta, 0px\)\)/)
expect(block('.action')).toMatch(/height:\s*calc\(28px \+ var\(--dsh-content-font-delta, 0px\)\)/)
expect(block('.action svg')).toMatch(/width:\s*calc\(15px \+ var\(--dsh-content-font-delta, 0px\)\)/)
expect(block('.noteOpen')).toMatch(/line-height:\s*calc\(28px \+ var\(--dsh-content-font-delta, 0px\)\)/)
expect(block('MessageFeedbackActions', '.action')).toMatch(/width:\s*calc\(28px \+ var\(--dsh-content-font-delta, 0px\)\)/)
expect(block('MessageFeedbackActions', '.action')).toMatch(/height:\s*calc\(28px \+ var\(--dsh-content-font-delta, 0px\)\)/)
expect(block('MessageFeedbackActions', '.action svg')).toMatch(/width:\s*calc\(15px \+ var\(--dsh-content-font-delta, 0px\)\)/)
})
it('uses the tertiary label colour for recorded rating icons', () => {
expect(block('MessageFeedbackActions', '.action[data-active]'))
.toMatch(/color:\s*var\(--dsw-alias-label-tertiary\)/)
})
})
describe('FeedbackDialog layout styles', () => {
it('uses the reviewed spacing, text colours, and submit-button geometry', () => {
expect(block('FeedbackDialog', '.dialog.dialog')).toMatch(/gap:\s*38px/)
expect(block('FeedbackDialog', '.categories')).toMatch(/margin-top:\s*-14px/)
expect(block('FeedbackDialog', '.chip')).toMatch(/color:\s*var\(--dsw-alias-label-primary\)/)
expect(block('FeedbackDialog', '.detail::placeholder')).toMatch(/color:\s*var\(--dsw-alias-label-caption\)/)
expect(block('FeedbackDialog', '.detail')).toMatch(/border-radius:\s*16px/)
expect(block('FeedbackDialog', '.submit')).toMatch(/border-radius:\s*18px/)
expect(block('FeedbackDialog', '.submit')).toMatch(/font-weight:\s*500/)
})
})
@@ -43,6 +43,15 @@
},
{
"path": "../ui-slots"
},
{
"path": "../../feedback/command-feedback"
},
{
"path": "../ui-commands"
},
{
"path": "../store"
}
]
}
@@ -16,7 +16,7 @@ import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store'
import { TestRemote } from '@deepseek-ai/dsh-client-test-runtime'
import type { ModelSelection, ModelSelectionProjection } from '@deepseek-ai/dsh-api-session-controller/types'
import type { CommandContribution, SelectOption } from '@deepseek-ai/dsh-client-ui-commands/client'
import type { CommandContribution, PopupSelectSpec, SelectOption } from '@deepseek-ai/dsh-client-ui-commands/client'
import type { ModelSelectInjected } from '../src/client/slots.ts'
import { apply, inject } from '../src/client/index.ts'
import { zh } from '../src/client/locales.ts'
@@ -166,6 +166,11 @@ async function bench(locale: 'zh' | 'en' = 'zh') {
return {
ctx, fiber, mint, calls, remote,
contribution: () => contribution!,
popup: (): PopupSelectSpec => {
const ui = contribution!.ui
if (ui.kind !== 'popupSelect') throw new Error('expected the popupSelect kind')
return ui
},
seat: () => seats.get('conversation.input.model')!,
hostCurrent: () => selected,
setHostCurrent: (selection: ModelSelection) => { defaultSelection = selection },
@@ -191,7 +196,7 @@ describe('ui-model-selection dual entry', () => {
it('localizes built-in descriptions and preserves external provider descriptions', async () => {
const b = await bench()
b.mint('s1')
const options = await b.contribution().ui.options(projection('s1'), new AbortController().signal)
const options = await b.popup().options(projection('s1'), new AbortController().signal)
expect(options.map((o: SelectOption) => o.label)).toEqual([
'DeepSeek-V4-Flash', 'DeepSeek-V4-Pro', 'External Flash',
])
@@ -208,7 +213,7 @@ describe('ui-model-selection dual entry', () => {
it('keeps built-in descriptions unchanged in English', async () => {
const b = await bench('en')
b.mint('s1')
const options = await b.contribution().ui.options(projection('s1'), new AbortController().signal)
const options = await b.popup().options(projection('s1'), new AbortController().signal)
expect(options[0]?.detail)
.toBe('DeepSeek · Fast, efficient, and economical; suited to focused, routine, or parallel tasks.')
expect(options[1]?.detail)
@@ -236,7 +241,7 @@ describe('ui-model-selection dual entry', () => {
reasoningEffort: 'max',
})
// The POPUP's next options pass reflects it without a seat-side reload.
const options = await b.contribution().ui.options(projection('s1'), new AbortController().signal)
const options = await b.popup().options(projection('s1'), new AbortController().signal)
expect(options.find((o: SelectOption) => o.label === 'DeepSeek-V4-Pro')).toMatchObject({ active: true })
})
@@ -244,9 +249,9 @@ describe('ui-model-selection dual entry', () => {
const b = await bench()
b.mint('s1')
const seatFace = b.seat().inject!(sid('s1'))
const options = await b.contribution().ui.options(projection('s1'), new AbortController().signal)
const options = await b.popup().options(projection('s1'), new AbortController().signal)
const pro = options.find((o: SelectOption) => o.label === 'DeepSeek-V4-Pro')!
await b.contribution().ui.onSelect(pro, projection('s1'))
await b.popup().onSelect(pro, projection('s1'))
expect(seatFace.directory.getSnapshot().current).toEqual({
provider: 'deepseek-official',
model: 'deepseek-v4-pro',
@@ -266,8 +271,8 @@ describe('ui-model-selection dual entry', () => {
// The service face resolves the same instance the seat inject handed out.
expect(b.ctx.modelDirectories.directoryFor(sid('a')).store).toBe(faceA.directory)
await Promise.all([
b.contribution().ui.options(projection('a'), new AbortController().signal),
b.contribution().ui.options(projection('b'), new AbortController().signal),
b.popup().options(projection('a'), new AbortController().signal),
b.popup().options(projection('b'), new AbortController().signal),
])
expect(b.calls.models).toBe(1)
})
@@ -396,7 +401,7 @@ describe('ui-model-selection dual entry', () => {
b.address(sid('child'))
expect(b.contribution().available(projection('child'))).toBe(false)
await expect(b.contribution().ui.options(
await expect(b.popup().options(
projection('child'),
new AbortController().signal,
)).rejects.toThrow(/unavailable for addressed subagent/)
@@ -15,7 +15,7 @@ import type { SessionId } from '@deepseek-ai/dsh-session/types'
import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
import { TestRemote, scriptedSettingsRemote } from '@deepseek-ai/dsh-client-test-runtime'
import { apply as settingsApply, inject as settingsInject } from '@deepseek-ai/dsh-client-ui-settings/client'
import type { CommandDecoration } from '@deepseek-ai/dsh-client-ui-commands/client'
import type { CommandDecoration, PopupSelectSpec } from '@deepseek-ai/dsh-client-ui-commands/client'
import type { PermissionSelect } from '@deepseek-ai/dsh-permission-presets/client'
import {
PermissionRow, type PermissionRowInjected,
@@ -82,6 +82,11 @@ async function bench() {
ctx, fiber, locale, values, commands, remote,
setResult: (r: { ok: boolean; matched?: boolean }) => { commandResult = r },
decoration: () => decoration,
popup: (): PopupSelectSpec => {
const ui = decoration!.ui
if (ui.kind !== 'popupSelect') throw new Error('expected the popupSelect kind')
return ui
},
permissionRow: () => ctx.slots.entries('settings.general.item')
.find(entry => entry.component === PermissionRow),
}
@@ -110,11 +115,11 @@ describe('ui-permission browser plugin', () => {
expect(c.available(proj)).toBe(false)
b.values.set(sid('s1'), { ...SELECT, options: [...SELECT.options, { value: 'custom', name: 'Custom' }], currentValue: 'custom' })
expect(c.available(proj)).toBe(true)
const options = await c.ui.options(proj, new AbortController().signal)
const options = await b.popup().options(proj, new AbortController().signal)
expect(options.map(option => option.id)).toEqual(['read-only', 'workspace-write', 'danger-full-access'])
expect(options.every(option => option.active !== true)).toBe(true)
b.values.set(sid('s1'), SELECT)
const again = await c.ui.options(proj, new AbortController().signal)
const again = await b.popup().options(proj, new AbortController().signal)
expect(again.find(option => option.id === 'workspace-write')?.active).toBe(true)
expect(again.find(option => option.id === 'read-only')?.detail).toBe('Reads only.')
// English built-ins use product labels; other kebab-case names title-case.
@@ -127,7 +132,7 @@ describe('ui-permission browser plugin', () => {
confirmLabel: 'Enable Full access',
})
b.locale.setLocale('zh')
const localized = await c.ui.options(proj, new AbortController().signal)
const localized = await b.popup().options(proj, new AbortController().signal)
expect(localized.map(option => option.label)).toEqual(['仅可查看', '工作区内修改', '完全权限'])
expect(localized.find(option => option.id === 'danger-full-access')?.confirmation).toEqual({
title: '确认启用完全权限?',
@@ -143,28 +148,27 @@ describe('ui-permission browser plugin', () => {
{ value: '__proto__', name: '__proto__' },
{ value: 'plain', name: 'Ask Every Time' },
] })
const passthrough = await c.ui.options(proj, new AbortController().signal)
const passthrough = await b.popup().options(proj, new AbortController().signal)
expect(passthrough.map(option => option.label)).toEqual([
'Project Files', 'Operator Mode', 'Custom Mode', '__proto__', 'Ask Every Time',
])
// A projection that vanished between availability and open throws.
expect(() => c.ui.options({ sessionId: sid('ghost') }, new AbortController().signal))
expect(() => b.popup().options({ sessionId: sid('ghost') }, new AbortController().signal))
.toThrow(/not available on this host/)
})
it('a pick submits the /permission line; rejection and unmatched throw', async () => {
const b = await bench()
const c = b.decoration()!
const proj = { sessionId: sid('s1') }
b.values.set(sid('s1'), SELECT)
await c.ui.onSelect({ id: 'danger-full-access', label: 'danger-full-access' }, proj)
await b.popup().onSelect({ id: 'danger-full-access', label: 'danger-full-access' }, proj)
expect(b.commands).toEqual(['/permission danger-full-access'])
b.setResult({ ok: false })
await expect(c.ui.onSelect({ id: 'read-only', label: 'read-only' }, proj)).rejects.toThrow(/permission switch failed/)
await expect(b.popup().onSelect({ id: 'read-only', label: 'read-only' }, proj)).rejects.toThrow(/permission switch failed/)
b.setResult({ ok: true, matched: false })
await expect(c.ui.onSelect({ id: 'read-only', label: 'read-only' }, proj)).rejects.toThrow(/no \/permission command/)
await expect(b.popup().onSelect({ id: 'read-only', label: 'read-only' }, proj)).rejects.toThrow(/no \/permission command/)
// An unmaterialized session throws before any submit.
await expect(c.ui.onSelect({ id: 'read-only', label: 'read-only' }, { sessionId: sid('ghost') }))
await expect(b.popup().onSelect({ id: 'read-only', label: 'read-only' }, { sessionId: sid('ghost') }))
.rejects.toThrow(/not materialized/)
})
@@ -3,9 +3,8 @@
* `useAnchoredPosition` wiring: a floating panel is placed from its anchor and
* keeps tracking it while open.
*
* The geometry itself needs real layout, which jsdom does not provide — the
* browser layout scenario in `apps/web/tests/message-feedback-layout.e2e.ts`
* owns that. What is asserted here is the wiring the clamp depends on: the
* The geometry itself needs real layout, which jsdom does not provide. What
* is asserted here is the wiring the clamp depends on: the
* listeners and the panel-size observer are attached while open and released on
* close, a size change replays the placement, and the hook still works where
* `ResizeObserver` does not exist.
@@ -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-settings-plugin-inventory/README.md
README.md: 9a7ea91521c08dd1855925af59521d3af6e47b25
README.zh.md: 2427d667d92b7a4c620fc6222507ecd8c2fabcef
README.md: d56e7bcd2bc8a1590910045319db5cd3b6307e85
README.zh.md: c83a21d6bc63e9e3f4c135d00f7d4926c6588144
@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
## Summary
The **Plugin list** tab lets Web users inspect plugins without changing their configuration. It presents agent-preset compositions first and keeps the global inventory collapsed until needed. Cards expose enablement, provenance, runtime status, disabled conditions, and discovery failures; global entries supplied by presets are identified with the enabling presets. Search covers both groups and points to matches in other presets. The tab supports loading, empty, no-match, failure, and retry states without exposing transport details, and it still shows the global inventory when no preset roster is available.
The **Plugin list** tab lets Web users inspect plugins without changing their configuration. It presents agent presets first and collapses the global inventory until needed. Cards retain the package name as the primary title, identify instances by stable entry id, and expose enablement, provenance, runtime status, disabled conditions, and discovery failures; preset-provided global entries name their presets. Search covers both groups and points to matches in other presets. The tab handles loading, empty, no-match, failure, and retry states without exposing transport details, and still shows the global inventory without a preset roster.
## Table of Contents
@@ -29,7 +29,7 @@ Open the Plugins section in Settings and select the **Plugin list** tab to inspe
### Reading a card
Each collapsed card uses the short module name as its title and a small enablement tag; enabled entries also show a colored root-fiber status dot. Expanding one card reveals the declared entry id, the full module specifier, and the state facts: a preset row names the preset it comes from, its runtime status when the composition is live, and its disable condition when it carries one; a preset-provided global row explains that agent presets provide it per session, names the presets that enable it, and offers a jump into the preset group. Preset names resolve through the shared `presetDisplayText` fold (`dsh-agent-presets/display`) over [`ui-agent-preset`](../ui-agent-preset/README.md)'s dictionaries: shipped presets follow the active locale while user-authored ones keep their own metadata, so an English surface never echoes the preset files' Chinese names. Search filters both groups by module name and entry id.
Each collapsed card uses the short module name as its primary title, shows the stable entry id underneath, and carries a small enablement tag; enabled entries also show a colored root-fiber status dot. A composition-generated subtitle omits its leading `include:` marker, while hover, search, the accessible name, and expanded details retain the complete id. Long entry ids truncate in the row and remain available on hover. Expanding one card reveals the declared entry id, the full module specifier, and the state facts: a preset row names the preset it comes from, its runtime status when the composition is live, and its disable condition when it carries one; a preset-provided global row explains that agent presets provide it per session, names the presets that enable it, and offers a jump into the preset group. Preset names resolve through the shared `presetDisplayText` fold (`dsh-agent-presets/display`) over [`ui-agent-preset`](../ui-agent-preset/README.md)'s dictionaries: shipped presets follow the active locale while user-authored ones keep their own metadata, so an English surface never echoes the preset files' Chinese names. Search filters both groups by module name and entry id.
### The preset switcher
@@ -55,7 +55,7 @@ The browser plugin registers one localized `settings.plugins.tab` contribution w
### Rendering
Row keys are scope-qualified (`global:`, `preset:<id>:<index>`), so one module appearing in both scopes keeps distinct disclosure state; an entry id is shown as detail only when the row declares one and is never classified by string shape. The preset-provided marking is derived client-side: a global entry carries it when it is disabled there while at least one preset row for the same module specifier is actually enabled, so a module every preset gates off (or declares only conditionally) stays plainly disabled rather than over-claiming provision.
Row keys are scope-qualified (`global:`, `preset:<id>:<index>`), so one module appearing in both scopes keeps distinct disclosure state; a declared entry id appears in expanded details and supplies the collapsed subtitle after removal of a leading composition `include:` marker, while a row without one stays unlabeled. The preset-provided marking is derived client-side: a global entry carries it when it is disabled there while at least one preset row for the same module specifier is actually enabled, so a module every preset gates off (or declares only conditionally) stays plainly disabled rather than over-claiming provision.
</details>
@@ -9,7 +9,7 @@ kind: "package-reference"
## 概述
**插件列表**标签页让 Web 用户查看插件,而不改变其配置。它优先展示 Agent 预设组合,并在需要前收起全局清单。卡片展示启停状态、出处、运行状态、禁用条件与发现失败;由预设提供的全局条目会标明启用它的预设。搜索覆盖两个分组,并指出其他预设中的匹配。标签页支持加载、空结果、无匹配、失败与重试状态,且不暴露传输细节;没有预设 roster 时仍会展示全局清单。
**插件列表**标签页让 Web 用户查看插件,而不改变其配置。它优先展示 Agent 预设,并在需要前收起全局清单。卡片保留包名作为主标题,以稳定的条目 id 标识实例,并展示启停状态、出处、运行状态、禁用条件与发现失败;由预设提供的全局条目会列出对应预设。搜索覆盖两个分组,并指出其他预设中的匹配。标签页处理加载、空结果、无匹配、失败与重试状态,且不暴露传输细节;没有预设 roster 时仍会展示全局清单。
## 目录
@@ -29,7 +29,7 @@ kind: "package-reference"
### 阅读卡片
每张收起的卡片使用模块短名称作为标题,并以小标签表示启停状态;已启用的条目还会显示彩色根 fiber 状态圆点。展开卡片后会显示声明的条目 id、完整模块标识与状态事实:预设行说明它来自哪个预设、组合存活时的运行状态,以及它携带的禁用条件;被预设提供的全局行说明它由 Agent 预设按会话提供、列出启用它的预设,并提供跳转到预设组的入口。预设名经共享的 `presetDisplayText` 纯函数(`dsh-agent-presets/display`)叠在 [`ui-agent-preset`](../ui-agent-preset/README.zh.md) 的字典上解析:内置预设走当前语言,用户自建预设保留自己的元数据,因此英文界面不会回显预设文件里的中文名。搜索按模块名称与条目 id 过滤两组。
每张收起的卡片使用模块短名称作为主标题,在下方显示稳定的条目 id,并以小标签表示启停状态;已启用的条目还会显示彩色根 fiber 状态圆点。组合生成的次标题省略开头的 `include:` 标记;悬停、搜索、无障碍名称与展开详情仍保留完整 id。长条目 id 会在行内截断,悬停时仍可查看完整值。展开卡片后会显示声明的条目 id、完整模块标识与状态事实:预设行说明它来自哪个预设、组合存活时的运行状态,以及它携带的禁用条件;被预设提供的全局行说明它由 Agent 预设按会话提供、列出启用它的预设,并提供跳转到预设组的入口。预设名经共享的 `presetDisplayText` 纯函数(`dsh-agent-presets/display`)叠在 [`ui-agent-preset`](../ui-agent-preset/README.zh.md) 的字典上解析:内置预设走当前语言,用户自建预设保留自己的元数据,因此英文界面不会回显预设文件里的中文名。搜索按模块名称与条目 id 过滤两组。
### 预设切换器
@@ -55,7 +55,7 @@ kind: "package-reference"
### 渲染
行 key 按作用域限定(`global:`、`preset:<id>:<index>`),因此同一模块出现在两个作用域时保持各自的展开状态;条目 id 只在行声明了它时作为详情展示,代码不按字符串形状对它分类。预设提供标记在客户端推导:一个全局条目在全局被停用、且至少一个预设行对同一模块标识实际启用时才携带它,因此被所有预设关掉(或仅条件声明)的模块保持单纯的已停用,而不是夸大提供关系。
行 key 按作用域限定(`global:`、`preset:<id>:<index>`),因此同一模块出现在两个作用域时保持各自的展开状态;声明的条目 id 出现在展开详情中,并在去掉开头的组合 `include:` 标记后作为收起次标题,没有 id 的行不显示次级标签。预设提供标记在客户端推导:一个全局条目在全局被停用、且至少一个预设行对同一模块标识实际启用时才携带它,因此被所有预设关掉(或仅条件声明)的模块保持单纯的已停用,而不是夸大提供关系。
</details>
@@ -126,9 +126,8 @@
.cardContent {
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
flex-direction: column;
align-items: stretch;
width: 100%;
min-height: 52px;
border: 0;
@@ -150,14 +149,36 @@
outline-offset: -2px;
}
.cardTitle {
.cardMainRow {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
min-width: 0;
}
.cardTitle,
.cardIdentity {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.cardTitle {
flex: 1;
min-width: 0;
font-size: 14px;
line-height: 20px;
font-weight: 600;
text-overflow: ellipsis;
white-space: nowrap;
}
.cardIdentity {
display: block;
width: 100%;
color: var(--dsw-alias-label-tertiary);
font-family: var(--ds-font-family-code);
font-size: 11px;
line-height: 16px;
}
.cardTrailing {
@@ -63,6 +63,11 @@ function moduleShortName(moduleName: string): string {
.replace(/^dsh-(?:host-|client-)?/, '')
}
/** Display an entry identity without the composition-only `include:` marker. */
function entrySubtitle(entryId: string): string {
return entryId.replace(/^include:/, '')
}
/** Whether one row's module name or entry id matches the catalog query. */
function matches(moduleName: string, entryId: string | null, normalizedQuery: string): boolean {
if (normalizedQuery.length === 0) return true
@@ -113,11 +118,14 @@ function PluginCard({ rowKey, moduleName, entryId, trailing, ariaLabel, failed,
aria-label={ariaLabel}
onClick={() => { onToggle(rowKey) }}
>
<strong className={css.cardTitle} title={moduleName}>{moduleShortName(moduleName)}</strong>
<span className={css.cardTrailing}>
{trailing}
<IconChevronDownOutline14 className={css.chevron} size={12} aria-hidden="true" />
<span className={css.cardMainRow}>
<strong className={css.cardTitle} title={moduleName}>{moduleShortName(moduleName)}</strong>
<span className={css.cardTrailing}>
{trailing}
<IconChevronDownOutline14 className={css.chevron} size={12} aria-hidden="true" />
</span>
</span>
{entryId === null ? null : <code className={css.cardIdentity} title={entryId}>{entrySubtitle(entryId)}</code>}
</button>
{open ? <div className={css.cardDetails} id={detailId}>{children}</div> : null}
</li>
@@ -280,7 +288,7 @@ export function PluginInventorySettingsTab({ list, presetName, t }: PluginInvent
failed={failed}
expanded={expanded}
onToggle={toggleRow}
ariaLabel={`${title}, ${stateText}`}
ariaLabel={`${title}${row.entryId === null ? '' : `, ${row.entryId}`}, ${stateText}`}
trailing={(
<>
{row.enabled === true && !failed && row.fiberPhase !== null
@@ -326,7 +334,7 @@ export function PluginInventorySettingsTab({ list, presetName, t }: PluginInvent
failed={failed}
expanded={expanded}
onToggle={toggleRow}
ariaLabel={`${title}, ${stateText}`}
ariaLabel={`${title}, ${entry.entryId}, ${stateText}`}
trailing={(
<>
{entry.enabled && !failed && entry.fiberPhase !== null
@@ -115,16 +115,16 @@ describe('PluginInventorySettingsTab', () => {
expect(screen.getByText(`1 ${en.failedCountLabel}`)).toBeTruthy()
// A preset row expands into its provenance facts.
fireEvent.click(screen.getByRole('button', { name: 'pwsh, Conditional' }))
fireEvent.click(screen.getByRole('button', { name: 'pwsh, pwsh, Conditional' }))
expect(screen.getByText(en.fromPreset)).toBeTruthy()
expect(screen.getByText('标准模式')).toBeTruthy()
expect(screen.getByText(en.condition)).toBeTruthy()
expect(screen.getByText('process.platform === \'win32\'')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: 'pwsh, Conditional' }))
fireEvent.click(screen.getByRole('button', { name: 'pwsh, pwsh, Conditional' }))
expect(screen.queryByText(en.condition)).toBeNull()
// A failed preset row names its runtime state instead of a condition.
fireEvent.click(screen.getByRole('button', { name: 'crashy, Failed' }))
fireEvent.click(screen.getByRole('button', { name: 'crashy, crashy, Failed' }))
expect(screen.getByText(en.runtime)).toBeTruthy()
expect(screen.getByText('Failed to start')).toBeTruthy()
@@ -134,6 +134,39 @@ describe('PluginInventorySettingsTab', () => {
expect(screen.getByText(en.moduleLabel).nextElementSibling?.textContent).toBe('@fixture/anonymous')
})
it('distinguishes collapsed same-module rows by stable entry id', async () => {
const longId = 'include:agent-presets:tool-subagent-secondary-with-a-complete-stable-identity'
const subtitle = 'agent-presets:tool-subagent-secondary-with-a-complete-stable-identity'
await renderReady({
entries: [],
agentPresets: [{
id: 'same-module',
trust: 'user',
isDefault: true,
rows: [
{ entryId: 'tool-subagent-primary', moduleName: '@deepseek-ai/dsh-tool-subagent', enabled: true, fiberPhase: null },
{ entryId: longId, moduleName: '@deepseek-ai/dsh-tool-subagent', enabled: false, fiberPhase: null },
],
}],
})
expect(screen.getByRole('button', { name: 'tool-subagent, tool-subagent-primary, Enabled' })
.getAttribute('aria-expanded')).toBe('false')
const secondary = screen.getByRole('button', { name: `tool-subagent, ${longId}, Disabled` })
expect(secondary.getAttribute('aria-expanded')).toBe('false')
expect(secondary.children).toHaveLength(2)
expect(secondary.children[0]?.textContent).toContain('tool-subagent')
expect(secondary.children[0]?.textContent).toContain('Disabled')
expect(secondary.children[1]?.textContent).toBe(subtitle)
expect(screen.getByTitle(longId).textContent).toBe(subtitle)
fireEvent.change(screen.getByRole('searchbox', { name: en.search }), { target: { value: 'include:agent-presets:tool-subagent-secondary' } })
expect(screen.queryByRole('button', { name: 'tool-subagent, tool-subagent-primary, Enabled' })).toBeNull()
const filteredSecondary = screen.getByRole('button', { name: `tool-subagent, ${longId}, Disabled` })
fireEvent.click(filteredSecondary)
expect(filteredSecondary.getAttribute('aria-expanded')).toBe('true')
})
it('expands the global plane with failures first and preset-provided rows inline', async () => {
const view = await renderReady()
@@ -148,21 +181,21 @@ describe('PluginInventorySettingsTab', () => {
// Rows the presets took over sit inline, marked instead of plainly disabled.
expect(screen.getAllByText(en.presetEnabledTag)).toHaveLength(2)
fireEvent.click(screen.getByRole('button', { name: 'tool-bash, Enabled via presets' }))
fireEvent.click(screen.getByRole('button', { name: 'tool-bash, bash-host, Enabled via presets' }))
expect(screen.getByText(en.presetProvidedDetail)).toBeTruthy()
expect(screen.getByText(en.enabledIn)).toBeTruthy()
expect(screen.getByText('标准模式 · ptc')).toBeTruthy()
// The failed global card reports its runtime state.
fireEvent.click(screen.getByRole('button', { name: 'telemetry, Failed' }))
fireEvent.click(screen.getByRole('button', { name: 'telemetry, telemetry, Failed' }))
expect(screen.getByText('Failed to start')).toBeTruthy()
// An enabled entry with no live fiber says so in its details, dot-free.
fireEvent.click(screen.getByRole('button', { name: 'unobserved-name, Enabled' }))
fireEvent.click(screen.getByRole('button', { name: 'unobserved-name, unobserved, Enabled' }))
expect(screen.getByText('Not running')).toBeTruthy()
// A disabled row outside every preset stays plainly disabled.
fireEvent.click(screen.getByRole('button', { name: 'dormant, Disabled' }))
fireEvent.click(screen.getByRole('button', { name: 'dormant, dormant, Disabled' }))
expect(screen.queryByText(en.presetProvidedDetail)).toBeNull()
fireEvent.click(globalToggle())
@@ -179,7 +212,7 @@ describe('PluginInventorySettingsTab', () => {
pickPreset('ptc')
expect(view.container.querySelector('[data-preset-plugin-count]')?.getAttribute('data-preset-plugin-count')).toBe('3')
fireEvent.click(screen.getAllByRole('button', { name: 'tool-bash, Enabled' })[0]!)
fireEvent.click(screen.getByRole('button', { name: 'tool-bash, bash, Enabled' }))
// An unnamed preset labels provenance by its id.
expect(screen.getByText(en.fromPreset).nextElementSibling?.textContent).toBe('ptc')
@@ -227,11 +260,11 @@ describe('PluginInventorySettingsTab', () => {
])
fireEvent.keyDown(document, { key: 'Escape' })
fireEvent.click(screen.getByRole('button', { name: 'pwsh, Conditional' }))
fireEvent.click(screen.getByRole('button', { name: 'pwsh, pwsh, Conditional' }))
expect(screen.getByText(en.fromPreset).nextElementSibling?.textContent).toBe('Localized standard')
fireEvent.click(globalToggle())
fireEvent.click(screen.getByRole('button', { name: 'tool-bash, Enabled via presets' }))
fireEvent.click(screen.getByRole('button', { name: 'tool-bash, bash-host, Enabled via presets' }))
expect(screen.getByText('Localized standard · Localized ptc')).toBeTruthy()
})
@@ -241,7 +274,7 @@ describe('PluginInventorySettingsTab', () => {
fireEvent.click(screen.getByRole('menuitem', { name: 'ptc' }))
fireEvent.click(globalToggle())
fireEvent.click(screen.getByRole('button', { name: 'tool-bash, Enabled via presets' }))
fireEvent.click(screen.getByRole('button', { name: 'tool-bash, bash-host, Enabled via presets' }))
fireEvent.click(screen.getByRole('button', { name: en.viewInPreset }))
expect(screen.getByRole('button', { name: en.switcherLabel }).textContent)
.toBe('标准模式 (default)')
@@ -290,10 +323,10 @@ describe('PluginInventorySettingsTab', () => {
expect(globalToggle().getAttribute('aria-expanded')).toBe('true')
expect(screen.getAllByRole('listitem')).toHaveLength(2)
fireEvent.click(screen.getByRole('button', { name: 'hmr, Enabled' }))
fireEvent.click(screen.getByRole('button', { name: 'hmr, hmr, Enabled' }))
expect(screen.getByText(en.runtime)).toBeTruthy()
expect(view.container.querySelector('[data-loader-entry]')?.textContent).toBe('hmr')
fireEvent.click(screen.getByRole('button', { name: 'off, Disabled' }))
fireEvent.click(screen.getByRole('button', { name: 'off, off, Disabled' }))
expect(screen.getAllByText(en.moduleLabel).length).toBeGreaterThan(0)
expect(screen.queryByText(en.runtime)).toBeNull()
})
@@ -0,0 +1,95 @@
/** Host budget decisions use controlled clocks and ELU samples; worker execution and binding transport stay real. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Context } from '@deepseek-ai/cordis'
import { WorkerThreadCodeRuntime } from '@deepseek-ai/dsh-code-runtime-worker-thread'
import type { CodeRunResult } from '@deepseek-ai/dsh-code-runtime'
const meter = vi.hoisted(() => ({ sample: vi.fn() }))
vi.mock('node:worker_threads', async (importOriginal) => {
const original = await importOriginal<typeof import('node:worker_threads')>()
return {
...original,
Worker: class extends original.Worker {
constructor(...args: ConstructorParameters<typeof original.Worker>) {
super(...args)
this.performance.eventLoopUtilization = meter.sample
}
},
}
})
describe('worker budgets with controlled ELU samples and real binding transport', () => {
let ctx: Context
let controller: AbortController
let run: Promise<CodeRunResult> | undefined
let release: (() => void) | undefined
beforeEach(() => {
ctx = new Context()
controller = new AbortController()
run = undefined
release = undefined
meter.sample.mockReset().mockReturnValue({ active: 10, idle: 0, utilization: 1 })
// Worker bootstrap and scheduling contribute to ELU active time; only the
// measured input and host deadlines are controlled, not worker execution.
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] })
})
afterEach(async () => {
const owned = { ctx, controller, run, release }
try {
owned.controller.abort('test cleanup')
owned.release?.()
} finally {
vi.useRealTimers()
}
try {
await owned.run
} finally {
await owned.ctx.fiber.dispose()
}
})
async function pendingBinding(): Promise<void> {
await ctx.plugin(WorkerThreadCodeRuntime, { computeMs: 1_000, maxWallMs: 30_000 })
let entered!: () => void
const ready = new Promise<void>((resolve) => { entered = resolve })
const binding = new Promise<string>((resolve) => { release = () => { resolve('slow-done') } })
run = ctx.codeRuntime.run({
program: 'return await tools.slow({})',
bindings: [{ global: 'tools', functions: { slow: () => { entered(); return binding } } }],
signal: controller.signal,
})
await Promise.race([
ready,
run.then((result) => { throw new Error('Worker settled before binding entry: ' + JSON.stringify(result)) }),
])
}
it('does not charge a binding wait longer than the compute budget', async () => {
await pendingBinding()
const settled = vi.fn()
void run!.then(settled, settled)
meter.sample.mockReturnValue({ active: 10, idle: 1_500, utilization: 10 / 1_510 })
await vi.advanceTimersByTimeAsync(1_500)
expect(meter.sample).toHaveBeenCalled()
expect(settled).not.toHaveBeenCalled()
release!()
expect(await run).toEqual({ logs: [], value: 'slow-done' })
})
it('expires active time even while a binding is pending', async () => {
await pendingBinding()
meter.sample.mockReturnValue({ active: 1_001, idle: 1_500, utilization: 1_001 / 2_501 })
await vi.advanceTimersByTimeAsync(25)
expect(await run).toEqual({ logs: [], error: { kind: 'timeout', message: 'compute budget exhausted (1000ms busy)' } })
})
it('expires the wall ceiling while active time remains below the compute budget', async () => {
await pendingBinding()
meter.sample.mockReturnValue({ active: 10, idle: 30_000, utilization: 10 / 30_010 })
await vi.advanceTimersByTimeAsync(30_000)
expect(await run).toEqual({ logs: [], error: { kind: 'timeout', message: 'wall-clock ceiling reached (30000ms)' } })
})
})
@@ -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/experimental/webworker-runtime/README.md
README.md: b9454e308e92ba78e3d11aa72dfd3723e8c07568
README.zh.md: 4d39f145d2ce2c826906ea1e60a26488eab9467e
README.md: 2327851be62bc4e09e8678cd8d0c7b07663d1bdd
README.zh.md: afd1bef17c8e921b4a6e97bd224deaa0f94e9486
@@ -32,6 +32,8 @@ Three artifacts from one tsdown pipeline:
Acceptance lives in `apps/web/tests/preview-boot.e2e.ts`, which serves the real built pages and drives the pre-boot chooser plus Worker activation in headless Chromium. The empty selection exercises first-run startup. The `vfs-example` overlay supplies ordinary workspace files and plaintext persistence artifacts for cold Workspace/Session discovery, tool presentation, subagent navigation, and history paging without a model request. The fixture generator owns current-generation logs and the projection cache; committed predecessor logs remain byte-identical alongside them. The chooser reserves WebFS as a separate user-authorized source; that provider does not read the built-in fixture.
The [built-bundle import sweep](tests/compile/transform-corpus-check.ts) checks bare Node imports after the library build. Its Dockkit exception accepts only Node’s unknown-extension error for the expected stylesheet; other failures and unexpectedly successful exempt imports remain errors. See the [CI observation decision](../../../.agents/notes/implemented/testing/2026-09-08-ci-completion-observations.md).
-----
<a id="model-experience"></a>
@@ -32,6 +32,8 @@ kind: "package-library"
验收在 `apps/web/tests/preview-boot.e2e.ts`:静态服务真实构建页面,在 headless Chromium 里驱动 pre-boot 选择面板与 Worker 激活。空白选择验证首次启动;`vfs-example` overlay 提供普通 workspace 文件与明文 persistence 产物,无需模型请求即可验证 Workspace/Session 冷发现、工具呈现、subagent 导航和历史分页。fixture 生成器负责当前代日志与投影缓存;已提交的前代日志逐字节保持不变,与它们并存。选择面板为 WebFS 保留独立的用户授权来源;该 provider 不读取内置 fixture。
[已构建 bundle 导入检查](tests/compile/transform-corpus-check.ts)在库构建后检查裸 Node 导入。Dockkit 例外仅接受 Node 针对预期样式表报告的未知扩展名错误;其他失败以及意外成功的豁免导入仍然报错。参见 [CI 观察决策](../../../.agents/notes/implemented/testing/2026-09-08-ci-completion-observations.zh.md)。
-----
<a id="model-experience"></a>
@@ -23,6 +23,8 @@ import { join } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
const repositoryRoot = fileURLToPath(new URL('../../../../../', import.meta.url))
const DOCKKIT_BUNDLE = 'packages/client/ui-dockkit/lib/index.js'
const DOCKKIT_CSS = join(repositoryRoot, 'packages/client/ui-dockkit/lib/components/dockkit.module.css')
/**
* Files Node's ESM loader cannot import in this repository. None is a finding:
@@ -34,7 +36,7 @@ const repositoryRoot = fileURLToPath(new URL('../../../../../', import.meta.url)
* import re-registers koffi's type names and fails as the second load.
*/
const BASELINE_EXEMPT: ReadonlyMap<string, string> = new Map([
['packages/client/ui-dockkit/lib/index.js', 'imports .css, which bare Node cannot load'],
[DOCKKIT_BUNDLE, 'imports .css, which bare Node cannot load'],
['packages/client/ui-primitives/lib/index.js', 'imports .css, which bare Node cannot load'],
['packages/client/web/lib/index.js', 'imports .css, which bare Node cannot load'],
['packages/subprocess/win32-process/lib/index.js', 'koffi type-name collision on a second load'],
@@ -109,7 +111,10 @@ if (files.length === 0) {
try {
await import(pathToFileURL(file).href)
} catch (reason) {
if (exemption === undefined) {
const expectedDockkitCss = reason instanceof Error
&& 'code' in reason && reason.code === 'ERR_UNKNOWN_FILE_EXTENSION'
&& reason.message === `Unknown file extension ".css" for ${DOCKKIT_CSS}`
if (exemption === undefined || (key === DOCKKIT_BUNDLE && !expectedDockkitCss)) {
// A bundle that stopped being importable is a real finding, so it
// fails rather than joining a tolerated total.
fail(`- UNEXPECTED BASELINE FAILURE ${key}: ${(reason as Error).message.split('\n')[0]}`)
@@ -13,8 +13,8 @@
* The corpus is the build output, so this skips on a tree that has none.
*/
import { spawnSync } from 'node:child_process'
import { fileURLToPath } from 'node:url'
import { expect, test } from 'vitest'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { expect, test, TestRunner } from 'vitest'
const runner = fileURLToPath(new URL('./transform-corpus-check.ts', import.meta.url))
@@ -30,3 +30,51 @@ test('every built bundle imports under Node', (context) => {
expect(output.split('\n').filter(line => line.startsWith('- ')).join('\n')).toBe('')
expect(finished.status, output).toBe(0)
}, 900_000)
// The hook replaces only the chosen bundle; shared build artifacts stay intact.
test.each([
['expected-css', 0, 'baselineExempt=1 unexpectedBaselineFailure=0'],
['error', 1, '- UNEXPECTED BASELINE FAILURE'],
['other-css', 1, '- UNEXPECTED BASELINE FAILURE'],
['other-code', 1, '- UNEXPECTED BASELINE FAILURE'],
['clean', 1, '- STALE EXEMPTION'],
] as const)('classifies dockkit import: %s', (mode, status, finding) => {
const root = new URL('../../../../../', import.meta.url)
const bundle = 'packages/client/ui-dockkit/lib/index.js'
const css = fileURLToPath(new URL('packages/client/ui-dockkit/lib/components/dockkit.module.css', root))
const message = mode === 'error'
? 'dockkit-negative-control'
: `Unknown file extension ".css" for ${mode === 'other-css' ? `${css}.other.css` : css}`
const source = mode === 'clean'
? 'export {}'
: `throw Object.assign(new Error(${JSON.stringify(message)}), { code: ${JSON.stringify(mode === 'other-code' ? 'ERR_OTHER' : 'ERR_UNKNOWN_FILE_EXTENSION')} })`
const script = `
import { registerHooks } from 'node:module'
const target = ${JSON.stringify(new URL(bundle, root).href)}
registerHooks({
resolve(specifier, context, nextResolve) {
if (specifier === target) return { url: target, shortCircuit: true }
return nextResolve(specifier, context)
},
load(url, context, nextLoad) {
if (url === target) {
return { format: 'module', shortCircuit: true, source: ${JSON.stringify(source)} }
}
return nextLoad(url, context)
},
})
process.argv = [process.execPath, 'corpus-classification', ${JSON.stringify(bundle)}]
await import(${JSON.stringify(pathToFileURL(runner).href)})
`
const finished = spawnSync(process.execPath, ['--import', 'tsx/esm', '--input-type=module', '-e', script], {
cwd: fileURLToPath(root), encoding: 'utf8', timeout: TestRunner.getCurrentTest()!.timeout,
})
const output = `${finished.stdout}${finished.stderr}`
expect(finished.error).toBeUndefined()
expect(finished.signal).toBeNull()
expect(finished.status, output).toBe(status)
expect(output).toContain(finding)
if (mode === 'error' || mode === 'other-css' || mode === 'other-code') {
expect(output).toContain(`- UNEXPECTED BASELINE FAILURE ${bundle}: ${message}\n`)
}
})
@@ -847,6 +847,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
occupants: [
'client-ui-commands PopupSelectView id \'command-popup\'',
'client-ui-input-trigger MenuView id \'slash-menu\'',
'client-ui-message-feedback FeedbackDialog id \'feedback-dialog\'',
],
replaceRisk: 'none',
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.overlay\', () => ctx.slots.register(\n { name: \'conversation.input.overlay\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
@@ -1557,6 +1557,19 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
},
],
},
{
key: 'sessionFeedback',
summary: 'Host Remote through which a product surface records a Session-level remark.',
description: 'Host Remote through which a product surface records a Session-level remark.',
methods: [
{
signature: '@Remote(\'record\') record(request: SessionFeedbackRecordRequest): Promise<SessionFeedbackRecordResult>',
description: 'Record one remark on a live Session.',
parameters: [{ name: 'request', description: 'target Session plus the optional text and category.' }],
returns: 'the recorded postcondition, or `session-not-found` when no live Session carries the id.',
},
],
},
{
key: 'sessionFileReferences',
summary: 'Host Remote adapter over the composed file-reference provider.',
@@ -4172,6 +4185,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [
name: 'EpochHeader',
declaration: 'export interface EpochHeader {\n config: LlmCallConfig;\n adapterDefaults?: LlmCallConfigAdapterDefaults;\n tools?: ToolSchema[];\n}',
},
{
name: 'FeedbackCategory',
declaration: 'export type FeedbackCategory = \'task-result\' | \'instruction-following\' | \'product-interaction\' | \'service-stability\' | \'resource-cost\' | \'security-privacy-permission\' | \'other\';',
},
{
name: 'FiberState',
declaration: 'export type FiberState = FiberStateEnum;',
@@ -4598,7 +4615,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [
},
{
name: 'MessageFeedbackItem',
declaration: 'export interface MessageFeedbackItem {\n readonly messageId: MessageId;\n readonly rating: MessageFeedbackRating;\n readonly note?: string;\n readonly version: MessageFeedbackVersion;\n readonly createdAt: number;\n readonly updatedAt: number;\n}',
declaration: 'export interface MessageFeedbackItem {\n readonly messageId: MessageId;\n readonly rating: MessageFeedbackRating;\n readonly note?: string;\n readonly category?: FeedbackCategory;\n readonly version: MessageFeedbackVersion;\n readonly createdAt: number;\n readonly updatedAt: number;\n}',
},
{
name: 'MessageFeedbackListRequest',
@@ -4622,7 +4639,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [
},
{
name: 'MessageFeedbackPutRequest',
declaration: 'export interface MessageFeedbackPutRequest {\n readonly sessionId: SessionId;\n readonly messageId: MessageId;\n readonly rating: MessageFeedbackRating;\n readonly note?: string;\n readonly ifVersion: MessageFeedbackVersion | null;\n}',
declaration: 'export interface MessageFeedbackPutRequest {\n readonly sessionId: SessionId;\n readonly messageId: MessageId;\n readonly rating: MessageFeedbackRating;\n readonly note?: string;\n readonly category?: FeedbackCategory;\n readonly ifVersion: MessageFeedbackVersion | null;\n}',
},
{
name: 'MessageFeedbackPutResult',
@@ -5132,6 +5149,22 @@ export const TYPE_API: readonly TypeApiEntry[] = [
name: 'SessionEventWindow',
declaration: 'export interface SessionEventWindow {\n session: SessionHeader;\n inheritedEventCount: SessionLogOffset;\n target: SessionEvent;\n events: SessionEvent[];\n startSeq: SessionSeq;\n endSeq: SessionSeq;\n}',
},
{
name: 'SessionFeedbackRecordRequest',
declaration: 'export interface SessionFeedbackRecordRequest {\n readonly sessionId: SessionId;\n readonly text?: string;\n readonly category?: FeedbackCategory;\n}',
},
{
name: 'SessionFeedbackRecordResult',
declaration: 'export type SessionFeedbackRecordResult = {\n readonly ok: true;\n readonly value: SessionFeedbackRecordValue;\n} | {\n readonly ok: false;\n readonly error: SessionFeedbackSessionNotFound;\n};',
},
{
name: 'SessionFeedbackRecordValue',
declaration: 'export interface SessionFeedbackRecordValue {\n readonly recorded: true;\n}',
},
{
name: 'SessionFeedbackSessionNotFound',
declaration: 'export interface SessionFeedbackSessionNotFound {\n readonly code: \'session-not-found\';\n readonly sessionId: SessionId;\n}',
},
{
name: 'SessionFollowFrame',
declaration: 'export type SessionFollowFrame = {\n readonly type: \'snapshot\';\n readonly header: SessionWireHeader;\n readonly cursor: number;\n readonly records: readonly SessionHistoryRecord[];\n readonly hasMore: boolean;\n readonly projections: SessionProjectionBaseline;\n readonly assistantStream?: SessionAssistantStreamBaseline;\n} | SessionEventEntry | {\n readonly type: \'assistant-stream\';\n readonly frame: SessionAssistantStreamFrame;\n};',
+2 -2
View File
@@ -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/feedback/README.md
README.md: ee813fea0350ec6cddfbf66ee21807ed543960d3
README.zh.md: 736ee5b77e5033f550c29eea14e1d429556da8e4
README.md: e4b538f2a498cdfa4e265226283c923a19b8b69e
README.zh.md: 83208f63a9857cc5db37822332e5b7acb4d56007
+2 -2
View File
@@ -22,8 +22,8 @@ The feedback group collects human opinions about the harness's work: users can s
| Package | Role |
|---|---|
| [`command-feedback`](command-feedback/README.md) | A `/feedback` command that records a free-text session remark with one command, without a model turn |
| [`message-feedback`](message-feedback/README.md) | Per-message ratings and notes, served to product surfaces through the `messageFeedback` service |
| [`command-feedback`](command-feedback/README.md) | Session-level feedback: the `/feedback` command, the `sessionFeedback` Remote behind the Web dialog, and the fixed category taxonomy, all without a model turn |
| [`message-feedback`](message-feedback/README.md) | Per-message ratings, categories, and notes, served to product surfaces through the `messageFeedback` service |
Session remarks are a one-way signal: recording one is safe at any point in a conversation and never changes what the model sees. With a feedback-gated sharing policy, recording a session remark is what releases the session for sharing.
+2 -2
View File
@@ -22,8 +22,8 @@ feedback 组收集用户对 harness 工作成果的意见:用户可以提交
| 包 | 职责 |
|---|---|
| [`command-feedback`](command-feedback/README.zh.md) | 一条命令即可记录自由文本会话评价的 `/feedback` 命令,无需模型轮次 |
| [`message-feedback`](message-feedback/README.zh.md) | 逐消息评分与备注,通过 `messageFeedback` 服务提供给产品界面 |
| [`command-feedback`](command-feedback/README.zh.md) | 会话级反馈:`/feedback` 命令、Web 弹窗背后的 `sessionFeedback` Remote,以及固定分类表,均无需模型轮次 |
| [`message-feedback`](message-feedback/README.zh.md) | 逐消息评分、分类与备注,通过 `messageFeedback` 服务提供给产品界面 |
会话评价是单向信号:在对话的任何时刻记录它都是安全的,且绝不会改变模型看到的内容。在 feedback-gated 共享策略下,记录会话评价正是释放会话共享的动作。
@@ -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/feedback/command-feedback/README.md
README.md: 83cb5b759431607a1702b2cc3038532d47db2d32
README.zh.md: 493ddf72b3b22454773dedcfbdd7d6910bf41e02
README.md: ad310f15b5b5b49fe879e063bd7d3c7c5518ebb8
README.zh.md: d0a4ab64a0f41165c291d974684cf2c7b241e7a4
+35 -13
View File
@@ -1,5 +1,5 @@
---
description: "Free-text session feedback through a `/feedback` command, for users and maintainers choosing, composing, or debugging feedback capture."
description: "Session feedback: the `/feedback` command, the `sessionFeedback` Host Remote behind the Web feedback dialog, and the fixed category taxonomy; for users and maintainers choosing, composing, or debugging feedback capture."
kind: "package-reference"
---
@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
## Summary
`dsh-command-feedback` lets a user tell the harness what they think of a session: type `/feedback` plus a remark, and the remark is recorded and acknowledged. Recording is immediate and never starts model work, so it is safe at any point in a conversation — the model neither sees the remark nor is interrupted by it. The acknowledgement names the session and the anonymous user. The command ships with the Web client and needs no configuration; headless, ACP, and JSON-RPC entry points do not provide slash commands and cannot run it.
`dsh-command-feedback` lets a user tell the harness what they think of a session. Typing `/feedback` plus a remark records it and acknowledges the session and anonymous user ids; the Web feedback dialog records a category and an optional description through the `sessionFeedback` Host Remote. Recording is immediate and never starts model work: the model neither sees the remark nor is interrupted by it. The package also owns the fixed category taxonomy every feedback surface files under. It ships with the standard `dsh` base and needs no configuration; headless, ACP, and JSON-RPC entry points provide no slash commands.
## Table of Contents
@@ -38,11 +38,30 @@ Type `/feedback` followed by your remark and send it. A successful entry is ackn
Surrounding whitespace is trimmed, but the remark is otherwise kept exactly as typed: no truncation, case folding, or command parsing — `/feedback /plan felt slow` records that literal text. Each command records its own entry; nothing is merged or replaced.
<a id="the-web-feedback-dialog"></a>
### The Web feedback dialog
In the Web client a bare `/feedback` — picked from the composer menu or typed and sent without text — opens the feedback dialog instead of the usage error. The dialog offers the seven categories below and a free-text box; every field is optional and an empty submission is accepted, and the conversation log travels with the recorded event as with every feedback event. It records through `sessionFeedback.record`, which appends the same `feedback/record` event without command bookkeeping and without an acknowledgement row; the dialog shows a toast instead.
| Category id | Meaning |
|---|---|
| `task-result` | The outcome of the task |
| `instruction-following` | Understanding and following instructions |
| `product-interaction` | Product features and interaction |
| `service-stability` | Service stability |
| `resource-cost` | Resource usage and cost |
| `security-privacy-permission` | Security, privacy, and permissions |
| `other` | Anything else |
The ids are durable log vocabulary shared with per-message feedback; each surface owns its localized labels.
### Recording feedback from your own UI
Feedback does not have to come from the slash command: any UI, hook, or host integration can record a remark directly, with the same guarantees and without a model turn. A custom app that wants the slash command mounts the command registry plus this plugin:
Feedback does not have to come from the slash command or the dialog: any UI, hook, or host integration can record a remark directly through `recordFeedback` or the `sessionFeedback` Remote, with the same guarantees and without a model turn. A custom app that wants the slash command mounts the Session store, the command registry, and this plugin; the Session store is what the `sessionFeedback` Remote resolves live Sessions from:
```yaml
- id: session
name: '@deepseek-ai/dsh-session'
- id: commands
name: '@deepseek-ai/dsh-commands'
- id: command-feedback
@@ -61,17 +80,18 @@ The Web client ships the command. Headless mode, ACP automation, and JSON-RPC pr
### Design concept
The remark is one append-only fact in the session log, owned by the event rather than by the command that produced it: feedback can arrive from any trigger, so the fact must not depend on the slash command. The command keeps its own bookkeeping payload-free, so the remark text exists in exactly one place in the log, and the event never surfaces to the model.
The remark is one append-only fact in the session log, owned by the event rather than by the trigger that produced it: feedback can arrive from the command, the dialog, or any integration, so the fact must not depend on the slash command. The command keeps its own bookkeeping payload-free, so the remark text exists in exactly one place in the log, and the event never surfaces to the model.
### How a remark is recorded
The producer trims the text, rejects empty input, and writes one event into the session log; the `/feedback` handler is a thin wrapper over that same producer and starts no model work. The write is eager but not flushed: the acknowledgement means the entry reached the log, not the disk. The first accepted remark for a harness home also mints the anonymous user id the acknowledgement reports. The exact producer contract and event payload live in [`src/index.ts`](src/index.ts).
The producer trims the text, records blank text as absent, and writes one event into the session log even when the entry carries neither text nor category; the `/feedback` handler rejects empty input itself and is otherwise a thin wrapper over that same producer, and the `sessionFeedback.record` Remote resolves the live Session by id and calls it too, answering `session-not-found` when no live owner carries the id. Neither path starts model work. The write is eager but not flushed: the acknowledgement means the entry reached the log, not the disk. The first accepted command remark for a harness home also mints the anonymous user id the acknowledgement reports. The exact producer contract lives in [`src/index.ts`](src/index.ts); the event payload, the taxonomy, and the Remote vocabulary live in [`src/types.ts`](src/types.ts).
### Source map
| File | Role |
|---|---|
| [`src/index.ts`](src/index.ts) | Plugin entry: `feedback/record` event declaration, `recordFeedback` producer, `/feedback` command registration |
| [`src/index.ts`](src/index.ts) | Plugin entry: `recordFeedback` producer, the `sessionFeedback` Remote service, `/feedback` command registration |
| [`src/types.ts`](src/types.ts) | `feedback/record` event declaration, the category taxonomy, and the Remote request and result types |
| — | No runtime invariant companion is published; each `feedback/record` is an independent append-only fact with no cross-event or mutable-data relationship. |
</details>
@@ -86,6 +106,7 @@ Read these pages when the package-level contract is not enough. They cover the c
- [dsh-commands](../../interaction/commands/README.md) — the registry that discovers the global command and its `recordInput` semantics.
- [Session persistence subsystem](../../../docs/subsystems/persistence.md) — how appended events become durable and what a flush barrier means.
- [Anonymous user identity](../../identity/anonymous-user-id/README.md) — the id the acknowledgement reports.
- [ui-message-feedback](../../client/ui-message-feedback/README.md) — the Web feedback dialog that records through the `sessionFeedback` Remote.
- [Feedback package map](../README.md) — where log-only capture sits next to per-message feedback.
-----
@@ -97,7 +118,7 @@ Read these pages when the package-level contract is not enough. They cover the c
#### What the model sees
Nothing. The slash input, `feedback/record`, and the acknowledgement are absent from model requests. The feedback event and registry lifecycle records are log-only and carry no `surfaceOp`, so they never reach the ordered surface, `deriveMessages()`, or a system prompt. Recording feedback during a turn does not change that turn's remaining requests.
Nothing. The slash input, the dialog, `feedback/record`, and the acknowledgement are absent from model requests. The feedback event and registry lifecycle records are log-only and carry no `surfaceOp`, so they never reach the ordered surface, `deriveMessages()`, or a system prompt. Recording feedback during a turn does not change that turn's remaining requests.
#### Token effect
@@ -112,13 +133,14 @@ Independent of the model request path. Recording appends to the session log only
<a id="known-limitations-and-deferred-work"></a>
These limits define where `/feedback` is a poor fit or behaves differently than a user might expect. They are current package constraints, not a task backlog.
These limits define where session feedback is a poor fit or behaves differently than a user might expect. They are current package constraints, not a task backlog.
- **No feedback retrieval or management surface** — there is no retrieval, aggregation, categorization, or model-facing tool for `feedback/record`.
- **No structured fields** — an entry is one free-text string with no category, severity, or referenced-event link, so feedback cannot be filtered by subject without re-reading its text.
- **No feedback retrieval or management surface** — there is no retrieval, aggregation, or model-facing tool for `feedback/record`.
- **Category and text only** — an entry carries at most one category and one free-text string, with no severity or referenced-event link.
- **Live Sessions only through the Remote** — `sessionFeedback.record` answers `session-not-found` for a Session no live owner carries; the Web dialog reports that failure when its Session retires while it is open.
- **No amend or withdraw** — the session log is append-only and this package adds no tombstone, so a mistaken entry stays recorded and can only be superseded by a later one.
- **No explicit durability barrier** — the acknowledgement follows the append, not a flush, so an entry recorded immediately before a crash can be lost with any other unflushed tail. A consumer that needs a barrier awaits `ctx.sessions.flush(session)`.
- **No visible acknowledgement on a fresh session** — the web transcript renders command rows only once a session is active, so `/feedback` on a still-blank session records the event but shows no acknowledgement row. Recording feedback after the first message renders normally.
- **No visible acknowledgement on a fresh session** — the web transcript renders command rows only once a session is active, so a typed `/feedback <text>` on a still-blank session records the event but shows no acknowledgement row; the dialog's toast does not depend on the transcript.
- **Web only among the shipped entry points** — headless mode, ACP automation, and JSON-RPC provide no command adapter, so `/feedback` is unavailable there.
<a id="dev-note"></a>
@@ -129,7 +151,7 @@ These limits define where `/feedback` is a poor fit or behaves differently than
This Dev Note is working context for maintainers; it is explicitly non-authoritative. Shipped behavior, limits, and rationale live in the sections above and the package code.
- The acknowledgement sentences are pinned by [`tests/command-feedback.spec.ts`](tests/command-feedback.spec.ts); changing them changes user-visible copy.
- Structured fields and a retrieval surface remain the open direction behind the first two limitations; nothing in the current contract reserves a format for them.
- The acknowledgement sentences and the category order are pinned by [`tests/command-feedback.spec.ts`](tests/command-feedback.spec.ts); changing them changes user-visible copy.
- A retrieval surface remains the open direction behind the first limitation; nothing in the current contract reserves a format for it.
</details>
+35 -13
View File
@@ -1,5 +1,5 @@
---
description: "通过 `/feedback` 命令记录自由文本会话反馈,供用户与维护者选择、组合或排查反馈采集。"
description: "会话反馈:`/feedback` 命令、Web 反馈弹窗背后的 `sessionFeedback` Host Remote,以及固定的分类表;供用户与维护者选择、组合或排查反馈采集。"
kind: "package-reference"
---
@@ -9,7 +9,7 @@ kind: "package-reference"
## 概述
`dsh-command-feedback` 让用户告诉 harness 他们对会话的看法:输入 `/feedback` 加一条评价,评价即被记录并得到确认。记录是即时的,绝不会启动模型工作,因此在对话的任何时刻都是安全的——模型既看不到这条评价,也不会被打断。确认文本会点名会话与匿名用户。命令随 Web 客户端交付,无需任何配置;无头模式、ACP(Agent Client Protocol)与 JSON-RPC 入口不提供斜杠命令,因此无法运行它。
`dsh-command-feedback` 让用户告诉 harness 他们对会话的看法。输入 `/feedback` 加一条评价,评价即被记录,并以会话 id 与匿名用户 id 确认;Web 反馈弹窗通过 `sessionFeedback` Host Remote 记录分类与可选描述。记录是即时的,绝不会启动模型工作:模型既看不到这条评价,也不会被打断。本包同时拥有所有反馈界面共用的固定分类表。它随标准 `dsh` 基础组合交付,无需任何配置;无头模式、ACP(Agent Client Protocol)与 JSON-RPC 入口不提供斜杠命令。
## 目录
@@ -38,11 +38,30 @@ kind: "package-reference"
前后空白会被去除,但除此之外,评价会按输入原样保留:不进行截断、大小写折叠或命令解析——`/feedback /plan felt slow` 记录的就是这段字面文本。每次执行命令都会记录自己的条目;不会发生合并或替换。
<a id="the-web-feedback-dialog"></a>
### Web 反馈弹窗
在 Web 客户端中,不带文本的 `/feedback`(从输入框菜单选中,或直接输入后发送)会打开反馈弹窗,而不是返回用法错误。弹窗提供下表的七个分类和一个自由文本框;每一项都可不填,空提交也会被接受,对话日志和其他反馈事件一样随记录的事件一起投递。弹窗通过 `sessionFeedback.record` 记录,追加的是同一个 `feedback/record` 事件,但没有命令簿记,也没有确认行;弹窗改用 toast 提示。
| 分类 id | 含义 |
|---|---|
| `task-result` | 任务结果 |
| `instruction-following` | 指令理解与遵循 |
| `product-interaction` | 产品功能与交互 |
| `service-stability` | 服务稳定性 |
| `resource-cost` | 资源使用与费用 |
| `security-privacy-permission` | 安全隐私与权限 |
| `other` | 其他 |
这些 id 是日志中的持久词汇,与逐消息反馈共用;各界面自行拥有本地化标签。
### 从自己的 UI 记录反馈
反馈不一定来自斜杠命令:任何 UI、钩子或 host 集成都可以直接记录评价,享有同样的保证且无需模型轮次。想要斜杠命令的自定义应用,把命令注册表与本插件组合在一起即可:
反馈不一定来自斜杠命令或弹窗:任何 UI、钩子或 host 集成都可以通过 `recordFeedback` 或 `sessionFeedback` Remote 直接记录评价,享有同样的保证且无需模型轮次。想要斜杠命令的自定义应用,把 Session 存储、命令注册表与本插件组合在一起即可;`sessionFeedback` Remote 从 Session 存储中解析 live Session:
```yaml
- id: session
name: '@deepseek-ai/dsh-session'
- id: commands
name: '@deepseek-ai/dsh-commands'
- id: command-feedback
@@ -61,17 +80,18 @@ Web 客户端随附该命令。无头模式、ACP 自动化和 JSON-RPC 不提
### 设计理念
评价是会话日志中一个仅追加的事实,由事件而非产生它的命令拥有:反馈可能来自任何触发方式,因此事实绝不能依赖斜杠命令。命令自身的簿记不携带载荷,所以评价文本在日志中只存在于一个地方,且该事件绝不会浮出到模型。
评价是会话日志中一个仅追加的事实,由事件而非产生它的触发方式拥有:反馈可能来自命令、弹窗或任何集成,因此事实绝不能依赖斜杠命令。命令自身的簿记不携带载荷,所以评价文本在日志中只存在于一个地方,且该事件绝不会浮出到模型。
### 评价如何被记录
生产方去除文本空白、拒绝空输入,并向会话日志写入一个事件;`/feedback` 处理器是该生产方的薄包装,不启动任何模型工作。写入是即时但未 flush 的:确认文本表示条目已到达日志,而不是已落盘。某个 harness home 首次接受的评价还会铸造确认文本所报告的匿名用户 id。精确的生产方约定与事件载荷见 [`src/index.ts`](src/index.ts)。
生产方去除文本空白,把空白文本记为缺省,并向会话日志写入一个事件,即使条目既无文本也无分类;`/feedback` 处理器自行拒绝空输入,其余部分是该生产方的薄包装,`sessionFeedback.record` Remote 则按 id 找到 live Session 后同样调用它,没有 live 持有者时回答 `session-not-found`。两条路径都不启动模型工作。写入是即时但未 flush 的:确认文本表示条目已到达日志,而不是已落盘。某个 harness home 首次接受的命令评价还会铸造确认文本所报告的匿名用户 id。精确的生产方约定见 [`src/index.ts`](src/index.ts);事件载荷、分类表与 Remote 词汇见 [`src/types.ts`](src/types.ts)。
### 源码地图
| 文件 | 职责 |
|---|---|
| [`src/index.ts`](src/index.ts) | 插件入口:`feedback/record` 事件声明、`recordFeedback` 生产方、`/feedback` 命令注册 |
| [`src/index.ts`](src/index.ts) | 插件入口:`recordFeedback` 生产方、`sessionFeedback` Remote 服务、`/feedback` 命令注册 |
| [`src/types.ts`](src/types.ts) | `feedback/record` 事件声明、分类表,以及 Remote 请求与结果类型 |
| — | 不发布运行时不变式伴生入口;每个事件都是独立的仅追加事实。 |
</details>
@@ -86,6 +106,7 @@ Web 客户端随附该命令。无头模式、ACP 自动化和 JSON-RPC 不提
- [dsh-commands](../../interaction/commands/README.zh.md)——发现全局命令并定义 `recordInput` 语义的注册表。
- [会话持久化子系统](../../../docs/subsystems/persistence.zh.md)——追加事件如何持久化、flush 屏障的含义。
- [匿名用户身份](../../identity/anonymous-user-id/README.zh.md)——确认文本报告的 id。
- [ui-message-feedback](../../client/ui-message-feedback/README.zh.md)——通过 `sessionFeedback` Remote 记录的 Web 反馈弹窗。
- [反馈包映射](../README.zh.md)——仅写入日志的采集与逐消息反馈并存的组。
-----
@@ -97,7 +118,7 @@ Web 客户端随附该命令。无头模式、ACP 自动化和 JSON-RPC 不提
#### 模型看到什么
无。斜杠输入、`feedback/record` 以及确认文本都不出现在模型请求中。反馈事件和注册表生命周期记录仅写入日志且不携带 `surfaceOp`,因此它们绝不会进入有序 surface、`deriveMessages()` 或系统提示词。在某个轮次中记录反馈不会改变该轮次剩余的请求。
无。斜杠输入、弹窗、`feedback/record` 以及确认文本都不出现在模型请求中。反馈事件和注册表生命周期记录仅写入日志且不携带 `surfaceOp`,因此它们绝不会进入有序 surface、`deriveMessages()` 或系统提示词。在某个轮次中记录反馈不会改变该轮次剩余的请求。
#### Token 影响
@@ -112,13 +133,14 @@ Web 客户端随附该命令。无头模式、ACP 自动化和 JSON-RPC 不提
<a id="known-limitations-and-deferred-work"></a>
这些限制说明 `/feedback` 何时不合适,或何时行为与用户预期不同。它们是当前包约束,不是任务积压。
这些限制说明会话反馈何时不合适,或何时行为与用户预期不同。它们是当前包约束,不是任务积压。
- **没有反馈检索或管理 surface**——本包不为 `feedback/record` 提供检索、聚合、分类或面向模型的工具。
- **没有结构化字段**——一条条目就是一个自由文本字符串,没有类别、严重程度或关联事件链接,因此无法在不重读文本的情况下按主题过滤反馈。
- **没有反馈检索或管理 surface**——本包不为 `feedback/record` 提供检索、聚合或面向模型的工具。
- **只有分类与文本**——一条条目至多携带一个分类和一个自由文本字符串,没有严重程度或关联事件链接。
- **Remote 只服务 live Session**——没有 live 持有者的 Session,`sessionFeedback.record` 回答 `session-not-found`;弹窗打开期间 Session 退役时,Web 弹窗会报告该失败。
- **不支持修改或撤回**——会话日志是仅追加的,本包也不新增 tombstone,因此错误的条目会一直保留在记录中,只能由后续条目取代。
- **没有显式持久化屏障**——确认文本紧随追加而非 flush,因此紧临崩溃前记录的条目可能与其他未 flush 的尾部一同丢失。需要该保证的消费方可自行等待 `ctx.sessions.flush(session)`。
- **新会话上没有可见的确认**——Web 转录只在会话激活后渲染命令行,因此在仍为空白的新会话上执行 `/feedback` 会记录事件但不会显示确认行。发送首条消息后再记录反馈即可正常渲染。
- **新会话上没有可见的确认**——Web 转录只在会话激活后渲染命令行,因此在仍为空白的新会话上输入 `/feedback <text>` 会记录事件但不会显示确认行;弹窗的 toast 不依赖转录。
- **随附的产品入口中只有 Web 使用此命令**——无头模式、ACP 自动化和 JSON-RPC 不提供命令适配器,因此 `/feedback` 在那里不可用。
<a id="dev-note"></a>
@@ -129,7 +151,7 @@ Web 客户端随附该命令。无头模式、ACP 自动化和 JSON-RPC 不提
本开发备注是维护者的工作上下文,明确不具权威性。已交付的行为、限制与理由以上文与包代码为准。
- 确认文本句子由 [`tests/command-feedback.spec.ts`](tests/command-feedback.spec.ts) 固定;修改它们会改变用户可见文案。
- 结构化字段与检索 surface 仍是前两条限制背后的开放方向;当前约定没有为它们预留任何格式。
- 确认文本句子与分类顺序由 [`tests/command-feedback.spec.ts`](tests/command-feedback.spec.ts) 固定;修改它们会改变用户可见文案。
- 检索 surface 仍是第一条限制背后的开放方向;当前约定没有为它预留任何格式。
</details>
@@ -1,6 +1,6 @@
{
"name": "@deepseek-ai/dsh-command-feedback",
"description": "Log-only session feedback producer and human-facing slash command",
"description": "Log-only session feedback: the record event, the sessionFeedback Host Remote, and the human-facing slash command",
"version": "0.1.5-alpha.1",
"publishConfig": {
"access": "public"
@@ -18,19 +18,40 @@
"types": "./lib/types/index.d.ts",
"default": "./lib/index.js"
},
"./types": {
"types": "./lib/types/types.d.ts",
"default": "./lib/types/types.js"
},
"./typert": {
"types": "./lib/typert.host.d.ts",
"default": "./lib/typert.host.js"
},
"./remote": {
"types": "./lib/typert.remote-client.d.ts",
"default": "./lib/typert.remote-client.js"
},
"./src/*": "./src/*",
"./package.json": "./package.json"
},
"files": [
"lib/index.js",
"lib/types/**/*.d.ts"
"lib/types/**/*.js",
"lib/types/**/*.d.ts",
"lib/typert.host.js",
"lib/typert.host.d.ts",
"lib/typert.remote-client.js",
"lib/typert.remote-client.d.ts"
],
"license": "MIT",
"peerDependencies": {
"@deepseek-ai/dsh-commands": "workspace:^",
"@deepseek-ai/dsh-session": "workspace:^",
"@deepseek-ai/dsh-anonymous-user-id": "workspace:^",
"@deepseek-ai/cordis": "workspace:^"
"@deepseek-ai/cordis": "workspace:^",
"@deepseek-ai/dsh-typert-protocol": "workspace:^"
},
"dependencies": {
"zod": "^4.4.3"
},
"devDependencies": {
"@deepseek-ai/cordis-plugin-include": "workspace:^",
@@ -41,6 +62,7 @@
"@deepseek-ai/dsh-llm": "workspace:^",
"@deepseek-ai/dsh-session": "workspace:^",
"@deepseek-ai/dsh-anonymous-user-id": "workspace:^",
"@deepseek-ai/cordis": "workspace:^"
"@deepseek-ai/cordis": "workspace:^",
"@deepseek-ai/dsh-typert-protocol": "workspace:^"
}
}
+77 -20
View File
@@ -1,8 +1,10 @@
/**
* Session feedback event plus the human-facing `/feedback` producer. Recording
* appends one authoritative log-only event and does not start model work. The
* append is eager but unflushed, so acknowledgement reports that the entry is
* logged, not that it reached disk.
* Session feedback: the `feedback/record` event, its command-independent
* producer, the `sessionFeedback` Host Remote a product surface records
* through, and the human-facing `/feedback` command. Recording appends one
* authoritative log-only event and does not start model work. The append is
* eager but unflushed, so acknowledgement reports that the entry is logged,
* not that it reached disk.
* @module @deepseek-ai/dsh-command-feedback
*/
@@ -10,32 +12,54 @@ import type { Context } from '@deepseek-ai/cordis'
import type { CommandInvocation, CommandResult } from '@deepseek-ai/dsh-commands'
import type { Session } from '@deepseek-ai/dsh-session'
import { getOrCreateAnonymousUserId } from '@deepseek-ai/dsh-anonymous-user-id'
import { TypertRemoteService, Remote } from '@deepseek-ai/dsh-typert-protocol'
import type {
FeedbackCategory,
FeedbackRecord,
SessionFeedbackRecordRequest,
SessionFeedbackRecordResult,
} from './types.ts'
export type * from './types.ts'
/**
* Every feedback category in the order product surfaces present them; each
* surface owns its localized labels.
*/
export const FEEDBACK_CATEGORIES = [
'task-result',
'instruction-following',
'product-interaction',
'service-stability',
'resource-cost',
'security-privacy-permission',
'other',
] as const satisfies readonly FeedbackCategory[]
export const name = 'command-feedback'
export const inject = ['commands']
const USAGE = 'Usage: /feedback <text>'
declare module '@deepseek-ai/dsh-session/types' {
interface SessionEventMap {
/**
* One recorded human remark about this session. Log-only and independent
* of its trigger; it never enters model context or derived history.
*/
'feedback/record': { text: string }
declare module '@deepseek-ai/cordis' {
interface Context {
sessionFeedback: SessionFeedbackService
}
}
/**
* Record feedback independently of any UI trigger.
* Record feedback independently of any UI trigger. Surrounding whitespace is
* discarded and a blank text is recorded as absent; an entry with neither
* text nor category is still recorded.
* @param session - session the feedback describes.
* @param text - human-authored feedback; surrounding whitespace is discarded.
* @throws {TypeError} when the normalized text is empty.
* @param entry - human-authored remark and its category.
*/
export function recordFeedback(session: Session, text: string): void {
const normalized = text.trim()
if (normalized.length === 0) throw new TypeError('feedback text must not be empty')
session.append('feedback/record', { text: normalized })
export function recordFeedback(session: Session, entry: FeedbackRecord): void {
const text = entry.text?.trim() ?? ''
session.append('feedback/record', {
...(text.length === 0 ? {} : { text }),
...(entry.category === undefined ? {} : { category: entry.category }),
})
}
/**
@@ -49,15 +73,48 @@ function executeFeedbackCommand(invocation: CommandInvocation): CommandResult {
if (invocation.rawInput.trim().length === 0) {
return { kind: 'error', text: `Feedback text is required. ${USAGE}` }
}
recordFeedback(invocation.agent.session, invocation.rawInput)
recordFeedback(invocation.agent.session, { text: invocation.rawInput })
return {
kind: 'success',
text: `Feedback recorded for session ${invocation.agent.session.id}\nAnonymous user: ${getOrCreateAnonymousUserId()}.`,
}
}
/** Register the global `/feedback` command for every composed command adapter. */
/** Host Remote through which a product surface records a Session-level remark. */
export class SessionFeedbackService extends TypertRemoteService {
static inject = ['sessions']
/**
* @param ctx - Host context carrying the live Session store.
*/
constructor(ctx: Context) {
super(ctx, 'sessionFeedback')
}
/**
* Record one remark on a live Session.
* @param request - target Session plus the optional text and category.
* @returns the recorded postcondition, or `session-not-found` when no live
* Session carries the id.
*/
@Remote('record')
record(request: SessionFeedbackRecordRequest): Promise<SessionFeedbackRecordResult> {
const session = this.ctx.sessions.get(request.sessionId)
if (session === undefined) {
return Promise.resolve({ ok: false, error: { code: 'session-not-found', sessionId: request.sessionId } })
}
recordFeedback(session, request)
return Promise.resolve({ ok: true, value: { recorded: true } })
}
}
/**
* Register the global `/feedback` command for every composed command adapter
* and mount the `sessionFeedback` Remote.
* @param ctx - Host context.
*/
export function apply(ctx: Context): void {
ctx.plugin(SessionFeedbackService)
ctx.commands.register({
name: 'feedback',
description: 'record feedback about this session',
@@ -0,0 +1,69 @@
/**
* Public vocabulary of Session-level feedback: the fixed category taxonomy,
* the `feedback/record` event payload, and the `sessionFeedback.record`
* Remote request and result types. Types only; the runtime category tuple is
* exported by the package entry, and a browser plugin imports types alone
* because its bundle may not carry Host values.
* @module @deepseek-ai/dsh-command-feedback/types
*/
import type { SessionId } from '@deepseek-ai/dsh-session/types'
/** One of the fixed feedback categories; the ids are durable log vocabulary. */
export type FeedbackCategory =
| 'task-result'
| 'instruction-following'
| 'product-interaction'
| 'service-stability'
| 'resource-cost'
| 'security-privacy-permission'
| 'other'
/**
* One recorded human remark about a Session. Both members are optional: a
* submission with neither still records that the human asked for the
* Session to be reviewed, which is what authorizes log delivery.
*/
export interface FeedbackRecord {
/** Free-text remark with surrounding whitespace removed; never empty when present. */
readonly text?: string
/** Category the human filed the remark under. */
readonly category?: FeedbackCategory
}
declare module '@deepseek-ai/dsh-session/types' {
interface SessionEventMap {
/**
* One recorded human remark about this session. Log-only and independent
* of its trigger; it never enters model context or derived history.
*/
'feedback/record': FeedbackRecord
}
}
/** Record one Session-level remark through the Host Remote. */
export interface SessionFeedbackRecordRequest {
/** Live Session the remark describes. */
readonly sessionId: SessionId
/** Free-text remark; blank text is recorded as absent. */
readonly text?: string
/** Category the human filed the remark under. */
readonly category?: FeedbackCategory
}
/** Stable postcondition of a recorded remark. */
export interface SessionFeedbackRecordValue {
/** The remark is appended to the Session log; flushing follows the Session's own schedule. */
readonly recorded: true
}
/** No live Session carries the requested id. */
export interface SessionFeedbackSessionNotFound {
readonly code: 'session-not-found'
readonly sessionId: SessionId
}
/** Result returned by the `sessionFeedback.record` operation. */
export type SessionFeedbackRecordResult =
| { readonly ok: true; readonly value: SessionFeedbackRecordValue }
| { readonly ok: false; readonly error: SessionFeedbackSessionNotFound }
@@ -6,6 +6,8 @@ import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent'
import CommandRuntime from '@deepseek-ai/dsh-commands'
import SessionStore, { foldSurface, Session, SessionId } from '@deepseek-ai/dsh-session'
import * as commandFeedback from '@deepseek-ai/dsh-command-feedback'
import type { FeedbackRecord } from '@deepseek-ai/dsh-command-feedback/types'
import { remoteMethods } from '@deepseek-ai/dsh-typert-protocol'
import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit'
const { USER_ID, getOrCreateAnonymousUserId } = vi.hoisted(() => {
@@ -72,10 +74,15 @@ async function run(test: Harness, suffix = ''): Promise<{ kind: string; text?: s
}
/** Authoritative feedback payloads in log order. */
function feedbackTexts(session: Session): string[] {
function feedbackRecords(session: Session): FeedbackRecord[] {
return session.snapshotEvents()
.filter(event => event.type === 'feedback/record')
.map(event => event.data.text)
.map(event => event.data)
}
/** The text of each authoritative feedback payload in log order. */
function feedbackTexts(session: Session): (string | undefined)[] {
return feedbackRecords(session).map(record => record.text)
}
describe('@deepseek-ai/dsh-command-feedback registration', () => {
@@ -99,6 +106,48 @@ describe('@deepseek-ai/dsh-command-feedback registration', () => {
})
})
describe('sessionFeedback Host Remote', () => {
it('publishes the exact Gateway namespace and Remote method name', async () => {
const test = await harness()
const binding = test.ctx.sessionFeedback.typertRemote
expect(binding.serviceKey).toBe('sessionFeedback')
expect(binding.namespace).toBe('sessionFeedback')
expect(remoteMethods(test.ctx.sessionFeedback)).toEqual([
{ method: 'record', invocation: { kind: 'direct' } },
])
})
it('records a remark on the live Session without command bookkeeping', async () => {
const test = await harness()
await expect(test.ctx.sessionFeedback.record({
sessionId: test.session.id, text: ' the diff view is unreadable ', category: 'product-interaction',
})).resolves.toEqual({ ok: true, value: { recorded: true } })
await expect(test.ctx.sessionFeedback.record({ sessionId: test.session.id }))
.resolves.toEqual({ ok: true, value: { recorded: true } })
expect(test.session.snapshotEvents().map(event => event.type)).toEqual(['feedback/record', 'feedback/record'])
expect(feedbackRecords(test.session)).toEqual([
{ text: 'the diff view is unreadable', category: 'product-interaction' },
{},
])
expect(getOrCreateAnonymousUserId).not.toHaveBeenCalled()
})
it('reports session-not-found for a Session no live owner carries', async () => {
const test = await harness()
const missing = SessionId('no-such-session')
await expect(test.ctx.sessionFeedback.record({ sessionId: missing, text: 'lost' }))
.resolves.toEqual({ ok: false, error: { code: 'session-not-found', sessionId: missing } })
expect(test.session.snapshotEvents()).toEqual([])
})
it('is mounted and unmounted with the plugin', async () => {
const test = await harness()
expect(test.ctx.get('sessionFeedback')).toBeDefined()
await test.plugin.dispose()
expect(test.ctx.get('sessionFeedback')).toBeUndefined()
})
})
describe('/feedback human command', () => {
it('acknowledges feedback and records its payload exactly once in the domain event', async () => {
const test = await harness()
@@ -114,12 +163,24 @@ describe('/feedback human command', () => {
it('exports a command-independent feedback producer', async () => {
const test = await harness()
commandFeedback.recordFeedback(test.session, ' recorded outside a command ')
expect(test.session.snapshotEvents().map(event => event.type)).toEqual(['feedback/record'])
expect(feedbackTexts(test.session)).toEqual(['recorded outside a command'])
expect(() => { commandFeedback.recordFeedback(test.session, ' \n\t ') })
.toThrow('feedback text must not be empty')
expect(feedbackTexts(test.session)).toEqual(['recorded outside a command'])
commandFeedback.recordFeedback(test.session, { text: ' recorded outside a command ' })
commandFeedback.recordFeedback(test.session, { text: ' \n\t ', category: 'service-stability' })
commandFeedback.recordFeedback(test.session, {})
expect(test.session.snapshotEvents().map(event => event.type))
.toEqual(['feedback/record', 'feedback/record', 'feedback/record'])
// Blank text is recorded as absent; an entry with neither member still records.
expect(feedbackRecords(test.session)).toEqual([
{ text: 'recorded outside a command' },
{ category: 'service-stability' },
{},
])
})
it('publishes the fixed category taxonomy in presentation order', () => {
expect(commandFeedback.FEEDBACK_CATEGORIES).toEqual([
'task-result', 'instruction-following', 'product-interaction', 'service-stability',
'resource-cost', 'security-privacy-permission', 'other',
])
})
it('keeps command bookkeeping around the authoritative feedback event', async () => {
@@ -22,6 +22,9 @@
},
{
"path": "../../identity/anonymous-user-id"
},
{
"path": "../../typert/protocol"
}
]
}
@@ -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/feedback/message-feedback/README.md
README.md: e1defa8d8fd6149f124267ffa0c382f4a82cf2ab
README.zh.md: d16f8f4416288e5373e3221e8f43a8b2d84e5f80
README.md: 4e75d167fe39c96002b32def24f447efdbc2be70
README.zh.md: 0c21e26f9a4ffa40ce29412c652029d3af4e9fe0
+5 -5
View File
@@ -1,5 +1,5 @@
---
description: "Canonical Session-log ratings and notes for finalized assistant messages."
description: "Canonical Session-log ratings, categories, and notes for finalized assistant messages."
kind: "package-reference"
---
@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
## Summary
This service records positive or negative ratings and optional verbatim notes for finalized assistant messages. The canonical Session log owns every creation, edit, and deletion; `list`, `put`, and `delete` expose current feedback without constructing or waking an Agent. Feedback is log-only and does not enter model history.
This service records positive or negative ratings, an optional category from the fixed feedback taxonomy, and optional verbatim notes for finalized assistant messages. The canonical Session log owns every creation, edit, and deletion; `list`, `put`, and `delete` expose current feedback without constructing or waking an Agent. Feedback is log-only and does not enter model history.
## Table of Contents
@@ -30,17 +30,17 @@ Mount `dsh-message-feedback` alongside `sessions` and `sessionPersistence`. It n
|---|---|---|
| `maxNoteBytes` | required | Positive safe-integer maximum UTF-8 bytes in one optional note. |
A supplied note must contain a non-whitespace character and fit the configured byte limit. Blank notes return `note-blank`; oversized notes return `note-too-large`. Accepted text is preserved exactly, including surrounding whitespace. Omitting a note clears it. Note validation precedes Session lookup.
A supplied note must contain a non-whitespace character and fit the configured byte limit. Blank notes return `note-blank`; oversized notes return `note-too-large`. Accepted text is preserved exactly, including surrounding whitespace. Omitting a note clears it. Note validation precedes Session lookup. A supplied category must be one of the [fixed feedback categories](../command-feedback/README.md#the-web-feedback-dialog); the Remote schema rejects any other value, and omitting the category clears it.
### Reading and changing feedback
| Operation | Request | Success | Business failures |
|---|---|---|---|
| `list` | Session id | Current items in creation order | Session not found |
| `put` | Session, message, rating, optional note, expected version | Current item | Session or target not found, version conflict, invalid note |
| `put` | Session, message, rating, optional note, optional category, expected version | Current item | Session or target not found, version conflict, invalid note |
| `delete` | Session, message, expected version | Item absent | Session not found, version conflict |
Create with `ifVersion: null`; edit or delete with the returned version. Stale mutations return `version-conflict` and the current item. Each material put mints a fresh token and preserves the original creation time. A matching no-op put returns the same item without appending an event. Deleting an absent item succeeds regardless of the supplied version, without appending an event. Recreating a deleted item starts a new creation time and ordering position.
Create with `ifVersion: null`; edit or delete with the returned version. Stale mutations return `version-conflict` and the current item. Each material put mints a fresh token and preserves the original creation time. A put that repeats the stored rating, note, and category is a no-op: it returns the same item without appending an event. Deleting an absent item succeeds regardless of the supplied version, without appending an event. Recreating a deleted item starts a new creation time and ordering position.
Targets must be non-empty assistant messages produced by append-origin events. User messages, empty assistant placeholders, and replacement-origin messages return `target-not-found`. Feedback survives restart; a fork starts without owned feedback even when its inherited prefix contains parent feedback.
@@ -1,5 +1,5 @@
---
description: "在权威 Session 日志中保存已完成 assistant 消息的评分与备注。"
description: "在权威 Session 日志中保存已完成 assistant 消息的评分、分类与备注。"
kind: "package-reference"
---
@@ -9,7 +9,7 @@ kind: "package-reference"
## 概述
本服务为已完成的 assistant 消息记录好评、差评及可选的原样备注。每次创建、编辑和删除都由权威 Session 日志保存;`list`、`put` 和 `delete` 提供当前反馈,不会构造或唤醒 Agent。反馈仅写入日志,不进入模型历史。
本服务为已完成的 assistant 消息记录好评、差评、固定反馈分类表中的可选分类,以及可选的原样备注。每次创建、编辑和删除都由权威 Session 日志保存;`list`、`put` 和 `delete` 提供当前反馈,不会构造或唤醒 Agent。反馈仅写入日志,不进入模型历史。
## 目录
@@ -30,17 +30,17 @@ kind: "package-reference"
|---|---|---|
| `maxNoteBytes` | 必填 | 单条可选备注的 UTF-8 字节上限,必须为正安全整数。 |
提交的备注必须包含非空白字符,且不超过配置的字节上限。空白备注返回 `note-blank`;过长备注返回 `note-too-large`。通过校验的文本会完整保留,包括首尾空白。省略备注会清除它。备注校验先于 Session 查找。
提交的备注必须包含非空白字符,且不超过配置的字节上限。空白备注返回 `note-blank`;过长备注返回 `note-too-large`。通过校验的文本会完整保留,包括首尾空白。省略备注会清除它。备注校验先于 Session 查找。提交的分类必须是[固定反馈分类](../command-feedback/README.zh.md#the-web-feedback-dialog)之一;Remote schema 拒绝其他值,省略分类会清除它。
### 读取与修改反馈
| 操作 | 请求 | 成功 | 业务失败 |
|---|---|---|---|
| `list` | Session id | 按创建顺序返回当前条目 | Session 不存在 |
| `put` | Session、消息、评分、可选备注、预期版本 | 当前条目 | Session 或目标不存在、版本冲突、备注无效 |
| `put` | Session、消息、评分、可选备注、可选分类、预期版本 | 当前条目 | Session 或目标不存在、版本冲突、备注无效 |
| `delete` | Session、消息、预期版本 | 条目不存在 | Session 不存在、版本冲突 |
创建时传入 `ifVersion: null`;编辑或删除时使用返回的版本。陈旧修改返回 `version-conflict` 及当前条目。每次实质 put 都生成新 token,并保留原始创建时间。匹配的无变化 put 返回相同条目,不追加事件。删除不存在的条目始终成功,不受所传版本影响,也不追加事件。重新创建已删除条目会产生新的创建时间和排序位置。
创建时传入 `ifVersion: null`;编辑或删除时使用返回的版本。陈旧修改返回 `version-conflict` 及当前条目。每次实质 put 都生成新 token,并保留原始创建时间。重复已存评分、备注与分类的 put 是无变化操作:返回相同条目,不追加事件。删除不存在的条目始终成功,不受所传版本影响,也不追加事件。重新创建已删除条目会产生新的创建时间和排序位置。
目标必须是由 append 来源事件产生的非空 assistant 消息。用户消息、空 assistant 占位及 replacement 来源消息返回 `target-not-found`。反馈跨重启保留;fork 即使继承了包含父会话反馈的前缀,也从没有自有反馈开始。
@@ -49,7 +49,8 @@
"@deepseek-ai/dsh-session": "workspace:^",
"@deepseek-ai/dsh-session-persistence": "workspace:^",
"@deepseek-ai/dsh-typert-protocol": "workspace:^",
"@deepseek-ai/cordis": "workspace:^"
"@deepseek-ai/cordis": "workspace:^",
"@deepseek-ai/dsh-command-feedback": "workspace:^"
},
"dependencies": {
"@deepseek-ai/schemastery": "workspace:^",
@@ -64,6 +65,7 @@
"@deepseek-ai/dsh-session-persistence": "workspace:^",
"@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^",
"@deepseek-ai/dsh-typert-protocol": "workspace:^",
"@deepseek-ai/cordis": "workspace:^"
"@deepseek-ai/cordis": "workspace:^",
"@deepseek-ai/dsh-command-feedback": "workspace:^"
}
}
@@ -9,6 +9,7 @@ import { isDeepStrictEqual } from 'node:util'
import { Context, Service } from '@deepseek-ai/cordis'
import s from '@deepseek-ai/schemastery'
import { z } from 'zod'
import { FEEDBACK_CATEGORIES } from '@deepseek-ai/dsh-command-feedback'
import { SessionSeq } from '@deepseek-ai/dsh-session/types'
import { deriveEventMessage, isAppendSurfaceEvent } from '@deepseek-ai/dsh-session/surface'
import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session/types'
@@ -63,6 +64,7 @@ const itemSchema = z.object({
messageId: z.string().min(1),
rating: z.enum(['positive', 'negative']),
note: z.string().refine(note => note.trim().length > 0).optional(),
category: z.enum(FEEDBACK_CATEGORIES).optional(),
version: z.uuid(),
createdAt: timestamp,
updatedAt: timestamp,
@@ -176,7 +178,8 @@ export class MessageFeedbackService extends TypertRemoteService {
if (request.ifVersion !== (existing?.version ?? null)) {
return rejected(this.versionConflict(existing ?? null))
}
if (existing !== undefined && existing.rating === request.rating && existing.note === note.value) {
if (existing !== undefined && existing.rating === request.rating && existing.note === note.value
&& existing.category === request.category) {
await append()
return success(snapshotItem(existing))
}
@@ -185,6 +188,7 @@ export class MessageFeedbackService extends TypertRemoteService {
messageId: request.messageId,
rating: request.rating,
...(note.value === undefined ? {} : { note: note.value }),
...(request.category === undefined ? {} : { category: request.category }),
version: randomUUID() as MessageFeedbackVersion,
createdAt: existing?.createdAt ?? now,
updatedAt: existing === undefined ? now : Math.max(now, existing.updatedAt),
@@ -8,6 +8,7 @@
import type { Branded } from '@deepseek-ai/dsh-brand'
import type { MessageId } from '@deepseek-ai/dsh-llm/brand'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import type { FeedbackCategory } from '@deepseek-ai/dsh-command-feedback/types'
/** Opaque compare-and-set token for one exact feedback item revision. */
export type MessageFeedbackVersion = Branded<'MessageFeedbackVersion'>
@@ -23,6 +24,8 @@ export interface MessageFeedbackItem {
readonly rating: MessageFeedbackRating
/** Optional explanation, preserved verbatim after validation. */
readonly note?: string
/** Category the human filed a negative judgment under. */
readonly category?: FeedbackCategory
/** Equality-only token replaced by every material create or update. */
readonly version: MessageFeedbackVersion
/** Host-assigned creation time in Unix epoch milliseconds. */
@@ -78,6 +81,8 @@ export interface MessageFeedbackPutRequest {
readonly rating: MessageFeedbackRating
/** Optional non-blank explanation. */
readonly note?: string
/** Optional category; absent keeps the item uncategorized. */
readonly category?: FeedbackCategory
/** Observed item version, or `null` to require that no item exists. */
readonly ifVersion: MessageFeedbackVersion | null
}
@@ -181,6 +181,62 @@ describe('MessageFeedbackService public contract', () => {
expect(Object.isFrozen(listed.value.items[0])).toBe(true)
})
it('stores a category with the judgment, treats a category change as material, and validates stored categories', async () => {
const { ctx, persistence } = await harness()
const fixture = messageFixture('categories')
persistence.persist(fixture.session)
const messageId = fixture.assistantMessageIds[0]
const created = expectItem(await ctx.messageFeedback.put({
sessionId: fixture.session.id,
messageId,
rating: 'negative',
note: 'wrong file',
category: 'task-result',
ifVersion: null,
}))
expect(created).toMatchObject({ rating: 'negative', note: 'wrong file', category: 'task-result' })
// The same value is a no-op; a different category is a material edit;
// omitting the category drops it.
const same = expectItem(await ctx.messageFeedback.put({
sessionId: fixture.session.id, messageId, rating: 'negative', note: 'wrong file', category: 'task-result',
ifVersion: created.version,
}))
expect(same).toEqual(created)
const recategorized = expectItem(await ctx.messageFeedback.put({
sessionId: fixture.session.id, messageId, rating: 'negative', note: 'wrong file', category: 'other',
ifVersion: created.version,
}))
expect(recategorized.version).not.toBe(created.version)
expect(recategorized.category).toBe('other')
const dropped = expectItem(await ctx.messageFeedback.put({
sessionId: fixture.session.id, messageId, rating: 'negative', ifVersion: recategorized.version,
}))
expect(dropped).not.toHaveProperty('category')
expect(dropped).not.toHaveProperty('note')
const events = (persistence.durable.get(fixture.session.id)?.events ?? [])
.filter(event => event.type === 'feedback/message-put')
.map(event => event.data.item.category)
expect(events).toEqual(['task-result', 'other', undefined])
// A stored payload outside the fixed taxonomy is refused on read.
const corrupt = messageFixture('corrupt-category')
corrupt.session.append('feedback/message-put', {
sessionId: corrupt.session.id,
item: {
messageId: corrupt.assistantMessageIds[0],
rating: 'negative',
category: 'not-a-category' as never,
version: staleVersion(),
createdAt: 1,
updatedAt: 1,
},
})
persistence.persist(corrupt.session)
await expect(ctx.messageFeedback.list({ sessionId: corrupt.session.id })).rejects.toThrow()
})
it('reports non-blank and complete UTF-8 byte limits without touching persistence', async () => {
const { ctx, persistence } = await harness(4)
const fixture = messageFixture('note-limits')
@@ -31,6 +31,9 @@
},
{
"path": "../../typert/protocol"
},
{
"path": "../command-feedback"
}
]
}
+2 -2
View File
@@ -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/fs/tool-present/README.md
README.md: 6767bb3b8d8839ae776fdf441ef853192c5117a2
README.zh.md: 8255e7be42de273d58d01ca9b4e108d4c65a585d
README.md: 77c1a83a30bdbe58b3be35d8bc0d879f1669b5a5
README.zh.md: cec2d64b4e6f95a4e8210e7e24a9c796ed95d749
+1 -1
View File
@@ -73,7 +73,7 @@ The pure `./types` entry declares `PresentedFile` and the Session event without
#### What the model sees
The [present schema](../../../docs/tool-catalog.md#present) asks for existing workspace files: “Declare existing workspace files as final deliverables. The user opens the current source files; their contents are not copied or preserved. Create the files before calling this tool.” Results report `Presented <path>` for each file; the program result and durable event contain paths and optional descriptions.
The [present schema](../../../docs/tool-catalog.md#present) asks for existing workspace files: “Declare existing workspace files as final deliverables. When a file you create or update is an output the user asked to receive, you must call present after writing it and before your final response, including files created through Bash or code execution. Mentioning its path in your reply does not replace this call. The files must already exist. The user opens the current source files; their contents are not copied or preserved.” Results report `Presented <path>` for each file; the program result and durable event contain paths and optional descriptions.
#### Token effect
+1 -1
View File
@@ -73,7 +73,7 @@ kind: "package-reference"
#### 模型看到的内容
[present schema](../../../docs/tool-catalog.zh.md#present)要求已有的工作区文件:“Declare existing workspace files as final deliverables. The user opens the current source files; their contents are not copied or preserved. Create the files before calling this tool.” 每个文件的结果为 `Presented <path>`;程序结果和持久事件包含路径及可选说明。
[present schema](../../../docs/tool-catalog.zh.md#present)要求已有的工作区文件:“Declare existing workspace files as final deliverables. When a file you create or update is an output the user asked to receive, you must call present after writing it and before your final response, including files created through Bash or code execution. Mentioning its path in your reply does not replace this call. The files must already exist. The user opens the current source files; their contents are not copied or preserved.” 每个文件的结果为 `Presented <path>`;程序结果和持久事件包含路径及可选说明。
#### Token 影响
+4 -1
View File
@@ -37,7 +37,10 @@ export function apply(ctx: Context, config: Config): void {
const pending = new WeakMap<ToolExecution, { session: Session; turn: number; files: PresentedFile[] }>()
ctx.tools.register(defineTool({
name: 'present',
description: 'Declare existing workspace files as final deliverables. The user opens the current source files; their contents are not copied or preserved. Create the files before calling this tool.',
description: 'Declare existing workspace files as final deliverables. '
+ 'When a file you create or update is an output the user asked to receive, you must call present after writing it and before your final response, including files created through Bash or code execution. '
+ 'Mentioning its path in your reply does not replace this call. The files must already exist. '
+ 'The user opens the current source files; their contents are not copied or preserved.',
parameters: {
files: {
type: 'array', required: true,
@@ -0,0 +1,56 @@
/** Detached launch settlement with controlled process events and watch time. */
import { ChildProcess, spawn } from 'node:child_process'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { launchDetachedApp } from '../src/resolver.ts'
vi.mock('node:child_process', async importOriginal => ({
...await importOriginal<typeof import('node:child_process')>(),
spawn: vi.fn(),
}))
afterEach(() => {
vi.restoreAllMocks()
vi.mocked(spawn).mockReset()
vi.useRealTimers()
})
describe('launchDetachedApp watch window', () => {
it.each(['exit 0', 'exit 3', 'error'] as const)('ignores late %s after unref without killing the child', async (event) => {
vi.useFakeTimers()
const child = new ChildProcess()
const unref = vi.spyOn(child, 'unref')
const kill = vi.spyOn(child, 'kill')
vi.mocked(spawn).mockReturnValueOnce(child)
try {
const launched = launchDetachedApp('fixture-app', [], { watchMs: 100 })
const fulfilled = vi.fn()
const rejected = vi.fn()
const observed = launched.then(fulfilled, rejected)
await vi.advanceTimersByTimeAsync(99)
expect(fulfilled).not.toHaveBeenCalled()
expect(unref).not.toHaveBeenCalled()
await vi.advanceTimersByTimeAsync(1)
await expect(launched).resolves.toBeUndefined()
await observed
expect(fulfilled).toHaveBeenCalledExactlyOnceWith(undefined)
expect(unref).toHaveBeenCalledTimes(1)
expect(kill).not.toHaveBeenCalled()
// emit() invokes the resolver's registered callback before returning.
const handled = event === 'error'
? child.emit('error', new Error('late launcher error'))
: child.emit('exit', event === 'exit 0' ? 0 : 3, null)
expect(handled).toBe(true)
expect(unref).toHaveBeenCalledTimes(1)
expect(kill).not.toHaveBeenCalled()
expect(rejected).not.toHaveBeenCalled()
expect(vi.getTimerCount()).toBe(0)
} finally {
child.removeAllListeners()
vi.restoreAllMocks()
vi.mocked(spawn).mockReset()
vi.useRealTimers()
}
})
})
@@ -664,18 +664,6 @@ describe('launchDetachedApp', () => {
.rejects.toMatchObject({ code: 'ENOENT' })
})
it('counts a child that outlives the watch window as launched without killing it', async () => {
// The child exits on its own shortly after; the launch settles at the
// window, long before that, and never awaits or kills the process.
const started = Date.now()
await expect(launchDetachedApp(
node, ['-e', 'setTimeout(() => {}, 1500)'], { watchMs: 100 },
)).resolves.toBeUndefined()
expect(Date.now() - started).toBeLessThan(1_400)
// A late exit after the settled window changes nothing.
await new Promise(resolve => setTimeout(resolve, 1_600))
})
it('hands the child a credential-scrubbed environment with explicit adapter entries', async () => {
const root = await tempRoot()
const witness = join(root, 'env.json')
+11 -2
View File
@@ -8,7 +8,7 @@ import { Context } from '@deepseek-ai/cordis'
import LocalFileSystem from '@deepseek-ai/dsh-fs-local'
import { LspInstance, readHostSource } from '@deepseek-ai/dsh-lsp-stdio'
import { encodeMessage } from '@deepseek-ai/dsh-lsp-stdio'
import type { ConnectionWriter } from '@deepseek-ai/dsh-lsp-stdio/src/connection.ts'
import type { ConnectionSpawner, ConnectionWriter } from '@deepseek-ai/dsh-lsp-stdio/src/connection.ts'
import type { InstanceSpec } from '@deepseek-ai/dsh-lsp-stdio/src/instance.ts'
import type { LspProviderQuery, LspQueryResult } from '@deepseek-ai/dsh-lsp'
import { scrubbedParentEnv } from '@deepseek-ai/dsh-subprocess'
@@ -45,6 +45,7 @@ function makeInstance(
env: Record<string, string> = {},
overrides: Partial<InstanceSpec> = {},
writer?: ConnectionWriter,
spawner: ConnectionSpawner = spawnSubprocess,
): LspInstance {
const instance = new LspInstance({
command: process.execPath,
@@ -59,7 +60,7 @@ function makeInstance(
shutdownTimeoutMs: 200,
killGraceMs: 200,
...overrides,
}, spawnSubprocess, writer)
}, spawner, writer)
live.push(instance)
return instance
}
@@ -211,6 +212,7 @@ describe('LspInstance query and abort', () => {
const marker = join(root, 'initialized.log')
const didOpenStarted = Promise.withResolvers<undefined>()
let didOpenFinished = false
let processClosed = false
const instance = makeInstance({
LSP_FAKE_INITIALIZED_MARKER: marker,
LSP_FAKE_PAUSE_STDIN_AFTER_INITIALIZED: '1',
@@ -227,6 +229,10 @@ describe('LspInstance query and abort', () => {
done(error)
})
didOpenStarted.resolve(undefined)
}, (spec) => {
const handle = spawnSubprocess(spec)
void Promise.allSettled([handle.done]).then(([result]) => { processClosed = result.status === 'fulfilled' })
return handle
})
const controller = new AbortController()
const outcome = run(instance, 'goToDefinition', controller.signal)
@@ -235,9 +241,12 @@ describe('LspInstance query and abort', () => {
await didOpenStarted.promise
signal.throwIfAborted()
expect(didOpenFinished).toBe(false)
expect(processClosed).toBe(false)
controller.abort(new Error('didOpen-abort'))
const failure = await outcome
expect(() => { throw failure }).toThrow(/didOpen-abort/)
expect(didOpenFinished).toBe(true)
expect(processClosed).toBe(true)
expect(instance.dead).toBe(true)
})
@@ -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/session/session-format-v1-to-v2/README.md
README.md: 9052dbe12a1e63fff332fbd51c8fc258f1a26ed0
README.zh.md: 42f429f7fab2f012f81d2d3954327ab1431a3d70
README.md: e2bcd2a2be31fddfd8ce77a1ab5fe3ef8cb22599
README.zh.md: cf8aa67722b04060ac70f46c6bbe65c9485028d2
@@ -41,7 +41,7 @@ const headerRecord = releasedV2SessionFormatCodec.encodeHeader(currentHeader, ta
const eventRecord = releasedV2SessionFormatCodec.encodeEvent(currentEvent)
```
`releasedV1SessionFormatCodec` reads the frozen v1 physical language one row at a time. `sessionFormatV1ToV2` creates the cardinality-changing Stage that the static catalog connects to that decoder without retaining a v1 event array. The catalog remaps declared references and validates the released-v2 envelope, inherited cut, event admission, and relationships. Persistence applies full installed-current validation in its Worker before publication. `releasedV2SessionFormatCodec` creates a current row decoder and encodes current headers and events one record at a time.
`releasedV1SessionFormatCodec` reads the frozen v1 physical language one row at a time. `sessionFormatV1ToV2` creates the cardinality-changing Stage that the static catalog connects to that decoder without retaining a v1 event array. The catalog remaps declared references and validates the released-v2 envelope, inherited cut, event admission, and relationships. Persistence applies full installed-current validation in its Worker before publication. `releasedV2SessionFormatCodec` creates a released-v2 row decoder and encodes v2 headers and events one record at a time.
A successful v1 `assistant/message` must cite its complete ordered attempt. The migration removes the cited top-level chunks and obsolete message provenance, compacts the chunks without joining token boundaries, and stores the stream on that message. An unclaimed attempt becomes one log-only `assistant/attempt` at its final chunk position. Unrelated interleaved events keep their relative order.
@@ -41,7 +41,7 @@ const headerRecord = releasedV2SessionFormatCodec.encodeHeader(currentHeader, ta
const eventRecord = releasedV2SessionFormatCodec.encodeEvent(currentEvent)
```
`releasedV1SessionFormatCodec` 逐行读取冻结的 v1 物理语言。`sessionFormatV1ToV2` 创建改变事件基数的 Stage,静态 catalog 把它连接到 decoder,且不保留 v1 事件数组。Catalog 会重映射已声明引用,并校验 released-v2 envelope、inherited cut、事件准入与关系。持久化在发布前通过 Worker 执行完整 installed-current 校验。`releasedV2SessionFormatCodec` 创建当前格式的逐行 decoder,并逐条编码当前 header 与事件。
`releasedV1SessionFormatCodec` 逐行读取冻结的 v1 物理语言。`sessionFormatV1ToV2` 创建改变事件基数的 Stage,静态 catalog 把它连接到 decoder,且不保留 v1 事件数组。Catalog 会重映射已声明引用,并校验 released-v2 envelope、inherited cut、事件准入与关系。持久化在发布前通过 Worker 执行完整 installed-current 校验。`releasedV2SessionFormatCodec` 创建已发布 v2 格式的逐行 decoder,并逐条编码 v2 header 与事件。
成功的 v1 `assistant/message` 必须引用其完整有序 attempt。迁移会移除这些顶层 chunk 和已停用的 message provenance,在不合并 token 边界的前提下压缩 chunk,并把 stream 存到该 message 上。未被 message 认领的 attempt 会在其最后一个 chunk 的位置变成一个仅日志可见的 `assistant/attempt`。无关的交错事件保持相对顺序。
@@ -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/session/session-format-v2-to-v3/README.md
README.md: c9ea46c14bce7e84c23af2a06e0cd310f13397cb
README.zh.md: 64306531b7fcf2c32815e3bbc3c73cb52b6449cf
README.md: d13abe2b6324db5459babc173a6c6b4b7e0069b5
README.zh.md: 5603d5a4049a0dc69c12fecf5347c9881da945be
@@ -194,7 +194,7 @@ The edge preserves historical request meaning and model configuration; it does n
<a id="known-limitations-and-deferred-work"></a>
- **Historical preset ambiguity** — released `code` references cannot distinguish a custom preset with the legacy built-in id; the [exact rename](#header-and-presets) is host-independent.
- **No file or settings migration** — this package never changes committed generations or `settings.yaml`. Persistence owns publishing the final successor; an existing V3 generation does not rerun its incoming edge. V3 is unreleased; compatibility or repair for already-written development V3 files is not provided.
- **No file or settings migration** — this package never changes committed generations or `settings.yaml`. Persistence owns publishing the final successor; an existing V3 generation does not rerun its incoming edge. V3 is released; its compatibility obligations follow the [released-format policy](../../../.agents/notes/implemented/architecture/2026-08-31-released-session-format-migrations.md).
<a id="dev-note"></a>
### Dev Note
@@ -194,7 +194,7 @@ V2 `session-log-deepseek/delivery-accepted` 若携带 `data.sessionFormatVersion
<a id="known-limitations-and-deferred-work"></a>
- **历史预设歧义** — 已发布 `code` 引用无法区分与旧内置标识同名的自定义预设;[精确重命名](#header-and-presets)不依赖宿主。
- **不迁移文件或设置** — 本包绝不修改已提交代或 `settings.yaml`。持久化负责发布最终后继代;已有 V3 代不重新运行其入边。V3 尚未发布;本包不为已写出的开发期 V3 文件提供兼容或修复。
- **不迁移文件或设置** — 本包绝不修改已提交代或 `settings.yaml`。持久化负责发布最终后继代;已有 V3 代不重新运行其入边。V3 已发布;其兼容性义务遵循[已发布格式策略](../../../.agents/notes/implemented/architecture/2026-08-31-released-session-format-migrations.zh.md)。
<a id="dev-note"></a>
### 开发备注
@@ -81,7 +81,7 @@ it('uploads freeform feedback and message put/edit/delete through the unchanged
session.append('user/message', user, { surfaceOp: 'append' })
session.append('assistant/message', { message: assistant, stream: [], turn: 1, step: 1 }, { surfaceOp: 'append' })
const messages = session.deriveMessages()
recordFeedback(session, ' The session needs a clearer explanation. ')
recordFeedback(session, { text: ' The session needs a clearer explanation. ' })
const created = await ctx.messageFeedback.put({ sessionId: session.id, messageId: assistant.id, rating: 'negative', note: 'Explain the result.', ifVersion: null })
if (!created.ok) throw new Error(created.error.code)
const initialPrefix = session.snapshotEvents()
@@ -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/session/session-persistence-jsonl/README.md
README.md: 76d4c635d52d705adc401120a8acbee0fb86adf4
README.zh.md: e2ed4465f1132c43ee7d13e1d36e8e34d6d53a5b
README.md: f60a1cb20ada758f0deaf59a16ce662ff66eaa71
README.zh.md: d56513a05bb8fe04b1a518acf36d78a7b6c542c5
@@ -53,7 +53,7 @@ The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-a
### On-disk layout
Each session gets a session-owned directory under a readable project directory. Every canonical generation starts with a physical header whose version equals its filename. Current v2 stores one physical row per durable event; the frozen v0 and v1 readers also understand their historical packed Assistant-delta rows. V2 stores `isSeeded` in the header and derives the inherited cut from the last tagged `session/end-seed` marker, while historical codecs translate their numeric `seedLength`. The format catalog completes that translation before a handle exposes current logical values. Current storage records use the lossless provenance representation described below:
Each session gets a session-owned directory under a readable project directory. Every canonical generation starts with a physical header whose version equals its filename. The current format stores one physical row per durable event; the frozen v0 and v1 readers also understand their historical packed Assistant-delta rows. The current format stores `isSeeded` in the header and derives the inherited cut from the last tagged `session/end-seed` marker, while historical codecs translate their numeric `seedLength`. The format catalog completes that translation before a handle exposes current logical values. Current storage records use the lossless provenance representation described below:
```text
<root>/
@@ -95,7 +95,7 @@ The backend owns its complete storage runtime (`src/storage.ts`): `JsonlSessionH
### Physical encoding
The default artifact is a standard concatenation of independent [Zstandard frames](../../../.agents/notes/implemented/architecture/2026-07-19-zstandard-jsonl-session-logs.md): one checksummed frame containing only the header line, then one checksummed frame per durable append batch, using Node's built-in Zstandard API at its default compression level (no level knob). Current v2 writes one event per row; `sourceEventSeqs` uses a lossless storage representation in which consecutive runs of at least three sequence numbers become `[start, end]` pairs, any other list stays verbatim, and reading expands the exact in-memory array. Historical migration reuses one Zstandard decoder, passes parsed rows through stateful format stages, and streams current records through one compression context in about 1 MiB main-thread slices while retaining only final current events, bounded decoder state, and the required sequence-remap table. Listing reads and validates only the header frame. `compression: 'none'` keeps the same storage-form logical lines without frame compression. A root belongs to one encoding: startup discovery and targeted lookup reject generations with the other suffix; format migration preserves the configured encoding, while compression conversion, mixed-root fallback, and dual write remain unsupported. Frozen v0 and v1 codecs retain their packed-row decoders solely for historical generations.
The default artifact is a standard concatenation of independent [Zstandard frames](../../../.agents/notes/implemented/architecture/2026-07-19-zstandard-jsonl-session-logs.md): one checksummed frame containing only the header line, then one checksummed frame per durable append batch, using Node's built-in Zstandard API at its default compression level (no level knob). The current format writes one event per row; `sourceEventSeqs` uses a lossless storage representation in which consecutive runs of at least three sequence numbers become `[start, end]` pairs, any other list stays verbatim, and reading expands the exact in-memory array. Historical migration reuses one Zstandard decoder, passes parsed rows through stateful format stages, and streams current records through one compression context in about 1 MiB main-thread slices while retaining only final current events, bounded decoder state, and the required sequence-remap table. Listing reads and validates only the header frame. `compression: 'none'` keeps the same storage-form logical lines without frame compression. A root belongs to one encoding: startup discovery and targeted lookup reject generations with the other suffix; format migration preserves the configured encoding, while compression conversion, mixed-root fallback, and dual write remain unsupported. Frozen v0 and v1 codecs retain their packed-row decoders solely for historical generations.
### Source map
@@ -151,7 +151,7 @@ JSONL storage does not mutate live request prefixes. A resumed loop can reuse pr
These limits define when this backend is a poor fit or needs special operational care. They are current package constraints, not a task backlog.
- **Format migration preserves the configured encoding and supports only the catalogued chain** — this build migrates released v0 or v1 to current v2; changing compression requires a separate root, and retained predecessors do not provide automatic fallback or downgrade support.
- **Format migration preserves the configured encoding and supports only the catalogued chain** — this build migrates supported historical generations to the current format; changing compression requires a separate root, and retained predecessors do not provide automatic fallback or downgrade support.
- **The flat-file storage layout does not load** — use a separate root or move pre-release artifacts into the project/session directory layout before loading.
- **Compressed files are not directly line-readable** — use the backend to load them, or select `compression: 'none'` before writing a fresh root when external line readers are required.
- **Nothing deletes session files** — logs accumulate under `root` until removed externally; the seam has no deletion API.
@@ -53,7 +53,7 @@ kind: "package-reference"
### 磁盘布局
每个会话在可读项目目录下获得一个会话自有目录。每个规范 generation 都以版本与文件名一致的物理 header 开始。当前 v2 为每个持久事件存储一行;冻结的 v0 与 v1 reader 也能理解其历史 packed Assistant delta 行。V2 在 header 中存储 `isSeeded`,并从最后一个带标记的 `session/end-seed` 推导 inherited cut;历史 codec 则转换其数字 `seedLength`。格式 catalog 会在句柄暴露当前逻辑值之前完成该转换。当前存储记录使用下文所述的无损来源序列表示:
每个会话在可读项目目录下获得一个会话自有目录。每个规范 generation 都以版本与文件名一致的物理 header 开始。当前格式为每个持久事件存储一行;冻结的 v0 与 v1 reader 也能理解其历史 packed Assistant delta 行。当前格式在 header 中存储 `isSeeded`,并从最后一个带标记的 `session/end-seed` 推导 inherited cut;历史 codec 则转换其数字 `seedLength`。格式 catalog 会在句柄暴露当前逻辑值之前完成该转换。当前存储记录使用下文所述的无损来源序列表示:
```text
<root>/
@@ -95,7 +95,7 @@ kind: "package-reference"
### 物理编码
默认产物是独立 [Zstandard 帧](../../../.agents/notes/implemented/architecture/2026-07-19-zstandard-jsonl-session-logs.zh.md) 的标准拼接:一个仅包含 header 行的带校验和帧,后跟每个持久 append 批次一个带校验和帧,使用 Node 内置 Zstandard API 的默认压缩级别(无级别开关)。当前 v2 为每个事件写一行;`sourceEventSeqs` 使用无损存储形式:至少包含三个序列号的连续段会变成 `[start, end]` 区间对,其他列表原样保留;读取时会展开回精确的内存数组。历史迁移会复用一个 Zstandard decoder,让已解析行流经有状态格式 Stage,并通过一个压缩 context 以约 1 MiB 主线程分片流式写入当前记录,同时只保留最终当前事件、有界 decoder 状态与必需的序号重映射表。列表只读取并验证 header 帧。`compression: 'none'` 保留相同的存储形式逻辑行,但不使用帧压缩。一个根只属于一种编码:启动发现与定向查找会拒绝使用另一后缀的 generation;格式迁移保留已配置编码,而压缩转换、混合根回退与双写仍不受支持。冻结的 v0 与 v1 codec 仅为历史 generation 保留 packed-row decoder。
默认产物是独立 [Zstandard 帧](../../../.agents/notes/implemented/architecture/2026-07-19-zstandard-jsonl-session-logs.zh.md) 的标准拼接:一个仅包含 header 行的带校验和帧,后跟每个持久 append 批次一个带校验和帧,使用 Node 内置 Zstandard API 的默认压缩级别(无级别开关)。当前格式为每个事件写一行;`sourceEventSeqs` 使用无损存储形式:至少包含三个序列号的连续段会变成 `[start, end]` 区间对,其他列表原样保留;读取时会展开回精确的内存数组。历史迁移会复用一个 Zstandard decoder,让已解析行流经有状态格式 Stage,并通过一个压缩 context 以约 1 MiB 主线程分片流式写入当前记录,同时只保留最终当前事件、有界 decoder 状态与必需的序号重映射表。列表只读取并验证 header 帧。`compression: 'none'` 保留相同的存储形式逻辑行,但不使用帧压缩。一个根只属于一种编码:启动发现与定向查找会拒绝使用另一后缀的 generation;格式迁移保留已配置编码,而压缩转换、混合根回退与双写仍不受支持。冻结的 v0 与 v1 codec 仅为历史 generation 保留 packed-row decoder。
### 源码地图
@@ -151,7 +151,7 @@ JSONL 存储不修改实时请求前缀。只有重建历史、当前 envelope
这些限制说明本后端何时不合适,或何时需要特别的运维注意。它们是当前包约束,不是任务积压。
- **格式迁移保留已配置编码,且只支持 catalog 中的链**——本 build 把已发布 v0 或 v1 迁移到当前 v2;更改压缩需要独立根,保留的前任不提供自动 fallback 或 downgrade 支持。
- **格式迁移保留已配置编码,且只支持 catalog 中的链**——本 build 把受支持的历史代迁移到当前格式;更改压缩需要独立根,保留的前任不提供自动 fallback 或 downgrade 支持。
- **平铺文件存储布局不加载**——加载前使用独立根,或将预发布产物移入项目/会话目录布局。
- **压缩文件不能直接按行读取**——使用后端加载;或在写入新根前选择 `compression: 'none'`,供外部行读取方使用。
- **不删除会话文件**——日志在 `root` 下累积,直到外部移除;seam 无删除接口。
@@ -76,7 +76,7 @@ export function parseGenerationLogFilename(
}
/**
* The current v2 physical header stored as the first JSONL record. The exact
* The current physical header stored as the first JSONL record. The exact
* inherited cut lives on the last tagged `session/end-seed` event.
*/
interface HeaderLine {
@@ -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/session/session-persistence/README.md
README.md: cbc57651ff17801e75bf8cccafb44e1a3df69e7d
README.zh.md: 4fa3ae43de8f0be50afb498f87a9ceaa2a2c23c7
README.md: f0243b7a38dda8d9296a0a1416c9c8a9a990df88
README.zh.md: 47c6f4e9a4fede80b2869ba6d1c986c9b144632a
Loaded 100 of 243 files, more files were not shown because too many files have changed in this diff. Show more