From 261f4704113baea0cd5817ea538413ed3a3e7473 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Thu, 5 Nov 2026 19:25:15 +0800 Subject: [PATCH 01/66] feat(web): move background jobs and subagents into the Session panel --- .../ui-agent-team/src/client/TeamBoard.tsx | 2 +- .../client/ui-agent-team/src/client/mount.ts | 4 +- .../tests/browser-plugin.client.spec.ts | 6 +- packages/client/ui-jobs/package.json | 8 +- ...tion.module.css => JobsSection.module.css} | 172 +- .../{JobListAction.tsx => JobsSection.tsx} | 276 +-- packages/client/ui-jobs/src/client/index.ts | 33 +- packages/client/ui-jobs/src/client/locales.ts | 24 - .../tests/browser-plugin.client.spec.ts | 28 +- .../tests/job-list-action.client.spec.tsx | 950 --------- .../tests/jobs-section.client.spec.tsx | 465 +++++ packages/client/ui-jobs/tsconfig.json | 12 +- packages/client/ui-subagent/package.json | 26 +- ....module.css => SubagentCatalog.module.css} | 120 +- .../src/client/SubagentCatalog.tsx | 559 ++++++ .../src/client/SubagentHeaderLineage.tsx | 919 ++------- .../src/client/SubagentsSection.tsx | 94 + .../client/ui-subagent/src/client/index.ts | 46 +- .../client/ui-subagent/src/client/locales.ts | 32 - .../client/ui-subagent/src/client/slots.ts | 7 +- .../tests/browser-plugin.client.spec.ts | 35 +- .../tests/conversation-ui.client.spec.tsx | 1725 ++++++----------- packages/client/ui-subagent/tsconfig.json | 33 +- pnpm-lock.yaml | 9 +- 24 files changed, 2081 insertions(+), 3504 deletions(-) rename packages/client/ui-jobs/src/client/{JobListAction.module.css => JobsSection.module.css} (67%) rename packages/client/ui-jobs/src/client/{JobListAction.tsx => JobsSection.tsx} (60%) delete mode 100644 packages/client/ui-jobs/tests/job-list-action.client.spec.tsx create mode 100644 packages/client/ui-jobs/tests/jobs-section.client.spec.tsx rename packages/client/ui-subagent/src/client/{SubagentHeaderLineage.module.css => SubagentCatalog.module.css} (81%) create mode 100644 packages/client/ui-subagent/src/client/SubagentCatalog.tsx create mode 100644 packages/client/ui-subagent/src/client/SubagentsSection.tsx diff --git a/packages/client/ui-agent-team/src/client/TeamBoard.tsx b/packages/client/ui-agent-team/src/client/TeamBoard.tsx index d6d0538fa9..42d687d854 100644 --- a/packages/client/ui-agent-team/src/client/TeamBoard.tsx +++ b/packages/client/ui-agent-team/src/client/TeamBoard.tsx @@ -14,7 +14,7 @@ import css from './TeamBoard.module.css' /** Full props of the task board below the shared subagent catalog. */ export type TeamBoardProps = - PropsRuntime<'conversation.session.header.actions.subagent.footer'> & PropsLocale + PropsRuntime<'conversation.session.panel.subagents.footer'> & PropsLocale type VisibleTask = TeamTaskView & { status: Exclude } diff --git a/packages/client/ui-agent-team/src/client/mount.ts b/packages/client/ui-agent-team/src/client/mount.ts index 833267e39e..6a899617ec 100644 --- a/packages/client/ui-agent-team/src/client/mount.ts +++ b/packages/client/ui-agent-team/src/client/mount.ts @@ -65,7 +65,7 @@ export function registerAgentTeamUi(ctx: ClientContext): void { }, TeamModeToggle)) }) }) - ctx.slots.inject('conversation.session.header.actions.subagent.footer', () => ctx.slots.register({ - name: 'conversation.session.header.actions.subagent.footer', id: 'agent-team', locale: NS, + ctx.slots.inject('conversation.session.panel.subagents.footer', () => ctx.slots.register({ + name: 'conversation.session.panel.subagents.footer', id: 'agent-team', locale: NS, }, TeamBoard)) } diff --git a/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts b/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts index ba964a033f..688ef0ebcc 100644 --- a/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts @@ -19,14 +19,14 @@ async function bench() { const collapseHeader = ctx.slots.register({ name: 'root', children: { - 'conversation.session.header.actions.subagent.footer': { kind: 'list', scope: 'session' }, + 'conversation.session.panel.subagents.footer': { kind: 'list', scope: 'session' }, 'conversation.input.model': { kind: 'single', scope: 'session' }, 'shell.overlay': { kind: 'list', scope: 'root' }, }, } as never, () => null) const fiber = ctx.plugin({ inject: [...inject], apply }) await fiber.await() - const entry = () => ctx.slots.entries('conversation.session.header.actions.subagent.footer') + const entry = () => ctx.slots.entries('conversation.session.panel.subagents.footer') .find(candidate => candidate.component === TeamBoard) return { ctx, fiber, entry, collapseHeader } } @@ -55,7 +55,7 @@ describe('task-board browser plugin', () => { expect(b.entry()).toBeUndefined() b.ctx.slots.register({ name: 'root', - children: { 'conversation.session.header.actions.subagent.footer': { kind: 'list', scope: 'session' } }, + children: { 'conversation.session.panel.subagents.footer': { kind: 'list', scope: 'session' } }, } as never, () => null) await Promise.resolve() expect(b.entry()).toBeDefined() diff --git a/packages/client/ui-jobs/package.json b/packages/client/ui-jobs/package.json index 2c8943e4c7..3c50087660 100644 --- a/packages/client/ui-jobs/package.json +++ b/packages/client/ui-jobs/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-client-ui-jobs", - "description": "Session-header background-job list with on-demand streaming record panels", + "description": "Session panel background-job list with on-demand streaming record panels", "version": "0.2.2-rc.1", "type": "module", "main": "lib/index.js", @@ -39,10 +39,10 @@ "@deepseek-ai/dsh-api-job-controller": "workspace:*", "@deepseek-ai/dsh-client-locale": "workspace:*", "@deepseek-ai/dsh-client-test-runtime": "workspace:*", - "@deepseek-ai/dsh-client-ui-conversation": "workspace:*", "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-session": "workspace:*", + "@deepseek-ai/dsh-client-ui-session-panel": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-jobs": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", @@ -63,8 +63,8 @@ "inject": [ "@deepseek-ai/dsh-api-job-controller", "@deepseek-ai/dsh-client-locale", - "@deepseek-ai/dsh-client-ui-conversation", - "@deepseek-ai/dsh-client-ui-primitives" + "@deepseek-ai/dsh-client-ui-primitives", + "@deepseek-ai/dsh-client-ui-session-panel" ], "platform": "web" } diff --git a/packages/client/ui-jobs/src/client/JobListAction.module.css b/packages/client/ui-jobs/src/client/JobsSection.module.css similarity index 67% rename from packages/client/ui-jobs/src/client/JobListAction.module.css rename to packages/client/ui-jobs/src/client/JobsSection.module.css index 6b72ce3241..333bb482f1 100644 --- a/packages/client/ui-jobs/src/client/JobListAction.module.css +++ b/packages/client/ui-jobs/src/client/JobsSection.module.css @@ -1,121 +1,10 @@ -.trigger { - display: inline-flex; - align-items: center; - gap: 4px; - min-height: 28px; - padding: 3px 2px; - border: 0; - border-radius: var(--dsw-radius-sm); - background: transparent; - color: var(--dsw-alias-label-tertiary); - font-size: 12px; - line-height: 18px; - cursor: pointer; -} - -.trigger:focus-visible { - color: var(--dsw-alias-label-secondary); -} - -@media (hover: hover) { - .trigger:hover { - color: var(--dsw-alias-label-secondary); - } -} - -.activitySlot { - display: inline-flex; - flex: none; - align-items: center; - justify-content: center; - width: 14px; - height: 14px; -} - -.trigger .compactIcon { - display: none; -} - -@container (max-width: 460px) { - .trigger .compactIcon { - display: block; - } - - .trigger .textModeActivity { - display: none; - } - - .trigger .count { - display: none; - } - - .trigger { - box-sizing: border-box; - width: 28px; - height: 28px; - padding: 0; - justify-content: center; - color: var(--dsw-alias-label-secondary); - } - - .trigger .activitySlot, - .trigger .activitySlot > svg { - width: 15px; - height: 15px; - } - - .trigger:focus-visible { - color: var(--dsw-alias-label-secondary); - } - - .trigger:active { - background: var(--dsw-alias-interactive-bg-active); - } - - @media (hover: hover) { - .trigger:hover { - color: var(--dsw-alias-label-secondary); - background: var(--dsw-alias-interactive-bg-hover); - } - } -} - -/* Portaled above the right sidebar (at most 40) and below modal overlays (1000). */ -.menu { - position: fixed; - z-index: 100; - box-sizing: border-box; - display: flex; - flex-direction: column; - width: 500px; - max-width: min(560px, calc(100vw - 32px)); - max-height: min(480px, calc(100dvh - 140px)); - overflow: hidden; - --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2); - --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2); - --dsw-elevation-stroke-color: var(--dsw-alias-border-l1); - box-shadow: var(--dsw-elevation-prominent); - position-area: none; - top: max(12px, calc(anchor(bottom) + 5px)); - bottom: 12px; - left: max(12px, anchor(left)); - right: 12px; - position-try-fallbacks: --dsh-jobs-window, --dsh-jobs-opposite, --dsh-jobs-wide-opposite, --dsh-jobs-tall, --dsh-jobs-viewport; - align-self: start; - justify-self: start; - height: fit-content; - min-height: 0; - margin: 0; -} - -.menuBody { +/* Rows sit inside the Session panel section body, which supplies the inset and scrolling. */ +.list { display: flex; flex-direction: column; gap: 1px; - min-height: 0; margin: 0; - padding: 4px; - overflow: auto; + padding: 0; list-style: none; } @@ -205,9 +94,9 @@ } } -/* The kind badge shares the card fill, so it pops on the menu surface instead. */ +/* The kind badge shares the card fill, so it pops on the panel surface instead. */ .rowLineLive .kind { - background: var(--dsw-specific-menu); + background: var(--dsw-alias-bg-layer-1); } .rowLine .row { @@ -243,7 +132,7 @@ height: 20px; border: 0.5px solid var(--dsw-alias-border-l2); border-radius: var(--dsw-radius-sm); - background: var(--dsw-specific-menu); + background: var(--dsw-alias-bg-layer-1); } /* Two-press kill affordance on running job rows: same persistent square. */ @@ -258,7 +147,7 @@ padding: 0; border: 0.5px solid var(--dsw-alias-border-l2); border-radius: var(--dsw-radius-sm); - background: var(--dsw-specific-menu); + background: var(--dsw-alias-bg-layer-1); color: var(--dsw-alias-label-secondary); cursor: pointer; } @@ -398,7 +287,7 @@ } /* A failed task's detail is the producer's raw text, so it has no bound; - without this it widens the row past the menu instead of eliding like .label. */ + without this it widens the row past the panel instead of eliding like .label. */ .status { flex: none; max-width: 60%; @@ -455,48 +344,3 @@ .noticeError { color: var(--dsw-alias-state-error-primary); } - -@position-try --dsh-jobs-window { - position-area: none; - top: max(12px, calc(anchor(bottom) + 5px)); - bottom: 12px; - left: 12px; - right: 12px; - margin: 0; - align-self: safe start; - justify-self: safe end; -} - -@position-try --dsh-jobs-opposite { - top: max(12px, var(--dsh-frame-overlay-top, 12px)); - bottom: max(12px, calc(anchor(top) + 5px)); - align-self: end; -} - -@position-try --dsh-jobs-wide-opposite { - top: max(12px, var(--dsh-frame-overlay-top, 12px)); - bottom: max(12px, calc(anchor(top) + 5px)); - left: 12px; - right: 12px; - align-self: end; - justify-self: safe end; -} - -@position-try --dsh-jobs-tall { - position-area: none; - top: max(12px, var(--dsh-frame-overlay-top, 12px)); - bottom: 12px; - left: max(12px, anchor(left)); - right: 12px; - margin: 0; - align-self: safe start; - justify-self: start; -} - -@position-try --dsh-jobs-viewport { - position-area: none; - inset: max(12px, var(--dsh-frame-overlay-top, 12px)) 12px 12px; - margin: 0; - align-self: safe start; - justify-self: safe end; -} diff --git a/packages/client/ui-jobs/src/client/JobListAction.tsx b/packages/client/ui-jobs/src/client/JobsSection.tsx similarity index 60% rename from packages/client/ui-jobs/src/client/JobListAction.tsx rename to packages/client/ui-jobs/src/client/JobsSection.tsx index 1c88d77ef9..b348e89777 100644 --- a/packages/client/ui-jobs/src/client/JobListAction.tsx +++ b/packages/client/ui-jobs/src/client/JobsSection.tsx @@ -1,19 +1,17 @@ -import { useCallback, useEffect, useId, useMemo, useRef, useState, type KeyboardEvent, type PointerEvent } from 'react' -import { createPortal } from 'react-dom' +import { useEffect, useMemo, useState } from 'react' import type { JobsSnapshot, JobView, ObservedJob } from '@deepseek-ai/dsh-api-job-controller/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { - IconChevronDownOutlineRegular, IconLayersOutlineRegular, IconStopFillRegular, MenuSurface, StateDot, TerminalBlock, Tooltip, - useDismissOnOutsidePointer, + IconChevronDownOutlineRegular, IconStopFillRegular, StateDot, TerminalBlock, type StateDotState, type TerminalBlockLabels, } from '@deepseek-ai/dsh-client-ui-primitives' import type { InjectFace, PropsLocale, PropsRuntime, TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' import { NS } from './locales.ts' -import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' -import css from './JobListAction.module.css' +import type {} from '@deepseek-ai/dsh-client-ui-session-panel/client' +import css from './JobsSection.module.css' -/** Registration-side business face for the job list. */ -export interface JobListInjected { +/** Registration-side business face for the background-jobs section. */ +export interface JobsSectionInjected { hooks: { /** Client jobs snapshot (rosters and observations) bound by the renderer as useJobs. */ jobs: { @@ -39,18 +37,15 @@ export interface JobListInjected { killJob: (sessionId: SessionId, jobId: string) => Promise } -/** Full props for the session-header job-list action. */ -export type JobListActionProps = - PropsRuntime<'conversation.session.header.actions'> +/** Full props for the Session panel's background-jobs section. */ +export type JobsSectionProps = + PropsRuntime<'conversation.session.panel.section'> & PropsLocale - & InjectFace + & InjectFace /** Stable empty list so a session with no jobs keeps one array identity. */ const NO_JOBS: readonly JobView[] = [] -/** Keyboard-reachable controls inside the list, in document order. */ -const FOCUSABLE = 'button:not(:disabled), a[href], [tabindex]:not([tabindex="-1"])' - /** How long an armed kill waits for its confirming press before disarming. */ const KILL_ARM_MS = 3_000 @@ -314,31 +309,21 @@ function JobItem({ job, view, expanded, now, onToggle, kill, t }: { } /** - * Session-header entry point for this session's background jobs. Mounting it - * keeps the session's roster stream open; it renders nothing at all until the - * session can see at least one job. Expanding an observable row (a live job, - * or a settled one with retained output) starts its observation stream, and - * collapsing (or closing the popover) stops it — output only flows while - * someone is watching. A running row carries a two-press stop button that - * requests a human kill through the job controller. Non-touch hover on a - * text-visible trigger opens after 150ms and closes after 120ms outside both - * trigger and portal. Compact triggers toggle on click; ArrowDown opens and - * pins either layout. Interacting inside also pins the menu until explicit - * dismissal; timers and the pin are local to the mounted session. + * Session panel section for this session's background jobs. Mounting it keeps + * the session's roster stream open; it renders nothing until the session can + * see at least one job, so the panel hides the section with its title. Live + * rows come first; settled rows fold under a count that expands and clears + * client-side. Expanding an observable row (a live job, or a settled one with + * retained output) starts its observation stream, and collapsing stops it — + * output only flows while someone is watching. A running row carries a + * two-press stop button that requests a human kill through the job controller. * @param props - runtime slot currency, the jobs snapshot hook, the roster, * observation, and kill controls, and the namespace translator. - * @returns the trigger and its popover list, or null when there is nothing to show. + * @returns the job list, or null when there is nothing to show. */ -export function JobListAction({ sessionId, useJobs, watchRows, observe, killJob, t }: JobListActionProps) { - const activityId = useId() +export function JobsSection({ sessionId, useJobs, watchRows, observe, killJob, t }: JobsSectionProps) { const jobs = useJobs(state => state.rows[sessionId]) ?? NO_JOBS const observedViews = useJobs(state => state.observed) - const [menuState, setMenuState] = useState<{ sessionId: SessionId; mode: 'closed' | 'hover' | 'pinned' }>( - { sessionId, mode: 'closed' }, - ) - const hoverOpenTimer = useRef | undefined>(undefined) - const hoverCloseTimer = useRef | undefined>(undefined) - if (menuState.sessionId !== sessionId) setMenuState({ sessionId, mode: 'closed' }) const [expandedKey, setExpandedKey] = useState(undefined) const [now, setNow] = useState(() => Date.now()) // Settled-section fold: an explicit user toggle wins; before one, the tail @@ -349,10 +334,6 @@ export function JobListAction({ sessionId, useJobs, watchRows, observe, killJob, const [clearedKeys, setClearedKeys] = useState>(() => new Set()) // One kill affordance advances at a time: arming a row disarms any other. const [killPhase, setKillPhase] = useState<{ key: string; state: Exclude } | undefined>(undefined) - const rootRef = useRef(null) - const triggerRef = useRef(null) - const countRef = useRef(null) - const menuRef = useRef(null) const rows = useMemo(() => ordered(jobs), [jobs]) const liveRows = useMemo(() => rows.filter(isLive), [rows]) @@ -361,101 +342,27 @@ export function JobListAction({ sessionId, useJobs, watchRows, observe, killJob, [rows, clearedKeys], ) const settledExpanded = settledOpen ?? liveRows.length === 0 - const visibleCount = liveRows.length + settledRows.length - const hasJobs = visibleCount > 0 - const open = hasJobs && menuState.sessionId === sessionId && menuState.mode !== 'closed' - const cancelHover = useCallback((): void => { - clearTimeout(hoverOpenTimer.current) - clearTimeout(hoverCloseTimer.current) - hoverOpenTimer.current = undefined - hoverCloseTimer.current = undefined - }, []) - - const changeOpen = useCallback((next: boolean): void => { - cancelHover() - if (next) setNow(Date.now()) - setMenuState({ sessionId, mode: next ? 'pinned' : 'closed' }) - }, [cancelHover, sessionId]) - - // CSS owns the compact breakpoint; read its result only for pointer gestures. - const allowsHoverOpen = (): boolean => countRef.current !== null - && getComputedStyle(countRef.current).display !== 'none' - - const hoverEnter = (event: PointerEvent): void => { - if (event.pointerType === 'touch') return - cancelHover() - if (open || !allowsHoverOpen()) return - hoverOpenTimer.current = setTimeout(() => { - hoverOpenTimer.current = undefined - if (!allowsHoverOpen()) return - setNow(Date.now()) - setMenuState({ sessionId, mode: 'hover' }) - }, 150) - } - - const hoverLeave = (event: PointerEvent): void => { - if (event.pointerType === 'touch') return - cancelHover() - if (!open || menuState.mode === 'pinned') return - hoverCloseTimer.current = setTimeout(() => { - hoverCloseTimer.current = undefined - setMenuState({ sessionId, mode: 'closed' }) - }, 120) - } - - // Timers belong to this mounted session and cannot survive a disappearing trigger. - useEffect(() => cancelHover, [cancelHover, sessionId, hasJobs]) - - const anchorName = `--dsh-jobs-${useId().replaceAll(':', '')}` - useDismissOnOutsidePointer(rootRef, open, changeOpen, menuRef) - // Hover does not move focus; Escape must also work from the rest of the page. - useEffect(() => { - if (!open) return - const dismiss = (event: globalThis.KeyboardEvent): void => { - if (event.key !== 'Escape' || event.defaultPrevented) return - event.preventDefault() - changeOpen(false) - } - document.addEventListener('keydown', dismiss) - return () => { document.removeEventListener('keydown', dismiss) } - }, [open, changeOpen]) - - // The roster follows the mounted session: one stream while this control - // lives, released with it. + // The roster follows the mounted section: one stream while it lives, released with it. useEffect(() => watchRows(sessionId), [sessionId, watchRows]) - // The clock only runs while an open list is showing something that moves. + // The clock only runs while the list shows something that moves. useEffect(() => { - if (!open || liveRows.length === 0) return + if (liveRows.length === 0) return setNow(Date.now()) const timer = setInterval(() => { setNow(Date.now()) }, 1_000) return () => { clearInterval(timer) } - }, [open, liveRows.length]) + }, [liveRows.length]) // Observation follows visibility: the stream opens when an observable panel - // expands and closes when it collapses, unmounts, or the popover closes. - const expandedRow = open && expandedKey !== undefined - ? rows.find(job => String(job.id) === expandedKey) - : undefined + // expands and closes when it collapses or the section unmounts. + const expandedRow = expandedKey === undefined ? undefined : rows.find(job => String(job.id) === expandedKey) const activeJob = expandedRow !== undefined && isObservable(expandedRow) ? expandedRow.id : undefined useEffect(() => { if (activeJob === undefined) return return observe(sessionId, activeJob) }, [sessionId, activeJob, observe]) - // A returning roster starts closed rather than restoring an obsolete pin. - useEffect(() => { - if (!hasJobs) changeOpen(false) - }, [hasJobs, changeOpen]) - - // An expanded row that left the list (owner disposal) folds its panel. - useEffect(() => { - if (expandedKey !== undefined && !rows.some(job => String(job.id) === expandedKey)) { - setExpandedKey(undefined) - } - }, [rows, expandedKey]) - // An armed kill disarms on a timer, and a failed one clears its hint; the // pending phase instead waits for the RPC (or the row's own status flip). // The cleanup clears the timer on every phase change, so a firing timer @@ -471,12 +378,9 @@ export function JobListAction({ sessionId, useJobs, watchRows, observe, killJob, // A phase whose row stopped being killable (settled, stopping, removed) // has no button to describe any more. - useEffect(() => { - if (killPhase !== undefined - && !rows.some(job => String(job.id) === killPhase.key && job.status === 'running')) { - setKillPhase(undefined) - } - }, [rows, killPhase]) + const killable = killPhase !== undefined + && rows.some(job => String(job.id) === killPhase.key && job.status === 'running') + if (killPhase !== undefined && !killable) setKillPhase(undefined) const pressKill = (job: JobView): void => { const key = String(job.id) @@ -490,17 +394,14 @@ export function JobListAction({ sessionId, useJobs, watchRows, observe, killJob, // frames (control stream) have no cross-carrier ordering, so re-enabling // here could offer a duplicate kill while the row still reads `running`. // The authoritative jobs frame flips the row to `stopping`, which removes - // the button and clears the phase through the killable-set effect above. + // the button and clears the phase above. setKillPhase(current => current?.key === key && !ok ? { key, state: 'failed' } : current) }) } - if (visibleCount === 0) return null - - const count = liveRows.length > 0 ? liveRows.length : visibleCount - const countLabel = t(count === 1 ? 'count.idle.one' : 'count.idle.other', { count }) + if (liveRows.length + settledRows.length === 0) return null const clearSettled = (): void => { setClearedKeys((current) => { @@ -513,35 +414,6 @@ export function JobListAction({ sessionId, useJobs, watchRows, observe, killJob, } } - // The portaled list sits at the end of the document, so Tab is bridged to - // keep the in-place order: the trigger leads into the list, and leaving - // either end of the list returns to the trigger's position in the page. - const onKeyDown = (event: KeyboardEvent): void => { - const trigger = triggerRef.current - if (event.key === 'Escape') { - event.preventDefault() - changeOpen(false) - trigger?.focus() - return - } - if (!open) return - const menu = menuRef.current - /* v8 ignore next -- both refs are attached while the open list renders. */ - if (event.key !== 'Tab' || trigger === null || menu === null) return - const focusable = [...menu.querySelectorAll(FOCUSABLE)] - if (event.target === trigger) { - // Every list carries a control: a live row's toggle or the settled section's buttons. - if (event.shiftKey) return - event.preventDefault() - focusable[0]?.focus() - } else if (event.shiftKey ? event.target === focusable[0] : event.target === focusable.at(-1)) { - // Shift+Tab lands on the trigger itself; Tab continues from it to the - // control that follows the trigger. - if (event.shiftKey) event.preventDefault() - trigger.focus() - } - } - const item = (job: JobView) => ( - - - - {liveRows.length > 0 && } - {open - ? createPortal( - { changeOpen(true) }} - onFocusCapture={() => { changeOpen(true) }} - > -
    - {liveRows.length > 0 - ? - : null} - {liveRows.map(item)} - {settledRows.length > 0 - ? ( -
  • - - -
  • - ) - : null} - {settledExpanded ? settledRows.map(item) : null} -
-
, - document.body, +
    + {liveRows.map(item)} + {settledRows.length > 0 + ? ( +
  • + + +
  • ) : null} - + {settledExpanded ? settledRows.map(item) : null} +
) } diff --git a/packages/client/ui-jobs/src/client/index.ts b/packages/client/ui-jobs/src/client/index.ts index 5174aa1fb8..8bc214bccc 100644 --- a/packages/client/ui-jobs/src/client/index.ts +++ b/packages/client/ui-jobs/src/client/index.ts @@ -1,17 +1,18 @@ /** - * Background-job plugin, browser half: contributes one session-header action - * that renders this session's jobs. Job rows, per-row observation streams, - * and the human kill all go through the `jobs` client service; this plugin - * holds no transport state of its own. + * Background-job plugin, browser half: contributes the Session panel's + * background-jobs section. Job rows, per-row observation streams, and the + * human kill all go through the `jobs` client service; this plugin holds no + * transport state of its own. */ import type { Context as ClientContext } from '@deepseek-ai/cordis' import type { JobId } from '@deepseek-ai/dsh-jobs/brand' -import { JobListAction } from './JobListAction.tsx' -import type { JobListInjected } from './JobListAction.tsx' +import { JobsSection } from './JobsSection.tsx' +import type { JobsSectionInjected } from './JobsSection.tsx' import type {} from '@deepseek-ai/dsh-api-job-controller/client' import type {} from '@deepseek-ai/dsh-client-locale/client' import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' import type {} from '@deepseek-ai/dsh-client-ui-session/client' +import type {} from '@deepseek-ai/dsh-client-ui-session-panel/client' import { en, ja, es, fr, de, ru, pt, NS, zh, type JobKey } from './locales.ts' declare module '@deepseek-ai/dsh-client-ui-slots' { @@ -21,26 +22,28 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { } } -export type { JobListActionProps, JobListInjected } from './JobListAction.tsx' +export type { JobsSectionProps, JobsSectionInjected } from './JobsSection.tsx' /** Required services: the jobs rosters, observations, and kill, the slot registry, and dictionaries. */ export const inject = ['jobs', 'slots', 'locale'] /** - * Client plugin body: register the dictionaries and the header action. + * Client plugin body: register the dictionaries and the Session panel section. * @param ctx - client root context. */ export function apply(ctx: ClientContext): void { ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'ui-jobs: dictionaries') + const t = ctx.locale.bind(NS) ctx.slots.inject( - 'conversation.session.header.actions', + 'conversation.session.panel.section', () => ctx.slots.register({ - name: 'conversation.session.header.actions', - id: 'job-list', - // Background work follows the preset label in the header actions band. - order: 20, + name: 'conversation.session.panel.section', + id: 'background-jobs', + // After change requests (100) and subagents (200). + order: 300, + label: () => t('list.aria'), locale: NS, - inject: (): JobListInjected => ({ + inject: (): JobsSectionInjected => ({ hooks: { jobs: ctx.jobs.state }, watchRows: sessionId => ctx.jobs.watchRows(sessionId), observe: (sessionId, id) => ctx.jobs.observe(sessionId, id), @@ -48,6 +51,6 @@ export function apply(ctx: ClientContext): void { // roster stream delivered, so the wire boundary stamps it back here. killJob: async (sessionId, jobId) => (await ctx.jobs.kill(sessionId, jobId as JobId)).ok, }), - }, JobListAction), + }, JobsSection), ) } diff --git a/packages/client/ui-jobs/src/client/locales.ts b/packages/client/ui-jobs/src/client/locales.ts index c968a08b5d..4d48f159e3 100644 --- a/packages/client/ui-jobs/src/client/locales.ts +++ b/packages/client/ui-jobs/src/client/locales.ts @@ -5,10 +5,7 @@ export const NS = 'job' /** Simplified Chinese dictionary (the key-set source of truth). */ export const zh = { - 'count.idle.one': '{count} 个后台任务', - 'count.idle.other': '{count} 个后台任务', 'list.aria': '后台任务', - 'section.live': '进行中', 'section.settledCount': '已结束 {count}', 'section.clear': '清空', 'row.expandAria': '展开 {label} 的实时输出', @@ -47,10 +44,7 @@ export const zh = { /** English dictionary, key-identical to the Chinese source of truth. */ export const en: Record = { - 'count.idle.one': '{count} background job', - 'count.idle.other': '{count} background jobs', 'list.aria': 'Background jobs', - 'section.live': 'Running', 'section.settledCount': 'Finished {count}', 'section.clear': 'Clear', 'row.expandAria': 'Show live output of {label}', @@ -92,10 +86,7 @@ export type JobKey = keyof typeof zh /** Japanese copy, checked against the English keys. */ export const ja = { - 'count.idle.one': 'バックグラウンドジョブ {count} 件', - 'count.idle.other': 'バックグラウンドジョブ {count} 件', 'list.aria': 'バックグラウンドジョブ', - 'section.live': '実行中', 'section.settledCount': '完了 {count} 件', 'section.clear': 'クリア', 'row.expandAria': '{label} のライブ出力を表示', @@ -134,10 +125,7 @@ export const ja = { /** Spanish dictionary, checked against the English keys. */ export const es = { - 'count.idle.one': 'Tareas en segundo plano: {count}', - 'count.idle.other': 'Tareas en segundo plano: {count}', 'list.aria': 'Trabajos en segundo plano', - 'section.live': 'corriendo', 'section.settledCount': 'Terminado {count}', 'section.clear': 'Borrar', 'row.expandAria': 'Mostrar salida en vivo de {label}', @@ -176,10 +164,7 @@ export const es = { /** French dictionary, checked against the English keys. */ export const fr = { - 'count.idle.one': 'Tâches en arrière-plan : {count}', - 'count.idle.other': 'Tâches en arrière-plan : {count}', 'list.aria': 'Travaux en arrière-plan', - 'section.live': 'Courir', 'section.settledCount': 'Terminé {count}', 'section.clear': 'Effacer', 'row.expandAria': 'Afficher la sortie en direct de {label}', @@ -218,10 +203,7 @@ export const fr = { /** German dictionary, checked against the English keys. */ export const de = { - 'count.idle.one': 'Hintergrundaufgaben: {count}', - 'count.idle.other': 'Hintergrundaufgaben: {count}', 'list.aria': 'Hintergrundjobs', - 'section.live': 'Laufen', 'section.settledCount': 'Fertig {count}', 'section.clear': 'Klar', 'row.expandAria': 'Live-Ausgabe von {label} anzeigen', @@ -260,10 +242,7 @@ export const de = { /** Russian dictionary, checked against the English keys. */ export const ru = { - 'count.idle.one': 'Фоновые задачи: {count}', - 'count.idle.other': 'Фоновые задачи: {count}', 'list.aria': 'Фоновые задания', - 'section.live': 'Бег', 'section.settledCount': 'Закончено {count}', 'section.clear': 'Очистить', 'row.expandAria': 'Показать живой вывод {label}', @@ -302,10 +281,7 @@ export const ru = { /** Portuguese dictionary, checked against the English keys. */ export const pt = { - 'count.idle.one': 'Tarefas em segundo plano: {count}', - 'count.idle.other': 'Tarefas em segundo plano: {count}', 'list.aria': 'Trabalhos em segundo plano', - 'section.live': 'Correndo', 'section.settledCount': 'Concluído {count}', 'section.clear': 'Limpar', 'row.expandAria': 'Mostrar saída ao vivo de {label}', diff --git a/packages/client/ui-jobs/tests/browser-plugin.client.spec.ts b/packages/client/ui-jobs/tests/browser-plugin.client.spec.ts index 1a393d7bf2..b66e5ab29a 100644 --- a/packages/client/ui-jobs/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-jobs/tests/browser-plugin.client.spec.ts @@ -9,17 +9,18 @@ import { JobId } from '@deepseek-ai/dsh-jobs/brand' import { SessionId } from '@deepseek-ai/dsh-session/types' import { describe, expect, it } from 'vitest' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' +import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots' import { stubConfigForm } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyLocale, inject as localeInject } from '@deepseek-ai/dsh-client-locale/client' import { apply, inject } from '../src/client/index.ts' -import type { JobListInjected } from '../src/client/JobListAction.tsx' +import type { JobsSectionInjected } from '../src/client/JobsSection.tsx' import { apply as applyNode } from '../src/index.ts' import { en, NS, zh } from '../src/client/locales.ts' -/** Slot ledger reader: entry ids currently registered in the header list. */ -function headerEntryIds(ctx: Context): (string | undefined)[] { +/** Slot ledger reader: entry ids currently registered in the Session panel section list. */ +function sectionEntryIds(ctx: Context): (string | undefined)[] { return ctx.slots - .entries('conversation.session.header.actions') + .entries('conversation.session.panel.section') .map(entry => entry.options.id) } @@ -39,7 +40,7 @@ async function bench(): Promise<{ ctx: Context; fiber: ReturnType null) ctx.provide('jobs', { @@ -80,10 +81,10 @@ describe('ui-jobs browser half', () => { it('exposes the jobs source and the roster, observation, and kill controls through the inject face', async () => { const { ctx } = await bench() const entry = ctx.slots - .entries('conversation.session.header.actions') - .find(candidate => candidate.options.id === 'job-list') - const inject = entry?.inject as (() => JobListInjected) | undefined - if (inject === undefined) throw new Error('job-list entry registered no inject face') + .entries('conversation.session.panel.section') + .find(candidate => candidate.options.id === 'background-jobs') + const inject = entry?.inject as (() => JobsSectionInjected) | undefined + if (inject === undefined) throw new Error('background-jobs entry registered no inject face') const face = inject() expect(face.hooks.jobs).toBeDefined() const release = face.watchRows(SessionId('session')) @@ -102,11 +103,14 @@ describe('ui-jobs browser half', () => { expect(kills).toEqual([['sess-live', 'bash-3'], ['sess-live', 'bash-4']]) }) - it('registers the header action, and fiber teardown removes it (HMR safety)', async () => { + it('registers the Session panel section, and fiber teardown removes it (HMR safety)', async () => { const { ctx, fiber } = await bench() - expect(headerEntryIds(ctx)).toContain('job-list') + expect(sectionEntryIds(ctx)).toContain('background-jobs') + const entry = ctx.slots.entries('conversation.session.panel.section').find(candidate => candidate.options.id === 'background-jobs') + expect(entry?.options.order).toBe(300) + expect(resolveSlotLabel(entry?.options.label)).toBe(zh['list.aria']) await fiber.dispose() - expect(headerEntryIds(ctx)).not.toContain('job-list') + expect(sectionEntryIds(ctx)).not.toContain('background-jobs') }) it('registers both dictionaries under its own namespace and releases them with the fiber', async () => { diff --git a/packages/client/ui-jobs/tests/job-list-action.client.spec.tsx b/packages/client/ui-jobs/tests/job-list-action.client.spec.tsx deleted file mode 100644 index 5bbf91ace5..0000000000 --- a/packages/client/ui-jobs/tests/job-list-action.client.spec.tsx +++ /dev/null @@ -1,950 +0,0 @@ -// @vitest-environment jsdom -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' -import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' -import type { JobsSnapshot, JobView, ObservedJob } from '@deepseek-ai/dsh-api-job-controller/client' -import type { SessionId } from '@deepseek-ai/dsh-session/types' -import { JobListAction, type JobListActionProps } from '../src/client/JobListAction.tsx' -import { zh, en, ja, es, fr, de, ru, pt } from '../src/client/locales.ts' - -beforeEach(() => { - class TooltipObserver implements ResizeObserver { - constructor(private readonly callback: ResizeObserverCallback) {} - observe(target: Element): void { - const size = { inlineSize: 160, blockSize: 30 } - this.callback([{ - target, borderBoxSize: [size], contentBoxSize: [size], devicePixelContentBoxSize: [size], contentRect: new DOMRect(), - }], this) - } - unobserve(): void {} - disconnect(): void {} - } - vi.stubGlobal('ResizeObserver', TooltipObserver) - vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true }))) -}) - -beforeEach(() => { - vi.stubGlobal('CSS', { supports: (property: string) => property === '-webkit-backdrop-filter' }) -}) - -afterEach(() => { - cleanup() - vi.restoreAllMocks() - vi.unstubAllGlobals() - vi.useRealTimers() -}) - -const SESSION = 'session' as SessionId -const t: JobListActionProps['t'] = makeTranslate(zh) - -/** A running job with nothing retained yet. */ -function job(over: Partial = {}): JobView { - return { - id: 'bash-1' as JobView['id'], - kind: 'bash', - label: 'pnpm run build', - status: 'running', - startedAt: 1_700_000_000_000, - output: { total: 0, earliest: 0 }, - ...over, - } -} - -/** A job that left retained output behind, so its row offers a panel even once settled. */ -function outputJob(over: Partial = {}): JobView { - return job({ output: { total: 12, earliest: 0 }, ...over }) -} - -function props( - jobs: readonly JobView[], - observe: JobListActionProps['observe'] = () => () => {}, - observed: Readonly> = {}, - killJob: JobListActionProps['killJob'] = async () => true, - watchRows: JobListActionProps['watchRows'] = () => () => {}, -): JobListActionProps { - const jobsState: JobsSnapshot = { rows: jobs.length > 0 ? { [SESSION]: jobs } : {}, observed } - function useJobs(select: (value: JobsSnapshot) => T): T { - return select(jobsState) - } - return { sessionId: SESSION, useJobs, watchRows, observe, killJob, t } as JobListActionProps -} - -function openList(): void { - fireEvent.click(screen.getAllByRole('button')[0]!) -} - -describe('JobListAction count copy', () => { - it.each([ - [zh, '1 个后台任务', '2 个后台任务'], - [en, '1 background job', '2 background jobs'], - [ja, 'バックグラウンドジョブ 1 件', 'バックグラウンドジョブ 2 件'], - [es, 'Tareas en segundo plano: 1', 'Tareas en segundo plano: 2'], - [fr, 'Tâches en arrière-plan : 1', 'Tâches en arrière-plan : 2'], - [de, 'Hintergrundaufgaben: 1', 'Hintergrundaufgaben: 2'], - [ru, 'Фоновые задачи: 1', 'Фоновые задачи: 2'], - [pt, 'Tarefas em segundo plano: 1', 'Tarefas em segundo plano: 2'], - ] as const)('uses neutral count copy for live and settled jobs in locale %#', (dictionary, one, two) => { - const translate: JobListActionProps['t'] = makeTranslate(dictionary) - const settled = job({ id: 'settled' as JobView['id'], status: 'completed', finishedAt: 1_700_000_003_000 }) - const { rerender } = render() - expect(screen.getByRole('button', { name: one, description: dictionary['section.live'] })).toBeDefined() - rerender() - expect(screen.getByRole('button', { name: one, description: dictionary['section.live'] })).toBeDefined() - rerender() - expect(screen.getByRole('button', { name: two, description: '' })).toBeDefined() - }) -}) - -describe('JobListAction visibility', () => { - it('renders nothing while the session sees no jobs', () => { - const { container } = render() - expect(container.innerHTML).toBe('') - }) - - it('watches the session roster while mounted and releases it on unmount', () => { - const stop = vi.fn() - const watchRows = vi.fn(() => stop) - const { unmount } = render() - expect(watchRows).toHaveBeenCalledWith(SESSION) - expect(stop).not.toHaveBeenCalled() - unmount() - expect(stop).toHaveBeenCalledTimes(1) - }) - - it('counts live jobs on the trigger', () => { - render() - expect(screen.getByRole('button', { name: '2 个后台任务' })).toBeDefined() - }) - - it('retains the compact Layers icon through running, stopping, and idle states without a root chevron', () => { - const { rerender } = render() - const trigger = screen.getByRole('button') - expect(trigger.querySelector('[data-icon="dsw-icon-layers-outline-regular"]')).not.toBeNull() - expect(trigger.querySelector('[data-state="ongoing"]')).not.toBeNull() - expect(trigger.querySelector('[data-icon="dsw-icon-chevron-down-outline-regular"]')).toBeNull() - rerender() - expect(screen.getByRole('button')).toBe(trigger) - expect(trigger.querySelector('[data-state="ongoing"]')).not.toBeNull() - rerender() - expect(screen.getByRole('button')).toBe(trigger) - expect(trigger.querySelector('[data-state="ongoing"]')).toBeNull() - const icon = trigger.querySelector('[data-icon="dsw-icon-layers-outline-regular"]') - expect(icon?.getAttribute('width')).toBe('14') - expect(trigger.querySelectorAll('svg')).toHaveLength(1) - }) - - it('falls back to the total when nothing is live', () => { - render() - expect(screen.getByRole('button', { name: '1 个后台任务' })).toBeDefined() - }) -}) - -describe('JobListAction hover', () => { - function pointer(target: Element, type: 'pointerover' | 'pointerout', pointerType = 'mouse'): void { - // jsdom lacks PointerEvent; preserve its pointer type on the native event. - const event = new MouseEvent(type, { bubbles: true }) - Object.defineProperty(event, 'pointerType', { value: pointerType }) - fireEvent(target, event) - } - - function advance(ms: number): void { - act(() => { vi.advanceTimersByTime(ms) }) - } - - function hoverOpen(): HTMLElement { - const trigger = screen.getByRole('button', { name: '1 个后台任务' }) - pointer(trigger, 'pointerover') - advance(149) - expect(screen.queryByRole('list')).toBeNull() - advance(1) - expect(trigger.getAttribute('aria-expanded')).toBe('true') - return trigger - } - - it('keeps the compact trigger click-only and shows its count tooltip after 500ms', () => { - vi.useFakeTimers() - render() - const trigger = screen.getByRole('button') - const count = trigger.querySelector('[data-job-count]')! - count.style.display = 'none' - pointer(trigger, 'pointerover') - advance(499) - expect(screen.queryByRole('list')).toBeNull() - expect(screen.queryByRole('tooltip')).toBeNull() - advance(1) - expect(screen.getByRole('tooltip').textContent).toBe('1 个后台任务') - fireEvent.click(trigger) - expect(screen.queryByRole('tooltip')).toBeNull() - pointer(trigger, 'pointerout') - advance(500) - expect(screen.getByRole('list')).toBeDefined() - fireEvent.click(trigger) - expect(screen.queryByRole('list')).toBeNull() - }) - - it('cancels pending wide hover when CSS hides the count and compact clicks close hover-opened lists', () => { - vi.useFakeTimers() - render() - const trigger = screen.getByRole('button') - const count = trigger.querySelector('[data-job-count]')! - pointer(trigger, 'pointerover') - advance(100) - count.style.display = 'none' - advance(50) - expect(screen.queryByRole('list')).toBeNull() - pointer(trigger, 'pointerout') - count.style.display = '' - hoverOpen() - count.style.display = 'none' - fireEvent.click(trigger) - expect(screen.queryByRole('list')).toBeNull() - }) - - it('shows count on keyboard focus immediately and opens and pins with ArrowDown', async () => { - vi.useFakeTimers() - render() - const trigger = screen.getByRole('button') - trigger.querySelector('[data-job-count]')!.style.display = 'none' - fireEvent.keyDown(document.body, { key: 'Tab' }) - act(() => { trigger.focus() }) - expect(screen.getByRole('tooltip').textContent).toBe('1 个后台任务') - fireEvent.keyDown(trigger, { key: 'ArrowDown' }) - await act(async () => { vi.runAllTicks() }) - expect(screen.queryByRole('tooltip')).toBeNull() - const row = screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') }) - expect(document.activeElement).toBe(row) - pointer(trigger, 'pointerout') - advance(120) - expect(screen.getByRole('list')).toBeDefined() - fireEvent.keyDown(row, { key: 'Escape' }) - expect(screen.queryByRole('list')).toBeNull() - expect(document.activeElement).toBe(trigger) - }) - - it('waits for hover, bridges the portal gap, and closes after leaving both surfaces', () => { - vi.useFakeTimers() - const observe = vi.fn(() => () => {}) - const { container } = render() - const trigger = hoverOpen() - const menu = screen.getByRole('list').parentElement! - expect(container.contains(menu)).toBe(false) - expect(observe).not.toHaveBeenCalled() - pointer(trigger, 'pointerout') - advance(119) - pointer(menu, 'pointerover') - advance(120) - expect(screen.getByRole('list')).toBeDefined() - pointer(menu, 'pointerout') - advance(119) - expect(screen.getByRole('list')).toBeDefined() - advance(1) - expect(screen.queryByRole('list')).toBeNull() - }) - - it('cancels short hover and preserves a returning pointer during leave grace', () => { - vi.useFakeTimers() - render() - const trigger = screen.getByRole('button') - pointer(trigger, 'pointerover') - advance(149) - pointer(trigger, 'pointerout') - advance(150) - expect(screen.queryByRole('list')).toBeNull() - hoverOpen() - pointer(trigger, 'pointerout') - advance(100) - pointer(trigger, 'pointerover') - advance(120) - expect(screen.getByRole('list')).toBeDefined() - }) - - it('pins a hover-opened list on click until explicit dismissal', () => { - vi.useFakeTimers() - render() - const trigger = hoverOpen() - fireEvent.click(trigger) - pointer(trigger, 'pointerout') - advance(120) - expect(screen.getByRole('list')).toBeDefined() - fireEvent.click(trigger) - expect(screen.queryByRole('list')).toBeNull() - hoverOpen() - fireEvent.click(trigger) - fireEvent.pointerDown(document.body) - expect(screen.queryByRole('list')).toBeNull() - hoverOpen() - pointer(trigger, 'pointerout') - advance(120) - expect(screen.queryByRole('list')).toBeNull() - }) - - it('ignores touch hover while keeping tap usable', () => { - vi.useFakeTimers() - render() - const trigger = screen.getByRole('button') - pointer(trigger, 'pointerover', 'touch') - advance(150) - expect(screen.queryByRole('list')).toBeNull() - fireEvent.click(trigger) - pointer(trigger, 'pointerout', 'touch') - advance(120) - expect(screen.getByRole('list')).toBeDefined() - fireEvent.click(trigger) - expect(screen.queryByRole('list')).toBeNull() - }) - - it('pins keyboard focus and releases expanded output on Escape or hover close', () => { - vi.useFakeTimers() - const stop = vi.fn() - const observe = vi.fn(() => stop) - render() - const trigger = hoverOpen() - pointer(trigger, 'pointerout') - act(() => { trigger.focus() }) - fireEvent.keyDown(trigger, { key: 'Tab' }) - const row = screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') }) - expect(document.activeElement).toBe(row) - advance(120) - fireEvent.click(row) - expect(observe).toHaveBeenCalledTimes(1) - fireEvent.keyDown(row, { key: 'Escape' }) - expect(document.activeElement).toBe(trigger) - expect(stop).toHaveBeenCalledTimes(1) - hoverOpen() - expect(observe).toHaveBeenCalledTimes(2) - pointer(trigger, 'pointerout') - advance(120) - expect(screen.queryByRole('list')).toBeNull() - expect(stop).toHaveBeenCalledTimes(2) - }) - - it('pins pointer interaction so leaving cannot interrupt stop confirmation', () => { - vi.useFakeTimers() - render() - const trigger = hoverOpen() - pointer(trigger, 'pointerout') - const stop = screen.getByTitle(zh['kill.stop'].replace('{label}', 'pnpm run build')) - fireEvent.pointerDown(stop) - fireEvent.click(stop) - pointer(screen.getByRole('list').parentElement!, 'pointerout') - advance(120) - expect(stop.getAttribute('data-kill-state')).toBe('armed') - expect(screen.getByRole('list')).toBeDefined() - }) - - it('dismisses a hover-opened list with Escape while focus is elsewhere', () => { - vi.useFakeTimers() - render() - hoverOpen() - fireEvent.keyDown(document.body, { key: 'a' }) - expect(screen.getByRole('list')).toBeDefined() - fireEvent.keyDown(document.body, { key: 'Escape' }) - expect(screen.queryByRole('list')).toBeNull() - }) - - it.each(['opening', 'closing'] as const)('cleans up a pending %s timer on unmount', (phase) => { - vi.useFakeTimers() - const { unmount } = render() - const trigger = screen.getByRole('button') - pointer(trigger, 'pointerover') - if (phase === 'closing') { - advance(150) - pointer(trigger, 'pointerout') - } - unmount() - expect(vi.getTimerCount()).toBe(0) - advance(150) - expect(screen.queryByRole('list')).toBeNull() - }) - - it('releases expanded output and pending hover close before showing another session', () => { - vi.useFakeTimers() - const stop = vi.fn() - const observe = vi.fn(() => stop) - const first = props([outputJob()], observe) - const { rerender } = render() - const trigger = hoverOpen() - const row = screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') }) - fireEvent.click(row) - expect(observe).toHaveBeenCalledTimes(1) - pointer(trigger, 'pointerout') - const nextId = 'next-session' as SessionId - rerender( select({ rows: { [nextId]: [outputJob()] }, observed: {} })} - />) - expect(stop).toHaveBeenCalledTimes(1) - expect(observe).toHaveBeenCalledTimes(1) - expect(vi.getTimerCount()).toBe(0) - hoverOpen() - advance(120) - expect(screen.getByRole('list')).toBeDefined() - expect(observe).toHaveBeenLastCalledWith(nextId, 'bash-1') - }) - - it('cancels pending hover and clears pins on session change or an empty roster', () => { - vi.useFakeTimers() - const first = props([job()]) - const nextId = 'next-session' as SessionId - const next: JobListActionProps = { - ...first, - sessionId: nextId, - useJobs: select => select({ rows: { [nextId]: [job()] }, observed: {} }), - } - const { rerender } = render() - pointer(screen.getByRole('button'), 'pointerover') - rerender() - advance(150) - expect(screen.queryByRole('list')).toBeNull() - const trigger = hoverOpen() - fireEvent.click(trigger) - rerender() - expect(screen.queryByRole('list')).toBeNull() - pointer(screen.getByRole('button'), 'pointerover') - rerender() - advance(150) - expect(vi.getTimerCount()).toBe(0) - rerender() - hoverOpen() - fireEvent.click(screen.getByRole('button', { name: '1 个后台任务' })) - rerender() - rerender() - expect(screen.queryByRole('list')).toBeNull() - }) -}) - -describe('JobListAction rows', () => { - it('renders a settled job without retained output as a static row', () => { - render() - expect(screen.getByRole('button', { name: '1 个后台任务' })).toBeDefined() - openList() - expect(screen.getByText('explore the repo')).toBeDefined() - expect(screen.queryByRole('button', { name: zh['row.expandAria'].replace('{label}', 'explore the repo') })).toBeNull() - }) - - it('offers a panel on a live row before any output arrived', () => { - render() - openList() - expect(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'warming up') })).toBeDefined() - }) - - it('shows the live progress line in place of the status word', () => { - render() - openList() - const list = screen.getByRole('list', { name: zh['list.aria'] }) - expect(within(list).getByText('pnpm run build')).toBeDefined() - expect(within(list).getByText('winding down')).toBeDefined() - }) - - it('folds the settled tail behind its count while live work exists, and clears on demand', () => { - const settled = [job({ id: 'bash-2' as JobView['id'], label: 'settled work', status: 'completed', finishedAt: 1_700_000_012_000 })] - render() - openList() - expect(screen.getByText(zh['section.live'], { selector: 'li' })).toBeDefined() - const toggle = screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') }) - // Folded by default while something runs; the toggle expands it. - expect(toggle.getAttribute('aria-expanded')).toBe('false') - expect(screen.queryByText('settled work')).toBeNull() - fireEvent.click(toggle) - expect(screen.getByText('settled work')).toBeDefined() - // Clearing hides the tail client-side and drops the whole section line. - fireEvent.click(screen.getByRole('button', { name: zh['section.clear'] })) - expect(screen.queryByText('settled work')).toBeNull() - expect(screen.queryByRole('button', { name: zh['section.clear'] })).toBeNull() - }) - - it('opens the settled tail by default when nothing is live', () => { - render() - openList() - expect(screen.getByText('pnpm run build')).toBeDefined() - expect(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') }).getAttribute('aria-expanded')).toBe('true') - }) - - it('clearing drops an expanded settled panel with its rows', () => { - const observe = vi.fn(() => () => {}) - render() - openList() - // Nothing live: the tail is open; expand the settled row's output panel. - fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'settled work') })) - expect(observe).toHaveBeenCalledWith(SESSION, 'bash-2') - fireEvent.click(screen.getByRole('button', { name: zh['section.clear'] })) - expect(screen.queryByText('settled work')).toBeNull() - expect(screen.queryByRole('button', { name: zh['row.collapseAria'].replace('{label}', 'settled work') })).toBeNull() - }) - - it('shows a settled duration and ticks a live one', () => { - vi.useFakeTimers({ now: 1_700_000_020_000 }) - render() - openList() - fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '3') })) - expect(screen.getByText('5秒')).toBeDefined() - expect(screen.getByText('12秒')).toBeDefined() - expect(screen.getByText('1小时3分')).toBeDefined() - expect(screen.getByText('1分12秒')).toBeDefined() - act(() => { vi.advanceTimersByTime(1_000) }) - expect(screen.getByText('6秒')).toBeDefined() - }) - - it('lists rows with kind, label, and detail-or-status', () => { - render() - openList() - fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') })) - const list = screen.getByRole('list', { name: zh['list.aria'] }) - const items = within(list).getAllByRole('listitem') - // The section line is a listitem too now: live row, section, settled row. - expect(items).toHaveLength(3) - expect(items[0]?.textContent).toContain('pnpm run build') - // A live row's second line is kind · duration; the status word only - // appears through a detail (none while running). - expect(items[0]?.textContent).toMatch(/小时|分|秒/) - expect(items[2]?.textContent).toContain('exit code: 3') - }) - - it('orders live rows first by start and settled rows newest-first with tie-breaks', () => { - const settled = (id: string, label: string, startedAt: number, finishedAt?: number): JobView => - job({ - id: id as JobView['id'], - label, - status: 'completed', - startedAt, - ...finishedAt !== undefined ? { finishedAt } : {}, - }) - render() - openList() - fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '5') })) - const labels = within(screen.getByRole('list', { name: zh['list.aria'] })) - .getAllByRole('listitem') - .map(item => item.querySelector('[title]')?.getAttribute('title')) - .filter((title): title is string => title != null && !title.startsWith('已运行') && !title.startsWith('耗时')) - expect(labels).toEqual([ - 'live-2', 'live-1', 'settled-d', 'settled-a', 'settled-c', 'settled-b', 'settled-e', - ]) - expect(screen.getAllByText(zh['status.completed']).length).toBeGreaterThan(0) - }) - - it('breaks a settled tie on start order so map iteration never decides it', () => { - render() - openList() - expect(within(screen.getByRole('list')).getAllByRole('listitem').map(row => row.querySelector('[title]')?.getAttribute('title')).filter(title => title !== undefined)) - .toEqual(['first', 'second']) - }) - - it('prefers the producer detail over the generic status word', () => { - render() - openList() - expect(within(screen.getByRole('list')).getByText('signal: SIGTERM')).toBeDefined() - }) - - it('renders settled status words and every lifecycle indicator', () => { - render() - openList() - fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '3') })) - for (const word of ['已完成', '已取消', '已失败']) { - expect(within(screen.getByRole('list')).getByText(word)).toBeDefined() - } - expect([...screen.getByRole('list').querySelectorAll('li [data-state]')].map(node => node.getAttribute('data-state'))) - .toEqual(['ongoing', 'warning', 'done', 'warning', 'error']) - }) -}) - -describe('JobListAction observation', () => { - it('marks killed rows, renders every output line unfolded, and copies the command', async () => { - const writeText = vi.fn().mockResolvedValue(undefined) - Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } }) - const lines = Array.from({ length: 24 }, (_value, index) => `line ${index + 1}`).join('\n') - const view: ObservedJob = { - jobId: 'bash-1' as JobView['id'], - text: lines, - gapBefore: false, - streaming: false, - } - render() - openList() - expect(screen.getByText(zh['status.killed'])).toBeDefined() - fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) - // The panel scrolls instead of folding: every line renders, no fold control. - expect(screen.getByText('line 1')).toBeDefined() - expect(screen.getByText('line 24')).toBeDefined() - expect(screen.queryByRole('button', { name: zh['terminal.expandAria'].replace('{n}', '8') })).toBeNull() - // The panel draws no state dot or label of its own — the row carries it. - expect(screen.queryByText(zh['terminal.done'])).toBeNull() - // The copy control carries the command, not the output. - await act(async () => { fireEvent.click(screen.getByRole('button', { name: zh['terminal.copy'] })) }) - expect(writeText).toHaveBeenCalledWith('pnpm run build') - }) - - it('anchors the portaled list with CSS without reading geometry on resize or ancestor scroll', () => { - const { container } = render() - const trigger = screen.getByRole('button', { name: '1 个后台任务' }) - const anchor = trigger.closest('div')! - const measure = vi.spyOn(anchor, 'getBoundingClientRect') - fireEvent.click(trigger) - const list = screen.getByRole('list', { name: zh['list.aria'] }) - const menu = list.closest('[data-menu-material]')! - expect(menu.parentElement).toBe(document.body) - expect(container.contains(list)).toBe(false) - expect(anchor.style.anchorName).not.toBe('') - expect(menu.style.positionAnchor).toBe(anchor.style.anchorName) - expect(menu.style.left).toBe('') - expect(menu.style.top).toBe('') - fireEvent(window, new Event('resize')) - fireEvent.scroll(container) - expect(menu.style.positionAnchor).toBe(anchor.style.anchorName) - expect(measure).not.toHaveBeenCalled() - }) - - it('gives independent job controls separate CSS anchors', () => { - render(<>) - const triggers = screen.getAllByRole('button', { name: '1 个后台任务' }) - const first = triggers[0]!.closest('div')! - const second = triggers[1]!.closest('div')! - expect(first.style.anchorName).not.toBe('') - expect(second.style.anchorName).not.toBe('') - expect(first.style.anchorName).not.toBe(second.style.anchorName) - }) - - it('keeps visual viewport changes out of inline placement and closes normally', () => { - const viewport = Object.assign(new EventTarget(), { width: 600, height: 500, offsetLeft: 40, offsetTop: 60 }) - vi.stubGlobal('visualViewport', viewport) - const listen = vi.spyOn(viewport, 'addEventListener') - render() - const trigger = screen.getByRole('button', { name: '1 个后台任务' }) - fireEvent.click(trigger) - const menu = screen.getByRole('list', { name: zh['list.aria'] }).closest('[data-menu-material]')! - const placement = menu.style.positionAnchor - act(() => { - viewport.offsetLeft = 100 - viewport.offsetTop = 120 - viewport.dispatchEvent(new Event('scroll')) - viewport.height = 200 - viewport.dispatchEvent(new Event('resize')) - }) - expect(menu.style.positionAnchor).toBe(placement) - expect(menu.style.left).toBe('') - expect(menu.style.top).toBe('') - expect(menu.style.getPropertyValue('--dsh-anchored-max-width')).toBe('') - expect(menu.style.getPropertyValue('--dsh-anchored-max-height')).toBe('') - expect(listen).not.toHaveBeenCalled() - fireEvent.click(trigger) - expect(screen.queryByRole('list', { name: zh['list.aria'] })).toBeNull() - }) - - it('keeps portaled controls interactive and releases observation on dismissal and unmount', () => { - const stop = vi.fn() - const observe = vi.fn(() => stop) - const { container, unmount } = render() - const trigger = screen.getByRole('button', { name: '1 个后台任务' }) - trigger.focus() - fireEvent.click(trigger) - const list = screen.getByRole('list', { name: zh['list.aria'] }) - expect(container.contains(list)).toBe(false) - const row = screen.getByRole('button', { - name: zh['row.expandAria'].replace('{label}', 'pnpm run build'), - }) - fireEvent.pointerDown(row) - fireEvent.click(row) - expect(screen.getByRole('list', { name: zh['list.aria'] })).toBe(list) - expect(observe).toHaveBeenCalledTimes(1) - expect(stop).not.toHaveBeenCalled() - const kill = screen.getByTitle(zh['kill.stop'].replace('{label}', 'pnpm run build')) - fireEvent.pointerDown(kill) - fireEvent.click(kill) - expect(kill.getAttribute('data-kill-state')).toBe('armed') - expect(screen.getByRole('list', { name: zh['list.aria'] })).toBe(list) - - row.focus() - fireEvent.keyDown(row, { key: 'Escape' }) - expect(screen.queryByRole('list', { name: zh['list.aria'] })).toBeNull() - expect(document.activeElement).toBe(trigger) - expect(stop).toHaveBeenCalledTimes(1) - fireEvent.click(trigger) - expect(observe).toHaveBeenCalledTimes(2) - fireEvent.pointerDown(document.body) - expect(screen.queryByRole('list', { name: zh['list.aria'] })).toBeNull() - expect(stop).toHaveBeenCalledTimes(2) - fireEvent.click(trigger) - expect(observe).toHaveBeenCalledTimes(3) - const reopened = screen.getByRole('list', { name: zh['list.aria'] }) - unmount() - expect(document.body.contains(reopened)).toBe(false) - expect(stop).toHaveBeenCalledTimes(3) - }) - - it('ignores other keys while open and closes once the roster empties', () => { - const settledPair = [ - outputJob({ id: 'bash-1' as JobView['id'], status: 'completed', finishedAt: 2 }), - outputJob({ id: 'bash-2' as JobView['id'], status: 'completed', finishedAt: 3 }), - ] - const { rerender } = render() - expect(screen.getByRole('button', { name: '2 个后台任务' })).toBeDefined() - openList() - const list = screen.getByRole('list', { name: zh['list.aria'] }) - fireEvent.keyDown(list, { key: 'a' }) - expect(screen.getByRole('list', { name: zh['list.aria'] })).toBeDefined() - // The roster emptying unmounts the control entirely; the open flag resets first. - rerender() - expect(screen.queryByRole('button')).toBeNull() - }) - - it('starts observing on expand with the session identity, renders the live text, and stops on collapse', () => { - const stop = vi.fn() - const observe = vi.fn(() => stop) - const view: ObservedJob = { - jobId: 'bash-1' as JobView['id'], - text: 'compiling…\n', - gapBefore: false, - streaming: true, - } - render() - openList() - fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) - expect(observe).toHaveBeenCalledWith(SESSION, 'bash-1') - expect(screen.getByText('compiling…')).toBeDefined() - - fireEvent.click(screen.getByRole('button', { name: zh['row.collapseAria'].replace('{label}', 'pnpm run build') })) - expect(stop).toHaveBeenCalledTimes(1) - }) - - it('renders a running panel with the prompt alone for a live row whose output has not arrived', () => { - const view: ObservedJob = { - jobId: 'bash-1' as JobView['id'], - text: '', - gapBefore: false, - streaming: true, - } - render() - openList() - fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) - expect(screen.getByRole('list', { name: zh['list.aria'] }).querySelector('[data-running]')).not.toBeNull() - expect(screen.queryByText(zh['terminal.noOutput'])).toBeNull() - }) - - it('surfaces retention gaps and stream failures above the panel', () => { - const view: ObservedJob = { - jobId: 'bash-1' as JobView['id'], - text: 'tail only', - gapBefore: true, - streaming: false, - error: 'connection lost', - } - render() - openList() - fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) - expect(screen.getByText(zh['output.gap'])).toBeDefined() - expect(screen.getByText('实时输出流中断:connection lost')).toBeDefined() - }) - - it('bridges Tab between the trigger and the portaled list and closes on Escape', () => { - render() - const trigger = screen.getAllByRole('button')[0]! - fireEvent.keyDown(trigger, { key: 'Tab' }) - openList() - const [first, last] = within(screen.getByRole('list', { name: zh['list.aria'] })).getAllByRole('button') - trigger.focus() - // Shift+Tab from the trigger leaves toward the controls before it. - expect(fireEvent.keyDown(trigger, { key: 'Tab', shiftKey: true })).toBe(true) - expect(document.activeElement).toBe(trigger) - // Tab from the trigger enters the list. - expect(fireEvent.keyDown(trigger, { key: 'Tab' })).toBe(false) - expect(document.activeElement).toBe(first) - // Inside the list Tab stays the browser's until an end is reached. - expect(fireEvent.keyDown(first!, { key: 'Tab' })).toBe(true) - // Tab off the last control resumes from the trigger's place in the page. - expect(fireEvent.keyDown(last!, { key: 'Tab' })).toBe(true) - expect(document.activeElement).toBe(trigger) - // Shift+Tab off the first control returns to the trigger itself. - first!.focus() - expect(fireEvent.keyDown(first!, { key: 'Tab', shiftKey: true })).toBe(false) - expect(document.activeElement).toBe(trigger) - first!.focus() - fireEvent.keyDown(first!, { key: 'Escape' }) - expect(screen.queryByRole('list', { name: zh['list.aria'] })).toBeNull() - expect(document.activeElement).toBe(trigger) - }) - - it('stops observation when the popover closes via Escape', () => { - const stop = vi.fn() - render( stop)} />) - openList() - fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) - fireEvent.keyDown(screen.getByRole('list', { name: zh['list.aria'] }), { key: 'Escape' }) - expect(stop).toHaveBeenCalledTimes(1) - expect(screen.queryByRole('list', { name: zh['list.aria'] })).toBeNull() - }) - - it('folds an expanded panel whose row left the roster', () => { - const stop = vi.fn() - // One stable observe identity across renders, as the inject face provides. - const observe = () => stop - const { rerender } = render() - openList() - fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) - rerender() - expect(stop).toHaveBeenCalledTimes(1) - expect(screen.queryByRole('button', { name: zh['row.collapseAria'].replace('{label}', 'other') })).toBeNull() - }) -}) - -describe('JobListAction human kill', () => { - const stopTitle = (label: string): string => zh['kill.stop'].replace('{label}', label) - - it('offers the stop control only on running rows', () => { - render() - openList() - expect(screen.getByTitle(stopTitle('pnpm run build'))).toBeDefined() - expect(screen.queryByTitle(stopTitle('done'))).toBeNull() - }) - - it('arms on the first press and kills on the confirming press', async () => { - const killJob = vi.fn(async () => true) - render() - openList() - const stop = screen.getByTitle(stopTitle('pnpm run build')) - fireEvent.click(stop) - expect(killJob).not.toHaveBeenCalled() - expect(stop.getAttribute('data-kill-state')).toBe('armed') - expect(screen.getByTitle(zh['kill.confirm'])).toBe(stop) - // The armed step is legible without hover: the button carries the label. - expect(stop.textContent).toBe(zh['kill.confirmAction']) - await act(async () => { fireEvent.click(stop) }) - expect(killJob).toHaveBeenCalledWith(SESSION, 'bash-1') - // An admitted kill stays pending: the unary response and the jobs frames - // have no cross-carrier ordering, so only the authoritative frame (the row - // leaving the killable set) releases the control — never the response. - expect(stop.getAttribute('data-kill-state')).toBe('pending') - expect(stop.hasAttribute('disabled')).toBe(true) - }) - - it('an armed press disarms after the confirmation window', () => { - vi.useFakeTimers() - const killJob = vi.fn(async () => true) - render() - openList() - const stop = screen.getByTitle(stopTitle('pnpm run build')) - fireEvent.click(stop) - expect(stop.getAttribute('data-kill-state')).toBe('armed') - act(() => { vi.advanceTimersByTime(3_000) }) - expect(stop.getAttribute('data-kill-state')).toBe('idle') - expect(killJob).not.toHaveBeenCalled() - }) - - it('a rejected kill shows its hint and then resets', async () => { - // Fake timers from the start so the failed-hint reset arms on the fake clock. - vi.useFakeTimers() - const killJob = vi.fn(async () => false) - render() - openList() - const stop = screen.getByTitle(stopTitle('pnpm run build')) - fireEvent.click(stop) - await act(async () => { fireEvent.click(stop) }) - expect(stop.getAttribute('data-kill-state')).toBe('failed') - expect(screen.getByTitle(zh['kill.failed'])).toBe(stop) - act(() => { vi.advanceTimersByTime(4_000) }) - expect(stop.getAttribute('data-kill-state')).toBe('idle') - }) - - it('arming a second row disarms the first', () => { - render() - openList() - const first = screen.getByTitle(stopTitle('pnpm run build')) - fireEvent.click(first) - expect(first.getAttribute('data-kill-state')).toBe('armed') - const second = screen.getByTitle(stopTitle('pnpm run watch')) - fireEvent.click(second) - expect(second.getAttribute('data-kill-state')).toBe('armed') - expect(first.getAttribute('data-kill-state')).toBe('idle') - }) - - it('a kill resolving after another row armed leaves the newer phase alone', async () => { - let resolveKill!: (ok: boolean) => void - const killJob = vi.fn(() => new Promise((resolve) => { resolveKill = resolve })) - render() - openList() - const first = screen.getByTitle(stopTitle('pnpm run build')) - fireEvent.click(first) - fireEvent.click(first) - expect(killJob).toHaveBeenCalledTimes(1) - // While the first kill is in flight, the user arms the second row; the - // late resolution must not clobber that newer phase. - const second = screen.getByTitle(stopTitle('pnpm run watch')) - fireEvent.click(second) - expect(second.getAttribute('data-kill-state')).toBe('armed') - await act(async () => { resolveKill(false) }) - expect(second.getAttribute('data-kill-state')).toBe('armed') - expect(first.getAttribute('data-kill-state')).toBe('idle') - }) - - it('clears an armed phase whose row stopped being killable', () => { - const { rerender } = render() - openList() - const stop = screen.getByTitle(stopTitle('pnpm run build')) - fireEvent.click(stop) - expect(stop.getAttribute('data-kill-state')).toBe('armed') - rerender() - // The stopping row offers no kill control any more, and the stale phase is gone. - expect(screen.queryByTitle(stopTitle('pnpm run build'))).toBeNull() - expect(document.querySelector('[data-kill-state]')).toBeNull() - }) -}) - -it.each([1, 2, 5, 21])('renders count-independent Russian labels for %i jobs', (count) => { - const jobs = Array.from({ length: count }, (_, i) => job({ id: `job-${i}` as JobView['id'] })) - const translate: JobListActionProps['t'] = makeTranslate(ru) - const view = render() - expect(screen.getByRole('button', { name: `Фоновые задачи: ${count}` })).toBeDefined() - view.rerender( ({ ...item, status: 'completed', finishedAt: 1_700_000_003_000 })))} t={translate} />) - expect(screen.getByRole('button', { name: `Фоновые задачи: ${count}` })).toBeDefined() -}) diff --git a/packages/client/ui-jobs/tests/jobs-section.client.spec.tsx b/packages/client/ui-jobs/tests/jobs-section.client.spec.tsx new file mode 100644 index 0000000000..296b28fc00 --- /dev/null +++ b/packages/client/ui-jobs/tests/jobs-section.client.spec.tsx @@ -0,0 +1,465 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import type { JobsSnapshot, JobView, ObservedJob } from '@deepseek-ai/dsh-api-job-controller/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { JobsSection, type JobsSectionProps } from '../src/client/JobsSection.tsx' +import { zh, ru } from '../src/client/locales.ts' + +beforeEach(() => { + class TooltipObserver implements ResizeObserver { + constructor(private readonly callback: ResizeObserverCallback) {} + observe(target: Element): void { + const size = { inlineSize: 160, blockSize: 30 } + this.callback([{ + target, borderBoxSize: [size], contentBoxSize: [size], devicePixelContentBoxSize: [size], contentRect: new DOMRect(), + }], this) + } + unobserve(): void {} + disconnect(): void {} + } + vi.stubGlobal('ResizeObserver', TooltipObserver) + vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true }))) +}) + +beforeEach(() => { + vi.stubGlobal('CSS', { supports: (property: string) => property === '-webkit-backdrop-filter' }) +}) + +afterEach(() => { + cleanup() + vi.restoreAllMocks() + vi.unstubAllGlobals() + vi.useRealTimers() +}) + +const SESSION = 'session' as SessionId +const t: JobsSectionProps['t'] = makeTranslate(zh) + +/** A running job with nothing retained yet. */ +function job(over: Partial = {}): JobView { + return { + id: 'bash-1' as JobView['id'], + kind: 'bash', + label: 'pnpm run build', + status: 'running', + startedAt: 1_700_000_000_000, + output: { total: 0, earliest: 0 }, + ...over, + } +} + +/** A job that left retained output behind, so its row offers a panel even once settled. */ +function outputJob(over: Partial = {}): JobView { + return job({ output: { total: 12, earliest: 0 }, ...over }) +} + +function props( + jobs: readonly JobView[], + observe: JobsSectionProps['observe'] = () => () => {}, + observed: Readonly> = {}, + killJob: JobsSectionProps['killJob'] = async () => true, + watchRows: JobsSectionProps['watchRows'] = () => () => {}, +): JobsSectionProps { + const jobsState: JobsSnapshot = { rows: jobs.length > 0 ? { [SESSION]: jobs } : {}, observed } + function useJobs(select: (value: JobsSnapshot) => T): T { + return select(jobsState) + } + return { sessionId: SESSION, useJobs, watchRows, observe, killJob, t } as JobsSectionProps +} + +/** The section renders its rows inline; there is no trigger to open. */ +function openList(): void {} + +describe('JobsSection visibility', () => { + it('renders nothing while the session sees no jobs', () => { + const { container } = render() + expect(container.innerHTML).toBe('') + }) + + it('watches the session roster while mounted and releases it on unmount', () => { + const stop = vi.fn() + const watchRows = vi.fn(() => stop) + const { unmount } = render() + expect(watchRows).toHaveBeenCalledWith(SESSION) + expect(stop).not.toHaveBeenCalled() + unmount() + expect(stop).toHaveBeenCalledTimes(1) + }) + +}) + +describe('JobsSection rows', () => { + it('renders a settled job without retained output as a static row', () => { + render() + expect(screen.getByRole('list', { name: zh['list.aria'] })).toBeDefined() + expect(screen.getByText('explore the repo')).toBeDefined() + expect(screen.queryByRole('button', { name: zh['row.expandAria'].replace('{label}', 'explore the repo') })).toBeNull() + }) + + it('offers a panel on a live row before any output arrived', () => { + render() + openList() + expect(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'warming up') })).toBeDefined() + }) + + it('shows the live progress line in place of the status word', () => { + render() + openList() + const list = screen.getByRole('list', { name: zh['list.aria'] }) + expect(within(list).getByText('pnpm run build')).toBeDefined() + expect(within(list).getByText('winding down')).toBeDefined() + }) + + it('folds the settled tail behind its count while live work exists, and clears on demand', () => { + const settled = [job({ id: 'bash-2' as JobView['id'], label: 'settled work', status: 'completed', finishedAt: 1_700_000_012_000 })] + render() + openList() + const toggle = screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') }) + // Folded by default while something runs; the toggle expands it. + expect(toggle.getAttribute('aria-expanded')).toBe('false') + expect(screen.queryByText('settled work')).toBeNull() + fireEvent.click(toggle) + expect(screen.getByText('settled work')).toBeDefined() + // Clearing hides the tail client-side and drops the whole section line. + fireEvent.click(screen.getByRole('button', { name: zh['section.clear'] })) + expect(screen.queryByText('settled work')).toBeNull() + expect(screen.queryByRole('button', { name: zh['section.clear'] })).toBeNull() + }) + + it('opens the settled tail by default when nothing is live', () => { + render() + openList() + expect(screen.getByText('pnpm run build')).toBeDefined() + expect(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') }).getAttribute('aria-expanded')).toBe('true') + }) + + it('clearing drops an expanded settled panel with its rows', () => { + const observe = vi.fn(() => () => {}) + render() + openList() + // Nothing live: the tail is open; expand the settled row's output panel. + fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'settled work') })) + expect(observe).toHaveBeenCalledWith(SESSION, 'bash-2') + fireEvent.click(screen.getByRole('button', { name: zh['section.clear'] })) + expect(screen.queryByText('settled work')).toBeNull() + expect(screen.queryByRole('button', { name: zh['row.collapseAria'].replace('{label}', 'settled work') })).toBeNull() + }) + + it('shows a settled duration and ticks a live one', () => { + vi.useFakeTimers({ now: 1_700_000_020_000 }) + render() + openList() + fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '3') })) + expect(screen.getByText('5秒')).toBeDefined() + expect(screen.getByText('12秒')).toBeDefined() + expect(screen.getByText('1小时3分')).toBeDefined() + expect(screen.getByText('1分12秒')).toBeDefined() + act(() => { vi.advanceTimersByTime(1_000) }) + expect(screen.getByText('6秒')).toBeDefined() + }) + + it('lists rows with kind, label, and detail-or-status', () => { + render() + openList() + fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') })) + const list = screen.getByRole('list', { name: zh['list.aria'] }) + const items = within(list).getAllByRole('listitem') + // The section line is a listitem too now: live row, section, settled row. + expect(items).toHaveLength(3) + expect(items[0]?.textContent).toContain('pnpm run build') + // A live row's second line is kind · duration; the status word only + // appears through a detail (none while running). + expect(items[0]?.textContent).toMatch(/小时|分|秒/) + expect(items[2]?.textContent).toContain('exit code: 3') + }) + + it('orders live rows first by start and settled rows newest-first with tie-breaks', () => { + const settled = (id: string, label: string, startedAt: number, finishedAt?: number): JobView => + job({ + id: id as JobView['id'], + label, + status: 'completed', + startedAt, + ...finishedAt !== undefined ? { finishedAt } : {}, + }) + render() + openList() + fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '5') })) + const labels = within(screen.getByRole('list', { name: zh['list.aria'] })) + .getAllByRole('listitem') + .map(item => item.querySelector('[title]')?.getAttribute('title')) + .filter((title): title is string => title != null && !title.startsWith('已运行') && !title.startsWith('耗时')) + expect(labels).toEqual([ + 'live-2', 'live-1', 'settled-d', 'settled-a', 'settled-c', 'settled-b', 'settled-e', + ]) + expect(screen.getAllByText(zh['status.completed']).length).toBeGreaterThan(0) + }) + + it('breaks a settled tie on start order so map iteration never decides it', () => { + render() + openList() + expect(within(screen.getByRole('list')).getAllByRole('listitem').map(row => row.querySelector('[title]')?.getAttribute('title')).filter(title => title !== undefined)) + .toEqual(['first', 'second']) + }) + + it('prefers the producer detail over the generic status word', () => { + render() + openList() + expect(within(screen.getByRole('list')).getByText('signal: SIGTERM')).toBeDefined() + }) + + it('renders settled status words and every lifecycle indicator', () => { + render() + openList() + fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '3') })) + for (const word of ['已完成', '已取消', '已失败']) { + expect(within(screen.getByRole('list')).getByText(word)).toBeDefined() + } + expect([...screen.getByRole('list').querySelectorAll('li [data-state]')].map(node => node.getAttribute('data-state'))) + .toEqual(['ongoing', 'warning', 'done', 'warning', 'error']) + }) +}) + +describe('JobsSection observation', () => { + it('marks killed rows, renders every output line unfolded, and copies the command', async () => { + const writeText = vi.fn().mockResolvedValue(undefined) + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } }) + const lines = Array.from({ length: 24 }, (_value, index) => `line ${index + 1}`).join('\n') + const view: ObservedJob = { + jobId: 'bash-1' as JobView['id'], + text: lines, + gapBefore: false, + streaming: false, + } + render() + openList() + expect(screen.getByText(zh['status.killed'])).toBeDefined() + fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) + // The panel scrolls instead of folding: every line renders, no fold control. + expect(screen.getByText('line 1')).toBeDefined() + expect(screen.getByText('line 24')).toBeDefined() + expect(screen.queryByRole('button', { name: zh['terminal.expandAria'].replace('{n}', '8') })).toBeNull() + // The panel draws no state dot or label of its own — the row carries it. + expect(screen.queryByText(zh['terminal.done'])).toBeNull() + // The copy control carries the command, not the output. + await act(async () => { fireEvent.click(screen.getByRole('button', { name: zh['terminal.copy'] })) }) + expect(writeText).toHaveBeenCalledWith('pnpm run build') + }) + + it('starts observing on expand with the session identity, renders the live text, and stops on collapse', () => { + const stop = vi.fn() + const observe = vi.fn(() => stop) + const view: ObservedJob = { + jobId: 'bash-1' as JobView['id'], + text: 'compiling…\n', + gapBefore: false, + streaming: true, + } + render() + openList() + fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) + expect(observe).toHaveBeenCalledWith(SESSION, 'bash-1') + expect(screen.getByText('compiling…')).toBeDefined() + + fireEvent.click(screen.getByRole('button', { name: zh['row.collapseAria'].replace('{label}', 'pnpm run build') })) + expect(stop).toHaveBeenCalledTimes(1) + }) + + it('renders a running panel with the prompt alone for a live row whose output has not arrived', () => { + const view: ObservedJob = { + jobId: 'bash-1' as JobView['id'], + text: '', + gapBefore: false, + streaming: true, + } + render() + openList() + fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) + expect(screen.getByRole('list', { name: zh['list.aria'] }).querySelector('[data-running]')).not.toBeNull() + expect(screen.queryByText(zh['terminal.noOutput'])).toBeNull() + }) + + it('surfaces retention gaps and stream failures above the panel', () => { + const view: ObservedJob = { + jobId: 'bash-1' as JobView['id'], + text: 'tail only', + gapBefore: true, + streaming: false, + error: 'connection lost', + } + render() + openList() + fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) + expect(screen.getByText(zh['output.gap'])).toBeDefined() + expect(screen.getByText('实时输出流中断:connection lost')).toBeDefined() + }) + + it('folds an expanded panel whose row left the roster', () => { + const stop = vi.fn() + // One stable observe identity across renders, as the inject face provides. + const observe = () => stop + const { rerender } = render() + openList() + fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) + rerender() + expect(stop).toHaveBeenCalledTimes(1) + expect(screen.queryByRole('button', { name: zh['row.collapseAria'].replace('{label}', 'other') })).toBeNull() + }) +}) + +describe('JobsSection human kill', () => { + const stopTitle = (label: string): string => zh['kill.stop'].replace('{label}', label) + + it('offers the stop control only on running rows', () => { + render() + openList() + expect(screen.getByTitle(stopTitle('pnpm run build'))).toBeDefined() + expect(screen.queryByTitle(stopTitle('done'))).toBeNull() + }) + + it('arms on the first press and kills on the confirming press', async () => { + const killJob = vi.fn(async () => true) + render() + openList() + const stop = screen.getByTitle(stopTitle('pnpm run build')) + fireEvent.click(stop) + expect(killJob).not.toHaveBeenCalled() + expect(stop.getAttribute('data-kill-state')).toBe('armed') + expect(screen.getByTitle(zh['kill.confirm'])).toBe(stop) + // The armed step is legible without hover: the button carries the label. + expect(stop.textContent).toBe(zh['kill.confirmAction']) + await act(async () => { fireEvent.click(stop) }) + expect(killJob).toHaveBeenCalledWith(SESSION, 'bash-1') + // An admitted kill stays pending: the unary response and the jobs frames + // have no cross-carrier ordering, so only the authoritative frame (the row + // leaving the killable set) releases the control — never the response. + expect(stop.getAttribute('data-kill-state')).toBe('pending') + expect(stop.hasAttribute('disabled')).toBe(true) + }) + + it('an armed press disarms after the confirmation window', () => { + vi.useFakeTimers() + const killJob = vi.fn(async () => true) + render() + openList() + const stop = screen.getByTitle(stopTitle('pnpm run build')) + fireEvent.click(stop) + expect(stop.getAttribute('data-kill-state')).toBe('armed') + act(() => { vi.advanceTimersByTime(3_000) }) + expect(stop.getAttribute('data-kill-state')).toBe('idle') + expect(killJob).not.toHaveBeenCalled() + }) + + it('a rejected kill shows its hint and then resets', async () => { + // Fake timers from the start so the failed-hint reset arms on the fake clock. + vi.useFakeTimers() + const killJob = vi.fn(async () => false) + render() + openList() + const stop = screen.getByTitle(stopTitle('pnpm run build')) + fireEvent.click(stop) + await act(async () => { fireEvent.click(stop) }) + expect(stop.getAttribute('data-kill-state')).toBe('failed') + expect(screen.getByTitle(zh['kill.failed'])).toBe(stop) + act(() => { vi.advanceTimersByTime(4_000) }) + expect(stop.getAttribute('data-kill-state')).toBe('idle') + }) + + it('arming a second row disarms the first', () => { + render() + openList() + const first = screen.getByTitle(stopTitle('pnpm run build')) + fireEvent.click(first) + expect(first.getAttribute('data-kill-state')).toBe('armed') + const second = screen.getByTitle(stopTitle('pnpm run watch')) + fireEvent.click(second) + expect(second.getAttribute('data-kill-state')).toBe('armed') + expect(first.getAttribute('data-kill-state')).toBe('idle') + }) + + it('a kill resolving after another row armed leaves the newer phase alone', async () => { + let resolveKill!: (ok: boolean) => void + const killJob = vi.fn(() => new Promise((resolve) => { resolveKill = resolve })) + render() + openList() + const first = screen.getByTitle(stopTitle('pnpm run build')) + fireEvent.click(first) + fireEvent.click(first) + expect(killJob).toHaveBeenCalledTimes(1) + // While the first kill is in flight, the user arms the second row; the + // late resolution must not clobber that newer phase. + const second = screen.getByTitle(stopTitle('pnpm run watch')) + fireEvent.click(second) + expect(second.getAttribute('data-kill-state')).toBe('armed') + await act(async () => { resolveKill(false) }) + expect(second.getAttribute('data-kill-state')).toBe('armed') + expect(first.getAttribute('data-kill-state')).toBe('idle') + }) + + it('clears an armed phase whose row stopped being killable', () => { + const { rerender } = render() + openList() + const stop = screen.getByTitle(stopTitle('pnpm run build')) + fireEvent.click(stop) + expect(stop.getAttribute('data-kill-state')).toBe('armed') + rerender() + // The stopping row offers no kill control any more, and the stale phase is gone. + expect(screen.queryByTitle(stopTitle('pnpm run build'))).toBeNull() + expect(document.querySelector('[data-kill-state]')).toBeNull() + }) +}) + +it('renders the Russian settled-count copy', () => { + const translate: JobsSectionProps['t'] = makeTranslate(ru) + render() + expect(screen.getByRole('button', { name: ru['section.settledCount'].replace('{count}', '1') })).toBeDefined() +}) diff --git a/packages/client/ui-jobs/tsconfig.json b/packages/client/ui-jobs/tsconfig.json index f5e1825084..5b38ad1aae 100644 --- a/packages/client/ui-jobs/tsconfig.json +++ b/packages/client/ui-jobs/tsconfig.json @@ -8,21 +8,18 @@ "src" ], "references": [ + { + "path": "../../../vendor/cordis" + }, { "path": "../../api/job-controller/tsconfig.client.json" }, { "path": "../../api/session-controller/tsconfig.client.json" }, - { - "path": "../../../vendor/cordis" - }, { "path": "../locale/tsconfig.client.json" }, - { - "path": "../ui-conversation/tsconfig.client.json" - }, { "path": "../ui-primitives" }, @@ -32,6 +29,9 @@ { "path": "../ui-session" }, + { + "path": "../ui-session-panel" + }, { "path": "../ui-slots" } diff --git a/packages/client/ui-subagent/package.json b/packages/client/ui-subagent/package.json index ade2634518..614e462dc8 100644 --- a/packages/client/ui-subagent/package.json +++ b/packages/client/ui-subagent/package.json @@ -34,9 +34,10 @@ "@deepseek-ai/dsh-client-resources", "@deepseek-ai/dsh-client-ui-chat", "@deepseek-ai/dsh-client-ui-conversation", - "@deepseek-ai/dsh-client-ui-primitives", - "@deepseek-ai/dsh-client-ui-sidebar-right", "@deepseek-ai/dsh-client-ui-input-trigger", + "@deepseek-ai/dsh-client-ui-primitives", + "@deepseek-ai/dsh-client-ui-session-panel", + "@deepseek-ai/dsh-client-ui-sidebar-right", "@deepseek-ai/dsh-client-ui-workspace" ], "platform": "web" @@ -51,6 +52,10 @@ "@deepseek-ai/cordis": "workspace:~" }, "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-agent-team": "workspace:*", + "@deepseek-ai/dsh-api-session-controller": "workspace:*", + "@deepseek-ai/dsh-client-connection": "workspace:*", "@deepseek-ai/dsh-client-locale": "workspace:*", "@deepseek-ai/dsh-client-resources": "workspace:*", "@deepseek-ai/dsh-client-test-runtime": "workspace:*", @@ -58,20 +63,17 @@ "@deepseek-ai/dsh-client-ui-conversation": "workspace:*", "@deepseek-ai/dsh-client-ui-input-trigger": "workspace:*", "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", + "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", + "@deepseek-ai/dsh-client-ui-session": "workspace:*", + "@deepseek-ai/dsh-client-ui-session-panel": "workspace:*", + "@deepseek-ai/dsh-client-ui-sidebar-right": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", + "@deepseek-ai/dsh-client-ui-workspace": "workspace:*", + "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-subagent": "workspace:*", "@deepseek-ai/dsh-token-meter": "workspace:*", - "@deepseek-ai/cordis": "workspace:~", "react": "^18.2.0", - "react-dom": "^18.2.0", - "@deepseek-ai/dsh-api-session-controller": "workspace:*", - "@deepseek-ai/dsh-client-connection": "workspace:*", - "@deepseek-ai/dsh-session": "workspace:*", - "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", - "@deepseek-ai/dsh-client-ui-sidebar-right": "workspace:*", - "@deepseek-ai/dsh-client-ui-session": "workspace:*", - "@deepseek-ai/dsh-client-ui-workspace": "workspace:*", - "@deepseek-ai/dsh-agent-team": "workspace:*" + "react-dom": "^18.2.0" }, "files": [ "locale/*.json", diff --git a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css b/packages/client/ui-subagent/src/client/SubagentCatalog.module.css similarity index 81% rename from packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css rename to packages/client/ui-subagent/src/client/SubagentCatalog.module.css index d3f58ad409..b1713aff5b 100644 --- a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css +++ b/packages/client/ui-subagent/src/client/SubagentCatalog.module.css @@ -11,7 +11,6 @@ margin-left: 6px; } -.trigger, .switcherTrigger { display: inline-flex; align-items: center; @@ -26,10 +25,6 @@ cursor: pointer; } -.trigger { - gap: 4px; -} - .switcherTrigger { gap: 4px; min-width: 0; @@ -57,25 +52,6 @@ flex: none; } -.activitySlot { - display: inline-flex; - flex: none; - align-items: center; - justify-content: center; - width: 14px; - height: 14px; -} - -.trigger:focus-visible { - color: var(--dsw-alias-label-primary); -} - -@media (hover: hover) { - .trigger:hover { - color: var(--dsw-alias-label-primary); - } -} - .switcherTrigger:focus-visible { color: var(--dsw-alias-label-primary); } @@ -100,55 +76,6 @@ transition: transform 120ms ease; } -.trigger .compactIcon { - display: none; -} - -/* The title-row container drops passive preset text at 540px; this action yields later. */ -@container (max-width: 460px) { - .trigger .compactIcon { - display: block; - } - - .trigger .textModeActivity { - display: none; - } - - .trigger .count { - display: none; - } - - .trigger { - box-sizing: border-box; - width: 28px; - height: 28px; - padding: 0; - justify-content: center; - color: var(--dsw-alias-label-secondary); - } - - .trigger .activitySlot, - .trigger .activitySlot > svg { - width: 15px; - height: 15px; - } - - .trigger:focus-visible { - color: var(--dsw-alias-label-secondary); - } - - .trigger:active { - background: var(--dsw-alias-interactive-bg-active); - } - - @media (hover: hover) { - .trigger:hover { - color: var(--dsw-alias-label-secondary); - background: var(--dsw-alias-interactive-bg-hover); - } - } -} - .menu { position: fixed; z-index: 100; @@ -193,40 +120,20 @@ } } -.sectionHeader { - display: flex; - align-items: flex-start; - gap: 7px; - padding: 4px 7px 8px; -} - -.sectionIcon { - display: grid; - flex: none; - place-items: center; - width: 14px; - height: 24px; - color: var(--dsw-alias-label-tertiary); -} - -.sectionTitle { - flex: none; - margin: 0; - color: var(--dsw-alias-label-primary); - font-size: 13px; - font-weight: 500; - line-height: 24px; -} - +/* Progress beside the Session panel section title, one line. */ .sectionProgress { - margin-inline-start: 4px; - flex: 1 1 auto; - min-width: 0; - padding-top: 2px; + overflow: hidden; color: var(--dsw-alias-label-tertiary); - font-size: 13px; - line-height: 20px; - overflow-wrap: anywhere; + font: var(--dsw-font-xxs-12); + text-overflow: ellipsis; + white-space: nowrap; +} + +/* The Session panel section supplies the inset and scrolling. */ +.sectionBody { + display: flex; + flex-direction: column; + min-width: 0; } .sectionEmpty { @@ -240,7 +147,8 @@ position: relative; min-width: 0; } -.menuBody > [role="tree"] > .node { +.menuBody > [role="tree"] > .node, +.sectionBody > [role="tree"] > .node { margin-left: -2px; } diff --git a/packages/client/ui-subagent/src/client/SubagentCatalog.tsx b/packages/client/ui-subagent/src/client/SubagentCatalog.tsx new file mode 100644 index 0000000000..98a35ed536 --- /dev/null +++ b/packages/client/ui-subagent/src/client/SubagentCatalog.tsx @@ -0,0 +1,559 @@ +/** Subagent catalog tree shared by the Session panel section and the breadcrumb switcher. */ +import { useEffect, useRef, useState, type KeyboardEvent, type MouseEvent } from 'react' +import type { + SessionListState, SessionProjectionMap, SessionProjectionSnapshot, SessionSummary, +} from '@deepseek-ai/dsh-api-session-controller/client' +import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client' +import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { + IconChevronRightOutlineRegular, IconRefreshOutlineRegular, IconCheckOutlineRegular, StateDot, Tooltip, +} from '@deepseek-ai/dsh-client-ui-primitives' +import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' +import type { NS } from './locales.ts' +import type {} from '@deepseek-ai/dsh-token-meter/client' +import css from './SubagentCatalog.module.css' + +/** One Session's direct subagents with their live activity. */ +export type SubagentCatalogSnapshot = Omit & { + state: 'loading' | 'ready' | 'migration-required' | 'error' + entries: (SessionProjectionMap['subagentCatalog'][number] & { activity: 'running' | 'inactive' })[] +} + +/** Catalogs of every Session whose projections the Client holds. */ +export type Catalogs = Readonly> + +/** Business actions supplied by the slot registrations. */ +export type SubagentCatalogInjected = { + openChild: (address: SubagentAddress) => void + openChildAside: (address: SubagentAddress) => void + refreshProjection: (parentSessionId: SessionId) => void +} + +interface CatalogRowsProps { + parentSessionId: SessionId + currentSessionId: SessionId | undefined + catalog: SubagentCatalogSnapshot + catalogs: Catalogs + summaries: Readonly> + expanded: ReadonlySet + level: number + openChild: (address: SubagentAddress) => void + openChildAside: (address: SubagentAddress) => void + refreshProjection: (parentSessionId: SessionId) => void + toggleBranch: (childSessionId: SessionId) => void + closeCatalog: () => void +} + +function treeItems(root: HTMLElement): HTMLElement[] { + return Array.from(root.querySelectorAll('[role="treeitem"]:not([aria-disabled="true"])')) +} + +/** Compact token count shared in shape with the conversation stats strip. */ +function formatTokens(value: number, t: TranslateNS): string { + const scaled = (next: number): string => next >= 100 + ? String(Math.round(next)) + : String(Math.round(next * 10) / 10) + if (value < 1_000) return String(value) + if (value < 1_000_000) return t('tokens.thousand', { value: scaled(value / 1_000) }) + return t('tokens.million', { value: scaled(value / 1_000_000) }) +} + +/** Sum the four disjoint durable provider-usage buckets. */ +function tokenTotal( + usage: SessionProjectionMap['tokenUsage'] | undefined, +): number | undefined { + return usage === undefined + ? undefined + : usage.uncachedInputTokens + usage.outputTokens + + usage.cacheReadTokens + usage.cacheWriteTokens +} + +/** Exact whole-second active-turn duration for one catalog row. */ +function activityDuration( + summary: SessionSummary | undefined, + activity: 'running' | 'inactive', + now: number, +): number | undefined { + if (summary === undefined) return undefined + const timing: SessionProjectionMap['subagentTiming'] | undefined + = summary.projectionValues?.subagentTiming + if (timing === undefined) return undefined + if (timing.active === undefined) return timing.settledMs + const end = activity === 'running' + ? now + : timing.active.through + return timing.settledMs + Math.max(0, end - timing.active.since) +} + +interface DurationParts { + seconds: number + minutes: number + hours: number + days: number + totalMinutes: number + totalHours: number +} + +function splitDuration(ms: number): DurationParts { + const totalSeconds = Math.floor(Math.max(0, ms) / 1_000) + const totalMinutes = Math.floor(totalSeconds / 60) + const totalHours = Math.floor(totalMinutes / 60) + return { + seconds: totalSeconds % 60, + minutes: totalMinutes % 60, + hours: totalHours % 24, + days: Math.floor(totalHours / 24), + totalMinutes, + totalHours, + } +} + +/** Format a duration with decreasing visual precision at larger scales. */ +function formatDuration(ms: number, t: TranslateNS): string { + const { seconds, minutes, hours, days, totalMinutes, totalHours } = splitDuration(ms) + if (days >= 365) { + const years = Math.floor(days / 365) + const months = Math.floor((days % 365) / 30) + return months === 0 + ? t('duration.years', { years }) + : t('duration.yearsMonths', { years, months }) + } + if (days >= 30) { + const months = Math.floor(days / 30) + const remainingDays = days % 30 + return remainingDays === 0 + ? t('duration.months', { months }) + : t('duration.monthsDays', { months, days: remainingDays }) + } + if (days > 0) { + return hours === 0 + ? t('duration.days', { days }) + : t('duration.daysHours', { days, hours }) + } + if (totalHours > 0) { + return t('duration.hours', { + hours: totalHours, + minutes: String(minutes).padStart(2, '0'), + seconds: String(seconds).padStart(2, '0'), + }) + } + if (totalMinutes > 0) { + return t('duration.minutes', { + minutes: totalMinutes, + seconds: String(seconds).padStart(2, '0'), + }) + } + return t('duration.seconds', { seconds }) +} + +/** Preserve exact whole seconds for hover and accessible naming. */ +function formatExactDuration(ms: number, t: TranslateNS): string { + const { seconds, minutes, hours, days } = splitDuration(ms) + return days === 0 + ? formatDuration(ms, t) + : t('duration.exactDays', { + days, + hours: String(hours).padStart(2, '0'), + minutes: String(minutes).padStart(2, '0'), + seconds: String(seconds).padStart(2, '0'), + }) +} + +/** Render catalog loading without inventing child membership. */ +function CatalogLoadingRows({ t }: { t: TranslateNS }) { + return
{t('loading.label')}
+} + +/** A child becomes a known leaf only after its own authoritative catalog loads empty. */ +function isKnownLeaf(catalog: SubagentCatalogSnapshot | undefined): boolean { + return catalog?.state === 'ready' && catalog.entries.length === 0 +} + +/** The agent name unique among the row's siblings, or the Session ID for entries recorded without one. */ +/** + * Name a catalog entry when it has no description. + * @param entry - catalog entry. + * @returns the entry's display name. + */ +export function entryName(entry: SubagentCatalogSnapshot['entries'][number]): string { + return entry.mode === 'continuable' || entry.mode === 'external' ? entry.name ?? entry.id : entry.id +} + +/** Only a local child's last closed, normally completed turn receives the completed marker. */ +function completedEntry(entry: SubagentCatalogSnapshot['entries'][number], summary: SessionSummary | undefined): boolean { + return entry.mode !== 'external' && entry.activity === 'inactive' + && summary?.projectionValues?.subagentTiming?.lastTurnCompleted === true +} + +/** Count direct catalog members without treating external or other inactive entries as completed. */ +function catalogProgress(entries: SubagentCatalogSnapshot['entries'], summaries: CatalogRowsProps['summaries'], t: TranslateNS): string { + let completed = 0 + let active = 0 + let inactive = 0 + let external = 0 + for (const entry of entries) { + if (entry.mode === 'external') external++ + else if (entry.activity === 'running') active++ + else if (completedEntry(entry, summaries[entry.id])) completed++ + else inactive++ + } + return [ + ...completed > 0 ? [t('progress.completed', { count: completed })] : [], + ...active > 0 ? [t('progress.active', { count: active })] : [], + ...inactive > 0 ? [t('progress.inactive', { count: inactive })] : [], + ...external > 0 ? [t('progress.external', { count: external })] : [], + ].join('\u2002·\u2002') +} + +/** Render one catalog level and recurse only through explicitly expanded rows. */ +function CatalogRows({ + parentSessionId, currentSessionId, catalog, catalogs, summaries, expanded, level, + openChild, openChildAside, refreshProjection, toggleBranch, closeCatalog, t, +}: CatalogRowsProps & { t: TranslateNS }) { + const [now, setNow] = useState(() => Date.now()) + const running = catalog.entries.some(entry => entry.activity === 'running') + useEffect(() => { + if (!running) return + const timer = setInterval(() => { setNow(Date.now()) }, 1_000) + return () => { clearInterval(timer) } + }, [running]) + const emptyLoading = catalog.state === 'loading' && catalog.entries.length === 0 + const reserveDisclosure = catalog.entries.some(entry => + entry.mode !== 'external' && !isKnownLeaf(catalogs[entry.id]) + && summaries[entry.id]?.formatStatus !== 'migration-required' + && catalogs[entry.id]?.state !== 'migration-required') + return ( + <> + {emptyLoading && ( + + )} + {catalog.state === 'error' && ( +
+ {catalog.error?.message ?? t('load.error')} + +
+ )} + {catalog.entries.map((entry) => { + const external = entry.mode === 'external' + const childCatalog = catalogs[entry.id] + const isCurrent = entry.id === currentSessionId + const knownLeaf = external || isKnownLeaf(childCatalog) + const requiresOpening = summaries[entry.id]?.formatStatus === 'migration-required' + || childCatalog?.state === 'migration-required' + const canExpand = !knownLeaf && !requiresOpening + const isExpanded = canExpand && expanded.has(entry.id) + const childLoading = childCatalog === undefined + || (childCatalog.state === 'loading' && childCatalog.entries.length === 0) + const summary = summaries[entry.id] + const description = entry.label || summary?.title + const name = entryName(entry) + const primaryLabel = description || name + const secondaryLabel = description ? name : undefined + const mode = external ? t('mode.external') : entry.mode === 'unknown' ? t('mode.unknown') + : entry.mode === 'one-shot' ? t('mode.oneShot') : t('mode.continuable') + const completed = completedEntry(entry, summary) + const activity = external ? undefined : entry.activity === 'running' + ? t('activity.running') + : completed + ? t('activity.completed') + : t('activity.inactive') + const secondary = [secondaryLabel, requiresOpening ? t('catalog.migrationRequired') : mode, activity] + .filter(value => value !== undefined) + .join(' · ') + const totalTokens = tokenTotal(summary?.projectionValues?.tokenUsage) + const durationMs = activityDuration( + summary, + entry.activity, + now, + ) + const tokenMetric = totalTokens === undefined + ? undefined + : t('tokens.total', { value: formatTokens(totalTokens, t) }) + const durationMetric = durationMs === undefined + ? undefined + : { + compact: formatDuration(durationMs, t), + exact: formatExactDuration(durationMs, t), + } + const metrics = [tokenMetric, durationMetric?.exact] + .filter(value => value !== undefined) + .join(' · ') + + const open = (): void => { + if (external) return + openChild({ + parentSessionId, + childSessionId: entry.id, + mode: entry.mode, + }) + closeCatalog() + } + const handleKey = (event: KeyboardEvent): void => { + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault() + event.stopPropagation() + open() + } else if ( + (event.key === 'ArrowRight' && canExpand && !isExpanded) + || (event.key === 'ArrowLeft' && isExpanded) + ) { + event.preventDefault() + event.stopPropagation() + toggleBranch(entry.id) + } + } + const toggle = (event: MouseEvent): void => { + event.preventDefault() + event.stopPropagation() + toggleBranch(entry.id) + } + + return ( +
+
value !== '').join(' ')} + {...canExpand ? { 'aria-expanded': isExpanded } : {}} + className={css.row} + onClick={open} + onKeyDown={handleKey} + > + {!canExpand + ? reserveDisclosure && + : ( + + )} +
+ + + + + {primaryLabel} + {secondaryLabel !== undefined && ( + {secondaryLabel} + )} + {requiresOpening && {t('catalog.migrationRequired')}} + + {metrics !== '' && ( + + {tokenMetric !== undefined && {tokenMetric}} + {durationMetric !== undefined && ( + + {durationMetric.compact} + + )} + + )} + {isCurrent + ? ( + + + + ) + : external ? : ( + + + + )} +
+
+ {isExpanded && ( +
+ {childCatalog === undefined + ? + : ( + + )} +
+ )} +
+ ) + })} + + ) +} + +/** + * Build every held Session's catalog from its projection and live status. + * @param projections - projection snapshots by Session. + * @param summaries - Session list rows by id. + * @param statuses - live Session statuses. + * @returns catalogs keyed by parent Session. + */ +export function deriveCatalogs( + projections: SessionListState['projectionsBySession'], + summaries: SessionListState['byId'], + statuses: SessionStatusSnapshot, +): Catalogs { + return Object.fromEntries(Object.entries(projections).map(([id, snapshot]) => { + const projected = snapshot.values.subagentCatalog + const state = snapshot.state === 'idle' + ? projected === undefined ? 'loading' : 'ready' + : snapshot.state === 'migration-required' && projected !== undefined ? 'ready' : snapshot.state + return [id, { + state, + error: snapshot.error, + entries: (projected ?? []).map(entry => ({ + ...entry, + activity: (statuses.get(entry.id)?.running ?? summaries[entry.id]?.running) === true + ? 'running' as const : 'inactive' as const, + })), + } satisfies SubagentCatalogSnapshot] + })) +} + +/** + * The direct subagents of `catalog`'s Session plus progress, as one phrase such as "2 of 3 done". + * @param catalog - catalog whose entries are counted. + * @param summaries - Session list rows by id. + * @param t - subagent copy. + * @returns the progress phrase, or an empty string without entries. + */ +export function progressOf(catalog: SubagentCatalogSnapshot, summaries: CatalogRowsProps['summaries'], t: TranslateNS): string { + return catalogProgress(catalog.entries, summaries, t) +} + +/** Props of one subagent tree. */ +export interface CatalogTreeProps { + /** Session whose direct catalog roots the tree. */ + rootSessionId: SessionId + /** Selected descendant highlighted in the tree. */ + currentSessionId?: SessionId | undefined + catalog: SubagentCatalogSnapshot + catalogs: Catalogs + summaries: CatalogRowsProps['summaries'] + openChild: (address: SubagentAddress) => void + openChildAside: (address: SubagentAddress) => void + refreshProjection: (parentSessionId: SessionId) => void + /** Called after a row opened a Session, so a surrounding popover or overlay can close. */ + onOpened: () => void + /** Focus the first row on mount, as a keyboard-opened popover does. */ + focusFirst?: boolean + t: TranslateNS +} + +/** + * Render a subagent tree with expandable branches and roving arrow-key focus. + * Expanding a branch refreshes that child's catalog; collapsing a branch also + * collapses its descendants. + * @param props - catalog data, actions, and copy. + * @returns the tree. + */ +export function CatalogTree({ + rootSessionId, currentSessionId, catalog, catalogs, summaries, + openChild, openChildAside, refreshProjection, onOpened, focusFirst = false, t, +}: CatalogTreeProps) { + const [expanded, setExpanded] = useState>(() => new Set()) + const treeRef = useRef(null) + useEffect(() => { + // Effects run after commit, when the tree element is attached. + if (focusFirst) treeItems(treeRef.current as HTMLDivElement)[0]?.focus() + }, [focusFirst]) + + const closeBranch = (root: SessionId): void => { + const closing = new Set() + const visit = (parentSessionId: SessionId): void => { + if (closing.has(parentSessionId) || !expanded.has(parentSessionId)) return + closing.add(parentSessionId) + for (const entry of catalogs[parentSessionId]?.entries ?? []) visit(entry.id) + } + visit(root) + setExpanded(current => new Set([...current].filter(id => !closing.has(id)))) + } + + const toggleBranch = (childSessionId: SessionId): void => { + if (expanded.has(childSessionId)) { + closeBranch(childSessionId) + return + } + setExpanded(current => new Set(current).add(childSessionId)) + refreshProjection(childSessionId) + } + + const navigate = (event: KeyboardEvent): void => { + const items = treeItems(event.currentTarget) + const index = items.indexOf(document.activeElement as HTMLElement) + const focusAt = (next: number): void => { items[(next + items.length) % items.length]?.focus() } + if (items.length === 0) return + if (event.key === 'Home') focusAt(0) + else if (event.key === 'End') focusAt(items.length - 1) + else if (event.key === 'ArrowDown') focusAt(index + 1) + else if (event.key === 'ArrowUp') focusAt(index < 0 ? items.length - 1 : index - 1) + else return + event.preventDefault() + } + + return ( +
+ +
+ ) +} diff --git a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx index 92a802ac66..2179934a72 100644 --- a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx +++ b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx @@ -1,180 +1,20 @@ -import { useMemo, useEffect, useId, useRef, useState, type KeyboardEvent, type MouseEvent, type ReactNode } from 'react' +/** Breadcrumb switcher for subagent Sessions: the current title opens its siblings' tree. */ +import { useMemo, useEffect, useId, useRef, useState } from 'react' import { createPortal } from 'react-dom' -import { - type SessionProjectionMap, type SessionSummary, - type SessionProjectionSnapshot, -} from '@deepseek-ai/dsh-api-session-controller/client' -import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' -import { - IconChevronRightOutlineRegular, IconRefreshOutlineRegular, IconUsersOutlineRegular, - IconCheckOutlineRegular, MenuSurface, StateDot, Tooltip, -} from '@deepseek-ai/dsh-client-ui-primitives' -import type { HostObservable, InjectFace, PropsLocale, PropsRenderSlots, PropsRuntime, TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' +import { MenuSurface } from '@deepseek-ai/dsh-client-ui-primitives' +import type { InjectFace, PropsLocale, PropsRuntime, TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' import { NS } from './locales.ts' import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' -import type {} from '@deepseek-ai/dsh-token-meter/client' -import type {} from '@deepseek-ai/dsh-agent-team/client' -import type {} from './slots.ts' -import css from './SubagentHeaderLineage.module.css' +import { CatalogTree, deriveCatalogs, entryName, type SubagentCatalogInjected, type SubagentCatalogSnapshot } from './SubagentCatalog.tsx' +import css from './SubagentCatalog.module.css' -type SubagentCatalogSnapshot = Omit & { - state: 'loading' | 'ready' | 'migration-required' | 'error' - entries: (SessionProjectionMap['subagentCatalog'][number] & { activity: 'running' | 'inactive' })[] -} -type Catalogs = Readonly> - -/** Business actions supplied by the slot registration. */ -export type SubagentCatalogInjected = { - openChild: (address: SubagentAddress) => void - openChildAside: (address: SubagentAddress) => void - refreshProjection: (parentSessionId: SessionId) => void -} - -/** Root catalog actions and availability of its optional footer. */ -export type SubagentCatalogActionInjected = SubagentCatalogInjected & { - hooks: { - /** Whether the catalog footer currently has a registered contributor. */ - footerAvailable: HostObservable - } -} +export type { SubagentCatalogInjected } from './SubagentCatalog.tsx' /** Full props for the session-header lineage renderer. */ export type SubagentHeaderLineageProps = PropsRuntime<'conversation.session.header.lineage'> & InjectFace & PropsLocale -interface CatalogRowsProps { - parentSessionId: SessionId - currentSessionId: SessionId | undefined - catalog: SubagentCatalogSnapshot - catalogs: Catalogs - summaries: Readonly> - expanded: ReadonlySet - level: number - openChild: (address: SubagentAddress) => void - openChildAside: (address: SubagentAddress) => void - refreshProjection: (parentSessionId: SessionId) => void - toggleBranch: (childSessionId: SessionId) => void - closeCatalog: () => void -} - -function treeItems(root: HTMLDivElement | null): HTMLElement[] { - return root === null - ? [] - : Array.from(root.querySelectorAll('[role="treeitem"]:not([aria-disabled="true"])')) -} - -/** Compact token count shared in shape with the conversation stats strip. */ -function formatTokens(value: number, t: TranslateNS): string { - const scaled = (next: number): string => next >= 100 - ? String(Math.round(next)) - : String(Math.round(next * 10) / 10) - if (value < 1_000) return String(value) - if (value < 1_000_000) return t('tokens.thousand', { value: scaled(value / 1_000) }) - return t('tokens.million', { value: scaled(value / 1_000_000) }) -} - -/** Sum the four disjoint durable provider-usage buckets. */ -function tokenTotal( - usage: SessionProjectionMap['tokenUsage'] | undefined, -): number | undefined { - return usage === undefined - ? undefined - : usage.uncachedInputTokens + usage.outputTokens - + usage.cacheReadTokens + usage.cacheWriteTokens -} - -/** Exact whole-second active-turn duration for one catalog row. */ -function activityDuration( - summary: SessionSummary | undefined, - activity: 'running' | 'inactive', - now: number, -): number | undefined { - if (summary === undefined) return undefined - const timing: SessionProjectionMap['subagentTiming'] | undefined - = summary.projectionValues?.subagentTiming - if (timing === undefined) return undefined - if (timing.active === undefined) return timing.settledMs - const end = activity === 'running' - ? now - : timing.active.through - return timing.settledMs + Math.max(0, end - timing.active.since) -} - -interface DurationParts { - seconds: number - minutes: number - hours: number - days: number - totalMinutes: number - totalHours: number -} - -function splitDuration(ms: number): DurationParts { - const totalSeconds = Math.floor(Math.max(0, ms) / 1_000) - const totalMinutes = Math.floor(totalSeconds / 60) - const totalHours = Math.floor(totalMinutes / 60) - return { - seconds: totalSeconds % 60, - minutes: totalMinutes % 60, - hours: totalHours % 24, - days: Math.floor(totalHours / 24), - totalMinutes, - totalHours, - } -} - -/** Format a duration with decreasing visual precision at larger scales. */ -function formatDuration(ms: number, t: TranslateNS): string { - const { seconds, minutes, hours, days, totalMinutes, totalHours } = splitDuration(ms) - if (days >= 365) { - const years = Math.floor(days / 365) - const months = Math.floor((days % 365) / 30) - return months === 0 - ? t('duration.years', { years }) - : t('duration.yearsMonths', { years, months }) - } - if (days >= 30) { - const months = Math.floor(days / 30) - const remainingDays = days % 30 - return remainingDays === 0 - ? t('duration.months', { months }) - : t('duration.monthsDays', { months, days: remainingDays }) - } - if (days > 0) { - return hours === 0 - ? t('duration.days', { days }) - : t('duration.daysHours', { days, hours }) - } - if (totalHours > 0) { - return t('duration.hours', { - hours: totalHours, - minutes: String(minutes).padStart(2, '0'), - seconds: String(seconds).padStart(2, '0'), - }) - } - if (totalMinutes > 0) { - return t('duration.minutes', { - minutes: totalMinutes, - seconds: String(seconds).padStart(2, '0'), - }) - } - return t('duration.seconds', { seconds }) -} - -/** Preserve exact whole seconds for hover and accessible naming. */ -function formatExactDuration(ms: number, t: TranslateNS): string { - const { seconds, minutes, hours, days } = splitDuration(ms) - return days === 0 - ? formatDuration(ms, t) - : t('duration.exactDays', { - days, - hours: String(hours).padStart(2, '0'), - minutes: String(minutes).padStart(2, '0'), - seconds: String(seconds).padStart(2, '0'), - }) -} - function SubagentSwitcherIcon() { return ( }) { - return
{t('loading.label')}
-} -/** A child becomes a known leaf only after its own authoritative catalog loads empty. */ -function isKnownLeaf(catalog: SubagentCatalogSnapshot | undefined): boolean { - return catalog?.state === 'ready' && catalog.entries.length === 0 -} - -/** The agent name unique among the row's siblings, or the Session ID for entries recorded without one. */ -function entryName(entry: SubagentCatalogSnapshot['entries'][number]): string { - return entry.mode === 'continuable' || entry.mode === 'external' ? entry.name ?? entry.id : entry.id -} - -/** Only a local child's last closed, normally completed turn receives the completed marker. */ -function completedEntry(entry: SubagentCatalogSnapshot['entries'][number], summary: SessionSummary | undefined): boolean { - return entry.mode !== 'external' && entry.activity === 'inactive' - && summary?.projectionValues?.subagentTiming?.lastTurnCompleted === true -} - -/** Count direct catalog members without treating external or other inactive entries as completed. */ -function catalogProgress(entries: SubagentCatalogSnapshot['entries'], summaries: CatalogRowsProps['summaries'], t: TranslateNS): string { - let completed = 0 - let active = 0 - let inactive = 0 - let external = 0 - for (const entry of entries) { - if (entry.mode === 'external') external++ - else if (entry.activity === 'running') active++ - else if (completedEntry(entry, summaries[entry.id])) completed++ - else inactive++ - } - return [ - ...completed > 0 ? [t('progress.completed', { count: completed })] : [], - ...active > 0 ? [t('progress.active', { count: active })] : [], - ...inactive > 0 ? [t('progress.inactive', { count: inactive })] : [], - ...external > 0 ? [t('progress.external', { count: external })] : [], - ].join('\u2002·\u2002') -} - -/** Render one catalog level and recurse only through explicitly expanded rows. */ -function CatalogRows({ - parentSessionId, currentSessionId, catalog, catalogs, summaries, expanded, level, - openChild, openChildAside, refreshProjection, toggleBranch, closeCatalog, t, -}: CatalogRowsProps & { t: TranslateNS }) { - const [now, setNow] = useState(() => Date.now()) - const running = catalog.entries.some(entry => entry.activity === 'running') - useEffect(() => { - if (!running) return - const timer = setInterval(() => { setNow(Date.now()) }, 1_000) - return () => { clearInterval(timer) } - }, [running]) - const emptyLoading = catalog.state === 'loading' && catalog.entries.length === 0 - const reserveDisclosure = catalog.entries.some(entry => - entry.mode !== 'external' && !isKnownLeaf(catalogs[entry.id]) - && summaries[entry.id]?.formatStatus !== 'migration-required' - && catalogs[entry.id]?.state !== 'migration-required') - return ( - <> - {emptyLoading && ( - - )} - {catalog.state === 'error' && ( -
- {catalog.error?.message ?? t('load.error')} - -
- )} - {catalog.entries.map((entry) => { - const external = entry.mode === 'external' - const childCatalog = catalogs[entry.id] - const isCurrent = entry.id === currentSessionId - const knownLeaf = external || isKnownLeaf(childCatalog) - const requiresOpening = summaries[entry.id]?.formatStatus === 'migration-required' - || childCatalog?.state === 'migration-required' - const canExpand = !knownLeaf && !requiresOpening - const isExpanded = canExpand && expanded.has(entry.id) - const childLoading = childCatalog === undefined - || (childCatalog.state === 'loading' && childCatalog.entries.length === 0) - const summary = summaries[entry.id] - const description = entry.label || summary?.title - const name = entryName(entry) - const primaryLabel = description || name - const secondaryLabel = description ? name : undefined - const mode = external ? t('mode.external') : entry.mode === 'unknown' ? t('mode.unknown') - : entry.mode === 'one-shot' ? t('mode.oneShot') : t('mode.continuable') - const completed = completedEntry(entry, summary) - const activity = external ? undefined : entry.activity === 'running' - ? t('activity.running') - : completed - ? t('activity.completed') - : t('activity.inactive') - const secondary = [secondaryLabel, requiresOpening ? t('catalog.migrationRequired') : mode, activity] - .filter(value => value !== undefined) - .join(' · ') - const totalTokens = tokenTotal(summary?.projectionValues?.tokenUsage) - const durationMs = activityDuration( - summary, - entry.activity, - now, - ) - const tokenMetric = totalTokens === undefined - ? undefined - : t('tokens.total', { value: formatTokens(totalTokens, t) }) - const durationMetric = durationMs === undefined - ? undefined - : { - compact: formatDuration(durationMs, t), - exact: formatExactDuration(durationMs, t), - } - const metrics = [tokenMetric, durationMetric?.exact] - .filter(value => value !== undefined) - .join(' · ') - - const open = (): void => { - if (external) return - openChild({ - parentSessionId, - childSessionId: entry.id, - mode: entry.mode, - }) - closeCatalog() - } - const handleKey = (event: KeyboardEvent): void => { - if (event.key === 'Enter' || event.key === ' ') { - event.preventDefault() - event.stopPropagation() - open() - } else if ( - (event.key === 'ArrowRight' && canExpand && !isExpanded) - || (event.key === 'ArrowLeft' && isExpanded) - ) { - event.preventDefault() - event.stopPropagation() - toggleBranch(entry.id) - } - } - const toggle = (event: MouseEvent): void => { - event.preventDefault() - event.stopPropagation() - toggleBranch(entry.id) - } - - return ( -
-
value !== '').join(' ')} - {...canExpand ? { 'aria-expanded': isExpanded } : {}} - className={css.row} - onClick={open} - onKeyDown={handleKey} - > - {!canExpand - ? reserveDisclosure && - : ( - - )} -
- - - - - {primaryLabel} - {secondaryLabel !== undefined && ( - {secondaryLabel} - )} - {requiresOpening && {t('catalog.migrationRequired')}} - - {metrics !== '' && ( - - {tokenMetric !== undefined && {tokenMetric}} - {durationMetric !== undefined && ( - - {durationMetric.compact} - - )} - - )} - {isCurrent - ? ( - - - - ) - : external ? : ( - - - - )} -
-
- {isExpanded && ( -
- {childCatalog === undefined - ? - : ( - - )} -
- )} -
- ) - })} - - ) -} - -interface CatalogDropdownSharedProps extends InjectFace { - /** Session whose direct catalog roots the tree. */ +interface SwitcherProps extends InjectFace { + /** Parent Session whose direct catalog roots the tree. */ rootSessionId: SessionId + /** Selected descendant highlighted in the tree. */ + currentSessionId: SessionId + /** Visible title included in the switcher's hover target. */ + displayTitle: string + /** Optional ancestor navigation when the combined title is clicked. */ + openTitle?: () => void useSessions: SubagentHeaderLineageProps['useSessions'] useSessionStatus: SubagentHeaderLineageProps['useSessionStatus'] t: TranslateNS - /** Section labels are useful only beside a visible shared-task list. */ - hasSharedTasks?: boolean - /** Retain an empty catalog's entry for shared tasks or a task-board error. */ - hasBoardContent?: boolean - renderFooter?: () => ReactNode } -type CatalogDropdownProps = CatalogDropdownSharedProps & ( - | { - /** Descendant-count control. */ - variant: 'count' - currentSessionId?: never - displayTitle?: never - openTitle?: never - } - | { - /** Current-title sibling switcher. */ - variant: 'switcher' - /** Selected descendant highlighted in the catalog. */ - currentSessionId: SessionId - /** Visible title included in the switcher's hover target. */ - displayTitle: string - /** Optional ancestor navigation when the combined title is clicked. */ - openTitle?: () => void - } -) - -/** One trigger-plus-tree dropdown over the catalog rooted at `rootSessionId`. */ -function CatalogDropdown(props: CatalogDropdownProps) { - const { - rootSessionId, currentSessionId, displayTitle, openTitle, variant, - useSessions, useSessionStatus, openChild, openChildAside, refreshProjection, t, hasSharedTasks = false, - } = props - const ancestorSwitcher = variant === 'switcher' && openTitle !== undefined +/** + * Title-and-chevron dropdown over the parent's subagent tree. Hover opens it + * after 150ms and leaving both surfaces closes it after 120ms; a click pins it + * until an outside press or Escape. With `openTitle`, a click navigates to the + * ancestor instead. + * @param props - tree root, current Session, title, Session hooks, actions, and copy. + * @returns the switcher. + */ +function Switcher({ + rootSessionId, currentSessionId, displayTitle, openTitle, + useSessions, useSessionStatus, openChild, openChildAside, refreshProjection, t, +}: SwitcherProps) { const projections = useSessions(state => state.projectionsBySession) const summaries = useSessions(state => state.byId) const statuses = useSessionStatus(value => value) - const catalogs = useMemo(() => { - return Object.fromEntries(Object.entries(projections).map(([id, snapshot]) => { - const projected = snapshot.values.subagentCatalog - const state = snapshot.state === 'idle' - ? projected === undefined ? 'loading' : 'ready' - : snapshot.state === 'migration-required' && projected !== undefined ? 'ready' : snapshot.state - return [id, { - state, - error: snapshot.error, - entries: (projected ?? []).map(entry => ({ - ...entry, - activity: (statuses.get(entry.id)?.running ?? summaries[entry.id]?.running) === true - ? 'running' as const : 'inactive' as const, - })), - } satisfies SubagentCatalogSnapshot] - })) - }, [projections, summaries, statuses]) - const catalog = catalogs[rootSessionId] - const [open, setOpen] = useState(false) - const [expanded, setExpanded] = useState>(() => new Set()) + const catalogs = useMemo(() => deriveCatalogs(projections, summaries, statuses), [projections, summaries, statuses]) + const catalog: SubagentCatalogSnapshot = catalogs[rootSessionId] ?? { entries: [], state: 'loading', error: null } + const [open, setOpen] = useState<'closed' | 'hover' | 'pinned' | 'keyboard'>('closed') const rootRef = useRef(null) const triggerRef = useRef(null) - const countRef = useRef(null) - const activityId = useId() const menuRef = useRef(null) - const anchorName = `--dsh-subagents-${activityId.replaceAll(':', '')}` - const hoverOpenTimer = useRef | undefined>(undefined) - const hoverCloseTimer = useRef | undefined>(undefined) - // A click-opened (pinned) menu ignores hover-out; only explicit dismissal closes it. - const pinnedRef = useRef(false) - const currentEntry = currentSessionId === undefined - ? undefined - : catalog?.entries.find(entry => entry.id === currentSessionId) - const switcherDisplayTitle = currentEntry !== undefined - ? currentEntry.label || entryName(currentEntry) - : displayTitle - const directChildren = catalog?.entries ?? [] - const directCount = directChildren.length - const runningCount = directChildren.filter(entry => entry.activity === 'running').length - const progress = catalogProgress(directChildren, summaries, t) - const totalCountKey = directCount === 1 ? 'count.total.one' : 'count.total.other' - const runningCountKey = runningCount === 1 ? 'count.running.one' : 'count.running.other' - const presentedCatalog: SubagentCatalogSnapshot | undefined = catalog ?? (variant === 'switcher' || props.hasBoardContent - ? { entries: [], state: 'loading', error: null } - : undefined) + const anchorName = `--dsh-subagents-${useId().replaceAll(':', '')}` + const hoverTimer = useRef | undefined>(undefined) + const currentEntry = catalog.entries.find(entry => entry.id === currentSessionId) + const title = currentEntry !== undefined ? currentEntry.label || entryName(currentEntry) : displayTitle + const shown = open !== 'closed' - const cancelHoverClose = (): void => { - if (hoverCloseTimer.current === undefined) return - clearTimeout(hoverCloseTimer.current) - hoverCloseTimer.current = undefined + const cancelHover = (): void => { + clearTimeout(hoverTimer.current) + hoverTimer.current = undefined } - - const cancelHoverOpen = (): void => { - if (hoverOpenTimer.current === undefined) return - clearTimeout(hoverOpenTimer.current) - hoverOpenTimer.current = undefined - } - - const changeOpen = (next: boolean, restoreFocus = false): void => { - cancelHoverOpen() - cancelHoverClose() - if (next) { - const trigger = triggerRef.current - /* v8 ignore next -- a queued callback can outlive the trigger */ - if (trigger === null) return - setOpen(true) - } - else { - pinnedRef.current = false - setOpen(false) - setExpanded(new Set()) - } + const close = (restoreFocus = false): void => { + cancelHover() + setOpen('closed') if (restoreFocus) queueMicrotask(() => { triggerRef.current?.focus() }) } - // CSS owns the header-width breakpoint; interaction reads its result only when scheduling hover. - const allowsHoverOpen = (): boolean => variant === 'switcher' - || (countRef.current !== null && getComputedStyle(countRef.current).display !== 'none') - - const scheduleHoverOpen = (): void => { - cancelHoverOpen() - cancelHoverClose() - if (open || !allowsHoverOpen()) return - hoverOpenTimer.current = setTimeout(() => { - hoverOpenTimer.current = undefined - if (allowsHoverOpen()) changeOpen(true) - }, 150) - } - - const scheduleHoverClose = (): void => { - cancelHoverOpen() - cancelHoverClose() - if (pinnedRef.current) return - hoverCloseTimer.current = setTimeout(() => { - hoverCloseTimer.current = undefined - changeOpen(false) - }, 120) - } - - const closeBranch = (root: SessionId): void => { - const closing = new Set() - const visit = (parentSessionId: SessionId): void => { - if (closing.has(parentSessionId) || !expanded.has(parentSessionId)) return - closing.add(parentSessionId) - const branch = catalogs[parentSessionId] - for (const entry of branch?.entries ?? []) { - visit(entry.id) - } - } - visit(root) - setExpanded(current => new Set([...current].filter(id => !closing.has(id)))) - } - - const toggleBranch = (childSessionId: SessionId): void => { - if (expanded.has(childSessionId)) { - closeBranch(childSessionId) - return - } - setExpanded(current => new Set(current).add(childSessionId)) - refreshProjection(childSessionId) - } - useEffect(() => { - if (!open) return + if (!shown) return const closeOutside = (event: PointerEvent): void => { - if ( - event.target instanceof Node - && !rootRef.current?.contains(event.target) - && !menuRef.current?.contains(event.target) - ) { - changeOpen(false) - } + if (event.target instanceof Node && !rootRef.current?.contains(event.target) && !menuRef.current?.contains(event.target)) close() } - document.addEventListener('pointerdown', closeOutside) const dismiss = (event: globalThis.KeyboardEvent): void => { if (event.key !== 'Escape') return event.preventDefault() - changeOpen(false, menuRef.current?.contains(document.activeElement) === true) + close(menuRef.current?.contains(document.activeElement) === true) } + document.addEventListener('pointerdown', closeOutside) document.addEventListener('keydown', dismiss) return () => { document.removeEventListener('pointerdown', closeOutside) document.removeEventListener('keydown', dismiss) } - }, [open]) + }, [shown]) + useEffect(() => cancelHover, []) - useEffect(() => () => { - cancelHoverOpen() - cancelHoverClose() - }, []) - - const visible = presentedCatalog !== undefined - && (variant === 'switcher' - || props.hasBoardContent || presentedCatalog.state === 'error' - || presentedCatalog.entries.length > 0) - useEffect(() => { - if (visible) return - cancelHoverOpen() - cancelHoverClose() - if (!open) return - pinnedRef.current = false - setOpen(false) - setExpanded(new Set()) - }, [visible, open]) - - if (!visible) return null - - const focusAt = (index: number): void => { - const items = treeItems(menuRef.current) - if (items.length === 0) return - items[(index + items.length) % items.length]?.focus() + const hoverIn = (pointerType: string): void => { + if (pointerType === 'touch') return + cancelHover() + if (shown) return + hoverTimer.current = setTimeout(() => { setOpen('hover') }, 150) } - - const navigate = (event: KeyboardEvent): void => { - if (event.target instanceof Element - && event.target !== triggerRef.current && event.target !== menuRef.current - && event.target.closest('[role="tree"]') === null) return - const items = treeItems(menuRef.current) - const index = items.indexOf(document.activeElement as HTMLElement) - if (event.key === 'Home') { - event.preventDefault() - focusAt(0) - } else if (event.key === 'End') { - event.preventDefault() - focusAt(items.length - 1) - } else if (event.key === 'ArrowDown') { - event.preventDefault() - focusAt(index + 1) - } else if (event.key === 'ArrowUp') { - event.preventDefault() - focusAt(index < 0 ? items.length - 1 : index - 1) - } + const hoverOut = (): void => { + cancelHover() + if (open !== 'hover') return + hoverTimer.current = setTimeout(() => { setOpen('closed') }, 120) } return ( -
- + - - {variant === 'count' && runningCount > 0 && ( - - )} - {open && createPortal(( + {title} + + + {shown && createPortal(( { - if (event.pointerType !== 'touch') cancelHoverClose() - }} - onPointerLeave={scheduleHoverClose} + onPointerEnter={(event) => { if (event.pointerType !== 'touch') cancelHover() }} + onPointerLeave={hoverOut} >
- {hasSharedTasks && ( -
- -

{t('section.title')}

- {progress && {progress}} -
- )} - {hasSharedTasks && presentedCatalog.state === 'ready' && directCount === 0 && ( -

{t('section.empty')}

- )} -
- { changeOpen(false) }} - t={t} - /> -
- {props.renderFooter?.()} + { close() }} + focusFirst={open === 'keyboard'} + t={t} + />
), document.body)} @@ -818,55 +184,9 @@ function CatalogDropdown(props: CatalogDropdownProps) { ) } -/** Full props for the root-session catalog entry in the header actions band. */ -export type SubagentCatalogActionProps = - PropsRuntime<'conversation.session.header.actions'> & InjectFace & PropsLocale - & Omit, 'SessionProvider'> - /** - * Session-header catalog action for root sessions: the descendant count and - * its dropdown after the preset label in the header actions band. Child sessions render nothing - * here — their breadcrumb switcher in the lineage slot owns the same - * navigation. - * @param props - Session standard props plus the catalog actions and translator. - * @returns The count dropdown, or null on a child session. - */ -export function SubagentCatalogAction(props: SubagentCatalogActionProps) { - const addressedChild = props.useSession(snapshot => snapshot.subagent !== null) - const listedChild = props.useSessions(state => state.byId[props.sessionId]?.origin === 'subagent') - if (addressedChild || listedChild) return null - return -} - -/** Bind task-board visibility only in root conversations. */ -function RootCatalogAction({ - sessionId, useProjection, useSessions, useSessionStatus, useFooterAvailable, - openChild, openChildAside, refreshProjection, t, renderSlot, -}: SubagentCatalogActionProps) { - const hasSharedTasks = useProjection('agentTeam', team => team?.enabled === true - && team.tasks.some(task => task.status !== 'deleted')) - const hasTaskFailure = useProjection('agentTeam', team => team?.enabled === true && team.failure !== undefined) - const footerAvailable = useFooterAvailable(value => value) - return ( - renderSlot('conversation.session.header.actions.subagent.footer', {})} - useSessions={useSessions} - useSessionStatus={useSessionStatus} - openChild={openChild} - openChildAside={openChildAside} - refreshProjection={refreshProjection} - t={t} - /> - ) -} - -/** - * Render one breadcrumb title together with its subagent navigation. + * Render one breadcrumb title together with its sibling switcher. The + * Session's own subagents are listed by the Session panel section. * @param props - Breadcrumb title, session standard props, and catalog actions. * @returns A title-and-chevron sibling switcher, or nothing on a root session. */ @@ -883,29 +203,20 @@ export function SubagentHeaderLineage({ const summary = state.byId[lineageSessionId] return summary?.origin === 'subagent' ? summary.parentId : undefined }) - const shared = { useSessions, useSessionStatus, openChild, openChildAside, refreshProjection, t } - // Root sessions carry no breadcrumb; their descendant count lives in the - // header actions band (SubagentCatalogAction). if (parentId === undefined) return null return ( - <> - - {openTitle === undefined && ( - - )} - + ) } diff --git a/packages/client/ui-subagent/src/client/SubagentsSection.tsx b/packages/client/ui-subagent/src/client/SubagentsSection.tsx new file mode 100644 index 0000000000..4c8eced002 --- /dev/null +++ b/packages/client/ui-subagent/src/client/SubagentsSection.tsx @@ -0,0 +1,94 @@ +/** Session panel section listing the current Session's subagents. */ +import { useMemo } from 'react' +import type { HostObservable, InjectFace, PropsLocale, PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type { NS } from './locales.ts' +import type {} from '@deepseek-ai/dsh-client-ui-session-panel/client' +import type {} from '@deepseek-ai/dsh-agent-team/client' +import { CatalogTree, deriveCatalogs, progressOf, type SubagentCatalogInjected, type SubagentCatalogSnapshot } from './SubagentCatalog.tsx' +import type {} from './slots.ts' +import css from './SubagentCatalog.module.css' + +/** Catalog actions and availability of the section's optional footer. */ +export type SubagentsSectionInjected = SubagentCatalogInjected & { + hooks: { + /** Whether the footer currently has a registered contributor. */ + footerAvailable: HostObservable + } +} + +/** Full props of the subagents section. */ +export type SubagentsSectionProps = + PropsRuntime<'conversation.session.panel.section'> + & Omit, 'SessionProvider'> + & InjectFace + & PropsLocale + +/** Full props of the section's progress title control. */ +export type SubagentsProgressProps = + PropsRuntime<'conversation.session.panel.section.actions'> & PropsLocale + +const LOADING: SubagentCatalogSnapshot = { entries: [], state: 'loading', error: null } + +/** + * Render the Session's subagent tree and, when a contributor registered one, + * the footer such as the shared task board. The section renders nothing while + * the Session has no subagents, no failed catalog read, and no board content. + * Opening a subagent closes the panel's overlay. + * @param props - Session hooks, panel owner values, catalog actions, footer renderer, and copy. + * @returns the section body, or null with nothing to show. + */ +export function SubagentsSection({ + sessionId, dismissOverlay, useSessions, useSessionStatus, useProjection, useFooterAvailable, + openChild, openChildAside, refreshProjection, renderSlot, t, +}: SubagentsSectionProps) { + const projections = useSessions(state => state.projectionsBySession) + const summaries = useSessions(state => state.byId) + const statuses = useSessionStatus(value => value) + const catalogs = useMemo(() => deriveCatalogs(projections, summaries, statuses), [projections, summaries, statuses]) + const footerAvailable = useFooterAvailable(value => value) + const hasSharedTasks = useProjection('agentTeam', team => team?.enabled === true + && team.tasks.some(task => task.status !== 'deleted')) + const hasTaskFailure = useProjection('agentTeam', team => team?.enabled === true && team.failure !== undefined) + const boardContent = footerAvailable && (hasSharedTasks || hasTaskFailure) + const catalog = catalogs[sessionId] + const listed = catalog !== undefined && (catalog.state === 'error' || catalog.entries.length > 0) + if (!listed && !boardContent) return null + const presented = catalog ?? LOADING + return ( +
+ {presented.state === 'ready' && presented.entries.length === 0 + ?

{t('section.empty')}

+ : ( + + )} + {footerAvailable && renderSlot('conversation.session.panel.subagents.footer', {})} +
+ ) +} + +/** + * Render the direct subagents' progress beside the section title. + * @param props - Session hooks and copy. + * @returns the progress phrase, or null without subagents. + */ +export function SubagentsProgress({ sessionId, useSessions, useSessionStatus, t }: SubagentsProgressProps) { + const projections = useSessions(state => state.projectionsBySession) + const summaries = useSessions(state => state.byId) + const statuses = useSessionStatus(value => value) + const progress = useMemo(() => { + const catalog = deriveCatalogs(projections, summaries, statuses)[sessionId] + return catalog === undefined ? '' : progressOf(catalog, summaries, t) + }, [projections, summaries, statuses, sessionId, t]) + if (progress === '') return null + return {progress} +} diff --git a/packages/client/ui-subagent/src/client/index.ts b/packages/client/ui-subagent/src/client/index.ts index a84992246d..ccb2f7bf05 100644 --- a/packages/client/ui-subagent/src/client/index.ts +++ b/packages/client/ui-subagent/src/client/index.ts @@ -3,7 +3,9 @@ import type { Context as ClientContext } from '@deepseek-ai/cordis' import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { ComposerChainProps } from '@deepseek-ai/dsh-client-ui-conversation/client' -import { SubagentCatalogAction, SubagentHeaderLineage, type SubagentCatalogInjected, type SubagentCatalogActionInjected } from './SubagentHeaderLineage.tsx' +import { SubagentHeaderLineage } from './SubagentHeaderLineage.tsx' +import type { SubagentCatalogInjected } from './SubagentCatalog.tsx' +import { SubagentsProgress, SubagentsSection, type SubagentsSectionInjected } from './SubagentsSection.tsx' import { SubagentReadOnlyComposer, type SubagentReadOnlyMatch, } from './SubagentReadOnlyComposer.tsx' @@ -12,6 +14,7 @@ import type {} from '@deepseek-ai/dsh-client-locale/client' import type {} from '@deepseek-ai/dsh-client-ui-chat/client' import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' import type {} from '@deepseek-ai/dsh-client-ui-session/client' +import type {} from '@deepseek-ai/dsh-client-ui-session-panel/client' import type {} from '@deepseek-ai/dsh-client-ui-sidebar-right/client' import type {} from '@deepseek-ai/dsh-client-ui-workspace/client' import { en, ja, es, fr, de, ru, pt, NS, zh, type SubagentKey } from './locales.ts' @@ -24,9 +27,9 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { } } -export type { - SubagentCatalogActionProps, SubagentCatalogInjected, SubagentCatalogActionInjected, SubagentHeaderLineageProps, -} from './SubagentHeaderLineage.tsx' +export type { SubagentCatalogInjected } from './SubagentCatalog.tsx' +export type { SubagentHeaderLineageProps } from './SubagentHeaderLineage.tsx' +export type { SubagentsProgressProps, SubagentsSectionInjected, SubagentsSectionProps } from './SubagentsSection.tsx' export type { SubagentReadOnlyComposerProps, SubagentReadOnlyMatch, } from './SubagentReadOnlyComposer.tsx' @@ -44,11 +47,13 @@ function selectReadOnlySubagent(owner: ComposerChainProps): SubagentReadOnlyMatc } /** - * Client plugin body: register the subagent catalog and read-only composer seats. + * Client plugin body: register the breadcrumb switcher, the Session panel + * subagents section, and the read-only composer. * @param ctx - client root context. */ export function apply(ctx: ClientContext): void { ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'ui-subagent: dictionaries') + const t = ctx.locale.bind(NS) ctx.inject(['resources', 'sidebarRightTabs'], (scope) => { registerSidebarChat(scope, ctx.locale.bind(NS)) }) @@ -67,8 +72,8 @@ export function apply(ctx: ClientContext): void { }, }) const footerAvailable = { - getSnapshot: () => ctx.slots.entries('conversation.session.header.actions.subagent.footer').length > 0, - subscribe: (listener: () => void) => ctx.slots.subscribe('conversation.session.header.actions.subagent.footer', listener), + getSnapshot: () => ctx.slots.entries('conversation.session.panel.subagents.footer').length > 0, + subscribe: (listener: () => void) => ctx.slots.subscribe('conversation.session.panel.subagents.footer', listener), } ctx.slots.inject( 'conversation.session.header.lineage', @@ -78,20 +83,25 @@ export function apply(ctx: ClientContext): void { inject: catalogActions, }, SubagentHeaderLineage), ) - ctx.slots.inject( - 'conversation.session.header.actions', - () => ctx.slots.register({ - name: 'conversation.session.header.actions', - id: 'subagent-catalog', - // Between the preset label (-10) and background tasks (20). - order: 10, + ctx.slots.inject('conversation.session.panel.section', function* () { + yield ctx.slots.register({ + name: 'conversation.session.panel.section', + id: 'subagents', + // After change requests (100), before background jobs (300). + order: 200, + label: () => t('section.title'), locale: NS, - inject: (sessionId): SubagentCatalogActionInjected => ({ + inject: (sessionId): SubagentsSectionInjected => ({ ...catalogActions(sessionId), hooks: { footerAvailable }, }), - children: { 'conversation.session.header.actions.subagent.footer': { kind: 'list', scope: 'session' } }, - }, SubagentCatalogAction), - ) + children: { 'conversation.session.panel.subagents.footer': { kind: 'list', scope: 'session' } }, + }, SubagentsSection) + yield ctx.slots.register({ + name: 'conversation.session.panel.section.actions', + key: 'subagents', + locale: NS, + }, SubagentsProgress) + }) ctx.slots.inject( 'conversation.composer', () => ctx.slots.register({ diff --git a/packages/client/ui-subagent/src/client/locales.ts b/packages/client/ui-subagent/src/client/locales.ts index 27a5b61391..6e87f7eef9 100644 --- a/packages/client/ui-subagent/src/client/locales.ts +++ b/packages/client/ui-subagent/src/client/locales.ts @@ -39,10 +39,6 @@ export const zh = { 'activity.inactive': '当前未运行', 'branch.collapse': '收起 {label} 的下级子智能体', 'branch.expand': '展开 {label} 的下级子智能体', - 'count.total.one': '{count} 个子智能体', - 'count.total.other': '{count} 个子智能体', - 'count.running.one': '{count} 个子智能体,正在运行', - 'count.running.other': '{count} 个子智能体,正在运行', 'switcher.aria': '切换子智能体:{title}', 'tree.aria': '子智能体会话', 'open.sidebar': '在侧边栏打开', @@ -90,10 +86,6 @@ export const en: Record = { 'activity.inactive': 'not running', 'branch.collapse': 'Collapse {label} descendants', 'branch.expand': 'Expand {label} descendants', - 'count.total.one': '{count} subagent', - 'count.total.other': '{count} subagents', - 'count.running.one': '{count} subagent running', - 'count.running.other': '{count} subagents running', 'switcher.aria': 'Switch subagent: {title}', 'tree.aria': 'Subagent sessions', 'open.sidebar': 'Open in sidebar', @@ -144,10 +136,6 @@ export const ja = { 'activity.inactive': '停止中', 'branch.collapse': '{label}の子孫を折りたたむ', 'branch.expand': '{label}の子孫を展開', - 'count.total.one': 'サブエージェント{count}件', - 'count.total.other': 'サブエージェント{count}件', - 'count.running.one': '実行中のサブエージェント{count}件', - 'count.running.other': '実行中のサブエージェント{count}件', 'switcher.aria': 'サブエージェントを切り替え: {title}', 'tree.aria': 'サブエージェントセッション', 'open.sidebar': 'サイドバーで開く', @@ -195,10 +183,6 @@ export const es = { 'activity.inactive': 'no corriendo', 'branch.collapse': 'Contraer descendientes de {label}', 'branch.expand': 'Ampliar descendientes de {label}', - 'count.total.one': 'Subagente {count}', - 'count.total.other': 'Subagentes {count}', - 'count.running.one': 'Subagente {count} ejecutándose', - 'count.running.other': 'Subagentes {count} ejecutándose', 'switcher.aria': 'Cambiar subagente: {title}', 'tree.aria': 'Sesiones de subagente', 'open.sidebar': 'Abrir en la barra lateral', @@ -246,10 +230,6 @@ export const fr = { 'activity.inactive': 'ne fonctionne pas', 'branch.collapse': 'Réduire les descendants de {label}', 'branch.expand': 'Développer les descendants de {label}', - 'count.total.one': 'Sous-agent {count}', - 'count.total.other': 'Sous-agents {count}', - 'count.running.one': "Sous-agent {count} en cours d'exécution", - 'count.running.other': "Sous-agents {count} en cours d'exécution", 'switcher.aria': 'Changer de sous-agent : {title}', 'tree.aria': 'Sessions de sous-agents', 'open.sidebar': 'Ouvrir dans la barre latérale', @@ -297,10 +277,6 @@ export const de = { 'activity.inactive': 'läuft nicht', 'branch.collapse': '{label}-Nachkommen reduzieren', 'branch.expand': 'Erweitern Sie {label}-Nachkommen', - 'count.total.one': '{count}-Subagent', - 'count.total.other': '{count}-Subagenten', - 'count.running.one': '{count}-Subagent läuft', - 'count.running.other': '{count} Subagenten laufen', 'switcher.aria': 'Subagent wechseln: {title}', 'tree.aria': 'Subagentensitzungen', 'open.sidebar': 'In der Seitenleiste öffnen', @@ -348,10 +324,6 @@ export const ru = { 'activity.inactive': 'не работает', 'branch.collapse': 'Свернуть потомков {label}', 'branch.expand': 'Развернуть потомков {label}', - 'count.total.one': 'Субагент {count}', - 'count.total.other': 'Субагенты {count}', - 'count.running.one': 'Субагент {count} работает', - 'count.running.other': 'Субагенты {count} работают', 'switcher.aria': 'Переключить субагент: {title}', 'tree.aria': 'Сеансы субагента', 'open.sidebar': 'Открыть в боковой панели', @@ -399,10 +371,6 @@ export const pt = { 'activity.inactive': 'não está funcionando', 'branch.collapse': 'Recolher {label} descendentes', 'branch.expand': 'Expandir {label} descendentes', - 'count.total.one': '{count} subagente', - 'count.total.other': '{count} subagentes', - 'count.running.one': '{count} subagente em execução', - 'count.running.other': '{count} subagentes em execução', 'switcher.aria': 'Alternar subagente: {title}', 'tree.aria': 'Sessões de subagente', 'open.sidebar': 'Abrir na barra lateral', diff --git a/packages/client/ui-subagent/src/client/slots.ts b/packages/client/ui-subagent/src/client/slots.ts index a3e379e62f..2233130f87 100644 --- a/packages/client/ui-subagent/src/client/slots.ts +++ b/packages/client/ui-subagent/src/client/slots.ts @@ -1,9 +1,10 @@ -/** Extension position below the root conversation's subagent catalog. */ +/** Extension position below the Session panel's subagent tree. */ +import type {} from '@deepseek-ai/dsh-client-ui-session-panel/client' declare module '@deepseek-ai/dsh-client-ui-slots' { interface SlotMap { - /** Content below the root Session's subagent tree. */ - 'conversation.session.header.actions.subagent.footer': { + /** Content below the Session's subagent tree in the Session panel, such as the shared task board. */ + 'conversation.session.panel.subagents.footer': { kind: 'list' scope: 'session' } diff --git a/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts b/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts index b5006a277b..a0dd3c56cd 100644 --- a/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts @@ -11,9 +11,11 @@ import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { ComposerChainProps } from '@deepseek-ai/dsh-client-ui-conversation/client' import { apply as applyLocale, inject as localeInject } from '@deepseek-ai/dsh-client-locale/client' -import { - SubagentHeaderLineage, type SubagentCatalogInjected, type SubagentCatalogActionInjected, -} from '../src/client/SubagentHeaderLineage.tsx' +import { SubagentHeaderLineage } from '../src/client/SubagentHeaderLineage.tsx' +import type { SubagentCatalogInjected } from '../src/client/SubagentCatalog.tsx' +import type { SubagentsSectionInjected } from '../src/client/SubagentsSection.tsx' +import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots' +import { en } from '../src/client/locales.ts' import { SubagentReadOnlyComposer, type SubagentReadOnlyMatch, } from '../src/client/SubagentReadOnlyComposer.tsx' @@ -64,7 +66,8 @@ async function provideSlotFaces(ctx: Context): Promise { name: 'root', children: { 'conversation.session.header.lineage': { kind: 'single', scope: 'session' }, - 'conversation.session.header.actions': { kind: 'list', scope: 'session' }, + 'conversation.session.panel.section': { kind: 'list', scope: 'session' }, + 'conversation.session.panel.section.actions': { kind: 'keyed', scope: 'session' }, 'conversation.composer': { kind: 'chain', scope: 'session' }, }, } as never, () => null) @@ -111,14 +114,14 @@ describe('apply', () => { it('keeps the root catalog extension available when optional Sidebar services arrive', async () => { const { ctx } = await fullBench(FAMILY) onTestFinished(() => ctx.fiber.dispose()) - ctx.slots.register({ name: 'conversation.session.header.actions.subagent.footer', id: 'test-content' }, () => null) + ctx.slots.register({ name: 'conversation.session.panel.subagents.footer', id: 'test-content' }, () => null) const registerResource = vi.fn(() => () => {}) const registerTab = vi.fn(() => () => {}) ctx.provide('resources', { register: registerResource } as never) ctx.provide('sidebarRightTabs', { register: registerTab } as never) await vi.waitFor(() => { expect(registerResource).toHaveBeenCalledOnce() }) expect(registerTab).toHaveBeenCalledOnce() - expect(ctx.slots.entries('conversation.session.header.actions.subagent.footer')).toHaveLength(1) + expect(ctx.slots.entries('conversation.session.panel.subagents.footer')).toHaveLength(1) }) it('registers catalog actions and selects read-only subagent composers from session facts', async () => { @@ -146,19 +149,21 @@ describe('apply', () => { { method: 'refreshProjections', args: [sid('parent')] }, ]) - // The root-session catalog seat registers in the actions band with the - // same business face, between the preset label (-10) and background - // tasks (20). - const actionEntry = ctx.slots.entries('conversation.session.header.actions') - .find(entry => entry.options.id === 'subagent-catalog')! - expect(actionEntry.options.order).toBe(10) - const actionProps = (actionEntry.inject as (id: SessionId) => SubagentCatalogActionInjected)(sid('parent')) - const source = actionProps.hooks.footerAvailable + // The Session panel section registers with the same business face, + // after change requests (100) and before background jobs (300), together + // with its progress control beside the title. + const sectionEntry = ctx.slots.entries('conversation.session.panel.section') + .find(entry => entry.options.id === 'subagents')! + expect(sectionEntry.options.order).toBe(200) + expect(resolveSlotLabel(sectionEntry.options.label)).toBe(en['section.title']) + expect(ctx.slots.entries('conversation.session.panel.section.actions').map(entry => entry.options.key)).toEqual(['subagents']) + const sectionProps = (sectionEntry.inject as (id: SessionId) => SubagentsSectionInjected)(sid('parent')) + const source = sectionProps.hooks.footerAvailable const changed = vi.fn() const unsubscribe = source.subscribe(changed) expect(source.getSnapshot()).toBe(false) const remove = ctx.slots.register({ - name: 'conversation.session.header.actions.subagent.footer', id: 'test-footer', + name: 'conversation.session.panel.subagents.footer', id: 'test-footer', }, () => null) expect(source.getSnapshot()).toBe(true) await vi.waitFor(() => { expect(changed).toHaveBeenCalledOnce() }) diff --git a/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx b/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx index 43d2255936..3b39f187f0 100644 --- a/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx +++ b/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx @@ -10,10 +10,8 @@ import type { SubagentAddress, SubagentCatalogEntry } from '@deepseek-ai/dsh-sub import type { TeamProjection, TeamTaskId, TeamTaskView } from '@deepseek-ai/dsh-agent-team/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client' -import { - SubagentCatalogAction, SubagentHeaderLineage, - type SubagentCatalogActionProps, type SubagentHeaderLineageProps, -} from '../src/client/SubagentHeaderLineage.tsx' +import { SubagentHeaderLineage, type SubagentHeaderLineageProps } from '../src/client/SubagentHeaderLineage.tsx' +import { SubagentsProgress, SubagentsSection, type SubagentsProgressProps, type SubagentsSectionProps } from '../src/client/SubagentsSection.tsx' import { SubagentReadOnlyComposer } from '../src/client/SubagentReadOnlyComposer.tsx' import { en, zh } from '../src/client/locales.ts' @@ -30,7 +28,8 @@ const GRANDCHILD = 'grandchild' as SessionId const t: SubagentHeaderLineageProps['t'] = makeTranslate(zh) type HeaderCatalogProps = SubagentHeaderLineageProps - & Pick + & Pick + & { dismissOverlay?: () => void } type CatalogFixtureEntry = Entry extends SubagentCatalogEntry ? Omit & { activity: 'running' | 'inactive' } @@ -183,87 +182,25 @@ function enableTooltips(): void { } /** - * Both header seats as the real header composes them: the breadcrumb switcher - * (child sessions, lineage slot) and the actions-band catalog entry (root - * sessions) — exactly one renders per form. The actions seat sees the same - * session the lineage renders. + * The two surfaces as the real page composes them: the breadcrumb switcher + * (child sessions, lineage slot) and the Session panel section listing the + * Session's own subagents. The section sees the same Session the lineage renders. */ function HeaderCatalog(props: HeaderCatalogProps) { - const actionProps: SubagentCatalogActionProps = { - ...props, sessionId: props.lineageSessionId, + const sectionProps: SubagentsSectionProps = { + ...props, sessionId: props.lineageSessionId, presentation: 'docked', dismissOverlay: props.dismissOverlay ?? vi.fn(), useProjection: ((_key: 'agentTeam', selector: (value: TeamProjection | undefined) => boolean) => - props.useSessions(state => selector(state.projectionsBySession[props.lineageSessionId]?.values.agentTeam))) as SubagentCatalogActionProps['useProjection'], + props.useSessions(state => selector(state.projectionsBySession[props.lineageSessionId]?.values.agentTeam))) as SubagentsSectionProps['useProjection'], } return ( <> - + ) } describe('SubagentHeaderLineage', () => { - it.each([ - { dictionary: zh, total: '2 个子智能体', running: '1 个子智能体,正在运行' }, - { dictionary: en, total: '2 subagents', running: '1 subagent running' }, - ])('keeps the total accessible name separate from the running description: $total', ({ dictionary, total, running }) => { - const input = props(catalog()) - const view = render() - const trigger = screen.getByRole('button', { name: total }) - expect(trigger.textContent).toBe(total) - expect(document.getElementById(trigger.getAttribute('aria-describedby')!)?.textContent).toBe(running) - view.rerender() - expect(screen.getByRole('button', { name: total }).getAttribute('aria-describedby')).toBeNull() - }) - - it('shows a non-collapsible heading with direct-member progress beside shared tasks', () => { - const finished = 'finished' as SessionId - const paused = 'paused' as SessionId - const external = 'external' as SessionId - const entries: CatalogFixture['entries'] = [ - { id: CHILD, mode: 'continuable', label: 'worker', activity: 'running' }, - { id: finished, mode: 'continuable', label: 'finished', activity: 'inactive' }, - { id: paused, mode: 'continuable', label: 'paused', activity: 'inactive' }, - { id: external, mode: 'external', label: 'external', activity: 'running' }, - ] - const summaries: Record = { - [CHILD]: { ...summary(CHILD, 1), running: true, projectionValues: { subagentTiming: { settledMs: 0, lastTurnCompleted: true } } }, - [finished]: { ...summary(finished, 1), projectionValues: { subagentTiming: { settledMs: 0, lastTurnCompleted: true } } }, - [paused]: { ...summary(paused, 1), projectionValues: { subagentTiming: { settledMs: 0, lastTurnCompleted: false } } }, - [external]: { - ...summary(external, 1), running: true, projectionValues: { subagentTiming: { settledMs: 0, lastTurnCompleted: true } }, - }, - } - const input = props(catalog({ entries, team: sharedTeam }), { - [CHILD]: catalog({ entries: [{ id: GRANDCHILD, mode: 'continuable', label: 'nested', activity: 'running' }] }), - }, summaries) - const view = render() - fireEvent.click(screen.getByRole('button', { name: '4 个子智能体' })) - const header = view.container.ownerDocument.querySelector('[data-subagent-section-header]')! - expect(within(header).getByRole('heading', { name: '子智能体' })).toBeTruthy() - expect(within(header).queryByRole('button')).toBeNull() - expect(header.textContent).toBe('子智能体1 已完成\u2002·\u20021 进行中\u2002·\u20021 未运行\u2002·\u20021 外部任务') - fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })) - expect(header.textContent).toContain('1 进行中') - expect(header.textContent).not.toContain('2 进行中') - view.rerender() - expect(header.textContent).toBe('Subagents1 completed\u2002·\u20021 in progress\u2002·\u20021 not running\u2002·\u20021 external') - }) - - it('omits zero progress counts from a completed-only catalog header', () => { - const input = props(catalog({ - team: sharedTeam, entries: [{ id: CHILD, mode: 'continuable', label: 'finished', activity: 'inactive' }], - }), {}, { - [CHILD]: { ...summary(CHILD, 1), projectionValues: { subagentTiming: { settledMs: 0, lastTurnCompleted: true } } }, - }) - render() - fireEvent.click(screen.getByRole('button', { name: '1 个子智能体' })) - const header = document.querySelector('[data-subagent-section-header]')! - expect(header.textContent).toBe('子智能体1 已完成') - }) it.each([ { name: 'absent Team projection', team: undefined, footer: true }, @@ -276,7 +213,6 @@ describe('SubagentHeaderLineage', () => { 'omits section headings from a members-only catalog with $name', ({ team, footer }) => { const input = props(catalog({ ...team === undefined ? {} : { team } })) render( select(footer)} />) - fireEvent.click(screen.getByRole('button', { name: /\d+ 个子智能体$/ })) expect(screen.getByRole('tree')).toBeTruthy() expect(screen.queryByRole('heading')).toBeNull() expect(document.querySelector('[data-subagent-section-header]')).toBeNull() @@ -284,33 +220,11 @@ describe('SubagentHeaderLineage', () => { }, ) - it('shows the description above the Session id and opens the row without a description toggle', () => { - const description = 'Check the construction and all bounds. '.repeat(20).trim() - const input = props(catalog({ - entries: [{ id: CHILD, mode: 'continuable', label: description, activity: 'running' }], - })) - render() - fireEvent.click(screen.getByRole('button', { name: /\d+ 个子智能体$/ })) - const row = screen.getByRole('treeitem', { name: new RegExp(CHILD) }) - const primary = within(row).getByText(description) - const id = within(row).getByText(CHILD) - expect(primary.compareDocumentPosition(id) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() - expect(row.getAttribute('aria-label')).toMatch(/^Check the construction/) - expect(primary.tagName).toBe('SPAN') - expect(primary.getAttribute('aria-expanded')).toBeNull() - expect(primary.querySelector('svg')).toBeNull() - expect(within(row).queryByRole('button', { name: /描述/ })).toBeNull() - fireEvent.click(primary) - expect(input.openChild).toHaveBeenCalledExactlyOnceWith({ parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable' }) - expect(screen.queryByRole('treeitem')).toBeNull() - }) - it.each([undefined, ''])('keeps a single ID line when the creation description is %s', (label) => { const input = props(catalog({ entries: [{ id: CHILD, mode: 'one-shot', ...label === undefined ? {} : { label }, activity: 'running' }], }), {}, { [CHILD]: { ...summary(CHILD, 1), running: true } }) render() - fireEvent.click(screen.getByRole('button', { name: /\d+ 个子智能体$/ })) const row = screen.getByRole('treeitem', { name: new RegExp(CHILD) }) expect(within(row).getAllByText(CHILD)).toHaveLength(1) expect(row.getAttribute('aria-label')).toMatch(new RegExp(`^${CHILD}`)) @@ -326,7 +240,6 @@ describe('SubagentHeaderLineage', () => { ], }), {}, { [CHILD]: { ...summary(CHILD, 1), running: true } }) render() - fireEvent.click(screen.getByRole('button', { name: /\d+ 个子智能体$/ })) const named = screen.getByRole('treeitem', { name: /^Review the diff reviewer/ }) expect(within(named).getByText('Review the diff').compareDocumentPosition(within(named).getByText('reviewer')) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() @@ -339,87 +252,11 @@ describe('SubagentHeaderLineage', () => { expect(input.openChild).toHaveBeenCalledExactlyOnceWith({ parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable' }) }) - it('hides an empty Team entry but keeps shared tasks and errors reachable without children', () => { - const input = props(catalog({ entries: [] })) - const initial = input.useSessions(state => state) - const mode: { enabled: boolean; tasks: TeamTaskView[]; failure?: string } = { enabled: true, tasks: [] } - const values = { ...initial.projectionsBySession[PARENT]!.values, agentTeam: mode } - const current = { - ...input, - useSessions: (select: (snapshot: SessionListState) => T): T => select({ - ...initial, projectionsBySession: { [PARENT]: { state: 'ready', error: null, values } }, - }), - renderSlot: () => mode.tasks.some(task => task.status !== 'deleted') - ?
Tasks
- : mode.failure === undefined ? null :
{mode.failure}
, - } - const view = render() - expect(screen.queryByRole('button')).toBeNull() - mode.tasks = [{ - id: 'task-1' as TeamTaskId, revision: 1, subject: 'Plan work', description: 'Prepare tasks before spawning workers', - status: 'pending', blockedBy: [], writeScopes: [], ready: true, writeScopeWarnings: [], - }] - view.rerender() - fireEvent.click(screen.getByRole('button', { name: '0 个子智能体' })) - const tree = screen.getByRole('tree') - const board = screen.getByRole('region', { name: 'Shared tasks' }) - expect(tree.compareDocumentPosition(board) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() - expect(screen.getByRole('heading', { name: zh['section.title'] })).toBeTruthy() - expect(screen.getByText(zh['section.empty'])).toBeTruthy() - expect(screen.getAllByRole('dialog')).toHaveLength(1) - mode.tasks = [] - view.rerender() - expect(screen.queryByRole('dialog')).toBeNull() - expect(screen.queryByRole('button')).toBeNull() - mode.tasks = [{ ...sharedTask, status: 'deleted' }] - view.rerender() - expect(screen.queryByRole('button')).toBeNull() - expect(screen.queryByText(zh['section.empty'])).toBeNull() - mode.tasks = [] - mode.failure = 'Invalid task record' - view.rerender() - fireEvent.click(screen.getByRole('button', { name: '0 个子智能体' })) - expect(screen.getByRole('dialog')).toBeTruthy() - expect(screen.queryByRole('heading')).toBeNull() - expect(screen.queryByText(zh['section.empty'])).toBeNull() - expect(document.querySelector('[data-subagent-section-header]')).toBeNull() - view.rerender( select(false)} />) - expect(screen.queryByRole('button')).toBeNull() - mode.enabled = false - view.rerender() - expect(screen.queryByRole('dialog')).toBeNull() - expect(screen.queryByRole('button')).toBeNull() - }) - - it.each([false, true])('keeps child navigation without reading or rendering a task board (listed: %s)', (listed) => { - const input = props(catalog({ team: sharedTeam }), {}, listed ? { - [CHILD]: { ...summary(CHILD, 1), origin: 'subagent', parentId: PARENT }, - } : {}, { parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable' }) - const readProjection = vi.fn((): never => { throw new Error('child task-board projection read') }) - const readFooter = vi.fn((): never => { throw new Error('child footer subscription') }) - const renderFooter = vi.fn(() =>
Tasks
) - render(<> - - - ) - fireEvent.click(screen.getByRole('button', { name: /切换子智能体/u })) - expect(screen.getByRole('tree')).toBeTruthy() - expect(screen.queryByRole('region', { name: 'Shared tasks' })).toBeNull() - expect(screen.queryByRole('heading')).toBeNull() - expect(screen.queryByText(zh['section.empty'])).toBeNull() - expect(document.querySelector('[data-subagent-section-header]')).toBeNull() - expect(readProjection).not.toHaveBeenCalled() - expect(readFooter).not.toHaveBeenCalled() - expect(renderFooter).not.toHaveBeenCalled() - }) - it('leaves task-board keys alone and dismisses the shared panel from outside focus', () => { const input = props(catalog()) render(<>