Merge PR #500 into CI optimization
This commit is contained in:
22
packages/client/ui-conversation/README.md
Normal file
22
packages/client/ui-conversation/README.md
Normal file
@@ -0,0 +1,22 @@
|
||||
# @deepseek-ai/dsh-client-ui-conversation
|
||||
|
||||
Conversation domain: skeleton (header/tabs/composer/empty state), chat view (grouped step-summary flow, streaming tail isolation), ctx.toolviews named registry with bash samples, minimal details panel, scope-addressed ConversationService. Contract: api-contracts v3 §7.
|
||||
|
||||
`src/client/` is organized for the future package split: `contract/` is the sole inter-domain shared face (`slots.ts` composed slot props, `views.ts` view ring, `toolview.ts` tool ring, `tool-call-model.ts`); the `skeleton/`, `chat/`, and `toolviews/` domain directories import contract files and never each other; `apply.ts` is the only assembly point allowed to import all three domains.
|
||||
|
||||
## Model Experience
|
||||
|
||||
None, as the conversation UI renders session history and streams in the browser; nothing here reaches a model request.
|
||||
|
||||
#### KV Cache effect
|
||||
|
||||
None; this package neither assembles nor sends a provider request.
|
||||
|
||||
## Known Limitations and Deferred Work
|
||||
|
||||
- **The stats line has no duration segment** — assistant `usage` carries token accounting only; elapsed-time needs a host data source.
|
||||
- **Details panel is the minimal form** — selected call args/result raw display; the Input/Output/Metadata switch, Prev/Next stepping, and See-in-trajectory deep link are deferred.
|
||||
- **Assistant footer extensions (IconActions row, per-message paging) are reserved slots** — drawn in the design, not implemented.
|
||||
- **The sparkle icon for the others tool row is a hand-drawn approximation** — the design glyph's vector geometry is not exportable locally; promotion into ui-primitives waits on an exact export.
|
||||
- **Approval/question cards are display-only placeholders** — web-side answering (composer takeover panel) is the P-II approvals project.
|
||||
- **Module-level toolview caches are single-bundle state** — the inject cache and registry maps must reach cross-bundle consumers through the package export surface and loader module table, never by a second bundle copy.
|
||||
63
packages/client/ui-conversation/package.json
Normal file
63
packages/client/ui-conversation/package.json
Normal file
@@ -0,0 +1,63 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-client-ui-conversation",
|
||||
"description": "Conversation domain: skeleton (header/tabs/composer), chat view, ctx.toolviews registry, minimal details panel",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "lib/index.js",
|
||||
"types": "lib/types/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./lib/types/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./invariant": {
|
||||
"types": "./lib/types/invariant.d.ts",
|
||||
"default": "./lib/invariant.js"
|
||||
},
|
||||
"./client": {
|
||||
"types": "./lib/types/client/index.d.ts",
|
||||
"default": "./lib/client.js"
|
||||
},
|
||||
"./src/*": "./src/*",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"dshClient": {
|
||||
"inject": [
|
||||
"@deepseek-ai/dsh-client-ui-layout"
|
||||
],
|
||||
"platform": "web"
|
||||
},
|
||||
"scripts": {
|
||||
"bundle": "tsdown",
|
||||
"watch": "tsdown --watch"
|
||||
},
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"@deepseek-ai/dsh-client-i18n": "workspace:^",
|
||||
"@deepseek-ai/dsh-client-runtime": "workspace:^",
|
||||
"@deepseek-ai/dsh-client-ui-layout": "workspace:^",
|
||||
"@deepseek-ai/dsh-client-ui-primitives": "workspace:^",
|
||||
"@deepseek-ai/dsh-client-ui-slots": "workspace:^",
|
||||
"@deepseek-ai/dsh-client-web-react": "workspace:^",
|
||||
"clsx": "^2.0.0",
|
||||
"react": "^18.2.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/dsh-invariants": "^0.0.1",
|
||||
"cordis": "^4.0.0-rc.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@deepseek-ai/dsh-invariants": "workspace:^",
|
||||
"@types/react": "~18.3.1",
|
||||
"cordis": "^4.0.0-rc.7"
|
||||
},
|
||||
"files": [
|
||||
"lib/index.js",
|
||||
"lib/invariant.js",
|
||||
"lib/client.js",
|
||||
"lib/types/**/*.d.ts",
|
||||
"lib/types/**/*.d.ts.map",
|
||||
"src"
|
||||
]
|
||||
}
|
||||
185
packages/client/ui-conversation/src/client/apply.ts
Normal file
185
packages/client/ui-conversation/src/client/apply.ts
Normal file
@@ -0,0 +1,185 @@
|
||||
/**
|
||||
* Client plugin body: provide the conversation service and toolview registry,
|
||||
* register the conversation/details slot occupants and the no-session empty
|
||||
* state, and mount the chat view with its samples. Assembly only — components
|
||||
* receive everything through inject factories; nothing here renders directly.
|
||||
*/
|
||||
import { createElement, Fragment, type ReactNode } from 'react'
|
||||
import type { Context } from 'cordis'
|
||||
import type { SessionBinding } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import { scopedSlots, shallowEqual } from '@deepseek-ai/dsh-client-web-react'
|
||||
import type { SnapshotSelectorHook, UseSession } from '@deepseek-ai/dsh-client-web-react'
|
||||
import type {
|
||||
SessionId, SessionListState, SessionsService, SlotsService,
|
||||
} from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { LayoutService } from '@deepseek-ai/dsh-client-ui-layout/client'
|
||||
import type { I18nService } from '@deepseek-ai/dsh-client-i18n/client'
|
||||
import type { ConvViewProps, SelectionTarget, ViewEntry, ViewId } from './contract/views.ts'
|
||||
import type { ConversationInjected, DetailsInjected, EmptyStateInjected } from './contract/slots.ts'
|
||||
import { ConversationService } from './service.ts'
|
||||
import { ToolViewRegistry } from './toolviews/registry.ts'
|
||||
import { childSessionScope, registerChat } from './chat/register.ts'
|
||||
import { registerBashSamples } from './toolviews/bash-sample.tsx'
|
||||
import { ConversationRoot } from './skeleton/ConversationRoot.tsx'
|
||||
import { DetailsPanel } from './skeleton/DetailsPanel.tsx'
|
||||
import { EmptyState } from './skeleton/EmptyState.tsx'
|
||||
|
||||
/** Required services (cordis fiber inject — the loader passes the whole export surface as an object plugin). */
|
||||
export const inject = ['slots', 'layout', 'sessions', 'i18n']
|
||||
|
||||
/** Resolve a service via ctx.get, failing loud. Property access is reserved
|
||||
* for contexts whose fiber declares the inject (scope fibers do not). */
|
||||
// T is the caller-named cast target; inlining `as T` per call site would scatter the budgeted cast.
|
||||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
|
||||
function need<T>(ctx: Context, name: string): T {
|
||||
const value = ctx.get(name) as T | undefined
|
||||
if (value === undefined) throw new Error(`ui-conversation: ${name} service unavailable`)
|
||||
return value
|
||||
}
|
||||
|
||||
/** Per-list-state cwd set (deduped, list order) for the empty-state picker. */
|
||||
const cwdsCache = new WeakMap<SessionListState, readonly string[]>()
|
||||
function cwdsOf(state: SessionListState): readonly string[] {
|
||||
let cached = cwdsCache.get(state)
|
||||
if (cached === undefined) {
|
||||
const seen = new Set<string>()
|
||||
for (const id of state.ids) {
|
||||
const cwd = state.byId[id]?.cwd
|
||||
if (cwd !== undefined && cwd !== '') seen.add(cwd)
|
||||
}
|
||||
cached = [...seen]
|
||||
cwdsCache.set(state, cached)
|
||||
}
|
||||
return cached
|
||||
}
|
||||
|
||||
/**
|
||||
* Client plugin body.
|
||||
* @param ctx - client root context.
|
||||
*/
|
||||
export function apply(ctx: Context): void {
|
||||
const sessions = need<SessionsService>(ctx, 'sessions')
|
||||
const layout = need<LayoutService>(ctx, 'layout')
|
||||
const i18n = need<I18nService>(ctx, 'i18n')
|
||||
const slots = need<SlotsService>(ctx, 'slots')
|
||||
|
||||
const conversation = new ConversationService(ctx)
|
||||
const toolviews = new ToolViewRegistry()
|
||||
ctx.provide('toolviews', toolviews)
|
||||
|
||||
const t = i18n.bind('conversation')
|
||||
// Chat view + StatsLine footer; bash samples assembled here (apply is the
|
||||
// only cross-domain point — chat consumes the resolver face, samples come
|
||||
// from the toolviews domain). registerView inside registerChat is already
|
||||
// effect-scoped; the raw sample registrations need the effect wrapper to
|
||||
// ride the fiber cascade.
|
||||
ctx.effect(
|
||||
() => registerChat({ conversation, toolviews, t }),
|
||||
'ui-conversation: chat view')
|
||||
ctx.effect(
|
||||
() => registerBashSamples(toolviews, childSessionScope(sessions.list)),
|
||||
'ui-conversation: bash toolview samples')
|
||||
|
||||
// ConvViewProps.slots is ScopedSlots<never>: a real outlet with an empty
|
||||
// whitelist (uncallable by type, correct runtime shape for future grants).
|
||||
const emptySlots = scopedSlots<never>(slots.core)
|
||||
|
||||
/** conversation slot: skeleton surface assembled once per (entry x session). */
|
||||
const conversationInject = (b: SessionBinding): ConversationInjected => {
|
||||
const bctx = b.ctx as Context
|
||||
const scoped = need<ConversationService>(bctx, 'conversation')
|
||||
const id = b.sessionId as SessionId
|
||||
const useSession = b.session.useSelector as UseSession
|
||||
const selectionStore = scoped.selection
|
||||
const draftsStore = scoped.drafts
|
||||
const session = sessions.manager.get(id)
|
||||
// Watch-driven history pull: assembling the surface IS the watch signal
|
||||
// (once per entry x session; open() is idempotent and self-recovers).
|
||||
void session.open()
|
||||
|
||||
const viewProps: Omit<ConvViewProps, 'slots'> = {
|
||||
sessionId: id,
|
||||
useSession,
|
||||
useSelection: selectionStore.useSelector,
|
||||
actions: {
|
||||
openDetails: (target: SelectionTarget) => { scoped.openDetails(target) },
|
||||
loadOlder: () => { void session.loadOlder() },
|
||||
},
|
||||
}
|
||||
|
||||
const injected: ConversationInjected = {
|
||||
useAncestry: () => sessions.list.useSelector(
|
||||
() => sessions.ancestry(id),
|
||||
(a, b) => shallowEqual(a, b)),
|
||||
views: {
|
||||
list: () => conversation.views(),
|
||||
subscribe: fn => conversation.subscribeViews(fn),
|
||||
version: () => conversation.viewsVersion(),
|
||||
},
|
||||
// layout's viewFor value type is its own looser ViewId; the registry is
|
||||
// the runtime validator (unknown ids fall back to the first view).
|
||||
useActiveView: () => layout.current.useSelector(s => s.viewFor[id]) as ViewId | undefined,
|
||||
composer: {
|
||||
useDraft: () => draftsStore.useSelector(s => s),
|
||||
setDraft: (text) => { draftsStore.set(text) },
|
||||
send: (mode) => {
|
||||
const text = draftsStore.getSnapshot().trim()
|
||||
if (text === '') return
|
||||
// Optimistic clear with failure restore (choreography lives with the
|
||||
// sender; the business failure also lands in snapshot.promptError).
|
||||
draftsStore.set('')
|
||||
void scoped.send(text, mode).catch(() => {
|
||||
if (draftsStore.getSnapshot() === '') draftsStore.set(text)
|
||||
})
|
||||
},
|
||||
stop: () => {
|
||||
scoped.cancel().catch(() => {
|
||||
// Stop failure surfaces via snapshot.promptError; nothing to restore.
|
||||
})
|
||||
},
|
||||
},
|
||||
actions: {
|
||||
openView: (view: ViewId) => { layout.openView(id, view) },
|
||||
open: (target: SessionId) => { layout.open(target) },
|
||||
},
|
||||
renderView: (entry: ViewEntry): ReactNode => {
|
||||
const children: ReactNode[] = []
|
||||
if (entry.chrome?.header !== undefined) {
|
||||
children.push(createElement(entry.chrome.header, { key: 'header', sessionId: id, useSession }))
|
||||
}
|
||||
children.push(createElement(entry.component, { key: 'view', ...viewProps, slots: emptySlots }))
|
||||
if (entry.chrome?.footer !== undefined) {
|
||||
children.push(createElement(entry.chrome.footer, { key: 'footer', sessionId: id, useSession }))
|
||||
}
|
||||
return createElement(Fragment, null, ...children)
|
||||
},
|
||||
}
|
||||
return injected
|
||||
}
|
||||
|
||||
/** details slot: minimal selection-driven panel. */
|
||||
const detailsInject = (b: SessionBinding): DetailsInjected => {
|
||||
const bctx = b.ctx as Context
|
||||
const scoped = need<ConversationService>(bctx, 'conversation')
|
||||
const injected: DetailsInjected = {
|
||||
useSelection: scoped.selection.useSelector,
|
||||
actions: { closeDetails: () => { layout.closeDetails() } },
|
||||
}
|
||||
return injected
|
||||
}
|
||||
|
||||
/** conversation.empty root slot: the NEW SESSION hero. */
|
||||
const emptyInject = (): EmptyStateInjected => {
|
||||
const useCwds: SnapshotSelectorHook<readonly string[]> = (sel, eq) =>
|
||||
sessions.list.useSelector(s => sel(cwdsOf(s)), eq)
|
||||
const injected: EmptyStateInjected = {
|
||||
useCwds,
|
||||
actions: { startSession: opts => conversation.startSession(opts) },
|
||||
}
|
||||
return injected
|
||||
}
|
||||
|
||||
slots.register('conversation', ConversationRoot, { inject: conversationInject })
|
||||
slots.register('details', DetailsPanel, { inject: detailsInject })
|
||||
slots.register('conversation.empty', EmptyState, { inject: emptyInject })
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/* Assistant flow body: full-width narration (figma 16/28), block gap 16. */
|
||||
|
||||
.root {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
font-size: 16px;
|
||||
line-height: 28px;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
}
|
||||
|
||||
.pulse {
|
||||
display: inline-block;
|
||||
width: 8px;
|
||||
height: 14px;
|
||||
background: var(--dsw-alias-state-business-primary);
|
||||
animation: pulse 1s infinite ease-in-out;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
50% { opacity: 0.2; }
|
||||
}
|
||||
|
||||
/* Interrupted-turn terminal marker: quiet inline tag, no animation. */
|
||||
.stopped {
|
||||
align-self: flex-start;
|
||||
padding: 0 6px;
|
||||
border-radius: 6px;
|
||||
background: var(--dsw-alias-interactive-bg-hover);
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
font-size: 11px;
|
||||
line-height: 18px;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// AssistantMarkdown: renders assistant blocks in order — markdown text body,
|
||||
// reasoning as the figma Think summary row (expand = indented gray text),
|
||||
// other-block JSON fallback. Tool-call heads are NOT rendered here: the chat
|
||||
// view groups them into tool rows via the toolview outlet (figma step-summary
|
||||
// flow). Shared by finalized nodes and the streaming partial (pulse marker).
|
||||
|
||||
import { memo } from 'react'
|
||||
import type { AssistantBlock } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { IconThinkOutline14, JsonBlock, MessageText } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { ToolRow } from './ToolRow.tsx'
|
||||
import css from './AssistantMarkdown.module.css'
|
||||
|
||||
export interface AssistantMarkdownProps {
|
||||
blocks: readonly AssistantBlock[]
|
||||
streaming: boolean
|
||||
/** Frozen partial of an aborted turn: rendered with a 已停止 marker, no pulse. */
|
||||
interrupted?: boolean | undefined
|
||||
}
|
||||
|
||||
function firstLine(text: string): string {
|
||||
const nl = text.indexOf('\n')
|
||||
return nl === -1 ? text : text.slice(0, nl)
|
||||
}
|
||||
|
||||
/** Reasoning block as the Think variant summary row (figma 39:28304). */
|
||||
function ThinkRow({ text, running }: { text: string; running: boolean }) {
|
||||
return (
|
||||
<ToolRow
|
||||
variant="think"
|
||||
icon={<IconThinkOutline14 />}
|
||||
title="Think"
|
||||
summary={firstLine(text)}
|
||||
body={text}
|
||||
state={running ? 'running' : 'ok'}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export const AssistantMarkdown = memo(function AssistantMarkdown({ blocks, streaming, interrupted }: AssistantMarkdownProps) {
|
||||
const last = blocks.length - 1
|
||||
return (
|
||||
<div className={css.root} data-streaming={streaming || undefined}>
|
||||
{blocks.map((block, i) => {
|
||||
switch (block.kind) {
|
||||
case 'text': return <MessageText key={i} text={block.text} />
|
||||
case 'reasoning': return <ThinkRow key={i} text={block.text} running={streaming && i === last} />
|
||||
// Tool-call heads render as tool rows in the chat view's grouping pass.
|
||||
case 'tool-call': return null
|
||||
default: return <JsonBlock key={i} label="未知内容块" payload={block.block} />
|
||||
}
|
||||
})}
|
||||
{streaming && <span className={css.pulse} />}
|
||||
{interrupted && <span className={css.stopped}>已停止</span>}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,101 @@
|
||||
/* Chat flow: block gap 16 between narration/bubbles/tool groups (figma);
|
||||
tool rows inside a group gap 10. Input padding cap rides the skeleton. */
|
||||
|
||||
.root {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
|
||||
.scroll {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding: 16px 24px;
|
||||
}
|
||||
|
||||
/* Message column: 736px fixed width, centered on the same axis as the
|
||||
input box; the scroller itself stays full-bleed. */
|
||||
.column {
|
||||
max-width: 736px;
|
||||
width: 100%;
|
||||
margin: 0 auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.toolGroup {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.callRow {
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
/* Selection linkage: the selected call row wears the blue outline.
|
||||
button-info-fill flips 500→400 with the theme, hitting the darker-blue
|
||||
dark-mode spec exactly (business-primary stays 500 on both). */
|
||||
.callRow[data-selected] {
|
||||
outline: 1.5px solid var(--dsw-alias-button-info-fill);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
|
||||
.hint {
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
.openError {
|
||||
color: var(--dsw-alias-state-error-primary);
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
.older {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.older button {
|
||||
border: none;
|
||||
border-radius: 14px;
|
||||
padding: 4px 12px;
|
||||
font-size: 12px;
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
background: var(--dsw-alias-interactive-bg-hover-solid);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.older button:disabled {
|
||||
cursor: default;
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
/* Back-to-bottom: 34px circular icon button at the column's right edge. */
|
||||
.toBottom {
|
||||
position: absolute;
|
||||
right: max(24px, calc((100% - 736px) / 2));
|
||||
bottom: 16px;
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0;
|
||||
border: 1px solid var(--dsw-alias-border-l2);
|
||||
border-radius: 100px;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
background: var(--dsw-alias-button-floating-fill);
|
||||
box-shadow: var(--dsw-shadow-lv2);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.toBottom:hover {
|
||||
background: var(--dsw-alias-button-floating-hover);
|
||||
}
|
||||
293
packages/client/ui-conversation/src/client/chat/ChatView.tsx
Normal file
293
packages/client/ui-conversation/src/client/chat/ChatView.tsx
Normal file
@@ -0,0 +1,293 @@
|
||||
// ChatView: the default conversation view — message flow with user bubbles,
|
||||
// assistant narration, tool summary rows grouped into step runs, pending
|
||||
// cards, paging and bottom-follow. Created via factory so plugin deps
|
||||
// (toolviews registry, i18n) arrive by closure, never by import.
|
||||
//
|
||||
// Render economics (architecture RFC performance model): the list parent
|
||||
// subscribes to snapshot segments that do NOT change per streaming chunk
|
||||
// (nodes/runningCalls/pending keep their references across chunk batches), so
|
||||
// during a token storm only StreamingTail re-renders; history rows hold via
|
||||
// memo on cache-stable node slices. Selection changes re-render the parent
|
||||
// map but only rows whose own selected bit flipped.
|
||||
|
||||
import {
|
||||
memo, useLayoutEffect, useMemo, useRef, useState, type FC, type ReactNode,
|
||||
} from 'react'
|
||||
import type {
|
||||
ConversationNode, ConversationSnapshot, RunningToolCall, SessionId, ToolResultNode,
|
||||
} from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { SnapshotSelectorHook } from '@deepseek-ai/dsh-client-web-react'
|
||||
import { IconChevronDownOutline14 } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { ConvViewProps, SelectionTarget, Translate } from '../contract/views.ts'
|
||||
import type { ToolViewProps } from '../contract/toolview.ts'
|
||||
import type { ToolViewResolver } from '../contract/toolview.ts'
|
||||
import { deriveChatFlow, type ChatFlowItem } from './chat-flow.ts'
|
||||
import { AssistantMarkdown } from './AssistantMarkdown.tsx'
|
||||
import { MessageItem } from './MessageItem.tsx'
|
||||
import { PendingCard } from './PendingCard.tsx'
|
||||
import { ToolViewOutlet } from './ToolViewOutlet.tsx'
|
||||
import css from './ChatView.module.css'
|
||||
|
||||
/** Plugin-supplied closure deps (assembled in registerChat, apply world). */
|
||||
export interface ChatViewDeps {
|
||||
toolviews: ToolViewResolver
|
||||
t: Translate
|
||||
}
|
||||
|
||||
const FOLLOW_THRESHOLD = 24
|
||||
|
||||
type OpenDetails = (target: SelectionTarget) => void
|
||||
|
||||
/** web-react's UseSession is deliberately wide (dependency direction); the
|
||||
* chat view narrows once to the runtime snapshot the binding actually feeds. */
|
||||
type UseConversation = SnapshotSelectorHook<ConversationSnapshot>
|
||||
|
||||
/** One tool call row (result or running): builds the bound ToolViewProps. */
|
||||
const CallRow = memo(function CallRow({ registry, sessionId, useSession, t, callId, toolName, block, seq, onOpenDetails, selected }: {
|
||||
registry: ToolViewResolver
|
||||
sessionId: SessionId
|
||||
useSession: ConvViewProps['useSession']
|
||||
t: Translate
|
||||
callId: string
|
||||
toolName: string
|
||||
block: ToolResultNode | RunningToolCall
|
||||
/** Surface seq for finalized results; the call's turn for running calls. */
|
||||
seq: number
|
||||
onOpenDetails: OpenDetails
|
||||
selected: boolean
|
||||
}) {
|
||||
const viewProps = useMemo<ToolViewProps>(() => ({
|
||||
callId, toolName, block, useSession,
|
||||
actions: { openDetails: () => onOpenDetails({ turnSeq: seq, callId, toolName }) },
|
||||
t,
|
||||
}), [callId, toolName, block, useSession, seq, onOpenDetails, t])
|
||||
return (
|
||||
<div className={css.callRow} data-selected={selected || undefined}>
|
||||
<ToolViewOutlet registry={registry} sessionId={sessionId} toolName={toolName} viewProps={viewProps} />
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
/** Consecutive tool results as one step-run group (figma VERTICAL gap10). */
|
||||
const ToolGroup = memo(function ToolGroup({ registry, sessionId, useSession, t, results, onOpenDetails, selectedCallId }: {
|
||||
registry: ToolViewResolver
|
||||
sessionId: SessionId
|
||||
useSession: ConvViewProps['useSession']
|
||||
t: Translate
|
||||
results: readonly ToolResultNode[]
|
||||
onOpenDetails: OpenDetails
|
||||
/** Only set when the selected call lives in THIS group (memo economy). */
|
||||
selectedCallId: string | undefined
|
||||
}) {
|
||||
return (
|
||||
<div className={css.toolGroup}>
|
||||
{results.map((node) => (
|
||||
<CallRow
|
||||
key={node.callId}
|
||||
registry={registry}
|
||||
sessionId={sessionId}
|
||||
useSession={useSession}
|
||||
t={t}
|
||||
callId={node.callId}
|
||||
toolName={node.call?.name ?? ''}
|
||||
block={node}
|
||||
seq={node.seq}
|
||||
onOpenDetails={onOpenDetails}
|
||||
selected={node.callId === selectedCallId}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
/** The streaming partial, isolated so chunk batches re-render only this tail.
|
||||
* onGrow lets the scroll owner follow content the parent never re-renders for. */
|
||||
function StreamingTail({ useSession, onGrow }: {
|
||||
useSession: UseConversation
|
||||
onGrow: () => void
|
||||
}) {
|
||||
const partial = useSession((s) => s.partial)
|
||||
useLayoutEffect(() => {
|
||||
onGrow()
|
||||
})
|
||||
if (partial === null) return null
|
||||
return <AssistantMarkdown blocks={partial.blocks} streaming />
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the chat view component over plugin deps.
|
||||
* @param deps - toolview registry and bound translator.
|
||||
* @returns the ConvViewProps component registered as the chat view.
|
||||
*/
|
||||
export function createChatView(deps: ChatViewDeps): FC<ConvViewProps> {
|
||||
const { toolviews, t } = deps
|
||||
|
||||
return function ChatView({ sessionId, useSession: useSessionWide, useSelection, actions }: ConvViewProps) {
|
||||
const useSession = useSessionWide as UseConversation
|
||||
const nodes = useSession((s) => s.nodes)
|
||||
const runningCalls = useSession((s) => s.runningCalls)
|
||||
const pending = useSession((s) => s.pending)
|
||||
const openState = useSession((s) => s.openState)
|
||||
const openErrorMessage = useSession((s) => s.openError === null ? null : `${s.openError.message}(${s.openError.code})`)
|
||||
const hasMore = useSession((s) => s.hasMore)
|
||||
const loadingOlder = useSession((s) => s.loadingOlder)
|
||||
const selectedCallId = useSelection((sel) => sel?.callId)
|
||||
|
||||
const items = useMemo(() => deriveChatFlow(nodes), [nodes])
|
||||
|
||||
const listRef = useRef<HTMLDivElement | null>(null)
|
||||
const atBottomRef = useRef(true)
|
||||
const [atBottom, setAtBottom] = useState(true)
|
||||
/** Paging anchor: height/position at click, compensated after the prepend lands. */
|
||||
const anchorRef = useRef<{ h: number; t: number } | null>(null)
|
||||
const firstSeqRef = useRef<number | null>(null)
|
||||
const openedRef = useRef(false)
|
||||
const lastKeyRef = useRef<string | null>(null)
|
||||
|
||||
const firstSeq = nodes[0]?.seq ?? null
|
||||
const lastItem = items[items.length - 1]
|
||||
|
||||
const toBottom = (el: HTMLDivElement): void => {
|
||||
el.scrollTop = el.scrollHeight
|
||||
atBottomRef.current = true
|
||||
setAtBottom(true)
|
||||
}
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = listRef.current
|
||||
/* v8 ignore next -- ref-null guard: React attaches the ref before layout effects run. */
|
||||
if (el === null) return
|
||||
// Open completed: jump to the bottom once.
|
||||
if (openState === 'open' && !openedRef.current) {
|
||||
openedRef.current = true
|
||||
toBottom(el)
|
||||
firstSeqRef.current = firstSeq
|
||||
lastKeyRef.current = lastItem?.key ?? null
|
||||
return
|
||||
}
|
||||
// Prepend (head seq decreased): compensate by the height delta.
|
||||
if (anchorRef.current !== null && firstSeq !== null && firstSeqRef.current !== null && firstSeq < firstSeqRef.current) {
|
||||
el.scrollTop = anchorRef.current.t + (el.scrollHeight - anchorRef.current.h)
|
||||
anchorRef.current = null
|
||||
firstSeqRef.current = firstSeq
|
||||
/* v8 ignore next -- ?? arm: a prepend adds nodes, so the flow list here is never empty. */
|
||||
lastKeyRef.current = lastItem?.key ?? null
|
||||
return
|
||||
}
|
||||
firstSeqRef.current = firstSeq
|
||||
// Own words must be visible: a new trailing user node force-scrolls
|
||||
// (send lives in the composer, so arrival is detected here, not armed there).
|
||||
const lastKey = lastItem?.key ?? null
|
||||
const appendedUser = lastKey !== lastKeyRef.current
|
||||
&& lastItem !== undefined && lastItem.kind === 'node' && lastItem.node.kind === 'user'
|
||||
lastKeyRef.current = lastKey
|
||||
if (appendedUser || atBottomRef.current) toBottom(el)
|
||||
})
|
||||
|
||||
const onScroll = (): void => {
|
||||
const el = listRef.current
|
||||
/* v8 ignore next -- ref-null guard: the handler only fires on the mounted element. */
|
||||
if (el === null) return
|
||||
const isAtBottom = el.scrollHeight - el.scrollTop - el.clientHeight <= FOLLOW_THRESHOLD + 1
|
||||
atBottomRef.current = isAtBottom
|
||||
setAtBottom(isAtBottom)
|
||||
}
|
||||
|
||||
// Follow streaming growth the parent never re-renders for (stable ref).
|
||||
// The ref starts null and is assigned every render, so the placeholder
|
||||
// initializer a function initial value would need never exists.
|
||||
const followRef = useRef<(() => void) | null>(null)
|
||||
followRef.current = () => {
|
||||
const el = listRef.current
|
||||
if (el !== null && atBottomRef.current) el.scrollTop = el.scrollHeight
|
||||
}
|
||||
const onGrow = useRef(() => followRef.current?.()).current
|
||||
|
||||
const loadOlder = (): void => {
|
||||
const el = listRef.current
|
||||
/* v8 ignore next -- ref-null guard: the paging button renders inside the list tree. */
|
||||
if (el !== null) anchorRef.current = { h: el.scrollHeight, t: el.scrollTop }
|
||||
actions.loadOlder()
|
||||
}
|
||||
|
||||
const renderItem = (item: ChatFlowItem): ReactNode => {
|
||||
if (item.kind === 'tool-group') {
|
||||
const inGroup = selectedCallId !== undefined
|
||||
&& item.results.some((r) => r.callId === selectedCallId)
|
||||
return (
|
||||
<ToolGroup
|
||||
key={item.key}
|
||||
registry={toolviews}
|
||||
sessionId={sessionId}
|
||||
useSession={useSession}
|
||||
t={t}
|
||||
results={item.results}
|
||||
onOpenDetails={actions.openDetails}
|
||||
selectedCallId={inGroup ? selectedCallId : undefined}
|
||||
/>
|
||||
)
|
||||
}
|
||||
const node: ConversationNode = item.node
|
||||
if (node.kind === 'assistant') {
|
||||
return <AssistantMarkdown key={item.key} blocks={node.blocks} streaming={false} interrupted={node.interrupted} />
|
||||
}
|
||||
/* v8 ignore next -- tool-result never reaches here: deriveChatFlow folds them into groups. */
|
||||
if (node.kind === 'tool-result') return null
|
||||
return <MessageItem key={item.key} node={node} />
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={css.root}>
|
||||
<div ref={listRef} className={css.scroll} onScroll={onScroll}>
|
||||
<div className={css.column}>
|
||||
{openState === 'loading' && <div className={css.hint}>载入历史…</div>}
|
||||
{openState === 'error' && <div className={css.openError}>历史加载失败:{openErrorMessage}</div>}
|
||||
{hasMore && (
|
||||
<div className={css.older}>
|
||||
<button type="button" disabled={loadingOlder} onClick={loadOlder}>
|
||||
{loadingOlder ? '加载中…' : '加载更早'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{items.map(renderItem)}
|
||||
<StreamingTail useSession={useSession} onGrow={onGrow} />
|
||||
{runningCalls.length > 0 && (
|
||||
<div className={css.toolGroup}>
|
||||
{runningCalls.map((call) => (
|
||||
<CallRow
|
||||
key={call.callId}
|
||||
registry={toolviews}
|
||||
sessionId={sessionId}
|
||||
useSession={useSession}
|
||||
t={t}
|
||||
callId={call.callId}
|
||||
toolName={call.name}
|
||||
block={call}
|
||||
seq={call.turn}
|
||||
onOpenDetails={actions.openDetails}
|
||||
selected={call.callId === selectedCallId}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{pending.map((item) => <PendingCard key={item.rpcId} item={item} />)}
|
||||
</div>
|
||||
</div>
|
||||
{!atBottom && (
|
||||
<button
|
||||
type="button"
|
||||
className={css.toBottom}
|
||||
aria-label="回到底部"
|
||||
onClick={() => {
|
||||
const el = listRef.current
|
||||
/* v8 ignore next -- ref-null guard: the button only renders alongside the mounted list. */
|
||||
if (el !== null) toBottom(el)
|
||||
}}
|
||||
>
|
||||
<IconChevronDownOutline14 />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// GenericToolCard: the registry-miss fallback toolview — classifies the tool
|
||||
// into one of the five figma row variants and renders the summary row. Also
|
||||
// the shared base the bash sample builds on: any ToolViewProps consumer.
|
||||
|
||||
import type { ReactNode } from 'react'
|
||||
import {
|
||||
IconApiOutline14, IconBrowseOutline16, IconSearchOutline16, IconThinkOutline14,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { ToolViewProps } from '../contract/toolview.ts'
|
||||
import { toolRowModel, type ToolCallBlock, type ToolRowVariant } from '../contract/tool-call-model.ts'
|
||||
import { ToolRow } from './ToolRow.tsx'
|
||||
import { IconSparkle16 } from './IconSparkle16.tsx'
|
||||
|
||||
/** Variant leading icons (figma table). */
|
||||
const VARIANT_ICONS: Record<ToolRowVariant, ReactNode> = {
|
||||
think: <IconThinkOutline14 />,
|
||||
search: <IconSearchOutline16 />,
|
||||
read: <IconBrowseOutline16 />,
|
||||
bash: <IconApiOutline14 size={16} />,
|
||||
others: <IconSparkle16 />,
|
||||
}
|
||||
|
||||
export function GenericToolCard({ toolName, block, actions }: ToolViewProps) {
|
||||
const model = toolRowModel(toolName, block as ToolCallBlock)
|
||||
return (
|
||||
<ToolRow
|
||||
variant={model.variant}
|
||||
icon={VARIANT_ICONS[model.variant]}
|
||||
title={model.title}
|
||||
summary={model.summary}
|
||||
body={model.body}
|
||||
state={model.state}
|
||||
onOpenDetails={actions.openDetails}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// Local sparkle icon for the Others tool-row variant (figma 43:31850 leading
|
||||
// glyph is an SF Symbols "sparkles" text glyph — not extractable as vector
|
||||
// data, so this is a hand-authored three-star approximation). Lives here
|
||||
// rather than ui-primitives until the exact glyph is exported and adopted
|
||||
// into the ic_ds_* family.
|
||||
|
||||
export function IconSparkle16({ size = 16, className }: { size?: number; className?: string }) {
|
||||
return (
|
||||
<svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M6.1 3.1Q6.6 7.8 11.3 8.3Q6.6 8.8 6.1 13.5Q5.6 8.8 0.9 8.3Q5.6 7.8 6.1 3.1Z" fill="currentColor" />
|
||||
<path d="M11.9 1Q12.2 3.7 14.9 4Q12.2 4.3 11.9 7Q11.6 4.3 8.9 4Q11.6 3.7 11.9 1Z" fill="currentColor" />
|
||||
<path d="M12.5 9.4Q12.7 11.4 14.7 11.6Q12.7 11.8 12.5 13.8Q12.3 11.8 10.3 11.6Q12.3 11.4 12.5 9.4Z" fill="currentColor" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/* User bubble: right-aligned, figma r22 fill = the bubble specific token
|
||||
(#EDF3FE light / dark pair rides the token sheet). */
|
||||
|
||||
/* Block spacing is the flow column's gap alone — no extra padding here. */
|
||||
.userRow {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.bubble {
|
||||
/* 525px cap inside the 736 column; percentage keeps narrow windows sane. */
|
||||
max-width: min(525px, 82%);
|
||||
background: var(--dsw-specific-bubble);
|
||||
border-radius: 22px;
|
||||
/* 44px single-line bubble: 24 line + 10 vertical padding each side. */
|
||||
padding: 10px 16px;
|
||||
font-size: 16px;
|
||||
line-height: 24px;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
}
|
||||
|
||||
.badge {
|
||||
display: inline-block;
|
||||
margin-bottom: 4px;
|
||||
padding: 1px 6px;
|
||||
border-radius: 6px;
|
||||
background: var(--dsw-alias-state-warn-primary);
|
||||
color: var(--dsw-alias-label-primary-foreground);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.contextRow {
|
||||
padding: 2px 0;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// MessageItem: the four simple node kinds — user bubble (right-aligned),
|
||||
// steering (badged bubble), context injection and unknown-surface JSON rows.
|
||||
// Props are frozen node slices off the snapshot cache; memo holds across
|
||||
// streaming because unchanged nodes keep their references.
|
||||
|
||||
import { memo } from 'react'
|
||||
import type {
|
||||
ContextMessageNode, SteeringMessageNode, UnknownSurfaceNode, UserMessageNode,
|
||||
} from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { JsonBlock, MessageText } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import css from './MessageItem.module.css'
|
||||
|
||||
export interface MessageItemProps {
|
||||
node: UserMessageNode | SteeringMessageNode | ContextMessageNode | UnknownSurfaceNode
|
||||
}
|
||||
|
||||
function contentText(content: readonly unknown[]): { text: string; rest: unknown[] } {
|
||||
const texts: string[] = []
|
||||
const rest: unknown[] = []
|
||||
for (const block of content) {
|
||||
const b = block as { type?: string; text?: string }
|
||||
if (b.type === 'text' && typeof b.text === 'string') texts.push(b.text)
|
||||
else rest.push(block)
|
||||
}
|
||||
return { text: texts.join(''), rest }
|
||||
}
|
||||
|
||||
export const MessageItem = memo(function MessageItem({ node }: MessageItemProps) {
|
||||
switch (node.kind) {
|
||||
case 'user':
|
||||
case 'steering': {
|
||||
const { text, rest } = contentText(node.content)
|
||||
return (
|
||||
<div className={css.userRow}>
|
||||
<div className={css.bubble}>
|
||||
{node.kind === 'steering' && <span className={css.badge}>插话</span>}
|
||||
<MessageText text={text} />
|
||||
{rest.map((block, i) => <JsonBlock key={i} label="附加内容块" payload={block} />)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
case 'context':
|
||||
return (
|
||||
<div className={css.contextRow}>
|
||||
<JsonBlock label="上下文注入" payload={{ content: node.content, meta: node.meta }} />
|
||||
</div>
|
||||
)
|
||||
default:
|
||||
return (
|
||||
<div className={css.contextRow}>
|
||||
<JsonBlock label={`未知 surface 事件:${node.type}`} payload={node.data} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,31 @@
|
||||
/* Amber pending strip (approval waiting = warn semantic, figma state colors). */
|
||||
|
||||
.card {
|
||||
margin: 6px 0;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid var(--dsw-alias-state-warn-secondary);
|
||||
border-radius: 10px;
|
||||
background: var(--dsw-alias-state-warn-tertiary);
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
}
|
||||
|
||||
.mono {
|
||||
font-family: var(--ds-font-family-code);
|
||||
}
|
||||
|
||||
.reason {
|
||||
margin-top: 4px;
|
||||
font-size: 12px;
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
}
|
||||
|
||||
.hint {
|
||||
margin-top: 6px;
|
||||
font-size: 11px;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// PendingCard: approval/question placeholder card (visible, not answerable —
|
||||
// the composer-takeover approval panel is a P-II item; wire pending semantics
|
||||
// already exist so the flow must show them).
|
||||
|
||||
import { memo } from 'react'
|
||||
import type { PendingInteraction } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { JsonBlock } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import css from './PendingCard.module.css'
|
||||
|
||||
export interface PendingCardProps {
|
||||
item: PendingInteraction
|
||||
}
|
||||
|
||||
export const PendingCard = memo(function PendingCard({ item }: PendingCardProps) {
|
||||
return (
|
||||
<div className={css.card}>
|
||||
{item.kind === 'approval' ? (
|
||||
<>
|
||||
<div className={css.title}>等待审批:<span className={css.mono}>{item.toolName}</span></div>
|
||||
{item.reason !== undefined && <div className={css.reason}>{item.reason}</div>}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className={css.title}>等待回答({item.questions.length} 题)</div>
|
||||
<JsonBlock label="问题内容" payload={item.questions} />
|
||||
</>
|
||||
)}
|
||||
<div className={css.hint}>请在原客户端处理(web 端作答后续里程碑提供)</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,13 @@
|
||||
/* Session stats row: 12/20 tertiary text under the flow, aligned to the
|
||||
736px message column axis. */
|
||||
|
||||
.root {
|
||||
max-width: 736px;
|
||||
width: 100%;
|
||||
margin: 0 auto;
|
||||
box-sizing: border-box;
|
||||
padding: 4px 24px 8px;
|
||||
font-size: 12px;
|
||||
line-height: 20px;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
// StatsLine: the session stats row (figma 122:11212 "cache hit 92% · 1,284
|
||||
// tokens · 45.2s · 5 turns · 32 steps"), mounted as the chat view's
|
||||
// chrome.footer — the first chrome-attachment consumer. Duration has no data
|
||||
// source in P-I (ledger). Subscribes to `nodes` only: chunk batches never swap
|
||||
// that reference, so the row renders zero times during streaming (the RFC
|
||||
// performance model's acceptance row).
|
||||
|
||||
import { memo, useMemo } from 'react'
|
||||
import type { ConversationSnapshot } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { SnapshotSelectorHook } from '@deepseek-ai/dsh-client-web-react'
|
||||
import type { ChromeProps } from '../contract/views.ts'
|
||||
import css from './StatsLine.module.css'
|
||||
|
||||
interface UsageTotals {
|
||||
turns: number
|
||||
steps: number
|
||||
tokens: number
|
||||
cacheHitPct: number | null
|
||||
}
|
||||
|
||||
/** Token accounting slice of assistant `usage` (typed upstream as unknown). */
|
||||
interface UsageLike {
|
||||
inputTokens?: number
|
||||
outputTokens?: number
|
||||
cacheReadTokens?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Fold assistant nodes into display totals.
|
||||
* @param nodes - snapshot nodes.
|
||||
* @returns totals; cacheHitPct null until any cache accounting arrives.
|
||||
*/
|
||||
export function deriveStats(nodes: ConversationSnapshot['nodes']): UsageTotals {
|
||||
const turns = new Set<number>()
|
||||
let steps = 0
|
||||
let tokens = 0
|
||||
let input = 0
|
||||
let cacheRead = 0
|
||||
for (const node of nodes) {
|
||||
if (node.kind !== 'assistant') continue
|
||||
turns.add(node.turn)
|
||||
steps += 1
|
||||
const usage = node.usage as UsageLike | undefined
|
||||
if (usage === undefined) continue
|
||||
input += usage.inputTokens ?? 0
|
||||
cacheRead += usage.cacheReadTokens ?? 0
|
||||
tokens += (usage.inputTokens ?? 0) + (usage.outputTokens ?? 0) + (usage.cacheReadTokens ?? 0)
|
||||
}
|
||||
const denom = input + cacheRead
|
||||
return {
|
||||
turns: turns.size,
|
||||
steps,
|
||||
tokens,
|
||||
cacheHitPct: denom === 0 ? null : Math.round((cacheRead / denom) * 100),
|
||||
}
|
||||
}
|
||||
|
||||
export const StatsLine = memo(function StatsLine({ useSession }: ChromeProps) {
|
||||
const nodes = (useSession as SnapshotSelectorHook<ConversationSnapshot>)((s) => s.nodes)
|
||||
const stats = useMemo(() => deriveStats(nodes), [nodes])
|
||||
if (stats.steps === 0) return null
|
||||
const parts: string[] = []
|
||||
if (stats.cacheHitPct !== null) parts.push(`cache hit ${stats.cacheHitPct}%`)
|
||||
parts.push(`${stats.tokens.toLocaleString('en-US')} tokens`)
|
||||
parts.push(`${stats.turns} turns`)
|
||||
parts.push(`${stats.steps} steps`)
|
||||
return <div className={css.root}>{parts.join(' · ')}</div>
|
||||
})
|
||||
@@ -0,0 +1,88 @@
|
||||
/* Tool summary row (figma 122:9479): 24px single line —
|
||||
[16 leading] gap6 [title 14/24] gap8 [2x2 dot] gap8 [summary FILL truncate]. */
|
||||
|
||||
.root {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: 24px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.row[data-clickable] {
|
||||
cursor: pointer;
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.row[data-clickable]:hover {
|
||||
background: var(--dsw-alias-interactive-bg-hover);
|
||||
}
|
||||
|
||||
.leading {
|
||||
flex: none;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin-right: 6px;
|
||||
padding: 0;
|
||||
border: none;
|
||||
background: none;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
}
|
||||
|
||||
/* The others-variant sparkle glyph is one gray step darker than the icon
|
||||
family in the source design. */
|
||||
.root[data-variant='others'] .leading {
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
}
|
||||
|
||||
button.leading {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.chevron {
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
}
|
||||
|
||||
.title {
|
||||
flex: none;
|
||||
font-size: 14px;
|
||||
line-height: 24px;
|
||||
color: var(--dsw-alias-label-primary-dimmed);
|
||||
}
|
||||
|
||||
.sep {
|
||||
flex: none;
|
||||
width: 2px;
|
||||
height: 2px;
|
||||
border-radius: 1px;
|
||||
margin: 0 8px;
|
||||
background: var(--dsw-alias-label-caption);
|
||||
}
|
||||
|
||||
.summary {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 14px;
|
||||
line-height: 24px;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
}
|
||||
|
||||
/* Expanded body: pad-left 22 indented gray text, no border, no fill. */
|
||||
.body {
|
||||
padding: 4px 0 4px 22px;
|
||||
font-size: 14px;
|
||||
line-height: 24px;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
}
|
||||
75
packages/client/ui-conversation/src/client/chat/ToolRow.tsx
Normal file
75
packages/client/ui-conversation/src/client/chat/ToolRow.tsx
Normal file
@@ -0,0 +1,75 @@
|
||||
// ToolRow: the single-line tool summary row (figma component set 122:9479) —
|
||||
// 16px leading slot (state dot / tool icon, chevron when expanded) + title +
|
||||
// separator dot + FILL-truncated summary. Expanded body is indented gray text;
|
||||
// no inline output (full results live in the details panel). Expand state is
|
||||
// component-local view state; row click hands the selection off to the owner.
|
||||
|
||||
import { useState, type ReactNode } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import { StateDot } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { IconChevronDownOutline14 } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { ToolRowState, ToolRowVariant } from '../contract/tool-call-model.ts'
|
||||
import css from './ToolRow.module.css'
|
||||
|
||||
export interface ToolRowProps {
|
||||
variant: ToolRowVariant
|
||||
/** Leading 16px tool icon, shown while collapsed and not running/failed. */
|
||||
icon: ReactNode
|
||||
title: string
|
||||
summary: string
|
||||
/** Expanded-body text; null = not expandable (leading slot never toggles). */
|
||||
body: string | null
|
||||
state: ToolRowState
|
||||
/** Selection handoff (row click), already bound to this call by the owner. */
|
||||
onOpenDetails?: (() => void) | undefined
|
||||
}
|
||||
|
||||
/** Leading-slot state substitution: the tool icon yields to the state semantic
|
||||
* (running = blue ring, error = red, interrupted = amber halo; ok = icon). */
|
||||
function leadingFor(state: ToolRowState, icon: ReactNode): ReactNode {
|
||||
switch (state) {
|
||||
case 'running': return <StateDot state="ongoing" />
|
||||
case 'error': return <StateDot state="error" />
|
||||
case 'stopped': return <StateDot state="warning" />
|
||||
default: return icon
|
||||
}
|
||||
}
|
||||
|
||||
export function ToolRow({ variant, icon, title, summary, body, state, onOpenDetails }: ToolRowProps) {
|
||||
const [expanded, setExpanded] = useState(false)
|
||||
const expandable = body !== null
|
||||
const open = expanded && expandable
|
||||
return (
|
||||
<div className={css.root} data-variant={variant} data-state={state}>
|
||||
<div
|
||||
className={css.row}
|
||||
data-clickable={onOpenDetails !== undefined || undefined}
|
||||
onClick={onOpenDetails}
|
||||
>
|
||||
{expandable ? (
|
||||
<button
|
||||
type="button"
|
||||
className={css.leading}
|
||||
aria-expanded={open}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setExpanded((v) => !v)
|
||||
}}
|
||||
>
|
||||
{open ? <IconChevronDownOutline14 className={clsx(css.chevron)} /> : leadingFor(state, icon)}
|
||||
</button>
|
||||
) : (
|
||||
<span className={css.leading}>{leadingFor(state, icon)}</span>
|
||||
)}
|
||||
<span className={css.title}>{title}</span>
|
||||
{!open && (
|
||||
<>
|
||||
<span className={css.sep} aria-hidden />
|
||||
<span className={css.summary}>{summary}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{open && <div className={css.body}>{body}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
// ToolViewOutlet: resolves the toolview for one call through ctx.toolviews
|
||||
// (uSES over the registry version so unload falls back live) and renders it
|
||||
// behind a per-row error boundary. GenericToolCard is the render-side
|
||||
// fallback for both a registry miss and a crashed custom row. A registrant
|
||||
// inject factory is called once per (registration x binding) and cached,
|
||||
// mirroring the scoped-slots injection discipline.
|
||||
|
||||
import { Component, useSyncExternalStore, type FC, type ReactNode } from 'react'
|
||||
import { useSessionBinding } from '@deepseek-ai/dsh-client-web-react'
|
||||
import type { SessionBinding } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { ToolViewInject, ToolViewProps, ToolViewResolver } from '../contract/toolview.ts'
|
||||
import { GenericToolCard } from './GenericToolCard.tsx'
|
||||
|
||||
export interface ToolViewOutletProps {
|
||||
registry: ToolViewResolver
|
||||
sessionId: SessionId
|
||||
toolName: string
|
||||
viewProps: ToolViewProps
|
||||
}
|
||||
|
||||
/** Inject cache: per inject-factory (stable per registration) x binding object. */
|
||||
const injectCache = new WeakMap<ToolViewInject<object>, WeakMap<object, object>>()
|
||||
|
||||
function cachedInject(inject: ToolViewInject<object>, binding: SessionBinding): object {
|
||||
let perBinding = injectCache.get(inject)
|
||||
if (!perBinding) {
|
||||
perBinding = new WeakMap()
|
||||
injectCache.set(inject, perBinding)
|
||||
}
|
||||
let props = perBinding.get(binding)
|
||||
if (!props) {
|
||||
props = inject(binding)
|
||||
perBinding.set(binding, props)
|
||||
}
|
||||
return props
|
||||
}
|
||||
|
||||
class RowErrorBoundary extends Component<
|
||||
{ resetKey: unknown; fallback: ReactNode; children: ReactNode }, { failed: boolean }
|
||||
> {
|
||||
override state = { failed: false }
|
||||
// Fallback state MUST flip here (render phase): a boundary whose derived
|
||||
// state does not change re-renders the crashing children and React gives
|
||||
// up after the second throw, escalating past the boundary.
|
||||
static getDerivedStateFromError(): { failed: boolean } {
|
||||
return { failed: true }
|
||||
}
|
||||
override componentDidCatch(error: unknown): void {
|
||||
console.error('toolview row crashed:', error)
|
||||
}
|
||||
// A re-registration (resetKey bump) retries the custom row.
|
||||
override componentDidUpdate(prev: { resetKey: unknown }): void {
|
||||
if (this.state.failed && prev.resetKey !== this.props.resetKey) {
|
||||
this.setState({ failed: false })
|
||||
}
|
||||
}
|
||||
override render(): ReactNode {
|
||||
if (this.state.failed) return this.props.fallback
|
||||
return this.props.children
|
||||
}
|
||||
}
|
||||
|
||||
/** Split component: only inject-carrying registrations need the session
|
||||
* binding hook (keeps injectless rendering free of the Provider requirement). */
|
||||
function InjectedRow({ Row, inject, viewProps }: {
|
||||
Row: FC<ToolViewProps & object>; inject: ToolViewInject<object>; viewProps: ToolViewProps
|
||||
}) {
|
||||
const binding = useSessionBinding()
|
||||
const injected = cachedInject(inject, binding)
|
||||
return <Row {...{ ...injected, ...viewProps }} />
|
||||
}
|
||||
|
||||
export function ToolViewOutlet({ registry, sessionId, toolName, viewProps }: ToolViewOutletProps) {
|
||||
const version = useSyncExternalStore(
|
||||
(fn) => registry.subscribe(fn),
|
||||
() => registry.getVersion(),
|
||||
)
|
||||
const resolved = registry.resolve(toolName, sessionId)
|
||||
if (resolved === undefined) return <GenericToolCard {...viewProps} />
|
||||
const Row = resolved.component
|
||||
return (
|
||||
<RowErrorBoundary resetKey={version} fallback={<GenericToolCard {...viewProps} />}>
|
||||
{resolved.inject === undefined
|
||||
? <Row {...viewProps} />
|
||||
: <InjectedRow Row={Row} inject={resolved.inject} viewProps={viewProps} />}
|
||||
</RowErrorBoundary>
|
||||
)
|
||||
}
|
||||
46
packages/client/ui-conversation/src/client/chat/chat-flow.ts
Normal file
46
packages/client/ui-conversation/src/client/chat/chat-flow.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Chat flow derivation: ConversationSnapshot nodes -> render items. Tool
|
||||
* results group into consecutive-run tool groups (figma step-summary flow,
|
||||
* VERTICAL gap10) alternating with narration; everything else passes through.
|
||||
* Item identity keys are stable across snapshots so the list parent can
|
||||
* subscribe to keys only while rows subscribe to content.
|
||||
*/
|
||||
import type { ConversationNode, ToolResultNode } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
|
||||
/** One renderable flow item; key is the React key and the parent's identity unit. */
|
||||
export type ChatFlowItem =
|
||||
| { kind: 'node'; key: string; node: ConversationNode }
|
||||
| { kind: 'tool-group'; key: string; results: readonly ToolResultNode[] }
|
||||
|
||||
/**
|
||||
* Group finalized nodes into the step-summary flow.
|
||||
* @param nodes - snapshot nodes (surface order).
|
||||
* @returns flow items; consecutive tool-results merged into one group keyed by the first seq.
|
||||
*/
|
||||
export function deriveChatFlow(nodes: readonly ConversationNode[]): ChatFlowItem[] {
|
||||
const items: ChatFlowItem[] = []
|
||||
let group: ToolResultNode[] | null = null
|
||||
for (const node of nodes) {
|
||||
if (node.kind === 'tool-result') {
|
||||
if (group === null) {
|
||||
group = [node]
|
||||
items.push({ kind: 'tool-group', key: `g${node.seq}`, results: group })
|
||||
} else {
|
||||
group.push(node)
|
||||
}
|
||||
} else {
|
||||
group = null
|
||||
items.push({ kind: 'node', key: `n${node.seq}`, node })
|
||||
}
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
/**
|
||||
* Key projection for the list parent's selector (content-blind identity).
|
||||
* @param items - derived flow items.
|
||||
* @returns joined key string usable with Object.is short-circuiting.
|
||||
*/
|
||||
export function flowKeys(items: readonly ChatFlowItem[]): string {
|
||||
return items.map(i => i.key).join('|')
|
||||
}
|
||||
52
packages/client/ui-conversation/src/client/chat/register.ts
Normal file
52
packages/client/ui-conversation/src/client/chat/register.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* Chat-side registration entry, called from the plugin apply (the assembly
|
||||
* point): registers the chat view with the stats-line footer chrome. The
|
||||
* chat domain touches the tool ring only through the contract resolver face;
|
||||
* bash sample registration moved to apply (cross-domain assembly).
|
||||
*/
|
||||
import type { SessionId, SessionListState } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { ConversationService } from '../service.ts'
|
||||
import type { Translate } from '../contract/views.ts'
|
||||
import type { ToolViewResolver } from '../contract/toolview.ts'
|
||||
import { createChatView } from './ChatView.tsx'
|
||||
import { StatsLine } from './StatsLine.tsx'
|
||||
|
||||
/** Read face of the sessions list store (subscription not needed: the filter
|
||||
* reads the latest snapshot at each resolve). */
|
||||
export interface SessionListReader { getSnapshot(): SessionListState }
|
||||
|
||||
/**
|
||||
* Default scoped-sample filter: the sub-session family. Sub-agent rows
|
||||
* rendering differently is the registry's canonical product scenario, and
|
||||
* forking gives W5 acceptance a real entry point to observe the differential.
|
||||
* @param list - injected sessions list read face.
|
||||
* @returns filter matching sessions with a parent.
|
||||
*/
|
||||
export function childSessionScope(list: SessionListReader): (sessionId: SessionId) => boolean {
|
||||
return sessionId => list.getSnapshot().byId[sessionId]?.parentId !== undefined
|
||||
}
|
||||
|
||||
/** Assembly inputs for {@link registerChat} (resolved by apply, not here). */
|
||||
export interface RegisterChatDeps {
|
||||
conversation: ConversationService
|
||||
/** Toolview read face consumed by the chat rows' outlet. */
|
||||
toolviews: ToolViewResolver
|
||||
/** Translator bound to the conversation namespace. */
|
||||
t: Translate
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the chat view (footer chrome included).
|
||||
* @param deps - assembled service instances.
|
||||
* @returns disposer removing the registration.
|
||||
*/
|
||||
export function registerChat(deps: RegisterChatDeps): () => void {
|
||||
const { conversation, toolviews, t } = deps
|
||||
return conversation.registerView({
|
||||
id: 'chat',
|
||||
label: 'Chat',
|
||||
order: 0,
|
||||
component: createChatView({ toolviews, t }),
|
||||
chrome: { footer: StatsLine },
|
||||
})
|
||||
}
|
||||
63
packages/client/ui-conversation/src/client/contract/slots.ts
Normal file
63
packages/client/ui-conversation/src/client/contract/slots.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* Slot-ring contract for the conversation package: the composed props shapes
|
||||
* its registrants mount into the layout-owned slots (conversation / details /
|
||||
* conversation.empty — the SlotMap declarations live with ui-layout, the
|
||||
* slot owner). Per the share-ownership rule, the owner share is REFERENCED
|
||||
* from ui-layout and each registrant's injected share is declared here, next
|
||||
* to the component that receives it; full component props = owner share &
|
||||
* standard share & own injected share.
|
||||
*/
|
||||
import type { ReactNode } from 'react'
|
||||
import type { SessionId, SessionSummary } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { SnapshotSelectorHook, UseSession } from '@deepseek-ai/dsh-client-web-react'
|
||||
import type { ConvOwnerProps, DetailsOwnerProps, EmptyOwnerProps } from '@deepseek-ai/dsh-client-ui-layout/client'
|
||||
import type { SelectionTarget, ViewEntry, ViewId } from './views.ts'
|
||||
|
||||
/** Injected share of the conversation slot (assembled by apply's inject factory). */
|
||||
export interface ConversationInjected {
|
||||
/** Breadcrumb chain (root ancestor first, self last; ancestry(list) feed). */
|
||||
useAncestry: () => readonly SessionSummary[]
|
||||
/** View registry read face (uSES triple from the conversation service). */
|
||||
views: {
|
||||
list(): readonly ViewEntry[]
|
||||
subscribe(fn: () => void): () => void
|
||||
version(): number
|
||||
}
|
||||
/** Active view accessor (layout.viewFor backed; undefined falls to 'chat'). */
|
||||
useActiveView: () => ViewId | undefined
|
||||
/** Composer surface: draft store hook pair + send/stop choreography. */
|
||||
composer: {
|
||||
useDraft: () => string
|
||||
setDraft(text: string): void
|
||||
send(mode: 'queue' | 'steer'): void
|
||||
stop(): void
|
||||
}
|
||||
actions: {
|
||||
openView(view: ViewId): void
|
||||
open(id: SessionId): void
|
||||
}
|
||||
/** Renders the active view's body (the owner closes over ConvViewProps assembly). */
|
||||
renderView: (entry: ViewEntry) => ReactNode
|
||||
}
|
||||
|
||||
/** Full conversation-slot component props: owner share & standard share & injected share. */
|
||||
export type ConversationSlotProps = ConvOwnerProps & { useSession: UseSession } & ConversationInjected
|
||||
|
||||
/** Injected share of the details slot. */
|
||||
export interface DetailsInjected {
|
||||
useSelection: SnapshotSelectorHook<SelectionTarget | null>
|
||||
actions: { closeDetails(): void }
|
||||
}
|
||||
|
||||
/** Full details-slot component props. */
|
||||
export type DetailsSlotProps = DetailsOwnerProps & { useSession: UseSession } & DetailsInjected
|
||||
|
||||
/** Injected share of the no-session empty-state slot (root slot: no standard share). */
|
||||
export interface EmptyStateInjected {
|
||||
/** cwd options derived from sessions.list (deduped; assembled by the inject factory). */
|
||||
useCwds: SnapshotSelectorHook<readonly string[]>
|
||||
actions: { startSession(opts: { cwd?: string; text: string; mode: 'queue' | 'steer' }): Promise<void> }
|
||||
}
|
||||
|
||||
/** Full empty-state component props. */
|
||||
export type EmptyStateSlotProps = EmptyOwnerProps & EmptyStateInjected
|
||||
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* Pure row-model derivation for tool summary rows: variant classification,
|
||||
* one-line summary and expanded-body text from the frozen call slice. No
|
||||
* inline output ever — full results live in the details panel.
|
||||
*/
|
||||
import type { ToolCallBlock } from './toolview.ts'
|
||||
|
||||
export type { ToolCallBlock } from './toolview.ts'
|
||||
|
||||
/** The frozen slice the chat view hands to toolview components as `block`
|
||||
* (both members are cache-stable references off ConversationSnapshot). */
|
||||
|
||||
/** The five figma row variants (think is fed by reasoning blocks, not tool calls). */
|
||||
export type ToolRowVariant = 'think' | 'search' | 'read' | 'bash' | 'others'
|
||||
|
||||
/** Row state semantic; colors self-supplied via StateDot (design gives none). */
|
||||
export type ToolRowState = 'running' | 'ok' | 'error' | 'stopped'
|
||||
|
||||
/** Figma row titles per variant (design literals, not translatable copy). */
|
||||
export const VARIANT_TITLES: Record<ToolRowVariant, string> = {
|
||||
think: 'Think', search: 'Search', read: 'Read', bash: 'Bash', others: 'Tool call',
|
||||
}
|
||||
|
||||
/** Known tool name -> variant; fs write/edit intentionally fall to others (no figma form). */
|
||||
const TOOL_VARIANTS: Record<string, ToolRowVariant> = {
|
||||
bash: 'bash',
|
||||
read: 'read',
|
||||
web_fetch: 'read',
|
||||
web_search: 'search',
|
||||
grep: 'search',
|
||||
glob: 'search',
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify a tool name into its row variant.
|
||||
* @param toolName - wire tool name.
|
||||
* @returns matching variant, others when unknown.
|
||||
*/
|
||||
export function classifyTool(toolName: string): ToolRowVariant {
|
||||
return TOOL_VARIANTS[toolName] ?? 'others'
|
||||
}
|
||||
|
||||
/** Everything ToolRow needs, derived once from the frozen slice. */
|
||||
export interface ToolRowModel {
|
||||
variant: ToolRowVariant
|
||||
title: string
|
||||
summary: string
|
||||
/** Expanded-body text (pretty args); null = row not expandable. */
|
||||
body: string | null
|
||||
state: ToolRowState
|
||||
}
|
||||
|
||||
function parseArgs(argsRaw: string): unknown {
|
||||
try {
|
||||
return JSON.parse(argsRaw)
|
||||
} catch {
|
||||
// Non-JSON args (mid-stream truncation): summary/body fall back to the raw string.
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
function firstLine(text: string): string {
|
||||
const nl = text.indexOf('\n')
|
||||
return nl === -1 ? text : text.slice(0, nl)
|
||||
}
|
||||
|
||||
function pickString(args: Record<string, unknown>, keys: readonly string[]): string | undefined {
|
||||
for (const key of keys) {
|
||||
const v = args[key]
|
||||
if (typeof v === 'string' && v !== '') return v
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** Summary key preference per variant (args-derived; result-derived summaries are a ledger item). */
|
||||
const SUMMARY_KEYS: Record<ToolRowVariant, readonly string[]> = {
|
||||
bash: ['description', 'command'],
|
||||
read: ['path', 'file_path', 'url'],
|
||||
search: ['query', 'pattern', 'url'],
|
||||
think: [],
|
||||
others: [],
|
||||
}
|
||||
|
||||
function deriveSummary(variant: ToolRowVariant, argsRaw: string): string {
|
||||
const parsed = parseArgs(argsRaw)
|
||||
if (typeof parsed !== 'object' || parsed === null) return firstLine(argsRaw)
|
||||
const args = parsed as Record<string, unknown>
|
||||
const picked = pickString(args, SUMMARY_KEYS[variant])
|
||||
if (picked !== undefined) return firstLine(picked)
|
||||
for (const v of Object.values(args)) {
|
||||
if (typeof v === 'string' && v !== '') return firstLine(v)
|
||||
}
|
||||
return firstLine(argsRaw)
|
||||
}
|
||||
|
||||
function deriveBody(argsRaw: string): string | null {
|
||||
if (argsRaw === '') return null
|
||||
const parsed = parseArgs(argsRaw)
|
||||
return parsed === undefined ? argsRaw : JSON.stringify(parsed, null, 2)
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive the full row model from a frozen call slice.
|
||||
* @param toolName - wire tool name (dispatch-supplied; survives windowless results).
|
||||
* @param block - RunningToolCall or ToolResultNode off the snapshot caches.
|
||||
* @returns the row model.
|
||||
*/
|
||||
export function toolRowModel(toolName: string, block: ToolCallBlock): ToolRowModel {
|
||||
const variant = classifyTool(toolName)
|
||||
const done = 'kind' in block
|
||||
const argsRaw = (done ? block.call?.argsRaw : block.argsRaw) ?? ''
|
||||
const state: ToolRowState = !done ? 'running'
|
||||
: block.error?.code === 'interrupted' ? 'stopped'
|
||||
: block.isError ? 'error' : 'ok'
|
||||
const base = argsRaw === '' ? block.callId : deriveSummary(variant, argsRaw)
|
||||
// Others keeps the static "Tool call" title (figma literal); the real tool
|
||||
// name rides the mutable summary slot so no information is lost.
|
||||
const summary = variant === 'others' && toolName !== '' ? `${toolName} · ${base}` : base
|
||||
return {
|
||||
variant,
|
||||
title: VARIANT_TITLES[variant],
|
||||
summary,
|
||||
body: deriveBody(argsRaw),
|
||||
state,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* Tool-ring contract: the props surface handed to toolview components, the
|
||||
* registry's resolve/registration shapes, and the tool-call block union.
|
||||
* Shared face between the chat domain (ToolViewOutlet consumes resolve) and
|
||||
* the toolviews domain (registry implementation + sample rows); domain
|
||||
* implementation files import this, never each other.
|
||||
*/
|
||||
import type { FC } from 'react'
|
||||
import type { SessionBinding } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { UseSession } from '@deepseek-ai/dsh-client-web-react'
|
||||
import type { SessionId, ToolCallBlock } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { CallId, Translate } from './views.ts'
|
||||
|
||||
// The block union's defining home is runtime (fold-product types); the
|
||||
// contract only forwards it (type-definition authority stays with the layer
|
||||
// that produces the values).
|
||||
export type { ToolCallBlock } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
|
||||
/** Props handed to registered toolview components. */
|
||||
export interface ToolViewProps {
|
||||
callId: CallId
|
||||
toolName: string
|
||||
block: ToolCallBlock
|
||||
useSession: UseSession
|
||||
actions: { openDetails(): void }
|
||||
t: Translate
|
||||
}
|
||||
|
||||
/**
|
||||
* Toolview inject factory: produces the registrant's private injected share
|
||||
* `I`, called once per (registration x session binding) and cached by the
|
||||
* render outlet. Session-bound by nature — tool rows always render inside a
|
||||
* session subtree.
|
||||
*/
|
||||
export type ToolViewInject<I extends object> = (b: SessionBinding) => I
|
||||
|
||||
/** Options accepted by the toolview registry's register; `I` is inferred from the inject factory. */
|
||||
export interface ToolViewOptions<I extends object = object> {
|
||||
/** Session filter; absent = global registration. */
|
||||
scope?: (sessionId: SessionId) => boolean
|
||||
/** Private inject factory merged into the row's props by the render outlet. */
|
||||
inject?: ToolViewInject<I>
|
||||
}
|
||||
|
||||
/**
|
||||
* A resolved toolview registration. `I` is erased to `object` on the resolve
|
||||
* read face (storage erases the per-registration parameter; the outlet merges
|
||||
* injected props untyped — the register site already proved component ⊇ I).
|
||||
*/
|
||||
export interface ResolvedToolView<I extends object = object> {
|
||||
component: FC<ToolViewProps & I>
|
||||
inject?: ToolViewInject<I>
|
||||
}
|
||||
|
||||
/** The registry's read face consumed by render outlets (implementation lives in the toolviews domain). */
|
||||
export interface ToolViewResolver {
|
||||
/**
|
||||
* Resolve the renderer for a tool in a session. Order: scope match (later
|
||||
* registration wins) > global > undefined (caller falls back to the
|
||||
* generic card).
|
||||
* @param tool - tool name.
|
||||
* @param sessionId - session the row renders in.
|
||||
* @returns resolved view, or undefined when nothing matches.
|
||||
*/
|
||||
resolve(tool: string, sessionId: SessionId): ResolvedToolView | undefined
|
||||
/**
|
||||
* Subscribe to registration changes (synchronous).
|
||||
* @param fn - change callback.
|
||||
* @returns unsubscribe.
|
||||
*/
|
||||
subscribe(fn: () => void): () => void
|
||||
/**
|
||||
* Monotonic version for uSES pairing.
|
||||
* @returns current version.
|
||||
*/
|
||||
getVersion(): number
|
||||
}
|
||||
68
packages/client/ui-conversation/src/client/contract/views.ts
Normal file
68
packages/client/ui-conversation/src/client/contract/views.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* View-ring contract: the typed conversation view table and the props
|
||||
* surfaces handed to registered views. Shared face between the skeleton
|
||||
* domain (ConversationRoot renders views) and the chat domain (registers the
|
||||
* chat view); domain implementation files import this, never each other.
|
||||
*/
|
||||
import type { FC } from 'react'
|
||||
import type { ScopedSlots } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { SnapshotSelectorHook, UseSession } from '@deepseek-ai/dsh-client-web-react'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
|
||||
/**
|
||||
* One ConversationViewMap entry: per-view props extension shapes (design
|
||||
* ledger, view ring). `chromeProps` extends {@link ChromeProps} for the
|
||||
* view's chrome attachments; `extraProps` extends {@link ConvViewProps} for
|
||||
* the view component itself. Both optional — the common bases stay the floor.
|
||||
*/
|
||||
export interface ViewEntryDef { chromeProps?: object; extraProps?: object }
|
||||
|
||||
/**
|
||||
* Typed conversation view table; ui-trajectory merges {trajectory, waterfall}.
|
||||
* The chat entry is declared inline here (self-merge from a sibling module
|
||||
* trips TS6305 under tsc -b).
|
||||
*/
|
||||
export interface ConversationViewMap { chat: ViewEntryDef }
|
||||
|
||||
/** View id constrained to registered ConversationViewMap keys (all string literals; chat is declared inline). */
|
||||
export type ViewId = keyof ConversationViewMap
|
||||
|
||||
/** Per-view chrome props: the common base plus the entry's declared extension. */
|
||||
export type ChromePropsOf<Id extends ViewId> =
|
||||
ChromeProps & (ConversationViewMap[Id] extends { chromeProps: infer C extends object } ? C : object)
|
||||
|
||||
/** Per-view component props: the common base plus the entry's declared extension. */
|
||||
export type ConvViewPropsOf<Id extends ViewId> =
|
||||
ConvViewProps & (ConversationViewMap[Id] extends { extraProps: infer E extends object } ? E : object)
|
||||
|
||||
/** Tool call identity as carried on the wire (branded upstream in connection). */
|
||||
export type CallId = string
|
||||
|
||||
/** Translate function bound to a namespace via i18n. */
|
||||
export type Translate = (key: string, params?: Record<string, unknown>) => string
|
||||
|
||||
/** One registered conversation view (props positions keyed by the entry's declared shapes). */
|
||||
export interface ViewEntry<Id extends ViewId = ViewId> {
|
||||
id: Id
|
||||
label: string
|
||||
order?: number
|
||||
component: FC<ConvViewPropsOf<Id>>
|
||||
/** Per-view chrome attachments (chat mounts the stats line as footer). */
|
||||
chrome?: { header?: FC<ChromePropsOf<Id>>; footer?: FC<ChromePropsOf<Id>> }
|
||||
}
|
||||
|
||||
/** Props for view chrome attachments. */
|
||||
export interface ChromeProps { sessionId: SessionId; useSession: UseSession }
|
||||
|
||||
/** Selection target for the details linkage channel (toolcall is the step special case). */
|
||||
export interface SelectionTarget { turnSeq: number; stepSeq?: number; callId?: CallId; toolName?: string }
|
||||
|
||||
/** Props handed to registered conversation views. */
|
||||
export interface ConvViewProps {
|
||||
sessionId: SessionId
|
||||
useSession: UseSession
|
||||
useSelection: SnapshotSelectorHook<SelectionTarget | null>
|
||||
actions: { openDetails(t: SelectionTarget): void; loadOlder(): void }
|
||||
/** Chat has no delegated sub-slots in P-I (toolviews go through the named registry). */
|
||||
slots: ScopedSlots<never>
|
||||
}
|
||||
42
packages/client/ui-conversation/src/client/index.ts
Normal file
42
packages/client/ui-conversation/src/client/index.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Conversation domain plugin, browser half: skeleton (header/tabs/composer),
|
||||
* typed view registry, scope-addressed ConversationService, named toolview
|
||||
* registry, minimal details panel. Contract: api-contracts v3 section 7.
|
||||
* Thin shell: type surfaces live in contract/, assembly in apply.ts; the
|
||||
* three implementation domains (skeleton/chat/toolviews) never import each
|
||||
* other — contract/ is their only shared face.
|
||||
*/
|
||||
import type { ConversationService } from './service.ts'
|
||||
import type { ToolViewRegistry } from './toolviews/registry.ts'
|
||||
|
||||
export { apply, inject } from './apply.ts'
|
||||
export { ConversationService } from './service.ts'
|
||||
export { ToolViewRegistry } from './toolviews/registry.ts'
|
||||
|
||||
export type {
|
||||
CallId, ChromeProps, ChromePropsOf, ConversationViewMap, ConvViewProps, ConvViewPropsOf,
|
||||
SelectionTarget, Translate, ViewEntry, ViewEntryDef, ViewId,
|
||||
} from './contract/views.ts'
|
||||
export type {
|
||||
ResolvedToolView, ToolCallBlock, ToolViewOptions, ToolViewProps, ToolViewResolver,
|
||||
} from './contract/toolview.ts'
|
||||
export type {
|
||||
ConversationInjected, ConversationSlotProps, DetailsInjected, DetailsSlotProps,
|
||||
EmptyStateInjected, EmptyStateSlotProps,
|
||||
} from './contract/slots.ts'
|
||||
|
||||
export { ConversationRoot } from './skeleton/ConversationRoot.tsx'
|
||||
export type { ConversationRootProps } from './skeleton/ConversationRoot.tsx'
|
||||
export { InputBar } from './skeleton/InputBar.tsx'
|
||||
export type { InputBarError, InputBarProps } from './skeleton/InputBar.tsx'
|
||||
export { EmptyState } from './skeleton/EmptyState.tsx'
|
||||
export type { EmptyStateProps } from './skeleton/EmptyState.tsx'
|
||||
export { DetailsPanel } from './skeleton/DetailsPanel.tsx'
|
||||
export type { DetailsPanelProps } from './skeleton/DetailsPanel.tsx'
|
||||
|
||||
declare module 'cordis' {
|
||||
interface Context {
|
||||
conversation: ConversationService
|
||||
toolviews: ToolViewRegistry
|
||||
}
|
||||
}
|
||||
251
packages/client/ui-conversation/src/client/service.ts
Normal file
251
packages/client/ui-conversation/src/client/service.ts
Normal file
@@ -0,0 +1,251 @@
|
||||
/**
|
||||
* ConversationService implementation: scope-addressed send/cancel, per-scope
|
||||
* selection/draft stores booked on the session scope fiber, view registry
|
||||
* with a uSES read face, openDetails orchestration, and the empty-state
|
||||
* startSession chain. Contract: api-contracts v3 section 7.
|
||||
*
|
||||
* Scope addressing rides the cordis Service tracker: property access through
|
||||
* `ctx.conversation` rebinds `this.ctx` to the caller's context, so methods
|
||||
* read the session tag with scopeOf (same mechanism as the host tool
|
||||
* registry). Mutable state lives in plain objects reached by one property
|
||||
* read — field assignment through the tracker's shadow proxy is off-limits,
|
||||
* as are `#` hard-private fields.
|
||||
*/
|
||||
import { Service } from 'cordis'
|
||||
import type { Context } from 'cordis'
|
||||
// Value import MUST use the /client subpath: only that specifier is in the
|
||||
// bundle externals (CLIENT_EXTERNALS), so it resolves to the shared runtime
|
||||
// module at load time. A bare-specifier value import gets INLINED as a second
|
||||
// module instance whose private scope-tag Symbol never matches the one
|
||||
// SessionsService tags contexts with — scopeOf then always returns undefined
|
||||
// in the browser while unit tests (single-instance path resolution) stay green.
|
||||
import { scopeOf } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { Session, SessionId, SessionsService } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { createSnapshotStore } from '@deepseek-ai/dsh-client-web-react'
|
||||
import type { SnapshotStore } from '@deepseek-ai/dsh-client-web-react'
|
||||
import type { LayoutService } from '@deepseek-ai/dsh-client-ui-layout/client'
|
||||
import type { SelectionTarget, ViewEntry, ViewId } from './index.ts'
|
||||
|
||||
/** Mutable view-registry cell (plain object: mutation never crosses the tracker proxy). */
|
||||
interface ViewsState {
|
||||
entries: Map<string, ViewEntry>
|
||||
/** Sorted projection cache; null = rebuild on next read. */
|
||||
cache: readonly ViewEntry[] | null
|
||||
tick: number
|
||||
listeners: Set<() => void>
|
||||
}
|
||||
|
||||
/** Scope-addressed conversation service (root singleton, provided as `conversation`). */
|
||||
export class ConversationService extends Service {
|
||||
private readonly selections = new Map<SessionId, SnapshotStore<SelectionTarget | null>>()
|
||||
private readonly draftStores = new Map<SessionId, SnapshotStore<string>>()
|
||||
private readonly viewsState: ViewsState = {
|
||||
entries: new Map(), cache: null, tick: 0, listeners: new Set(),
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ctx - owning root context (the plugin apply context; the service
|
||||
* registers itself and follows that fiber's lifetime).
|
||||
*/
|
||||
constructor(ctx: Context) {
|
||||
super(ctx, 'conversation')
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a prompt into the scoped session. Business failures also land in the
|
||||
* session snapshot's promptError (object-layer surface); the rejection here
|
||||
* exists for caller choreography (the composer restores the draft on it).
|
||||
* @param text - prompt text, sent verbatim as one text block.
|
||||
* @param mode - queue after the current turn, or steer into it.
|
||||
*/
|
||||
async send(text: string, mode: 'queue' | 'steer'): Promise<void> {
|
||||
const session = this.scopedSession('send')
|
||||
const result = await session.prompt([{ type: 'text', text }], mode)
|
||||
if (!result.ok) throw new Error(`conversation.send failed: ${result.error.code}: ${result.error.message}`)
|
||||
}
|
||||
|
||||
/** Cancel the scoped session's in-flight turn (failures land in promptError and reject, as in send). */
|
||||
async cancel(): Promise<void> {
|
||||
const session = this.scopedSession('cancel')
|
||||
const result = await session.cancel()
|
||||
if (!result.ok) throw new Error(`conversation.cancel failed: ${result.error.code}: ${result.error.message}`)
|
||||
}
|
||||
|
||||
/** Per-scope selection channel (details linkage); root access throws. */
|
||||
get selection(): SnapshotStore<SelectionTarget | null> {
|
||||
return this.scopeStore(this.selections, 'selection',
|
||||
() => createSnapshotStore<SelectionTarget | null>(null))
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-scope draft store, persisted per session id; root access throws.
|
||||
* Persistence is hand-rolled (raw string per key): the snapshot-store
|
||||
* engine's persist middleware object-spreads state on save, corrupting
|
||||
* primitive-state stores.
|
||||
*/
|
||||
get drafts(): SnapshotStore<string> {
|
||||
return this.scopeStore(this.draftStores, 'drafts', (id) => {
|
||||
const key = `dsh.conversation.draft.${id}`
|
||||
const store = createSnapshotStore<string>(loadDraft(key))
|
||||
store.subscribe(() => { saveDraft(key, store.getSnapshot()) })
|
||||
return store
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the scoped selection and open the details panel. Orchestration
|
||||
* only — panel geometry stays with ctx.layout.
|
||||
* @param target - selection target.
|
||||
*/
|
||||
openDetails(target: SelectionTarget): void {
|
||||
this.selection.set(target)
|
||||
this.requireLayout().openDetails()
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a conversation view. Duplicate ids throw; the registration is an
|
||||
* effect on the caller's fiber (plugin unload collects it).
|
||||
* @param entry - the view entry.
|
||||
* @returns disposer removing the view.
|
||||
*/
|
||||
registerView<Id extends ViewId>(entry: ViewEntry<Id>): () => void {
|
||||
const views = this.viewsState
|
||||
const dispose = this.ctx.effect(() => {
|
||||
if (views.entries.has(entry.id)) {
|
||||
throw new Error(`conversation view "${entry.id}" is already registered`)
|
||||
}
|
||||
views.entries.set(entry.id, entry)
|
||||
bumpViews(views)
|
||||
return () => {
|
||||
views.entries.delete(entry.id)
|
||||
bumpViews(views)
|
||||
}
|
||||
}, 'conversation.registerView()')
|
||||
// The effect disposer settles asynchronously; the registry face stays a
|
||||
// synchronous fire-and-forget disposer.
|
||||
return () => { void dispose() }
|
||||
}
|
||||
|
||||
/**
|
||||
* Registered views ordered by `order` (ties keep registration sequence).
|
||||
* Stable array reference between mutations (uSES getSnapshot source).
|
||||
* @returns the view entries.
|
||||
*/
|
||||
views(): readonly ViewEntry[] {
|
||||
const state = this.viewsState
|
||||
state.cache ??= [...state.entries.values()].sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
|
||||
return state.cache
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to view registry changes (synchronous, like the toolview registry).
|
||||
* @param fn - change callback.
|
||||
* @returns unsubscribe.
|
||||
*/
|
||||
subscribeViews(fn: () => void): () => void {
|
||||
const { listeners } = this.viewsState
|
||||
listeners.add(fn)
|
||||
return () => { listeners.delete(fn) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Monotonic view registry version for uSES pairing.
|
||||
* @returns current version.
|
||||
*/
|
||||
viewsVersion(): number {
|
||||
return this.viewsState.tick
|
||||
}
|
||||
|
||||
/**
|
||||
* Empty-state first-send chain (root-context method; does not read scope):
|
||||
* create the session, navigate to it, then send through the new scope.
|
||||
* The create → open ordering is safe: the manager merges the new summary
|
||||
* synchronously before create() resolves, so the list store is projected by
|
||||
* the time open() validates against it (manager notification batching is
|
||||
* microtask-based; SessionsService projects on the same flush that create
|
||||
* awaited through the RPC round trip).
|
||||
* @param opts - project directory, prompt text, and send mode.
|
||||
*/
|
||||
async startSession(opts: { cwd?: string; text: string; mode: 'queue' | 'steer' }): Promise<void> {
|
||||
const sessions = this.requireSessions()
|
||||
const id = await sessions.create(opts.cwd === undefined ? {} : { cwd: opts.cwd })
|
||||
// The manager notifier flushes per microtask; one await guarantees the
|
||||
// list-store projection landed before layout.open validates against it.
|
||||
await Promise.resolve()
|
||||
this.requireLayout().open(id)
|
||||
const scoped = sessions.scope(id)
|
||||
if (scoped === undefined) throw new Error(`conversation.startSession: created session "${id}" resolved no scope`)
|
||||
// ctx.get, not scoped.conversation: property access walks the fiber
|
||||
// topology (a scope fiber never injects services), while get reads the
|
||||
// global store and still binds this service to the scoped ctx.
|
||||
const scopedConversation = scoped.get('conversation')
|
||||
if (scopedConversation === undefined) throw new Error('conversation.startSession: conversation service unavailable through the new scope')
|
||||
await scopedConversation.send(opts.text, opts.mode)
|
||||
}
|
||||
|
||||
/** Resolve the caller scope's Session or throw on root contexts. */
|
||||
private scopedSession(op: string): Session {
|
||||
const id = this.scopeId(op)
|
||||
return this.requireSessions().manager.get(id)
|
||||
}
|
||||
|
||||
/** Read the caller's session scope tag; root contexts fail loud. */
|
||||
private scopeId(op: string): SessionId {
|
||||
const id = scopeOf(this.ctx)
|
||||
if (id === undefined) {
|
||||
throw new Error(`conversation.${op} requires a session scope — address one via ctx.sessions.scope(id).conversation`)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-scope store account: lazily created, booked on the scope fiber so the
|
||||
* scope teardown (SessionsService prune) collects the entry.
|
||||
*/
|
||||
private scopeStore<T>(
|
||||
map: Map<SessionId, SnapshotStore<T>>, op: string,
|
||||
make: (id: SessionId) => SnapshotStore<T>): SnapshotStore<T> {
|
||||
const id = this.scopeId(op)
|
||||
let store = map.get(id)
|
||||
if (store === undefined) {
|
||||
store = make(id)
|
||||
map.set(id, store)
|
||||
this.ctx.effect(() => () => { map.delete(id) }, `conversation.${op} scope account`)
|
||||
}
|
||||
return store
|
||||
}
|
||||
|
||||
private requireSessions(): SessionsService {
|
||||
// ctx.get instead of ctx.sessions: the typed Context merge is suspended
|
||||
// while the client/host `sessions` declaration collision awaits
|
||||
// arbitration (see the runtime package's Context merge note).
|
||||
const sessions = this.ctx.get('sessions')
|
||||
if (sessions === undefined) throw new Error('conversation: sessions service unavailable')
|
||||
return sessions
|
||||
}
|
||||
|
||||
private requireLayout(): LayoutService {
|
||||
const layout = this.ctx.get('layout')
|
||||
if (layout === undefined) throw new Error('conversation: layout service unavailable')
|
||||
return layout
|
||||
}
|
||||
}
|
||||
|
||||
function bumpViews(state: ViewsState): void {
|
||||
state.cache = null
|
||||
state.tick += 1
|
||||
for (const fn of [...state.listeners]) fn()
|
||||
}
|
||||
|
||||
function loadDraft(key: string): string {
|
||||
/* v8 ignore next -- storage-less environment guard (workers/tests without DOM); jsdom always provides localStorage. */
|
||||
if (typeof localStorage === 'undefined') return ''
|
||||
return localStorage.getItem(key) ?? ''
|
||||
}
|
||||
|
||||
function saveDraft(key: string, text: string): void {
|
||||
/* v8 ignore next -- storage-less environment guard (workers/tests without DOM); jsdom always provides localStorage. */
|
||||
if (typeof localStorage === 'undefined') return
|
||||
if (text === '') localStorage.removeItem(key)
|
||||
else localStorage.setItem(key, text)
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
/* Conversation column skeleton: header (breadcrumb row + tabs) over the view
|
||||
area, composer InputBar at the bottom. Column width/squeeze is layout's;
|
||||
this fills its cell. Figma: Header 39:27730 (83px two-row), tabs 13px with
|
||||
a 3px active bar. */
|
||||
|
||||
.root {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
min-width: 0;
|
||||
background: var(--dsw-alias-bg-base);
|
||||
}
|
||||
|
||||
.header {
|
||||
flex: none;
|
||||
padding: 12px 28px 0 20px;
|
||||
border-bottom: 1px solid var(--dsw-alias-border-l2);
|
||||
}
|
||||
|
||||
.crumbRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
min-height: 32px;
|
||||
}
|
||||
|
||||
.crumbs {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.crumbSeg {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.crumbSep {
|
||||
/* figma: "/" separators are 14px caption gray (75:7903), one tint lighter than crumb text. */
|
||||
color: var(--dsw-alias-label-caption);
|
||||
font-size: 14px;
|
||||
line-height: 20px;
|
||||
}
|
||||
|
||||
.crumb {
|
||||
max-width: 220px;
|
||||
overflow: hidden;
|
||||
padding: 4px 8px;
|
||||
border: none;
|
||||
border-radius: 12px;
|
||||
background: transparent;
|
||||
font-size: 13px;
|
||||
line-height: 16px;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.crumb:hover:not(:disabled) {
|
||||
background: var(--dsw-alias-interactive-bg-hover);
|
||||
}
|
||||
|
||||
.crumbCurrent {
|
||||
font-weight: 500;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.meta {
|
||||
margin-left: 4px;
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
}
|
||||
|
||||
/* figma Tab_Group 34:11441: 35px strip, gap 36, pad-left 8, tabs bottom-aligned. */
|
||||
.tabs {
|
||||
display: flex;
|
||||
gap: 36px;
|
||||
margin-top: 4px;
|
||||
padding-left: 8px;
|
||||
}
|
||||
|
||||
/* figma .Tab 34:11442: 13/16 wt510 text, gap 8 to the 3px bar (no bottom rounding). */
|
||||
.tab {
|
||||
position: relative;
|
||||
padding: 0 0 11px;
|
||||
border: none;
|
||||
background: transparent;
|
||||
font-size: 13px;
|
||||
line-height: 16px;
|
||||
font-weight: 510;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.tab::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
height: 3px;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
/* Selected tab is blue, not ink: brand-primary resolves to neutral black in
|
||||
this token sheet, so the selected state rides the business blue — the
|
||||
nearest semantic token that stays blue in both themes. */
|
||||
.tabActive {
|
||||
color: var(--dsw-alias-state-business-primary);
|
||||
}
|
||||
|
||||
.tabActive::after {
|
||||
background: var(--dsw-alias-state-business-primary);
|
||||
}
|
||||
|
||||
.viewArea {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
// ConversationRoot: the conversation slot's skeleton (figma Header 39:27730 +
|
||||
// Tab_Group + view area + composer). Zero framework imports — everything
|
||||
// arrives via props from the inject factory: breadcrumb feed, view registry
|
||||
// read face, per-view render, and the composer's draft/send choreography.
|
||||
// The active view id lives in layout.viewFor (shell viewing state), read and
|
||||
// written through injected accessors.
|
||||
|
||||
import { useSyncExternalStore } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import type { ConversationSlotProps } from '../contract/slots.ts'
|
||||
import { InputBar } from './InputBar.tsx'
|
||||
import type { InputBarError } from './InputBar.tsx'
|
||||
import css from './ConversationRoot.module.css'
|
||||
|
||||
/**
|
||||
* Full props = owner share (sessionId) & standard share (useSession) &
|
||||
* injected share — composed by reference from the contract, never re-typed
|
||||
* here (share-ownership rule).
|
||||
*/
|
||||
export type ConversationRootProps = ConversationSlotProps
|
||||
|
||||
export function ConversationRoot({
|
||||
sessionId, useSession, useAncestry, views, useActiveView, composer, actions, renderView,
|
||||
}: ConversationRootProps) {
|
||||
useSyncExternalStore(views.subscribe, views.version)
|
||||
const list = views.list()
|
||||
const activeId = useActiveView() ?? 'chat'
|
||||
const active = list.find(v => v.id === activeId) ?? list[0]
|
||||
|
||||
const ancestry = useAncestry()
|
||||
const draft = composer.useDraft()
|
||||
const running = useSession(s => (s as { running: boolean }).running)
|
||||
const removed = useSession(s => (s as { removed: boolean }).removed)
|
||||
const promptError = useSession(s => (s as { promptError: { op: 'send' | 'stop'; error: { message: string; code: string } } | null }).promptError)
|
||||
const turns = useSession(s => countTurns(s as { nodes: readonly { kind: string }[] }))
|
||||
|
||||
const error: InputBarError | null = promptError === null
|
||||
? null
|
||||
: { op: promptError.op, message: `${promptError.error.message}(${promptError.error.code})` }
|
||||
|
||||
return (
|
||||
<div className={css.root}>
|
||||
<header className={css.header}>
|
||||
<div className={css.crumbRow}>
|
||||
<nav className={css.crumbs} aria-label="会话层级">
|
||||
{ancestry.map((s, i) => {
|
||||
const last = i === ancestry.length - 1
|
||||
return (
|
||||
<span key={s.id} className={css.crumbSeg}>
|
||||
{i > 0 && <span className={css.crumbSep}>/</span>}
|
||||
<button
|
||||
type="button"
|
||||
className={clsx(css.crumb, last && css.crumbCurrent)}
|
||||
disabled={last}
|
||||
onClick={() => { actions.open(s.id) }}
|
||||
>
|
||||
{s.title}
|
||||
</button>
|
||||
</span>
|
||||
)
|
||||
})}
|
||||
{ancestry.length === 0 && <span className={css.crumbCurrent}>{sessionId}</span>}
|
||||
<span className={css.meta}>· {turns} turns</span>
|
||||
</nav>
|
||||
{/* Header button row (Fork / Session log / I/O Details): a P-I visual
|
||||
placeholder registry slot is deferred — buttons land with their features. */}
|
||||
</div>
|
||||
{list.length > 1 && (
|
||||
<div className={css.tabs} role="tablist">
|
||||
{list.map(v => (
|
||||
<button
|
||||
key={v.id}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={v.id === active?.id}
|
||||
className={clsx(css.tab, v.id === active?.id && css.tabActive)}
|
||||
onClick={() => { actions.openView(v.id) }}
|
||||
>
|
||||
{v.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</header>
|
||||
|
||||
<div className={css.viewArea}>
|
||||
{active !== undefined && renderView(active)}
|
||||
</div>
|
||||
|
||||
<InputBar
|
||||
draft={draft}
|
||||
running={running}
|
||||
disabled={removed}
|
||||
error={error}
|
||||
variant="composer"
|
||||
onDraftChange={composer.setDraft}
|
||||
onSend={composer.send}
|
||||
onStop={composer.stop}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Turn count = user message nodes in the window (display meta; exact host count deferred). */
|
||||
function countTurns(s: { nodes: readonly { kind: string }[] }): number {
|
||||
let n = 0
|
||||
for (const node of s.nodes) if (node.kind === 'user') n += 1
|
||||
return n
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
/* Details third column, minimal P-I fill: header (name + close) over a
|
||||
scrolling body of Input/Output code sections. Panel width/squeeze belongs
|
||||
to layout; this fills whatever the column gives. */
|
||||
|
||||
.root {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
min-width: 0;
|
||||
border-left: 1px solid var(--dsw-alias-border-l2);
|
||||
background: var(--dsw-alias-bg-base);
|
||||
}
|
||||
|
||||
/* figma RightSidebar header frame (I54:42735;43:36451): pad 14/12/12/12, gap 8. */
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
padding: 14px 12px 12px;
|
||||
border-bottom: 1px solid var(--dsw-alias-border-l2);
|
||||
}
|
||||
|
||||
/* figma I54:42735;43:41479: 14/20 wt500. */
|
||||
.title {
|
||||
overflow: hidden;
|
||||
font-size: 14px;
|
||||
line-height: 20px;
|
||||
font-weight: 500;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.close {
|
||||
display: grid;
|
||||
flex: none;
|
||||
place-items: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border: none;
|
||||
border-radius: 999px;
|
||||
background: transparent;
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.close:hover {
|
||||
background: var(--dsw-alias-interactive-bg-hover);
|
||||
}
|
||||
|
||||
.body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
padding: 12px 16px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.empty {
|
||||
padding: 8px 0;
|
||||
font-size: 13px;
|
||||
line-height: 20px;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
}
|
||||
|
||||
.section {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.sectionLabel {
|
||||
margin-bottom: 6px;
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
font-weight: 500;
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
}
|
||||
|
||||
/* figma Code-block (I54:42735;43:41429): r12, pad 16, mono 13/22. */
|
||||
.code {
|
||||
margin: 0;
|
||||
padding: 16px;
|
||||
border-radius: 12px;
|
||||
background: var(--dsw-alias-markdown-code-block);
|
||||
font-family: var(--ds-font-family-code);
|
||||
font-size: 13px;
|
||||
line-height: 22px;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.code[data-error] {
|
||||
color: var(--dsw-alias-state-error-primary);
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
// DetailsPanel, P-I minimal form: close button + the selected call's args and
|
||||
// result rendered raw. The three-段 Switch / Prev-Next stepping / See-in-
|
||||
// trajectory are deferred (ledger). Subscribes to the per-scope selection and
|
||||
// derives the call material from the session snapshot — no data of its own.
|
||||
|
||||
import type { ConversationSnapshot, ToolResultNode } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { shallowEqual } from '@deepseek-ai/dsh-client-web-react'
|
||||
import type { DetailsSlotProps } from '../contract/slots.ts'
|
||||
import css from './DetailsPanel.module.css'
|
||||
|
||||
/** Full props composed by reference from the contract (owner & standard & injected shares). */
|
||||
export type DetailsPanelProps = DetailsSlotProps
|
||||
|
||||
/** Selected call material: resolved result node, or the in-flight running call's args. */
|
||||
interface CallMaterial {
|
||||
name: string
|
||||
argsRaw: string | null
|
||||
result: ToolResultNode | null
|
||||
running: boolean
|
||||
}
|
||||
|
||||
function materialFor(s: ConversationSnapshot, callId: string): CallMaterial | null {
|
||||
for (const node of s.nodes) {
|
||||
if (node.kind === 'tool-result' && node.callId === callId) {
|
||||
return { name: node.call?.name ?? callId, argsRaw: node.call?.argsRaw ?? null, result: node, running: false }
|
||||
}
|
||||
}
|
||||
const open = s.runningCalls.find(c => c.callId === callId)
|
||||
if (open !== undefined) {
|
||||
return { name: open.name, argsRaw: open.argsRaw, result: null, running: true }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function pretty(raw: string): string {
|
||||
try {
|
||||
return JSON.stringify(JSON.parse(raw), null, 2)
|
||||
} catch {
|
||||
// Not JSON (streaming fragment or plain text): show verbatim.
|
||||
return raw
|
||||
}
|
||||
}
|
||||
|
||||
export function DetailsPanel({ useSession, useSelection, actions }: DetailsPanelProps) {
|
||||
const selection = useSelection(s => s)
|
||||
const callId = selection?.callId
|
||||
// materialFor builds a fresh wrapper; shallowEqual short-circuits on its
|
||||
// stable members (result node reference rides the snapshot's structural sharing).
|
||||
const material = useSession(
|
||||
s => (callId === undefined ? null : materialFor(s as ConversationSnapshot, callId)),
|
||||
(a, b) => shallowEqual(a, b))
|
||||
|
||||
return (
|
||||
<div className={css.root}>
|
||||
<div className={css.header}>
|
||||
<div className={css.title}>
|
||||
{selection === null ? '详情' : material?.name ?? selection.toolName ?? '详情'}
|
||||
</div>
|
||||
<button
|
||||
type="button" className={css.close} aria-label="关闭详情"
|
||||
onClick={() => { actions.closeDetails() }}
|
||||
>
|
||||
<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden>
|
||||
<path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<div className={css.body}>
|
||||
{selection === null || callId === undefined
|
||||
? <div className={css.empty}>点击消息流中的工具行查看详情</div>
|
||||
: material === null
|
||||
? <div className={css.empty}>该调用不在当前窗口内</div>
|
||||
: (
|
||||
<>
|
||||
{material.argsRaw !== null && (
|
||||
<section className={css.section}>
|
||||
<div className={css.sectionLabel}>Input</div>
|
||||
<pre className={css.code}>{pretty(material.argsRaw)}</pre>
|
||||
</section>
|
||||
)}
|
||||
<section className={css.section}>
|
||||
<div className={css.sectionLabel}>Output</div>
|
||||
{/* materialFor invariant: result===null ⇔ running (a settled
|
||||
material always carries its result node). */}
|
||||
{material.result === null
|
||||
? <div className={css.empty}>运行中…</div>
|
||||
: (
|
||||
<pre className={css.code} data-error={material.result.isError || undefined}>
|
||||
{renderResult(material.result)}
|
||||
</pre>
|
||||
)}
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Flatten result content blocks to display text (text blocks verbatim, others as JSON). */
|
||||
function renderResult(node: ToolResultNode): string {
|
||||
const parts: string[] = []
|
||||
for (const block of node.content) {
|
||||
if (block.type === 'text') parts.push(block.text)
|
||||
else parts.push(JSON.stringify(block, null, 2))
|
||||
}
|
||||
if (parts.length === 0 && node.error !== undefined) {
|
||||
parts.push(`${node.error.name}: ${node.error.code}`)
|
||||
}
|
||||
return parts.join('\n')
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/* NEW SESSION hero: headline over the shared InputBar card, centered in the
|
||||
conversation column. The card is the same component as the composer —
|
||||
only positioning lives here. */
|
||||
|
||||
.root {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
min-width: 0;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
/* figma hero group 34:10409: headline block sits 36px above the input card. */
|
||||
.card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 36px;
|
||||
width: 100%;
|
||||
max-width: 776px;
|
||||
}
|
||||
|
||||
/* figma 34:10411: fish + title row, gap 10, centered; title 26/32 wt600 (34:10414). */
|
||||
.headline {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
font-size: 26px;
|
||||
line-height: 32px;
|
||||
font-weight: 600;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
}
|
||||
|
||||
/* figma 34:10412/10413: brand-blue vector. */
|
||||
.fish {
|
||||
flex: none;
|
||||
color: var(--dsw-alias-state-business-primary);
|
||||
}
|
||||
|
||||
.picker {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.select,
|
||||
.customInput {
|
||||
max-width: 320px;
|
||||
padding: 4px 10px;
|
||||
border: 1px solid var(--dsw-alias-border-l2-darkmode-thin);
|
||||
border-radius: 12px;
|
||||
background: var(--dsw-alias-bg-base);
|
||||
font-size: 13px;
|
||||
line-height: 20px;
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
}
|
||||
|
||||
.customInput {
|
||||
width: 320px;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.customInput:focus {
|
||||
/* Business blue, not brand-primary: that token resolves to ink in this sheet. */
|
||||
border-color: var(--dsw-alias-state-business-primary);
|
||||
color: var(--dsw-alias-label-primary);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
// EmptyState (figma NEW SESSION screen): centered hero card built around the
|
||||
// SAME InputBar component the resident composer uses (the empty→content
|
||||
// transition is one component changing position, never a swap). Project
|
||||
// picker: cwd set derived from sessions.list plus a free-form new-directory
|
||||
// input; submit runs the startSession chain (create → open → send) in one
|
||||
// service call.
|
||||
|
||||
import { useState } from 'react'
|
||||
import { FishLogo } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { EmptyStateSlotProps } from '../contract/slots.ts'
|
||||
import { InputBar } from './InputBar.tsx'
|
||||
import type { InputBarError } from './InputBar.tsx'
|
||||
import css from './EmptyState.module.css'
|
||||
|
||||
/** Select sentinel for the free-form directory entry (impossible as a real path: not absolute). */
|
||||
const NEW_DIR = '::new-directory'
|
||||
|
||||
/** Full props composed by reference from the contract (owner & injected shares; root slot has no standard share). */
|
||||
export type EmptyStateProps = EmptyStateSlotProps
|
||||
|
||||
export function EmptyState({ useCwds, actions }: EmptyStateProps) {
|
||||
const cwds = useCwds(s => s)
|
||||
// Local viewing state: the empty state owns no session, so its draft is
|
||||
// ephemeral by design (drafts are keyed by session id; there is none yet).
|
||||
const [draft, setDraft] = useState('')
|
||||
const [cwd, setCwd] = useState<string>('')
|
||||
const [custom, setCustom] = useState(false)
|
||||
const [sending, setSending] = useState(false)
|
||||
const [error, setError] = useState<InputBarError | null>(null)
|
||||
|
||||
const submit = (mode: 'queue' | 'steer'): void => {
|
||||
const text = draft.trim()
|
||||
/* v8 ignore next -- defensive: InputBar disables send while empty. */
|
||||
if (text === '' || sending) return
|
||||
setSending(true)
|
||||
setError(null)
|
||||
const chosen = cwd.trim()
|
||||
actions.startSession({ text, mode, ...(chosen === '' ? {} : { cwd: chosen }) })
|
||||
.catch((reason: unknown) => {
|
||||
// The empty state survives failure with the draft intact (no session
|
||||
// exists to carry promptError; this is the only local error surface).
|
||||
setError({ op: 'send', message: reason instanceof Error ? reason.message : String(reason) })
|
||||
setSending(false)
|
||||
})
|
||||
// Success needs no cleanup: layout.open swaps this slot out for the session body.
|
||||
}
|
||||
|
||||
const picker = (
|
||||
<div className={css.picker}>
|
||||
{custom
|
||||
? (
|
||||
<input
|
||||
className={css.customInput}
|
||||
value={cwd}
|
||||
autoFocus
|
||||
placeholder="目录路径,如 /home/me/proj"
|
||||
onChange={(e) => { setCwd(e.target.value) }}
|
||||
/>
|
||||
)
|
||||
: (
|
||||
<select
|
||||
className={css.select}
|
||||
value={cwd}
|
||||
aria-label="项目目录"
|
||||
onChange={(e) => {
|
||||
if (e.target.value === NEW_DIR) {
|
||||
setCustom(true)
|
||||
setCwd('')
|
||||
} else {
|
||||
setCwd(e.target.value)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<option value="">默认目录</option>
|
||||
{cwds.map(c => <option key={c} value={c}>{c}</option>)}
|
||||
<option value={NEW_DIR}>新目录…</option>
|
||||
</select>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className={css.root}>
|
||||
<div className={css.card}>
|
||||
<div className={css.headline}>
|
||||
{/* figma 34:10412: fish 34x25 leading the headline, gap 10. */}
|
||||
<FishLogo size={34} className={css.fish} />
|
||||
Let's start building
|
||||
</div>
|
||||
<InputBar
|
||||
draft={draft}
|
||||
running={false}
|
||||
disabled={sending}
|
||||
error={error}
|
||||
variant="hero"
|
||||
placeholder="Message to run task, plan and build"
|
||||
accessory={picker}
|
||||
onDraftChange={setDraft}
|
||||
onSend={submit}
|
||||
/* v8 ignore next -- structural noop: hero never passes running=true, so stop is unreachable. */
|
||||
onStop={() => {}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
/* Floating capsule input (figma Input_Bottom 34:11445): card floats above the
|
||||
viewport bottom inside the centered message column; textarea on top, action
|
||||
row below, one primary circle button bottom-right. Input width rides the
|
||||
column (776 is a cap, not a fixed size — layout rule: the box shrinks with
|
||||
the center column keeping its padding). Hero variant = the same card
|
||||
centered in the empty state; the transition between the two is a position
|
||||
move of one component. */
|
||||
|
||||
.root {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
/* figma Input_Bottom 34:11445: pad L32/R32/B12; the bottom gradient mask is
|
||||
owned by the chat scroller. Top 8 hosts the error strip's breathing room. */
|
||||
padding: 8px 32px 12px;
|
||||
}
|
||||
|
||||
.hero {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.error {
|
||||
width: 100%;
|
||||
max-width: 776px;
|
||||
margin-bottom: 6px;
|
||||
padding: 4px 8px;
|
||||
border-radius: 8px;
|
||||
background: var(--dsw-alias-interactive-bg-hover-danger);
|
||||
color: var(--dsw-alias-state-error-primary);
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
.card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
/* figma Input 34:11458: 12px between the text area and the button row. */
|
||||
gap: 12px;
|
||||
width: 100%;
|
||||
max-width: 776px;
|
||||
/* Input stroke: black/0.10 light, white/0.06 dark (figma darkmode note says
|
||||
the input border is one notch weaker than buttons) — exactly the
|
||||
l2-darkmode-thin pair. Fill: the input surface token (elevated in dark). */
|
||||
border: 1px solid var(--dsw-alias-border-l2-darkmode-thin);
|
||||
border-radius: 20px;
|
||||
background: var(--dsw-specific-input-major);
|
||||
box-shadow: var(--dsw-shadow-lv2);
|
||||
font-size: 16px;
|
||||
line-height: 24px;
|
||||
}
|
||||
|
||||
/* New-session state rounds up (figma: r24 and a taller box). */
|
||||
.hero .card {
|
||||
border-radius: 24px;
|
||||
}
|
||||
|
||||
.accessory {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 10px 12px 0;
|
||||
}
|
||||
|
||||
/* Mirror-div auto-grow wrapper: the hidden mirror is in normal flow and sets the height
|
||||
(min 2 lines / max 14 lines); the textarea rides it absolutely. Mirror and textarea
|
||||
MUST share font, line-height, padding and wrapping rules or heights diverge. */
|
||||
.grow {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.input {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
resize: none;
|
||||
overflow-y: auto;
|
||||
border: none;
|
||||
outline: none;
|
||||
background: transparent;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
/* Business blue, not brand-primary: that token resolves to ink in this sheet. */
|
||||
caret-color: var(--dsw-alias-state-business-primary);
|
||||
}
|
||||
|
||||
.input,
|
||||
.mirror {
|
||||
padding: 12px 16px 0;
|
||||
font-size: inherit;
|
||||
line-height: inherit;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* figma 34:10434: #ADB2B8 light / #81858C dark — the caption pair exactly. */
|
||||
.input::placeholder {
|
||||
color: var(--dsw-alias-label-caption);
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
/* Running lock: grayed but the draft stays visible; the turn ending re-enables. */
|
||||
.input:disabled {
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.mirror {
|
||||
visibility: hidden;
|
||||
pointer-events: none;
|
||||
/* 2-line floor: 2 × 24px line + 12px top padding; 14-line cap (336px). */
|
||||
min-height: 60px;
|
||||
max-height: 336px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.hero .mirror {
|
||||
/* New-session box is taller at rest (figma 118px input area). */
|
||||
min-height: 84px;
|
||||
}
|
||||
|
||||
/* figma Frame 1123 (34:11463): pad 12/0/10/10, buttons vertically centered. */
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
padding: 0 10px 10px 12px;
|
||||
}
|
||||
|
||||
/* Primary send (figma IconButton 34:10465): 34px circle, #3964FE light /
|
||||
#679EFE dark — the info-fill pair (500→400), NOT button-primary (ink);
|
||||
white glyph; empty text = 0.4 opacity. */
|
||||
.primary {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
border: none;
|
||||
border-radius: 999px;
|
||||
background: var(--dsw-alias-button-info-fill);
|
||||
color: var(--dsw-alias-label-primary-foreground);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.primary:hover {
|
||||
background: var(--dsw-alias-button-info-hover);
|
||||
}
|
||||
|
||||
.primary:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
/* Stop state: same slot, dimmed brand fill — the running-state send-key
|
||||
replacement is a design gap filled by us (figma gives no stop form). */
|
||||
.stopping,
|
||||
.stopping:hover {
|
||||
background: var(--dsw-alias-button-primary-dimmed);
|
||||
color: var(--dsw-alias-brand-text);
|
||||
}
|
||||
142
packages/client/ui-conversation/src/client/skeleton/InputBar.tsx
Normal file
142
packages/client/ui-conversation/src/client/skeleton/InputBar.tsx
Normal file
@@ -0,0 +1,142 @@
|
||||
// InputBar: the one composer input (figma Input_Bottom). The same component
|
||||
// serves the empty state (variant='hero': centered launch card) and the
|
||||
// resident composer (variant='composer') — the empty→content transition is a
|
||||
// position move of this component, never a swap (layout ruling). Running
|
||||
// LOCKS the input: textarea disabled with the draft visible, stop is the only
|
||||
// action; the turn ending re-enables and refocuses.
|
||||
|
||||
import { useEffect, useRef } from 'react'
|
||||
import type { KeyboardEvent, MouseEvent, ReactNode } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import css from './InputBar.module.css'
|
||||
|
||||
/** Prompt failure surface (mirrors the session snapshot's promptError shape). */
|
||||
export interface InputBarError {
|
||||
op: 'send' | 'stop'
|
||||
message: string
|
||||
}
|
||||
|
||||
export interface InputBarProps {
|
||||
draft: string
|
||||
running: boolean
|
||||
disabled: boolean
|
||||
error: InputBarError | null
|
||||
/** Hero = empty-state centered card; composer = resident bottom bar. */
|
||||
variant: 'hero' | 'composer'
|
||||
placeholder?: string
|
||||
/** Optional leading accessory row content (the empty state mounts its cwd picker here). */
|
||||
accessory?: ReactNode
|
||||
onDraftChange: (text: string) => void
|
||||
onSend: (mode: 'queue' | 'steer') => void
|
||||
onStop: () => void
|
||||
}
|
||||
|
||||
export function InputBar({
|
||||
draft, running, disabled, error, variant, placeholder, accessory, onDraftChange, onSend, onStop,
|
||||
}: InputBarProps) {
|
||||
const empty = draft.trim() === ''
|
||||
const inputRef = useRef<HTMLTextAreaElement | null>(null)
|
||||
// IME guard: composition Enter picks a candidate, it must not send. The ref outlives renders;
|
||||
// clearing is deferred one tick because Safari delivers the closing keydown AFTER compositionend.
|
||||
const composingRef = useRef(false)
|
||||
const onCompositionStart = (): void => {
|
||||
composingRef.current = true
|
||||
}
|
||||
const onCompositionEnd = (): void => {
|
||||
setTimeout(() => {
|
||||
composingRef.current = false
|
||||
}, 10)
|
||||
}
|
||||
|
||||
// Locked while running: the browser drops keystrokes AND focus on a disabled
|
||||
// textarea — no sending mid-turn, stop or wait.
|
||||
const locked = disabled || running
|
||||
|
||||
// Unlock (mount / session switch / turn end) returns focus to the box.
|
||||
useEffect(() => {
|
||||
if (!locked) inputRef.current?.focus()
|
||||
}, [locked])
|
||||
|
||||
const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>): void => {
|
||||
if (e.key !== 'Enter') return
|
||||
if (composingRef.current || e.nativeEvent.isComposing || e.nativeEvent.keyCode === 229) return
|
||||
if (e.shiftKey) return // native newline
|
||||
if (e.ctrlKey || e.metaKey) {
|
||||
// execCommand keeps the browser undo stack intact, unlike a setState splice.
|
||||
e.preventDefault()
|
||||
document.execCommand('insertText', false, '\n')
|
||||
return
|
||||
}
|
||||
e.preventDefault()
|
||||
if (e.repeat) return // held-down Enter must not machine-gun sends
|
||||
if (!empty && !locked) onSend('queue')
|
||||
}
|
||||
|
||||
// Button presses steal focus from the textarea; suppress at mousedown so typing continues seamlessly.
|
||||
const keepFocus = (e: MouseEvent<HTMLButtonElement>): void => {
|
||||
e.preventDefault()
|
||||
inputRef.current?.focus()
|
||||
}
|
||||
|
||||
const primaryLabel = running ? '停止' : '发送'
|
||||
const onPrimary = (): void => {
|
||||
if (running) {
|
||||
onStop()
|
||||
return
|
||||
}
|
||||
/* v8 ignore next -- defensive: the primary button is disabled while empty||disabled, so a click cannot reach the false arm. */
|
||||
if (!empty && !disabled) onSend('queue')
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={clsx(css.root, variant === 'hero' && css.hero)}>
|
||||
{error !== null && (
|
||||
<div className={css.error}>
|
||||
{error.op === 'stop' ? '停止失败' : '发送失败'}:{error.message}
|
||||
</div>
|
||||
)}
|
||||
<div className={css.card}>
|
||||
{accessory !== undefined && <div className={css.accessory}>{accessory}</div>}
|
||||
{/* Mirror-div auto-grow: the hidden mirror renders draft+'\n' and stretches the wrapper
|
||||
(min/max capped in CSS); the absolutely-positioned textarea rides its height. Counting
|
||||
rows by '\n' cannot see soft wraps. */}
|
||||
<div className={css.grow}>
|
||||
<textarea
|
||||
ref={inputRef}
|
||||
className={css.input}
|
||||
value={draft}
|
||||
disabled={locked}
|
||||
placeholder={placeholder ?? (disabled ? '会话不可用' : running ? '回复生成中,可停止后再输入' : '输入消息,Enter 发送,Shift+Enter 换行')}
|
||||
rows={2}
|
||||
onChange={(e) => onDraftChange(e.target.value)}
|
||||
onKeyDown={onKeyDown}
|
||||
onCompositionStart={onCompositionStart}
|
||||
onCompositionEnd={onCompositionEnd}
|
||||
/>
|
||||
<div aria-hidden className={css.mirror}>{`${draft}\n`}</div>
|
||||
</div>
|
||||
<div className={css.row}>
|
||||
<button
|
||||
type="button"
|
||||
className={clsx(css.primary, running && css.stopping)}
|
||||
aria-label={primaryLabel}
|
||||
title={running ? '停止本轮' : '发送(Enter)'}
|
||||
disabled={!running && (empty || disabled)}
|
||||
onMouseDown={keepFocus}
|
||||
onClick={onPrimary}
|
||||
>
|
||||
{running ? (
|
||||
<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden>
|
||||
<rect x="4" y="4" width="8" height="8" rx="1.5" fill="currentColor" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden>
|
||||
<path d="M8 13V3.8M8 3.8L3.8 8M8 3.8L12.2 8" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" fill="none" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/* Sample bash rows: deliberately distinct from ToolRow so the differential
|
||||
registry hit is visible at a glance. */
|
||||
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
height: 24px;
|
||||
min-width: 0;
|
||||
cursor: pointer;
|
||||
border-radius: 6px;
|
||||
font-family: var(--ds-font-family-code);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.row:hover {
|
||||
background: var(--dsw-alias-interactive-bg-hover);
|
||||
}
|
||||
|
||||
.prompt {
|
||||
flex: none;
|
||||
color: var(--dsw-alias-state-success-primary);
|
||||
}
|
||||
|
||||
.scopeBadge {
|
||||
flex: none;
|
||||
padding: 0 6px;
|
||||
border-radius: 6px;
|
||||
font-size: 11px;
|
||||
line-height: 18px;
|
||||
color: var(--dsw-alias-label-primary-foreground);
|
||||
background: var(--dsw-alias-state-business-primary);
|
||||
}
|
||||
|
||||
.command {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
}
|
||||
|
||||
.err {
|
||||
flex: none;
|
||||
color: var(--dsw-alias-state-error-primary);
|
||||
font-size: 11px;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// Bash toolview sample, written in third-party posture: everything below uses
|
||||
// only the public registration surface (ctx.toolviews.register + ToolViewProps)
|
||||
// — the differential-rendering acceptance proof for the registry chain.
|
||||
// Two registrations: a global bash row, and a scope-filtered variant that
|
||||
// takes over for matching sessions only (later registration wins its tier).
|
||||
|
||||
import type { SessionId } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { ToolViewProps } from '../contract/toolview.ts'
|
||||
import type { ToolViewRegistry } from './registry.ts'
|
||||
import { toolRowModel, type ToolCallBlock } from '../contract/tool-call-model.ts'
|
||||
import css from './bash-sample.module.css'
|
||||
|
||||
/** Global bash row: command-first monospace summary (replaces the generic row). */
|
||||
export function BashRow({ toolName, block, actions }: ToolViewProps) {
|
||||
const model = toolRowModel(toolName, block as ToolCallBlock)
|
||||
return (
|
||||
<div className={css.row} data-sample="bash-global" onClick={actions.openDetails}>
|
||||
<span className={css.prompt} aria-hidden>$</span>
|
||||
<span className={css.command}>{model.summary}</span>
|
||||
{model.state === 'error' && <span className={css.err}>failed</span>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Scoped variant: visually distinct so the differential hit is observable. */
|
||||
export function ScopedBashRow({ toolName, block, actions }: ToolViewProps) {
|
||||
const model = toolRowModel(toolName, block as ToolCallBlock)
|
||||
return (
|
||||
<div className={css.row} data-sample="bash-scoped" onClick={actions.openDetails}>
|
||||
<span className={css.scopeBadge}>scoped</span>
|
||||
<span className={css.command}>{model.summary}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Register both sample rows.
|
||||
* @param toolviews - the conversation plugin's registry service.
|
||||
* @param scope - session filter for the scoped variant.
|
||||
* @returns disposer removing both registrations.
|
||||
*/
|
||||
export function registerBashSamples(
|
||||
toolviews: ToolViewRegistry,
|
||||
scope: (sessionId: SessionId) => boolean,
|
||||
): () => void {
|
||||
const offGlobal = toolviews.register('bash', BashRow)
|
||||
const offScoped = toolviews.register('bash', ScopedBashRow, { scope })
|
||||
return () => {
|
||||
offGlobal()
|
||||
offScoped()
|
||||
}
|
||||
}
|
||||
103
packages/client/ui-conversation/src/client/toolviews/registry.ts
Normal file
103
packages/client/ui-conversation/src/client/toolviews/registry.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* ToolViewRegistry: named per-tool component registry, session-scope aware
|
||||
* (api-contracts v3 section 7). Consumed by chat now, trajectory/waterfall
|
||||
* later — deliberately a named service, not a SlotMap key. The tool key set
|
||||
* is deliberately open (model-side tools arrive at runtime): the strong
|
||||
* typing lives inside the Entry — `I` is inferred from the inject factory at
|
||||
* the register site and proves component props ⊇ ToolViewProps & I.
|
||||
*/
|
||||
import type { FC } from 'react'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { ResolvedToolView, ToolViewOptions, ToolViewProps } from '../contract/toolview.ts'
|
||||
|
||||
/** Stored registration: the per-registration inject parameter is erased
|
||||
* (storage-erase/read-restore is the typed-Map boundary, one cast budgeted). */
|
||||
interface Registration extends ToolViewOptions {
|
||||
component: FC<ToolViewProps & object>
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-tool renderer registry. Resolution order: scope match (later
|
||||
* registration wins) > global (same tie-break) > undefined, where the caller
|
||||
* falls back to GenericToolCard.
|
||||
*/
|
||||
export class ToolViewRegistry {
|
||||
private byTool = new Map<string, Registration[]>()
|
||||
private version = 0
|
||||
private listeners = new Set<() => void>()
|
||||
|
||||
/**
|
||||
* Register a tool row renderer. The component must accept the shared
|
||||
* ToolViewProps plus its own injected share `I` — mismatches (missing keys,
|
||||
* wrong types, an inject factory that does not produce what the component
|
||||
* declares) are register-site compile errors.
|
||||
* @param tool - tool name the renderer takes over.
|
||||
* @param component - row component over ToolViewProps & I.
|
||||
* @param opts - optional session-scope filter and private inject factory.
|
||||
* @returns disposer removing this registration.
|
||||
*/
|
||||
register<I extends object = object>(
|
||||
tool: string, component: FC<ToolViewProps & I>, opts?: ToolViewOptions<I>): () => void {
|
||||
const list = this.byTool.get(tool) ?? []
|
||||
if (list.length === 0) this.byTool.set(tool, list)
|
||||
// Storage erases I (heterogeneous registrations share one list); resolve
|
||||
// restores the erased shape on the read face.
|
||||
const entry: Registration = { component: component as FC<ToolViewProps & object>, ...opts }
|
||||
list.push(entry)
|
||||
this.bump()
|
||||
let disposed = false
|
||||
return () => {
|
||||
if (disposed) return
|
||||
disposed = true
|
||||
const at = list.indexOf(entry)
|
||||
/* v8 ignore next -- negative arm: an entry lives in one list and only its
|
||||
own once-guarded disposer removes it, so a live disposer always finds it. */
|
||||
if (at >= 0) list.splice(at, 1)
|
||||
if (list.length === 0) this.byTool.delete(tool)
|
||||
this.bump()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the renderer for a tool in a session.
|
||||
* @param tool - tool name.
|
||||
* @param sessionId - session the row renders in (fed to scope filters).
|
||||
* @returns resolved view, or undefined when nothing matches.
|
||||
*/
|
||||
resolve(tool: string, sessionId: SessionId): ResolvedToolView | undefined {
|
||||
const list = this.byTool.get(tool)
|
||||
if (list === undefined) return undefined
|
||||
let global: Registration | undefined
|
||||
let scoped: Registration | undefined
|
||||
for (const entry of list) {
|
||||
if (entry.scope === undefined) global = entry
|
||||
else if (entry.scope(sessionId)) scoped = entry
|
||||
}
|
||||
const hit = scoped ?? global
|
||||
if (hit === undefined) return undefined
|
||||
return hit.inject === undefined ? { component: hit.component } : { component: hit.component, inject: hit.inject }
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to registration changes (render outlets re-resolve on notify).
|
||||
* @param fn - change listener.
|
||||
* @returns disposer.
|
||||
*/
|
||||
subscribe(fn: () => void): () => void {
|
||||
this.listeners.add(fn)
|
||||
return () => this.listeners.delete(fn)
|
||||
}
|
||||
|
||||
/**
|
||||
* Monotonic registration version for uSES getSnapshot.
|
||||
* @returns current version.
|
||||
*/
|
||||
getVersion(): number {
|
||||
return this.version
|
||||
}
|
||||
|
||||
private bump(): void {
|
||||
this.version += 1
|
||||
for (const fn of this.listeners) fn()
|
||||
}
|
||||
}
|
||||
6
packages/client/ui-conversation/src/css-modules.d.ts
vendored
Normal file
6
packages/client/ui-conversation/src/css-modules.d.ts
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
declare module '*.module.css' {
|
||||
const classes: Record<string, string>
|
||||
export default classes
|
||||
}
|
||||
|
||||
declare module '*.css'
|
||||
10
packages/client/ui-conversation/src/index.ts
Normal file
10
packages/client/ui-conversation/src/index.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* Conversation plugin, node half. Pure UI plugin: the empty apply exists so
|
||||
* the plugin appears in the host cordis.yml / Loader (load and lifecycle
|
||||
* follow the host; the browser half ships via exports["./client"], discovered
|
||||
* through the package.json dshClient declaration). Contract: api-contracts
|
||||
* v3 sections 0.3 and 7.
|
||||
*/
|
||||
|
||||
/** Host plugin body — no host-side behavior for the conversation plugin. */
|
||||
export function apply(): void {}
|
||||
33
packages/client/ui-conversation/src/invariant.ts
Normal file
33
packages/client/ui-conversation/src/invariant.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* Package-owned invariant companion for `@deepseek-ai/dsh-client-ui-conversation`.
|
||||
* @module @deepseek-ai/dsh-client-ui-conversation/invariant
|
||||
*/
|
||||
|
||||
/* jscpd:ignore-start */
|
||||
import type { Context } from 'cordis'
|
||||
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
|
||||
|
||||
const PACKAGE_NAME = '@deepseek-ai/dsh-client-ui-conversation'
|
||||
|
||||
/** Cordis companion plugin name. */
|
||||
export const name = 'client-ui-conversation-invariant'
|
||||
/** Service required before the companion can reserve package ownership. */
|
||||
export const inject = ['invariants']
|
||||
|
||||
/**
|
||||
* No runtime invariant: the conversation service emits no cordis events — its
|
||||
* view and toolview registries notify through package-local subscribe faces
|
||||
* whose ordering (synchronous version bump before notification) is exercised
|
||||
* directly by the behavior specs, and the per-scope store accounts are owned
|
||||
* mutable state with no cross-plugin observer to contradict.
|
||||
*/
|
||||
const install: InvariantInstaller = () => {}
|
||||
|
||||
/**
|
||||
* Register this package's invariant companion.
|
||||
* @param ctx - Cordis context carrying the invariant service.
|
||||
* @returns the installed registration's disposer after setup succeeds.
|
||||
*/
|
||||
export const apply = (ctx: Context): Promise<() => void> =>
|
||||
Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))
|
||||
/* jscpd:ignore-end */
|
||||
276
packages/client/ui-conversation/tests/apply-inject.spec.tsx
Normal file
276
packages/client/ui-conversation/tests/apply-inject.spec.tsx
Normal file
@@ -0,0 +1,276 @@
|
||||
// @vitest-environment jsdom
|
||||
// apply inject factories exercised end to end: the conversation slot surface
|
||||
// (ancestry feed, views triple, active view, composer choreography incl.
|
||||
// optimistic clear + failure restore, renderView chrome assembly, watch-driven
|
||||
// open), the details surface, and the empty-state surface (cwd derivation
|
||||
// cache). Complements chat-apply.spec.tsx, which stops at registration.
|
||||
|
||||
import { Context } from 'cordis'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { act, cleanup, render } from '@testing-library/react'
|
||||
import { createElement } from 'react'
|
||||
import { createSnapshotStore, bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react'
|
||||
import { SlotsService, scopeOf } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { ConversationSnapshot, SessionId, SessionListState } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { apply, inject } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import type { ConversationService, ViewEntry } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import type { SessionBinding } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-layout/client'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
const ROOT = 'root-1' as SessionId
|
||||
|
||||
const SCOPE_TAG: symbol = (() => {
|
||||
const recorded: (string | symbol)[] = []
|
||||
const spy = new Proxy(new Context(), {
|
||||
get(target, prop, receiver) {
|
||||
recorded.push(prop)
|
||||
return Reflect.get(target, prop, receiver)
|
||||
},
|
||||
})
|
||||
void scopeOf(spy as Context)
|
||||
const symbol = recorded.find((p): p is symbol => typeof p === 'symbol')
|
||||
if (symbol === undefined) throw new Error('scopeOf probe recorded no symbol read')
|
||||
return symbol
|
||||
})()
|
||||
|
||||
function snapshotBase(): ConversationSnapshot {
|
||||
return {
|
||||
sessionId: ROOT, nodes: [], foldDegraded: false, partial: null, runningCalls: [],
|
||||
pending: [], running: false, removed: false, openState: 'open', openError: null,
|
||||
hasMore: false, loadingOlder: false, promptError: null, lastAgentError: null,
|
||||
} as ConversationSnapshot
|
||||
}
|
||||
|
||||
async function bench() {
|
||||
const ctx = new Context()
|
||||
const slotsFiber = ctx.plugin(SlotsService)
|
||||
await slotsFiber.await()
|
||||
|
||||
const listStore = createSnapshotStore<SessionListState>({
|
||||
ids: [ROOT],
|
||||
byId: { [ROOT]: { id: ROOT, title: 'R', cwd: '/proj', running: false, updatedAt: 1 } },
|
||||
})
|
||||
const snap = snapshotBase()
|
||||
const sessionFake = {
|
||||
getSnapshot: () => snap,
|
||||
subscribe: () => () => {},
|
||||
useSelector: undefined as unknown,
|
||||
open: vi.fn(() => Promise.resolve()),
|
||||
loadOlder: vi.fn(() => Promise.resolve()),
|
||||
prompt: vi.fn<() => Promise<{ ok: boolean; value?: object; error?: { code: string; message: string } }>>(
|
||||
() => Promise.resolve({ ok: true, value: { accepted: true } })),
|
||||
cancel: vi.fn<() => Promise<{ ok: boolean; value?: object; error?: { code: string; message: string } }>>(
|
||||
() => Promise.resolve({ ok: true, value: { accepted: true } })),
|
||||
}
|
||||
sessionFake.useSelector = bindSnapshotSelector(sessionFake as never)
|
||||
const scopes = new Map<SessionId, Context>()
|
||||
const mint = (id: SessionId): Context => {
|
||||
let scoped = scopes.get(id)
|
||||
if (scoped === undefined) {
|
||||
scoped = ctx.plugin(() => {}).ctx.extend({ [SCOPE_TAG]: id }) as Context
|
||||
scopes.set(id, scoped)
|
||||
}
|
||||
return scoped
|
||||
}
|
||||
const sessionsFake = {
|
||||
list: listStore,
|
||||
manager: { get: () => sessionFake },
|
||||
ancestry: (id: SessionId) => {
|
||||
const s = listStore.getSnapshot().byId[id]
|
||||
return s === undefined ? [] : [s]
|
||||
},
|
||||
scope: (id: SessionId) => mint(id),
|
||||
create: vi.fn(() => Promise.resolve(ROOT)),
|
||||
}
|
||||
ctx.provide('sessions', sessionsFake)
|
||||
const layoutFake = {
|
||||
current: createSnapshotStore<{ sessionId?: SessionId; viewFor: Record<string, string> }>({ viewFor: {} }),
|
||||
open: vi.fn(), openView: vi.fn(), openDetails: vi.fn(), closeDetails: vi.fn(),
|
||||
}
|
||||
ctx.provide('layout', layoutFake)
|
||||
ctx.provide('i18n', { bind: () => (key: string) => key })
|
||||
|
||||
const slots = ctx.get('slots') as SlotsService
|
||||
slots.define('conversation', { kind: 'single', scope: 'session' })
|
||||
slots.define('details', { kind: 'single', scope: 'session' })
|
||||
slots.define('conversation.empty', { kind: 'single', scope: 'root' })
|
||||
|
||||
const fiber = ctx.plugin({ inject: [...inject], apply })
|
||||
await fiber.await()
|
||||
|
||||
const binding: SessionBinding = {
|
||||
sessionId: ROOT as never,
|
||||
session: { useSelector: sessionFake.useSelector } as never,
|
||||
ctx: mint(ROOT) as never,
|
||||
}
|
||||
const entryOf = (key: 'conversation' | 'details' | 'conversation.empty') => {
|
||||
const entries = slots.entries(key)
|
||||
return entries[0]! as { options: { inject: (b: unknown) => Record<string, unknown> } }
|
||||
}
|
||||
return { ctx, slots, binding, sessionFake, sessionsFake, layoutFake, mint, entryOf }
|
||||
}
|
||||
|
||||
describe('conversation slot inject surface', () => {
|
||||
it('assembles the full surface and pulls history through the watch signal', async () => {
|
||||
const b = await bench()
|
||||
const injected = b.entryOf('conversation').options.inject(b.binding) as {
|
||||
useAncestry: () => readonly { id: SessionId }[]
|
||||
views: { list(): readonly ViewEntry[]; version(): number; subscribe(fn: () => void): () => void }
|
||||
useActiveView: () => string | undefined
|
||||
composer: { useDraft: () => string; setDraft(t: string): void; send(m: string): void; stop(): void }
|
||||
actions: { openView(v: string): void; open(id: SessionId): void }
|
||||
renderView: (entry: ViewEntry) => unknown
|
||||
}
|
||||
expect(b.sessionFake.open).toHaveBeenCalledTimes(1)
|
||||
expect(injected.views.list().map(v => v.id)).toEqual(['chat'])
|
||||
injected.actions.openView('chat')
|
||||
expect(b.layoutFake.openView).toHaveBeenCalledWith(ROOT, 'chat')
|
||||
injected.actions.open(ROOT)
|
||||
expect(b.layoutFake.open).toHaveBeenCalledWith(ROOT)
|
||||
})
|
||||
|
||||
it('composer send trims, optimistically clears, and restores on failure; stop swallows rejection', async () => {
|
||||
const b = await bench()
|
||||
const injected = b.entryOf('conversation').options.inject(b.binding) as {
|
||||
composer: { setDraft(t: string): void; send(m: 'queue'): void; stop(): void }
|
||||
}
|
||||
const scoped = b.mint(ROOT).get('conversation') as ConversationService
|
||||
// Whitespace-only draft: no send.
|
||||
scoped.drafts.set(' ')
|
||||
injected.composer.send('queue')
|
||||
expect(b.sessionFake.prompt).not.toHaveBeenCalled()
|
||||
// Success: cleared and stays cleared.
|
||||
injected.composer.setDraft('hello')
|
||||
injected.composer.send('queue')
|
||||
expect(scoped.drafts.getSnapshot()).toBe('')
|
||||
await Promise.resolve()
|
||||
expect(b.sessionFake.prompt).toHaveBeenCalledWith([{ type: 'text', text: 'hello' }], 'queue')
|
||||
// Failure: restored (draft still empty when the rejection lands).
|
||||
b.sessionFake.prompt.mockResolvedValueOnce({ ok: false, error: { code: 'agent-busy', message: 'b' } })
|
||||
injected.composer.setDraft('retry me')
|
||||
injected.composer.send('queue')
|
||||
await vi.waitFor(() => {
|
||||
expect(scoped.drafts.getSnapshot()).toBe('retry me')
|
||||
})
|
||||
// Failure with new typing: no clobber.
|
||||
b.sessionFake.prompt.mockResolvedValueOnce({ ok: false, error: { code: 'agent-busy', message: 'b' } })
|
||||
injected.composer.send('queue')
|
||||
injected.composer.setDraft('typed during flight')
|
||||
await new Promise(r => setTimeout(r, 0))
|
||||
expect(scoped.drafts.getSnapshot()).toBe('typed during flight')
|
||||
// Stop failure is swallowed (promptError owns the surface).
|
||||
b.sessionFake.cancel.mockResolvedValueOnce({ ok: false, error: { code: 'internal', message: 'x' } })
|
||||
injected.composer.stop()
|
||||
await new Promise(r => setTimeout(r, 0))
|
||||
})
|
||||
|
||||
it('view actions forward: openDetails writes selection through the scoped service, loadOlder hits the session', async () => {
|
||||
const b = await bench()
|
||||
const injected = b.entryOf('conversation').options.inject(b.binding) as {
|
||||
// viewProps rides renderView's closure; reach the actions through a rendered entry.
|
||||
renderView: (entry: ViewEntry) => React.ReactNode
|
||||
}
|
||||
let captured: { openDetails(t: { turnSeq: number; callId?: string }): void; loadOlder(): void } | undefined
|
||||
const Probe = (p: { actions: typeof captured }) => {
|
||||
captured = p.actions
|
||||
return null
|
||||
}
|
||||
render(createElement('div', null, injected.renderView({
|
||||
id: 'chat', label: 'Chat', component: Probe,
|
||||
} as unknown as ViewEntry)))
|
||||
captured!.openDetails({ turnSeq: 2, callId: 'c1' })
|
||||
expect(b.layoutFake.openDetails).toHaveBeenCalledTimes(1)
|
||||
const scoped = b.mint(ROOT).get('conversation') as import('@deepseek-ai/dsh-client-ui-conversation/client').ConversationService
|
||||
expect(scoped.selection.getSnapshot()).toEqual({ turnSeq: 2, callId: 'c1' })
|
||||
captured!.loadOlder()
|
||||
expect(b.sessionFake.loadOlder).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('renderView mounts chrome header/footer around the view body', async () => {
|
||||
const b = await bench()
|
||||
const injected = b.entryOf('conversation').options.inject(b.binding) as {
|
||||
renderView: (entry: ViewEntry) => React.ReactNode
|
||||
}
|
||||
const entry = {
|
||||
id: 'chat', label: 'Chat',
|
||||
component: () => createElement('div', { 'data-testid': 'body' }),
|
||||
chrome: {
|
||||
header: () => createElement('div', { 'data-testid': 'hd' }),
|
||||
footer: () => createElement('div', { 'data-testid': 'ft' }),
|
||||
},
|
||||
} as unknown as ViewEntry
|
||||
const view = render(createElement('div', null, injected.renderView(entry)))
|
||||
expect(view.getByTestId('hd')).toBeTruthy()
|
||||
expect(view.getByTestId('body')).toBeTruthy()
|
||||
expect(view.getByTestId('ft')).toBeTruthy()
|
||||
// Ancestry and draft/active-view hooks execute inside a component tree.
|
||||
const HookProbe = () => {
|
||||
const injected2 = b.entryOf('conversation').options.inject(b.binding) as {
|
||||
useAncestry: () => readonly { title: string }[]
|
||||
useActiveView: () => string | undefined
|
||||
composer: { useDraft: () => string }
|
||||
}
|
||||
const chain = injected2.useAncestry()
|
||||
const active = injected2.useActiveView()
|
||||
const draft = injected2.composer.useDraft()
|
||||
return createElement('i', { 'data-testid': 'probe' }, `${chain.length}|${active ?? 'none'}|${draft}`)
|
||||
}
|
||||
const probe = render(createElement(HookProbe))
|
||||
// Draft content carries over from the composer case (per-scope store is
|
||||
// process-resident); the probe asserts hook wiring, not draft value.
|
||||
expect(probe.getByTestId('probe').textContent).toMatch(/^1\|none\|/)
|
||||
// A list-store update while mounted drives the ancestry selector's
|
||||
// shallowEqual arm (same derived chain → short-circuit, no re-render churn).
|
||||
await act(async () => {
|
||||
b.sessionsFake.list.update((d: { byId: Record<string, { updatedAt: number }> }) => {
|
||||
d.byId[ROOT]!.updatedAt = 2
|
||||
})
|
||||
})
|
||||
expect(probe.getByTestId('probe').textContent).toMatch(/^1\|none\|/)
|
||||
// The views read-face triple forwards to the service registry.
|
||||
const injected3 = b.entryOf('conversation').options.inject(b.binding) as {
|
||||
views: { list(): readonly { id: string }[]; subscribe(fn: () => void): () => void; version(): number }
|
||||
}
|
||||
expect(injected3.views.list().map(v => v.id)).toEqual(['chat'])
|
||||
const beforeVersion = injected3.views.version()
|
||||
const listener = vi.fn()
|
||||
const unsub = injected3.views.subscribe(listener)
|
||||
const conversation = b.ctx.get('conversation') as import('@deepseek-ai/dsh-client-ui-conversation/client').ConversationService
|
||||
const offExtra = conversation.registerView({ id: 'chat2', label: 'X', component: () => null } as never)
|
||||
expect(listener).toHaveBeenCalled()
|
||||
expect(injected3.views.version()).toBeGreaterThan(beforeVersion)
|
||||
offExtra()
|
||||
unsub()
|
||||
})
|
||||
})
|
||||
|
||||
describe('details and empty inject surfaces', () => {
|
||||
it('details surface wires selection and closeDetails', async () => {
|
||||
const b = await bench()
|
||||
const injected = b.entryOf('details').options.inject(b.binding) as {
|
||||
useSelection: unknown
|
||||
actions: { closeDetails(): void }
|
||||
}
|
||||
expect(injected.useSelection).toBeTypeOf('function')
|
||||
injected.actions.closeDetails()
|
||||
expect(b.layoutFake.closeDetails).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('empty surface derives the deduped cwd set with a per-state cache and starts sessions', async () => {
|
||||
const b = await bench()
|
||||
const injected = b.entryOf('conversation.empty').options.inject({ ctx: b.ctx }) as {
|
||||
useCwds: (sel: (s: readonly string[]) => unknown, eq?: unknown) => unknown
|
||||
actions: { startSession(opts: { text: string; mode: 'queue' }): Promise<void> }
|
||||
}
|
||||
const CwdsProbe = () => {
|
||||
const cwds = injected.useCwds(s => s) as readonly string[]
|
||||
return createElement('i', { 'data-testid': 'cwds' }, cwds.join(','))
|
||||
}
|
||||
const view = render(createElement(CwdsProbe))
|
||||
expect(view.getByTestId('cwds').textContent).toBe('/proj')
|
||||
await injected.actions.startSession({ text: 'go', mode: 'queue' })
|
||||
expect(b.sessionsFake.create).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
105
packages/client/ui-conversation/tests/chat-apply.spec.tsx
Normal file
105
packages/client/ui-conversation/tests/chat-apply.spec.tsx
Normal file
@@ -0,0 +1,105 @@
|
||||
// @vitest-environment jsdom
|
||||
// apply wiring: services provided, chat view + footer chrome registered, the
|
||||
// three slot registrations land against ui-layout-shaped specs, and the bash
|
||||
// samples resolve differentially (sub-session default scope). Full-chain
|
||||
// rendering belongs to the shell e2e; this spec stops at the assembly surface.
|
||||
|
||||
import { Context } from 'cordis'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { createSnapshotStore } from '@deepseek-ai/dsh-client-web-react'
|
||||
import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { SessionId, SessionListState } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { apply, inject, ToolViewRegistry } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import type { ConversationService } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
// Type-only: pulls ui-layout's SlotMap declaration merge into this spec's
|
||||
// program so the slot keys below typecheck in the client lane.
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-layout/client'
|
||||
|
||||
const ROOT = 'root-1' as SessionId
|
||||
const CHILD = 'child-1' as SessionId
|
||||
|
||||
async function bench() {
|
||||
const ctx = new Context()
|
||||
const slotsFiber = ctx.plugin(SlotsService)
|
||||
await slotsFiber.await()
|
||||
|
||||
const listStore = createSnapshotStore<SessionListState>({
|
||||
ids: [ROOT, CHILD],
|
||||
byId: {
|
||||
[ROOT]: { id: ROOT, title: 'R', running: false, updatedAt: 1 },
|
||||
[CHILD]: { id: CHILD, title: 'C', parentId: ROOT, running: false, updatedAt: 2 },
|
||||
},
|
||||
})
|
||||
const sessionsFake = {
|
||||
list: listStore,
|
||||
manager: { get: vi.fn() },
|
||||
ancestry: () => [],
|
||||
scope: () => undefined,
|
||||
create: vi.fn(),
|
||||
}
|
||||
ctx.provide('sessions', sessionsFake)
|
||||
ctx.provide('layout', {
|
||||
current: createSnapshotStore<{ viewFor: Record<string, string> }>({ viewFor: {} }),
|
||||
open: vi.fn(), openView: vi.fn(), openDetails: vi.fn(), closeDetails: vi.fn(),
|
||||
})
|
||||
ctx.provide('i18n', { bind: () => (key: string) => key })
|
||||
|
||||
// Specs owned by ui-layout in production; declared here so registrations land.
|
||||
const slots = ctx.get('slots') as SlotsService
|
||||
slots.define('conversation', { kind: 'single', scope: 'session' })
|
||||
slots.define('details', { kind: 'single', scope: 'session' })
|
||||
slots.define('conversation.empty', { kind: 'single', scope: 'root' })
|
||||
|
||||
const fiber = ctx.plugin({ inject: [...inject], apply })
|
||||
return { ctx, fiber, slots }
|
||||
}
|
||||
|
||||
describe('apply wiring', () => {
|
||||
it('provides conversation and toolviews services', async () => {
|
||||
const b = await bench()
|
||||
await b.fiber.await()
|
||||
expect(b.ctx.get('conversation')).toBeDefined()
|
||||
expect(b.ctx.get('toolviews')).toBeInstanceOf(ToolViewRegistry)
|
||||
})
|
||||
|
||||
it('registers the chat view with the stats footer', async () => {
|
||||
const b = await bench()
|
||||
await b.fiber.await()
|
||||
const conversation = b.ctx.get('conversation') as ConversationService
|
||||
const views = conversation.views()
|
||||
expect(views.map((v) => v.id)).toEqual(['chat'])
|
||||
expect(views[0]?.chrome?.footer).toBeDefined()
|
||||
})
|
||||
|
||||
it('occupies conversation/details/conversation.empty with inject factories', async () => {
|
||||
const b = await bench()
|
||||
await b.fiber.await()
|
||||
for (const key of ['conversation', 'details', 'conversation.empty'] as const) {
|
||||
const entries = b.slots.entries(key)
|
||||
expect(entries, key).toHaveLength(1)
|
||||
expect((entries[0]!.options as { inject?: unknown }).inject, key).toBeTypeOf('function')
|
||||
}
|
||||
})
|
||||
|
||||
it('bash samples resolve differentially: scoped row for sub-sessions, global for roots', async () => {
|
||||
const b = await bench()
|
||||
await b.fiber.await()
|
||||
const toolviews = b.ctx.get('toolviews') as ToolViewRegistry
|
||||
const forChild = toolviews.resolve('bash', CHILD)
|
||||
const forRoot = toolviews.resolve('bash', ROOT)
|
||||
expect(forChild).toBeDefined()
|
||||
expect(forRoot).toBeDefined()
|
||||
expect(forChild!.component).not.toBe(forRoot!.component)
|
||||
})
|
||||
|
||||
it('plugin fiber disposal collects every registration (unload cascade)', async () => {
|
||||
const b = await bench()
|
||||
await b.fiber.await()
|
||||
await b.fiber.dispose()
|
||||
expect(b.slots.entries('conversation')).toHaveLength(0)
|
||||
expect(b.slots.entries('details')).toHaveLength(0)
|
||||
expect(b.slots.entries('conversation.empty')).toHaveLength(0)
|
||||
expect(b.ctx.get('conversation')).toBeUndefined()
|
||||
expect(b.ctx.get('toolviews')).toBeUndefined()
|
||||
})
|
||||
})
|
||||
156
packages/client/ui-conversation/tests/chat-branch-tails.spec.tsx
Normal file
156
packages/client/ui-conversation/tests/chat-branch-tails.spec.tsx
Normal file
@@ -0,0 +1,156 @@
|
||||
// @vitest-environment jsdom
|
||||
// Remaining chat branch tails: MessageItem context/unknown/steering arms,
|
||||
// ToolViewOutlet inject cache + crash fallback + retry, StatsLine no-cache
|
||||
// join, PendingCard reason strip, AssistantMarkdown single-line reasoning,
|
||||
// ChatView view-body fallbacks, and apply's action lambdas.
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { cleanup, render } from '@testing-library/react'
|
||||
import { act } from '@testing-library/react'
|
||||
import type { SessionId, ToolResultNode } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { RpcId } from '@deepseek-ai/dsh-client-connection/client'
|
||||
import { bindSnapshotSelector, createSessionProvider } from '@deepseek-ai/dsh-client-web-react'
|
||||
import type { SessionBinding as ReactSessionBinding, UseSession } from '@deepseek-ai/dsh-client-web-react'
|
||||
import { ToolViewRegistry } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import type { ToolViewProps, Translate } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import { MessageItem } from '../src/client/chat/MessageItem.tsx'
|
||||
import { PendingCard } from '../src/client/chat/PendingCard.tsx'
|
||||
import { AssistantMarkdown } from '../src/client/chat/AssistantMarkdown.tsx'
|
||||
import { StatsLine } from '../src/client/chat/StatsLine.tsx'
|
||||
import { ToolViewOutlet } from '../src/client/chat/ToolViewOutlet.tsx'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
const SID = 's1' as SessionId
|
||||
|
||||
const result = (callId: string): ToolResultNode => ({
|
||||
kind: 'tool-result', seq: 3, callId,
|
||||
call: { name: 'bash', argsRaw: '{"command":"x"}' },
|
||||
content: [], isError: false, callView: null, resultView: null,
|
||||
})
|
||||
|
||||
const viewProps = (): ToolViewProps => ({
|
||||
callId: 'c1', toolName: 'bash', block: result('c1'),
|
||||
useSession: (() => { throw new Error('unused') }) as unknown as UseSession,
|
||||
actions: { openDetails: vi.fn() },
|
||||
t: ((k: string) => k) as Translate,
|
||||
})
|
||||
|
||||
describe('MessageItem arms', () => {
|
||||
it('steering bubbles carry the interjection badge and non-text rest blocks', () => {
|
||||
const view = render(
|
||||
<MessageItem node={{
|
||||
kind: 'steering', seq: 2, turn: 1, source: null,
|
||||
content: [{ type: 'text', text: 'steer!' }, { type: 'image', data: 'x' }] as never,
|
||||
} as never}
|
||||
/>,
|
||||
)
|
||||
expect(view.getByText('插话')).toBeTruthy()
|
||||
expect(view.getByText('steer!')).toBeTruthy()
|
||||
expect(view.getByText(/附加内容块/)).toBeTruthy()
|
||||
})
|
||||
|
||||
it('context and unknown nodes render their JSON rows', () => {
|
||||
const ctxView = render(
|
||||
<MessageItem node={{ kind: 'context', seq: 3, content: [], source: null, meta: { k: 1 } } as never} />,
|
||||
)
|
||||
expect(ctxView.getByText(/上下文注入/)).toBeTruthy()
|
||||
const unknownView = render(
|
||||
<MessageItem node={{ kind: 'unknown', seq: 4, type: 'surface/next', data: { x: 1 } } as never} />,
|
||||
)
|
||||
expect(unknownView.getByText(/未知 surface 事件:surface\/next/)).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
describe('small branch tails', () => {
|
||||
it('PendingCard approval reason renders when present', () => {
|
||||
const view = render(
|
||||
<PendingCard item={{ kind: 'approval', rpcId: 'r1' as RpcId, approvalId: 'a1', toolName: 'rm', reason: 'careful' }} />,
|
||||
)
|
||||
expect(view.getByText('careful')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('AssistantMarkdown single-line reasoning summary skips the newline cut', () => {
|
||||
const view = render(
|
||||
<AssistantMarkdown blocks={[{ kind: 'reasoning', text: 'one-liner' }]} streaming={false} />,
|
||||
)
|
||||
expect(view.getByText('one-liner')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('StatsLine omits the cache-hit segment when no input accounting exists at all', () => {
|
||||
// cacheHitPct is null only when input+cacheRead are both zero (pure
|
||||
// output accounting) — any input makes it a real 0%.
|
||||
const snap = {
|
||||
nodes: [{ kind: 'assistant', seq: 1, turn: 1, step: 1, blocks: [], usage: { outputTokens: 10 } }],
|
||||
}
|
||||
const source = { getSnapshot: () => snap, subscribe: () => () => {} }
|
||||
const view = render(
|
||||
<StatsLine sessionId={SID} useSession={bindSnapshotSelector(source) as unknown as UseSession} />,
|
||||
)
|
||||
expect(view.getByText('10 tokens · 1 turns · 1 steps')).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
describe('ToolViewOutlet dispatch', () => {
|
||||
it('caches the inject factory per (registration x binding) and merges its props', () => {
|
||||
const registry = new ToolViewRegistry()
|
||||
const inject = vi.fn(() => ({ extra: 'injected' }))
|
||||
registry.register('bash',
|
||||
(p: ToolViewProps & { extra: string }) => <div data-testid="row">{p.extra}</div>,
|
||||
{ inject })
|
||||
// InjectedRow reads the session binding from context: mount through the
|
||||
// real SessionProvider so the (factory x binding) cache path executes.
|
||||
const binding: ReactSessionBinding = {
|
||||
sessionId: SID,
|
||||
session: { useSelector: (() => { throw new Error('unused') }) as never },
|
||||
ctx: {},
|
||||
}
|
||||
const Provider = createSessionProvider({
|
||||
useCurrent: () => SID,
|
||||
resolveBinding: () => binding,
|
||||
renderBody: () => (
|
||||
<ToolViewOutlet registry={registry} sessionId={SID} toolName="bash" viewProps={viewProps()} />
|
||||
),
|
||||
})
|
||||
const view = render(<Provider />)
|
||||
expect(view.getByTestId('row').textContent).toBe('injected')
|
||||
expect(inject).toHaveBeenCalledTimes(1)
|
||||
// Remount against the SAME binding: cache hit, factory not re-run.
|
||||
view.unmount()
|
||||
const second = render(<Provider />)
|
||||
expect(second.getByTestId('row').textContent).toBe('injected')
|
||||
expect(inject).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('a crashing custom row falls back to GenericToolCard and retries on re-registration', () => {
|
||||
const registry = new ToolViewRegistry()
|
||||
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
// React dev builds re-dispatch boundary-caught errors as window 'error'
|
||||
// events (invokeGuardedCallback); swallow them so vitest sees the caught path.
|
||||
const swallow = (e: Event): void => { e.preventDefault() }
|
||||
window.addEventListener('error', swallow)
|
||||
try {
|
||||
const Bomb = () => { throw new Error('row bomb') }
|
||||
registry.register('bash', Bomb as never)
|
||||
const view = render(
|
||||
<ToolViewOutlet registry={registry} sessionId={SID} toolName="bash" viewProps={viewProps()} />,
|
||||
)
|
||||
// Crash caught: generic row rendered instead.
|
||||
expect(view.getByText('Bash')).toBeTruthy()
|
||||
// A new registration bumps the version; the boundary retries the custom row.
|
||||
act(() => { registry.register('bash', (() => <div data-testid="fixed" />) as never) })
|
||||
expect(view.getByTestId('fixed')).toBeTruthy()
|
||||
} finally {
|
||||
window.removeEventListener('error', swallow)
|
||||
consoleError.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('registry miss renders the generic row directly', () => {
|
||||
const registry = new ToolViewRegistry()
|
||||
const view = render(
|
||||
<ToolViewOutlet registry={registry} sessionId={SID} toolName="bash" viewProps={viewProps()} />,
|
||||
)
|
||||
expect(view.getByText('Bash')).toBeTruthy()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,178 @@
|
||||
// @vitest-environment jsdom
|
||||
// StatsLine (chrome.footer first consumer): totals derivation + the RFC hard
|
||||
// acceptance — zero renders during streaming. Bash sample: differential
|
||||
// registry hits per session, teardown reverts to the generic row.
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { act, cleanup, fireEvent, render } from '@testing-library/react'
|
||||
import type {
|
||||
AssistantMessageNode, ConversationSnapshot, SessionId, ToolResultNode,
|
||||
} from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react'
|
||||
import type { UseSession } from '@deepseek-ai/dsh-client-web-react'
|
||||
import type { ChromeProps, ToolViewProps } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import { ToolViewRegistry } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import { StatsLine, deriveStats } from '../src/client/chat/StatsLine.tsx'
|
||||
import { BashRow, ScopedBashRow, registerBashSamples } from '../src/client/toolviews/bash-sample.tsx'
|
||||
import { ToolViewOutlet } from '../src/client/chat/ToolViewOutlet.tsx'
|
||||
import { childSessionScope } from '../src/client/chat/register.ts'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
const SID = 's1' as SessionId
|
||||
|
||||
const assistant = (seq: number, turn: number, usage?: unknown): AssistantMessageNode => ({
|
||||
kind: 'assistant', seq, turn, step: seq, blocks: [{ kind: 'text', text: `t${seq}` }],
|
||||
...(usage === undefined ? {} : { usage }),
|
||||
})
|
||||
|
||||
function snapshotBase(): ConversationSnapshot {
|
||||
return {
|
||||
sessionId: SID, nodes: [], foldDegraded: false, partial: null, runningCalls: [],
|
||||
pending: [], running: false, removed: false, openState: 'open', openError: null,
|
||||
hasMore: false, loadingOlder: false, promptError: null, lastAgentError: null,
|
||||
}
|
||||
}
|
||||
|
||||
function makeSource(init?: Partial<ConversationSnapshot>) {
|
||||
let snap: ConversationSnapshot = { ...snapshotBase(), ...init }
|
||||
const subs = new Set<() => void>()
|
||||
return {
|
||||
set(next: Partial<ConversationSnapshot>) {
|
||||
snap = { ...snap, ...next }
|
||||
for (const fn of [...subs]) fn()
|
||||
},
|
||||
source: {
|
||||
getSnapshot: () => snap,
|
||||
subscribe: (fn: () => void) => {
|
||||
subs.add(fn)
|
||||
return () => subs.delete(fn)
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
describe('deriveStats', () => {
|
||||
it('folds turns/steps/tokens and cache hit percentage', () => {
|
||||
const stats = deriveStats([
|
||||
assistant(1, 1, { inputTokens: 100, outputTokens: 50, cacheReadTokens: 900 }),
|
||||
assistant(2, 1, { inputTokens: 100, outputTokens: 50 }),
|
||||
assistant(3, 2),
|
||||
])
|
||||
expect(stats.turns).toBe(2)
|
||||
expect(stats.steps).toBe(3)
|
||||
expect(stats.tokens).toBe(1200)
|
||||
expect(stats.cacheHitPct).toBe(82)
|
||||
})
|
||||
|
||||
it('cache hit stays null with no cache accounting; non-assistant nodes ignored', () => {
|
||||
const tool: ToolResultNode = {
|
||||
kind: 'tool-result', seq: 5, callId: 'c', call: null, content: [],
|
||||
isError: false, callView: null, resultView: null,
|
||||
}
|
||||
const stats = deriveStats([tool, assistant(1, 1)])
|
||||
expect(stats.steps).toBe(1)
|
||||
expect(stats.cacheHitPct).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('StatsLine', () => {
|
||||
function props(source: { getSnapshot(): ConversationSnapshot; subscribe(fn: () => void): () => void }): ChromeProps {
|
||||
return { sessionId: SID, useSession: bindSnapshotSelector(source) as unknown as UseSession }
|
||||
}
|
||||
|
||||
it('renders the joined stats row and hides with zero steps', () => {
|
||||
const { source } = makeSource({
|
||||
nodes: [assistant(1, 1, { inputTokens: 10, outputTokens: 5, cacheReadTokens: 90 })],
|
||||
})
|
||||
const view = render(<StatsLine {...props(source)} />)
|
||||
expect(view.getByText('cache hit 90% · 105 tokens · 1 turns · 1 steps')).toBeTruthy()
|
||||
const empty = makeSource()
|
||||
const emptyView = render(<StatsLine {...props(empty.source)} />)
|
||||
expect(emptyView.container.textContent).toBe('')
|
||||
})
|
||||
|
||||
it('renders ZERO times during streaming chunk frames (RFC hard acceptance)', () => {
|
||||
const { set, source } = makeSource({ nodes: [assistant(1, 1)] })
|
||||
let renders = 0
|
||||
function Counting(p: ChromeProps) {
|
||||
renders += 1
|
||||
return <StatsLine {...p} />
|
||||
}
|
||||
render(<Counting {...props(source)} />)
|
||||
const before = renders
|
||||
// Chunk frames swap partial only; nodes keeps its reference (object-layer contract).
|
||||
act(() => set({ partial: { turn: 1, step: 2, blocks: [{ kind: 'text', text: 'a' }] } }))
|
||||
act(() => set({ partial: { turn: 1, step: 2, blocks: [{ kind: 'text', text: 'ab' }] } }))
|
||||
act(() => set({ running: true }))
|
||||
expect(renders).toBe(before)
|
||||
})
|
||||
})
|
||||
|
||||
describe('bash toolview samples', () => {
|
||||
const result = (callId: string): ToolResultNode => ({
|
||||
kind: 'tool-result', seq: 3, callId,
|
||||
call: { name: 'bash', argsRaw: '{"command":"make build","description":"Build"}' },
|
||||
content: [], isError: false, callView: null, resultView: null,
|
||||
})
|
||||
|
||||
const viewProps = (openDetails = vi.fn()): ToolViewProps => ({
|
||||
callId: 'c1', toolName: 'bash', block: result('c1'),
|
||||
useSession: (() => { throw new Error('unused') }) as unknown as UseSession,
|
||||
actions: { openDetails },
|
||||
t: (k) => k,
|
||||
})
|
||||
|
||||
function outlet(registry: ToolViewRegistry, sessionId: SessionId, p = viewProps()) {
|
||||
return render(
|
||||
<ToolViewOutlet registry={registry} sessionId={sessionId} toolName="bash" viewProps={p} />,
|
||||
)
|
||||
}
|
||||
|
||||
it('differential rendering: scoped row for the matching session, global elsewhere', () => {
|
||||
const registry = new ToolViewRegistry()
|
||||
registerBashSamples(registry, (id) => id === ('swarm' as SessionId))
|
||||
const scoped = outlet(registry, 'swarm' as SessionId)
|
||||
expect(scoped.container.querySelector('[data-sample="bash-scoped"]')).not.toBeNull()
|
||||
const plain = outlet(registry, SID)
|
||||
expect(plain.container.querySelector('[data-sample="bash-global"]')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('teardown removes both registrations and falls back to the generic row', () => {
|
||||
const registry = new ToolViewRegistry()
|
||||
const off = registerBashSamples(registry, () => true)
|
||||
const view = outlet(registry, SID)
|
||||
expect(view.container.querySelector('[data-sample="bash-scoped"]')).not.toBeNull()
|
||||
act(() => off())
|
||||
expect(view.container.querySelector('[data-sample]')).toBeNull()
|
||||
expect(view.getByText('Bash')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('childSessionScope matches sub-sessions via the injected list read face', () => {
|
||||
const child = 'child' as SessionId
|
||||
const root = 'root' as SessionId
|
||||
const scope = childSessionScope({
|
||||
getSnapshot: () => ({
|
||||
ids: [root, child],
|
||||
byId: {
|
||||
[root]: { id: root, title: 'r', running: false, updatedAt: 0 },
|
||||
[child]: { id: child, title: 'c', parentId: root, running: false, updatedAt: 0 },
|
||||
},
|
||||
}),
|
||||
})
|
||||
expect(scope(child)).toBe(true)
|
||||
expect(scope(root)).toBe(false)
|
||||
expect(scope('gone' as SessionId)).toBe(false)
|
||||
})
|
||||
|
||||
it('sample rows summarize the command and hand clicks to openDetails', () => {
|
||||
const open = vi.fn()
|
||||
const p = viewProps(open)
|
||||
const global = render(<BashRow {...p} />)
|
||||
expect(global.getByText('Build')).toBeTruthy()
|
||||
fireEvent.click(global.getByText('Build'))
|
||||
expect(open).toHaveBeenCalledTimes(1)
|
||||
const scoped = render(<ScopedBashRow {...p} />)
|
||||
expect(scoped.getByText('scoped')).toBeTruthy()
|
||||
})
|
||||
})
|
||||
147
packages/client/ui-conversation/tests/chat-tool-row.spec.tsx
Normal file
147
packages/client/ui-conversation/tests/chat-tool-row.spec.tsx
Normal file
@@ -0,0 +1,147 @@
|
||||
// @vitest-environment jsdom
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { cleanup, fireEvent, render } from '@testing-library/react'
|
||||
|
||||
afterEach(cleanup)
|
||||
import type { RunningToolCall, ToolResultNode } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { UseSession } from '@deepseek-ai/dsh-client-web-react'
|
||||
import { classifyTool, toolRowModel } from '../src/client/contract/tool-call-model.ts'
|
||||
import { ToolRow } from '../src/client/chat/ToolRow.tsx'
|
||||
import { GenericToolCard } from '../src/client/chat/GenericToolCard.tsx'
|
||||
import type { ToolViewProps } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
|
||||
const running = (over?: Partial<RunningToolCall>): RunningToolCall => ({
|
||||
callId: 'c1', name: 'bash', argsRaw: '{"command":"ls -la","description":"List files"}',
|
||||
turn: 1, step: 1, callView: null, ...over,
|
||||
})
|
||||
|
||||
const result = (over?: Partial<ToolResultNode>): ToolResultNode => ({
|
||||
kind: 'tool-result', seq: 10, callId: 'c1',
|
||||
call: { name: 'bash', argsRaw: '{"command":"ls -la","description":"List files"}' },
|
||||
content: [], isError: false, callView: null, resultView: null, ...over,
|
||||
})
|
||||
|
||||
describe('tool-call-model', () => {
|
||||
it('classifies known tools and falls back to others', () => {
|
||||
expect(classifyTool('bash')).toBe('bash')
|
||||
expect(classifyTool('read')).toBe('read')
|
||||
expect(classifyTool('web_fetch')).toBe('read')
|
||||
expect(classifyTool('web_search')).toBe('search')
|
||||
expect(classifyTool('grep')).toBe('search')
|
||||
expect(classifyTool('todo_write')).toBe('others')
|
||||
})
|
||||
|
||||
it('derives state across running/ok/error/interrupted', () => {
|
||||
expect(toolRowModel('bash', running()).state).toBe('running')
|
||||
expect(toolRowModel('bash', result()).state).toBe('ok')
|
||||
expect(toolRowModel('bash', result({ isError: true })).state).toBe('error')
|
||||
expect(toolRowModel('bash', result({ isError: true, error: { name: 'E', code: 'interrupted' } })).state).toBe('stopped')
|
||||
})
|
||||
|
||||
it('derives the bash summary from description over command', () => {
|
||||
const m = toolRowModel('bash', running())
|
||||
expect(m.title).toBe('Bash')
|
||||
expect(m.summary).toBe('List files')
|
||||
expect(toolRowModel('bash', running({ argsRaw: '{"command":"pwd"}' })).summary).toBe('pwd')
|
||||
})
|
||||
|
||||
it('keeps summaries single-line and falls back for opaque args', () => {
|
||||
expect(toolRowModel('bash', running({ argsRaw: '{"command":"a\\nb"}' })).summary).toBe('a')
|
||||
expect(toolRowModel('read', running({ name: 'read', argsRaw: '{"path":"/tmp/x.ts"}' })).summary).toBe('/tmp/x.ts')
|
||||
// Others rows prefix the real tool name into the summary slot (figma-flows
|
||||
// ruling: static "Tool call" title, name rides the mutable summary).
|
||||
expect(toolRowModel('x', running({ argsRaw: '{"n":1}' })).summary).toBe('x · {"n":1}')
|
||||
expect(toolRowModel('x', running({ argsRaw: 'not json' })).summary).toBe('x · not json')
|
||||
expect(toolRowModel('x', running({ argsRaw: '' })).summary).toBe('x · c1')
|
||||
expect(toolRowModel('', running({ argsRaw: '' })).summary).toBe('c1')
|
||||
})
|
||||
|
||||
it('body pretty-prints JSON args, keeps raw non-JSON, null when empty', () => {
|
||||
expect(toolRowModel('bash', running({ argsRaw: '{"a":1}' })).body).toBe('{\n "a": 1\n}')
|
||||
expect(toolRowModel('bash', running({ argsRaw: 'raw' })).body).toBe('raw')
|
||||
expect(toolRowModel('bash', running({ argsRaw: '' })).body).toBeNull()
|
||||
expect(toolRowModel('bash', result({ call: null })).body).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('ToolRow', () => {
|
||||
const rowProps = {
|
||||
variant: 'bash' as const, icon: <i data-testid="tool-icon" />, title: 'Bash',
|
||||
summary: 'List files', body: '{\n "a": 1\n}', state: 'ok' as const,
|
||||
}
|
||||
|
||||
it('renders leading icon, title and summary while collapsed', () => {
|
||||
const view = render(<ToolRow {...rowProps} />)
|
||||
expect(view.queryByTestId('tool-icon')).not.toBeNull()
|
||||
expect(view.getByText('Bash')).toBeTruthy()
|
||||
expect(view.getByText('List files')).toBeTruthy()
|
||||
expect(view.container.querySelector('[aria-expanded]')?.getAttribute('aria-expanded')).toBe('false')
|
||||
})
|
||||
|
||||
it('expanding swaps the leading slot to a chevron, hides summary, shows body', () => {
|
||||
const view = render(<ToolRow {...rowProps} />)
|
||||
fireEvent.click(view.container.querySelector('button')!)
|
||||
expect(view.queryByTestId('tool-icon')).toBeNull()
|
||||
expect(view.container.querySelector('svg')).not.toBeNull()
|
||||
expect(view.queryByText('List files')).toBeNull()
|
||||
expect(view.getByText(/"a": 1/)).toBeTruthy()
|
||||
fireEvent.click(view.container.querySelector('button')!)
|
||||
expect(view.queryByTestId('tool-icon')).not.toBeNull()
|
||||
expect(view.getByText('List files')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('running and error states replace the icon with a StateDot', () => {
|
||||
const runningView = render(<ToolRow {...rowProps} state="running" />)
|
||||
expect(runningView.queryByTestId('tool-icon')).toBeNull()
|
||||
expect(runningView.container.querySelector('[data-state="running"]')).not.toBeNull()
|
||||
const errorView = render(<ToolRow {...rowProps} state="error" />)
|
||||
expect(errorView.queryByTestId('tool-icon')).toBeNull()
|
||||
})
|
||||
|
||||
it('non-expandable rows render a passive leading slot', () => {
|
||||
const view = render(<ToolRow {...rowProps} body={null} />)
|
||||
expect(view.container.querySelector('button')).toBeNull()
|
||||
expect(view.queryByTestId('tool-icon')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('row click hands off to onOpenDetails; the expand toggle does not', () => {
|
||||
const open = vi.fn()
|
||||
const view = render(<ToolRow {...rowProps} onOpenDetails={open} />)
|
||||
fireEvent.click(view.getByText('List files'))
|
||||
expect(open).toHaveBeenCalledTimes(1)
|
||||
fireEvent.click(view.container.querySelector('button')!)
|
||||
expect(open).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GenericToolCard', () => {
|
||||
const props = (toolName: string, block: RunningToolCall | ToolResultNode): ToolViewProps => ({
|
||||
callId: 'c1', toolName, block,
|
||||
useSession: (() => { throw new Error('unused') }) as unknown as UseSession,
|
||||
actions: { openDetails: vi.fn() },
|
||||
t: (k) => k,
|
||||
})
|
||||
|
||||
it('renders the classified variant row from the frozen slice', () => {
|
||||
const view = render(<GenericToolCard {...props('bash', result())} />)
|
||||
expect(view.getByText('Bash')).toBeTruthy()
|
||||
expect(view.getByText('List files')).toBeTruthy()
|
||||
expect(view.container.querySelector('[data-variant="bash"]')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('unknown tools land on the others variant titled Tool call', () => {
|
||||
const view = render(
|
||||
<GenericToolCard {...props('todo_write', running({ name: 'todo_write', argsRaw: '{"note":"x"}' }))} />,
|
||||
)
|
||||
expect(view.getByText('Tool call')).toBeTruthy()
|
||||
expect(view.container.querySelector('[data-variant="others"]')).not.toBeNull()
|
||||
expect(view.container.querySelector('[data-state="running"]')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('row click reaches actions.openDetails', () => {
|
||||
const p = props('bash', result())
|
||||
const view = render(<GenericToolCard {...p} />)
|
||||
fireEvent.click(view.getByText('List files'))
|
||||
expect(p.actions.openDetails).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
305
packages/client/ui-conversation/tests/chat-view.spec.tsx
Normal file
305
packages/client/ui-conversation/tests/chat-view.spec.tsx
Normal file
@@ -0,0 +1,305 @@
|
||||
// @vitest-environment jsdom
|
||||
// ChatView behavior: flow derivation, streaming isolation (Profiler counts),
|
||||
// toolview dispatch and selection handoff — driven through a scripted
|
||||
// ObservableSnapshot fake, no wire.
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { Profiler } from 'react'
|
||||
import { act, cleanup, fireEvent, render } from '@testing-library/react'
|
||||
import type {
|
||||
AssistantMessageNode, ConversationNode, ConversationSnapshot, RunningToolCall, SessionId, ToolResultNode, UserMessageNode,
|
||||
} from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react'
|
||||
import type { UseSession } from '@deepseek-ai/dsh-client-web-react'
|
||||
import type { ConvViewProps, SelectionTarget } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import { ToolViewRegistry } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import { createChatView } from '../src/client/chat/ChatView.tsx'
|
||||
import { deriveChatFlow, flowKeys } from '../src/client/chat/chat-flow.ts'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
const SID = 's1' as SessionId
|
||||
|
||||
function snapshotBase(): ConversationSnapshot {
|
||||
return {
|
||||
sessionId: SID, nodes: [], foldDegraded: false, partial: null, runningCalls: [],
|
||||
pending: [], running: false, removed: false, openState: 'open', openError: null,
|
||||
hasMore: false, loadingOlder: false, promptError: null, lastAgentError: null,
|
||||
}
|
||||
}
|
||||
|
||||
/** Scripted snapshot source: set() swaps the top-level object like the real Session. */
|
||||
function makeSource(init?: Partial<ConversationSnapshot>) {
|
||||
let snap: ConversationSnapshot = { ...snapshotBase(), ...init }
|
||||
const subs = new Set<() => void>()
|
||||
return {
|
||||
set(next: Partial<ConversationSnapshot>) {
|
||||
snap = { ...snap, ...next }
|
||||
for (const fn of [...subs]) fn()
|
||||
},
|
||||
source: {
|
||||
getSnapshot: () => snap,
|
||||
subscribe: (fn: () => void) => {
|
||||
subs.add(fn)
|
||||
return () => subs.delete(fn)
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const user = (seq: number, text: string): UserMessageNode => ({
|
||||
kind: 'user', seq, content: [{ type: 'text', text }] as never, source: null,
|
||||
})
|
||||
const assistant = (seq: number, text: string): AssistantMessageNode => ({
|
||||
kind: 'assistant', seq, turn: 1, step: 1, blocks: [{ kind: 'text', text }],
|
||||
})
|
||||
const toolResult = (seq: number, callId: string, name = 'bash'): ToolResultNode => ({
|
||||
kind: 'tool-result', seq, callId,
|
||||
call: { name, argsRaw: `{"command":"cmd-${callId}","description":"run ${callId}"}` },
|
||||
content: [], isError: false, callView: null, resultView: null,
|
||||
})
|
||||
const runningCall = (callId: string, name = 'bash'): RunningToolCall => ({
|
||||
callId, name, argsRaw: `{"command":"cmd-${callId}"}`, turn: 2, step: 1, callView: null,
|
||||
})
|
||||
|
||||
function makeHarness(init?: Partial<ConversationSnapshot>) {
|
||||
const { set, source } = makeSource(init)
|
||||
const registry = new ToolViewRegistry()
|
||||
const ChatView = createChatView({ toolviews: registry, t: (k) => k })
|
||||
const openDetails = vi.fn<(t: SelectionTarget) => void>()
|
||||
const loadOlder = vi.fn()
|
||||
const selection = makeSelection()
|
||||
const props: ConvViewProps = {
|
||||
sessionId: SID,
|
||||
useSession: bindSnapshotSelector(source) as unknown as UseSession,
|
||||
useSelection: bindSnapshotSelector(selection.source),
|
||||
actions: { openDetails, loadOlder },
|
||||
slots: { renderSlot: () => null } as never,
|
||||
}
|
||||
return { set, registry, ChatView, props, openDetails, loadOlder, setSelection: selection.set }
|
||||
}
|
||||
|
||||
function makeSelection() {
|
||||
let sel: SelectionTarget | null = null
|
||||
const subs = new Set<() => void>()
|
||||
return {
|
||||
set(next: SelectionTarget | null) {
|
||||
sel = next
|
||||
for (const fn of [...subs]) fn()
|
||||
},
|
||||
source: {
|
||||
getSnapshot: () => sel,
|
||||
subscribe: (fn: () => void) => {
|
||||
subs.add(fn)
|
||||
return () => subs.delete(fn)
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
describe('chat-flow derivation', () => {
|
||||
it('groups consecutive tool results and keeps stable keys', () => {
|
||||
const nodes: ConversationNode[] = [
|
||||
user(1, 'hi'), assistant(2, 'let me look'), toolResult(3, 'a'), toolResult(4, 'b'),
|
||||
assistant(5, 'found'), toolResult(6, 'c'),
|
||||
]
|
||||
const items = deriveChatFlow(nodes)
|
||||
expect(items.map((i) => i.kind)).toEqual(['node', 'node', 'tool-group', 'node', 'tool-group'])
|
||||
const group = items[2]!
|
||||
expect(group.kind === 'tool-group' && group.results.map((r) => r.callId)).toEqual(['a', 'b'])
|
||||
expect(flowKeys(items)).toBe('n1|n2|g3|n5|g6')
|
||||
expect(flowKeys(deriveChatFlow([...nodes, toolResult(7, 'd')]))).toBe('n1|n2|g3|n5|g6')
|
||||
})
|
||||
})
|
||||
|
||||
describe('ChatView', () => {
|
||||
it('a windowless tool result (call head truncated) renders with an empty tool name', () => {
|
||||
const h = makeHarness({
|
||||
nodes: [{ ...toolResult(3, 'w1'), call: null }],
|
||||
})
|
||||
const view = render(<h.ChatView {...h.props} />)
|
||||
// classifyTool('') → others; the summary slot falls back to the callId.
|
||||
expect(view.container.querySelector('[data-variant="others"]')).not.toBeNull()
|
||||
expect(view.getByText('w1')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('prepend keeps the viewport anchored when the reader is NOT at the bottom (no lastKey force)', () => {
|
||||
// Covers the prepend early-return arm where lastItem exists but the key
|
||||
// path is not taken (anchor branch wins before the appended-user check).
|
||||
const h = makeHarness({ nodes: [user(9, 'late')], hasMore: true })
|
||||
const view = render(<h.ChatView {...h.props} />)
|
||||
const scroller = view.container.querySelector('[class*="scroll"]') as HTMLDivElement
|
||||
Object.defineProperty(scroller, 'scrollHeight', { value: 800, writable: true })
|
||||
Object.defineProperty(scroller, 'clientHeight', { value: 200, writable: true })
|
||||
scroller.scrollTop = 50
|
||||
fireEvent.scroll(scroller)
|
||||
fireEvent.click(view.getByText('加载更早'))
|
||||
Object.defineProperty(scroller, 'scrollHeight', { value: 1300, writable: true })
|
||||
act(() => h.set({ nodes: [assistant(2, 'older'), user(9, 'late')] }))
|
||||
expect(scroller.scrollTop).toBe(550) // 50 + (1300 - 800)
|
||||
})
|
||||
|
||||
it('renders the fixture main line: bubble, narration, grouped tool rows', () => {
|
||||
const h = makeHarness({
|
||||
nodes: [user(1, 'do the thing'), assistant(2, 'running tools'), toolResult(3, 'a'), toolResult(4, 'b')],
|
||||
})
|
||||
const view = render(<h.ChatView {...h.props} />)
|
||||
expect(view.getByText('do the thing')).toBeTruthy()
|
||||
expect(view.getByText('running tools')).toBeTruthy()
|
||||
expect(view.getAllByText('Bash')).toHaveLength(2)
|
||||
expect(view.getByText('run a')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('streaming partial frames re-render only the tail (Profiler count)', () => {
|
||||
const h = makeHarness({
|
||||
nodes: [user(1, 'q'), assistant(2, 'old answer'), toolResult(3, 'a')],
|
||||
})
|
||||
let renders = 0
|
||||
const counting = (
|
||||
<Profiler id="chat" onRender={() => { renders += 1 }}>
|
||||
<h.ChatView {...h.props} />
|
||||
</Profiler>
|
||||
)
|
||||
const view = render(counting)
|
||||
const before = renders
|
||||
const beforeHtml = view.container.querySelector('[class*="toolGroup"]')!.innerHTML
|
||||
act(() => {
|
||||
h.set({ partial: { turn: 2, step: 1, blocks: [{ kind: 'text', text: 'streaming…' }] } })
|
||||
})
|
||||
act(() => {
|
||||
h.set({ partial: { turn: 2, step: 1, blocks: [{ kind: 'text', text: 'streaming… more' }] } })
|
||||
})
|
||||
expect(view.getByText('streaming… more')).toBeTruthy()
|
||||
// Each chunk commits exactly one profiler pass (the tail), never a full-tree storm.
|
||||
expect(renders - before).toBe(2)
|
||||
expect(view.container.querySelector('[class*="toolGroup"]')!.innerHTML).toBe(beforeHtml)
|
||||
})
|
||||
|
||||
it('streaming leaves neighbor tool rows and history items at zero re-renders', () => {
|
||||
const h = makeHarness({
|
||||
nodes: [user(1, 'q'), assistant(2, 'old'), toolResult(3, 'a')],
|
||||
})
|
||||
let rowRenders = 0
|
||||
h.registry.register('bash', () => {
|
||||
rowRenders += 1
|
||||
return <div data-testid="counting-row" />
|
||||
})
|
||||
const view = render(<h.ChatView {...h.props} />)
|
||||
expect(view.getByTestId('counting-row')).toBeTruthy()
|
||||
const afterMount = rowRenders
|
||||
act(() => {
|
||||
h.set({ partial: { turn: 2, step: 1, blocks: [{ kind: 'text', text: 'chunk1' }] } })
|
||||
})
|
||||
act(() => {
|
||||
h.set({ partial: { turn: 2, step: 1, blocks: [{ kind: 'text', text: 'chunk1 chunk2' }] } })
|
||||
})
|
||||
expect(rowRenders).toBe(afterMount)
|
||||
})
|
||||
|
||||
it('tool row expands to the args body via the leading slot toggle', () => {
|
||||
const h = makeHarness({ nodes: [toolResult(3, 'a')] })
|
||||
const view = render(<h.ChatView {...h.props} />)
|
||||
expect(view.queryByText(/"command": "cmd-a"/)).toBeNull()
|
||||
fireEvent.click(view.container.querySelector('button[aria-expanded]')!)
|
||||
expect(view.getByText(/"command": "cmd-a"/)).toBeTruthy()
|
||||
})
|
||||
|
||||
it('clicking a tool row opens details with callId and toolName; selection paints the outline', () => {
|
||||
const h = makeHarness({ nodes: [toolResult(3, 'a')] })
|
||||
const view = render(<h.ChatView {...h.props} />)
|
||||
fireEvent.click(view.getByText('run a'))
|
||||
expect(h.openDetails).toHaveBeenCalledWith({ turnSeq: 3, callId: 'a', toolName: 'bash' })
|
||||
expect(view.container.querySelector('[data-selected]')).toBeNull()
|
||||
act(() => h.setSelection({ turnSeq: 3, callId: 'a', toolName: 'bash' }))
|
||||
expect(view.container.querySelector('[data-selected]')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('running calls render as a live tool group with the running state', () => {
|
||||
const h = makeHarness({ runningCalls: [runningCall('r1')], running: true })
|
||||
const view = render(<h.ChatView {...h.props} />)
|
||||
expect(view.container.querySelector('[data-state="running"]')).not.toBeNull()
|
||||
expect(view.getByText('cmd-r1')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('a scoped toolview registration takes over rendering for its session only', () => {
|
||||
const h = makeHarness({ nodes: [toolResult(3, 'a')] })
|
||||
h.registry.register('bash', () => <div data-testid="custom-bash" />, { scope: (id) => id === SID })
|
||||
const view = render(<h.ChatView {...h.props} />)
|
||||
expect(view.getByTestId('custom-bash')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('unregistering a toolview falls back to the generic row live', () => {
|
||||
const h = makeHarness({ nodes: [toolResult(3, 'a')] })
|
||||
const off = h.registry.register('bash', () => <div data-testid="custom-bash" />)
|
||||
const view = render(<h.ChatView {...h.props} />)
|
||||
expect(view.getByTestId('custom-bash')).toBeTruthy()
|
||||
act(() => off())
|
||||
expect(view.queryByTestId('custom-bash')).toBeNull()
|
||||
expect(view.getByText('Bash')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('prepend compensates scrollTop by the height delta; a trailing user node force-scrolls', () => {
|
||||
const h = makeHarness({ nodes: [user(5, 'later'), assistant(6, 'a')], hasMore: true })
|
||||
const view = render(<h.ChatView {...h.props} />)
|
||||
const scroller = view.container.querySelector('[class*="scroll"]') as HTMLDivElement
|
||||
// jsdom has no layout: fake the metrics the anchor math reads.
|
||||
Object.defineProperty(scroller, 'scrollHeight', { value: 1000, writable: true })
|
||||
Object.defineProperty(scroller, 'clientHeight', { value: 400, writable: true })
|
||||
// Arm the paging anchor, then deliver an older page (head seq decreases).
|
||||
fireEvent.click(view.getByText('加载更早'))
|
||||
Object.defineProperty(scroller, 'scrollHeight', { value: 1600, writable: true })
|
||||
act(() => h.set({ nodes: [user(1, 'old'), assistant(2, 'b'), user(5, 'later'), assistant(6, 'a')] }))
|
||||
expect(scroller.scrollTop).toBe(600) // 0 + (1600 - 1000)
|
||||
// A new trailing user bubble (own words) force-scrolls to the bottom.
|
||||
act(() => h.set({ nodes: [user(1, 'old'), assistant(2, 'b'), user(5, 'later'), assistant(6, 'a'), user(9, 'mine')] }))
|
||||
expect(scroller.scrollTop).toBe(1600)
|
||||
})
|
||||
|
||||
it('scrolling away disables follow and shows the back-to-bottom button; clicking returns', () => {
|
||||
const h = makeHarness({ nodes: [user(1, 'q'), assistant(2, 'a')] })
|
||||
const view = render(<h.ChatView {...h.props} />)
|
||||
const scroller = view.container.querySelector('[class*="scroll"]') as HTMLDivElement
|
||||
Object.defineProperty(scroller, 'scrollHeight', { value: 1000, writable: true })
|
||||
Object.defineProperty(scroller, 'clientHeight', { value: 300, writable: true })
|
||||
scroller.scrollTop = 100 // far from bottom
|
||||
fireEvent.scroll(scroller)
|
||||
const backButton = view.getByLabelText('回到底部')
|
||||
expect(backButton).toBeTruthy()
|
||||
// Streaming growth must NOT drag a scrolled-away reader down.
|
||||
act(() => h.set({ partial: { turn: 1, step: 1, blocks: [{ kind: 'text', text: 'grow' }] } }))
|
||||
expect(scroller.scrollTop).toBe(100)
|
||||
fireEvent.click(backButton)
|
||||
expect(scroller.scrollTop).toBe(1000)
|
||||
// At the bottom again: follow re-arms and the button unmounts.
|
||||
expect(view.queryByLabelText('回到底部')).toBeNull()
|
||||
})
|
||||
|
||||
it('paging button loads older and shows its busy label', () => {
|
||||
const h = makeHarness({ nodes: [user(5, 'later')], hasMore: true })
|
||||
const view = render(<h.ChatView {...h.props} />)
|
||||
fireEvent.click(view.getByText('加载更早'))
|
||||
expect(h.loadOlder).toHaveBeenCalledTimes(1)
|
||||
act(() => h.set({ loadingOlder: true }))
|
||||
expect(view.getByText('加载中…')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('shows open error and loading states', () => {
|
||||
const h = makeHarness({
|
||||
openState: 'error',
|
||||
openError: { code: 'internal', message: 'boom' } as never,
|
||||
})
|
||||
const view = render(<h.ChatView {...h.props} />)
|
||||
expect(view.getByText(/历史加载失败:boom/)).toBeTruthy()
|
||||
const loading = makeHarness({ openState: 'loading' })
|
||||
const lv = render(<loading.ChatView {...loading.props} />)
|
||||
expect(lv.getByText('载入历史…')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('pending interactions render placeholder cards', () => {
|
||||
const h = makeHarness({
|
||||
pending: [{ kind: 'approval', rpcId: 'r1' as never, approvalId: 'ap1', toolName: 'bash' }],
|
||||
})
|
||||
const view = render(<h.ChatView {...h.props} />)
|
||||
expect(view.getByText(/等待审批/)).toBeTruthy()
|
||||
})
|
||||
})
|
||||
127
packages/client/ui-conversation/tests/coverage-tails.spec.tsx
Normal file
127
packages/client/ui-conversation/tests/coverage-tails.spec.tsx
Normal file
@@ -0,0 +1,127 @@
|
||||
// @vitest-environment jsdom
|
||||
// Branch tails the acceptance specs do not reach: ToolRow stopped-state dot,
|
||||
// PendingCard question arm, bash sample error pill, registry disposer
|
||||
// idempotence re-entry, register.ts explicit bashSampleScope override, the
|
||||
// node-half empty apply, and AssistantMarkdown reasoning/unknown block arms.
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { cleanup, render } from '@testing-library/react'
|
||||
import type { ToolResultNode } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { RpcId } from '@deepseek-ai/dsh-client-connection/client'
|
||||
import type { UseSession } from '@deepseek-ai/dsh-client-web-react'
|
||||
import { ToolViewRegistry } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import type { ConversationService, Translate, ToolViewProps } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import { apply as nodeApply } from '../src/index.ts'
|
||||
import { GenericToolCard } from '../src/client/chat/GenericToolCard.tsx'
|
||||
import { ToolRow } from '../src/client/chat/ToolRow.tsx'
|
||||
import { PendingCard } from '../src/client/chat/PendingCard.tsx'
|
||||
import { AssistantMarkdown } from '../src/client/chat/AssistantMarkdown.tsx'
|
||||
import { BashRow } from '../src/client/toolviews/bash-sample.tsx'
|
||||
import { registerChat } from '../src/client/chat/register.ts'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
describe('tails', () => {
|
||||
it('node-half apply is an intentional no-op', () => {
|
||||
expect(nodeApply()).toBeUndefined()
|
||||
})
|
||||
|
||||
it('ToolRow stopped state renders the warning dot in the leading slot', () => {
|
||||
const view = render(
|
||||
<ToolRow variant="bash" icon={<i data-testid="icon" />} title="Bash" summary="s" body={null} state="stopped" />,
|
||||
)
|
||||
expect(view.queryByTestId('icon')).toBeNull()
|
||||
expect(view.container.querySelector('[data-state="stopped"]')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('PendingCard renders the question arm with its count', () => {
|
||||
const view = render(
|
||||
<PendingCard item={{ kind: 'question', rpcId: 'r1' as RpcId, questions: [{}, {}] }} />,
|
||||
)
|
||||
expect(view.getByText(/等待回答(2 题)/)).toBeTruthy()
|
||||
})
|
||||
|
||||
it('AssistantMarkdown renders reasoning as a Think row and unknown blocks as JSON fallback', () => {
|
||||
const view = render(
|
||||
<AssistantMarkdown
|
||||
blocks={[
|
||||
{ kind: 'reasoning', text: 'thinking hard\nsecond line' },
|
||||
{ kind: 'tool-call', callId: 'c', name: 'bash', argsRaw: '{}' },
|
||||
{ kind: 'other', block: { type: 'mystery' } },
|
||||
]}
|
||||
streaming
|
||||
/>,
|
||||
)
|
||||
expect(view.getByText('Think')).toBeTruthy()
|
||||
expect(view.getByText('thinking hard')).toBeTruthy()
|
||||
expect(view.getByText(/未知内容块/)).toBeTruthy()
|
||||
const stopped = render(
|
||||
<AssistantMarkdown blocks={[{ kind: 'text', text: 'partial words' }]} streaming={false} interrupted />,
|
||||
)
|
||||
expect(stopped.getByText('已停止')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('a settled others-variant row renders the sparkle icon in the leading slot', () => {
|
||||
const settled: ToolResultNode = {
|
||||
kind: 'tool-result', seq: 2, callId: 'c5',
|
||||
call: { name: 'todo_write', argsRaw: '{"note":"x"}' },
|
||||
content: [], isError: false, callView: null, resultView: null,
|
||||
}
|
||||
const props: ToolViewProps = {
|
||||
callId: 'c5', toolName: 'todo_write', block: settled,
|
||||
useSession: (() => { throw new Error('unused') }) as unknown as UseSession,
|
||||
actions: { openDetails: vi.fn() },
|
||||
t: ((k: string) => k) as Translate,
|
||||
}
|
||||
const view = render(<GenericToolCard {...props} />)
|
||||
// Settled ok state keeps the variant icon (sparkle) instead of a StateDot.
|
||||
expect(view.container.querySelector('[data-variant="others"] svg')).not.toBeNull()
|
||||
expect(view.container.querySelector('[data-state="ok"]')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('BashRow shows the failed pill on error results', () => {
|
||||
const errorResult: ToolResultNode = {
|
||||
kind: 'tool-result', seq: 1, callId: 'c1',
|
||||
call: { name: 'bash', argsRaw: '{"command":"boom"}' },
|
||||
content: [], isError: true, callView: null, resultView: null,
|
||||
}
|
||||
const props: ToolViewProps = {
|
||||
callId: 'c1', toolName: 'bash', block: errorResult,
|
||||
useSession: (() => { throw new Error('unused') }) as unknown as UseSession,
|
||||
actions: { openDetails: vi.fn() },
|
||||
t: ((k: string) => k) as Translate,
|
||||
}
|
||||
const view = render(<BashRow {...props} />)
|
||||
expect(view.getByText('failed')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('registry disposer re-entry is a no-op after the entry was already removed', () => {
|
||||
const registry = new ToolViewRegistry()
|
||||
const off = registry.register('bash', (() => null) as never)
|
||||
const v1 = registry.getVersion()
|
||||
off()
|
||||
const v2 = registry.getVersion()
|
||||
off()
|
||||
expect(registry.getVersion()).toBe(v2)
|
||||
expect(v2).toBeGreaterThan(v1)
|
||||
})
|
||||
|
||||
it('registerChat registers the chat view with the stats footer and disposes cleanly', () => {
|
||||
const disposer = vi.fn()
|
||||
const calls: unknown[] = []
|
||||
const conversation = {
|
||||
registerView: (entry: unknown) => {
|
||||
calls.push(entry)
|
||||
return disposer
|
||||
},
|
||||
} as unknown as ConversationService
|
||||
const toolviews = new ToolViewRegistry()
|
||||
const off = registerChat({ conversation, toolviews, t: ((k: string) => k) as Translate })
|
||||
const entry = calls[0] as { id: string; chrome?: { footer?: unknown } }
|
||||
expect(entry.id).toBe('chat')
|
||||
// footer is a memo exotic component (object, not plain function).
|
||||
expect(entry.chrome?.footer).toBeDefined()
|
||||
off()
|
||||
expect(disposer).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
140
packages/client/ui-conversation/tests/gate-branch-tails.spec.tsx
Normal file
140
packages/client/ui-conversation/tests/gate-branch-tails.spec.tsx
Normal file
@@ -0,0 +1,140 @@
|
||||
// @vitest-environment jsdom
|
||||
// Final branch tails for the coverage gate, post slot-phase-2: apply's need()
|
||||
// throw + cwd cache hit/empty-cwd skip, AssistantMarkdown non-final reasoning,
|
||||
// StatsLine usage-less node, ChatView tool-group selected passthrough +
|
||||
// running-empty guard, DetailsPanel titleless selection, registry disposer
|
||||
// after a foreign removal emptied the list.
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { cleanup, render } from '@testing-library/react'
|
||||
import { Context } from 'cordis'
|
||||
import { createSnapshotStore, bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react'
|
||||
import type { UseSession } from '@deepseek-ai/dsh-client-web-react'
|
||||
import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { ConversationSnapshot, SessionId, SessionListState } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { apply, inject, ToolViewRegistry } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import type { SelectionTarget } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import { AssistantMarkdown } from '../src/client/chat/AssistantMarkdown.tsx'
|
||||
import { StatsLine } from '../src/client/chat/StatsLine.tsx'
|
||||
import { DetailsPanel } from '../src/client/skeleton/DetailsPanel.tsx'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-layout/client'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
const SID = 's1' as SessionId
|
||||
|
||||
function snapshotBase(): ConversationSnapshot {
|
||||
return {
|
||||
sessionId: SID, nodes: [], foldDegraded: false, partial: null, runningCalls: [],
|
||||
pending: [], running: false, removed: false, openState: 'open', openError: null,
|
||||
hasMore: false, loadingOlder: false, promptError: null, lastAgentError: null,
|
||||
} as ConversationSnapshot
|
||||
}
|
||||
|
||||
describe('apply need() and cwd cache', () => {
|
||||
it('apply fails loud when a required service is absent', () => {
|
||||
// Call apply directly (no fiber machinery): need('sessions') on a bare
|
||||
// context throws synchronously — the loud-failure branch without the
|
||||
// fiber runner's internal rejection surface. Mount semantics (inject
|
||||
// gating) are covered by the full bench in apply-inject.spec.
|
||||
void inject
|
||||
const ctx = new Context()
|
||||
expect(() => { (apply as (c: Context) => void)(ctx) }).toThrow(/sessions service unavailable/)
|
||||
})
|
||||
|
||||
it('cwd derivation caches per list state and skips empty cwd values', async () => {
|
||||
const ctx = new Context()
|
||||
const slotsFiber = ctx.plugin(SlotsService)
|
||||
await slotsFiber.await()
|
||||
const listStore = createSnapshotStore<SessionListState>({
|
||||
ids: [SID, 'x2' as SessionId, 'x3' as SessionId],
|
||||
byId: {
|
||||
[SID]: { id: SID, title: 'a', cwd: '/proj', running: false, updatedAt: 1 },
|
||||
['x2' as SessionId]: { id: 'x2' as SessionId, title: 'b', cwd: '', running: false, updatedAt: 1 },
|
||||
['x3' as SessionId]: { id: 'x3' as SessionId, title: 'c', running: false, updatedAt: 1 },
|
||||
},
|
||||
})
|
||||
ctx.provide('sessions', { list: listStore, manager: { get: vi.fn() }, ancestry: () => [], scope: () => undefined, create: vi.fn() })
|
||||
ctx.provide('layout', { current: createSnapshotStore<{ viewFor: Record<string, string> }>({ viewFor: {} }), open: vi.fn(), openView: vi.fn(), openDetails: vi.fn(), closeDetails: vi.fn() })
|
||||
ctx.provide('i18n', { bind: () => (k: string) => k })
|
||||
const slots = ctx.get('slots') as SlotsService
|
||||
slots.define('conversation', { kind: 'single', scope: 'session' })
|
||||
slots.define('details', { kind: 'single', scope: 'session' })
|
||||
slots.define('conversation.empty', { kind: 'single', scope: 'root' })
|
||||
const fiber = ctx.plugin({ inject: [...inject], apply })
|
||||
await fiber.await()
|
||||
const entry = slots.entries('conversation.empty')[0]! as unknown as {
|
||||
options: { inject: (b: unknown) => { useCwds: (sel: (s: readonly string[]) => readonly string[]) => readonly string[] } }
|
||||
}
|
||||
const injected = entry.options.inject({ ctx })
|
||||
const Probe = () => {
|
||||
const cwds = injected.useCwds(s => s)
|
||||
const again = injected.useCwds(s => s)
|
||||
// Cache hit: same state object yields the same derived array reference.
|
||||
return <i data-testid="cwds">{`${cwds.join(',')}|${String(cwds === again)}`}</i>
|
||||
}
|
||||
const view = render(<Probe />)
|
||||
expect(view.getByTestId('cwds').textContent).toBe('/proj|true')
|
||||
})
|
||||
})
|
||||
|
||||
describe('render branch tails', () => {
|
||||
it('AssistantMarkdown reasoning row is ok-state when not the streaming tail', () => {
|
||||
const view = render(
|
||||
<AssistantMarkdown
|
||||
blocks={[{ kind: 'reasoning', text: 'done thinking' }, { kind: 'text', text: 'answer' }]}
|
||||
streaming
|
||||
/>,
|
||||
)
|
||||
// reasoning at index 0 with a later block: running is false → ok state.
|
||||
expect(view.container.querySelector('[data-state="ok"]')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('StatsLine skips usage-less nodes and defaults each absent counter to zero', () => {
|
||||
const snap = {
|
||||
nodes: [
|
||||
{ kind: 'assistant', seq: 1, turn: 1, step: 1, blocks: [] },
|
||||
{ kind: 'assistant', seq: 2, turn: 1, step: 2, blocks: [], usage: { inputTokens: 4, outputTokens: 6 } },
|
||||
// outputTokens absent: the tokens sum's ?? 0 arm for output.
|
||||
{ kind: 'assistant', seq: 3, turn: 2, step: 1, blocks: [], usage: { inputTokens: 5 } },
|
||||
],
|
||||
}
|
||||
const source = { getSnapshot: () => snap, subscribe: () => () => {} }
|
||||
const view = render(
|
||||
<StatsLine sessionId={SID} useSession={bindSnapshotSelector(source) as unknown as UseSession} />,
|
||||
)
|
||||
expect(view.getByText('cache hit 0% · 15 tokens · 2 turns · 3 steps')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('AssistantMarkdown reasoning as the streaming tail renders the running ring', () => {
|
||||
const view = render(
|
||||
<AssistantMarkdown blocks={[{ kind: 'reasoning', text: 'still thinking' }]} streaming />,
|
||||
)
|
||||
expect(view.container.querySelector('[data-state="running"]')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('DetailsPanel title falls to 详情 when the selection has no toolName and no material', () => {
|
||||
const SEL: SelectionTarget = { turnSeq: 1, callId: 'ghost' }
|
||||
const view = render(
|
||||
<DetailsPanel
|
||||
sessionId={SID}
|
||||
useSession={bindSnapshotSelector({ getSnapshot: () => snapshotBase(), subscribe: () => () => {} }) as unknown as UseSession}
|
||||
useSelection={bindSnapshotSelector({ getSnapshot: () => SEL, subscribe: () => () => {} })}
|
||||
actions={{ closeDetails: vi.fn() }}
|
||||
/>,
|
||||
)
|
||||
expect(view.getByText('详情')).toBeTruthy()
|
||||
expect(view.getByText('该调用不在当前窗口内')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('registry disposer tolerates the list already emptied by a sibling disposer', () => {
|
||||
const registry = new ToolViewRegistry()
|
||||
const offA = registry.register('bash', () => null)
|
||||
const offB = registry.register('bash', () => null)
|
||||
offA()
|
||||
offB()
|
||||
// Both entries gone; a re-register works from a fresh list.
|
||||
registry.register('bash', () => null)
|
||||
expect(registry.resolve('bash', SID)).toBeDefined()
|
||||
})
|
||||
})
|
||||
131
packages/client/ui-conversation/tests/input-bar.spec.tsx
Normal file
131
packages/client/ui-conversation/tests/input-bar.spec.tsx
Normal file
@@ -0,0 +1,131 @@
|
||||
// @vitest-environment jsdom
|
||||
// InputBar behavior: Enter-send semantics (IME guard, shift newline,
|
||||
// ctrl/meta insert, repeat suppression), the running lock with stop-only
|
||||
// action, unlock refocus, error strip copy, and the focus-keeping mousedown.
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { cleanup, fireEvent, render } from '@testing-library/react'
|
||||
import { InputBar } from '../src/client/skeleton/InputBar.tsx'
|
||||
import type { InputBarProps } from '../src/client/skeleton/InputBar.tsx'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
function setup(over?: Partial<InputBarProps>) {
|
||||
const props: InputBarProps = {
|
||||
draft: 'hello', running: false, disabled: false, error: null,
|
||||
variant: 'composer',
|
||||
onDraftChange: vi.fn(), onSend: vi.fn(), onStop: vi.fn(),
|
||||
...over,
|
||||
}
|
||||
const view = render(<InputBar {...props} />)
|
||||
const textarea = view.container.querySelector('textarea')!
|
||||
const button = view.container.querySelector('button')!
|
||||
return { view, textarea, button, props }
|
||||
}
|
||||
|
||||
describe('Enter semantics', () => {
|
||||
it('plain Enter sends queue mode; repeat and empty are suppressed', () => {
|
||||
const { textarea, props } = setup()
|
||||
fireEvent.keyDown(textarea, { key: 'Enter' })
|
||||
expect(props.onSend).toHaveBeenCalledWith('queue')
|
||||
fireEvent.keyDown(textarea, { key: 'Enter', repeat: true })
|
||||
expect(props.onSend).toHaveBeenCalledTimes(1)
|
||||
const empty = setup({ draft: ' ' })
|
||||
fireEvent.keyDown(empty.textarea, { key: 'Enter' })
|
||||
expect(empty.props.onSend).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('non-Enter keys and Shift+Enter fall through to native behavior', () => {
|
||||
const { textarea, props } = setup()
|
||||
fireEvent.keyDown(textarea, { key: 'a' })
|
||||
fireEvent.keyDown(textarea, { key: 'Enter', shiftKey: true })
|
||||
expect(props.onSend).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('Ctrl/Meta+Enter inserts a newline through execCommand instead of sending', () => {
|
||||
const exec = vi.fn()
|
||||
;(document as unknown as { execCommand: typeof exec }).execCommand = exec
|
||||
const { textarea, props } = setup()
|
||||
fireEvent.keyDown(textarea, { key: 'Enter', ctrlKey: true })
|
||||
expect(exec).toHaveBeenCalledWith('insertText', false, '\n')
|
||||
expect(props.onSend).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('composition Enter never sends: ref guard, isComposing, and keyCode 229 paths', async () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
const { textarea, props } = setup()
|
||||
fireEvent.compositionStart(textarea)
|
||||
fireEvent.keyDown(textarea, { key: 'Enter' })
|
||||
expect(props.onSend).not.toHaveBeenCalled()
|
||||
fireEvent.compositionEnd(textarea)
|
||||
// Safari delivers the closing keydown before the deferred clear.
|
||||
fireEvent.keyDown(textarea, { key: 'Enter' })
|
||||
expect(props.onSend).not.toHaveBeenCalled()
|
||||
vi.advanceTimersByTime(20)
|
||||
fireEvent.keyDown(textarea, { key: 'Enter', keyCode: 229 })
|
||||
expect(props.onSend).not.toHaveBeenCalled()
|
||||
fireEvent.keyDown(textarea, { key: 'Enter' })
|
||||
expect(props.onSend).toHaveBeenCalledTimes(1)
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('running lock and primary button', () => {
|
||||
it('running locks the textarea and turns the primary into stop', () => {
|
||||
const { textarea, button, props } = setup({ running: true })
|
||||
expect(textarea.disabled).toBe(true)
|
||||
expect(button.getAttribute('aria-label')).toBe('停止')
|
||||
fireEvent.click(button)
|
||||
expect(props.onStop).toHaveBeenCalledTimes(1)
|
||||
expect(props.onSend).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('idle primary sends and disables on empty draft', () => {
|
||||
const { button, props } = setup()
|
||||
fireEvent.click(button)
|
||||
expect(props.onSend).toHaveBeenCalledWith('queue')
|
||||
const empty = setup({ draft: '' })
|
||||
expect(empty.button.disabled).toBe(true)
|
||||
})
|
||||
|
||||
it('unlock refocuses the textarea; mousedown on the button keeps focus', () => {
|
||||
const { view, props } = setup({ running: true })
|
||||
view.rerender(<InputBar {...props} running={false} />)
|
||||
const textarea = view.container.querySelector('textarea')!
|
||||
expect(document.activeElement).toBe(textarea)
|
||||
textarea.blur()
|
||||
fireEvent.mouseDown(view.container.querySelector('button')!)
|
||||
expect(document.activeElement).toBe(textarea)
|
||||
})
|
||||
|
||||
it('disabled state shows the unavailable placeholder; typing forwards drafts', () => {
|
||||
const { textarea } = setup({ disabled: true, draft: '' })
|
||||
expect(textarea.placeholder).toBe('会话不可用')
|
||||
const live = setup({ draft: '' })
|
||||
expect(live.textarea.placeholder).toContain('Enter 发送')
|
||||
fireEvent.change(live.textarea, { target: { value: 'typed' } })
|
||||
expect(live.props.onDraftChange).toHaveBeenCalledWith('typed')
|
||||
const runningPh = setup({ running: true, draft: '' })
|
||||
expect(runningPh.textarea.placeholder).toContain('停止')
|
||||
const custom = setup({ placeholder: '自定义' })
|
||||
expect(custom.textarea.placeholder).toBe('自定义')
|
||||
})
|
||||
})
|
||||
|
||||
describe('error strip and variants', () => {
|
||||
it('renders send and stop failure copy', () => {
|
||||
const send = setup({ error: { op: 'send', message: 'boom' } })
|
||||
expect(send.view.getByText(/发送失败:boom/)).toBeTruthy()
|
||||
const stop = setup({ error: { op: 'stop', message: 'halt' } })
|
||||
expect(stop.view.getByText(/停止失败:halt/)).toBeTruthy()
|
||||
})
|
||||
|
||||
it('hero variant adds the hero class and accessory row renders', () => {
|
||||
const { view } = setup({ variant: 'hero', accessory: <i data-testid="acc" /> })
|
||||
expect(view.getByTestId('acc')).toBeTruthy()
|
||||
expect(view.container.querySelector('[class*="hero"]')).not.toBeNull()
|
||||
})
|
||||
})
|
||||
121
packages/client/ui-conversation/tests/selection-survival.spec.ts
Normal file
121
packages/client/ui-conversation/tests/selection-survival.spec.ts
Normal file
@@ -0,0 +1,121 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* M1a regression pin: the per-scope selection must survive list refreshes.
|
||||
* Drives the REAL SessionsService + ConversationService chain over the
|
||||
* programmable wire fake — a late list refresh that upgrades the display
|
||||
* title (bare id → cwd basename) and a reconnect-driven refreshList+resync
|
||||
* must neither recreate the session scope nor clear the selection account.
|
||||
*/
|
||||
import { Context } from 'cordis'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-client-connection/client'
|
||||
import { SessionsService } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { ConversationService } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
|
||||
// The runtime package's programmable fake lives in its tests; import through
|
||||
// the src path (same pattern the runtime specs use — test-support material).
|
||||
import { FakeApiClient, ok } from '../../runtime/tests/fake-api.ts'
|
||||
|
||||
const sid = (s: string): SessionId => s as SessionId
|
||||
|
||||
interface Bench {
|
||||
ctx: Context
|
||||
api: FakeApiClient
|
||||
sessions: SessionsService
|
||||
conversation: ConversationService
|
||||
}
|
||||
|
||||
function bench(): Bench {
|
||||
const ctx = new Context()
|
||||
const api = new FakeApiClient()
|
||||
const sessions = new SessionsService(ctx, api)
|
||||
const conversation = new ConversationService(ctx)
|
||||
return { ctx, api, sessions, conversation }
|
||||
}
|
||||
|
||||
async function flush(): Promise<void> {
|
||||
// Manager notifier + store batching are microtask-based.
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
}
|
||||
|
||||
function feed(b: Bench, rows: { id: string; cwd?: string; running?: boolean }[]): void {
|
||||
b.api.onList = () => Promise.resolve(ok({
|
||||
items: rows.map(r => ({
|
||||
sessionId: sid(r.id), updatedAt: 1, running: r.running ?? false,
|
||||
...(r.cwd !== undefined ? { cwd: r.cwd } : {}),
|
||||
})),
|
||||
}) as never)
|
||||
}
|
||||
|
||||
describe('selection survives list refreshes (M1a)', () => {
|
||||
it('create → select → title-upgrading refresh keeps scope, binding, store and value', async () => {
|
||||
const b = bench()
|
||||
// First-send shape: client-side create inserts the row without cwd (title = bare id).
|
||||
b.api.onCreate = () => Promise.resolve(ok({ sessionId: sid('s1') }))
|
||||
const id = await b.sessions.create({})
|
||||
await flush()
|
||||
expect(b.sessions.list.getSnapshot().byId[id]?.title).toBe('s1')
|
||||
|
||||
const binding = b.sessions.binding(id)
|
||||
expect(binding).toBeDefined()
|
||||
const scoped = b.sessions.scope(id)!
|
||||
const store = (scoped.get('conversation') as ConversationService).selection
|
||||
store.set({ turnSeq: 3, callId: 'c1' })
|
||||
|
||||
// The late list refresh lands (host knows the cwd → formal title).
|
||||
feed(b, [{ id: 's1', cwd: '/w/proj-a' }])
|
||||
await b.sessions.manager.refreshList()
|
||||
await flush()
|
||||
expect(b.sessions.list.getSnapshot().byId[id]?.title).toBe('proj-a')
|
||||
|
||||
// Scope, binding and the selection account must all be identity-stable.
|
||||
expect(b.sessions.scope(id)).toBe(scoped)
|
||||
expect(b.sessions.binding(id)).toBe(binding)
|
||||
const after = (b.sessions.scope(id)!.get('conversation') as ConversationService).selection
|
||||
expect(after).toBe(store)
|
||||
expect(after.getSnapshot()).toEqual({ turnSeq: 3, callId: 'c1' })
|
||||
})
|
||||
|
||||
it('reconnect (handleConnected: refreshList + resync) keeps the selection account', async () => {
|
||||
const b = bench()
|
||||
feed(b, [{ id: 's1' }])
|
||||
await b.sessions.manager.refreshList()
|
||||
await flush()
|
||||
|
||||
const scoped = b.sessions.scope(sid('s1'))!
|
||||
const store = (scoped.get('conversation') as ConversationService).selection
|
||||
store.set({ turnSeq: 1, callId: 'c9' })
|
||||
|
||||
// Reconnect generation: title upgrade arrives with the re-pull.
|
||||
feed(b, [{ id: 's1', cwd: '/w/proj-a', running: true }])
|
||||
b.sessions.manager.handleConnected()
|
||||
await flush()
|
||||
await flush()
|
||||
|
||||
expect(b.sessions.scope(sid('s1'))).toBe(scoped)
|
||||
const after = (b.sessions.scope(sid('s1'))!.get('conversation') as ConversationService).selection
|
||||
expect(after).toBe(store)
|
||||
expect(after.getSnapshot()).toEqual({ turnSeq: 1, callId: 'c9' })
|
||||
})
|
||||
|
||||
it('a transiently failing list refresh does not prune live scopes', async () => {
|
||||
const b = bench()
|
||||
feed(b, [{ id: 's1' }])
|
||||
await b.sessions.manager.refreshList()
|
||||
await flush()
|
||||
const scoped = b.sessions.scope(sid('s1'))!
|
||||
const store = (scoped.get('conversation') as ConversationService).selection
|
||||
store.set({ turnSeq: 2, callId: 'c2' })
|
||||
|
||||
// Wire hiccup: the reconnect-time list RPC throws (transport error).
|
||||
b.api.onList = () => Promise.reject(new Error('boom'))
|
||||
b.sessions.manager.handleConnected()
|
||||
await flush()
|
||||
await flush()
|
||||
|
||||
expect(b.sessions.scope(sid('s1'))).toBe(scoped)
|
||||
expect((b.sessions.scope(sid('s1'))!.get('conversation') as ConversationService).selection.getSnapshot())
|
||||
.toEqual({ turnSeq: 2, callId: 'c2' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,191 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* ConversationService orchestration half: scope-addressed send/cancel (result
|
||||
* folding, root throw), openDetails choreography, the startSession chain, and
|
||||
* the service-unavailable loud failures. Store semantics live in
|
||||
* service-stores.spec.ts.
|
||||
*/
|
||||
import { Context } from 'cordis'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { scopeOf } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { SessionId, SessionsService } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { ConversationService } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
|
||||
const sid = (s: string): SessionId => s as SessionId
|
||||
|
||||
/** Recover the module-private scope tag through the public seam (same probe as service-stores.spec). */
|
||||
const SCOPE_TAG: symbol = (() => {
|
||||
const recorded: (string | symbol)[] = []
|
||||
const spy = new Proxy(new Context(), {
|
||||
get(target, prop, receiver): unknown {
|
||||
recorded.push(prop)
|
||||
return Reflect.get(target, prop, receiver)
|
||||
},
|
||||
})
|
||||
void scopeOf(spy)
|
||||
const symbol = recorded.find((p): p is symbol => typeof p === 'symbol')
|
||||
if (symbol === undefined) throw new Error('scopeOf probe recorded no symbol read')
|
||||
return symbol
|
||||
})()
|
||||
|
||||
interface SessionDouble {
|
||||
prompt: ReturnType<typeof vi.fn>
|
||||
cancel: ReturnType<typeof vi.fn>
|
||||
}
|
||||
|
||||
async function bench(opts?: { layout?: boolean; sessions?: boolean }) {
|
||||
const ctx = new Context()
|
||||
const sessionDoubles = new Map<SessionId, SessionDouble>()
|
||||
const scopes = new Map<SessionId, Context>()
|
||||
const mint = (id: SessionId): Context => {
|
||||
let scoped = scopes.get(id)
|
||||
if (scoped === undefined) {
|
||||
const fiber = ctx.plugin(() => {})
|
||||
scoped = fiber.ctx.extend({ [SCOPE_TAG]: id })
|
||||
scopes.set(id, scoped)
|
||||
}
|
||||
return scoped
|
||||
}
|
||||
const createMock = vi.fn(() => Promise.resolve(sid('new-1')))
|
||||
const sessionsFake = {
|
||||
manager: {
|
||||
get: (id: SessionId) => {
|
||||
let s = sessionDoubles.get(id)
|
||||
if (s === undefined) {
|
||||
s = {
|
||||
prompt: vi.fn(() => Promise.resolve({ ok: true, value: { accepted: true } })),
|
||||
cancel: vi.fn(() => Promise.resolve({ ok: true, value: { accepted: true } })),
|
||||
}
|
||||
sessionDoubles.set(id, s)
|
||||
}
|
||||
return s
|
||||
},
|
||||
},
|
||||
create: createMock,
|
||||
scope: (id: SessionId) => (id === sid('new-1') ? mint(id) : scopes.get(id)),
|
||||
} as unknown as SessionsService
|
||||
if (opts?.sessions !== false) ctx.provide('sessions', sessionsFake)
|
||||
const layoutFake = { open: vi.fn(), openDetails: vi.fn() }
|
||||
if (opts?.layout !== false) ctx.provide('layout', layoutFake)
|
||||
const fiber = ctx.plugin((pluginCtx) => { void new ConversationService(pluginCtx) })
|
||||
await fiber.await()
|
||||
const svc = ctx.get('conversation') as ConversationService
|
||||
const scopedSvc = (id: SessionId) => mint(id).get('conversation') as ConversationService
|
||||
return { ctx, svc, scopedSvc, mint, sessionDoubles, sessionsFake, createMock, layoutFake }
|
||||
}
|
||||
|
||||
describe('send / cancel', () => {
|
||||
it('sends one text block through the scoped session with the mode', async () => {
|
||||
const b = await bench()
|
||||
await b.scopedSvc(sid('s1')).send('hello', 'steer')
|
||||
expect(b.sessionDoubles.get(sid('s1'))!.prompt).toHaveBeenCalledWith(
|
||||
[{ type: 'text', text: 'hello' }], 'steer')
|
||||
})
|
||||
|
||||
it('folds business failure into a thrown error carrying code and message', async () => {
|
||||
const b = await bench()
|
||||
const s = b.scopedSvc(sid('s1'))
|
||||
// Materialize the double first (manager.get is the lazy mint point).
|
||||
b.sessionsFake.manager.get(sid('s1'))
|
||||
const double = b.sessionDoubles.get(sid('s1'))!
|
||||
double.prompt.mockResolvedValue({ ok: false, error: { code: 'agent-busy', message: 'busy' } })
|
||||
await expect(s.send('x', 'queue')).rejects.toThrow(/send failed: agent-busy: busy/)
|
||||
})
|
||||
|
||||
it('cancel resolves on ok and throws the folded business error', async () => {
|
||||
const b = await bench()
|
||||
const s = b.scopedSvc(sid('s1'))
|
||||
await s.cancel()
|
||||
const double = b.sessionDoubles.get(sid('s1'))!
|
||||
expect(double.cancel).toHaveBeenCalledTimes(1)
|
||||
double.cancel.mockResolvedValue({ ok: false, error: { code: 'internal', message: 'nope' } })
|
||||
await expect(s.cancel()).rejects.toThrow(/cancel failed: internal: nope/)
|
||||
})
|
||||
|
||||
it('root-context send and cancel throw the addressing hint', async () => {
|
||||
const b = await bench()
|
||||
await expect(b.svc.send('x', 'queue')).rejects.toThrow(/requires a session scope/)
|
||||
await expect(b.svc.cancel()).rejects.toThrow(/requires a session scope/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('openDetails', () => {
|
||||
it('writes the scoped selection then opens the layout panel', async () => {
|
||||
const b = await bench()
|
||||
const s = b.scopedSvc(sid('s1'))
|
||||
s.openDetails({ turnSeq: 3, callId: 'c1', toolName: 'bash' })
|
||||
expect(s.selection.getSnapshot()).toEqual({ turnSeq: 3, callId: 'c1', toolName: 'bash' })
|
||||
expect(b.layoutFake.openDetails).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('startSession chain', () => {
|
||||
it('creates, navigates, then sends through the new scope', async () => {
|
||||
const b = await bench()
|
||||
await b.svc.startSession({ cwd: '/proj', text: 'first', mode: 'queue' })
|
||||
expect(b.createMock).toHaveBeenCalledWith({ cwd: '/proj' })
|
||||
expect(b.layoutFake.open).toHaveBeenCalledWith(sid('new-1'))
|
||||
expect(b.sessionDoubles.get(sid('new-1'))!.prompt).toHaveBeenCalledWith(
|
||||
[{ type: 'text', text: 'first' }], 'queue')
|
||||
})
|
||||
|
||||
it('omits cwd from create when not chosen', async () => {
|
||||
const b = await bench()
|
||||
await b.svc.startSession({ text: 't', mode: 'steer' })
|
||||
expect(b.createMock).toHaveBeenCalledWith({})
|
||||
})
|
||||
|
||||
it('fails loud when the created session resolves no scope', async () => {
|
||||
const b = await bench()
|
||||
;(b.sessionsFake.create as ReturnType<typeof vi.fn>).mockResolvedValue(sid('ghost'))
|
||||
await expect(b.svc.startSession({ text: 't', mode: 'queue' })).rejects.toThrow(/resolved no scope/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('service-unavailable loud failures', () => {
|
||||
it('throws when sessions is missing', async () => {
|
||||
const b = await bench({ sessions: false })
|
||||
await expect(b.svc.startSession({ text: 't', mode: 'queue' })).rejects.toThrow(/sessions service unavailable/)
|
||||
})
|
||||
|
||||
it('throws when layout is missing', async () => {
|
||||
const b = await bench({ layout: false })
|
||||
const s = b.scopedSvc(sid('s1'))
|
||||
expect(() => { s.openDetails({ turnSeq: 1 }) }).toThrow(/layout service unavailable/)
|
||||
})
|
||||
|
||||
it('startSession fails loud when the new scope cannot resolve conversation', async () => {
|
||||
const b = await bench()
|
||||
// A scope minted outside the service tree: scoped.get('conversation') finds nothing.
|
||||
const foreign = new Context()
|
||||
const foreignScope = foreign.plugin(() => {}).ctx.extend({})
|
||||
;(b.sessionsFake.scope as unknown) = () => foreignScope
|
||||
await expect(b.svc.startSession({ text: 't', mode: 'queue' }))
|
||||
.rejects.toThrow(/conversation service unavailable through the new scope/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('views ordering and draft persistence branches', () => {
|
||||
it('orders by explicit order with undefined treated as zero (both comparator arms)', async () => {
|
||||
const b = await bench()
|
||||
const entry = (id: string, order?: number) => ({
|
||||
id, label: id, component: () => null,
|
||||
...(order !== undefined ? { order } : {}),
|
||||
})
|
||||
b.svc.registerView(entry('z-late', 5) as never)
|
||||
b.svc.registerView(entry('default-zero') as never)
|
||||
b.svc.registerView(entry('first', -1) as never)
|
||||
expect(b.svc.views().map(v => v.id)).toEqual(['first', 'default-zero', 'z-late'])
|
||||
})
|
||||
|
||||
it('draft store round-trips through localStorage and removes the key when emptied', async () => {
|
||||
const b = await bench()
|
||||
localStorage.setItem('dsh.conversation.draft.s9', 'restored')
|
||||
const s = b.scopedSvc(sid('s9'))
|
||||
expect(s.drafts.getSnapshot()).toBe('restored')
|
||||
s.drafts.set('typed')
|
||||
expect(localStorage.getItem('dsh.conversation.draft.s9')).toBe('typed')
|
||||
s.drafts.set('')
|
||||
expect(localStorage.getItem('dsh.conversation.draft.s9')).toBeNull()
|
||||
})
|
||||
})
|
||||
176
packages/client/ui-conversation/tests/service-stores.spec.ts
Normal file
176
packages/client/ui-conversation/tests/service-stores.spec.ts
Normal file
@@ -0,0 +1,176 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* ConversationService store half: scope-addressed selection/drafts accounts
|
||||
* (lazy mint, per-scope isolation, root access throws, scope teardown
|
||||
* collects), view registry (order, duplicate throw, effect-scoped disposal,
|
||||
* uSES read face). Send/cancel/startSession orchestration live in
|
||||
* service-orchestration.spec.ts.
|
||||
*/
|
||||
import { Context } from 'cordis'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { FC } from 'react'
|
||||
import { scopeOf } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { SessionId, SessionsService } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { ConversationService } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import type { ConvViewProps, ViewEntry } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
|
||||
const sid = (s: string): SessionId => s as SessionId
|
||||
|
||||
/**
|
||||
* The scope tag symbol is module-private to the runtime package; recover it
|
||||
* through the public seam by recording which symbol scopeOf reads off a
|
||||
* spying proxy (keeps this bench honest against the real tagging shape
|
||||
* without dragging the full SessionsService + wire fake in here).
|
||||
*/
|
||||
const SCOPE_TAG: symbol = (() => {
|
||||
const recorded: (string | symbol)[] = []
|
||||
const spy = new Proxy(new Context(), {
|
||||
get(target, prop, receiver): unknown {
|
||||
recorded.push(prop)
|
||||
return Reflect.get(target, prop, receiver)
|
||||
},
|
||||
})
|
||||
void scopeOf(spy)
|
||||
const symbol = recorded.find((p): p is symbol => typeof p === 'symbol')
|
||||
if (symbol === undefined) throw new Error('scopeOf probe recorded no symbol read')
|
||||
return symbol
|
||||
})()
|
||||
|
||||
/** Scope bench: real cordis scope fibers tagged like SessionsService.resolve mints them. */
|
||||
interface Bench {
|
||||
ctx: Context
|
||||
svc: ConversationService
|
||||
mint: (id: SessionId) => Context
|
||||
dispose: (id: SessionId) => Promise<void>
|
||||
}
|
||||
|
||||
function bench(): Bench {
|
||||
const ctx = new Context()
|
||||
const fibers = new Map<SessionId, { fiber: ReturnType<Context['plugin']>; ctx: Context }>()
|
||||
const mint = (id: SessionId): Context => {
|
||||
let rec = fibers.get(id)
|
||||
if (rec === undefined) {
|
||||
const fiber = ctx.plugin(() => {})
|
||||
const scoped = fiber.ctx.extend({ [SCOPE_TAG]: id })
|
||||
rec = { fiber, ctx: scoped }
|
||||
fibers.set(id, rec)
|
||||
}
|
||||
return rec.ctx
|
||||
}
|
||||
const dispose = async (id: SessionId): Promise<void> => {
|
||||
const rec = fibers.get(id)
|
||||
if (rec !== undefined) {
|
||||
await rec.fiber.dispose()
|
||||
fibers.delete(id)
|
||||
}
|
||||
}
|
||||
const sessions = { scope: (id: SessionId) => fibers.get(id)?.ctx } as unknown as SessionsService
|
||||
ctx.provide('sessions', sessions)
|
||||
const svc = new ConversationService(ctx)
|
||||
return { ctx, svc, mint, dispose }
|
||||
}
|
||||
|
||||
/** Scoped service view: ctx.get binds the root singleton to the scoped ctx (scope addressing seam). */
|
||||
function convo(scoped: Context): ConversationService {
|
||||
const service = scoped.get('conversation')
|
||||
if (service === undefined) throw new Error('bench: conversation unavailable')
|
||||
return service
|
||||
}
|
||||
|
||||
const viewComp = (() => null) as unknown as FC<ConvViewProps>
|
||||
const entry = (id: string, order?: number): ViewEntry =>
|
||||
({ id, label: id, component: viewComp, ...(order !== undefined ? { order } : {}) }) as unknown as ViewEntry
|
||||
|
||||
beforeEach(() => { localStorage.clear() })
|
||||
|
||||
describe('scope addressing of stores', () => {
|
||||
it('root-context selection/drafts access throws with the addressing hint', () => {
|
||||
const b = bench()
|
||||
expect(() => b.svc.selection).toThrow(/requires a session scope/)
|
||||
expect(() => b.svc.drafts).toThrow(/requires a session scope/)
|
||||
})
|
||||
|
||||
it('mints one store per scope and keeps identity per session', () => {
|
||||
const b = bench()
|
||||
const c1 = b.mint(sid('s1'))
|
||||
const c2 = b.mint(sid('s2'))
|
||||
const sel1 = convo(c1).selection
|
||||
const sel2 = convo(c2).selection
|
||||
expect(sel1).not.toBe(sel2)
|
||||
expect(convo(c1).selection).toBe(sel1)
|
||||
sel1.set({ turnSeq: 3 })
|
||||
expect(sel1.getSnapshot()).toEqual({ turnSeq: 3 })
|
||||
expect(sel2.getSnapshot()).toBeNull()
|
||||
})
|
||||
|
||||
it('persists drafts keyed by session id and evolves independently', async () => {
|
||||
const b = bench()
|
||||
const c1 = b.mint(sid('s1'))
|
||||
convo(c1).drafts.set('hello')
|
||||
expect(localStorage.getItem('dsh.conversation.draft.s1')).toBe('hello')
|
||||
const c2 = b.mint(sid('s2'))
|
||||
expect(convo(c2).drafts.getSnapshot()).toBe('')
|
||||
// Re-minting after teardown rehydrates from storage; clearing removes the key.
|
||||
await b.dispose(sid('s1'))
|
||||
expect(convo(b.mint(sid('s1'))).drafts.getSnapshot()).toBe('hello')
|
||||
convo(b.mint(sid('s1'))).drafts.set('')
|
||||
expect(localStorage.getItem('dsh.conversation.draft.s1')).toBeNull()
|
||||
})
|
||||
|
||||
it('scope fiber disposal collects the store account (fresh store on re-mint)', async () => {
|
||||
const b = bench()
|
||||
const c1 = b.mint(sid('s1'))
|
||||
const sel = convo(c1).selection
|
||||
sel.set({ turnSeq: 1 })
|
||||
await b.dispose(sid('s1'))
|
||||
const again = b.mint(sid('s1'))
|
||||
const sel2 = convo(again).selection
|
||||
expect(sel2).not.toBe(sel)
|
||||
expect(sel2.getSnapshot()).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('view registry', () => {
|
||||
it('orders by order (ties keep registration sequence) with a stable cache reference', () => {
|
||||
const b = bench()
|
||||
b.svc.registerView(entry('chat', 0))
|
||||
b.svc.registerView(entry('waterfall', 2))
|
||||
b.svc.registerView(entry('trajectory', 1))
|
||||
const views = b.svc.views()
|
||||
expect(views.map(v => v.id)).toEqual(['chat', 'trajectory', 'waterfall'])
|
||||
expect(b.svc.views()).toBe(views)
|
||||
})
|
||||
|
||||
it('duplicate id throws; disposer removes and bumps the version', () => {
|
||||
const b = bench()
|
||||
const fn = vi.fn()
|
||||
b.svc.subscribeViews(fn)
|
||||
const off = b.svc.registerView(entry('chat'))
|
||||
expect(() => b.svc.registerView(entry('chat'))).toThrow(/already registered/)
|
||||
const v1 = b.svc.viewsVersion()
|
||||
off()
|
||||
expect(b.svc.viewsVersion()).toBeGreaterThan(v1)
|
||||
expect(b.svc.views()).toEqual([])
|
||||
expect(fn).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('unsubscribe stops notifications', () => {
|
||||
const b = bench()
|
||||
const fn = vi.fn()
|
||||
const unsub = b.svc.subscribeViews(fn)
|
||||
unsub()
|
||||
b.svc.registerView(entry('chat'))
|
||||
expect(fn).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('a registering plugin fiber unloading collects its views (effect cascade)', async () => {
|
||||
const b = bench()
|
||||
const fiber = b.ctx.plugin((pluginCtx: Context) => {
|
||||
convo(pluginCtx).registerView(entry('chat'))
|
||||
})
|
||||
await fiber.await()
|
||||
expect(b.svc.views().map(v => v.id)).toEqual(['chat'])
|
||||
await fiber.dispose()
|
||||
expect(b.svc.views()).toEqual([])
|
||||
})
|
||||
})
|
||||
245
packages/client/ui-conversation/tests/skeleton-branches.spec.tsx
Normal file
245
packages/client/ui-conversation/tests/skeleton-branches.spec.tsx
Normal file
@@ -0,0 +1,245 @@
|
||||
// @vitest-environment jsdom
|
||||
// Skeleton branch tails for the coverage gate (complements skeleton.spec.tsx
|
||||
// acceptance flows): breadcrumb ancestry rendering + error strip in
|
||||
// ConversationRoot, DetailsPanel non-JSON args / non-text result blocks /
|
||||
// error-only results, EmptyState failure surface and custom-directory swap.
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { cleanup, fireEvent, render, waitFor } from '@testing-library/react'
|
||||
import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react'
|
||||
import type { UseSession } from '@deepseek-ai/dsh-client-web-react'
|
||||
import type { ConversationSnapshot, SessionId, SessionSummary } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { ConversationRoot, DetailsPanel, EmptyState } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import type { SelectionTarget, ViewEntry } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
const SID = 's1' as SessionId
|
||||
|
||||
function snapshotBase(): ConversationSnapshot {
|
||||
return {
|
||||
sessionId: SID, nodes: [], foldDegraded: false, partial: null, runningCalls: [],
|
||||
pending: [], running: false, removed: false, openState: 'open', openError: null,
|
||||
hasMore: false, loadingOlder: false, promptError: null, lastAgentError: null,
|
||||
} as ConversationSnapshot
|
||||
}
|
||||
|
||||
function sessionSource(over?: Partial<ConversationSnapshot>) {
|
||||
const snap = { ...snapshotBase(), ...over }
|
||||
return {
|
||||
getSnapshot: () => snap,
|
||||
subscribe: () => () => {},
|
||||
}
|
||||
}
|
||||
|
||||
const summary = (id: string, title: string): SessionSummary =>
|
||||
({ id: id as SessionId, title, running: false, updatedAt: 1 })
|
||||
|
||||
describe('ConversationRoot branches', () => {
|
||||
const chatEntry: ViewEntry = {
|
||||
id: 'chat', label: 'Chat', component: () => null,
|
||||
} as unknown as ViewEntry
|
||||
|
||||
function rootProps(over?: {
|
||||
ancestry?: readonly SessionSummary[]
|
||||
snapshot?: Partial<ConversationSnapshot>
|
||||
}) {
|
||||
const open = vi.fn()
|
||||
const view = render(
|
||||
<ConversationRoot
|
||||
sessionId={SID}
|
||||
useSession={bindSnapshotSelector(sessionSource(over?.snapshot)) as unknown as UseSession}
|
||||
useAncestry={() => over?.ancestry ?? []}
|
||||
views={{ list: () => [chatEntry], subscribe: () => () => {}, version: () => 1 }}
|
||||
useActiveView={() => undefined}
|
||||
composer={{ useDraft: () => '', setDraft: vi.fn(), send: vi.fn(), stop: vi.fn() }}
|
||||
actions={{ openView: vi.fn(), open }}
|
||||
renderView={() => <div data-testid="view-body" />}
|
||||
/>,
|
||||
)
|
||||
return { view, open }
|
||||
}
|
||||
|
||||
it('renders the ancestry breadcrumb with separators and navigates on ancestor click', () => {
|
||||
const { view, open } = rootProps({
|
||||
ancestry: [summary('root-1', 'Workspace'), summary('s1', 'Current')],
|
||||
})
|
||||
expect(view.getByText('Workspace')).toBeTruthy()
|
||||
expect(view.getByText('/')).toBeTruthy()
|
||||
fireEvent.click(view.getByText('Workspace'))
|
||||
expect(open).toHaveBeenCalledWith('root-1' as SessionId)
|
||||
// The last crumb is the current session: disabled, no navigation.
|
||||
fireEvent.click(view.getByText('Current'))
|
||||
expect(open).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('falls back to the raw session id without ancestry and counts user turns', () => {
|
||||
const { view } = rootProps({
|
||||
snapshot: { nodes: [{ kind: 'user', seq: 1 } as never, { kind: 'assistant', seq: 2 } as never] },
|
||||
})
|
||||
expect(view.getByText(SID)).toBeTruthy()
|
||||
expect(view.getByText(/1 turns/)).toBeTruthy()
|
||||
})
|
||||
|
||||
it('surfaces promptError through the composer error strip', () => {
|
||||
const { view } = rootProps({
|
||||
snapshot: { promptError: { op: 'stop', error: { message: 'halt', code: 'internal' } } as never },
|
||||
})
|
||||
expect(view.getByText(/停止失败:halt(internal)/)).toBeTruthy()
|
||||
})
|
||||
|
||||
it('an unknown active view id falls back to the first registered view', () => {
|
||||
const view = render(
|
||||
<ConversationRoot
|
||||
sessionId={SID}
|
||||
useSession={bindSnapshotSelector(sessionSource()) as unknown as UseSession}
|
||||
useAncestry={() => []}
|
||||
views={{ list: () => [chatEntry], subscribe: () => () => {}, version: () => 1 }}
|
||||
useActiveView={() => 'gone' as never}
|
||||
composer={{ useDraft: () => '', setDraft: vi.fn(), send: vi.fn(), stop: vi.fn() }}
|
||||
actions={{ openView: vi.fn(), open: vi.fn() }}
|
||||
renderView={(entry) => <div data-testid={`body-${entry.id}`} />}
|
||||
/>,
|
||||
)
|
||||
expect(view.getByTestId('body-chat')).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
describe('DetailsPanel branches', () => {
|
||||
function panel(selection: SelectionTarget | null, snapshot?: Partial<ConversationSnapshot>) {
|
||||
return render(
|
||||
<DetailsPanel
|
||||
sessionId={SID}
|
||||
useSession={bindSnapshotSelector(sessionSource(snapshot)) as unknown as UseSession}
|
||||
useSelection={bindSnapshotSelector({ getSnapshot: () => selection, subscribe: () => () => {} })}
|
||||
actions={{ closeDetails: vi.fn() }}
|
||||
/>,
|
||||
)
|
||||
}
|
||||
|
||||
it('shows non-JSON args verbatim (streaming fragment path)', () => {
|
||||
const view = panel({ turnSeq: 1, callId: 'c1', toolName: 'bash' }, {
|
||||
runningCalls: [{ callId: 'c1', name: 'bash', argsRaw: '{"cmd": tru', turn: 1, step: 1, callView: null }],
|
||||
})
|
||||
expect(view.getByText('{"cmd": tru')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('a selection without callId renders the empty hint (selector null arm)', () => {
|
||||
const view = panel({ turnSeq: 2 })
|
||||
expect(view.getByText(/点击消息流中的工具行查看详情/)).toBeTruthy()
|
||||
})
|
||||
|
||||
it('snapshot updates re-run the material selector through the shallow equality arm', () => {
|
||||
let snap = { ...snapshotBase(), runningCalls: [{ callId: 'c9', name: 'bash', argsRaw: '{"a":1}', turn: 1, step: 1, callView: null }] } as ConversationSnapshot
|
||||
const subs = new Set<() => void>()
|
||||
const source = {
|
||||
getSnapshot: () => snap,
|
||||
subscribe: (fn: () => void) => {
|
||||
subs.add(fn)
|
||||
return () => subs.delete(fn)
|
||||
},
|
||||
}
|
||||
const SEL: SelectionTarget = { turnSeq: 1, callId: 'c9' }
|
||||
const view = render(
|
||||
<DetailsPanel
|
||||
sessionId={SID}
|
||||
useSession={bindSnapshotSelector(source) as unknown as UseSession}
|
||||
useSelection={bindSnapshotSelector({ getSnapshot: () => SEL, subscribe: () => () => {} })}
|
||||
actions={{ closeDetails: vi.fn() }}
|
||||
/>,
|
||||
)
|
||||
expect(view.getByText(/"a": 1/)).toBeTruthy()
|
||||
// Top-level swap with identical material members: the eq arm short-circuits.
|
||||
snap = { ...snap }
|
||||
for (const fn of [...subs]) fn()
|
||||
expect(view.getByText(/"a": 1/)).toBeTruthy()
|
||||
})
|
||||
|
||||
it('windowless call material: no name/args fallback to callId, mixed node walk skips non-matches', () => {
|
||||
// A tool-result whose call head fell outside the window (call === null),
|
||||
// preceded by non-matching nodes so the walk exercises both filter arms.
|
||||
const view = panel({ turnSeq: 1, callId: 'c8' }, {
|
||||
nodes: [
|
||||
{ kind: 'user', seq: 1, content: [], source: null } as never,
|
||||
{ kind: 'tool-result', seq: 2, callId: 'other', call: { name: 'x', argsRaw: '{}' }, content: [], isError: false, callView: null, resultView: null } as never,
|
||||
{ kind: 'tool-result', seq: 3, callId: 'c8', call: null, content: [], isError: false, callView: null, resultView: null } as never,
|
||||
],
|
||||
})
|
||||
expect(view.getByText('c8')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('stringifies non-text result blocks and renders error-only results', () => {
|
||||
const withBlocks = panel({ turnSeq: 1, callId: 'c2' }, {
|
||||
nodes: [{
|
||||
kind: 'tool-result', seq: 3, callId: 'c2', call: { name: 'read', argsRaw: '{}' },
|
||||
content: [{ type: 'image', data: 'x' } as never],
|
||||
isError: false, callView: null, resultView: null,
|
||||
} as never],
|
||||
})
|
||||
expect(withBlocks.getByText(/"type": "image"/)).toBeTruthy()
|
||||
const errorOnly = panel({ turnSeq: 1, callId: 'c3' }, {
|
||||
nodes: [{
|
||||
kind: 'tool-result', seq: 4, callId: 'c3', call: { name: 'bash', argsRaw: '{}' },
|
||||
content: [], isError: true, error: { name: 'ToolError', code: 'timeout' },
|
||||
callView: null, resultView: null,
|
||||
} as never],
|
||||
})
|
||||
expect(errorOnly.getByText(/ToolError: timeout/)).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
describe('EmptyState branches', () => {
|
||||
// getSnapshot must return a stable reference (uSES contract) — a fresh
|
||||
// array per call loops the selector forever.
|
||||
const CWDS: readonly string[] = ['/proj']
|
||||
const NO_CWDS: readonly string[] = []
|
||||
|
||||
it('keeps the draft and surfaces a local error strip when startSession rejects', async () => {
|
||||
const startSession = vi.fn(() => Promise.reject(new Error('create down')))
|
||||
const view = render(
|
||||
<EmptyState
|
||||
useCwds={bindSnapshotSelector({ getSnapshot: () => CWDS, subscribe: () => () => {} })}
|
||||
actions={{ startSession }}
|
||||
/>,
|
||||
)
|
||||
const textarea = view.container.querySelector('textarea')!
|
||||
fireEvent.change(textarea, { target: { value: 'first task' } })
|
||||
fireEvent.keyDown(textarea, { key: 'Enter' })
|
||||
await waitFor(() => expect(view.getByText(/发送失败:create down/)).toBeTruthy())
|
||||
expect((textarea as HTMLTextAreaElement).value).toBe('first task')
|
||||
})
|
||||
|
||||
it('non-Error rejection reasons stringify into the error strip', async () => {
|
||||
const startSession = vi.fn(() => Promise.reject('plain-string'))
|
||||
const view = render(
|
||||
<EmptyState
|
||||
useCwds={bindSnapshotSelector({ getSnapshot: () => NO_CWDS, subscribe: () => () => {} })}
|
||||
actions={{ startSession }}
|
||||
/>,
|
||||
)
|
||||
const textarea = view.container.querySelector('textarea')!
|
||||
fireEvent.change(textarea, { target: { value: 'go' } })
|
||||
fireEvent.keyDown(textarea, { key: 'Enter' })
|
||||
await waitFor(() => expect(view.getByText(/发送失败:plain-string/)).toBeTruthy())
|
||||
})
|
||||
|
||||
it('cwd select picks an option, swaps to free-form on 新目录, and submits the typed path', async () => {
|
||||
const startSession = vi.fn(() => Promise.resolve())
|
||||
const view = render(
|
||||
<EmptyState
|
||||
useCwds={bindSnapshotSelector({ getSnapshot: () => CWDS, subscribe: () => () => {} })}
|
||||
actions={{ startSession }}
|
||||
/>,
|
||||
)
|
||||
const select = view.container.querySelector('select')!
|
||||
fireEvent.change(select, { target: { value: '/proj' } })
|
||||
expect((select as HTMLSelectElement).value).toBe('/proj')
|
||||
fireEvent.change(select, { target: { value: '::new-directory' } })
|
||||
const custom = view.container.querySelector('input')!
|
||||
fireEvent.change(custom, { target: { value: '/typed/dir' } })
|
||||
const textarea = view.container.querySelector('textarea')!
|
||||
fireEvent.change(textarea, { target: { value: 'task' } })
|
||||
fireEvent.keyDown(textarea, { key: 'Enter' })
|
||||
await waitFor(() => expect(startSession).toHaveBeenCalledWith({ text: 'task', mode: 'queue', cwd: '/typed/dir' }))
|
||||
})
|
||||
})
|
||||
181
packages/client/ui-conversation/tests/skeleton.spec.tsx
Normal file
181
packages/client/ui-conversation/tests/skeleton.spec.tsx
Normal file
@@ -0,0 +1,181 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* Skeleton acceptance: empty-state transition (same InputBar component in
|
||||
* hero position, startSession submit), ConversationRoot view switching over
|
||||
* the registry face, DetailsPanel open/close linkage against a layout-shaped
|
||||
* fake. Components stay framework-free — everything arrives via props here,
|
||||
* exactly as the inject factories will assemble them.
|
||||
*/
|
||||
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { FC } from 'react'
|
||||
import { bindSnapshotSelector, createSnapshotStore } from '@deepseek-ai/dsh-client-web-react'
|
||||
import type { UseSession } from '@deepseek-ai/dsh-client-web-react'
|
||||
import type { SessionId, SessionSummary } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import {
|
||||
ConversationRoot, DetailsPanel, EmptyState,
|
||||
} from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import type { SelectionTarget, ViewEntry, ViewId } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
|
||||
const sid = (s: string): SessionId => s as SessionId
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
/** Minimal conversation snapshot slice the skeleton reads. */
|
||||
interface FakeSnapshot {
|
||||
nodes: readonly { kind: string; callId?: string; call?: { name: string; argsRaw: string } | null; content?: readonly { type: string; text?: string }[]; isError?: boolean }[]
|
||||
runningCalls: readonly { callId: string; name: string; argsRaw: string }[]
|
||||
running: boolean
|
||||
removed: boolean
|
||||
promptError: { op: 'send' | 'stop'; error: { message: string; code: string } } | null
|
||||
}
|
||||
|
||||
function fakeSession(init: Partial<FakeSnapshot> = {}) {
|
||||
const store = createSnapshotStore<FakeSnapshot>({
|
||||
nodes: [], runningCalls: [], running: false, removed: false, promptError: null, ...init,
|
||||
})
|
||||
return { store, useSession: bindSnapshotSelector(store) as unknown as UseSession }
|
||||
}
|
||||
|
||||
describe('EmptyState', () => {
|
||||
it('submits startSession with the typed text and picked cwd; failure surfaces locally', async () => {
|
||||
const cwds = createSnapshotStore<readonly string[]>(['/w/app', '/w/lib'])
|
||||
let reject!: (e: Error) => void
|
||||
const startSession = vi.fn(() => new Promise<void>((_res, rej) => { reject = rej }))
|
||||
render(<EmptyState useCwds={cwds.useSelector} actions={{ startSession }} />)
|
||||
|
||||
fireEvent.change(screen.getByRole('combobox', { name: '项目目录' }), { target: { value: '/w/app' } })
|
||||
const box = screen.getByPlaceholderText('Message to run task, plan and build')
|
||||
fireEvent.change(box, { target: { value: '造一个轮子' } })
|
||||
fireEvent.keyDown(box, { key: 'Enter' })
|
||||
expect(startSession).toHaveBeenCalledWith({ text: '造一个轮子', mode: 'queue', cwd: '/w/app' })
|
||||
|
||||
reject(new Error('后端拒收'))
|
||||
expect(await screen.findByText(/后端拒收/)).toBeTruthy()
|
||||
// Draft survives the failure for retry.
|
||||
expect((box as HTMLTextAreaElement).value).toBe('造一个轮子')
|
||||
})
|
||||
|
||||
it('new-directory option swaps the select for a free-form input', () => {
|
||||
const cwds = createSnapshotStore<readonly string[]>([])
|
||||
render(<EmptyState useCwds={cwds.useSelector} actions={{ startSession: () => Promise.resolve() }} />)
|
||||
fireEvent.change(screen.getByRole('combobox'), { target: { value: '::new-directory' } })
|
||||
const custom = screen.getByPlaceholderText(/目录路径/)
|
||||
fireEvent.change(custom, { target: { value: '/tmp/fresh' } })
|
||||
expect((custom as HTMLInputElement).value).toBe('/tmp/fresh')
|
||||
})
|
||||
})
|
||||
|
||||
describe('ConversationRoot', () => {
|
||||
function bench(views: ViewEntry[], active?: string) {
|
||||
const { useSession } = fakeSession({ nodes: [{ kind: 'user' }, { kind: 'user' }] })
|
||||
const activeStore = createSnapshotStore<string | undefined>(active)
|
||||
const openView = vi.fn((v: string) => { activeStore.set(v) })
|
||||
const open = vi.fn()
|
||||
const drafts = createSnapshotStore<string>('')
|
||||
const send = vi.fn()
|
||||
const stop = vi.fn()
|
||||
const ancestry: SessionSummary[] = [
|
||||
{ id: sid('root'), title: 'proj', running: false, updatedAt: 1 },
|
||||
{ id: sid('s1'), title: 'child', running: false, updatedAt: 1, parentId: sid('root') },
|
||||
]
|
||||
const rendered: string[] = []
|
||||
const ui = render(
|
||||
<ConversationRoot
|
||||
sessionId={sid('s1')}
|
||||
useSession={useSession}
|
||||
useAncestry={() => ancestry}
|
||||
views={{
|
||||
list: () => views,
|
||||
subscribe: () => () => {},
|
||||
version: () => 1,
|
||||
}}
|
||||
useActiveView={() => activeStore.useSelector(s => s) as ViewId | undefined}
|
||||
composer={{
|
||||
useDraft: () => drafts.useSelector(s => s),
|
||||
setDraft: (t) => { drafts.set(t) },
|
||||
send, stop,
|
||||
}}
|
||||
actions={{ openView: openView as (v: never) => void, open }}
|
||||
renderView={(entry) => { rendered.push(entry.id); return <div data-testid={`view-${entry.id}`} /> }}
|
||||
/>)
|
||||
return { ui, openView, open, rendered, send, drafts }
|
||||
}
|
||||
|
||||
const comp = (() => null) as unknown as FC<never>
|
||||
const view = (id: string, label: string): ViewEntry =>
|
||||
({ id, label, component: comp }) as unknown as ViewEntry
|
||||
|
||||
it('renders breadcrumb chain, meta turns, and the active view (default chat)', () => {
|
||||
const { rendered, open } = bench([view('chat', 'Chat'), view('trajectory', 'Trajectory')])
|
||||
expect(screen.getByText('proj')).toBeTruthy()
|
||||
expect(screen.getByText('child')).toBeTruthy()
|
||||
expect(screen.getByText(/2 turns/)).toBeTruthy()
|
||||
expect(rendered).toEqual(['chat'])
|
||||
// Ancestor crumb navigates; current crumb is disabled.
|
||||
fireEvent.click(screen.getByRole('button', { name: 'proj' }))
|
||||
expect(open).toHaveBeenCalledWith('root')
|
||||
expect((screen.getByRole('button', { name: 'child' }) as HTMLButtonElement).disabled).toBe(true)
|
||||
})
|
||||
|
||||
it('switches views through actions.openView and re-renders the new body', () => {
|
||||
const { openView } = bench([view('chat', 'Chat'), view('trajectory', 'Trajectory')])
|
||||
fireEvent.click(screen.getByRole('tab', { name: 'Trajectory' }))
|
||||
expect(openView).toHaveBeenCalledWith('trajectory')
|
||||
expect(screen.getByTestId('view-trajectory')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('hides the tab strip with a single view and wires the composer send', () => {
|
||||
const { send } = bench([view('chat', 'Chat')])
|
||||
expect(screen.queryByRole('tablist')).toBeNull()
|
||||
const box = screen.getByPlaceholderText(/输入消息/)
|
||||
fireEvent.change(box, { target: { value: 'hi' } })
|
||||
fireEvent.keyDown(box, { key: 'Enter' })
|
||||
expect(send).toHaveBeenCalledWith('queue')
|
||||
})
|
||||
})
|
||||
|
||||
describe('DetailsPanel', () => {
|
||||
function benchDetails(snapshot: Partial<FakeSnapshot>, selection: SelectionTarget | null) {
|
||||
const { useSession } = fakeSession(snapshot)
|
||||
const selectionStore = createSnapshotStore<SelectionTarget | null>(selection)
|
||||
const closeDetails = vi.fn()
|
||||
render(
|
||||
<DetailsPanel
|
||||
sessionId={sid('s1')}
|
||||
useSession={useSession}
|
||||
useSelection={selectionStore.useSelector}
|
||||
actions={{ closeDetails }}
|
||||
/>)
|
||||
return { closeDetails, selectionStore }
|
||||
}
|
||||
|
||||
it('renders the selected call args and result; close fires the layout-linked action', () => {
|
||||
const { closeDetails } = benchDetails({
|
||||
nodes: [{
|
||||
kind: 'tool-result', callId: 'c1',
|
||||
call: { name: 'bash', argsRaw: '{"cmd":"ls"}' },
|
||||
content: [{ type: 'text', text: 'file-a\nfile-b' }],
|
||||
isError: false,
|
||||
}],
|
||||
}, { turnSeq: 1, callId: 'c1' })
|
||||
expect(screen.getByText('bash')).toBeTruthy()
|
||||
expect(screen.getByText(/"cmd": "ls"/)).toBeTruthy()
|
||||
expect(screen.getByText(/file-a/)).toBeTruthy()
|
||||
fireEvent.click(screen.getByRole('button', { name: '关闭详情' }))
|
||||
expect(closeDetails).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('shows the empty hint without a selection and the running state for open calls', () => {
|
||||
benchDetails({ runningCalls: [{ callId: 'c9', name: 'bash', argsRaw: '{}' }] }, null)
|
||||
expect(screen.getByText(/点击消息流中的工具行/)).toBeTruthy()
|
||||
cleanup()
|
||||
benchDetails({ runningCalls: [{ callId: 'c9', name: 'bash', argsRaw: '{}' }] }, { turnSeq: 1, callId: 'c9' })
|
||||
expect(screen.getByText('运行中…')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('reports an out-of-window call distinctly', () => {
|
||||
benchDetails({}, { turnSeq: 1, callId: 'ghost' })
|
||||
expect(screen.getByText(/不在当前窗口内/)).toBeTruthy()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* Tool-ring Entry typing (design §7): I inferred from the inject factory at
|
||||
* the register site, component must accept ToolViewProps & I, and the resolve
|
||||
* read face carries the erased-but-present inject. Compile-time checks via
|
||||
* @ts-expect-error pairs; the runtime assertions just keep vitest happy.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { FC } from 'react'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { ToolViewRegistry } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import type { ToolViewProps } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
|
||||
const sid = (s: string): SessionId => s as SessionId
|
||||
|
||||
// Positive control: component's own injected share matches the factory's product.
|
||||
interface RowInjected { useMyStore: () => number }
|
||||
const InjectedRowComp: FC<ToolViewProps & RowInjected> = () => null
|
||||
// Plain rows take the shared props only.
|
||||
const PlainRowComp: FC<ToolViewProps> = () => null
|
||||
|
||||
describe('tool-ring entry typing', () => {
|
||||
it('register infers I from the inject factory and accepts a matching component', () => {
|
||||
const reg = new ToolViewRegistry()
|
||||
const off = reg.register('bash', InjectedRowComp, {
|
||||
inject: () => ({ useMyStore: () => 1 }),
|
||||
})
|
||||
expect(reg.resolve('bash', sid('s'))?.inject).toBeDefined()
|
||||
off()
|
||||
})
|
||||
|
||||
it('injectless registration needs no options and resolves without inject', () => {
|
||||
const reg = new ToolViewRegistry()
|
||||
reg.register('read', PlainRowComp)
|
||||
expect('inject' in (reg.resolve('read', sid('s')) ?? {})).toBe(false)
|
||||
})
|
||||
|
||||
it('compile-time: factory product must cover the component injected share', () => {
|
||||
const reg = new ToolViewRegistry()
|
||||
reg.register('bash', InjectedRowComp, {
|
||||
// @ts-expect-error the factory misses useMyStore, which the component requires
|
||||
inject: () => ({ somethingElse: 1 }),
|
||||
})
|
||||
expect(true).toBe(true)
|
||||
})
|
||||
|
||||
// Known boundary (not asserted): a component demanding an injected share CAN
|
||||
// register bare — with I defaulting to `object`, FC<ToolViewProps & RowInjected>
|
||||
// is structurally assignable to FC<ToolViewProps & object> (parameter
|
||||
// bivariance over a wider props type). The register-site guarantee holds in
|
||||
// the direction that matters: WITH an inject factory, its product must cover
|
||||
// the component's share (previous case). The bare-register gap is the same
|
||||
// one SlotMap's single-kind register has and is accepted by design §7.
|
||||
|
||||
it('compile-time: scope filter receives the branded SessionId', () => {
|
||||
const reg = new ToolViewRegistry()
|
||||
reg.register('bash', PlainRowComp, {
|
||||
// @ts-expect-error number is not assignable to SessionId
|
||||
scope: (id: number) => id > 0,
|
||||
})
|
||||
expect(true).toBe(true)
|
||||
})
|
||||
})
|
||||
101
packages/client/ui-conversation/tests/toolview-registry.spec.ts
Normal file
101
packages/client/ui-conversation/tests/toolview-registry.spec.ts
Normal file
@@ -0,0 +1,101 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { ToolViewRegistry } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import type { ToolViewProps } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
|
||||
const sid = (s: string) => s as SessionId
|
||||
const comp = (name: string) => {
|
||||
const fc = () => null
|
||||
fc.displayName = name
|
||||
return fc as unknown as import('react').FC<ToolViewProps>
|
||||
}
|
||||
|
||||
describe('ToolViewRegistry', () => {
|
||||
it('resolves a global registration for any session', () => {
|
||||
const reg = new ToolViewRegistry()
|
||||
const bash = comp('Bash')
|
||||
reg.register('bash', bash)
|
||||
expect(reg.resolve('bash', sid('a'))?.component).toBe(bash)
|
||||
expect(reg.resolve('bash', sid('b'))?.component).toBe(bash)
|
||||
expect(reg.resolve('read', sid('a'))).toBeUndefined()
|
||||
})
|
||||
|
||||
it('prefers a matching scope filter over the global registration', () => {
|
||||
const reg = new ToolViewRegistry()
|
||||
const global = comp('Global')
|
||||
const swarm = comp('Swarm')
|
||||
reg.register('bash', global)
|
||||
reg.register('bash', swarm, { scope: id => id === sid('swarm-1') })
|
||||
expect(reg.resolve('bash', sid('swarm-1'))?.component).toBe(swarm)
|
||||
expect(reg.resolve('bash', sid('plain'))?.component).toBe(global)
|
||||
})
|
||||
|
||||
it('later registration wins within the same tier, scoped and global', () => {
|
||||
const reg = new ToolViewRegistry()
|
||||
const s1 = comp('S1')
|
||||
const s2 = comp('S2')
|
||||
const g1 = comp('G1')
|
||||
const g2 = comp('G2')
|
||||
reg.register('bash', g1)
|
||||
reg.register('bash', s1, { scope: () => true })
|
||||
reg.register('bash', s2, { scope: () => true })
|
||||
reg.register('bash', g2)
|
||||
expect(reg.resolve('bash', sid('x'))?.component).toBe(s2)
|
||||
const scopeless = new ToolViewRegistry()
|
||||
scopeless.register('bash', g1)
|
||||
scopeless.register('bash', g2)
|
||||
expect(scopeless.resolve('bash', sid('x'))?.component).toBe(g2)
|
||||
})
|
||||
|
||||
it('a non-matching scope filter falls through to global, then undefined', () => {
|
||||
const reg = new ToolViewRegistry()
|
||||
const scoped = comp('Scoped')
|
||||
reg.register('bash', scoped, { scope: () => false })
|
||||
expect(reg.resolve('bash', sid('x'))).toBeUndefined()
|
||||
const global = comp('Global')
|
||||
reg.register('bash', global)
|
||||
expect(reg.resolve('bash', sid('x'))?.component).toBe(global)
|
||||
})
|
||||
|
||||
it('disposer removes exactly its registration and is idempotent', () => {
|
||||
const reg = new ToolViewRegistry()
|
||||
const g = comp('G')
|
||||
const s = comp('S')
|
||||
const off = reg.register('bash', s, { scope: () => true })
|
||||
reg.register('bash', g)
|
||||
off()
|
||||
off()
|
||||
expect(reg.resolve('bash', sid('x'))?.component).toBe(g)
|
||||
})
|
||||
|
||||
it('unregistering the last entry resolves undefined (GenericToolCard fallback)', () => {
|
||||
const reg = new ToolViewRegistry()
|
||||
const off = reg.register('bash', comp('B'))
|
||||
off()
|
||||
expect(reg.resolve('bash', sid('x'))).toBeUndefined()
|
||||
})
|
||||
|
||||
it('carries the inject factory through resolve', () => {
|
||||
const reg = new ToolViewRegistry()
|
||||
const inject = () => ({})
|
||||
reg.register('bash', comp('B'), { inject })
|
||||
expect(reg.resolve('bash', sid('x'))?.inject).toBe(inject)
|
||||
reg.register('read', comp('R'))
|
||||
expect('inject' in reg.resolve('read', sid('x'))!).toBe(false)
|
||||
})
|
||||
|
||||
it('notifies subscribers and bumps the version on register and dispose', () => {
|
||||
const reg = new ToolViewRegistry()
|
||||
const fn = vi.fn()
|
||||
const unsub = reg.subscribe(fn)
|
||||
const v0 = reg.getVersion()
|
||||
const off = reg.register('bash', comp('B'))
|
||||
expect(fn).toHaveBeenCalledTimes(1)
|
||||
expect(reg.getVersion()).toBeGreaterThan(v0)
|
||||
off()
|
||||
expect(fn).toHaveBeenCalledTimes(2)
|
||||
unsub()
|
||||
reg.register('read', comp('R'))
|
||||
expect(fn).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,96 @@
|
||||
// Tool-ring type-chain samples (design §9 item 5, toolviews half): the
|
||||
// register→inject→resolve chain where `I` is inferred from the inject
|
||||
// factory and proved against the component at the register site, plus
|
||||
// expect-error duals. Tool names stay an open set (no per-tool props table —
|
||||
// design §7); the strong typing under test is Entry-internal. The known
|
||||
// bare-register variance edge (FC<Props & I> assignable to FC<Props & object>
|
||||
// without an inject factory) is accepted by design §7 and deliberately not
|
||||
// pinned here. Follows the slots-ring exemplar's shape.
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { FC, ReactNode } from 'react'
|
||||
import type { SessionBinding } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { ToolViewOptions, ToolViewProps } from '../src/client/contract/toolview.ts'
|
||||
import { ToolViewRegistry } from '../src/client/toolviews/registry.ts'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
|
||||
const sid = (s: string): SessionId => s as SessionId
|
||||
|
||||
/** Registrant's own injected share (locally declared — ownership rule). */
|
||||
interface RowInjected { useRuns: () => number; actions2: { rerun: () => void } }
|
||||
|
||||
const InjectedRow: FC<ToolViewProps & RowInjected> = () => null
|
||||
const PlainRow: FC<ToolViewProps> = () => null
|
||||
|
||||
describe('tool-ring type-chain negatives (compile-time; body never runs)', () => {
|
||||
it('holds the negative samples as expect-error sites', () => {
|
||||
const negatives = (registry: ToolViewRegistry) => {
|
||||
// 1. Inject factory under-produces the component's declared share:
|
||||
// I infers from the factory, and the component position then fails.
|
||||
registry.register(
|
||||
'bash',
|
||||
// @ts-expect-error component wants actions2, which the factory never produces
|
||||
InjectedRow,
|
||||
{ inject: () => ({ useRuns: () => 1 }) },
|
||||
)
|
||||
// 2. Inject factory produces a drifted value type for a declared key
|
||||
// (I infers from the component position here, so TS flags the factory).
|
||||
registry.register(
|
||||
'bash',
|
||||
InjectedRow,
|
||||
// @ts-expect-error useRuns returns string here, component wants number
|
||||
{ inject: () => ({ useRuns: () => 'one', actions2: { rerun: () => {} } }) },
|
||||
)
|
||||
// 3. Options object drifts: scope filter with a wrong parameter shape.
|
||||
const badScope: ToolViewOptions<RowInjected> = {
|
||||
// @ts-expect-error scope takes a SessionId, not a numeric index
|
||||
scope: (index: number) => index > 0,
|
||||
}
|
||||
void badScope
|
||||
// 4. Component demanding props outside ToolViewProps & I (a key neither
|
||||
// standard nor injected) cannot register even with a full factory.
|
||||
const Overreaching: FC<ToolViewProps & RowInjected & { fromNowhere: boolean }> = () => null
|
||||
registry.register(
|
||||
'bash',
|
||||
// @ts-expect-error fromNowhere is neither a standard prop nor produced by the factory
|
||||
Overreaching,
|
||||
{ inject: (): RowInjected => ({ useRuns: () => 1, actions2: { rerun: () => {} } }) },
|
||||
)
|
||||
return null as ReactNode
|
||||
}
|
||||
expect(negatives).toBeTypeOf('function')
|
||||
})
|
||||
})
|
||||
|
||||
describe('tool-ring full chain (positive dual)', () => {
|
||||
it('registers with an inferred inject share, resolves by scope order, and reads the erased face back', () => {
|
||||
const registry = new ToolViewRegistry()
|
||||
// Registration: I inferred from the factory, component proved ⊇ ToolViewProps & I.
|
||||
const disposeGlobal = registry.register('bash', InjectedRow, {
|
||||
inject: (b: SessionBinding): RowInjected => ({
|
||||
useRuns: () => b.sessionId.length,
|
||||
actions2: { rerun: () => {} },
|
||||
}),
|
||||
})
|
||||
const disposeScoped = registry.register('bash', PlainRow, {
|
||||
scope: id => id === sid('swarm-1'),
|
||||
})
|
||||
|
||||
// Resolve: scope match beats global; elsewhere the global row wins.
|
||||
expect(registry.resolve('bash', sid('swarm-1'))?.component).toBe(PlainRow)
|
||||
const global = registry.resolve('bash', sid('other'))
|
||||
expect(global?.component).toBe(InjectedRow)
|
||||
// Read face: I is erased to object, the factory reference survives; the
|
||||
// outlet-side restoration is the budgeted cast (same boundary as slots).
|
||||
const injected = (global?.inject as (b: SessionBinding) => RowInjected)(
|
||||
{ sessionId: 'ab', session: { useSelector: undefined }, ctx: undefined },
|
||||
)
|
||||
expect(injected.useRuns()).toBe(2)
|
||||
// Unknown tool → undefined (caller falls back to the generic card).
|
||||
expect(registry.resolve('ghost-tool', sid('other'))).toBeUndefined()
|
||||
|
||||
disposeScoped()
|
||||
expect(registry.resolve('bash', sid('swarm-1'))?.component).toBe(InjectedRow)
|
||||
disposeGlobal()
|
||||
expect(registry.resolve('bash', sid('other'))).toBeUndefined()
|
||||
})
|
||||
})
|
||||
100
packages/client/ui-conversation/tests/views-type-chain.spec.tsx
Normal file
100
packages/client/ui-conversation/tests/views-type-chain.spec.tsx
Normal file
@@ -0,0 +1,100 @@
|
||||
// View-ring type-chain samples (design §9 item 5, views half): the
|
||||
// register→inject→render chain composed through ConversationViewMap's
|
||||
// per-view extension shapes, plus expect-error duals for each stage.
|
||||
// Follows the slots-ring exemplar (ui-slots/tests/type-chain.spec.tsx):
|
||||
// negatives live in a never-executed function body; the positive dual runs
|
||||
// the real ConversationService view registry.
|
||||
import { Context } from 'cordis'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { FC, ReactNode } from 'react'
|
||||
import type {
|
||||
ChromePropsOf, ConvViewProps, ConvViewPropsOf, ViewEntry,
|
||||
} from '../src/client/contract/views.ts'
|
||||
import { ConversationService } from '../src/client/service.ts'
|
||||
|
||||
// Test-only view keys with distinct extension shapes (merged like
|
||||
// ui-trajectory does; extension fields are optional per ViewEntryDef).
|
||||
declare module '../src/client/contract/views.ts' {
|
||||
interface ConversationViewMap {
|
||||
'vt-extended': { chromeProps: { statLabel: string }; extraProps: { density: 'compact' | 'wide' } }
|
||||
'vt-plain': object
|
||||
}
|
||||
}
|
||||
|
||||
const ExtendedView: FC<ConvViewPropsOf<'vt-extended'>> = ({ density }) => (density === 'compact' ? null : null)
|
||||
const ExtendedChrome: FC<ChromePropsOf<'vt-extended'>> = ({ statLabel }) => (statLabel === '' ? null : null)
|
||||
const PlainView: FC<ConvViewPropsOf<'vt-plain'>> = () => null
|
||||
|
||||
describe('view-ring type-chain negatives (compile-time; body never runs)', () => {
|
||||
it('holds the negative samples as expect-error sites', () => {
|
||||
const negatives = (service: ConversationService) => {
|
||||
// 1. Registration: a component missing the entry's declared extraProps
|
||||
// cannot register under that id (props flow from the map entry).
|
||||
const NarrowComp: FC<ConvViewProps & { density: number }> = () => null
|
||||
service.registerView({
|
||||
id: 'vt-extended',
|
||||
label: 'x',
|
||||
// @ts-expect-error density has the wrong value type vs the map entry's extraProps
|
||||
component: NarrowComp,
|
||||
})
|
||||
// 2. Registration: chrome typed for another view's chromeProps drifts.
|
||||
service.registerView({
|
||||
id: 'vt-plain',
|
||||
label: 'x',
|
||||
component: PlainView,
|
||||
// @ts-expect-error vt-plain declares no statLabel chromeProps
|
||||
chrome: { footer: ExtendedChrome },
|
||||
})
|
||||
// 3. Registration: id outside the map is rejected at the entry.
|
||||
service.registerView({
|
||||
// @ts-expect-error unregistered view id
|
||||
id: 'vt-ghost',
|
||||
label: 'x',
|
||||
component: PlainView,
|
||||
})
|
||||
// 4. Render side: per-view props narrow — the extended view's density
|
||||
// is not accessible under another id's props type.
|
||||
const renderPlain = (props: ConvViewPropsOf<'vt-plain'>): ReactNode => {
|
||||
// @ts-expect-error density belongs to vt-extended's extension, not vt-plain
|
||||
return props.density === 'compact' ? null : null
|
||||
}
|
||||
void renderPlain
|
||||
// 5. Entry-shape drift: ViewEntry<Id> ties chrome and component to the
|
||||
// SAME id — mixing ids inside one entry fails.
|
||||
const mixed: ViewEntry<'vt-extended'> = {
|
||||
id: 'vt-extended',
|
||||
label: 'x',
|
||||
component: ExtendedView,
|
||||
// @ts-expect-error chrome for vt-plain cannot ride a vt-extended entry
|
||||
chrome: { header: (props: ChromePropsOf<'vt-plain'> & { onlyPlain: true }) => null },
|
||||
}
|
||||
void mixed
|
||||
return null as ReactNode
|
||||
}
|
||||
expect(negatives).toBeTypeOf('function')
|
||||
})
|
||||
})
|
||||
|
||||
describe('view-ring full chain (positive dual)', () => {
|
||||
it('registers, lists, and renders through the per-view extension shapes', () => {
|
||||
const ctx = new Context()
|
||||
const service = new ConversationService(ctx)
|
||||
// Registration: extension-typed component + same-id chrome compose cleanly.
|
||||
const dispose = service.registerView({
|
||||
id: 'vt-extended',
|
||||
label: '扩展视图',
|
||||
order: 7,
|
||||
component: ExtendedView,
|
||||
chrome: { footer: ExtendedChrome },
|
||||
})
|
||||
const entry = service.views().find(v => v.id === 'vt-extended')
|
||||
expect(entry?.label).toBe('扩展视图')
|
||||
// Render surface: the listed entry's component accepts the composed props
|
||||
// (base ConvViewProps + the map extension), spelled here as the same type
|
||||
// the runtime hands over.
|
||||
expect(typeof entry?.component).toBe('function')
|
||||
expect(typeof entry?.chrome?.footer).toBe('function')
|
||||
dispose()
|
||||
expect(service.views().some(v => v.id === 'vt-extended')).toBe(false)
|
||||
})
|
||||
})
|
||||
46
packages/client/ui-conversation/tsconfig.json
Normal file
46
packages/client/ui-conversation/tsconfig.json
Normal file
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"extends": "../../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "lib/types",
|
||||
"jsx": "react-jsx",
|
||||
"lib": [
|
||||
"ES2024",
|
||||
"DOM",
|
||||
"DOM.Iterable"
|
||||
],
|
||||
"types": []
|
||||
},
|
||||
"include": [
|
||||
"src"
|
||||
],
|
||||
"references": [
|
||||
{
|
||||
"path": "../../../vendor/cordis"
|
||||
},
|
||||
{
|
||||
"path": "../ui-slots"
|
||||
},
|
||||
{
|
||||
"path": "../ui-primitives"
|
||||
},
|
||||
{
|
||||
"path": "../web-react"
|
||||
},
|
||||
{
|
||||
"path": "../runtime"
|
||||
},
|
||||
{
|
||||
"path": "../ui-layout"
|
||||
},
|
||||
{
|
||||
"path": "../i18n"
|
||||
},
|
||||
{
|
||||
"path": "../../support/invariants"
|
||||
}
|
||||
],
|
||||
"exclude": [
|
||||
"**/*.legacy.*"
|
||||
]
|
||||
}
|
||||
3
packages/client/ui-conversation/tsdown.config.ts
Normal file
3
packages/client/ui-conversation/tsdown.config.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import { clientBundle } from '../tsdown.client.ts'
|
||||
|
||||
export default clientBundle('@deepseek-ai/dsh-client-ui-conversation', ['lib/types/index.js', 'lib/types/invariant.js'])
|
||||
Reference in New Issue
Block a user