Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(workbench): Activity panel P2 — tool summary v2, visibility toggle, expand cap, JSON dialog (A–E) (#946)
Call Whiteeea007fb6a74
diff --git a/config/v2_config.py b/config/v2_config.pyindex 557ef5104..e2a17655d 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -315,6 +315,12 @@ class UiConfig:# group, and the message mirror streams those rows live. Default off: a strict# no-op — the live stream and transcript stay exactly as they are today.show_agent_activity: bool = False+ # When true (default), the Activity panel renders tool-call rows; when false,+ # only assistant narration rows show. Pure display filter — step counts,+ # durations, and data collection are unaffected. Independent of+ # ``show_agent_activity`` (which gates the whole panel); this only filters rows+ # within it. Default on so the panel keeps today's full detail unless hidden.+ show_tool_calls: bool = Truetrusted_public_origins: List[str] = field(default_factory=list)# Display name appended to the browser tab title ("Avibe - <name>"). When# blank the UI falls back to the read-only ``default_instance_name`` field@@ -586,6 +592,14 @@ class V2Config:ui.show_agent_activity = raw_show_activity.strip().lower() in ("1", "true", "yes", "on")else:ui.show_agent_activity = bool(raw_show_activity)+ # ``show_tool_calls`` defaults true; a string "false"/"0" must coerce to False+ # (``bool("false")`` is True) — same parse as above, applied when a string form+ # is supplied; a missing key keeps the ``UiConfig`` default (True).+ raw_show_tools = ui.show_tool_calls+ if isinstance(raw_show_tools, str):+ ui.show_tool_calls = raw_show_tools.strip().lower() in ("1", "true", "yes", "on")+ else:+ ui.show_tool_calls = bool(raw_show_tools)remote_access_payload = payload.get("remote_access") or {}if not isinstance(remote_access_payload, dict):diff --git a/docs/plans/chat-agent-activity-panel.md b/docs/plans/chat-agent-activity-panel.mdindex 0b6afb723..2da3e5674 100644--- a/docs/plans/chat-agent-activity-panel.md+++ b/docs/plans/chat-agent-activity-panel.md@@ -291,3 +291,78 @@ layout measurement (`offsetHeight >= cap`) gates the fade, so the height behavioitself is CSS-driven — not unit-testable under jsdom, which does no layout. Expandedmode is unchanged: `max-h-[40vh]` + internal scroll already fits content up to itscap. Tail auto-follow (the Transcript scroller) is untouched.++## As-built implementation notes (P2 — items A–E)++Owner-approved iteration package (design signed off 2026-07-20). Frontend-only+except one new display-config field. NO-TOUCH held: IM adapters,+`message_dispatcher`, mirror publish logic, endpoint grouping.++### A — Tool-row summary v2 (3-tier degrade, frontend-only parse)++`ActivityRow.text` for a tool call is the backend `format_toolcall` STRING+(`modules/im/formatters/base_formatter.py`): `` 🔧 `ToolName` `{compact json}` ``.+Names/arg-keys differ per backend (Claude Capitalized `file_path`/`command`; Codex+`bash`/`file_change` with `file`+`type`; OpenCode lowercase `file_path||path`; a+restore path emits `` `name`: `arg` `` with no JSON) — hence the degrade. Pure+helpers in `ui/src/lib/agentActivity.ts`: `parseToolCall` (name + parsed JSON args+or `null`), `toolRecipe` (tier-1 known-tool recipe: command → `$ cmd`; read → dir+muted + basename; edit/write → basename + op badge, op from name or Codex `type`;+web/search/grep → quoted query/URL; task → description — case-insensitive prefix,+paths probe `file_path`→`path`→`file`), `genericChips` (tier-2 ≤3 scalar chips ++overflow), `toolSummary` (tier-3 raw, unchanged). Any parse failure / non-object /+oversize (>20k) → `args: null` → tier 3; `ActivityToolRow` also wraps the parse in+try/catch so nothing can blank a row. Rendered by `ToolSummary` in+`AgentActivityGroup.tsx`. Unit-tested per tier + exception fallback in+`agentActivity.test.ts`.++### B — Tool-row visibility eye toggle + `config.ui.show_tool_calls`++New bool `UiConfig.show_tool_calls` (default **true**), coerced in+`V2Config.from_payload` like `show_agent_activity`. Both runtime serializers are+`__dict__`-based so it rides along automatically and the #939 serializer-coverage+guard is satisfied with no serializer edits (it derives fields from+`fields(UiConfig)`). Display-only → NO `message_mirror` cache / reset hook. The eye+pill (`ToolsEyePill`, eye/eye-off + "Tools"/"工具", icon-only < `sm`) sits in the+running-card header and the expanded-panel header (never the collapsed chip); it+flips the same config the Settings toggle writes (global, cross-device) via+`api.saveConfig({ ui: { show_tool_calls } })`, threaded through the `activity` prop+in `ChatPage`. Filter is the pure `filterActivityRows` (assistant narration ALWAYS+shows; step counts use the unfiltered length). All-filtered placeholders:+expanded → "已隐藏 N 条工具调用"; compact LIVE → "工具调用已隐藏 · 进行中" (never+falls back to ThinkingBubble). Settings row added in `SettingsMessagingPage.tsx`+(`dashboard.showToolCalls*`). i18n en+zh.++### C — Done/history expanded height cap++The expanded settled panel (`ActivityChip`, done/interrupted/failed incl. history)+body is `max-h-[60vh] overflow-y-auto` → height = min(content, ~60vh), opening at+the TOP (natural `scrollTop=0`, no tail-follow). The LIVE running card's expanded+scroller is unchanged (`max-h-[40vh]`, follows tail). Page-level scroll anchoring+untouched.++### D — Inline detail v2 + full-JSON dialog++Row-click detail (`ToolDetail`) renders the SAME parse as A: a kv table (key mono+muted; long/multiline values as wrapping code blocks; `timeout` ms humanized);+parse failure → raw text (unchanged fallback). A "{ } JSON" button opens+`ToolJsonDialog` — the shared `components/ui/dialog` + the lazy `preview-json`+viewer FileViewer uses (zero new deps), scrollable, copy button+(`copyTextToClipboard(JSON.stringify(args,null,2))`), ESC/backdrop close. Parse+failure → dialog shows raw text, still copyable.++### E — Settings copy++`dashboard.showAgentActivityHint` retrimmed per owner dictation (dropped the+Web-only / default-off tail) in en + zh.++### Verification & real-browser residual++`ui` build green; `vitest` full suite green (A/D parse tiers + B filter logic ++existing reducer/wire tests); backend `pytest` green (new+`test_show_tool_calls_defaults_on_and_round_trips` + the #939 serializer-coverage+guard auto-covering the new field); `ruff` clean; changed-file `eslint` clean.+**jsdom does no layout**, so these need the owner's Incus/real-browser pass: the C+60vh scroll feel + top-open, the compact fade-at-cap, the eye-pill live toggle ++cross-device persistence, the D JSON dialog open/copy/close, and the tier-1/2/3+rendering against real per-backend `format_toolcall` output.diff --git a/tests/test_v2_config_platform_registry.py b/tests/test_v2_config_platform_registry.pyindex d4555e57b..fc59d742b 100644--- a/tests/test_v2_config_platform_registry.py+++ b/tests/test_v2_config_platform_registry.py@@ -293,6 +293,27 @@ def test_show_agent_activity_defaults_off_and_round_trips() -> None:assert V2Config.from_payload(payload).ui.show_agent_activity is False, falsey+def test_show_tool_calls_defaults_on_and_round_trips() -> None:+ # Default ON: absent from the ui payload → True (unlike show_agent_activity), and+ # serializes so the Web UI + ChatPage bootstrap read it (display-only filter).+ payload = api.config_to_payload(_base_config())+ assert payload["ui"]["show_tool_calls"] is True++ payload["ui"]["show_tool_calls"] = False+ config = V2Config.from_payload(payload)+ assert config.ui.show_tool_calls is False+ assert api.config_to_payload(config)["ui"]["show_tool_calls"] is False++ # String forms parse explicitly — ``bool("false")`` would be True, which must NOT+ # keep tool rows visible when the user hid them.+ for truthy in ("true", "True", "1", "yes", "on"):+ payload["ui"]["show_tool_calls"] = truthy+ assert V2Config.from_payload(payload).ui.show_tool_calls is True, truthy+ for falsey in ("false", "False", "0", "no", "off", ""):+ payload["ui"]["show_tool_calls"] = falsey+ assert V2Config.from_payload(payload).ui.show_tool_calls is False, falsey++def test_config_payload_includes_vibe_cloud_remote_access() -> None:config = _base_config()config.remote_access.vibe_cloud.enabled = Truediff --git a/ui/src/components/settings/SettingsMessagingPage.tsx b/ui/src/components/settings/SettingsMessagingPage.tsxindex 721d9dd48..60550924e 100644--- a/ui/src/components/settings/SettingsMessagingPage.tsx+++ b/ui/src/components/settings/SettingsMessagingPage.tsx@@ -507,6 +507,25 @@ export const SettingsMessagingPage: React.FC = () => {/>}/>++ <SettingsRow+ title={t('dashboard.showToolCalls')}+ description={t('dashboard.showToolCallsHint')}+ control={+ <ToggleSwitch+ // Default on: absent key reads as enabled (only an explicit false hides).+ enabled={config.ui?.show_tool_calls !== false}+ onClick={() => {+ const next = config.ui?.show_tool_calls === false;+ const nextConfig = {+ ...config,+ ui: { ...(config.ui || {}), show_tool_calls: next },+ };+ void persist(nextConfig, { ui: { show_tool_calls: next } });+ }}+ />+ }+ /></SettingsPanel><SettingsPaneldiff --git a/ui/src/components/workbench/AgentActivityGroup.tsx b/ui/src/components/workbench/AgentActivityGroup.tsxindex 60a5375a2..38d64c406 100644--- a/ui/src/components/workbench/AgentActivityGroup.tsx+++ b/ui/src/components/workbench/AgentActivityGroup.tsx@@ -1,12 +1,17 @@-import { memo, useEffect, useLayoutEffect, useRef, useState } from 'react';+import { lazy, memo, Suspense, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import {AlertTriangle,Bot,+ Braces,+ Check,CheckCircle2,ChevronDown,ChevronRight,CircleSlash,+ Copy,+ Eye,+ EyeOff,FileText,Globe,Loader2,@@ -19,17 +24,30 @@ import type { LucideIcon } from 'lucide-react';import clsx from 'clsx';import { Markdown } from '../ui/markdown';+import { Dialog, DialogContent } from '../ui/dialog';+import { copyTextToClipboard } from '../../lib/utils';import {activityDurationParts,+ filterActivityRows,+ genericChips,+ parseToolCall,parseToolName,toolIconKind,+ toolParams,+ toolRecipe,toolSummary,type ActivityGroup,type ActivityRow,type ActivityStatus,+ type FileOp,+ type ParsedToolCall,type ToolIconKind,} from '../../lib/agentActivity';+// The full-JSON viewer is the same lazy, syntax-highlighted tree FileViewer uses —+// loaded only when a JSON dialog opens (zero new deps; see file-preview.tsx).+const PreviewJson = lazy(() => import('../ui/preview-json'));+// Shared status → icon + tint. ``running`` and ``done`` are mint (success family),// ``failed`` destructive, ``interrupted`` gold — mirrors the design states A–E.const STATUS_TINT: Record<ActivityStatus, string> = {@@ -39,6 +57,15 @@ const STATUS_TINT: Record<ActivityStatus, string> = {interrupted: 'text-gold',};+// Status → chip/header border+background tint (shared by the collapsed chip and the+// expanded panel header so a done panel reads mint, failed destructive, etc.).+const statusChipClasses = (status: ActivityStatus): string =>+ status === 'failed'+ ? 'border-destructive/30 bg-destructive/[0.06]'+ : status === 'interrupted'+ ? 'border-gold/30 bg-gold/[0.07]'+ : 'border-mint/25 bg-mint/[0.07]';+// Static tool-icon table (looked up by kind, never constructed during render).const TOOL_ICON: Record<ToolIconKind, LucideIcon> = {terminal: Terminal,@@ -49,17 +76,232 @@ const TOOL_ICON: Record<ToolIconKind, LucideIcon> = {wrench: Wrench,};+// File operation → badge glyph + i18n key (the mint-soft "+ 新增" style chip in A).+const FILE_OP_META: Record<FileOp, { glyph: string; i18nKey: string; className: string }> = {+ create: { glyph: '+', i18nKey: 'chat.agentActivity.opCreate', className: 'border-mint/30 bg-mint/[0.08] text-mint' },+ modify: { glyph: '~', i18nKey: 'chat.agentActivity.opModify', className: 'border-cyan/30 bg-cyan/[0.08] text-cyan' },+ delete: { glyph: '−', i18nKey: 'chat.agentActivity.opDelete', className: 'border-gold/30 bg-gold/[0.08] text-gold' },+};+const stepLabel = (t: (k: string, o?: Record<string, unknown>) => string, count: number): string =>t(count === 1 ? 'chat.agentActivity.step' : 'chat.agentActivity.steps', { count });-// ----- One tool-call row: icon + tool name (mono) + one-line summary; click to-// reveal the full stored call text (from agent_events.content_json). -----+// ----- B: tool-row visibility pill (eye / eye-off + "Tools"). Global, config-backed+// (``config.ui.show_tool_calls``); the label collapses to icon-only on narrow widths+// (tooltip keeps it). A plain button — never nested inside another button. -----+const ToolsEyePill: React.FC<{ shown: boolean; onToggle: () => void }> = ({ shown, onToggle }) => {+ const { t } = useTranslation();+ const label = t('chat.agentActivity.tools');+ return (+ <button+ type="button"+ onClick={onToggle}+ aria-pressed={shown}+ title={shown ? t('chat.agentActivity.hideTools') : t('chat.agentActivity.showTools')}+ className={clsx(+ 'inline-flex shrink-0 items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] transition-colors',+ shown+ ? 'border-border bg-foreground/[0.04] text-foreground/80 hover:bg-foreground/[0.08]'+ : 'border-border bg-transparent text-muted hover:bg-foreground/[0.05]',+ )}+ >+ {shown ? <Eye className="size-3.5" aria-hidden="true" /> : <EyeOff className="size-3.5" aria-hidden="true" />}+ <span className="hidden sm:inline">{label}</span>+ </button>+ );+};++// ----- D: full-JSON dialog. Reuses the shared Dialog + the lazy JSON viewer; a parse+// failure shows the raw text (still copyable). ESC/backdrop close via Radix. -----+const ToolJsonDialog: React.FC<{ open: boolean; onClose: () => void; parsed: ParsedToolCall }> = ({+ open,+ onClose,+ parsed,+}) => {+ const { t } = useTranslation();+ const [copied, setCopied] = useState(false);+ const copyText = parsed.args ? JSON.stringify(parsed.args, null, 2) : parsed.raw;+ const copy = async () => {+ if (await copyTextToClipboard(copyText)) {+ setCopied(true);+ window.setTimeout(() => setCopied(false), 1600);+ }+ };+ return (+ <Dialog open={open} onOpenChange={(next) => (!next ? onClose() : undefined)}>+ <DialogContent className="max-w-2xl gap-0 overflow-hidden p-0">+ {/* ``DialogContent`` renders its own absolute close X at right-4 top-4;+ reserve right padding so the Copy action never sits under it. */}+ <div className="flex items-center gap-2 border-b border-border py-2.5 pl-4 pr-12">+ <Terminal className="size-3.5 shrink-0 text-muted" aria-hidden="true" />+ <span className="min-w-0 flex-1 truncate font-mono text-[12px] font-medium text-foreground">+ {parsed.name || '—'}+ </span>+ <button+ type="button"+ onClick={copy}+ className="inline-flex shrink-0 items-center gap-1 rounded-md border border-border px-2 py-1 text-[11px] font-medium text-foreground/80 transition-colors hover:bg-foreground/[0.06]"+ >+ {copied ? <Check className="size-3.5 text-mint" /> : <Copy className="size-3.5" />}+ {copied ? t('chat.agentActivity.copied') : t('chat.agentActivity.copy')}+ </button>+ </div>+ <div className="max-h-[60vh] overflow-auto px-2 py-2">+ {parsed.args ? (+ <Suspense+ fallback={<div className="p-3 text-[12px] text-muted">{t('chat.agentActivity.jsonLoading')}</div>}+ >+ <PreviewJson value={parsed.args} />+ </Suspense>+ ) : (+ <pre className="whitespace-pre-wrap break-words px-2 font-mono text-[11px] leading-relaxed text-muted">+ {parsed.raw}+ </pre>+ )}+ </div>+ </DialogContent>+ </Dialog>+ );+};++// ----- A: one-line tool summary. Tier 1 known-tool recipe (command / path / file-op /+// query / description) → tier 2 generic kv chips → tier 3 raw text (today). -----+const ToolSummary: React.FC<{ parsed: ParsedToolCall }> = ({ parsed }) => {+ const { t } = useTranslation();+ const recipe = parsed.args ? toolRecipe(parsed.name, parsed.args) : null;++ if (recipe) {+ switch (recipe.kind) {+ case 'command':+ return (+ <span className="min-w-0 flex-1 truncate font-mono text-[12px] text-foreground/80">+ <span className="text-muted">$ </span>+ {recipe.command}+ </span>+ );+ case 'read':+ return (+ <span className="min-w-0 flex-1 truncate text-[12px]">+ {recipe.dir && <span className="text-muted">{recipe.dir}</span>}+ <span className="font-medium text-foreground">{recipe.base}</span>+ </span>+ );+ case 'fileop': {+ const op = FILE_OP_META[recipe.op];+ return (+ <span className="flex min-w-0 flex-1 items-center gap-1.5 truncate text-[12px]">+ <span className="min-w-0 truncate">+ {recipe.dir && <span className="text-muted">{recipe.dir}</span>}+ <span className="font-medium text-foreground">{recipe.base}</span>+ </span>+ <span+ className={clsx('shrink-0 rounded-full border px-1.5 py-px text-[10px] font-medium', op.className)}+ >+ {op.glyph} {t(op.i18nKey)}+ </span>+ </span>+ );+ }+ case 'query':+ return (+ <span className="min-w-0 flex-1 truncate text-[12px] text-foreground/80">「{recipe.text}」</span>+ );+ case 'text':+ return <span className="min-w-0 flex-1 truncate text-[12px] text-foreground/80">{recipe.text}</span>;+ }+ }++ if (parsed.args) {+ // Tier 2: unknown tool, JSON parsed → generic kv chips + overflow.+ const { chips, overflow } = genericChips(parsed.args);+ if (chips.length === 0 && overflow === 0) return <span className="min-w-0 flex-1" />;+ return (+ <span className="flex min-w-0 flex-1 items-center gap-1 overflow-hidden">+ {chips.map((chip) => (+ <span+ key={chip.key}+ className="inline-flex shrink-0 items-center gap-1 rounded-md border border-border bg-foreground/[0.03] px-1.5 py-px text-[11px]"+ >+ <span className="font-mono text-muted">{chip.key}</span>+ <span className="max-w-[16ch] truncate text-foreground/80">{chip.value}</span>+ </span>+ ))}+ {overflow > 0 && <span className="shrink-0 text-[11px] text-muted">+{overflow}</span>}+ </span>+ );+ }++ // Tier 3: parse failed / no params / oversized → today's raw one-liner.+ const summary = toolSummary(parsed.raw);+ return summary ? (+ <span className="min-w-0 flex-1 truncate text-[12px] text-muted">{summary}</span>+ ) : (+ <span className="min-w-0 flex-1" />+ );+};++// ----- D: expanded inline detail. Same parse as A → a kv table (long/multiline values+// as wrapping code blocks; ``timeout`` humanized); parse failure → raw text. A small+// "{ } JSON" button opens the full-JSON dialog. -----+const ToolDetail: React.FC<{ parsed: ParsedToolCall }> = ({ parsed }) => {+ const { t } = useTranslation();+ const [jsonOpen, setJsonOpen] = useState(false);+ const params = parsed.args ? toolParams(parsed.args) : null;+ return (+ <div className="mx-1.5 mb-1 mt-0.5 rounded-md border border-border bg-foreground/[0.03]">+ <div className="flex items-center gap-2 border-b border-border px-2.5 py-1.5">+ <span className="flex-1 text-[11px] font-medium uppercase tracking-wide text-muted">+ {t('chat.agentActivity.params')}+ </span>+ <button+ type="button"+ onClick={() => setJsonOpen(true)}+ className="inline-flex shrink-0 items-center gap-1 rounded-md border border-border px-1.5 py-0.5 text-[11px] font-medium text-foreground/80 transition-colors hover:bg-foreground/[0.06]"+ >+ <Braces className="size-3" aria-hidden="true" />+ {t('chat.agentActivity.viewJson')}+ </button>+ </div>+ {params && params.length > 0 ? (+ <div className="flex flex-col gap-1 px-2.5 py-2">+ {params.map((p) => (+ <div key={p.key} className={clsx('gap-2 text-[11px]', p.block ? 'flex flex-col' : 'flex items-baseline')}>+ <span className="shrink-0 font-mono text-muted">{p.key}</span>+ {p.block ? (+ <pre className="max-h-56 overflow-auto whitespace-pre-wrap break-words rounded bg-foreground/[0.04] px-2 py-1 font-mono text-[11px] leading-relaxed text-foreground/90">+ {p.value}+ </pre>+ ) : (+ <span className="min-w-0 flex-1 break-words text-foreground/90">{p.value}</span>+ )}+ </div>+ ))}+ </div>+ ) : (+ // Tier 3 (or empty-args): the raw stored call text, unchanged.+ <pre className="max-h-56 overflow-auto whitespace-pre-wrap break-words px-2.5 py-2 font-mono text-[11px] leading-relaxed text-muted">+ {parsed.raw}+ </pre>+ )}+ <ToolJsonDialog open={jsonOpen} onClose={() => setJsonOpen(false)} parsed={parsed} />+ </div>+ );+};++// ----- One tool-call row: icon + tool name (mono) + A summary; click to reveal the D+// detail. The whole parse is wrapped so any unexpected shape degrades to tier 3, never+// blank. -----const ActivityToolRow: React.FC<{ row: ActivityRow }> = ({ row }) => {const { t } = useTranslation();const [open, setOpen] = useState(false);- const name = parseToolName(row.text);- const summary = toolSummary(row.text);- const Icon = TOOL_ICON[toolIconKind(name)];+ const parsed = useMemo<ParsedToolCall>(() => {+ try {+ return parseToolCall(row.text);+ } catch {+ return { name: parseToolName(row.text), args: null, raw: row.text || '' };+ }+ }, [row.text]);+ const Icon = TOOL_ICON[toolIconKind(parsed.name)];return (<div className="flex flex-col"><button@@ -70,22 +312,14 @@ const ActivityToolRow: React.FC<{ row: ActivityRow }> = ({ row }) => {className="group/act flex w-full items-center gap-2 rounded-md px-1.5 py-1 text-left transition-colors hover:bg-foreground/[0.04]"><Icon className="size-3.5 shrink-0 text-muted" aria-hidden="true" />- <span className="shrink-0 font-mono text-[11px] font-medium text-foreground">{name || '—'}</span>- {summary ? (- <span className="min-w-0 flex-1 truncate text-[12px] text-muted">{summary}</span>- ) : (- <span className="min-w-0 flex-1" />- )}+ <span className="shrink-0 font-mono text-[11px] font-medium text-foreground">{parsed.name || '—'}</span>+ <ToolSummary parsed={parsed} /><ChevronRightclassName={clsx('size-3.5 shrink-0 text-muted transition-transform', open && 'rotate-90')}aria-hidden="true"/></button>- {open && (- <pre className="mx-1.5 mb-1 mt-0.5 max-h-56 overflow-auto whitespace-pre-wrap break-words rounded-md border border-border bg-foreground/[0.03] px-2.5 py-2 font-mono text-[11px] leading-relaxed text-muted">- {row.text}- </pre>- )}+ {open && <ToolDetail parsed={parsed} />}</div>);};@@ -109,13 +343,44 @@ const ActivityRowItem = memo(function ActivityRowItem({ row }: { row: ActivityRoreturn row.kind === 'tool_call' ? <ActivityToolRow row={row} /> : <ActivityAssistantRow row={row} />;});-const ActivityRows: React.FC<{ rows: ActivityRow[] }> = ({ rows }) => (- <div className="flex flex-col gap-0.5">- {rows.map((row) => (- <ActivityRowItem key={row.id} row={row} />- ))}- </div>-);+// ``variant`` picks the all-filtered placeholder: the compact LIVE card shows a single+// "hidden · running" line; expanded panels show a "N hidden" count row (and append that+// count as a trailing line when narration rows are also present).+type RowsVariant = 'compact-live' | 'panel';++const ActivityRows: React.FC<{ rows: ActivityRow[]; showToolCalls: boolean; variant: RowsVariant }> = ({+ rows,+ showToolCalls,+ variant,+}) => {+ const { t } = useTranslation();+ const { visible, hiddenTools } = filterActivityRows(rows, showToolCalls);++ if (visible.length === 0) {+ // Everything filtered (all rows were tool calls, no narration).+ if (variant === 'compact-live') {+ return <div className="px-1.5 py-1 text-[12px] italic text-muted">{t('chat.agentActivity.toolsHiddenLive')}</div>;+ }+ return (+ <div className="px-1.5 py-1 text-[12px] italic text-muted">+ {t('chat.agentActivity.toolsHidden', { count: hiddenTools })}+ </div>+ );+ }++ return (+ <div className="flex flex-col gap-0.5">+ {visible.map((row) => (+ <ActivityRowItem key={row.id} row={row} />+ ))}+ {variant === 'panel' && hiddenTools > 0 && (+ <div className="px-1.5 pt-0.5 text-[11px] italic text-muted">+ {t('chat.agentActivity.toolsHidden', { count: hiddenTools })}+ </div>+ )}+ </div>+ );+};// ===== Running card (states A/B): compact fixed-height viewport that never grows,// or an expanded ~40vh internal scroller that auto-follows the tail. =====@@ -129,7 +394,9 @@ export const ActivityCard: React.FC<{startedAtMs: number | null;expanded: boolean;onToggleExpanded: () => void;-}> = ({ rows, startedAtMs, expanded, onToggleExpanded }) => {+ showToolCalls: boolean;+ onToggleTools: () => void;+}> = ({ rows, startedAtMs, expanded, onToggleExpanded, showToolCalls, onToggleTools }) => {const { t } = useTranslation();const [nowMs, setNowMs] = useState(() => Date.now());// Fallback start if the turn's start time is unknown (defensive — the card only@@ -155,7 +422,7 @@ export const ActivityCard: React.FC<{if (expanded && following && scrollRef.current) {scrollRef.current.scrollTop = scrollRef.current.scrollHeight;}- }, [rows.length, expanded, following]);+ }, [rows.length, expanded, following, showToolCalls]);// Measure whether the compact body has hit the cap (content clamped) — drives the// top fade so it only appears once older rows are actually clipped. A ResizeObserver@@ -181,24 +448,28 @@ export const ActivityCard: React.FC<{return (<div className="flex w-full justify-start"><div className="flex w-full max-w-[min(92%,860px)] flex-col overflow-hidden rounded-2xl rounded-tl-md border border-mint/25 bg-background">- {/* Header — click toggles compact ↔ expanded (design interaction rule). */}- <button- type="button"- onClick={onToggleExpanded}- aria-expanded={expanded}- className="flex items-center gap-2 border-b border-mint/20 bg-mint/[0.09] px-3 py-2 text-left"- >- <Loader2 className="size-3.5 shrink-0 animate-spin text-mint" aria-hidden="true" />- <span className="text-[12px] font-medium text-mint">{t('chat.agentActivity.running')}</span>- {rows.length > 0 && (- <span className="text-[12px] text-muted">· {stepLabel(t, rows.length)}</span>- )}- <span className="ml-auto shrink-0 font-mono text-[11px] text-muted">{clock}</span>- <ChevronDown- className={clsx('size-3.5 shrink-0 text-muted transition-transform', expanded && 'rotate-180')}- aria-hidden="true"- />- </button>+ {/* Header — the label/clock region toggles compact ↔ expanded; the eye pill+ (B) is a sibling button (never nested) that flips tool-row visibility. */}+ <div className="flex items-center gap-2 border-b border-mint/20 bg-mint/[0.09] px-3 py-2">+ <button+ type="button"+ onClick={onToggleExpanded}+ aria-expanded={expanded}+ className="flex min-w-0 flex-1 items-center gap-2 text-left"+ >+ <Loader2 className="size-3.5 shrink-0 animate-spin text-mint" aria-hidden="true" />+ <span className="text-[12px] font-medium text-mint">{t('chat.agentActivity.running')}</span>+ {rows.length > 0 && <span className="text-[12px] text-muted">· {stepLabel(t, rows.length)}</span>}+ <span className="ml-auto shrink-0 font-mono text-[11px] text-muted">{clock}</span>+ </button>+ <ToolsEyePill shown={showToolCalls} onToggle={onToggleTools} />+ <button type="button" onClick={onToggleExpanded} aria-label={t('chat.agentActivity.collapse')}>+ <ChevronDown+ className={clsx('size-3.5 shrink-0 text-muted transition-transform', expanded && 'rotate-180')}+ aria-hidden="true"+ />+ </button>+ </div>{expanded ? (<div className="relative"><div@@ -210,7 +481,7 @@ export const ActivityCard: React.FC<{}}className="max-h-[40vh] overflow-y-auto px-1.5 py-1.5 [overflow-anchor:none]">- <ActivityRows rows={rows} />+ <ActivityRows rows={rows} showToolCalls={showToolCalls} variant="panel" /></div>{!following && (<button@@ -238,7 +509,7 @@ export const ActivityCard: React.FC<{className="relative flex flex-col justify-end overflow-hidden px-1.5 py-1.5"style={{ maxHeight: COMPACT_CAP_PX }}>- <ActivityRows rows={rows} />+ <ActivityRows rows={rows} showToolCalls={showToolCalls} variant="compact-live" />{compactAtCap && (<div className="pointer-events-none absolute inset-x-0 top-0 h-8 bg-gradient-to-b from-background to-transparent" />)}@@ -250,7 +521,7 @@ export const ActivityCard: React.FC<{};// ===== Collapsed chip (states C/D/E): a one-line summary that hugs the reply from-// above; click to expand the stored rows (lazy-loaded by the parent). =====+// above; click to expand into a full panel (header + scrollable rows, capped ~60vh). =====export const ActivityChip: React.FC<{group: ActivityGroup;expanded: boolean;@@ -258,7 +529,9 @@ export const ActivityChip: React.FC<{error?: boolean;onToggle: () => void;onRetry?: () => void;-}> = ({ group, expanded, loading, error, onToggle, onRetry }) => {+ showToolCalls: boolean;+ onToggleTools: () => void;+}> = ({ group, expanded, loading, error, onToggle, onRetry, showToolCalls, onToggleTools }) => {const { t } = useTranslation();const StatusIcon =group.status === 'failed' ? AlertTriangle : group.status === 'interrupted' ? CircleSlash : CheckCircle2;@@ -278,56 +551,75 @@ export const ActivityChip: React.FC<{label = `${t('chat.agentActivity.label')} · ${stepLabel(t, group.steps)}${duration ? ` · ${duration}` : ''}`;}- return (- <div className="flex w-full justify-start">- <div className="flex w-full max-w-[min(92%,860px)] flex-col gap-1">+ const body = loading ? (+ <div className="flex items-center justify-center py-3 text-muted">+ <Loader2 className="size-4 animate-spin" />+ </div>+ ) : group.rows && group.rows.length > 0 ? (+ <ActivityRows rows={group.rows} showToolCalls={showToolCalls} variant="panel" />+ ) : error ? (+ // A transient detail-fetch failure — show a retry, not a misleading "no+ // activity", since the summary already counted steps.+ <div className="flex items-center justify-between gap-2 px-1.5 py-2 text-[12px] text-muted">+ <span>{t('chat.agentActivity.loadFailed')}</span>+ {onRetry && (<buttontype="button"- onClick={onToggle}- aria-expanded={expanded}- title={expanded ? t('chat.agentActivity.collapse') : t('chat.agentActivity.expand')}- className={clsx(- 'inline-flex w-fit max-w-full items-center gap-1.5 rounded-full border px-2.5 py-1 text-[11px] transition-colors',- group.status === 'failed'- ? 'border-destructive/30 bg-destructive/[0.06] hover:bg-destructive/[0.1]'- : group.status === 'interrupted'- ? 'border-gold/30 bg-gold/[0.07] hover:bg-gold/[0.12]'- : 'border-mint/25 bg-mint/[0.07] hover:bg-mint/[0.12]',- )}+ onClick={onRetry}+ className="shrink-0 rounded-md border border-border px-2 py-0.5 text-[11px] font-medium text-cyan transition-colors hover:bg-surface-2">- <StatusIcon className={clsx('size-3.5 shrink-0', STATUS_TINT[group.status])} aria-hidden="true" />- <span className="min-w-0 truncate font-medium text-foreground/90">{label}</span>- <ChevronDown- className={clsx('size-3.5 shrink-0 text-muted transition-transform', expanded && 'rotate-180')}- aria-hidden="true"- />+ {t('chat.agentActivity.retry')}</button>- {expanded && (- <div className="w-full rounded-xl rounded-tl-md border border-border bg-foreground/[0.02] px-1.5 py-1.5">- {loading ? (- <div className="flex items-center justify-center py-3 text-muted">- <Loader2 className="size-4 animate-spin" />- </div>- ) : group.rows && group.rows.length > 0 ? (- <ActivityRows rows={group.rows} />- ) : error ? (- // A transient detail-fetch failure — show a retry, not a misleading- // "no activity", since the summary already counted steps.- <div className="flex items-center justify-between gap-2 px-1.5 py-2 text-[12px] text-muted">- <span>{t('chat.agentActivity.loadFailed')}</span>- {onRetry && (- <button- type="button"- onClick={onRetry}- className="shrink-0 rounded-md border border-border px-2 py-0.5 text-[11px] font-medium text-cyan transition-colors hover:bg-surface-2"- >- {t('chat.agentActivity.retry')}- </button>- )}- </div>- ) : (- <div className="px-1.5 py-2 text-[12px] text-muted">{t('chat.agentActivity.empty')}</div>+ )}+ </div>+ ) : (+ <div className="px-1.5 py-2 text-[12px] text-muted">{t('chat.agentActivity.empty')}</div>+ );++ return (+ <div className="flex w-full justify-start">+ <div className="flex w-full max-w-[min(92%,860px)] flex-col gap-1">+ {!expanded ? (+ <button+ type="button"+ onClick={onToggle}+ aria-expanded={false}+ title={t('chat.agentActivity.expand')}+ className={clsx(+ 'inline-flex w-fit max-w-full items-center gap-1.5 rounded-full border px-2.5 py-1 text-[11px] transition-colors',+ group.status === 'failed'+ ? 'border-destructive/30 bg-destructive/[0.06] hover:bg-destructive/[0.1]'+ : group.status === 'interrupted'+ ? 'border-gold/30 bg-gold/[0.07] hover:bg-gold/[0.12]'+ : 'border-mint/25 bg-mint/[0.07] hover:bg-mint/[0.12]',)}+ >+ <StatusIcon className={clsx('size-3.5 shrink-0', STATUS_TINT[group.status])} aria-hidden="true" />+ <span className="min-w-0 truncate font-medium text-foreground/90">{label}</span>+ <ChevronDown className="size-3.5 shrink-0 text-muted" aria-hidden="true" />+ </button>+ ) : (+ // Expanded: a full panel card. Header bar carries the status/label (toggles+ // collapse), the B eye pill, and a collapse chevron; body is the ~60vh+ // capped, top-anchored scroller (C).+ <div className="w-full overflow-hidden rounded-xl rounded-tl-md border border-border bg-foreground/[0.02]">+ <div className={clsx('flex items-center gap-2 border-b px-3 py-2', statusChipClasses(group.status))}>+ <button+ type="button"+ onClick={onToggle}+ aria-expanded+ title={t('chat.agentActivity.collapse')}+ className="flex min-w-0 flex-1 items-center gap-1.5 text-left"+ >+ <StatusIcon className={clsx('size-3.5 shrink-0', STATUS_TINT[group.status])} aria-hidden="true" />+ <span className="min-w-0 truncate text-[12px] font-medium text-foreground/90">{label}</span>+ </button>+ <ToolsEyePill shown={showToolCalls} onToggle={onToggleTools} />+ <button type="button" onClick={onToggle} aria-label={t('chat.agentActivity.collapse')}>+ <ChevronDown className="size-3.5 shrink-0 rotate-180 text-muted" aria-hidden="true" />+ </button>+ </div>+ <div className="max-h-[60vh] overflow-y-auto px-1.5 py-1.5">{body}</div></div>)}</div>diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex dfa4abbe4..5bf13dd90 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -349,6 +349,18 @@ export const ChatPage: React.FC = () => {const [liveRows, setLiveRows] = useState<ActivityRow[]>([]);const [liveStartedAt, setLiveStartedAt] = useState<number | null>(null);const [activityCardExpanded, setActivityCardExpanded] = useState(false);+ // Tool-row visibility (``config.ui.show_tool_calls``, default on). Global ++ // cross-device: the eye pill and the Settings toggle write the same config field.+ const [showToolCalls, setShowToolCalls] = useState(true);+ const toggleToolCalls = useCallback(() => {+ setShowToolCalls((prev) => {+ const next = !prev;+ // Optimistic; persist the minimal ui patch (save_config deep-merges). A failed+ // save leaves the local flag as the user set it for this session.+ void api.saveConfig({ ui: { show_tool_calls: next } }).catch(() => {});+ return next;+ });+ }, [api]);const [expandedActivity, setExpandedActivity] = useState<Record<string, boolean>>({});const [loadingActivity, setLoadingActivity] = useState<Record<string, boolean>>({});// Groups whose lazy detail fetch failed — the chip shows a retry affordance@@ -843,6 +855,8 @@ export const ChatPage: React.FC = () => {const activityEnabled = Boolean(bootstrap.config?.ui?.show_agent_activity);setShowAgentActivity(activityEnabled);showAgentActivityRef.current = activityEnabled;+ // Default on: only an explicit ``false`` hides tool rows.+ setShowToolCalls(bootstrap.config?.ui?.show_tool_calls !== false);// Merge (not replace) so a row that arrived over the stream during the// load isn't clobbered; the session-change reset keeps prior sessions out.setMessages((prev) => mergeById(bootstrap.messages, prev));@@ -1862,6 +1876,8 @@ export const ChatPage: React.FC = () => {error: activityError,onToggleGroup: toggleActivityGroup,onRetryGroup: loadActivityDetail,+ showToolCalls,+ onToggleTools: toggleToolCalls,}}footer={sessionId ? (@@ -2476,6 +2492,8 @@ interface TranscriptProps {error: Record<string, boolean>;onToggleGroup: (group: ActivityGroup) => void;onRetryGroup: (group: ActivityGroup) => void;+ showToolCalls: boolean;+ onToggleTools: () => void;};// Rendered at the end of the scroll content, after the last message (e.g. the in-scroll// vault request cards). Part of the timeline, so it scrolls with the conversation.@@ -2608,6 +2626,8 @@ const Transcript: React.FC<TranscriptProps> = ({error={!!activity.error[group.id]}onToggle={() => activity.onToggleGroup(group)}onRetry={() => activity.onRetryGroup(group)}+ showToolCalls={activity.showToolCalls}+ onToggleTools={activity.onToggleTools}/>) : null;const empty = messages.length === 0 && !working;@@ -2888,6 +2908,8 @@ const Transcript: React.FC<TranscriptProps> = ({startedAtMs={activity.liveStartedAt}expanded={activity.cardExpanded}onToggleExpanded={activity.onToggleCard}+ showToolCalls={activity.showToolCalls}+ onToggleTools={activity.onToggleTools}/>) : showThinking ? (<ThinkingBubble session={session} />diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex a4ea5734b..d18ffa08f 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1729,7 +1729,9 @@"chatMessageFontSize": "Chat Message Font Size","chatMessageFontSizeHint": "Font size for user and agent message bubbles in the Web UI chat","showAgentActivity": "Show Agent Activity",- "showAgentActivityHint": "Show the agent's intermediate steps — interim messages and tool calls — live in Web chat, collapsing to a one-line summary when the reply arrives. Web chat only; does not affect IM platforms. Default off.",+ "showAgentActivityHint": "Show the agent's intermediate steps live in chat — interim messages and tool-call summaries; collapses automatically when the work finishes.",+ "showToolCalls": "Show Tool Calls",+ "showToolCallsHint": "Show tool-call rows inside the Activity panel — turn off to keep only the agent's narration. Step counts and durations are unaffected. Also toggleable live from the panel's Tools control.","slackLinkPreviews": "Suppress Slack Link Previews","slackLinkPreviewsHint": "Disable Slack URL and media preview cards for messages sent by Avibe","allowedChannels": "Allowed Groups",@@ -2381,7 +2383,20 @@"retry": "Retry","durationMin": "{{minutes}}m {{seconds}}s","durationSec": "{{seconds}}s",- "empty": "No activity recorded for this turn."+ "empty": "No activity recorded for this turn.",+ "tools": "Tools",+ "showTools": "Show tool calls",+ "hideTools": "Hide tool calls",+ "toolsHidden": "{{count}} tool calls hidden",+ "toolsHiddenLive": "Tool calls hidden · running",+ "params": "Parameters",+ "viewJson": "JSON",+ "jsonLoading": "Loading…",+ "copy": "Copy",+ "copied": "Copied",+ "opCreate": "created",+ "opModify": "modified",+ "opDelete": "deleted"},"queue": {"title": "Queued · {{count}}",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex a03ef5c98..be10bf019 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1729,7 +1729,9 @@"chatMessageFontSize": "聊天消息字号","chatMessageFontSizeHint": "Web UI 聊天页里用户和 Agent 消息气泡的文字大小","showAgentActivity": "显示 Agent 执行过程",- "showAgentActivityHint": "在 Web 聊天中实时显示 Agent 的中间步骤——中间消息与工具调用摘要,回复到达后自动折叠为一行摘要。仅 Web 聊天,不影响 IM 平台。默认关闭。",+ "showAgentActivityHint": "在聊天中实时显示 Agent 的中间步骤 —— 中间消息与工具调用摘要,工作完成后自动折叠。",+ "showToolCalls": "显示工具调用",+ "showToolCallsHint": "在执行过程面板中显示工具调用行 —— 关闭后仅保留 Agent 的叙述文字。步数与耗时不受影响。也可在面板的「工具」按钮上实时切换。","slackLinkPreviews": "关闭 Slack 链接预览","slackLinkPreviewsHint": "关闭 Avibe 发送到 Slack 的 URL 和媒体预览卡片","allowedChannels": "允许的群组",@@ -2381,7 +2383,20 @@"retry": "重试","durationMin": "{{minutes}} 分 {{seconds}} 秒","durationSec": "{{seconds}} 秒",- "empty": "本轮没有执行过程记录。"+ "empty": "本轮没有执行过程记录。",+ "tools": "工具",+ "showTools": "显示工具调用",+ "hideTools": "隐藏工具调用",+ "toolsHidden": "已隐藏 {{count}} 条工具调用",+ "toolsHiddenLive": "工具调用已隐藏 · 进行中",+ "params": "参数",+ "viewJson": "JSON",+ "jsonLoading": "加载中…",+ "copy": "复制",+ "copied": "已复制",+ "opCreate": "新增",+ "opModify": "修改",+ "opDelete": "删除"},"queue": {"title": "排队中 · {{count}}",diff --git a/ui/src/lib/agentActivity.test.ts b/ui/src/lib/agentActivity.test.tsindex 5d886a472..ed4126c56 100644--- a/ui/src/lib/agentActivity.test.ts+++ b/ui/src/lib/agentActivity.test.ts@@ -4,13 +4,18 @@ import type { WorkbenchMessage } from '../context/ApiContext';import {activityDurationParts,activityRowFromMessage,+ filterActivityRows,+ genericChips,groupFromWire,initialLiveActivity,isActivityMessageType,liveActivityReducer,+ parseToolCall,parseToolName,shouldShowRunningCard,toolIconKind,+ toolParams,+ toolRecipe,toolSummary,type ActivityRow,} from './agentActivity';@@ -56,6 +61,164 @@ describe('toolIconKind', () => {});});+describe('parseToolCall (tier gating: extract name + JSON args, or null)', () => {+ it('extracts args from each backend shape', () => {+ // Claude (Capitalized, file_path)+ expect(parseToolCall('🔧 `Bash` `{"command":"pdftotext report.pdf"}`').args).toEqual({+ command: 'pdftotext report.pdf',+ });+ // Codex bundles result fields into bash args+ expect(+ parseToolCall('🔧 `bash` `{"command":"ls","status":"completed","exit_code":0,"output":"a"}`').args,+ ).toEqual({ command: 'ls', status: 'completed', exit_code: 0, output: 'a' });+ // OpenCode (lowercase, path)+ expect(parseToolCall('🔧 `read` `{"path":"foo.py"}`').args).toEqual({ path: 'foo.py' });+ expect(parseToolCall('🔧 `Bash` `{"command":"x"}`').name).toBe('Bash');+ });++ it('yields args:null (→ tier 3) for no-params / malformed / non-object / oversized / restore-path', () => {+ expect(parseToolCall('🔧 `TodoWrite`').args).toBeNull(); // no params+ expect(parseToolCall('🔧 `Bash` `{"command":}`').args).toBeNull(); // malformed JSON+ expect(parseToolCall('🔧 `Bash` `[1,2,3]`').args).toBeNull(); // JSON but not an object+ expect(parseToolCall('`bash`: `ls -la`').args).toBeNull(); // OpenCode restore path (no JSON)+ const huge = `🔧 \`Bash\` \`{"command":"${'x'.repeat(20001)}"}\``;+ expect(parseToolCall(huge).args).toBeNull(); // oversized → raw+ });++ it('never throws on arbitrary garbage (exception → tier 3)', () => {+ expect(() => parseToolCall('')).not.toThrow();+ expect(() => parseToolCall('not a tool call at all')).not.toThrow();+ expect(parseToolCall('🔧 `X` `{"a":"\\u00e4' /* truncated */).args).toBeNull();+ });+});++describe('toolRecipe (tier 1: known-tool recipes, backend-agnostic)', () => {+ it('bash/shell family → command (Claude/Codex/OpenCode)', () => {+ expect(toolRecipe('Bash', { command: 'pwd' })).toEqual({ kind: 'command', command: 'pwd' });+ expect(toolRecipe('bash', { command: 'ls', status: 'completed', exit_code: 0 })).toEqual({+ kind: 'command',+ command: 'ls',+ });+ });++ it('read/list family → dir muted + basename (probes file_path → path → file)', () => {+ expect(toolRecipe('Read', { file_path: '研报/中金_CATL_2026展望.pdf' })).toEqual({+ kind: 'read',+ dir: '研报/',+ base: '中金_CATL_2026展望.pdf',+ });+ expect(toolRecipe('read', { path: 'notes.md' })).toEqual({ kind: 'read', dir: '', base: 'notes.md' });+ expect(toolRecipe('LS', { path: '/tmp/dir/' })).toEqual({ kind: 'read', dir: '/tmp/', base: 'dir' });+ });++ it('edit/write/apply → fileop with an operation derived from name or Codex type', () => {+ expect(toolRecipe('Write', { file_path: 'new.txt', content: 'x' })).toEqual({+ kind: 'fileop',+ dir: '',+ base: 'new.txt',+ op: 'create',+ });+ expect(toolRecipe('Edit', { file_path: 'a.ts', old_string: 'a', new_string: 'b' })).toMatchObject({+ kind: 'fileop',+ op: 'modify',+ });+ expect(toolRecipe('file_change', { file: 'x.py', type: 'created' })).toMatchObject({ op: 'create' });+ expect(toolRecipe('file_change', { file: 'x.py', type: 'deleted' })).toMatchObject({ op: 'delete' });+ expect(toolRecipe('file_change', { file: 'x.py', type: 'modified' })).toMatchObject({ op: 'modify' });+ });++ it('web/search/fetch/grep → quoted query or URL', () => {+ expect(toolRecipe('WebSearch', { query: 'CATL 2026' })).toEqual({ kind: 'query', text: 'CATL 2026' });+ expect(toolRecipe('WebFetch', { url: 'https://x.com', prompt: 'p' })).toEqual({+ kind: 'query',+ text: 'https://x.com',+ });+ expect(toolRecipe('Grep', { pattern: 'consolidated' })).toEqual({ kind: 'query', text: 'consolidated' });+ });++ it('task/agent → description', () => {+ expect(toolRecipe('Task', { description: 'read two reports', prompt: '…' })).toEqual({+ kind: 'text',+ text: 'read two reports',+ });+ });++ it('returns null for unknown tools and for a known tool missing its primary arg (→ tier 2/3)', () => {+ expect(toolRecipe('custom_tool', { path: '/tmp/x.csv', rows: 1200 })).toBeNull();+ expect(toolRecipe('Bash', { description: 'no command here' })).toBeNull();+ expect(toolRecipe('Read', {})).toBeNull();+ });+});++describe('genericChips (tier 2: unknown tool, JSON parses)', () => {+ it('shows up to 3 short scalar params + an overflow count for the rest', () => {+ const { chips, overflow } = genericChips({+ path: '/tmp/x.csv',+ rows: 1200,+ format: 'csv',+ mode: 'r',+ note: 'extra',+ });+ expect(chips).toEqual([+ { key: 'path', value: '/tmp/x.csv' },+ { key: 'rows', value: '1200' },+ { key: 'format', value: 'csv' },+ ]);+ expect(overflow).toBe(2);+ });++ it('truncates long values and counts non-scalar params as overflow', () => {+ const { chips, overflow } = genericChips({ big: 'y'.repeat(100), obj: { a: 1 }, ok: 'v' });+ expect(chips.find((c) => c.key === 'big')?.value.endsWith('…')).toBe(true);+ expect(chips.some((c) => c.key === 'obj')).toBe(false); // object is not chip-worthy+ expect(overflow).toBe(1); // the object param+ });+});++describe('toolParams (D: inline detail kv table)', () => {+ it('orders kv, flags long/multiline as block, humanizes timeout ms', () => {+ const params = toolParams({+ command: 'pdftotext -layout report.pdf -',+ workdir: '.',+ timeout: 70000,+ });+ expect(params.map((p) => p.key)).toEqual(['command', 'workdir', 'timeout']);+ expect(params.find((p) => p.key === 'workdir')).toEqual({ key: 'workdir', value: '.', block: false });+ expect(params.find((p) => p.key === 'timeout')?.value).toBe('70000 (70s)');+ expect(toolParams({ patch: 'line1\nline2' })[0].block).toBe(true);+ });+});++describe('filterActivityRows (B: eye toggle filters tool rows only)', () => {+ const rows: ActivityRow[] = [+ { id: 'a1', kind: 'assistant', text: 'narration', created_at: 't1' },+ { id: 't1', kind: 'tool_call', text: '🔧 `Bash` `{"command":"ls"}`', created_at: 't2' },+ { id: 't2', kind: 'tool_call', text: '🔧 `Read` `{"file_path":"x"}`', created_at: 't3' },+ ];++ it('shows everything when tools are enabled', () => {+ expect(filterActivityRows(rows, true)).toEqual({ visible: rows, hiddenTools: 0 });+ });++ it('hides tool rows but keeps assistant narration, counting the hidden tools', () => {+ const { visible, hiddenTools } = filterActivityRows(rows, false);+ expect(visible.map((r) => r.id)).toEqual(['a1']);+ expect(hiddenTools).toBe(2);+ });++ it('everything filtered when there is no narration (drives the placeholder)', () => {+ const toolsOnly = rows.filter((r) => r.kind === 'tool_call');+ const { visible, hiddenTools } = filterActivityRows(toolsOnly, false);+ expect(visible).toEqual([]);+ expect(hiddenTools).toBe(2);+ });++ it('never hides assistant rows even with tools off', () => {+ const narrationOnly = rows.filter((r) => r.kind === 'assistant');+ expect(filterActivityRows(narrationOnly, false)).toEqual({ visible: narrationOnly, hiddenTools: 0 });+ });+});+describe('activityDurationParts', () => {it('splits into whole-second minutes/seconds (units applied via i18n)', () => {expect(activityDurationParts(45000)).toEqual({ minutes: 0, seconds: 45 });@@ -187,7 +350,7 @@ describe('liveActivityReducer (generation invariant)', () => {});it('rehydrate_for_gen fills only an empty buffer of the current generation', () => {- let s = liveActivityReducer(initialLiveActivity(), { type: 'turn_start' });+ const s = liveActivityReducer(initialLiveActivity(), { type: 'turn_start' });const gen = s.gen;const hydrated = liveActivityReducer(s, {type: 'rehydrate_for_gen',diff --git a/ui/src/lib/agentActivity.ts b/ui/src/lib/agentActivity.tsindex cb4a1cd33..78ae8e8c4 100644--- a/ui/src/lib/agentActivity.ts+++ b/ui/src/lib/agentActivity.ts@@ -205,3 +205,160 @@ export const activityDurationParts = (const totalSeconds = Math.round(ms / 1000);return { minutes: Math.floor(totalSeconds / 60), seconds: totalSeconds % 60 };};++// ===== Tool-call summary v2 (A/D): 3-tier degrade, frontend-only parse =====+// ``ActivityRow.text`` for a tool call is the backend ``format_toolcall`` STRING —+// ``🔧 `ToolName` `{compact json}` `` (base_formatter.py). Tool names and arg keys+// differ per backend (Claude Capitalized `file_path`/`command`; Codex `bash`/+// `file_change` with `file`+`type`; OpenCode lowercase `file_path||path`; an+// OpenCode restore path emits `` `name`: `arg` `` with no JSON), which is why we+// degrade: tier 1 known-tool recipes → tier 2 generic kv chips → tier 3 raw text.+// Everything here is a PURE function of the row text; any parse failure/oversize+// yields ``args: null`` (→ tier 3), and the component wraps calls in try/catch so+// an unexpected shape can never blank a row.++// A parsed params object is only trusted below this size (compact JSON is tiny;+// anything larger is treated as oversized → tier 3 raw).+const MAX_TOOL_PARAMS_BYTES = 20000;++export type ParsedToolCall = {+ name: string;+ args: Record<string, unknown> | null; // parsed JSON object, or null → tier 3+ raw: string; // full original row text (tier-3 render + JSON-dialog fallback)+};++// Extract the tool name + the embedded compact-JSON params object (when present and+// parseable) from a ``format_toolcall`` string. Never throws.+export const parseToolCall = (text: string): ParsedToolCall => {+ const raw = text || '';+ const name = parseToolName(raw);+ let args: Record<string, unknown> | null = null;+ try {+ let firstLine = raw.split('\n')[0].replace(TOOL_GLYPH, '').trim();+ // Drop the leading tool-name token (backtick-wrapped or bare word).+ const nameToken = firstLine.match(/^`[^`]+`\s*/);+ firstLine = nameToken ? firstLine.slice(nameToken[0].length) : firstLine.replace(/^\S+\s*/, '');+ firstLine = firstLine.trim();+ // Unwrap a single surrounding backtick pair (format_toolcall wraps the JSON).+ const wrapped = firstLine.match(/^`([\s\S]*)`$/);+ const candidate = (wrapped ? wrapped[1] : firstLine).trim();+ if (candidate.startsWith('{') && candidate.length <= MAX_TOOL_PARAMS_BYTES) {+ const parsed: unknown = JSON.parse(candidate);+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {+ args = parsed as Record<string, unknown>;+ }+ }+ } catch {+ args = null;+ }+ return { name, args, raw };+};++const splitPath = (p: string): { dir: string; base: string } => {+ const clean = p.replace(/\/+$/, '');+ const idx = clean.lastIndexOf('/');+ return idx >= 0 ? { dir: clean.slice(0, idx + 1), base: clean.slice(idx + 1) } : { dir: '', base: clean };+};++export type FileOp = 'create' | 'modify' | 'delete';++// Tier-1 render intents (keyed on known tool-name prefix + expected arg presence).+export type ToolRecipe =+ | { kind: 'command'; command: string } // bash/shell → ``$ <command>``+ | { kind: 'read'; dir: string; base: string } // read/list → dir muted + base bold+ | { kind: 'fileop'; dir: string; base: string; op: FileOp } // edit/write → base + op badge+ | { kind: 'query'; text: string } // web/search/fetch → quoted query / URL+ | { kind: 'text'; text: string }; // task/agent → description++const asStr = (v: unknown): string | undefined => (typeof v === 'string' && v.length > 0 ? v : undefined);++const fileOpFrom = (name: string, args: Record<string, unknown>): FileOp => {+ const type = (asStr(args.type) || '').toLowerCase();+ if (/^(creat|add)/.test(type)) return 'create';+ if (/^(delet|remov)/.test(type)) return 'delete';+ if (/^(modif|edit|updat|chang)/.test(type)) return 'modify';+ if (name.startsWith('write') || name.startsWith('create')) return 'create';+ if (name.startsWith('delete') || name.startsWith('remove')) return 'delete';+ return 'modify'; // edit/update/apply/patch/notebook default+};++// Known-tool recipe (tier 1). Returns null for unknown tools or a known tool whose+// expected primary arg is absent → the caller falls back to tier 2 (generic chips).+// Backend-agnostic: name matching is case-insensitive and by PREFIX, and paths probe+// ``file_path`` → ``path`` → ``file`` to cover Claude/OpenCode/Codex divergence.+export const toolRecipe = (name: string, args: Record<string, unknown>): ToolRecipe | null => {+ const n = (name || '').trim().toLowerCase();+ const starts = (prefixes: string[]) => prefixes.some((p) => n.startsWith(p));+ const path = asStr(args.file_path) ?? asStr(args.filePath) ?? asStr(args.path) ?? asStr(args.file);+ const command = asStr(args.command) ?? asStr(args.cmd);++ if (starts(['bash', 'shell', 'exec', 'run', 'sh', 'zsh', 'terminal', 'command'])) {+ return command != null ? { kind: 'command', command } : null;+ }+ if (starts(['write', 'edit', 'create', 'update', 'apply', 'patch', 'notebook', 'multiedit', 'file_change', 'filechange'])) {+ return path != null ? { kind: 'fileop', ...splitPath(path), op: fileOpFrom(n, args) } : null;+ }+ if (starts(['read', 'cat', 'open', 'view', 'list', 'ls', 'glob', 'find'])) {+ return path != null ? { kind: 'read', ...splitPath(path) } : null;+ }+ if (starts(['web', 'fetch', 'http', 'browse', 'url', 'search', 'grep'])) {+ const query = asStr(args.query) ?? asStr(args.url) ?? asStr(args.pattern);+ return query != null ? { kind: 'query', text: query } : null;+ }+ if (starts(['task', 'agent', 'mcp', 'sub', 'delegate'])) {+ const desc = asStr(args.description) ?? asStr(args.prompt);+ return desc != null ? { kind: 'text', text: desc } : null;+ }+ return null;+};++export type ToolChip = { key: string; value: string };++const truncateValue = (s: string, max = 48): string => (s.length > max ? `${s.slice(0, max - 1)}…` : s);++// A chip-worthy value is a single-line scalar (string/number/bool). Length does NOT+// disqualify — long values are shown truncated (per spec); only multiline strings and+// objects/arrays are excluded (they still count toward the overflow tally).+const isChipScalar = (v: unknown): boolean =>+ (typeof v === 'string' && !v.includes('\n')) || typeof v === 'number' || typeof v === 'boolean';++// Tier-2 generic chips: up to ``max`` scalar params (long values truncated) + an+// overflow count for every remaining param (including the non-chip-worthy ones).+export const genericChips = (+ args: Record<string, unknown>,+ max = 3,+): { chips: ToolChip[]; overflow: number } => {+ const entries = Object.entries(args);+ const chips: ToolChip[] = [];+ for (const [key, value] of entries) {+ if (chips.length >= max) break;+ if (isChipScalar(value)) chips.push({ key, value: truncateValue(String(value)) });+ }+ return { chips, overflow: Math.max(0, entries.length - chips.length) };+};++// B: tool-row visibility filter. Assistant narration ALWAYS shows; only tool_call+// rows are hidden. Pure so the component's placeholder logic is unit-testable and the+// step counts (which use the unfiltered length) stay independent of display.+export const filterActivityRows = (+ rows: ActivityRow[],+ showToolCalls: boolean,+): { visible: ActivityRow[]; hiddenTools: number } => {+ if (showToolCalls) return { visible: rows, hiddenTools: 0 };+ const visible = rows.filter((r) => r.kind !== 'tool_call');+ return { visible, hiddenTools: rows.length - visible.length };+};++export type ToolParam = { key: string; value: string; block: boolean };++// Full ordered kv params for the inline detail table (D). Long/multiline values are+// flagged ``block`` (rendered as a wrapping code block); ``timeout`` in ms is+// humanized inline (e.g. ``70000`` → ``70000 (70s)``) mirroring the design.+export const toolParams = (args: Record<string, unknown>): ToolParam[] =>+ Object.entries(args).map(([key, value]) => {+ let text = typeof value === 'string' ? value : JSON.stringify(value);+ if (key === 'timeout' && typeof value === 'number' && value >= 1000) {+ text = `${value} (${Math.round(value / 1000)}s)`;+ }+ return { key, value: text, block: text.includes('\n') || text.length > 60 };+ });