Files
apes-sidebar/src/client/tasks-shared.tsx
T
Menghuan1918 9ccc147e00 feat(tasks): 第二轮真机反馈——聚合条动作行、模式 chip、弹窗用量/耗时、原生侧栏转录、动效
用户在自己跑的 3080 实例上测完报回六条,逐条修:

1. 「已完成的聚合卡下方空荡荡」= 上一轮把计数收进徽标后那条只剩一个
   chevron(我的取舍造成)。小条改为动作行:组图标 + 「展开」(新词条
   tasksFoldExpandShort × 20 词典)+ 出错尾注 + 展开箭头。
2. 「展开后的子代理点不回去」= 真缺陷:expandedGroups 压过了 foldedIds,
   展开组内卡片的 chevron 失效。改成手动折叠优先(手动 → 页级规则 →
   组展开),补模型 + 组件两层判别性用例。
3. 「一次性一直显示」→ 模式词搬进徽标行成 chip(用户口径)。智能体卡不再
   有 mono 元信息行,卡片高度预算拆成 GRAPH_AGENT_NODE_H / GRAPH_NODE_H
   (只有 workflow run 卡保留元信息行),rowStrideFor(nodes) 按模型里有没有
   run 选行距。
4. 动效:接入 @formkit/auto-animate(用户选定,~3KB、无依赖无安装脚本)+
   useAutoAnimateRef 包装(WAAPI 守卫 → jsdom 空转、尊重 reduced-motion),
   挂到画布卡片层 / 树视图 / 任务抽屉;详情卡另加 140ms 入场关键帧。核心
   bundle +56KB(未压缩 CJS)。
5. 弹窗多两项:Token 用量(宿主 tokenUsage 四桶求和,悬停给明细)+ 耗时
   (宿主 subagentTiming,按 3s 轮询刷新)。SidebarProjectionSnapshot 镜像
   补两个键、模型新增 metrics 入参;**按存在性渲染**,没有测量就不显示这一
   行(0 是投影初始态,与「没工作过」不可区分)。
6. 「查看转录」改为在原生右侧栏打开:宿主 ui-subagent 的 subagentchat tab
   类型(宿主自己的子代理列表就是点行=主窗、点 chevron=侧栏)。插件照抄其
   地址公式并调 openResource(..., { kind, preferNewPane: true }),三级降级回
   主窗;页脚变「主按钮 + caret 菜单(在主窗口中打开)」。

测试 2238 passed / 17 skipped(191 文件)、tsc 0 错误、eslint 0 错误、构建
通过;新构建已装进 sidebar-test profile,:3080 上挂载正常、0 pageerror。
动效观感与真实数据的两行数值未在真机逐帧核验(右栏在无头上下文里被
transform 移出视口,合成点击不稳)——已如实记进设计文档的第二轮偏差段。
2026-10-11 23:15:40 +08:00

