Release 1.5.0 with inline bubble question cards and interaction settings

This commit is contained in:
QQ 2026-11-30 16:42:06 +08:00
parent 7d8dfb1e5d
commit 8bcf48169b
22 changed files with 5309 additions and 52 deletions

View File

@ -1,5 +1,12 @@
# Changelog
## 1.5.0 — 2026-11-30
- 气泡内嵌提问选项卡:新增 `conversation.composer` 拦截与单挂载接管控制器,仅将模型发起的提问(`kind === 'question'`)选项卡直接嵌进对应波次的 AI 回复气泡中,同时保留工具审批与方案确认在底部原生操作区的实时弹出;切到「轨迹」等其他标签页时自动退回原生底部操作区。
- 历史提问查看、补答与重答:每轮提问卡支持展示状态(待回答 / 已继续工作仍可回答 / 已排队 / 已回答 / 已取消 / 已中断 / 未作答)、展开/查看原卡、在继续工作状态下直接提交补答,以及对历史已答或中断/取消提问发起追问修改;当更早轮次仍有未回答提问落在渲染窗口之外时,底部展示「去回答」提示条并在定位按钮显示「待回答」。
- 设置面板新增开关:在「设置 → Better Chat」新增「在回复气泡内显示提问选项卡」开关(默认开启)。
- 验证:`tsc --noEmit`、`vitest run`(38 个文件 / 287 个用例)、`tsdown` 构建通过。
## 1.4.0 — 2026-11-29
- 长会话渲染窗口与性能隔离:默认仅渲染最近 `6` 轮对话(可在「设置 → Better Chat」配置 `4 / 6 / 10 / 20 / 全部` 或 `1–200` 自定义轮数),支持顶部「加载更早记录(还有 N 轮)」分批向上展开并保持视口滚动锚定;跳回早期区间时底部提供「向下展开 / 回到最新」控制条;`RetiringTurns` 区分窗口裁剪与真实撤回动画;`TurnGroup` 对已结束轮次进行快照隔离并稳定化分组引用,消除末尾流式输出时历史对话重算与重绘卡顿。

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,6 +1,6 @@
{
"name": "dsh-better-chat",
"version": "1.4.0",
"version": "1.5.0",
"description": "DSH 聊天增强插件:审批回车批准 / Esc 拒绝、权限 UI、插件商店更新、默认自动审查。",
"type": "module",
"license": "MIT",

View File

@ -3,7 +3,7 @@ import type { ReactNode } from 'react';
import type { ChatSnapshot } from '@deepseek-ai/dsh-client-ui-chat/client';
import type { ReaderProps } from './types.js';
import type { LiveStep, LiveTurnItem } from './live-turn.js';
import { arrangeTurnWaves, collapseRows, containsNewUser, flowRows, FOLD_TIMING, retiringKeys } from './fold-choreography.js';
import { arrangeTurnWaves, collapseRows, containsNewUser, distributeBubbleQuestions, flowRows, FOLD_TIMING, retiringKeys } from './fold-choreography.js';
import type { FlowBucket, FlowRow, FoldPhase } from './fold-choreography.js';
import { Disclosure } from './motion.js';
import { FoldSummaryText } from './LiveFold.js';
@ -150,10 +150,16 @@ function ProcessScroll({ children, live, hidden }: { children: ReactNode; live:
</div>;
}
export function ChoreographedFlow({ frame, motion, enabled, urgent, open, onOpenChange, processOpen, running, renderStep, id, status }: {
export interface BubbleQuestionItem {
readonly callId: string;
readonly node: ReactNode;
}
export function ChoreographedFlow({ frame, motion, enabled, urgent, open, onOpenChange, processOpen, running, renderStep, id, status, bubbleQuestions }: {
frame: PresentationFrame; motion: boolean; enabled: boolean; urgent: boolean;
open: Readonly<Record<string, boolean>>; onOpenChange: (key: string, value: boolean) => void;
processOpen: boolean; running: boolean; renderStep: (step: LiveStep, folded: boolean) => ReactNode; id: string; status?: ReactNode;
bubbleQuestions?: readonly BubbleQuestionItem[];
}) {
const root = useRef<HTMLDivElement>(null);
const [collapsedFrames, setCollapsedFrames] = useState<ReadonlySet<string>>(() => new Set());
@ -298,6 +304,7 @@ export function ChoreographedFlow({ frame, motion, enabled, urgent, open, onOpen
return { row, key: row.key, hidden, process: isProcess, bucket: isProcess ? 'process' : 'other' };
});
const waves = arrangeTurnWaves(cells);
const { byWaveKey: questionsByWave, tailOnly } = distributeBubbleQuestions(waves, bubbleQuestions ?? []);
let statusWaveIndex = -1;
if (status) {
for (let i = waves.length - 1; i >= 0; i--) {
@ -326,6 +333,7 @@ export function ChoreographedFlow({ frame, motion, enabled, urgent, open, onOpen
<div id={id} ref={root} className={css.choreographedFlow} data-reader-flow data-reader-transition={state.phase} data-ud-motion="fold-choreography">
{waves.map((wave, index) => {
if (wave.user) return renderCell(wave.user);
const waveQuestions = questionsByWave.get(wave.key) ?? [];
const hasStatus = index === statusWaveIndex && !!status;
const hasProcessRows = wave.process.length > 0;
const showProcessFrame = hasStatus || (processOpen && hasProcessRows);
@ -335,9 +343,20 @@ export function ChoreographedFlow({ frame, motion, enabled, urgent, open, onOpen
const scrollHidden = localCollapsed || (!processOpen && !wave.process.some(cell => cell.row.kind === 'summary')) || !hasVisibleProcessContent;
const frameCollapsed = scrollHidden;
return <Fragment key={`wave:${wave.key}`}>
{wave.body.length > 0 && <div className={css.answerBubble} data-reader-answer-bubble>
{(wave.body.length > 0 || waveQuestions.length > 0) && (
<div
className={css.answerBubble}
data-reader-answer-bubble
data-reader-bubble-with-questions={waveQuestions.length > 0 || undefined}
>
{wave.body.map(cell => renderCell(cell))}
</div>}
{waveQuestions.length > 0 && (
<div className={css.bubbleQuestions} data-reader-bubble-questions>
{waveQuestions.map(item => <Fragment key={item.callId}>{item.node}</Fragment>)}
</div>
)}
</div>
)}
{wave.other.map(cell => renderCell(cell))}
{showProcessFrame && <div className={css.processViewport} data-reader-process-frame data-reader-frame-collapsed={frameCollapsed || undefined}>
{hasStatus && <div className={css.turnStickyLanes} data-flow-process>{status}</div>}
@ -358,6 +377,13 @@ export function ChoreographedFlow({ frame, motion, enabled, urgent, open, onOpen
</div>}
</Fragment>;
})}
{tailOnly.length > 0 && (
<div className={css.answerBubble} data-reader-answer-bubble data-reader-bubble-with-questions="true">
<div className={css.bubbleQuestions} data-reader-bubble-questions>
{tailOnly.map(item => <Fragment key={item.callId}>{item.node}</Fragment>)}
</div>
</div>
)}
</div>
</StreamMotionContext.Provider>
</FlowSnapshot.Provider>;

View File

@ -48,7 +48,11 @@
--dsw-alias-state-success-primary: #2f9e63;
--dsw-alias-state-error-primary: #d1483c;
--dsw-alias-state-warning-primary: #d8862c;
--dsw-alias-state-warn-primary: #b45309;
--dsw-alias-state-warn-secondary: rgba(217, 119, 6, 0.35);
--dsw-alias-state-warn-tertiary: rgba(245, 158, 11, 0.12);
--dsw-specific-bubble: #eff3fb;
--dsw-specific-input-major: #ffffff;
--dsw-alias-markdown-code-block: #f6f7f9;
--dsw-elevation-panel: 0 2px 12px rgba(15, 23, 42, 0.08);
}
@ -72,7 +76,11 @@
--dsw-alias-state-success-primary: #45c47f;
--dsw-alias-state-error-primary: #f06559;
--dsw-alias-state-warning-primary: #e8a449;
--dsw-alias-state-warn-primary: #f5b95b;
--dsw-alias-state-warn-secondary: rgba(245, 185, 91, 0.32);
--dsw-alias-state-warn-tertiary: rgba(245, 185, 91, 0.14);
--dsw-specific-bubble: #252d40;
--dsw-specific-input-major: #1e222a;
--dsw-alias-markdown-code-block: #1b1e25;
--dsw-elevation-panel: 0 4px 18px rgba(0, 0, 0, 0.45);
}
@ -131,7 +139,15 @@
border: 1px solid var(--dsw-alias-border-l1);
overflow-wrap: anywhere;
}
.answerBubble:not(:has(> .flowCell:not([hidden]))) { display: none; }
.answerBubble[data-reader-bubble-with-questions] {
width: fit-content;
min-width: min(100%, 300px);
max-width: var(--reader-ai-max-width);
}
.root[data-reader-bubble-style="plain"] .answerBubble[data-reader-bubble-with-questions] {
width: 100%;
}
.answerBubble:not(:has(> .flowCell:not([hidden]), > .bubbleQuestions)) { display: none; }
.answerBubble > .flowCell > .flowCellInner { padding-bottom: 0; }
.answerBubble :global(.md-code-block) {
background: var(--dsw-alias-bg-base);
@ -520,6 +536,421 @@
.errorCode { font-size: 11px; padding: 1px 5px; border-radius: 4px; background: rgba(239, 68, 68, 0.12); color: #dc2626; font-family: inherit; }
.attention { display: flex; flex-direction: column; gap: 3px; border: 1px solid var(--dsw-alias-state-business-primary); color: var(--dsw-alias-label-primary); background: var(--dsw-alias-bg-base); }
.attention span { color: var(--dsw-alias-label-secondary); }
.inlineInteraction {
width: 100%;
max-width: 100%;
min-width: 0;
margin-top: 2px;
/* Official composer takeover cards inherit these tokens from [data-composer-seat]
and apply horizontal padding = var(--dsh-composer-side-clearance) + 16px.
Inside .column, cancel the extra side gutter and keep a bounded detail height. */
--dsh-composer-side-clearance: -16px;
--dsh-composer-text-max-height: 360px;
animation: readerInlineCardIn 200ms cubic-bezier(.22, 1, .36, 1) both;
}
.inlineInteraction > [data-slot] > * {
padding-inline: 0;
padding-block: 0;
width: 100%;
box-sizing: border-box;
}
@keyframes readerInlineCardIn {
from { opacity: 0; transform: translateY(6px); }
to { opacity: 1; transform: translateY(0); }
}
[data-motion=off] .inlineInteraction { animation: none !important; }
@media (prefers-reduced-motion: reduce) { .inlineInteraction { animation: none !important; } }
.bubbleQuestions {
display: flex;
flex-direction: column;
gap: 8px;
width: 100%;
min-width: 0;
}
.answerBubble > .flowCell:not([hidden]) ~ .bubbleQuestions {
padding-top: 2px;
}
.bubbleQuestions .inlineInteraction {
margin-top: 0;
}
.museQuestionBlock,
.bubbleQuestions .questionCard {
display: flex;
flex-direction: column;
gap: 8px;
min-width: 0;
padding: 0;
border: 0;
border-radius: 0;
background: transparent;
box-shadow: none;
color: var(--dsw-alias-label-primary);
font-size: calc(14px + var(--dsh-content-font-delta, 0px));
line-height: calc(22px + var(--dsh-content-font-delta, 0px));
box-sizing: border-box;
}
.answerBubble > .flowCell:not([hidden]) ~ .bubbleQuestions > .questionCard {
padding-top: 10px;
border-top: 1px dashed var(--dsw-alias-border-l1);
}
.questionPromptText {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 6px;
color: var(--dsw-alias-label-primary);
font-size: calc(14px + var(--dsh-content-font-delta, 0px));
line-height: calc(22px + var(--dsh-content-font-delta, 0px));
}
.questionStepTabs {
display: flex;
flex-wrap: wrap;
gap: 4px;
}
.questionStepTab {
border: 1px dashed var(--dsw-alias-border-l1);
border-radius: 999px;
background: transparent;
color: var(--dsw-alias-label-tertiary);
font: inherit;
font-size: 12px;
line-height: 18px;
padding: 2px 9px;
cursor: pointer;
}
.questionStepTab[data-done] {
color: var(--dsw-alias-label-secondary);
border-color: var(--dsw-alias-border-l2);
}
.questionStepTab[data-active] {
border-style: solid;
border-color: var(--dsw-alias-state-business-primary);
color: var(--dsw-alias-state-business-primary);
font-weight: 500;
}
.questionCard {
display: flex;
flex-direction: column;
gap: 8px;
min-width: 0;
color: var(--dsw-alias-label-primary);
font-size: 13px;
line-height: 20px;
box-sizing: border-box;
}
.questionInlineFoot {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 6px 10px;
margin-top: 2px;
}
.questionInlineLinks {
display: inline-flex;
align-items: center;
gap: 10px;
}
.questionGhostBtn {
border: 0;
padding: 2px 4px;
border-radius: 6px;
background: transparent;
color: var(--dsw-alias-label-tertiary);
font: inherit;
font-size: 12px;
line-height: 18px;
cursor: pointer;
white-space: nowrap;
}
.questionGhostBtn:hover:not(:disabled) {
color: var(--dsw-alias-label-primary);
background: var(--dsw-alias-interactive-bg-hover);
}
.questionGhostBtn:disabled { opacity: 0.5; cursor: default; }
.questionOptionRowHead {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
width: 100%;
}
.questionOptionCheck {
flex: none;
font-size: 12px;
font-weight: 600;
color: var(--dsw-alias-state-business-primary);
}
.questionCardHeader {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px 12px;
flex-wrap: wrap;
min-width: 0;
}
.questionSummaryBtn,
.questionSummaryStatic {
display: flex;
align-items: center;
gap: 8px;
flex: 1 1 200px;
min-width: 0;
padding: 0;
border: 0;
background: transparent;
color: inherit;
font: inherit;
text-align: left;
}
.questionSummaryBtn { cursor: pointer; }
.questionSummaryBtn:hover .questionSummaryText { color: var(--dsw-alias-label-primary); }
.questionStatusBadge {
flex: none;
display: inline-flex;
align-items: center;
padding: 1px 8px;
border-radius: 999px;
font-size: 11px;
font-weight: 500;
line-height: 18px;
color: var(--dsw-alias-label-secondary);
background: var(--dsw-alias-interactive-bg-hover);
}
.questionCard[data-question-status="open"] .questionStatusBadge,
.questionCard[data-question-status="continued"] .questionStatusBadge {
color: var(--dsw-alias-state-warn-primary, var(--dsw-alias-state-business-primary));
background: var(--dsw-alias-state-warn-tertiary, var(--dsw-alias-interactive-bg-hover));
}
.questionCard[data-question-status="answered"] .questionStatusBadge {
color: var(--dsw-alias-state-success-primary, var(--dsw-alias-label-secondary));
background: color-mix(in srgb, var(--dsw-alias-state-success-primary, #2f9e63) 12%, transparent);
}
.questionSummaryText {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--dsw-alias-label-secondary);
font-size: 13px;
}
.questionCardActions {
display: inline-flex;
align-items: center;
flex-wrap: wrap;
gap: 6px;
flex: none;
}
.questionActionBtn {
border: 1px solid var(--dsw-alias-border-l2);
border-radius: 8px;
background: var(--dsw-alias-bg-base);
color: var(--dsw-alias-label-secondary);
font: inherit;
font-size: 12px;
line-height: 18px;
padding: 4px 10px;
cursor: pointer;
white-space: nowrap;
transition: background-color 140ms ease, border-color 140ms ease, color 140ms ease;
}
.questionActionBtn:hover:not(:disabled) {
background: var(--dsw-alias-interactive-bg-hover);
color: var(--dsw-alias-label-primary);
border-color: var(--dsw-alias-border-l3, var(--dsw-alias-border-l2));
}
.questionActionBtn:disabled { opacity: 0.55; cursor: default; }
.questionActionPrimary {
border-color: transparent;
background: var(--dsw-alias-state-business-primary);
color: #ffffff;
font-weight: 500;
}
.questionActionPrimary:hover:not(:disabled) {
background: color-mix(in srgb, var(--dsw-alias-state-business-primary) 88%, #000000);
color: #ffffff;
border-color: transparent;
}
.questionPreviewList,
.questionHistoryList {
display: flex;
flex-direction: column;
gap: 8px;
margin: 0;
padding-top: 6px;
border-top: 1px solid var(--dsw-alias-border-l1);
}
.questionPreviewItem,
.questionHistoryItem {
display: flex;
flex-direction: column;
gap: 4px;
min-width: 0;
}
.questionPreviewPrompt,
.questionHistoryPrompt,
.questionFormPrompt {
display: flex;
align-items: baseline;
flex-wrap: wrap;
gap: 6px;
font-size: 13px;
line-height: 20px;
color: var(--dsw-alias-label-primary);
}
.questionHeaderChip {
flex: none;
padding: 0 6px;
border-radius: 5px;
background: var(--dsw-alias-interactive-bg-hover);
color: var(--dsw-alias-label-secondary);
font-size: 11px;
line-height: 18px;
}
.questionOptionTags {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.questionOptionTag {
padding: 2px 8px;
border-radius: 999px;
border: 1px solid var(--dsw-alias-border-l1);
background: var(--dsw-alias-bg-module-platform);
color: var(--dsw-alias-label-secondary);
font-size: 12px;
line-height: 18px;
}
.questionHistoryAnswer {
margin: 0;
font-size: 12px;
line-height: 18px;
color: var(--dsw-alias-label-secondary);
overflow-wrap: anywhere;
}
.questionReanswerForm {
display: flex;
flex-direction: column;
gap: 12px;
padding-top: 8px;
border-top: 1px solid var(--dsw-alias-border-l1);
}
.questionFormBlock {
display: flex;
flex-direction: column;
gap: 8px;
min-width: 0;
}
.questionMultiHint {
font-size: 11px;
color: var(--dsw-alias-label-tertiary);
}
.questionOptionGrid {
display: flex;
flex-direction: column;
gap: 8px;
width: 100%;
}
.questionOptionBtn {
width: 100%;
box-sizing: border-box;
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 2px;
padding: 9px 14px;
border-radius: 12px;
border: 1px dashed var(--dsw-alias-border-l2);
background: transparent;
color: var(--dsw-alias-label-primary);
font: inherit;
font-size: calc(13.5px + var(--dsh-content-font-delta, 0px));
line-height: 20px;
text-align: left;
cursor: pointer;
transition: background-color 140ms ease, border-color 140ms ease;
}
.questionOptionBtn:hover:not(:disabled) {
background: var(--dsw-alias-interactive-bg-hover);
border-color: var(--dsw-alias-border-l3, var(--dsw-alias-border-l2));
}
.questionOptionBtn:disabled { opacity: 0.6; cursor: default; }
.questionOptionBtn[data-selected] {
border-style: solid;
border-color: var(--dsw-alias-state-business-primary);
background: color-mix(in srgb, var(--dsw-alias-state-business-primary) 10%, transparent);
}
.questionOptionLabel { font-weight: 500; overflow-wrap: anywhere; }
.questionOptionDesc { font-size: 11px; line-height: 16px; color: var(--dsw-alias-label-secondary); overflow-wrap: anywhere; }
.questionCustomInput {
width: 100%;
box-sizing: border-box;
padding: 7px 10px;
border-radius: 8px;
border: 1px solid var(--dsw-alias-border-l2);
background: var(--dsw-alias-bg-base);
color: var(--dsw-alias-label-primary);
font: inherit;
font-size: 12px;
line-height: 18px;
}
.questionCustomInput:focus {
outline: 2px solid color-mix(in srgb, var(--dsw-alias-state-business-primary) 45%, transparent);
border-color: var(--dsw-alias-state-business-primary);
}
.questionFormError {
margin: 0;
font-size: 12px;
line-height: 18px;
color: var(--dsw-alias-state-error-primary, #d1483c);
}
.questionFormFooter {
display: flex;
justify-content: flex-end;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
.unansweredBanner {
display: flex;
flex-direction: column;
gap: 8px;
padding: 10px 14px;
border-radius: 12px;
border: 1px solid var(--dsw-alias-state-warn-secondary, var(--dsw-alias-border-l2));
background: var(--dsw-alias-state-warn-tertiary, var(--dsw-alias-bg-module-platform));
font-size: 12px;
line-height: 18px;
}
.unansweredBannerLabel {
font-weight: 500;
color: var(--dsw-alias-state-warn-primary, var(--dsw-alias-label-primary));
}
.unansweredBannerList {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.unansweredBannerBtn {
border: 1px solid var(--dsw-alias-border-l2);
border-radius: 999px;
background: var(--dsw-alias-bg-base);
color: var(--dsw-alias-label-primary);
font: inherit;
font-size: 12px;
line-height: 18px;
padding: 3px 12px;
cursor: pointer;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.unansweredBannerBtn:hover {
background: var(--dsw-alias-interactive-bg-hover);
border-color: var(--dsw-alias-state-business-primary);
}
.unknown { background: var(--dsw-alias-bg-module-platform); border: 1px solid var(--dsw-alias-border-l2); border-radius: 10px; padding: 12px 14px; font-size: 13px; line-height: 22px; }
.unknown p { margin: 0 0 6px; }
.historyButton {
@ -636,6 +1067,7 @@
.priorFoldDrawer { display: flex; flex-direction: column; gap: 14px; min-width: 0; width: 100%; }
.jump { margin-top: -34px; flex: none; width: 34px; height: 34px; display: flex; justify-content: center; align-items: center; padding: 0; border: 0; border-radius: 100px; color: var(--dsw-alias-label-primary); background: var(--dsw-alias-button-floating-fill, var(--dsw-alias-bg-base)); box-shadow: var(--dsw-elevation-panel, 0 2px 8px var(--dsw-alias-border-l1)); pointer-events: auto; }
.jump:hover { background: var(--dsw-alias-button-floating-hover, var(--dsw-alias-interactive-bg-hover)); }
.jumpPending { width: auto; padding: 0 12px; gap: 5px; font-size: 12px; font-weight: 500; border: 1px solid color-mix(in srgb, var(--dsw-alias-state-business-primary) 35%, transparent); color: var(--dsw-alias-state-business-primary); }
/* Keep each label and count together when a longer digest needs another line. */
.foldSummary { display: inline-flex; align-items: baseline; flex-wrap: wrap; min-width: 0; }
.foldSummaryPart { display: inline-flex; align-items: baseline; white-space: nowrap; flex: none; }
@ -928,6 +1360,31 @@
.root[data-reader-glass] .imageDialog {
background: transparent;
}
.root[data-reader-glass] .inlineInteraction {
--dsw-specific-input-major: color-mix(in srgb, var(--dsw-alias-bg-base, rgba(255, 255, 255, 0.85)) 72%, transparent);
}
.root[data-reader-glass] .inlineInteraction > [data-slot] > * > * {
backdrop-filter: blur(14px);
}
.root[data-reader-glass] .bubbleQuestions .questionCard {
background: transparent;
backdrop-filter: none;
}
.root[data-reader-glass] .unansweredBanner {
background: color-mix(in srgb, var(--dsw-alias-bg-base, rgba(255, 255, 255, 0.8)) 55%, transparent);
backdrop-filter: blur(12px);
}
.root[data-reader-glass] .questionOptionBtn {
background: transparent;
}
.root[data-reader-glass] .questionOptionBtn:hover:not(:disabled) {
background: color-mix(in srgb, var(--dsw-alias-bg-base, rgba(255, 255, 255, 0.85)) 25%, transparent);
}
.root[data-reader-glass] .questionCustomInput,
.root[data-reader-glass] .questionActionBtn:not(.questionActionPrimary),
.root[data-reader-glass] .unansweredBannerBtn {
background: color-mix(in srgb, var(--dsw-alias-bg-base, rgba(255, 255, 255, 0.85)) 40%, transparent);
}
/* Diff overlay in skin mode */
.root[data-reader-glass] .diffOverlay {
background: color-mix(in srgb, var(--dsw-alias-bg-module-platform, rgba(127,127,127,.1)) 20%, transparent);

View File

@ -4,6 +4,7 @@ import { Fragment, memo, useCallback, useEffect, useId, useInsertionEffect, useL
import type { ReactNode, RefObject } from 'react';
import type { ChatConversationViewNode, ChatNode, ChatNodeKind, ChatNodeOwnerProps, ChatSnapshot } from '@deepseek-ai/dsh-client-ui-chat/client';
import type { TurnLocation } from '@deepseek-ai/dsh-client-ui-conversation/client';
import type { SessionPendingInteraction } from '@deepseek-ai/dsh-client-ui-session/client';
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store';
import { JsonBlock, MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives';
import { BlockBoundary, Blocks, contentBlocks, CopyAnswer, UserMessageActions } from './Blocks.js';
@ -11,6 +12,17 @@ import { AssistantNode } from './AssistantNode.js';
import { ToolActivity, ToolMedia } from './ToolActivity.js';
import { OfficialActions, OfficialNode, OfficialTail } from './OfficialContent.js';
import { OFFICIAL_SEATS, readerGroupAction } from './official-slots.js';
import { inlineInteractionsOf, isInlineQuestionPending } from './inline-interaction.js';
import { asInteractivePending, MuseLiveQuestion, TurnQuestionCard } from './TurnQuestionCard.js';
import {
extractGroupQuestions,
findHostedPendingGroupKey,
findOffWindowActiveQuestions,
pendingCallIdOf,
queuedQuestionRepliesFromInbox,
type TurnQuestionEntry,
type UserQuestionsProjectionView,
} from './turn-questions.js';
import { preparingLabel, readerFlow } from './tool-activity.js';
import { Disclosure, ProcessFragment, RetiringTurns, StatusText, useMotionAllowed, usePinnedSelection, useReadingScroll } from './motion.js';
import { StreamMotionContext } from './streaming.js';
@ -27,7 +39,7 @@ import { mergeTimelineItems, type TimelineItem } from './timeline.js';
import { presentLiveTurn, segmentLiveTurn } from './live-turn.js';
import type { LiveStep } from './live-turn.js';
import { aiBubbleStyleOf, aiBubbleWidthOf, readerThemeOf } from './appearance.js';
import { ChoreographedFlow, useFlowChat } from './ChoreographedFlow.js';
import { ChoreographedFlow, useFlowChat, type BubbleQuestionItem } from './ChoreographedFlow.js';
import { ClosedProcessSummary } from './ClosedProcessSummary.js';
import { ReaderLaneScope, StickyLane } from './StickyLane.js';
import type { ReaderGroup, TurnBoundary } from './projection.js';
@ -494,7 +506,28 @@ type ClosedSnapshotCache = {
nodes: ReadonlyArray<ChatConversationViewNode | undefined>;
};
const TurnGroup = memo(function TurnGroup({ group, motion, autoFold, pinnedKeys, selectedProcessKeys, isAwaitingModel = false, ...props }: ReaderProps & { group: ReaderGroup; motion: boolean; autoFold: boolean; pinnedKeys: readonly string[]; selectedProcessKeys: readonly string[]; isAwaitingModel?: boolean }) {
const TurnGroup = memo(function TurnGroup({
group,
motion,
autoFold,
pinnedKeys,
selectedProcessKeys,
isAwaitingModel = false,
turnQuestions,
hostedPending,
inlineClaimed = false,
...props
}: ReaderProps & {
group: ReaderGroup;
motion: boolean;
autoFold: boolean;
pinnedKeys: readonly string[];
selectedProcessKeys: readonly string[];
isAwaitingModel?: boolean;
turnQuestions?: readonly TurnQuestionEntry[];
hostedPending?: SessionPendingInteraction;
inlineClaimed?: boolean;
}) {
const turnCache = useRef<ClosedSnapshotCache | null>(null);
const selectTurnSnapshot = useCallback((current: ChatSnapshot): ChatSnapshot => {
const prev = turnCache.current;
@ -669,12 +702,46 @@ const TurnGroup = memo(function TurnGroup({ group, motion, autoFold, pinnedKeys,
<BlockBoundary><MainNode {...shared} boundary={boundary} nodeKey={step.nodeKey} pinned={pinnedKeys.includes(step.nodeKey)} processOpen={processOpen} /></BlockBoundary>
</Fragment>;
};
const bubbleQuestions = useMemo<readonly BubbleQuestionItem[] | undefined>(() => {
if (!turnQuestions || turnQuestions.length === 0) return undefined;
return turnQuestions.map(entry => ({
callId: entry.callId,
node: (
<TurnQuestionCard
entry={entry}
sessionId={props.sessionId}
pending={hostedPending !== undefined && pendingCallIdOf(hostedPending) === entry.callId ? hostedPending : undefined}
inlineClaimed={inlineClaimed}
useSession={props.useSession}
renderSlotChain={props.renderSlotChain}
revealQuestion={props.revealQuestion}
reviewQuestion={props.reviewQuestion}
answerContinuedQuestion={props.answerContinuedQuestion}
sendFollowUp={props.sendFollowUp}
fillComposer={props.fillComposer}
/>
),
}));
}, [
turnQuestions,
props.sessionId,
hostedPending,
inlineClaimed,
props.useSession,
props.renderSlotChain,
props.revealQuestion,
props.reviewQuestion,
props.answerContinuedQuestion,
props.sendFollowUp,
props.fillComposer,
]);
return <section className={css.turn} data-reader-group-key={group.key} data-reader-turn={group.turn ?? 'unresolved'} data-reader-turn-state={boundary.status} data-reader-turn-result={boundary.reason ?? undefined}>
{startsWithUser && <BlockBoundary><MainNode {...shared} useChat={props.useChat} boundary={boundary} nodeKey={group.keys[0]} /></BlockBoundary>}
<div className={css.turnStickyRegion} data-reader-sticky-region>
<ChoreographedFlow id={flowId} frame={presentation} motion={motion} enabled={autoFold && boundary.status === 'open' && !holdingSelection}
urgent={hasTurnError || interaction !== undefined || !sessionRunning} open={foldOpenByKey} processOpen={expanded}
running={sessionRunning && boundary.status === 'open' && !holdingSelection}
bubbleQuestions={bubbleQuestions}
status={(showStatusLane || showClosedSummary) && <StickyLane kind="status" className={css.turnProcessSticky}>
{showStatusLane && <Disclosure open={expanded} onChange={setExpanded} controls={flowId} buttonRef={processButton}
label={<GroupStatus group={group} useChat={props.useChat} pending={interaction} motion={motion} />} />}
@ -696,6 +763,79 @@ const TurnGroup = memo(function TurnGroup({ group, motion, autoFold, pinnedKeys,
</section>;
});
const noopSubscribe = () => () => {};
const InlineInteraction = memo(function InlineInteraction({
sessionId,
pending,
useSession,
renderSlotChain,
inlineEnabled,
inlineClaimed,
}: Pick<ReaderProps, 'sessionId' | 'useSession' | 'renderSlotChain'> & {
pending: SessionPendingInteraction;
inlineEnabled: boolean;
inlineClaimed: boolean;
}) {
const session = useSession(snapshot => snapshot);
const attention = (
<div className={css.attention} role="alert" data-reader-attention>
<strong>需要你回答一个问题</strong>
<span>请在下方原生操作区处理。此提示不会收进执行过程。</span>
</div>
);
if (!inlineEnabled) return attention;
if (!inlineClaimed) return null;
const interactive = asInteractivePending(pending);
if (interactive) {
return (
<div className={css.answerBubble} data-reader-answer-bubble data-reader-bubble-with-questions="true">
<div className={css.bubbleQuestions} data-reader-bubble-questions>
<MuseLiveQuestion callId={pendingCallIdOf(pending) ?? pending.key} pending={interactive} />
</div>
</div>
);
}
return (
<div className={css.answerBubble} data-reader-answer-bubble data-reader-bubble-with-questions="true">
<div className={css.bubbleQuestions} data-reader-bubble-questions>
<div className={css.inlineInteraction} data-reader-inline-interaction data-reader-anchor>
{renderSlotChain(OFFICIAL_SEATS.composer, {
sessionId,
session,
pendingInteraction: pending,
}, {
fallback: attention,
})}
</div>
</div>
</div>
);
});
function sameTurnQuestionEntryList(
prev: readonly TurnQuestionEntry[] | undefined,
next: readonly TurnQuestionEntry[],
): boolean {
if (!prev || prev.length !== next.length) return false;
for (let i = 0; i < prev.length; i += 1) {
const a = prev[i]!;
const b = next[i]!;
if (a.callId !== b.callId || a.status !== b.status || a.turn !== b.turn || a.groupKey !== b.groupKey) return false;
if (a.questions.length !== b.questions.length || a.answers.length !== b.answers.length) return false;
if ((a.reviewRecord === undefined) !== (b.reviewRecord === undefined)) return false;
if (a.answers.some((ans, j) => {
const other = b.answers[j];
return !other
|| ans.id !== other.id
|| ans.custom !== other.custom
|| ans.selected.length !== other.selected.length
|| ans.selected.some((label, k) => label !== other.selected[k]);
})) return false;
}
return true;
}
export function Reader(props: ReaderProps) {
useInsertionEffect(() => { ensureStyles(); }, []);
const root = useRef<HTMLDivElement>(null);
@ -708,6 +848,7 @@ export function Reader(props: ReaderProps) {
const timeline = props.useChat(snapshot => snapshot.timeline);
const running = props.useSession(snapshot => snapshot.running);
const pending = props.useSessionStatus(snapshot => snapshot.get(props.sessionId)?.pendingInteraction);
const questionPending = isInlineQuestionPending(pending) ? pending : undefined;
const openError = props.useSession(snapshot => snapshot.openError);
const loading = props.useSession(snapshot => snapshot.openState === 'loading');
const hasMore = props.useSession(snapshot => snapshot.hasMore);
@ -715,6 +856,11 @@ export function Reader(props: ReaderProps) {
const pendingSubmissions = props.useSession(snapshot => snapshot.pendingSubmissions);
const pendingList = asReadonlyArray<PendingSubmissionEcho>(pendingSubmissions);
const inbox = props.useProjection?.('inbox');
const userQuestionsProjection = props.useProjection?.('userQuestions' as never) as UserQuestionsProjectionView | undefined;
const queuedQuestionReplies = useMemo(
() => queuedQuestionRepliesFromInbox(inbox),
[inbox],
);
type PendingInboxItem = { source?: { kind?: string; rpcId?: unknown }; content?: readonly unknown[] };
const inboxSteering = asReadonlyArray<PendingInboxItem>(inbox?.['next-step']).filter(item => item.source?.kind === 'user');
const observed = useMemo(() => observedInputIds(order, key => nodes.get(key)), [order, nodes]);
@ -755,6 +901,17 @@ export function Reader(props: ReaderProps) {
const frostedGlass = readerTheme === 'glass';
const aiBubbleStyle = aiBubbleStyleOf(prefsSnap);
const aiBubbleWidth = aiBubbleWidthOf(prefsSnap);
const inlineEnabled = inlineInteractionsOf(prefsSnap) && props.inlineInteraction !== undefined;
const inlineToken = useRef(Symbol('reader-inline-interaction')).current;
useLayoutEffect(
() => props.inlineInteraction?.acquire(props.sessionId, inlineToken),
[props.inlineInteraction, props.sessionId, inlineToken],
);
const inlineClaimed = useSyncExternalStore(
props.inlineInteraction?.subscribe ?? noopSubscribe,
() => props.inlineInteraction?.isClaimed(props.sessionId, inlineToken) ?? false,
() => false,
);
const streamMotion = useMemo(() => ({ enabled: motion, activatedAt: activatedAt.current }), [motion]);
const previousGroupsRef = useRef<readonly ReaderGroup[]>([]);
const groups = useMemo(() => {
@ -888,6 +1045,58 @@ export function Reader(props: ReaderProps) {
[groups, windowState, renderTurnLimit],
);
const renderedGroups = windowSlice.visible;
const prevTurnQuestionsRef = useRef<Map<string, readonly TurnQuestionEntry[]>>(new Map());
const turnQuestionsByGroup = useMemo(() => {
const next = new Map<string, readonly TurnQuestionEntry[]>();
if (!inlineEnabled) {
prevTurnQuestionsRef.current = next;
return next;
}
const prev = prevTurnQuestionsRef.current;
for (const group of renderedGroups) {
const turn = group.turn === null ? undefined : timeline.turns.get(group.turn);
const list = extractGroupQuestions({
group,
turn,
getNode: key => nodes.get(key),
userQuestions: userQuestionsProjection,
queuedReplies: queuedQuestionReplies,
});
if (list.length === 0) continue;
const existing = prev.get(group.key);
next.set(group.key, sameTurnQuestionEntryList(existing, list) && existing ? existing : list);
}
prevTurnQuestionsRef.current = next;
return next;
}, [inlineEnabled, renderedGroups, timeline, nodes, userQuestionsProjection, queuedQuestionReplies]);
const hostedPendingGroupKey = useMemo(
() => (inlineEnabled && inlineClaimed
? findHostedPendingGroupKey(questionPending, renderedGroups, turnQuestionsByGroup)
: null),
[inlineEnabled, inlineClaimed, questionPending, renderedGroups, turnQuestionsByGroup],
);
const renderedQuestionCallIds = useMemo(() => {
const ids = new Set<string>();
for (const entries of turnQuestionsByGroup.values()) {
for (const entry of entries) ids.add(entry.callId);
}
return ids;
}, [turnQuestionsByGroup]);
const offWindowActiveQuestions = useMemo(
() => (inlineEnabled
? findOffWindowActiveQuestions(
userQuestionsProjection,
queuedQuestionReplies,
renderedQuestionCallIds,
pendingCallIdOf(questionPending),
)
: []),
[inlineEnabled, userQuestionsProjection, queuedQuestionReplies, renderedQuestionCallIds, questionPending],
);
const allGroupKeys = useMemo(() => new Set(groups.map(group => group.key)), [groups]);
const shouldRetire = useCallback((key: string) => !allGroupKeys.has(key), [allGroupKeys]);
@ -1147,6 +1356,48 @@ export function Reader(props: ReaderProps) {
}
}, [lastKey, lastNode?.kind, lastSubmissionId, scroll, windowState.kind, renderTurnLimit, setWindowState]);
const isPendingInEarlierTurn = hostedPendingGroupKey !== null
&& hostedPendingGroupKey !== renderedGroups.at(-1)?.key;
const lastAutoScrolledPendingRef = useRef<string | null>(null);
useLayoutEffect(() => {
if (questionPending === undefined) {
lastAutoScrolledPendingRef.current = null;
return;
}
if (!inlineClaimed) return;
if (lastAutoScrolledPendingRef.current === questionPending.key) return;
lastAutoScrolledPendingRef.current = questionPending.key;
if (isPendingInEarlierTurn) return;
if (windowState.kind === 'range') {
pendingScrollBottomRef.current = true;
setWindowState(initialTurnWindow(renderTurnLimit));
}
scroll.jump();
}, [questionPending?.key, inlineClaimed, isPendingInEarlierTurn, windowState.kind, renderTurnLimit, setWindowState, scroll.jump]);
const handleOpenOffWindowQuestion = useCallback((callId: string) => {
const targetGroup = groups.find(group => {
const turn = group.turn === null ? undefined : timeline.turns.get(group.turn);
return extractGroupQuestions({
group,
turn,
getNode: key => nodes.get(key),
userQuestions: userQuestionsProjection,
queuedReplies: queuedQuestionReplies,
}).some(item => item.callId === callId);
});
if (targetGroup && targetGroup.turn !== null) {
pendingJumpRef.current = {
turn: targetGroup.turn,
seq: null,
expiresAt: Date.now() + 3000,
};
scroll.release();
setWindowState(cur => jumpToTurnInWindow(groups, cur, targetGroup.turn!, renderTurnLimit));
}
props.revealQuestion?.(callId);
}, [groups, timeline, nodes, userQuestionsProjection, queuedQuestionReplies, renderTurnLimit, setWindowState, scroll.release, props.revealQuestion]);
// ChatView publishes data-chat-flow="" on its column. Skins treat a
// scrollport without that hook as inspect-only and hide [data-composer-seat].
// dsh-claude-style 0.19.x also hides the host seat whenever the first tab
@ -1187,7 +1438,7 @@ export function Reader(props: ReaderProps) {
{historyError && <div className={css.notice}>历史记录加载失败,可再次尝试;现有内容未改变。</div>}
{openError && <div className={css.error} role="alert">会话暂时无法读取:{openError.message}</div>}
{loading && groups.length === 0 && <p className={css.empty} role="status">正在读取会话…</p>}
<RetiringTurns groups={renderedGroups} shouldRetire={shouldRetire} onCommitted={flushPendingScrollActions} render={group => <TurnGroup {...props} group={group} motion={motion} autoFold={autoFold} pinnedKeys={pinnedKeys} selectedProcessKeys={selectedProcessKeys} isAwaitingModel={isAwaitingModel && group.key === groups.at(-1)?.key} />} />
<RetiringTurns groups={renderedGroups} shouldRetire={shouldRetire} onCommitted={flushPendingScrollActions} render={group => <TurnGroup {...props} group={group} motion={motion} autoFold={autoFold} pinnedKeys={pinnedKeys} selectedProcessKeys={selectedProcessKeys} isAwaitingModel={isAwaitingModel && group.key === groups.at(-1)?.key} turnQuestions={inlineEnabled ? turnQuestionsByGroup.get(group.key) : undefined} hostedPending={group.key === hostedPendingGroupKey ? questionPending : undefined} inlineClaimed={inlineClaimed} />} />
{windowSlice.hiddenNewer > 0 && (
<div className={css.newerBar} data-reader-newer-bar>
<span className={css.newerBarText}>以下还有 {hiddenNewerTurns} 轮较新对话</span>
@ -1240,13 +1491,51 @@ export function Reader(props: ReaderProps) {
);
})}
{isAwaitingModel && <WaitingStatus anchor={waitAnchor} label={props.t ? props.t('chat.deepDiving') : '深度求索中...'} />}
{pending !== undefined && <div className={css.attention} role="alert" data-reader-attention>
<strong>{pending.kind === 'question' ? '需要你回答一个问题' : '需要你的确认'}</strong>
<span>请在下方原生操作区处理。此提示不会收进执行过程。</span>
</div>}
{(scroll.detached || windowSlice.hiddenNewer > 0) && <div className={css.jumpDock}><button type="button" className={css.jump} aria-label="回到底部" title="回到底部" onClick={jumpToLatest}>
{offWindowActiveQuestions.length > 0 && (
<div className={css.unansweredBanner} data-reader-unanswered-earlier>
<span className={css.unansweredBannerLabel}>
还有 {offWindowActiveQuestions.length} 组更早轮次的未回答问题:
</span>
<div className={css.unansweredBannerList}>
{offWindowActiveQuestions.map(item => (
<button
key={item.callId}
type="button"
className={css.unansweredBannerBtn}
onClick={() => { handleOpenOffWindowQuestion(item.callId); }}
>
去回答:{item.questions[0]?.question ?? '待回答问题'}
</button>
))}
</div>
</div>
)}
{questionPending !== undefined && hostedPendingGroupKey === null && (
<InlineInteraction
sessionId={props.sessionId}
pending={questionPending}
useSession={props.useSession}
renderSlotChain={props.renderSlotChain}
inlineEnabled={inlineEnabled}
inlineClaimed={inlineClaimed}
/>
)}
{(scroll.detached || windowSlice.hiddenNewer > 0) && (
<div className={css.jumpDock}>
<button
type="button"
className={questionPending !== undefined && inlineClaimed && !isPendingInEarlierTurn ? `${css.jump} ${css.jumpPending}` : css.jump}
aria-label={questionPending !== undefined && inlineClaimed && !isPendingInEarlierTurn ? '定位到待回答卡片' : '回到底部'}
title={questionPending !== undefined && inlineClaimed && !isPendingInEarlierTurn ? '定位到待回答卡片' : '回到底部'}
onClick={jumpToLatest}
>
{questionPending !== undefined && inlineClaimed && !isPendingInEarlierTurn && (
<span>待回答</span>
)}
<svg viewBox="0 0 14 14" width="14" height="14" aria-hidden="true"><path d="M3 5.5 7 9.5 11 5.5" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" /></svg>
</button></div>}
</button>
</div>
)}
</div>
</div></ReaderLaneScope></StreamMotionContext.Provider>;
}

View File

@ -21,6 +21,7 @@ import {
} from './chat/bindings.js';
import type { ChatPrefs } from './chat/bindings-store.js';
import { deliverableOpenModeOf, type DeliverableOpenMode } from './open-file.js';
import { inlineInteractionsOf } from './inline-interaction.js';
import { settingsCopyFor, type SettingsCopy, type SettingsCopyKey } from './settings-copy.js';
import {
MAX_RENDER_TURNS,
@ -41,6 +42,7 @@ export interface ReaderPrefsSnapshot {
autoFold?: boolean;
processOnly?: boolean;
renderTurnLimit?: number;
inlineInteractions?: boolean;
}
export interface OpenPrefs {
@ -55,6 +57,7 @@ export interface OpenPrefs {
setFoldIntensity?: (value: FoldIntensity) => void;
setAutoFold?: (value: boolean) => void;
setRenderTurnLimit?: (value: number) => void;
setInlineInteractions?: (value: boolean) => void;
};
}
@ -96,6 +99,7 @@ export function SettingsSection(props: SettingsProps) {
const aiBubbleWidth = aiBubbleWidthOf(snap);
const autoFold = snap.autoFold !== false && snap.foldIntensity !== 0;
const renderTurnLimit = renderTurnLimitOf(snap);
const inlineInteractions = inlineInteractionsOf(snap);
const [turnDraft, setTurnDraft] = useState(() => (renderTurnLimit > 0 ? String(renderTurnLimit) : ''));
useEffect(() => {
setTurnDraft(renderTurnLimit > 0 ? String(renderTurnLimit) : '');
@ -353,6 +357,22 @@ export function SettingsSection(props: SettingsProps) {
</div>
</div>
<div className={css.row}>
<div className={css.rowText}>
<div className={css.title}>{text(props, copy, 'inlineInteractionsTitle')}</div>
<div className={css.desc}>{text(props, copy, 'inlineInteractionsDescription')}</div>
</div>
<button
type="button"
role="switch"
aria-checked={inlineInteractions}
className={css.switch}
data-on={inlineInteractions || undefined}
data-better-display-inline-interactions={inlineInteractions ? 'on' : 'off'}
onClick={() => { props.prefs.actions.setInlineInteractions?.(!inlineInteractions); }}
/>
</div>
{chat ? (
<section className={css.block} data-better-chat-shortcuts>
<div className={css.title}>{text(props, copy, 'shortcutTitle')}</div>

View File

@ -0,0 +1,926 @@
import { memo, useCallback, useEffect, useState } from 'react';
import type { SessionPendingInteraction } from '@deepseek-ai/dsh-client-ui-session/client';
import type { SessionId } from '@deepseek-ai/dsh-session/types';
import { OFFICIAL_SEATS } from './official-slots.js';
import type { ReaderInjected, ReaderProps } from './types.js';
import {
answerDisplayValues,
formatQuestionFollowUpReply,
type QuestionAnswerItem,
type QuestionItem,
type TurnQuestionEntry,
type TurnQuestionStatus,
} from './turn-questions.js';
import css from './Reader.module.css';
interface QuestionDraft {
readonly id: string;
readonly selected: string[];
readonly custom: string;
}
interface PendingQuestionSnapshotView {
readonly state?: string;
readonly channel?: string;
readonly closed?: boolean;
readonly countdown?: {
readonly remainingMs: number;
readonly running: boolean;
};
}
export interface InteractivePendingQuestion {
readonly key: string;
readonly kind: string;
readonly questions?: readonly QuestionItem[];
readonly review?: readonly QuestionAnswerItem[];
answer(payload: { answers: QuestionAnswerItem[] }): Promise<unknown>;
dismiss?(): Promise<unknown>;
snapshot?(): PendingQuestionSnapshotView;
getSnapshot?(): PendingQuestionSnapshotView;
subscribe?(listener: () => void): () => void;
holdFocus?(): void;
releaseFocus?(): void;
engage?(): void;
}
export function asInteractivePending(
pending: SessionPendingInteraction | undefined,
): InteractivePendingQuestion | undefined {
if (!pending || pending.kind !== 'question') return undefined;
const candidate = pending as unknown as Partial<InteractivePendingQuestion>;
if (typeof candidate.answer !== 'function') return undefined;
if (candidate.review !== undefined) return undefined;
return candidate as InteractivePendingQuestion;
}
function buildInitialDrafts(
questions: readonly QuestionItem[],
answers: readonly QuestionAnswerItem[],
): QuestionDraft[] {
const byId = new Map(answers.map(item => [item.id, item]));
return questions.map(question => {
const prev = byId.get(question.id);
return {
id: question.id,
selected: prev ? [...prev.selected] : [],
custom: prev?.custom ?? '',
};
});
}
function statusBadgeLabel(status: TurnQuestionStatus): string {
switch (status) {
case 'open':
return '待回答';
case 'continued':
return '已继续工作 · 仍可回答';
case 'queued':
return '回答已排队 · 等待接收';
case 'answered':
return '已回答';
case 'cancelled':
return '已取消';
case 'interrupted':
return '已中断';
case 'closed':
return '未作答';
}
}
function summaryLineForEntry(entry: TurnQuestionEntry): string {
const first = entry.questions[0];
if (!first) return statusBadgeLabel(entry.status);
const title = first.header && first.header !== first.question ? first.header : first.question;
const firstAnswer = entry.answers.find(item => item.id === first.id);
const values = answerDisplayValues(firstAnswer);
const tail = entry.questions.length > 1 ? ` · 共 ${entry.questions.length} 题` : '';
if (entry.status === 'answered' || entry.status === 'queued') {
const answerText = values.length > 0 ? values.join('、') : '已跳过';
return `${title}:${answerText}${tail}`;
}
return `${title}${tail}`;
}
export const HostedOfficialQuestion = memo(function HostedOfficialQuestion({
callId,
sessionId,
pending,
useSession,
renderSlotChain,
}: {
callId: string;
sessionId: SessionId;
pending: SessionPendingInteraction;
useSession: ReaderProps['useSession'];
renderSlotChain: ReaderProps['renderSlotChain'];
}) {
const session = useSession(snapshot => snapshot);
const fallback = (
<div className={css.attention} role="alert" data-reader-attention>
<strong>需要你回答一个问题</strong>
<span>请在下方原生操作区处理。此提示不会收进执行过程。</span>
</div>
);
return (
<div
className={css.inlineInteraction}
data-reader-inline-interaction
data-reader-question-call={callId}
data-reader-anchor
>
{renderSlotChain(OFFICIAL_SEATS.composer, {
sessionId,
session,
pendingInteraction: pending,
}, { fallback })}
</div>
);
});
/**
* Native Muse-style flat-in-bubble UI for live pending `ask_user_question` interactions.
* Single-question single-select options render as full-width dashed buttons that
* submit on one click directly inside the AI reply bubble.
*/
export const MuseLiveQuestion = memo(function MuseLiveQuestion({
callId,
pending,
fallbackQuestions,
}: {
callId: string;
pending: InteractivePendingQuestion;
fallbackQuestions?: readonly QuestionItem[];
}) {
const questions = (pending.questions && pending.questions.length > 0)
? pending.questions
: (fallbackQuestions ?? []);
const [step, setStep] = useState(0);
const [drafts, setDrafts] = useState<QuestionDraft[]>(() => buildInitialDrafts(questions, []));
const [customOpen, setCustomOpen] = useState(false);
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const [snapshot, setSnapshot] = useState<PendingQuestionSnapshotView>(
() => pending.snapshot?.() ?? pending.getSnapshot?.() ?? {},
);
useEffect(() => {
const sync = () => {
setSnapshot(pending.snapshot?.() ?? pending.getSnapshot?.() ?? {});
};
sync();
return pending.subscribe?.(sync);
}, [pending]);
useEffect(() => {
setDrafts(current => {
if (
current.length === questions.length
&& current.every((item, idx) => item.id === questions[idx]?.id)
) {
return current;
}
return buildInitialDrafts(questions, []);
});
setStep(current => (questions.length > 0 ? Math.min(current, questions.length - 1) : 0));
}, [questions]);
useEffect(() => () => {
pending.releaseFocus?.();
}, [pending]);
const submitPayload = useCallback(async (answers: QuestionAnswerItem[]) => {
if (submitting) return;
setSubmitting(true);
setError(null);
try {
const channel = (pending.snapshot?.() ?? pending.getSnapshot?.())?.channel;
await pending.answer({ answers });
if (channel === 'rpc') {
await pending.dismiss?.();
}
} catch (cause) {
setError(cause instanceof Error ? cause.message : '提交回答失败,请重试。');
} finally {
setSubmitting(false);
}
}, [submitting, pending]);
const activeIndex = Math.min(step, Math.max(0, questions.length - 1));
const currentQuestion = questions[activeIndex];
if (!currentQuestion) return null;
const isSingleQuickPick = questions.length === 1
&& currentQuestion.multiSelect !== true
&& (currentQuestion.options?.length ?? 0) > 0;
const draft = drafts[activeIndex] ?? { id: currentQuestion.id, selected: [], custom: '' };
const channelReady = snapshot.channel !== 'none';
const remainingSec = snapshot.countdown?.running
? Math.ceil(snapshot.countdown.remainingMs / 1000)
: undefined;
const handleOptionClick = (label: string) => {
if (submitting || !channelReady) return;
pending.engage?.();
setError(null);
if (isSingleQuickPick && !customOpen) {
void submitPayload([{ id: currentQuestion.id, selected: [label] }]);
return;
}
const multi = currentQuestion.multiSelect === true;
const nextDrafts = drafts.map((item, idx) => {
if (idx !== activeIndex) return item;
if (multi) {
const exists = item.selected.includes(label);
return {
...item,
selected: exists ? item.selected.filter(x => x !== label) : [...item.selected, label],
};
}
const already = item.selected.length === 1 && item.selected[0] === label;
return { ...item, selected: already ? [] : [label], custom: '' };
});
setDrafts(nextDrafts);
if (!multi && activeIndex < questions.length - 1) {
setStep(activeIndex + 1);
}
};
const handleSubmitDrafts = () => {
const answers: QuestionAnswerItem[] = questions.map((item, idx) => {
const value = drafts[idx] ?? { id: item.id, selected: [], custom: '' };
const custom = value.custom.trim();
return {
id: item.id,
selected: custom === '' || item.multiSelect === true ? [...value.selected] : [],
...(custom !== '' ? { custom } : {}),
};
});
const missingIndex = answers.findIndex(
item => item.selected.length === 0 && (item.custom?.length ?? 0) === 0,
);
if (missingIndex >= 0) {
setStep(missingIndex);
setError('请先选择选项或输入自定义回答。');
return;
}
void submitPayload(answers);
};
const showSubmitBar = !isSingleQuickPick || customOpen;
return (
<div
className={css.museQuestionBlock}
data-reader-inline-interaction
data-reader-turn-question={callId}
data-question-status="open"
data-reader-anchor
onMouseEnter={() => { pending.holdFocus?.(); }}
onMouseLeave={() => { pending.releaseFocus?.(); }}
onFocusCapture={() => { pending.holdFocus?.(); }}
onBlurCapture={event => {
if (!event.currentTarget.contains(event.relatedTarget)) {
pending.releaseFocus?.();
}
}}
>
{questions.length > 1 && (
<div className={css.questionStepTabs} role="tablist" aria-label="问题列表">
{questions.map((item, idx) => {
const done = (drafts[idx]?.selected.length ?? 0) > 0
|| (drafts[idx]?.custom.trim().length ?? 0) > 0;
return (
<button
key={item.id}
type="button"
role="tab"
aria-selected={idx === activeIndex}
className={css.questionStepTab}
data-active={idx === activeIndex || undefined}
data-done={done || undefined}
onClick={() => { setStep(idx); setError(null); }}
>
{`${idx + 1}. ${item.header ?? `问题 ${idx + 1}`}`}
</button>
);
})}
</div>
)}
<div className={css.questionPromptText}>
{currentQuestion.header && currentQuestion.header !== currentQuestion.question && questions.length === 1 && (
<span className={css.questionHeaderChip}>{currentQuestion.header}</span>
)}
<span>{currentQuestion.question}</span>
{currentQuestion.multiSelect === true && <span className={css.questionMultiHint}>多选</span>}
{remainingSec !== undefined && (
<span className={css.questionMultiHint}>{`${remainingSec}s`}</span>
)}
</div>
{currentQuestion.options && currentQuestion.options.length > 0 && (
<div className={css.questionOptionGrid}>
{currentQuestion.options.map(option => {
const selected = draft.selected.includes(option.label);
return (
<button
key={option.label}
type="button"
className={css.questionOptionBtn}
disabled={submitting || !channelReady}
data-selected={selected || undefined}
aria-pressed={selected}
onClick={() => { handleOptionClick(option.label); }}
>
<span className={css.questionOptionRowHead}>
<span className={css.questionOptionLabel}>{option.label}</span>
{selected && <span className={css.questionOptionCheck} aria-hidden="true">✓</span>}
</span>
{option.description && (
<span className={css.questionOptionDesc}>{option.description}</span>
)}
</button>
);
})}
</div>
)}
{(customOpen || (currentQuestion.options?.length ?? 0) === 0) && (
<input
type="text"
className={css.questionCustomInput}
placeholder="输入你的回答…"
value={draft.custom}
disabled={submitting || !channelReady}
onChange={event => {
pending.engage?.();
setError(null);
const value = event.target.value;
setDrafts(current => current.map((item, idx) => (
idx === activeIndex
? { ...item, custom: value, selected: currentQuestion.multiSelect ? item.selected : [] }
: item
)));
}}
onKeyDown={event => {
if (event.key === 'Enter' && (!isSingleQuickPick || event.ctrlKey || event.metaKey || valueOrSubmitReady(draft))) {
if (!currentQuestion.multiSelect && questions.length === 1 && draft.custom.trim()) {
event.preventDefault();
handleSubmitDrafts();
}
}
}}
/>
)}
{error && <p className={css.questionFormError} role="alert">{error}</p>}
<div className={css.questionInlineFoot}>
<div className={css.questionInlineLinks}>
{(currentQuestion.options?.length ?? 0) > 0 && (
<button
type="button"
className={css.questionGhostBtn}
disabled={submitting}
onClick={() => { setCustomOpen(v => !v); }}
>
{customOpen ? '收起输入' : '+ 自定义回答'}
</button>
)}
<button
type="button"
className={css.questionGhostBtn}
disabled={submitting || !channelReady}
onClick={() => {
void submitPayload(questions.map(item => ({ id: item.id, selected: [] })));
}}
>
跳过
</button>
</div>
{showSubmitBar && (
<div className={css.questionCardActions}>
{activeIndex > 0 && (
<button
type="button"
className={css.questionActionBtn}
disabled={submitting}
onClick={() => { setStep(activeIndex - 1); }}
>
上一题
</button>
)}
{activeIndex < questions.length - 1 ? (
<button
type="button"
className={`${css.questionActionBtn} ${css.questionActionPrimary}`}
disabled={submitting}
onClick={() => { setStep(activeIndex + 1); }}
>
下一题
</button>
) : (
<button
type="button"
className={`${css.questionActionBtn} ${css.questionActionPrimary}`}
disabled={submitting || !channelReady}
onClick={handleSubmitDrafts}
>
{submitting ? '正在提交…' : '提交回答'}
</button>
)}
</div>
)}
</div>
</div>
);
});
function valueOrSubmitReady(draft: QuestionDraft): boolean {
return draft.selected.length > 0 || draft.custom.trim().length > 0;
}
export interface TurnQuestionCardProps {
entry: TurnQuestionEntry;
sessionId: SessionId;
pending: SessionPendingInteraction | undefined;
inlineClaimed: boolean;
useSession: ReaderProps['useSession'];
renderSlotChain: ReaderProps['renderSlotChain'];
revealQuestion?: ReaderInjected['revealQuestion'];
reviewQuestion?: ReaderInjected['reviewQuestion'];
answerContinuedQuestion?: ReaderInjected['answerContinuedQuestion'];
sendFollowUp?: ReaderInjected['sendFollowUp'];
fillComposer?: ReaderInjected['fillComposer'];
}
export const TurnQuestionCard = memo(function TurnQuestionCard({
entry,
sessionId,
pending,
inlineClaimed,
useSession,
renderSlotChain,
revealQuestion,
reviewQuestion,
answerContinuedQuestion,
sendFollowUp,
fillComposer,
}: TurnQuestionCardProps) {
const [formOpen, setFormOpen] = useState(false);
const [customOpen, setCustomOpen] = useState(false);
const [detailsOpen, setDetailsOpen] = useState(false);
const [drafts, setDrafts] = useState<QuestionDraft[]>(() =>
buildInitialDrafts(entry.questions, entry.answers),
);
const [submitting, setSubmitting] = useState(false);
const [formError, setFormError] = useState<string | null>(null);
useEffect(() => {
if (entry.status === 'queued' || entry.status === 'answered') {
setFormOpen(false);
setCustomOpen(false);
setFormError(null);
}
}, [entry.status]);
const openForm = useCallback(() => {
setDrafts(buildInitialDrafts(entry.questions, entry.answers));
setFormError(null);
setDetailsOpen(false);
setFormOpen(true);
}, [entry.questions, entry.answers]);
const submitPayload = useCallback(async (payload: QuestionAnswerItem[]) => {
if (submitting) return;
setSubmitting(true);
setFormError(null);
try {
if (entry.status === 'continued' && answerContinuedQuestion) {
const accepted = await answerContinuedQuestion(entry.callId, payload);
if (accepted) {
setFormOpen(false);
setCustomOpen(false);
return;
}
}
const mode = entry.status === 'answered' ? 'revise' : 'answer';
const text = formatQuestionFollowUpReply(entry.questions, payload, mode);
if (sendFollowUp && await sendFollowUp(text)) {
setFormOpen(false);
setCustomOpen(false);
return;
}
if (fillComposer?.(text)) {
setFormOpen(false);
setCustomOpen(false);
return;
}
setFormError('暂时无法提交回答,请稍后再试。');
} catch {
setFormError('暂时无法提交回答,请稍后再试。');
} finally {
setSubmitting(false);
}
}, [submitting, entry.status, entry.callId, entry.questions, answerContinuedQuestion, sendFollowUp, fillComposer]);
const toggleOption = useCallback((
question: QuestionItem,
label: string,
quickSubmitSingle: boolean,
) => {
if (submitting) return;
setFormError(null);
if (quickSubmitSingle && !customOpen) {
void submitPayload([{ id: question.id, selected: [label] }]);
return;
}
const multi = question.multiSelect === true;
setDrafts(current => current.map(draft => {
if (draft.id !== question.id) return draft;
if (multi) {
const exists = draft.selected.includes(label);
return {
...draft,
selected: exists
? draft.selected.filter(item => item !== label)
: [...draft.selected, label],
};
}
const alreadyOnly = draft.selected.length === 1 && draft.selected[0] === label;
return {
...draft,
selected: alreadyOnly ? [] : [label],
};
}));
}, [submitting, customOpen, submitPayload]);
const updateCustom = useCallback((questionId: string, custom: string) => {
setFormError(null);
setDrafts(current => current.map(draft => (
draft.id === questionId ? { ...draft, custom } : draft
)));
}, []);
const buildPayload = useCallback((): QuestionAnswerItem[] | null => {
const items: QuestionAnswerItem[] = drafts.map(draft => {
const custom = draft.custom.trim();
return {
id: draft.id,
selected: [...draft.selected],
...(custom.length > 0 ? { custom } : {}),
};
});
const hasAny = items.some(item => item.selected.length > 0 || (item.custom?.length ?? 0) > 0);
if (!hasAny) {
setFormError('请至少选择一个选项或填写自定义回答。');
return null;
}
return items;
}, [drafts]);
const followUpMode = entry.status === 'answered' ? 'revise' : 'answer';
const handleFillComposer = useCallback(() => {
const payload = buildPayload();
if (!payload) return;
const text = formatQuestionFollowUpReply(entry.questions, payload, followUpMode);
if (fillComposer?.(text)) {
setFormOpen(false);
} else {
setFormError('未能写入底部输入框,请稍后重试。');
}
}, [buildPayload, entry.questions, followUpMode, fillComposer]);
const handleSubmit = useCallback(async () => {
const payload = buildPayload();
if (!payload) return;
await submitPayload(payload);
}, [buildPayload, submitPayload]);
// 1. Active pending interaction: prefer native Muse bubble layout; fall back to slot host if needed.
if (pending !== undefined && inlineClaimed) {
const interactive = asInteractivePending(pending);
if (interactive) {
return (
<MuseLiveQuestion
callId={entry.callId}
pending={interactive}
fallbackQuestions={entry.questions}
/>
);
}
return (
<HostedOfficialQuestion
callId={entry.callId}
sessionId={sessionId}
pending={pending}
useSession={useSession}
renderSlotChain={renderSlotChain}
/>
);
}
const isActive = entry.status === 'open' || entry.status === 'continued';
const isQueued = entry.status === 'queued';
const answersById = new Map(entry.answers.map(item => [item.id, item]));
const isQuickSingleActive = isActive
&& entry.questions.length === 1
&& entry.questions[0]?.multiSelect !== true
&& (entry.questions[0]?.options?.length ?? 0) > 0;
// 2. Active/continued unanswered question inside the bubble: show Muse dashed options directly!
if (isActive && entry.questions.length > 0) {
const useFormDraft = !isQuickSingleActive || customOpen;
return (
<div
className={css.museQuestionBlock}
data-reader-turn-question={entry.callId}
data-question-status={entry.status}
data-reader-anchor
>
{entry.questions.map(question => {
const draft = drafts.find(item => item.id === question.id) ?? {
id: question.id,
selected: [],
custom: '',
};
const multi = question.multiSelect === true;
return (
<div key={question.id} className={css.questionFormBlock}>
<div className={css.questionPromptText}>
{question.header && question.header !== question.question && (
<span className={css.questionHeaderChip}>{question.header}</span>
)}
<span>{question.question}</span>
{multi && <span className={css.questionMultiHint}>多选</span>}
<span className={css.questionStatusBadge}>{statusBadgeLabel(entry.status)}</span>
</div>
{question.options && question.options.length > 0 && (
<div className={css.questionOptionGrid}>
{question.options.map(option => {
const selected = useFormDraft && draft.selected.includes(option.label);
return (
<button
key={option.label}
type="button"
className={css.questionOptionBtn}
disabled={submitting}
data-selected={selected || undefined}
aria-pressed={selected}
onClick={() => {
if (!useFormDraft && revealQuestion?.(entry.callId)) return;
toggleOption(question, option.label, isQuickSingleActive);
}}
>
<span className={css.questionOptionRowHead}>
<span className={css.questionOptionLabel}>{option.label}</span>
{selected && <span className={css.questionOptionCheck} aria-hidden="true">✓</span>}
</span>
{option.description && (
<span className={css.questionOptionDesc}>{option.description}</span>
)}
</button>
);
})}
</div>
)}
{(customOpen || (question.options?.length ?? 0) === 0) && (
<input
type="text"
className={css.questionCustomInput}
placeholder="自定义回答或补充说明…"
value={draft.custom}
disabled={submitting}
onChange={event => { updateCustom(question.id, event.target.value); }}
onKeyDown={event => {
if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) {
event.preventDefault();
void handleSubmit();
}
}}
/>
)}
</div>
);
})}
{formError && <p className={css.questionFormError} role="alert">{formError}</p>}
<div className={css.questionInlineFoot}>
<div className={css.questionInlineLinks}>
<button
type="button"
className={css.questionGhostBtn}
disabled={submitting}
onClick={() => { setCustomOpen(value => !value); }}
>
{customOpen ? '收起输入' : '+ 自定义回答'}
</button>
</div>
{useFormDraft && (
<div className={css.questionCardActions}>
<button
type="button"
className={css.questionActionBtn}
disabled={submitting}
onClick={handleFillComposer}
>
填入输入框
</button>
<button
type="button"
className={`${css.questionActionBtn} ${css.questionActionPrimary}`}
disabled={submitting}
onClick={() => { void handleSubmit(); }}
>
{submitting ? '正在发送…' : '提交回答'}
</button>
</div>
)}
</div>
</div>
);
}
// 3. Settled/queued/cancelled/interrupted historical question inside the bubble.
return (
<div
className={css.questionCard}
data-reader-turn-question={entry.callId}
data-question-status={entry.status}
>
<div className={css.questionCardHeader}>
{entry.questions.length > 0 && !isQueued ? (
<button
type="button"
className={css.questionSummaryBtn}
aria-expanded={detailsOpen}
onClick={() => { setDetailsOpen(value => !value); }}
title={detailsOpen ? '收起问题详情' : '展开查看全部问题与回答'}
>
<span className={css.questionStatusBadge}>{statusBadgeLabel(entry.status)}</span>
<span className={css.questionSummaryText}>{summaryLineForEntry(entry)}</span>
</button>
) : (
<div className={css.questionSummaryStatic}>
<span className={css.questionStatusBadge}>{statusBadgeLabel(entry.status)}</span>
<span className={css.questionSummaryText}>{summaryLineForEntry(entry)}</span>
</div>
)}
<div className={css.questionCardActions}>
{!isQueued && entry.reviewRecord !== undefined && reviewQuestion !== undefined && (
<button
type="button"
className={css.questionGhostBtn}
onClick={() => {
setFormOpen(false);
reviewQuestion(entry.callId, entry.reviewRecord!);
}}
>
查看原卡
</button>
)}
{!isQueued && entry.questions.length > 0 && (
<button
type="button"
className={css.questionGhostBtn}
data-reader-question-reanswer
aria-expanded={formOpen}
onClick={() => {
if (formOpen) setFormOpen(false);
else openForm();
}}
>
{formOpen ? '收起' : entry.status === 'answered' ? '重新回答' : '补充回答'}
</button>
)}
</div>
</div>
{!formOpen && (detailsOpen || isQueued) && entry.questions.length > 0 && (
<dl className={css.questionHistoryList}>
{entry.questions.map(question => {
const values = answerDisplayValues(answersById.get(question.id));
return (
<div key={question.id} className={css.questionHistoryItem}>
<dt className={css.questionHistoryPrompt}>
{question.header && question.header !== question.question && (
<span className={css.questionHeaderChip}>{question.header}</span>
)}
<span>{question.question}</span>
</dt>
<dd className={css.questionHistoryAnswer}>
{values.length > 0
? values.join(' · ')
: question.options && question.options.length > 0
? `可选项:${question.options.map(opt => opt.label).join(' / ')}`
: '(未填写)'}
</dd>
</div>
);
})}
</dl>
)}
{formOpen && (
<div className={css.questionReanswerForm} data-reader-question-form>
{entry.questions.map(question => {
const draft = drafts.find(item => item.id === question.id) ?? {
id: question.id,
selected: [],
custom: '',
};
const multi = question.multiSelect === true;
return (
<div key={question.id} className={css.questionFormBlock}>
<div className={css.questionFormPrompt}>
{question.header && question.header !== question.question && (
<span className={css.questionHeaderChip}>{question.header}</span>
)}
<span>{question.question}</span>
{multi && <span className={css.questionMultiHint}>多选</span>}
</div>
{question.options && question.options.length > 0 && (
<div className={css.questionOptionGrid}>
{question.options.map(option => {
const selected = draft.selected.includes(option.label);
return (
<button
key={option.label}
type="button"
className={css.questionOptionBtn}
data-selected={selected || undefined}
aria-pressed={selected}
onClick={() => { toggleOption(question, option.label, false); }}
>
<span className={css.questionOptionRowHead}>
<span className={css.questionOptionLabel}>{option.label}</span>
{selected && <span className={css.questionOptionCheck} aria-hidden="true">✓</span>}
</span>
{option.description && (
<span className={css.questionOptionDesc}>{option.description}</span>
)}
</button>
);
})}
</div>
)}
<input
type="text"
className={css.questionCustomInput}
placeholder="自定义回答或补充说明…"
value={draft.custom}
disabled={submitting}
onChange={event => { updateCustom(question.id, event.target.value); }}
onKeyDown={event => {
if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) {
event.preventDefault();
void handleSubmit();
}
}}
/>
</div>
);
})}
{formError && <p className={css.questionFormError} role="alert">{formError}</p>}
<div className={css.questionFormFooter}>
<button
type="button"
className={css.questionActionBtn}
disabled={submitting}
onClick={() => { setFormOpen(false); }}
>
取消
</button>
<button
type="button"
className={css.questionActionBtn}
disabled={submitting}
onClick={handleFillComposer}
>
填入输入框
</button>
<button
type="button"
className={`${css.questionActionBtn} ${css.questionActionPrimary}`}
disabled={submitting}
onClick={() => { void handleSubmit(); }}
>
{submitting ? '正在发送…' : entry.status === 'answered' ? '发送新回答' : '提交回答'}
</button>
</div>
</div>
)}
</div>
);
});

View File

@ -105,3 +105,57 @@ export function containsNewUser(before: readonly LiveTurnItem[], after: readonly
const users = new Set(before.filter(item => item.kind === 'user').map(item => item.key));
return after.some(item => item.kind === 'user' && !users.has(item.key));
}
export type QuestionMatchableRow = {
readonly row: FlowRow;
};
function waveContainsCallId(wave: FlowWave<QuestionMatchableRow>, callId: string): boolean {
for (const cell of [...wave.process, ...wave.other]) {
if (cell.row.kind === 'step') {
if (cell.row.step.kind === 'tool' && cell.row.step.entry.callId === callId) return true;
} else if (cell.row.item.steps.some(step => step.kind === 'tool' && step.entry.callId === callId)) {
return true;
}
}
return false;
}
/**
* Place each turn question option card inside the AI answer bubble of the wave
* that issued it (before the process fold), falling back to the last non-user
* wave or `tailOnly` when no assistant wave exists yet.
*/
export function distributeBubbleQuestions<
Row extends QuestionMatchableRow,
Item extends { readonly callId: string },
>(
waves: readonly FlowWave<Row>[],
items: readonly Item[],
): { byWaveKey: Map<string, Item[]>; tailOnly: Item[] } {
const byWaveKey = new Map<string, Item[]>();
const tailOnly: Item[] = [];
if (items.length === 0) return { byWaveKey, tailOnly };
let lastAssistantWaveKey: string | undefined;
for (let i = waves.length - 1; i >= 0; i -= 1) {
const wave = waves[i]!;
if (!wave.user) {
lastAssistantWaveKey = wave.key;
break;
}
}
for (const item of items) {
const owner = waves.find(wave => !wave.user && waveContainsCallId(wave, item.callId));
const targetKey = owner?.key ?? lastAssistantWaveKey;
if (targetKey === undefined) {
tailOnly.push(item);
continue;
}
const list = byWaveKey.get(targetKey) ?? [];
list.push(item);
byWaveKey.set(targetKey, list);
}
return { byWaveKey, tailOnly };
}

View File

@ -0,0 +1,286 @@
import type { Context } from '@deepseek-ai/cordis';
import type { ComposerChainProps } from '@deepseek-ai/dsh-client-ui-conversation/client';
import type { SessionPendingInteraction } from '@deepseek-ai/dsh-client-ui-session/client';
import type { SessionId } from '@deepseek-ai/dsh-session/types';
import {
INLINE_COMPOSER_INTERCEPTOR_PRIORITY,
INLINE_COMPOSER_INTERCEPTOR_REGISTRANT,
OFFICIAL_SEATS,
OFFICIAL_SLOTS,
acceptMirroredComposerEntry,
type CompositionRegistry,
} from './official-slots.js';
export const INLINE_INTERACTIONS_DEFAULT = true;
export function inlineInteractionsOf(snap?: { inlineInteractions?: boolean }): boolean {
return snap?.inlineInteractions !== false;
}
/**
* Only non-blocking user-question option cards move inside the message bubble.
* Tool approvals, CUA prompts, and plan-review confirmations must keep popping up
* live above the bottom composer so ongoing work is never blocked out of sight.
*/
export function isInlineQuestionPending(
pending: SessionPendingInteraction | undefined,
): pending is SessionPendingInteraction {
return pending !== undefined && pending.kind === 'question';
}
export interface InlineInteractionController {
acquire(sessionId: SessionId, token: symbol): () => void;
isClaimed(sessionId: SessionId, token: symbol): boolean;
setEnabled(next: boolean): void;
isEnabled(): boolean;
subscribe(listener: () => void): () => void;
getVersion(): number;
dispose(): void;
}
/**
* Interceptor component registered on `conversation.composer`.
* Returns `null` while `ConversationRoot` (`overlay: true`) keeps the resident
* composer bar hidden and preserves its draft state.
*/
export function InlineComposerInterceptor() {
return null;
}
type ComposerSelectFn = (owner: ComposerChainProps) => unknown;
export function createInlineInteractionController(
slots: CompositionRegistry,
options?: { initialEnabled?: boolean },
): InlineInteractionController {
let enabled = options?.initialEnabled ?? INLINE_INTERACTIONS_DEFAULT;
let disposed = false;
let composerDeclared = false;
const mounts = new Map<SessionId, symbol[]>();
const claimed = new Map<SessionId, symbol>();
let interceptorDispose: (() => void) | null = null;
const listeners = new Set<() => void>();
let version = 0;
let handoffSeq = 0;
const emit = () => {
version += 1;
for (const listener of [...listeners]) {
try {
listener();
} catch (error) {
console.error('[dsh-better-chat] inline-interaction listener failed:', error);
}
}
};
const hasMirroredComposerMatch = (owner: ComposerChainProps): boolean => {
if (slots.spec(OFFICIAL_SEATS.composer) === undefined) return false;
for (const entry of slots.entriesOfSlot(OFFICIAL_SLOTS.composer)) {
if (!acceptMirroredComposerEntry(entry)) continue;
const select = entry.select as ComposerSelectFn | undefined;
if (typeof select !== 'function') continue;
try {
if (select(owner) !== null) return true;
} catch {
// Declining a throwing official selector mirrors SlotOutlet chain semantics.
}
}
return false;
};
const disposeInterceptor = () => {
if (interceptorDispose === null) return;
const stop = interceptorDispose;
interceptorDispose = null;
stop();
};
const refreshInterceptor = () => {
disposeInterceptor();
if (disposed || !enabled || !composerDeclared || mounts.size === 0) return;
interceptorDispose = slots.register({
name: OFFICIAL_SLOTS.composer,
priority: INLINE_COMPOSER_INTERCEPTOR_PRIORITY,
registrant: INLINE_COMPOSER_INTERCEPTOR_REGISTRANT,
select: (owner: ComposerChainProps) => {
if (disposed || !enabled || owner.sessionId === undefined || !isInlineQuestionPending(owner.pendingInteraction)) {
return null;
}
if (!mounts.has(owner.sessionId)) return null;
return hasMirroredComposerMatch(owner)
? { pendingInteraction: owner.pendingInteraction }
: null;
},
}, InlineComposerInterceptor);
};
const syncAllClaims = () => {
if (disposed || !enabled || !composerDeclared) return;
let changed = false;
for (const [sessionId, tokens] of mounts) {
const primary = tokens[0];
if (primary !== undefined && claimed.get(sessionId) !== primary) {
claimed.set(sessionId, primary);
changed = true;
}
}
for (const sessionId of [...claimed.keys()]) {
if (!mounts.has(sessionId)) {
claimed.delete(sessionId);
changed = true;
}
}
if (changed) emit();
};
const scheduleDoubleMicrotask = (fn: () => void) => {
const seq = ++handoffSeq;
queueMicrotask(() => {
if (disposed || seq !== handoffSeq) return;
queueMicrotask(() => {
if (disposed || seq !== handoffSeq) return;
fn();
});
});
};
const injectDispose = slots.inject(OFFICIAL_SLOTS.composer, () => {
composerDeclared = true;
if (enabled && mounts.size > 0) {
refreshInterceptor();
scheduleDoubleMicrotask(syncAllClaims);
}
return () => {
composerDeclared = false;
handoffSeq += 1;
const hadClaims = claimed.size > 0;
claimed.clear();
disposeInterceptor();
if (hadClaims) emit();
};
});
return {
acquire(sessionId: SessionId, token: symbol): () => void {
if (disposed) return () => {};
let tokens = mounts.get(sessionId);
if (!tokens) {
tokens = [];
mounts.set(sessionId, tokens);
}
if (!tokens.includes(token)) {
tokens.push(token);
}
if (enabled && composerDeclared) {
const primary = tokens[0];
if (primary !== undefined && claimed.get(sessionId) !== primary) {
refreshInterceptor();
scheduleDoubleMicrotask(syncAllClaims);
}
}
let released = false;
return () => {
if (released) return;
released = true;
const current = mounts.get(sessionId);
if (current) {
const index = current.indexOf(token);
if (index !== -1) current.splice(index, 1);
if (current.length === 0) mounts.delete(sessionId);
}
const wasClaimed = claimed.get(sessionId) === token;
if (wasClaimed) {
claimed.delete(sessionId);
emit();
}
if (disposed) return;
const remaining = mounts.get(sessionId);
if (enabled && composerDeclared && remaining && remaining.length > 0) {
const nextPrimary = remaining[0];
if (nextPrimary !== undefined && (wasClaimed || claimed.get(sessionId) !== nextPrimary)) {
refreshInterceptor();
scheduleDoubleMicrotask(syncAllClaims);
}
} else if (composerDeclared) {
refreshInterceptor();
}
};
},
isClaimed(sessionId: SessionId, token: symbol): boolean {
if (disposed || !enabled || !composerDeclared) return false;
return claimed.get(sessionId) === token;
},
setEnabled(next: boolean): void {
const normalized = Boolean(next);
if (disposed || normalized === enabled) return;
enabled = normalized;
if (!normalized) {
const hadClaims = claimed.size > 0;
claimed.clear();
if (hadClaims) emit();
scheduleDoubleMicrotask(() => {
if (!enabled) refreshInterceptor();
});
} else {
if (composerDeclared && mounts.size > 0) {
refreshInterceptor();
scheduleDoubleMicrotask(syncAllClaims);
}
}
},
isEnabled(): boolean {
return enabled;
},
subscribe(listener: () => void): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
},
getVersion(): number {
return version;
},
dispose(): void {
if (disposed) return;
disposed = true;
handoffSeq += 1;
const hadClaims = claimed.size > 0;
claimed.clear();
mounts.clear();
disposeInterceptor();
injectDispose();
if (hadClaims) emit();
listeners.clear();
},
};
}
export function installInlineInteractions(
ctx: Context,
prefs: { getSnapshot: () => { inlineInteractions?: boolean } | undefined; subscribe: (fn: () => void) => () => void },
): { controller: InlineInteractionController; dispose: () => void } {
const slots = ctx.slots as unknown as CompositionRegistry;
const controller = createInlineInteractionController(slots, {
initialEnabled: inlineInteractionsOf(prefs.getSnapshot()),
});
const unsubPrefs = prefs.subscribe(() => {
controller.setEnabled(inlineInteractionsOf(prefs.getSnapshot()));
});
let stopped = false;
return {
controller,
dispose: () => {
if (stopped) return;
stopped = true;
unsubPrefs();
controller.dispose();
},
};
}

View File

@ -462,7 +462,7 @@ export function useReadingScroll(root: RefObject<HTMLElement>, motion: boolean):
if (!bottom) { following.current = false; setDetached(true); }
};
const fromProcess = (event: Event) => event.target instanceof Element
&& event.target.closest('[data-reader-process-scroll]');
&& event.target.closest('[data-reader-process-scroll], [data-approval-scroll]');
const onWheel = (event: WheelEvent) => {
if (fromProcess(event)) return;
cancelAnimationFrame(followFrame); followFrame = 0; lastWrittenTop = null;

View File

@ -1,6 +1,7 @@
import { createElement, memo, useEffect, useLayoutEffect, useMemo, useRef, type ComponentType, type ReactNode, type RefObject } from 'react';
import type { Context } from '@deepseek-ai/cordis';
import type { UseGroupAction } from '@deepseek-ai/dsh-client-ui-chat/client';
import type {} from '@deepseek-ai/dsh-client-ui-conversation/client';
import type { SlotEntryDef, SlotMap, SlotSpec, StoredEntry } from '@deepseek-ai/dsh-client-ui-slots';
import type {} from '@deepseek-ai/dsh-client-ui-renderer/client';
@ -21,6 +22,7 @@ export const OFFICIAL_SLOTS = {
nodes: 'conversation.chat.node',
messageImages: 'conversation.chat.message.images',
userImages: 'conversation.chat.user.images',
composer: 'conversation.composer',
} as const;
export type OfficialFamily = keyof typeof OFFICIAL_SLOTS;
export const OFFICIAL_SEATS = {
@ -30,6 +32,7 @@ export const OFFICIAL_SEATS = {
nodes: 'dsh-better-display.official.nodes/conversation.chat.node',
messageImages: 'dsh-better-display.official.messageImages/conversation.chat.message.images',
userImages: 'dsh-better-display.official.userImages/conversation.chat.user.images',
composer: 'dsh-better-display.official.composer/conversation.composer',
} as const;
export type OfficialSeat = typeof OFFICIAL_SEATS[OfficialFamily];
export const officialSeat = (family: OfficialFamily, source: string = OFFICIAL_SLOTS[family]) =>
@ -57,6 +60,7 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
'dsh-better-display.official.nodes/conversation.chat.node': SlotMap['conversation.chat.node'];
'dsh-better-display.official.messageImages/conversation.chat.message.images': SlotMap['conversation.chat.message.images'];
'dsh-better-display.official.userImages/conversation.chat.user.images': SlotMap['conversation.chat.user.images'];
'dsh-better-display.official.composer/conversation.composer': SlotMap['conversation.composer'];
}
}
@ -110,6 +114,23 @@ export function acceptMirroredChatNode(entry: StoredEntry): boolean {
if (key === 'assistant-step') return (entry.options.priority ?? OFFICIAL_ASSISTANT_PRIORITY) < OFFICIAL_ASSISTANT_PRIORITY;
return !READER_OWNED_NODES.has(key);
}
/**
* Priority & registrant used by our inline-interaction interceptor on `conversation.composer`.
* Read-only subagent banners register at `-10`; CUA/questions/approval cards register at `-1`/`0`/`1`.
*/
export const INLINE_COMPOSER_INTERCEPTOR_PRIORITY = -5;
export const INLINE_COMPOSER_INTERCEPTOR_REGISTRANT = 'dsh-better-display:inline-interaction-interceptor';
/**
* Mirror `conversation.composer` interaction cards into Reader while excluding
* our own bottom-dock interceptor and host-level read-only subagent banners (`priority <= -5`).
*/
export function acceptMirroredComposerEntry(entry: StoredEntry): boolean {
if (entry.registrant === INLINE_COMPOSER_INTERCEPTOR_REGISTRANT) return false;
return (entry.options.priority ?? 0) > INLINE_COMPOSER_INTERCEPTOR_PRIORITY;
}
const EXPECTED: Record<OfficialFamily, Spec> = {
actions: { kind: 'list', scope: 'session' },
tools: { kind: 'keyed', scope: 'session' },
@ -117,6 +138,7 @@ const EXPECTED: Record<OfficialFamily, Spec> = {
nodes: { kind: 'keyed', scope: 'session' },
messageImages: { kind: 'single', scope: 'session' },
userImages: { kind: 'single', scope: 'session' },
composer: { kind: 'chain', scope: 'session' },
};
/**
@ -250,7 +272,11 @@ export function installOfficialSlots(ctx: Context): () => void {
throw new Error(`Official slot contract changed: ${source}`);
}
return mirrorOfficialSlot(slots, source, target, `dsh-better-display.official.${family}`,
family === 'nodes' ? acceptMirroredChatNode : undefined);
family === 'nodes'
? acceptMirroredChatNode
: family === 'composer'
? acceptMirroredComposerEntry
: undefined);
}));
}
} catch (error) {

View File

@ -22,6 +22,8 @@ import { fileAddressFor, modeFromSnapshot, openDeliverableFile } from './open-fi
import type { ReaderInjected } from './types.js';
import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment';
import { installOfficialSlots, officialChildren, type CompositionRegistry } from './official-slots.js';
import { installInlineInteractions } from './inline-interaction.js';
import type { QuestionAnswerItem, QuestionReviewRecord } from './turn-questions.js';
import { TEXT_TRANSFORM_SERVICE, createTextTransformRegistry, installTextTransformRegistry } from './text-transform.js';
/** Structural face of the sanctioned per-session composer writer. */
@ -30,6 +32,27 @@ interface ComposerShell {
}
interface ConversationFace {
input?: { shell?: (id: SessionId) => ComposerShell };
sendSession?: (
session: unknown,
text: string,
attachmentIds: readonly unknown[],
mode: 'queue',
) => Promise<{ kind?: string }>;
}
interface UserQuestionPanelsFace {
reveal?: (sessionId: SessionId, callId: string) => boolean;
review?: (sessionId: SessionId, callId: string, record: QuestionReviewRecord) => boolean;
}
interface UserQuestionsRemoteFace {
userQuestions?: {
answer?: (
sessionId: SessionId,
callId: string,
payload: { answers: readonly QuestionAnswerItem[] },
) => Promise<{ ok: boolean; value?: boolean }>;
};
}
interface SidebarRightFace {
@ -94,6 +117,8 @@ export function apply(ctx: Context, options: { chatPrefs?: ChatPrefs } = {}): vo
ctx.slots.inject('conversation.chat.node', function* () {
yield retireHostedChatView(ctx.slots as unknown as ViewLedger);
const inlineInteraction = installInlineInteractions(ctx, prefs);
yield inlineInteraction.dispose;
// Occupies the built-in 对话 View: the transcript area draws the reader,
// the official composer/header/scroll port stay untouched.
yield ctx.slots.register({
@ -117,6 +142,7 @@ export function apply(ctx: Context, options: { chatPrefs?: ChatPrefs } = {}): vo
};
return {
openPrefs: prefs,
inlineInteraction: inlineInteraction.controller,
officialImageLoader: Object.assign(
(attachment: ImageAttachmentRef) => uiConversation.imageUrl(sessionId, attachment),
{ peek: (attachment: ImageAttachmentRef) => uiConversation.peekImageUrl(sessionId, attachment) },
@ -241,6 +267,46 @@ export function apply(ctx: Context, options: { chatPrefs?: ChatPrefs } = {}): vo
return false;
}
},
revealQuestion: (callId: string) => {
try {
const panels = ctx.get?.('userQuestionPanels') as UserQuestionPanelsFace | undefined;
return panels?.reveal?.(sessionId, callId) ?? false;
} catch {
return false;
}
},
reviewQuestion: (callId: string, record: QuestionReviewRecord) => {
try {
const panels = ctx.get?.('userQuestionPanels') as UserQuestionPanelsFace | undefined;
return panels?.review?.(sessionId, callId, record) ?? false;
} catch {
return false;
}
},
answerContinuedQuestion: async (callId: string, answers: readonly QuestionAnswerItem[]) => {
try {
const remote = (ctx.remote ?? ctx.get?.('remote')) as UserQuestionsRemoteFace | undefined;
const result = await remote?.userQuestions?.answer?.(sessionId, callId, { answers });
return Boolean(result?.ok && result?.value);
} catch {
return false;
}
},
sendFollowUp: async (text: string) => {
const trimmed = text.trim();
if (!trimmed) return false;
try {
const conv = (ctx.get?.('conversation') ?? (ctx as unknown as { conversation?: ConversationFace }).conversation) as ConversationFace | undefined;
const current = ctx.sessions?.binding?.(sessionId)?.session;
if (conv?.sendSession && current) {
const result = await conv.sendSession(current, trimmed, [], 'queue');
return result?.kind === 'success';
}
} catch (error) {
console.warn('[dsh-better-chat] sendFollowUp failed:', error);
}
return false;
},
};
},

View File

@ -27,6 +27,8 @@ export type SettingsCopyKey =
| 'renderTurnsAll'
| 'renderTurnsUnit'
| 'renderTurnsCustom'
| 'inlineInteractionsTitle'
| 'inlineInteractionsDescription'
| 'shortcutTitle'
| 'shortcutDescription'
| 'shortcutAllow'
@ -71,6 +73,8 @@ export const en: SettingsCopy = {
renderTurnsAll: 'All',
renderTurnsUnit: 'turns',
renderTurnsCustom: 'Custom',
inlineInteractionsTitle: 'Embed question cards in reply bubbles',
inlineInteractionsDescription: 'On by default: places ask-question option cards inside the matching AI reply bubble with history review and re-answering; tool approvals keep popping up live at the bottom bar so work is never blocked. Switching away from Chat falls back to the native dock.',
shortcutTitle: 'Approval card shortcuts',
shortcutDescription: 'Click a keycap and press the new combination. Allow-type actions use Enter, reject uses Esc; modifiers are free. Esc alone cancels while recording. Stored in the plugin config.',
shortcutAllow: 'Allow once',
@ -114,6 +118,8 @@ export const zh: SettingsCopy = {
renderTurnsAll: '全部',
renderTurnsUnit: '轮',
renderTurnsCustom: '自定义',
inlineInteractionsTitle: '在回复气泡内显示提问选项卡',
inlineInteractionsDescription: '默认开启:把模型发起的提问选项卡直接嵌进对应的 AI 回复气泡中,支持查看原卡、补答与重答;工具审批与方案确认仍实时从底部弹出,不阻塞后续操作。切到「轨迹」等其他标签页时会自动退回原生底部操作区。',
shortcutTitle: '审批卡快捷键',
shortcutDescription: '点键帽后按下新的组合键。允许类只能用 Enter,拒绝只能用 Esc,修饰键随意;录制时单独按 Esc 取消。保存在插件配置里,重启后仍在。',
shortcutAllow: '允许(单次)',

View File

@ -19,6 +19,7 @@ import {
} from './appearance.js';
import type { DeliverableOpenMode } from './open-file.js';
import { DEFAULT_RENDER_TURNS, normalizeRenderTurnLimit } from './turn-window.js';
import { INLINE_INTERACTIONS_DEFAULT } from './inline-interaction.js';
export interface ReaderState {
expanded: Record<string, boolean>;
@ -44,6 +45,8 @@ export interface ReaderState {
processOnly: boolean;
/** Max recent turns to render initially (`0` = render all loaded turns). */
renderTurnLimit: number;
/** Embed active question/option cards and approval cards inline in the conversation stream (`true` default). */
inlineInteractions: boolean;
}
type ReaderActions = {
setExpanded: (draft: ReaderState, key: string, value: boolean) => void;
@ -57,6 +60,7 @@ type ReaderActions = {
setAiBubbleStyle: (draft: ReaderState, value: AiBubbleStyle) => void;
setAiBubbleWidth: (draft: ReaderState, value: AiBubbleWidth) => void;
setRenderTurnLimit: (draft: ReaderState, value: number) => void;
setInlineInteractions: (draft: ReaderState, value: boolean) => void;
};
function applyFoldIntensity(draft: ReaderState, value: FoldIntensity): void {
@ -79,6 +83,7 @@ export function createReaderStore(): EngineStoreHandle<ReaderState, ReaderAction
aiBubbleWidth: AI_BUBBLE_WIDTH_DEFAULT,
processOnly: false,
renderTurnLimit: DEFAULT_RENDER_TURNS,
inlineInteractions: INLINE_INTERACTIONS_DEFAULT,
}),
persist: 'dsh.reader.v1',
actions: {
@ -104,6 +109,7 @@ export function createReaderStore(): EngineStoreHandle<ReaderState, ReaderAction
setAiBubbleStyle: (draft, value: AiBubbleStyle) => { draft.aiBubbleStyle = normalizeAiBubbleStyle(value); },
setAiBubbleWidth: (draft, value: AiBubbleWidth) => { draft.aiBubbleWidth = normalizeAiBubbleWidth(value); },
setRenderTurnLimit: (draft, value: number) => { draft.renderTurnLimit = normalizeRenderTurnLimit(value); },
setInlineInteractions: (draft, value: boolean) => { draft.inlineInteractions = Boolean(value); },
},
});
}

View File

@ -0,0 +1,477 @@
import type { ChatConversationViewNode } from '@deepseek-ai/dsh-client-ui-chat/client';
import type { ToolCallBlock, TurnLocation } from '@deepseek-ai/dsh-client-ui-conversation/client';
import type { SessionPendingInteraction } from '@deepseek-ai/dsh-client-ui-session/client';
import type { ReaderGroup } from './projection.js';
export interface QuestionOptionItem {
readonly label: string;
readonly description?: string;
}
export interface QuestionItem {
readonly id: string;
readonly question: string;
readonly header?: string;
readonly detail?: string;
readonly options?: readonly QuestionOptionItem[];
readonly multiSelect?: boolean;
}
export interface QuestionAnswerItem {
readonly id: string;
readonly selected: readonly string[];
readonly custom?: string;
}
export interface QuestionReviewRecord {
readonly questions: readonly QuestionItem[];
readonly answers: readonly QuestionAnswerItem[];
}
export interface UserQuestionsActiveRow {
readonly callId: string;
readonly questions: readonly QuestionItem[];
readonly state: 'open' | 'continued';
}
export interface UserQuestionsSettledRow {
readonly callId: string;
readonly answers: readonly QuestionAnswerItem[];
}
export interface UserQuestionsProjectionView {
readonly active?: readonly UserQuestionsActiveRow[];
readonly settled?: readonly UserQuestionsSettledRow[];
}
export type TurnQuestionStatus =
| 'open'
| 'continued'
| 'queued'
| 'answered'
| 'cancelled'
| 'interrupted'
| 'closed';
export interface TurnQuestionEntry {
readonly callId: string;
readonly status: TurnQuestionStatus;
readonly questions: readonly QuestionItem[];
readonly answers: readonly QuestionAnswerItem[];
readonly reviewRecord?: QuestionReviewRecord;
readonly turn: number | null;
readonly groupKey: string;
}
function asRecord(value: unknown): Record<string, unknown> | null {
return typeof value === 'object' && value !== null && !Array.isArray(value)
? value as Record<string, unknown>
: null;
}
function nonEmptyString(value: unknown): string | undefined {
if (typeof value !== 'string') return undefined;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
export function parseQuestionItems(rawArguments: string | undefined): QuestionItem[] {
if (typeof rawArguments !== 'string' || rawArguments.trim() === '') return [];
let parsed: unknown;
try {
parsed = JSON.parse(rawArguments);
} catch {
return [];
}
const root = asRecord(parsed);
if (!root || !Array.isArray(root.questions)) return [];
const items: QuestionItem[] = [];
for (const rawItem of root.questions) {
const item = asRecord(rawItem);
if (!item) continue;
const id = nonEmptyString(item.id);
const question = nonEmptyString(item.question);
if (!id || !question) continue;
const header = nonEmptyString(item.header);
const detail = nonEmptyString(item.detail);
const multiSelect = typeof item.multiSelect === 'boolean'
? item.multiSelect
: typeof item.multi_select === 'boolean'
? item.multi_select
: undefined;
let options: QuestionOptionItem[] | undefined;
if (Array.isArray(item.options)) {
const normalized: QuestionOptionItem[] = [];
for (const rawOption of item.options) {
const opt = asRecord(rawOption);
if (!opt || typeof opt.label !== 'string' || opt.label.trim() === '') continue;
const description = nonEmptyString(opt.description);
normalized.push({
label: opt.label,
...(description !== undefined ? { description } : {}),
});
}
if (normalized.length > 0) options = normalized;
}
items.push({
id,
question,
...(header !== undefined ? { header } : {}),
...(detail !== undefined ? { detail } : {}),
...(options !== undefined ? { options } : {}),
...(multiSelect !== undefined ? { multiSelect } : {}),
});
}
return items;
}
export function parseAnswerBatch(text: string | undefined): QuestionAnswerItem[] | null {
if (typeof text !== 'string' || text.trim() === '') return null;
let parsed: unknown;
try {
parsed = JSON.parse(text);
} catch {
return null;
}
const root = asRecord(parsed);
if (!root || !Array.isArray(root.answers)) return null;
const answers: QuestionAnswerItem[] = [];
for (const rawAnswer of root.answers) {
const item = asRecord(rawAnswer);
if (!item || typeof item.id !== 'string' || !Array.isArray(item.selected)) return null;
if (!item.selected.every((label): label is string => typeof label === 'string')) return null;
const custom = typeof item.custom === 'string' && item.custom.length > 0 ? item.custom : undefined;
answers.push({
id: item.id,
selected: [...item.selected],
...(custom !== undefined ? { custom } : {}),
});
}
return answers;
}
export function isPendingToolResult(text: string | undefined): boolean {
if (typeof text !== 'string' || text.trim() === '') return false;
try {
const parsed = asRecord(JSON.parse(text));
return parsed !== null && parsed.pending === true && typeof parsed.callId === 'string';
} catch {
return false;
}
}
export function queuedQuestionRepliesFromInbox(inbox: unknown): Map<string, QuestionAnswerItem[]> {
const result = new Map<string, QuestionAnswerItem[]>();
const box = asRecord(inbox);
if (!box) return result;
const nextStep = Array.isArray(box['next-step']) ? box['next-step'] : [];
const nextTurn = Array.isArray(box['next-turn']) ? box['next-turn'] : [];
for (const message of [...nextStep, ...nextTurn]) {
const msg = asRecord(message);
if (!msg) continue;
const source = asRecord(msg.source);
if (!source || source.kind !== 'user-question-reply' || typeof source.callId !== 'string') continue;
let batch: QuestionAnswerItem[] = [];
if (Array.isArray(msg.content)) {
for (const block of msg.content) {
const part = asRecord(block);
if (part?.type === 'text' && typeof part.text === 'string') {
const parsed = parseAnswerBatch(part.text);
if (parsed !== null) {
batch = parsed;
break;
}
}
}
}
result.set(source.callId, batch);
}
return result;
}
export function pendingCallIdOf(pending: unknown): string | undefined {
const rec = asRecord(pending);
if (!rec) return undefined;
return nonEmptyString(rec.callId);
}
interface CollectedQuestionCall {
readonly callId: string;
argsRaw?: string;
block?: ToolCallBlock;
}
function visitToolBlock(block: ToolCallBlock, collected: Map<string, CollectedQuestionCall>): void {
const callId = block.callId;
const toolName = 'kind' in block ? block.call?.name : block.name;
if (callId && toolName === 'ask_user_question') {
const argsRaw = 'kind' in block
? block.call?.argsRaw
: ('argsRaw' in block ? block.argsRaw : undefined);
collected.set(callId, { callId, argsRaw, block });
}
if ('kind' in block && Array.isArray(block.subCalls)) {
for (const child of block.subCalls) {
visitToolBlock(child, collected);
}
}
}
function collectGroupQuestionCalls(
group: ReaderGroup,
turn: TurnLocation | undefined,
getNode: (key: string) => ChatConversationViewNode | undefined,
): CollectedQuestionCall[] {
const collected = new Map<string, CollectedQuestionCall>();
for (const key of group.keys) {
const node = getNode(key);
if (!node || node.visibility === 'hidden' || node.kind !== 'tool-call') continue;
visitToolBlock((node.data as { root: ToolCallBlock }).root, collected);
}
for (const step of turn?.steps ?? []) {
const assistant = step.data.get('assistant-step');
for (const draft of assistant?.blocks ?? []) {
if (draft.kind !== 'tool-call' || draft.name !== 'ask_user_question' || !draft.callId) continue;
const existing = collected.get(draft.callId);
if (existing) {
if (!existing.argsRaw && draft.argsRaw) existing.argsRaw = draft.argsRaw;
} else {
collected.set(draft.callId, { callId: draft.callId, argsRaw: draft.argsRaw });
}
}
}
return [...collected.values()];
}
function singleResultText(block: Extract<ToolCallBlock, { kind: string }>): string | undefined {
if (!Array.isArray(block.content)) return undefined;
const textBlock = block.content.find(item => item?.type === 'text');
return typeof textBlock?.text === 'string' ? textBlock.text : undefined;
}
export function extractGroupQuestions(args: {
group: ReaderGroup;
turn: TurnLocation | undefined;
getNode: (key: string) => ChatConversationViewNode | undefined;
userQuestions: UserQuestionsProjectionView | undefined;
queuedReplies: ReadonlyMap<string, readonly QuestionAnswerItem[]>;
}): TurnQuestionEntry[] {
const { group, turn, getNode, userQuestions, queuedReplies } = args;
const calls = collectGroupQuestionCalls(group, turn, getNode);
if (calls.length === 0) return [];
const activeByCall = new Map((userQuestions?.active ?? []).map(row => [row.callId, row]));
const settledByCall = new Map((userQuestions?.settled ?? []).map(row => [row.callId, row]));
const entries: TurnQuestionEntry[] = [];
for (const { callId, argsRaw, block } of calls) {
const parsedArgs = parseQuestionItems(argsRaw);
const activeRow = activeByCall.get(callId);
const settledRow = settledByCall.get(callId);
if (activeRow) {
const questions = activeRow.questions.length > 0 ? activeRow.questions : parsedArgs;
if (queuedReplies.has(callId)) {
entries.push({
callId,
status: 'queued',
questions,
answers: queuedReplies.get(callId) ?? [],
turn: group.turn,
groupKey: group.key,
});
} else {
entries.push({
callId,
status: activeRow.state === 'continued' ? 'continued' : 'open',
questions,
answers: [],
turn: group.turn,
groupKey: group.key,
});
}
continue;
}
if (settledRow) {
if (parsedArgs.length === 0) continue;
if (settledRow.answers.length === 0) {
entries.push({
callId,
status: 'closed',
questions: parsedArgs,
answers: [],
turn: group.turn,
groupKey: group.key,
});
} else {
entries.push({
callId,
status: 'answered',
questions: parsedArgs,
answers: settledRow.answers,
reviewRecord: { questions: parsedArgs, answers: settledRow.answers },
turn: group.turn,
groupKey: group.key,
});
}
continue;
}
if (parsedArgs.length === 0) continue;
if (!block || !('kind' in block)) {
entries.push({
callId,
status: 'open',
questions: parsedArgs,
answers: [],
turn: group.turn,
groupKey: group.key,
});
continue;
}
if (block.error?.code === 'ASK_CANCELLED') {
entries.push({
callId,
status: 'cancelled',
questions: parsedArgs,
answers: [],
turn: group.turn,
groupKey: group.key,
});
continue;
}
if (block.error?.code === 'ASK_ABORTED') {
entries.push({
callId,
status: 'interrupted',
questions: parsedArgs,
answers: [],
turn: group.turn,
groupKey: group.key,
});
continue;
}
if (block.isError) {
entries.push({
callId,
status: 'closed',
questions: parsedArgs,
answers: [],
turn: group.turn,
groupKey: group.key,
});
continue;
}
const resultText = singleResultText(block);
if (isPendingToolResult(resultText)) {
entries.push({
callId,
status: 'closed',
questions: parsedArgs,
answers: [],
turn: group.turn,
groupKey: group.key,
});
continue;
}
const parsedAnswers = parseAnswerBatch(resultText);
if (parsedAnswers !== null) {
entries.push({
callId,
status: 'answered',
questions: parsedArgs,
answers: parsedAnswers,
reviewRecord: { questions: parsedArgs, answers: parsedAnswers },
turn: group.turn,
groupKey: group.key,
});
continue;
}
entries.push({
callId,
status: 'closed',
questions: parsedArgs,
answers: [],
turn: group.turn,
groupKey: group.key,
});
}
return entries;
}
export function findHostedPendingGroupKey(
pending: SessionPendingInteraction | undefined,
renderedGroups: readonly ReaderGroup[],
questionsByGroup: ReadonlyMap<string, readonly TurnQuestionEntry[]>,
): string | null {
if (!pending || pending.kind !== 'question') return null;
const callId = pendingCallIdOf(pending);
if (!callId) return null;
for (const group of renderedGroups) {
const items = questionsByGroup.get(group.key);
if (items?.some(entry => entry.callId === callId)) {
return group.key;
}
}
return null;
}
export function findOffWindowActiveQuestions(
userQuestions: UserQuestionsProjectionView | undefined,
queuedReplies: ReadonlyMap<string, readonly QuestionAnswerItem[]>,
renderedCallIds: ReadonlySet<string>,
pendingCallId: string | undefined,
): readonly UserQuestionsActiveRow[] {
const active = userQuestions?.active;
if (!Array.isArray(active) || active.length === 0) return [];
return active.filter(item =>
!renderedCallIds.has(item.callId)
&& !queuedReplies.has(item.callId)
&& item.callId !== pendingCallId);
}
export function answerDisplayValues(answer: QuestionAnswerItem | undefined): string[] {
if (!answer) return [];
const values = answer.selected.filter(label => label.trim().length > 0);
const custom = answer.custom?.trim();
if (custom && !values.includes(custom)) values.push(custom);
return values;
}
export function formatQuestionFollowUpReply(
questions: readonly QuestionItem[],
answers: readonly QuestionAnswerItem[],
mode: 'revise' | 'answer',
): string {
const header = mode === 'revise'
? '关于之前的问题,更新我的回答:'
: '关于之前未完成的问题,我的回答如下:';
const byId = new Map(answers.map(item => [item.id, item]));
const lines = questions.map(question => {
const title = question.header && question.header !== question.question
? `${question.header} — ${question.question}`
: question.question;
const values = answerDisplayValues(byId.get(question.id));
return `- ${title}:${values.length > 0 ? values.join(';') : '(跳过)'}`;
});
return [header, ...lines].join('\n');
}

View File

@ -67,6 +67,7 @@ export interface ReaderInjected {
autoFold?: boolean;
processOnly?: boolean;
renderTurnLimit?: number;
inlineInteractions?: boolean;
};
subscribe: (fn: () => void) => () => void;
actions?: {
@ -78,8 +79,19 @@ export interface ReaderInjected {
setAiBubbleWidth?: (value: import('./appearance.js').AiBubbleWidth) => void;
setDeliverableOpenMode?: (value: import('./open-file.js').DeliverableOpenMode) => void;
setRenderTurnLimit?: (value: number) => void;
setInlineInteractions?: (value: boolean) => void;
};
};
/** Coordinates single-mount inline takeover for question/approval cards. */
inlineInteraction?: Pick<import('./inline-interaction.js').InlineInteractionController, 'acquire' | 'isClaimed' | 'subscribe' | 'getVersion'>;
/** Re-open an active question panel inline via DSH userQuestionPanels. */
revealQuestion?: (callId: string) => boolean;
/** Re-open an answered question review card inline via DSH userQuestionPanels. */
reviewQuestion?: (callId: string, record: import('./turn-questions.js').QuestionReviewRecord) => boolean;
/** Answer a timed continued question directly through DSH remote.userQuestions. */
answerContinuedQuestion?: (callId: string, answers: readonly import('./turn-questions.js').QuestionAnswerItem[]) => Promise<boolean>;
/** Submit a follow-up user message into the active session. */
sendFollowUp?: (text: string) => Promise<boolean>;
/** Reveal and highlight a workspace file in macOS Finder or Windows Explorer. */
revealFile?: (path: string) => Promise<void> | void;
/** Fork the conversation at a specific message sequence into a new branch session. */

View File

@ -0,0 +1,376 @@
import assert from 'node:assert/strict';
import { test } from 'vitest';
import { SlotCore } from '@deepseek-ai/dsh-client-ui-slots';
import type { ComposerChainProps } from '@deepseek-ai/dsh-client-ui-conversation/client';
import type { SessionId } from '@deepseek-ai/dsh-session/types';
import {
INLINE_COMPOSER_INTERCEPTOR_PRIORITY,
INLINE_COMPOSER_INTERCEPTOR_REGISTRANT,
OFFICIAL_SEATS,
OFFICIAL_SLOTS,
acceptMirroredComposerEntry,
type CompositionRegistry,
} from '../src/client/official-slots.js';
import {
INLINE_INTERACTIONS_DEFAULT,
InlineComposerInterceptor,
createInlineInteractionController,
inlineInteractionsOf,
isInlineQuestionPending,
} from '../src/client/inline-interaction.js';
const tick = () => Promise.resolve();
const twoTicks = async () => {
await tick();
await tick();
};
function createTestRegistry(options: { declareReaderSeat?: boolean } = {}) {
const core = new SlotCore();
const register = (opts: object, component: unknown) =>
(core.register as Function)(opts, component) as () => void;
const children: Record<string, { kind: 'chain'; scope: 'session' }> = {
[OFFICIAL_SLOTS.composer]: { kind: 'chain', scope: 'session' },
};
if (options.declareReaderSeat !== false) {
children[OFFICIAL_SEATS.composer] = { kind: 'chain', scope: 'session' };
}
const disposeRoot = register({ name: 'root', children }, () => null);
const slots: CompositionRegistry = {
register,
spec: key => core.spec(key as never),
entriesOfSlot: key => core.entriesOfSlot(key),
subscribe: (key, fn) => core.subscribe(key, fn),
inject: (key, effect) => {
let active: (() => void) | undefined;
let activeEpoch: number | undefined;
let stopped = false;
const reconcile = () => {
if (stopped) return;
const spec = core.specDynamic(key);
const epoch = core.declarationEpoch(key);
if (active !== undefined && activeEpoch === epoch) return;
const prev = active;
active = undefined;
activeEpoch = undefined;
prev?.();
if (spec === undefined) return;
active = effect();
activeEpoch = epoch;
};
const unsub = core.subscribeDeclaration(key, reconcile);
reconcile();
return () => {
if (stopped) return;
stopped = true;
unsub();
const prev = active;
active = undefined;
activeEpoch = undefined;
prev?.();
};
},
};
return { core, slots, register, disposeRoot };
}
function elect(core: SlotCore, key: string, owner: ComposerChainProps) {
for (const entry of core.entriesOfSlot(key)) {
const select = entry.select as ((value: ComposerChainProps) => unknown) | undefined;
if (typeof select !== 'function') continue;
const matched = select(owner);
if (matched !== null) return { entry, matched };
}
return null;
}
const makeOwner = (
sessionId: string,
kind?: string,
subagentMode?: 'one-shot' | 'unknown' | 'continuable',
): ComposerChainProps => ({
sessionId: sessionId as SessionId,
session: subagentMode
? ({ subagent: { address: { mode: subagentMode } } } as unknown as ComposerChainProps['session'])
: ({ subagent: null } as unknown as ComposerChainProps['session']),
pendingInteraction: kind
? ({ key: `${kind}:1`, kind, sessionId: sessionId as SessionId } as ComposerChainProps['pendingInteraction'])
: undefined,
});
test('inlineInteractionsOf defaults to true and honors explicit boolean overrides', () => {
assert.equal(INLINE_INTERACTIONS_DEFAULT, true);
assert.equal(inlineInteractionsOf(undefined), true);
assert.equal(inlineInteractionsOf({}), true);
assert.equal(inlineInteractionsOf({ inlineInteractions: true }), true);
assert.equal(inlineInteractionsOf({ inlineInteractions: false }), false);
});
test('acceptMirroredComposerEntry excludes interceptor and read-only subagent banners while accepting interaction cards', () => {
const { core, register } = createTestRegistry();
register({
name: OFFICIAL_SLOTS.composer,
priority: -10,
registrant: 'dsh-client-ui-subagent',
select: () => null,
}, () => null);
register({
name: OFFICIAL_SLOTS.composer,
priority: INLINE_COMPOSER_INTERCEPTOR_PRIORITY,
registrant: INLINE_COMPOSER_INTERCEPTOR_REGISTRANT,
select: () => null,
}, InlineComposerInterceptor);
register({
name: OFFICIAL_SLOTS.composer,
priority: -1,
registrant: 'dsh-cua',
select: () => null,
}, () => null);
register({
name: OFFICIAL_SLOTS.composer,
priority: 0,
registrant: 'dsh-client-ui-user-questions',
select: () => null,
}, () => null);
register({
name: OFFICIAL_SLOTS.composer,
priority: 1,
registrant: 'dsh-client-ui-approval',
select: () => null,
}, () => null);
const accepted = core
.entriesOfSlot(OFFICIAL_SLOTS.composer)
.filter(acceptMirroredComposerEntry)
.map(entry => entry.registrant);
assert.deepEqual(accepted, ['dsh-cua', 'dsh-client-ui-user-questions', 'dsh-client-ui-approval']);
});
test('isInlineQuestionPending accepts only user-question option cards and keeps approvals/plan-review real-time', () => {
assert.equal(isInlineQuestionPending(undefined), false);
assert.equal(isInlineQuestionPending(makeOwner('s1', 'question').pendingInteraction), true);
assert.equal(isInlineQuestionPending(makeOwner('s1', 'approval').pendingInteraction), false);
assert.equal(isInlineQuestionPending(makeOwner('s1', 'plan-review').pendingInteraction), false);
});
test('steady-state interception claims official question cards while letting approvals/plan-review pop up natively in real time', async () => {
const { core, slots, register } = createTestRegistry();
const SubagentBanner = () => null;
const QuestionCard = () => null;
const ApprovalCard = () => null;
const PlanReviewCard = () => null;
register({
name: OFFICIAL_SLOTS.composer,
priority: -10,
registrant: 'dsh-client-ui-subagent',
select: (owner: ComposerChainProps) => {
const mode = (owner.session as { subagent?: { address?: { mode?: string } } | null } | undefined)?.subagent?.address?.mode;
return mode === 'one-shot' || mode === 'unknown' ? { reason: mode } : null;
},
}, SubagentBanner);
register({
name: OFFICIAL_SLOTS.composer,
priority: 0,
registrant: 'dsh-client-ui-user-questions',
select: (owner: ComposerChainProps) => owner.pendingInteraction?.kind === 'question' ? owner.pendingInteraction : null,
}, QuestionCard);
register({
name: OFFICIAL_SLOTS.composer,
priority: 0,
registrant: 'dsh-client-ui-plan-review',
select: (owner: ComposerChainProps) => owner.pendingInteraction?.kind === 'plan-review' ? owner.pendingInteraction : null,
}, PlanReviewCard);
register({
name: OFFICIAL_SLOTS.composer,
priority: 1,
registrant: 'dsh-client-ui-approval',
select: (owner: ComposerChainProps) => owner.pendingInteraction?.kind === 'approval' ? owner.pendingInteraction : null,
}, ApprovalCard);
const controller = createInlineInteractionController(slots);
const s1 = 'session-1' as SessionId;
const s2 = 'session-2' as SessionId;
const token = Symbol('reader-1');
const release = controller.acquire(s1, token);
// Single-mount timing: not claimed synchronously or after 1 microtask.
assert.equal(controller.isClaimed(s1, token), false);
await tick();
assert.equal(controller.isClaimed(s1, token), false);
await tick();
assert.equal(controller.isClaimed(s1, token), true);
// Question card for mounted Reader session elects our interceptor (renders in-bubble via OFFICIAL_SEATS.composer).
const questionWin = elect(core, OFFICIAL_SLOTS.composer, makeOwner(s1, 'question'));
assert.equal(questionWin?.entry.component, InlineComposerInterceptor);
assert.equal(InlineComposerInterceptor(), null);
// Tool approval & plan confirmation MUST pass through real-time to native bottom composer so work is never blocked!
const approvalWin = elect(core, OFFICIAL_SLOTS.composer, makeOwner(s1, 'approval'));
assert.equal(approvalWin?.entry.component, ApprovalCard);
const planWin = elect(core, OFFICIAL_SLOTS.composer, makeOwner(s1, 'plan-review'));
assert.equal(planWin?.entry.component, PlanReviewCard);
// Idle session (no pendingInteraction) falls through to resident composerBar.
assert.equal(elect(core, OFFICIAL_SLOTS.composer, makeOwner(s1, undefined)), null);
// Read-only subagent banner at priority -10 wins ahead of our interceptor.
const subagentWin = elect(core, OFFICIAL_SLOTS.composer, makeOwner(s1, 'question', 'one-shot'));
assert.equal(subagentWin?.entry.component, SubagentBanner);
// Unhandled pendingInteraction kind is NOT swallowed.
assert.equal(elect(core, OFFICIAL_SLOTS.composer, makeOwner(s1, 'unknown-kind')), null);
// Other session without mounted Reader keeps native bottom dock question cards.
const s2Win = elect(core, OFFICIAL_SLOTS.composer, makeOwner(s2, 'question'));
assert.equal(s2Win?.entry.component, QuestionCard);
release();
controller.dispose();
});
test('releasing a Reader mount (tab switch) clears inline claim synchronously and restores bottom dock immediately', async () => {
const { core, slots, register } = createTestRegistry();
const QuestionCard = () => null;
register({
name: OFFICIAL_SLOTS.composer,
priority: 0,
registrant: 'dsh-client-ui-user-questions',
select: (owner: ComposerChainProps) => owner.pendingInteraction?.kind === 'question' ? owner.pendingInteraction : null,
}, QuestionCard);
const controller = createInlineInteractionController(slots);
const s1 = 'session-tab' as SessionId;
const token = Symbol('reader');
const release = controller.acquire(s1, token);
await twoTicks();
assert.equal(controller.isClaimed(s1, token), true);
assert.equal(elect(core, OFFICIAL_SLOTS.composer, makeOwner(s1, 'question'))?.entry.component, InlineComposerInterceptor);
let composerNotified = 0;
const unsubComposer = core.subscribe(OFFICIAL_SLOTS.composer, () => { composerNotified += 1; });
release();
// Inline claim clears synchronously and bottom composer elects official QuestionCard.
assert.equal(controller.isClaimed(s1, token), false);
assert.equal(elect(core, OFFICIAL_SLOTS.composer, makeOwner(s1, 'question'))?.entry.component, QuestionCard);
await tick();
assert.ok(composerNotified > 0, 'conversation.composer subscribers must be notified so bottom dock remounts');
unsubComposer();
controller.dispose();
});
test('setEnabled toggles cleanly with single-mount two-microtask handoff in both directions', async () => {
const { core, slots, register } = createTestRegistry();
const QuestionCard = () => null;
register({
name: OFFICIAL_SLOTS.composer,
priority: 0,
registrant: 'dsh-client-ui-user-questions',
select: (owner: ComposerChainProps) => owner.pendingInteraction?.kind === 'question' ? owner.pendingInteraction : null,
}, QuestionCard);
const controller = createInlineInteractionController(slots);
const s1 = 'session-toggle' as SessionId;
const token = Symbol('reader');
const release = controller.acquire(s1, token);
await twoTicks();
assert.equal(controller.isClaimed(s1, token), true);
// Turning OFF: inline claim drops synchronously; interceptor stays removed after two microtasks.
controller.setEnabled(false);
assert.equal(controller.isEnabled(), false);
assert.equal(controller.isClaimed(s1, token), false);
// Interceptor entry still present until the 2-microtask handoff disposes it cleanly.
assert.equal(
core.entriesOfSlot(OFFICIAL_SLOTS.composer).some(e => e.registrant === INLINE_COMPOSER_INTERCEPTOR_REGISTRANT),
true,
);
await twoTicks();
assert.equal(
core.entriesOfSlot(OFFICIAL_SLOTS.composer).some(e => e.registrant === INLINE_COMPOSER_INTERCEPTOR_REGISTRANT),
false,
);
assert.equal(elect(core, OFFICIAL_SLOTS.composer, makeOwner(s1, 'question'))?.entry.component, QuestionCard);
// Turning ON: interceptor registers synchronously; inline claim waits 2 microtasks.
controller.setEnabled(true);
assert.equal(controller.isEnabled(), true);
assert.equal(
core.entriesOfSlot(OFFICIAL_SLOTS.composer).some(e => e.registrant === INLINE_COMPOSER_INTERCEPTOR_REGISTRANT),
true,
);
assert.equal(controller.isClaimed(s1, token), false);
await tick();
assert.equal(controller.isClaimed(s1, token), false);
await tick();
assert.equal(controller.isClaimed(s1, token), true);
assert.equal(elect(core, OFFICIAL_SLOTS.composer, makeOwner(s1, 'question'))?.entry.component, InlineComposerInterceptor);
release();
controller.dispose();
});
test('multiple Reader instances for the same session only claim the primary token and promote on release', async () => {
const { slots, register } = createTestRegistry();
register({
name: OFFICIAL_SLOTS.composer,
priority: 0,
registrant: 'dsh-client-ui-user-questions',
select: (owner: ComposerChainProps) => owner.pendingInteraction?.kind === 'question' ? owner.pendingInteraction : null,
}, () => null);
const controller = createInlineInteractionController(slots);
const s1 = 'session-multi' as SessionId;
const primary = Symbol('primary');
const secondary = Symbol('secondary');
const releasePrimary = controller.acquire(s1, primary);
const releaseSecondary = controller.acquire(s1, secondary);
await twoTicks();
assert.equal(controller.isClaimed(s1, primary), true);
assert.equal(controller.isClaimed(s1, secondary), false);
releasePrimary();
assert.equal(controller.isClaimed(s1, primary), false);
assert.equal(controller.isClaimed(s1, secondary), false);
await twoTicks();
assert.equal(controller.isClaimed(s1, secondary), true);
releaseSecondary();
assert.equal(controller.isClaimed(s1, secondary), false);
controller.dispose();
});
test('interceptor declines when Reader mirrored composer seat is not declared and cleans up on dispose', async () => {
const { core, slots, register } = createTestRegistry({ declareReaderSeat: false });
const QuestionCard = () => null;
register({
name: OFFICIAL_SLOTS.composer,
priority: 0,
registrant: 'dsh-client-ui-user-questions',
select: (owner: ComposerChainProps) => owner.pendingInteraction?.kind === 'question' ? owner.pendingInteraction : null,
}, QuestionCard);
const controller = createInlineInteractionController(slots);
const s1 = 'session-no-seat' as SessionId;
const token = Symbol('reader');
controller.acquire(s1, token);
await twoTicks();
// Without OFFICIAL_SEATS.composer declared, interceptor refuses so bottom dock keeps handling it.
assert.equal(elect(core, OFFICIAL_SLOTS.composer, makeOwner(s1, 'question'))?.entry.component, QuestionCard);
controller.dispose();
assert.equal(controller.isClaimed(s1, token), false);
assert.equal(
core.entriesOfSlot(OFFICIAL_SLOTS.composer).some(e => e.registrant === INLINE_COMPOSER_INTERCEPTOR_REGISTRANT),
false,
);
});

View File

@ -2,7 +2,15 @@ import assert from 'node:assert/strict';
import { test } from 'vitest';
import { memo } from 'react';
import { SlotCore } from '@deepseek-ai/dsh-client-ui-slots';
import { acceptMirroredChatNode, mirrorOfficialSlot, readerTailMatch, type CompositionRegistry } from '../src/client/official-slots.js';
import {
INLINE_COMPOSER_INTERCEPTOR_PRIORITY,
INLINE_COMPOSER_INTERCEPTOR_REGISTRANT,
acceptMirroredChatNode,
acceptMirroredComposerEntry,
mirrorOfficialSlot,
readerTailMatch,
type CompositionRegistry,
} from '../src/client/official-slots.js';
function registry(kind: 'keyed' | 'chain' | 'list' = 'keyed') {
const core = new SlotCore();
@ -149,3 +157,49 @@ test('partial setup rolls back its own registrations on a nested contract failur
assert.equal(core.entriesOfSlot('source').length, 1);
assert.equal(core.entriesOfSlot('detail').length, 1);
});
test('composer chain mirroring forwards question/approval cards and nested plan-review actions while ignoring interceptor churn', async () => {
const { core, slots, register } = registry('chain');
const SubagentBanner = memo(() => null);
const QuestionComposer = memo(() => null);
const PlanReviewAction = memo(() => null);
const ApprovalPanel = memo(() => null);
const questionSelect = (owner: unknown) => owner;
const approvalSelect = (owner: unknown) => owner;
register({ name: 'source', priority: -10, registrant: 'dsh-client-ui-subagent', select: () => null }, SubagentBanner);
register({
name: 'source',
priority: 0,
registrant: 'dsh-client-ui-user-questions',
select: questionSelect,
children: { 'conversation.plan-review.actions': { kind: 'list', scope: 'session' } },
}, QuestionComposer);
register({ name: 'conversation.plan-review.actions', id: 'open-plan', order: 10 }, PlanReviewAction);
register({ name: 'source', priority: 1, registrant: 'dsh-client-ui-approval', select: approvalSelect }, ApprovalPanel);
const stop = mirrorOfficialSlot(slots, 'source', 'reader', 'reader.composer', acceptMirroredComposerEntry);
const mirroredBefore = core.entriesOfSlot('reader');
assert.equal(mirroredBefore.length, 2);
assert.equal(mirroredBefore[0].select, questionSelect);
assert.equal(mirroredBefore[1].select, approvalSelect);
assert.equal(mirroredBefore[1].component, ApprovalPanel);
assert.equal(core.entriesOfSlot('reader.composer/conversation.plan-review.actions')[0]?.component, PlanReviewAction);
// Adding and removing our own bottom-dock interceptor must not remount mirrored cards.
const removeInterceptor = register({
name: 'source',
priority: INLINE_COMPOSER_INTERCEPTOR_PRIORITY,
registrant: INLINE_COMPOSER_INTERCEPTOR_REGISTRANT,
select: () => null,
}, () => null);
await changed();
assert.deepEqual(core.entriesOfSlot('reader'), mirroredBefore);
removeInterceptor();
await changed();
assert.deepEqual(core.entriesOfSlot('reader'), mirroredBefore);
stop();
assert.equal(core.entriesOfSlot('reader').length, 0);
assert.equal(slots.spec('reader.composer/conversation.plan-review.actions'), undefined);
});

View File

@ -160,3 +160,40 @@ test('theme, bubble style, and bubble width preferences are wired into Settings
assert.match(readerCss, /\.root\[data-reader-bubble-style="plain"\] \.answerBubble/u);
assert.match(readerCss, /\.root\[data-reader-bubble-width="100"\]/u);
});
test('inline question cards embed inside AI bubbles, approvals remain native real-time popups, and slots stay wired', async () => {
const officialSlots = await readFile(new URL('../src/client/official-slots.tsx', import.meta.url), 'utf8');
const inlineSource = await readFile(new URL('../src/client/inline-interaction.ts', import.meta.url), 'utf8');
assert.match(officialSlots, /composer:\s*'conversation\.composer'/u);
assert.match(officialSlots, /composer:\s*'dsh-better-display\.official\.composer\/conversation\.composer'/u);
assert.match(officialSlots, /acceptMirroredComposerEntry/u);
assert.match(inlineSource, /isInlineQuestionPending/u);
assert.match(inlineSource, /pending\.kind === 'question'/u);
assert.match(source, /installInlineInteractions\(ctx,\s*prefs\)/u);
assert.match(storeSource, /inlineInteractions:\s*INLINE_INTERACTIONS_DEFAULT/u);
assert.match(storeSource, /setInlineInteractions/u);
assert.match(settingsSection, /data-better-display-inline-interactions=/u);
assert.match(reader, /isInlineQuestionPending\(pending\)/u);
assert.match(reader, /data-reader-inline-interaction/u);
assert.match(reader, /OFFICIAL_SEATS\.composer/u);
assert.match(flow, /distributeBubbleQuestions/u);
assert.match(flow, /data-reader-bubble-questions/u);
assert.match(readerCss, /--dsh-composer-text-max-height:/u);
assert.match(readerCss, /\.inlineInteraction\s*\{/u);
assert.match(readerCss, /\.bubbleQuestions\s*\{/u);
});
test('per-turn question cards and historical re-answering / review are wired into Reader', async () => {
const cardSource = await readFile(new URL('../src/client/TurnQuestionCard.tsx', import.meta.url), 'utf8');
assert.match(cardSource, /data-reader-turn-question=/u);
assert.match(cardSource, /data-reader-question-reanswer/u);
assert.match(cardSource, /MuseLiveQuestion/u);
assert.match(readerCss, /\.questionOptionBtn\s*\{[^}]*border:\s*1px dashed/u);
assert.match(source, /revealQuestion:/u);
assert.match(source, /reviewQuestion:/u);
assert.match(source, /sendFollowUp:/u);
assert.match(reader, /TurnQuestionCard/u);
assert.match(reader, /extractGroupQuestions/u);
assert.match(reader, /findHostedPendingGroupKey/u);
assert.match(reader, /data-reader-unanswered-earlier/u);
});

View File

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