376 lines
15 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Shared presentation bits of the Tasks page's two modes (graph + tree):
* the state dot, the agent/workflow/task GLYPHS (host primitive icons — the
* page draws no glyphs of its own), the short mono meta line, the node task
* line, and the iconified live activity row ("activity glyph + wording").
*
* Card content contract (the page's answer to "everything is ellipsized"):
* line 1 state dot + agent icon + name (11px semibold, one line)
* line 2 mode/model · activity (9px mono, one line)
* line 3 live activity line (running nodes only)
* line 4 owned shared task (team members only)
* Everything else lives in the popovers.
*
* {@link activityLine} is the ONE rule that resolves a node's merged activity
* wording: the card's bottom bar and the node detail popover both read it, so
* the two surfaces can never disagree about what a node is doing.
*/
import type { ReactNode } from 'react'
import {
IconAgentPresetOutlineRegular, IconBranchOutlineRegular, IconChecklistOutlineRegular, IconUserOutlineRegular,
type StateDotState,
} from '@deepseek-ai/dsh-client-ui-primitives'
import type { SidebarChildLiveView } from '../context-types.ts'
import { doneActivityTitle, liveActivityLabel } from './process-labels.ts'
import type {
TasksAgentNode, TasksFoldNode, TasksNodeState, TasksNodeTask, TasksWorkflowNode,
} from './tasks-model.ts'
import { activityGlyph } from './activity-icons.tsx'
import { t, type CopyKey } from './locales.ts'
import css from './tasks-graph.module.css'
/** Preview cap of one tool-call argument line. */
const ARGS_PREVIEW = 48
/** Preview cap of one text line. */
const TEXT_PREVIEW = 72
/** The host StateDot semantic of a node display state. */
export function nodeDotState(state: TasksNodeState): StateDotState {
switch (state) {
case 'running': return 'ongoing'
case 'idle': return 'idle'
case 'done': return 'done'
case 'error': return 'error'
}
}
/** The short state word of a node (the meta line's second token). */
export function stateLabel(state: TasksNodeState): string {
const key: CopyKey = state === 'running'
? 'tasksStateRunning'
: state === 'idle'
? 'subagentInactive'
: state === 'error' ? 'tasksStateError' : 'tasksStateDone'
return t(key)
}
/**
* The merged activity line of one agent node — the ONE rule both surfaces
* read (the card's bottom bar and the node detail popover).
*
* - a RUNNING node shows the host's own live wording for its newest range
* ("正在读取文件 · main.ts"), which is what the main conversation shows for
* the same work;
* - a settled one shows the same summary in its completed form (the host's
* `done.*` phrasing) — running wording on a finished node would claim it is
* analysing something it already answered;
* - a node the live channel carries NO summary for answers undefined, and the
* callers fall back to the state word. That case must stay distinguishable:
* the host's `thinking` wording is what a range with nothing dispatched
* reads as, not what "we know nothing about this node" reads as.
*/
export function activityLine(node: TasksAgentNode): string | undefined {
const summary = node.live?.summary
if (summary === undefined) return undefined
return node.state === 'running' ? liveActivityLabel(summary) : doneActivityTitle(summary)
}
/**
* The two facts every task display rule reads. Deliberately NARROWER than
* either carrier (`TasksNodeTask` on the graph, `SidebarTeamTaskView` in the
* board and the task window) so one rule serves all of them — the window sees
* a `deleted` status the graph never draws, and only the shared rule needs to
* know that a deleted task is not "blocked".
*/
export interface TaskStatusFacts {
status: 'pending' | 'in_progress' | 'completed' | 'deleted'
ready: boolean
}
/** The task status label key. */
export function taskStatusKey(status: TaskStatusFacts['status']): CopyKey {
switch (status) {
case 'pending': return 'teamTaskPending'
case 'in_progress': return 'teamTaskInProgress'
case 'completed': return 'teamTaskCompleted'
case 'deleted': return 'teamTaskDeleted'
}
}
/**
* Whether a shared task is HELD UP by its blockers.
*
* The service's `ready` flag means exactly one thing: "a pending task whose
* every blocker completed, so it can be CLAIMED". It is therefore false for
* every task that is not queued — which makes `!ready` the wrong test for
* "blocked": a claimed task (in_progress) and a finished one both report
* `ready: false`, and reading the flag alone labelled a task that is actively
* being worked on as 阻塞 (reproduced on the real board: claiming a task made
* its Tag flip from 待办 to 阻塞).
*/
export function taskBlocked(task: TaskStatusFacts): boolean {
return task.status === 'pending' && !task.ready
}
/** The status word of a task row: its own status, or 阻塞 when held up. */
export function taskStatusLabel(task: TaskStatusFacts): string {
return t(taskBlocked(task) ? 'teamTaskBlocked' : taskStatusKey(task.status))
}
/** The tone of a task's status Tag (or dot) — the same three-way rule. */
export function taskTone(task: TaskStatusFacts): 'success' | 'info' | 'warning' {
if (task.status === 'completed') return 'success'
return taskBlocked(task) ? 'warning' : 'info'
}
/** The host StateDot semantic of a task row/line. */
export function taskDotState(task: TaskStatusFacts): StateDotState {
if (task.status === 'completed') return 'done'
return taskBlocked(task) ? 'warning' : 'ongoing'
}
/** First `limit` characters with an ellipsis when truncated. */
export function preview(text: string, limit: number = ARGS_PREVIEW): string {
return text.length > limit ? `${text.slice(0, limit)}…` : text
}
/** Collapse whitespace for single-line previews. */
export function flatten(text: string): string {
return text.replace(/\s+/g, ' ').trim()
}
/** The host icon of one agent node (the lead and plain children share one). */
export function AgentGlyph(props: { node: TasksAgentNode; size?: number }): ReactNode {
const size = props.size ?? 11
if (props.node.team?.role === 'teammate') return <IconUserOutlineRegular size={size} />
return <IconAgentPresetOutlineRegular size={size} />
}
/** The workflow-run glyph. */
export function WorkflowGlyph(props: { size?: number }): ReactNode {
return <IconBranchOutlineRegular size={props.size ?? 11} />
}
/** The fold aggregate glyph. */
export function FoldGlyph(props: { size?: number }): ReactNode {
return <IconChecklistOutlineRegular size={props.size ?? 11} />
}
/**
* The mode word of one catalog row, or undefined when it names no mode. DSH
* 0.1.7 added `unknown` (a child the host's catalog fold kept without a
* readable descriptor): it claims NEITHER mode, so the segment is omitted
* rather than mislabelled.
*/
export function modeLabel(mode: TasksAgentNode['mode']): string | undefined {
switch (mode) {
case 'one-shot': return t('subagentModeOneShot')
case 'continuable': return t('subagentModeContinuable')
case 'unknown':
case undefined: return undefined
}
}
/**
* The mono meta line of an agent card — at most two short tokens:
* - the topology root: 主代理 · 状态
* - any other agent: 模式 · 状态 (a teammate without a catalog mode falls back
* to its team role, the one durable identity the roster still carries — the
* `agentTeam` projection has no model field to print, see team-projection.ts)
*/
export function agentMeta(node: TasksAgentNode): string {
const state = stateLabel(node.state)
if (node.parentId === undefined) return `${t('subagentMainAgent')} · ${state}`
const mode = modeLabel(node.mode)
if (mode !== undefined) return `${mode} · ${state}`
const fallback = node.team === undefined ? undefined : teamRoleLabel(node.team)
return fallback === undefined ? state : `${fallback} · ${state}`
}
/**
* The identity CHIP of an agent card: the word that rides BESIDE the kind badge
* (一次性 / 可持续), or the one team state the badge cannot express (准备中 /
* 出错).
*
* It is a chip and not a line of its own because the mode is the same word on
* every card of its kind: as a mono meta line it cost a 16px row to repeat
* itself, and the reader's report was exactly "模型一次性的子代理一直显示一次性".
* A plain teammate answers undefined — the badge already reads 成员 — and the
* root answers undefined too (its badge reads 主代理).
*
* The state stays out of it: the card's bottom bar carries it (its dot, and its
* word whenever no activity line takes that place), and the accessible name
* keeps {@link agentMeta} with the state included, because a screen reader
* never sees the bar's dot.
*/
export function agentChip(node: TasksAgentNode): string | undefined {
if (node.parentId === undefined) return undefined
const mode = modeLabel(node.mode)
if (mode !== undefined) return mode
if (node.team === undefined) return undefined
if (node.team.phase === 'provisioning') return t('tasksStateProvisioning')
if (node.team.phase === 'failed') return t('tasksStateError')
return undefined
}
/** The roster row's own identity word (the fallback for a modelless teammate). */
function teamRoleLabel(team: NonNullable<TasksAgentNode['team']>): string | undefined {
if (team.role === 'lead') return undefined
if (team.phase === 'provisioning') return t('tasksStateProvisioning')
if (team.phase === 'failed') return t('tasksStateError')
return t('tasksKindTeammate')
}
/** The mono meta line of a workflow run card: status · member tally. */
export function workflowMeta(node: TasksWorkflowNode): string {
const { run } = node
let done = 0
let total = 0
for (const phase of run.phases) {
for (const member of phase.members) {
total += 1
if (member.outcome !== undefined) done += 1
}
}
return `${t(workflowStatusKey(run.status))} · ${t('workflowMembers', { done, total })}`
}
/** The workflow run status label key. */
export function workflowStatusKey(status: TasksWorkflowNode['run']['status']): CopyKey {
switch (status) {
case 'running': return 'workflowRunning'
case 'completed': return 'workflowCompleted'
case 'cancelled': return 'workflowCancelled'
case 'failed': return 'workflowFailed'
}
}
/** The task a node surfaces first: in-progress, else pending, else the last. */
export function primaryTask(tasks: readonly TasksNodeTask[]): TasksNodeTask | undefined {
return tasks.find(task => task.status === 'in_progress')
?? tasks.find(task => task.status === 'pending')
?? tasks[tasks.length - 1]
}
/**
* The node's shared-task line: an icon, the primary task's subject, its
* status word, and a `+N` tail when the agent owns more. Renders nothing
* without tasks, so non-team nodes keep the three-line shape.
*/
export function TaskLine(props: {
tasks: readonly TasksNodeTask[] | undefined
onOpenTask(taskId: string, anchor: HTMLElement): void
}): ReactNode {
const tasks = props.tasks ?? []
const primary = primaryTask(tasks)
if (primary === undefined) return null
return (
<span
role="button"
tabIndex={0}
className={css.taskLine}
title={tasks.map(task => `${task.subject}(${t(taskStatusKey(task.status))})`).join('\n')}
onClick={(event) => {
event.stopPropagation()
props.onOpenTask(primary.id, event.currentTarget)
}}
onKeyDown={(event) => {
if (event.key !== 'Enter' && event.key !== ' ') return
event.preventDefault()
event.stopPropagation()
props.onOpenTask(primary.id, event.currentTarget)
}}
>
<span className={css.taskGlyph} aria-hidden="true"><IconChecklistOutlineRegular size={9} /></span>
<span className={css.taskSubject}>{primary.subject}</span>
<span className={css.taskState}>{t(taskStatusKey(primary.status))}</span>
{tasks.length > 1 && <span className={css.taskMore}>{`+${tasks.length - 1}`}</span>}
</span>
)
}
/**
* The live activity row of a RUNNING agent: the merged process summary the
* main conversation would show for the child's newest range (category wording
* + the running call's detail), plus the flattened last text line underneath.
* A running node with neither reads as thinking.
*
* The glyph follows the summary's own CATEGORY (the host's `ProcessActivity`),
* so "正在读取文件" is prefixed by the read family and "正在运行命令" by the
* command one — one fixed glyph made every row claim to be a shell command.
*/
export function LiveLine(props: { live: SidebarChildLiveView | undefined }): ReactNode {
const { live } = props
const activity = liveActivityLabel(live?.summary)
if (activity === undefined && live?.text === undefined) {
return <span className={css.nodeMeta}>{t('subagentThinking')}</span>
}
return (
<>
{activity !== undefined && (
<span className={css.live}>
<span className={css.liveGlyph} aria-hidden="true">
{activityGlyph(live?.summary?.running)(9)}
</span>
<span className={css.liveTool} title={activity}>{activity}</span>
</span>
)}
{live?.text !== undefined && (
<span className={css.liveText}>{preview(flatten(live.text), TEXT_PREVIEW)}</span>
)}
</>
)
}
/**
* The fold aggregate's name line: two label previews, plus `+N` when the group
* holds more.
*
* A roster aggregate can swallow dozens of members, and the card has one line
* for them. Naming two and saying how many are left over is what keeps that
* line honest at any size — the exact `+N` the team task line already uses,
* not a second convention. The group's total is also on the badge, so `+N` is
* a tail, never the only count.
*
* @param previews - member labels, in page order (see {@link TasksFoldNode.previews}).
* @param count - how many members the group holds in total.
*/
export function foldPreviews(previews: readonly string[], count: number): string {
const tail = count > previews.length ? ` +${count - previews.length}` : ''
return `${previews.join(' / ')}${tail}`
}
/**
* The fold aggregate's failures, as its own line: `出错 N`, or undefined when
* the group has none. The `done` row's bottom bar prints exactly this and
* nothing else, because the badge above it already carries the count
* (`✓ N 已完成`) — the same number twice on a 190px card was one of them
* saying it again.
*/
export function foldErrorTally(node: TasksFoldNode): string | undefined {
return node.errorCount > 0 ? `${t('tasksStateError')} ${node.errorCount}` : undefined
}
/**
* The fold aggregate's full tally (its accessible name and tooltip).
*
* The two groups read differently on purpose. The `done` row counts its
* finished members and calls out failures beside them (`✓ 4 已完成 · 出错 1`
* — a row of nothing but failures is `出错 N`), because "✓ N 已完成" alone
* would quietly include them. The `idle` row says what the members are doing
* now: nothing (`N 待命`), which is why they were swept away.
*
* The VISIBLE surfaces split this differently: the graph card's badge carries
* the count and its bar carries {@link foldErrorTally}, so the tally's count
* half is printed once. This full string stays the accessible name — a screen
* reader never sees the badge.
*/
export function foldTally(node: TasksFoldNode): string {
if (node.foldKind === 'idle') return t('tasksFoldIdle', { count: node.count })
const parts: string[] = []
if (node.doneCount > 0) parts.push(t('tasksFoldCompleted', { count: node.doneCount }))
const errors = foldErrorTally(node)
if (errors !== undefined) parts.push(errors)
return parts.join(' · ')
}