🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(cc): task tools + AskUserQuestion freeform note + waitingForHuman topic status (#14870)
Arvin Xu929d23a94eb7
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.jsonindex b9e64bd9b6d..cbbe90effa7 100644--- a/locales/en-US/plugin.json+++ b/locales/en-US/plugin.json@@ -90,6 +90,14 @@"builtins.lobe-agent.title": "Lobe Agent","builtins.lobe-claude-code.agent.instruction": "Instruction","builtins.lobe-claude-code.agent.result": "Result",+ "builtins.lobe-claude-code.task.createLabel": "Creating task: ",+ "builtins.lobe-claude-code.task.getLabel": "Inspecting task #{{taskId}}",+ "builtins.lobe-claude-code.task.listLabel": "Listing tasks",+ "builtins.lobe-claude-code.task.updateCompleted": "Completed",+ "builtins.lobe-claude-code.task.updateDeleted": "Deleted",+ "builtins.lobe-claude-code.task.updateInProgress": "Started",+ "builtins.lobe-claude-code.task.updateLabel": "Updating task #{{taskId}}",+ "builtins.lobe-claude-code.task.updatePending": "Reset","builtins.lobe-claude-code.todoWrite.allDone": "All tasks completed","builtins.lobe-claude-code.todoWrite.currentStep": "Current step","builtins.lobe-claude-code.todoWrite.todos": "Todos",diff --git a/locales/en-US/tool.json b/locales/en-US/tool.jsonindex 964bf0e16d0..00e60f875da 100644--- a/locales/en-US/tool.json+++ b/locales/en-US/tool.json@@ -40,6 +40,14 @@"agentMarketplace.render.alreadyInLibraryTag": "Already in library","agentMarketplace.render.alreadyInLibrary_one": "{{count}} already in library","agentMarketplace.render.alreadyInLibrary_other": "{{count}} already in library",+ "claudeCode.askUserQuestion.escape.back": "Back to options",+ "claudeCode.askUserQuestion.escape.enter": "Or type directly",+ "claudeCode.askUserQuestion.escape.placeholder": "Type your answer here…",+ "claudeCode.askUserQuestion.multiSelectTag": "(multi-select)",+ "claudeCode.askUserQuestion.skip": "Skip",+ "claudeCode.askUserQuestion.submit": "Submit",+ "claudeCode.askUserQuestion.timeExpired": "Time expired — using option 1 of each question.",+ "claudeCode.askUserQuestion.timeRemaining": "Time remaining: {{time}} · unanswered questions default to option 1 on timeout.","codeInterpreter-legacy.error": "Execution Error","codeInterpreter-legacy.executing": "Executing...","codeInterpreter-legacy.files": "Files:",diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.jsonindex 5dbd77660b6..6dedd091303 100644--- a/locales/zh-CN/plugin.json+++ b/locales/zh-CN/plugin.json@@ -90,6 +90,14 @@"builtins.lobe-agent.title": "Lobe Agent","builtins.lobe-claude-code.agent.instruction": "指令","builtins.lobe-claude-code.agent.result": "结果",+ "builtins.lobe-claude-code.task.createLabel": "正在创建任务:",+ "builtins.lobe-claude-code.task.getLabel": "查看任务 #{{taskId}}",+ "builtins.lobe-claude-code.task.listLabel": "正在列出任务",+ "builtins.lobe-claude-code.task.updateCompleted": "已完成",+ "builtins.lobe-claude-code.task.updateDeleted": "已删除",+ "builtins.lobe-claude-code.task.updateInProgress": "开始执行",+ "builtins.lobe-claude-code.task.updateLabel": "正在更新任务 #{{taskId}}",+ "builtins.lobe-claude-code.task.updatePending": "重置为待办","builtins.lobe-claude-code.todoWrite.allDone": "全部任务已完成","builtins.lobe-claude-code.todoWrite.currentStep": "当前步骤","builtins.lobe-claude-code.todoWrite.todos": "待办",diff --git a/locales/zh-CN/tool.json b/locales/zh-CN/tool.jsonindex 46729ddd478..8604cad9f05 100644--- a/locales/zh-CN/tool.json+++ b/locales/zh-CN/tool.json@@ -40,6 +40,14 @@"agentMarketplace.render.alreadyInLibraryTag": "已在库中","agentMarketplace.render.alreadyInLibrary_one": "{{count}} 个已在库中","agentMarketplace.render.alreadyInLibrary_other": "{{count}} 个已在库中",+ "claudeCode.askUserQuestion.escape.back": "返回选项",+ "claudeCode.askUserQuestion.escape.enter": "或直接输入",+ "claudeCode.askUserQuestion.escape.placeholder": "在此输入你的回复…",+ "claudeCode.askUserQuestion.multiSelectTag": "(多选)",+ "claudeCode.askUserQuestion.skip": "跳过",+ "claudeCode.askUserQuestion.submit": "提交",+ "claudeCode.askUserQuestion.timeExpired": "已超时——将使用每题的选项 1。",+ "claudeCode.askUserQuestion.timeRemaining": "剩余时间:{{time}} · 超时后未作答题目默认选项 1。","codeInterpreter-legacy.error": "执行出错","codeInterpreter-legacy.executing": "正在执行...","codeInterpreter-legacy.files": "文件:",diff --git a/packages/builtin-tool-claude-code/src/client/Inspector/Task.tsx b/packages/builtin-tool-claude-code/src/client/Inspector/Task.tsxnew file mode 100644index 00000000000..91abe890f57--- /dev/null+++ b/packages/builtin-tool-claude-code/src/client/Inspector/Task.tsx@@ -0,0 +1,271 @@+'use client';++import { inspectorTextStyles, shinyTextStyles } from '@lobechat/shared-tool-ui/styles';+import type { BuiltinInspectorProps } from '@lobechat/types';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { memo, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import {+ ClaudeCodeApiName,+ type TaskCreateArgs,+ type TaskListArgs,+ type TaskUpdateArgs,+} from '../../types';++const RING_SIZE = 14;+const RING_STROKE = 2;+const RING_RADIUS = (RING_SIZE - RING_STROKE) / 2;+const RING_CIRCUM = 2 * Math.PI * RING_RADIUS;++const styles = createStaticStyles(({ css, cssVar }) => ({+ chip: css`+ overflow: hidden;+ flex-shrink: 1;++ min-width: 0;+ margin-inline-start: 4px;+ padding-block: 1px;+ padding-inline: 8px;+ border-radius: 999px;++ color: ${cssVar.colorText};+ text-overflow: ellipsis;+ white-space: nowrap;++ background: ${cssVar.colorFillSecondary};+ `,+ ring: css`+ transform: rotate(-90deg);+ flex-shrink: 0;+ margin-inline-end: 6px;+ `,+ ringProgress: css`+ transition:+ stroke-dashoffset 240ms ease,+ stroke 240ms ease;+ `,+ ringTrack: css`+ stroke: ${cssVar.colorFillSecondary};+ `,+}));++/**+ * Items shape the CC adapter emits on `pluginState.todos` — normalized+ * `todo|processing|completed` alphabet. Mirrors `StepContextTodos` from+ * `@lobechat/types` but inlined to keep this package light.+ *+ * `id` is optional: legacy TodoWrite-derived snapshots are positional and+ * have no stable id, while the Task* tools (CC 2.1.143+) populate it with+ * the CC-server-assigned numeric id so per-call inspectors can look up+ * subject text by `args.taskId`.+ */+interface TaskPluginStateItem {+ id?: string;+ status: 'todo' | 'processing' | 'completed';+ text: string;+}++interface TaskPluginState {+ todos?: {+ items?: TaskPluginStateItem[];+ updatedAt?: string;+ };+}++interface TaskStats {+ completed: number;+ inProgress?: TaskPluginStateItem;+ total: number;+}++const computeStats = (items: TaskPluginStateItem[]): TaskStats => ({+ completed: items.filter((item) => item.status === 'completed').length,+ inProgress: items.find((item) => item.status === 'processing'),+ total: items.length,+});++interface ProgressRingProps {+ stats: TaskStats;+}++const ProgressRing = memo<ProgressRingProps>(({ stats }) => {+ const { completed, total } = stats;+ const ratio = total > 0 ? completed / total : 0;+ const allDone = total > 0 && completed === total;+ const color = allDone ? cssVar.colorSuccess : cssVar.colorInfo;++ return (+ <svg className={styles.ring} height={RING_SIZE} width={RING_SIZE}>+ <circle+ className={styles.ringTrack}+ cx={RING_SIZE / 2}+ cy={RING_SIZE / 2}+ fill="none"+ r={RING_RADIUS}+ strokeWidth={RING_STROKE}+ />+ <circle+ className={styles.ringProgress}+ cx={RING_SIZE / 2}+ cy={RING_SIZE / 2}+ fill="none"+ r={RING_RADIUS}+ stroke={color}+ strokeDasharray={RING_CIRCUM}+ strokeDashoffset={RING_CIRCUM * (1 - ratio)}+ strokeLinecap="round"+ strokeWidth={RING_STROKE}+ />+ </svg>+ );+});++ProgressRing.displayName = 'ClaudeCodeTaskProgressRing';++type TaskInspectorArgs = TaskCreateArgs | TaskUpdateArgs | TaskListArgs;++/**+ * Unified inspector chip for CC 2.1.143+ task tools (TaskCreate / TaskUpdate /+ * TaskList). Reads the **adapter-synthesized** `pluginState.todos` snapshot —+ * not per-call args — because each individual TaskCreate / TaskUpdate carries+ * only a delta. The full list is only knowable after `applyTaskToolResult`+ * folds the delta into the running accumulator and emits a fresh snapshot+ * (see `claudeCode.ts:applyTaskToolResult`).+ *+ * Per-tool overrides for the inspector chip:+ * - TaskCreate: the per-call action is "added one task" — the cumulative+ * progress ring would read like `0/3` after three creates, which buries+ * the actual new-task signal. Always show `Creating task: <subject>` from+ * args, regardless of pluginState. Render-side, TaskCreate is also+ * deliberately NOT registered in `ClaudeCodeRenders` — the chip carries+ * the meaningful info; the default tool card handles args / result.+ * - TaskUpdate / TaskList: the cumulative aggregate IS the meaningful+ * signal (status flipped to completed = progress, list = snapshot), so+ * keep the progress-ring + label + count chip that matches+ * {@link TodoWriteInspector}.+ *+ * Streaming / loading fallbacks read args:+ * - TaskUpdate → "Updating task #N"+ * - TaskList → "Listing tasks"+ */+export const TaskInspector = memo<BuiltinInspectorProps<TaskInspectorArgs, TaskPluginState>>(+ ({ apiName, args, partialArgs, pluginState, isArgumentsStreaming, isLoading }) => {+ const { t } = useTranslation('plugin');++ const items = pluginState?.todos?.items ?? [];+ const stats = useMemo(() => computeStats(items), [items]);+ const allDone = stats.total > 0 && stats.completed === stats.total;++ // TaskCreate: chip always identifies the task being added, not the+ // accumulated todo count. Drop the aggregate path entirely so the+ // chip stays informative whether or not pluginState is populated yet.+ if (apiName === ClaudeCodeApiName.TaskCreate) {+ const subject = ((args || partialArgs) as TaskCreateArgs | undefined)?.subject;+ const text = subject+ ? `${t('builtins.lobe-claude-code.task.createLabel')}${subject}`+ : t('builtins.lobe-claude-code.task.createLabel');+ return (+ <div+ className={cx(+ inspectorTextStyles.root,+ (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,+ )}+ >+ {text}+ </div>+ );+ }++ // TaskUpdate with a `status` flip: the per-call signal IS that status+ // change ("Completed: Read hosts"), which the aggregate `Todos: x/y` chip+ // buries. Resolve subject from pluginState by id (CC adapter emits id on+ // every Task* synthesis, see `synthesizeTaskPluginState`); `args.subject`+ // is the resume-gap fallback when the snapshot hasn't been built yet.+ // Cryptic `#N` is intentionally NOT user-facing — fall back to the bare+ // verb if subject is missing (rare; happens before first pluginState).+ // TaskUpdate without `status` (metadata-only edit) falls through to the+ // aggregate path — no single-word verb describes those.+ if (apiName === ClaudeCodeApiName.TaskUpdate) {+ const updateArgs = (args || partialArgs) as TaskUpdateArgs | undefined;+ const status = updateArgs?.status;+ if (status) {+ const taskId = updateArgs?.taskId;+ const subject =+ (taskId ? items.find((item) => item.id === taskId)?.text : undefined) ??+ updateArgs?.subject;+ const verb =+ status === 'deleted'+ ? t('builtins.lobe-claude-code.task.updateDeleted')+ : status === 'completed'+ ? t('builtins.lobe-claude-code.task.updateCompleted')+ : status === 'in_progress'+ ? t('builtins.lobe-claude-code.task.updateInProgress')+ : t('builtins.lobe-claude-code.task.updatePending');+ return (+ <div+ className={cx(+ inspectorTextStyles.root,+ (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,+ )}+ >+ {subject ? `${verb}: ${subject}` : verb}+ </div>+ );+ }+ }++ // No pluginState yet (args streaming or tool_use → tool_result gap):+ // fall back to a per-tool descriptive label sourced from args. Matches+ // TodoWriteInspector's `isArgumentsStreaming && stats.total === 0` branch.+ if (stats.total === 0) {+ const resolvedArgs = (args || partialArgs) as TaskInspectorArgs | undefined;+ const fallback = (() => {+ if (apiName === ClaudeCodeApiName.TaskUpdate) {+ const taskId = (resolvedArgs as TaskUpdateArgs | undefined)?.taskId;+ return taskId+ ? t('builtins.lobe-claude-code.task.updateLabel', { taskId })+ : t('builtins.lobe-claude-code.todoWrite.todos');+ }+ return t('builtins.lobe-claude-code.task.listLabel');+ })();+ return (+ <div+ className={cx(+ inspectorTextStyles.root,+ (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,+ )}+ >+ {fallback}+ </div>+ );+ }++ const label = stats.inProgress+ ? t('builtins.lobe-claude-code.todoWrite.currentStep')+ : allDone+ ? t('builtins.lobe-claude-code.todoWrite.allDone')+ : t('builtins.lobe-claude-code.todoWrite.todos');++ const detail = stats.inProgress+ ? stats.inProgress.text+ : !allDone+ ? `${stats.completed}/${stats.total}`+ : undefined;++ return (+ <div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>+ <ProgressRing stats={stats} />+ <span>{label}</span>+ {detail && (+ <>+ <span>:</span>+ <span className={styles.chip}>{detail}</span>+ </>+ )}+ </div>+ );+ },+);++TaskInspector.displayName = 'ClaudeCodeTaskInspector';diff --git a/packages/builtin-tool-claude-code/src/client/Inspector/TaskGet.tsx b/packages/builtin-tool-claude-code/src/client/Inspector/TaskGet.tsxnew file mode 100644index 00000000000..712192a8cc2--- /dev/null+++ b/packages/builtin-tool-claude-code/src/client/Inspector/TaskGet.tsx@@ -0,0 +1,34 @@+'use client';++import { inspectorTextStyles, shinyTextStyles } from '@lobechat/shared-tool-ui/styles';+import type { BuiltinInspectorProps } from '@lobechat/types';+import { cx } from 'antd-style';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import type { TaskGetArgs } from '../../types';++/**+ * TaskGet is read-only — the adapter doesn't synthesize `pluginState.todos`+ * for it (only TaskCreate / TaskUpdate / TaskList mutate the accumulator).+ * Render just enough to identify which task was inspected.+ */+export const TaskGetInspector = memo<BuiltinInspectorProps<TaskGetArgs>>(+ ({ args, partialArgs, isArgumentsStreaming, isLoading }) => {+ const { t } = useTranslation('plugin');+ const taskId = args?.taskId ?? partialArgs?.taskId;++ return (+ <div+ className={cx(+ inspectorTextStyles.root,+ (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,+ )}+ >+ {t('builtins.lobe-claude-code.task.getLabel', { taskId: taskId ?? '' })}+ </div>+ );+ },+);++TaskGetInspector.displayName = 'ClaudeCodeTaskGetInspector';diff --git a/packages/builtin-tool-claude-code/src/client/Inspector/index.ts b/packages/builtin-tool-claude-code/src/client/Inspector/index.tsindex 5f3a087ac69..3c1ac8847a9 100644--- a/packages/builtin-tool-claude-code/src/client/Inspector/index.ts+++ b/packages/builtin-tool-claude-code/src/client/Inspector/index.ts@@ -15,6 +15,8 @@ import { MonitorInspector } from './Monitor';import { ReadInspector } from './Read';import { ScheduleWakeupInspector } from './ScheduleWakeup';import { SkillInspector } from './Skill';+import { TaskInspector } from './Task';+import { TaskGetInspector } from './TaskGet';import { TaskOutputInspector } from './TaskOutput';import { TaskStopInspector } from './TaskStop';import { TodoWriteInspector } from './TodoWrite';@@ -48,8 +50,16 @@ export const ClaudeCodeInspectors = {[ClaudeCodeApiName.Read]: ReadInspector,[ClaudeCodeApiName.ScheduleWakeup]: ScheduleWakeupInspector,[ClaudeCodeApiName.Skill]: SkillInspector,+ // CC 2.1.143+ task tools — TaskCreate / TaskUpdate / TaskList share the+ // same inspector because they're driven by the adapter-synthesized+ // `pluginState.todos` snapshot (the per-call args are deltas, not state).+ // TaskGet is read-only with no pluginState, so it gets its own minimal chip.+ [ClaudeCodeApiName.TaskCreate]: TaskInspector,+ [ClaudeCodeApiName.TaskGet]: TaskGetInspector,+ [ClaudeCodeApiName.TaskList]: TaskInspector,[ClaudeCodeApiName.TaskOutput]: TaskOutputInspector,[ClaudeCodeApiName.TaskStop]: TaskStopInspector,+ [ClaudeCodeApiName.TaskUpdate]: TaskInspector,[ClaudeCodeApiName.TodoWrite]: TodoWriteInspector,[ClaudeCodeApiName.ToolSearch]: ToolSearchInspector,[ClaudeCodeApiName.WebFetch]: WebFetchInspector,diff --git a/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion.tsx b/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion.tsxindex 22321764876..32a211d04a6 100644--- a/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion.tsx+++ b/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion.tsx@@ -1,10 +1,11 @@'use client';import type { BuiltinInterventionProps } from '@lobechat/types';-import { Button, Flexbox, Icon, Tabs, Text } from '@lobehub/ui';+import { Button, Flexbox, Icon, Tabs, Text, TextArea } from '@lobehub/ui';import { createStaticStyles, cx } from 'antd-style';-import { Check, Send, X } from 'lucide-react';+import { ArrowLeft, Check, PenLine, Send, X } from 'lucide-react';import { memo, useCallback, useEffect, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';import { useConversationStore } from '@/features/Conversation/store';import { dataSelectors } from '@/features/Conversation/store/slices/data/selectors';@@ -12,6 +13,16 @@ import { useChatStore } from '@/store/chat';import type { AskUserQuestionArgs, AskUserQuestionItem } from '../../types';+/**+ * Sentinel key the bridge formatter (`AskUserMcpServer.formatAnswerForCC`)+ * looks for to detect escape-mode replies. When present, the payload is just+ * `{ __freeform__: <text> }` (multi-choice picks are intentionally absent)+ * and the text is forwarded to CC verbatim — no `User answers:` framing.+ * Matches the convention `lobe-user-interaction` already uses for its own+ * "Or type directly" escape hatch.+ */+const FREEFORM_PAYLOAD_KEY = '__freeform__';+/*** Server-side bridge timeout (matches `AskUserMcpServer.pendingTimeoutMs`).* Not strictly synchronized — server is authoritative — but keeps the on-screen@@ -30,6 +41,23 @@ const formatRemaining = (msLeft: number): string => {};const styles = createStaticStyles(({ css, cssVar }) => ({+ // "Or type directly" / "Back to options" link — slim secondary text that+ // sits alongside Skip in the action bar; matches the+ // `lobe-user-interaction` escape-toggle styling so the two flows feel+ // like the same control.+ escapeLink: css`+ cursor: pointer;++ display: inline-flex;+ gap: 4px;+ align-items: center;++ transition: color 0.12s ease;++ &:hover {+ color: ${cssVar.colorText};+ }+ `,// Card sits inline with the chat — no surrounding panel chrome. Hover// tints the row so the stack reads as clickable; selection swaps to a// filled `colorPrimaryBg` so the pick is visually weighty.@@ -133,6 +161,7 @@ interface QuestionPanelProps {}const QuestionPanel = memo<QuestionPanelProps>(({ question, answer, disabled, onToggle }) => {+ const { t } = useTranslation('tool');const isOptionSelected = (label: string): boolean =>question.multiSelect ? Array.isArray(answer) && answer.includes(label) : answer === label;@@ -142,7 +171,7 @@ const QuestionPanel = memo<QuestionPanelProps>(({ question, answer, disabled, on{question.header && <Text type="secondary">{question.header}</Text>}{question.multiSelect && (<Text fontSize={12} type="secondary">- (multi-select)+ {t('claudeCode.askUserQuestion.multiSelectTag')}</Text>)}</Flexbox>@@ -189,6 +218,7 @@ QuestionPanel.displayName = 'CCAskUserQuestionPanel';*/const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestionArgs>>(({ args, messageId, onInteractionAction }) => {+ const { t } = useTranslation('tool');const questions = args?.questions ?? [];// Persisted draft (survives unmount / HMR / refresh) — read from the tool@@ -201,9 +231,27 @@ const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestio});const setInterventionDraft = useChatStore((s) => s.setInterventionDraft);- const [answers, setAnswers] = useState<Record<string, string | string[]>>(- () => persistedDraft ?? {},- );+ // Persisted draft may carry both form picks and escape-mode text under+ // `__freeform__`. Split them so `answers` only contains per-question+ // picks and `escapeText` owns the freeform string — otherwise a stale+ // `__freeform__` key would leak into the form-mode submit payload.+ const [answers, setAnswers] = useState<Record<string, string | string[]>>(() => {+ if (!persistedDraft) return {};+ const { [FREEFORM_PAYLOAD_KEY]: _, ...rest } = persistedDraft;+ return rest;+ });+ // Escape-mode mirrors `lobe-user-interaction`'s "Or type directly"+ // toggle — options and freeform are mutually exclusive, not stacked.+ // Persisted text under the `__freeform__` key restores the user back+ // into escape mode on remount; an empty draft starts in form mode.+ const [escapeText, setEscapeText] = useState<string>(() => {+ const v = persistedDraft?.[FREEFORM_PAYLOAD_KEY];+ return typeof v === 'string' ? v : '';+ });+ const [escapeActive, setEscapeActive] = useState<boolean>(() => {+ const v = persistedDraft?.[FREEFORM_PAYLOAD_KEY];+ return typeof v === 'string' && v.length > 0;+ });const [submitting, setSubmitting] = useState(false);const [activeTab, setActiveTab] = useState<string>(() => {// Resume on the first unanswered question so coming back lands the user@@ -240,7 +288,8 @@ const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestio} else {next = { ...prev, [q.question]: label };}- // Persist to pluginState so the picks survive remount / refresh.+ // Persist picks only. Form mode is mutually exclusive with escape+ // mode, so we never co-mingle `__freeform__` into a form-mode draft.setInterventionDraft(messageId, next);// Single-select auto-advance: if there's a next unanswered question,@@ -280,7 +329,47 @@ const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestio[onInteractionAction, submitting],);- const handleSubmit = useCallback(() => submitWith(answers), [answers, submitWith]);+ const handleEscapeTextChange = useCallback(+ (value: string) => {+ setEscapeText(value);+ // Only persist the freeform text while escape mode is the active UI.+ // Stale `__freeform__` entries left in the draft would re-arm escape+ // mode on the next mount, which is not what the user signalled.+ setInterventionDraft(messageId, {+ ...answers,+ [FREEFORM_PAYLOAD_KEY]: value,+ });+ },+ [answers, messageId, setInterventionDraft],+ );++ const handleEscapeToggle = useCallback(() => {+ setEscapeActive((prev) => {+ const next = !prev;+ // Mirror the toggle into the draft: turning escape ON saves the+ // current text (so a refresh resumes here); turning it OFF strips+ // `__freeform__` so the next mount lands back in form mode.+ if (next) {+ setInterventionDraft(messageId, {+ ...answers,+ [FREEFORM_PAYLOAD_KEY]: escapeText,+ });+ } else {+ setInterventionDraft(messageId, answers);+ }+ return next;+ });+ }, [answers, escapeText, messageId, setInterventionDraft]);++ const handleSubmit = useCallback(() => {+ if (escapeActive) {+ // Escape mode is mutually exclusive with picks — send the text alone+ // under `__freeform__`. Bridge formatter forwards it to CC verbatim.+ void submitWith({ [FREEFORM_PAYLOAD_KEY]: escapeText.trim() });+ } else {+ void submitWith(answers);+ }+ }, [answers, escapeActive, escapeText, submitWith]);const handleSkip = useCallback(async () => {if (!onInteractionAction || submitting) return;@@ -307,8 +396,16 @@ const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestio// Beats letting the server-side bridge time out into a `cancelled`// result — the model gets a structured answer it can act on instead of// a "user didn't respond" isError. Single-shot via `submitting` guard.+ //+ // Escape-mode special case: if the user is in escape mode with non-empty+ // text when the countdown hits zero, submit that text as-is rather than+ // discarding their work and falling back to option 1.useEffect(() => {if (!expired || submitting || questions.length === 0) return;+ if (escapeActive && escapeText.trim().length > 0) {+ void submitWith({ [FREEFORM_PAYLOAD_KEY]: escapeText.trim() });+ return;+ }const fallback: Record<string, string | string[]> = { ...answers };for (const q of questions) {const a = fallback[q.question];@@ -319,14 +416,17 @@ const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestio}}void submitWith(fallback);- }, [expired, submitting, questions, answers, submitWith]);+ }, [expired, submitting, questions, answers, escapeActive, escapeText, submitWith]);const isMulti = questions.length > 1;const activeQuestion = questions[Number(activeTab)] ?? questions[0];+ const isSubmitDisabled = escapeActive+ ? !escapeText.trim() || submitting || expired+ : !allAnswered || expired || submitting;return (<Flexbox gap={12}>- {isMulti && (+ {!escapeActive && isMulti && (<TabscompactactiveKey={activeTab}@@ -347,34 +447,69 @@ const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestio/>)}- {activeQuestion && (- <QuestionPanel- answer={answers[activeQuestion.question]}+ {escapeActive ? (+ <TextArea+ autoSize={{ maxRows: 8, minRows: 3 }}disabled={expired || submitting}- question={activeQuestion}- onToggle={handleToggle}+ placeholder={t('claudeCode.askUserQuestion.escape.placeholder')}+ value={escapeText}+ variant="filled"+ onChange={(e) => handleEscapeTextChange(e.target.value)}/>+ ) : (+ activeQuestion && (+ <QuestionPanel+ answer={answers[activeQuestion.question]}+ disabled={expired || submitting}+ question={activeQuestion}+ onToggle={handleToggle}+ />+ ))}<Flexbox horizontal align="center" gap={8} justify="space-between">- <Text fontSize={12} type="secondary">- {expired- ? 'Time expired — using option 1 of each question.'- : `Time remaining: ${formatRemaining(deadline - now)} · ` +- 'unanswered questions default to option 1 on timeout.'}- </Text>+ <Flexbox horizontal align="center" gap={12}>+ {escapeActive ? (+ <Text+ className={styles.escapeLink}+ fontSize={12}+ type="secondary"+ onClick={expired || submitting ? undefined : handleEscapeToggle}+ >+ <Icon icon={ArrowLeft} size={12} />+ {t('claudeCode.askUserQuestion.escape.back')}+ </Text>+ ) : (+ <Text+ className={styles.escapeLink}+ fontSize={12}+ type="secondary"+ onClick={expired || submitting ? undefined : handleEscapeToggle}+ >+ {t('claudeCode.askUserQuestion.escape.enter')}+ <Icon icon={PenLine} size={12} />+ </Text>+ )}+ <Text fontSize={12} type="secondary">+ {expired+ ? t('claudeCode.askUserQuestion.timeExpired')+ : t('claudeCode.askUserQuestion.timeRemaining', {+ time: formatRemaining(deadline - now),+ })}+ </Text>+ </Flexbox><Flexbox horizontal gap={8}><Button disabled={submitting} icon={X} onClick={handleSkip}>- Skip+ {t('claudeCode.askUserQuestion.skip')}</Button><Button- disabled={!allAnswered || expired || submitting}+ disabled={isSubmitDisabled}icon={Send}loading={submitting}type="primary"onClick={handleSubmit}>- Submit+ {t('claudeCode.askUserQuestion.submit')}</Button></Flexbox></Flexbox>diff --git a/packages/builtin-tool-claude-code/src/client/Render/AskUserQuestion/index.tsx b/packages/builtin-tool-claude-code/src/client/Render/AskUserQuestion/index.tsxindex 1234d86c73c..1fa24f9976f 100644--- a/packages/builtin-tool-claude-code/src/client/Render/AskUserQuestion/index.tsx+++ b/packages/builtin-tool-claude-code/src/client/Render/AskUserQuestion/index.tsx@@ -3,7 +3,7 @@import type { BuiltinRenderProps } from '@lobechat/types';import { Flexbox, Icon, Text } from '@lobehub/ui';import { createStaticStyles, cx } from 'antd-style';-import { Check } from 'lucide-react';+import { Check, PenLine } from 'lucide-react';import { memo } from 'react';import type { AskUserQuestionArgs, AskUserQuestionItem } from '../../../types';@@ -112,8 +112,34 @@ const AskUserQuestion = memo<>(({ args, pluginError, pluginState }) => {const questions = args?.questions ?? [];const answers = pluginState?.askUserAnswers;+ const freeform = answers?.['__freeform__'];+ const freeformText = typeof freeform === 'string' ? freeform.trim() : '';const isError = !!pluginError;+ // Escape-mode reply: the user opted out of the multi-choice form and+ // wrote freeform text instead. The form picks are intentionally absent,+ // so render the questions for context (header + body only) plus the+ // typed reply as one card — Q&A pairs would render as empty rows.+ if (freeformText) {+ return (+ <Flexbox className={styles.container} gap={12}>+ {questions.map((q, idx) => (+ <Flexbox gap={4} key={`${q.question}-${idx}`}>+ {q.header && <span className={styles.header}>{q.header}</span>}+ <Text className={styles.question}>{q.question}</Text>+ </Flexbox>+ ))}+ <Flexbox horizontal align="flex-start" className={cx(styles.answerRow)} gap={8}>+ <Icon className={styles.check} icon={PenLine} size={14} />+ <Text className={styles.answer}>{freeformText}</Text>+ </Flexbox>+ {isError && (+ <Text type="warning">(No answer received — model continued without their input.)</Text>+ )}+ </Flexbox>+ );+ }+return (<Flexbox className={styles.container} gap={12}>{questions.map((q, idx) => (diff --git a/packages/builtin-tool-claude-code/src/client/Render/Task/index.tsx b/packages/builtin-tool-claude-code/src/client/Render/Task/index.tsxnew file mode 100644index 00000000000..a949e7a59c6--- /dev/null+++ b/packages/builtin-tool-claude-code/src/client/Render/Task/index.tsx@@ -0,0 +1,283 @@+'use client';++import type { BuiltinRenderProps } from '@lobechat/types';+import { Block, Checkbox, Icon } from '@lobehub/ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { CircleArrowRight, CircleCheckBig, CircleX, ListTodo, RotateCcw } from 'lucide-react';+import { memo, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { ClaudeCodeApiName, type TaskUpdateArgs } from '../../../types';++const styles = createStaticStyles(({ css, cssVar }) => ({+ header: css`+ display: flex;+ gap: 8px;+ align-items: center;++ padding-block: 10px;+ padding-inline: 12px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};++ background: ${cssVar.colorFillQuaternary};+ `,+ headerCount: css`+ flex-shrink: 0;++ padding-block: 2px;+ padding-inline: 8px;+ border-radius: 999px;++ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;+ color: ${cssVar.colorTextSecondary};++ background: ${cssVar.colorFillTertiary};+ `,+ headerDetail: css`+ overflow: hidden;+ min-width: 0;+ color: ${cssVar.colorText};+ text-overflow: ellipsis;+ `,+ headerLabel: css`+ overflow: hidden;+ display: flex;+ flex: 1;+ gap: 0;+ align-items: center;++ min-width: 0;++ color: ${cssVar.colorTextSecondary};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ itemRow: css`+ width: 100%;+ padding-block: 10px;+ padding-inline: 12px;+ border-block-end: 1px dashed ${cssVar.colorBorderSecondary};++ &:last-child {+ border-block-end: none;+ }+ `,+ processingRow: css`+ display: flex;+ gap: 7px;+ align-items: center;+ `,+ textCompleted: css`+ color: ${cssVar.colorTextQuaternary};+ text-decoration: line-through;+ `,+ textPending: css`+ color: ${cssVar.colorTextSecondary};+ `,+ textProcessing: css`+ color: ${cssVar.colorText};+ `,+}));++interface TaskPluginStateItem {+ id?: string;+ status: 'todo' | 'processing' | 'completed';+ text: string;+}++interface TaskPluginState {+ todos?: {+ items?: TaskPluginStateItem[];+ updatedAt?: string;+ };+}++interface TaskRowProps {+ item: TaskPluginStateItem;+}++const TaskRow = memo<TaskRowProps>(({ item }) => {+ const { status, text } = item;++ if (status === 'processing') {+ return (+ <div className={cx(styles.itemRow, styles.processingRow)}>+ <Icon icon={CircleArrowRight} size={17} style={{ color: cssVar.colorInfo }} />+ <span className={styles.textProcessing}>{text}</span>+ </div>+ );+ }++ const isCompleted = status === 'completed';++ return (+ <Checkbox+ backgroundColor={cssVar.colorSuccess}+ checked={isCompleted}+ shape={'circle'}+ style={{ borderWidth: 1.5, cursor: 'default' }}+ classNames={{+ text: cx(styles.textPending, isCompleted && styles.textCompleted),+ wrapper: styles.itemRow,+ }}+ textProps={{+ type: isCompleted ? 'secondary' : undefined,+ }}+ >+ {text}+ </Checkbox>+ );+});++TaskRow.displayName = 'ClaudeCodeTaskRow';++/**+ * Per-call override that swaps the header into a status-flip readout+ * ("Completed: Read hosts") when the panel is rendered for a TaskUpdate.+ * Computed by the Task component from `apiName` + `args` so TaskHeader+ * stays a pure presentational component.+ *+ * `label` is the verb shown before `:`, `detail` is the subject; both+ * are pre-localized strings (no i18n inside TaskHeader for overrides).+ */+interface TaskHeaderOverride {+ color: string;+ detail?: string;+ icon: typeof CircleArrowRight;+ label: string;+}++interface TaskHeaderProps {+ completed: number;+ inProgress?: TaskPluginStateItem;+ override?: TaskHeaderOverride;+ total: number;+}++const TaskHeader = memo<TaskHeaderProps>(({ completed, total, inProgress, override }) => {+ const { t } = useTranslation('plugin');+ const allDone = total > 0 && completed === total;++ const icon =+ override?.icon ?? (inProgress ? CircleArrowRight : allDone ? CircleCheckBig : ListTodo);+ const color =+ override?.color ??+ (inProgress ? cssVar.colorInfo : allDone ? cssVar.colorSuccess : cssVar.colorTextSecondary);++ const label =+ override?.label ??+ (inProgress+ ? t('builtins.lobe-claude-code.todoWrite.currentStep')+ : allDone+ ? t('builtins.lobe-claude-code.todoWrite.allDone')+ : t('builtins.lobe-claude-code.todoWrite.todos'));+ const detail = override ? override.detail : inProgress?.text;++ return (+ <div className={styles.header}>+ <Icon icon={icon} size={16} style={{ color, flexShrink: 0 }} />+ <div className={styles.headerLabel}>+ <span>{label}</span>+ {detail && (+ <>+ <span>: </span>+ <span className={styles.headerDetail}>{detail}</span>+ </>+ )}+ </div>+ <span className={styles.headerCount}>+ {completed}/{total}+ </span>+ </div>+ );+});++TaskHeader.displayName = 'ClaudeCodeTaskHeader';++/**+ * Panel render for CC 2.1.143+ task tools (TaskCreate / TaskUpdate / TaskList).+ *+ * Reads the **adapter-synthesized** `pluginState.todos.items` snapshot — the+ * same source consumed by `selectTodosFromMessages`. Each per-call args+ * carries only a delta, so the panel can't be built from args alone; the+ * accumulator's snapshot is the source of truth.+ *+ * Returns `null` when the snapshot is absent or empty (typical for a fresh+ * TaskList before any creates, or a TaskUpdate that failed).+ *+ * Header behaviour:+ * - Default (TaskCreate / TaskList / TaskUpdate without status): shows the+ * standard `currentStep / allDone / todos` aggregate label so the panel+ * stays visually consistent with legacy TodoWrite sessions.+ * - TaskUpdate with `args.status`: the per-call signal IS that status flip,+ * so the header mirrors the chip ("Completed: Read hosts") instead of+ * burying it under the aggregate. Subject is resolved from pluginState+ * by id; `args.subject` is the resume-gap fallback.+ */+const Task = memo<BuiltinRenderProps<TaskUpdateArgs | undefined, TaskPluginState>>(+ ({ apiName, args, pluginState }) => {+ const items = pluginState?.todos?.items;+ const { t } = useTranslation('plugin');++ const stats = useMemo(() => {+ const list = items ?? [];+ return {+ completed: list.filter((item) => item.status === 'completed').length,+ inProgress: list.find((item) => item.status === 'processing'),+ total: list.length,+ };+ }, [items]);++ const override = useMemo<TaskHeaderOverride | undefined>(() => {+ if (apiName !== ClaudeCodeApiName.TaskUpdate || !args?.status) return undefined;+ const { status, taskId, subject: argsSubject } = args;+ const resolvedSubject =+ (taskId ? items?.find((item) => item.id === taskId)?.text : undefined) ?? argsSubject;+ const map = {+ completed: {+ color: cssVar.colorSuccess,+ icon: CircleCheckBig,+ label: t('builtins.lobe-claude-code.task.updateCompleted'),+ },+ deleted: {+ color: cssVar.colorError,+ icon: CircleX,+ label: t('builtins.lobe-claude-code.task.updateDeleted'),+ },+ in_progress: {+ color: cssVar.colorInfo,+ icon: CircleArrowRight,+ label: t('builtins.lobe-claude-code.task.updateInProgress'),+ },+ pending: {+ color: cssVar.colorTextSecondary,+ icon: RotateCcw,+ label: t('builtins.lobe-claude-code.task.updatePending'),+ },+ } as const;+ const entry = map[status];+ return { ...entry, detail: resolvedSubject };+ }, [apiName, args, items, t]);++ if (!items || items.length === 0) return null;++ return (+ <Block variant={'outlined'} width="100%">+ <TaskHeader+ completed={stats.completed}+ inProgress={stats.inProgress}+ override={override}+ total={stats.total}+ />+ {items.map((item, index) => (+ <TaskRow item={item} key={index} />+ ))}+ </Block>+ );+ },+);++Task.displayName = 'ClaudeCodeTask';++export default Task;diff --git a/packages/builtin-tool-claude-code/src/client/Render/index.ts b/packages/builtin-tool-claude-code/src/client/Render/index.tsindex 71b55187ad0..a1e7e00288c 100644--- a/packages/builtin-tool-claude-code/src/client/Render/index.ts+++ b/packages/builtin-tool-claude-code/src/client/Render/index.ts@@ -9,6 +9,7 @@ import Glob from './Glob';import Grep from './Grep';import Read from './Read';import Skill from './Skill';+import Task from './Task';import TodoWrite from './TodoWrite';import WebFetch from './WebFetch';import WebSearch from './WebSearch';@@ -31,6 +32,15 @@ export const ClaudeCodeRenders = {[ClaudeCodeApiName.Grep]: Grep,[ClaudeCodeApiName.Read]: Read,[ClaudeCodeApiName.Skill]: Skill,+ // Task panel renders the adapter-synthesized `pluginState.todos` snapshot.+ // Only TaskUpdate / TaskList show it — those events express list-level+ // changes (status flip / full snapshot) where the cumulative panel is+ // genuinely informative. TaskCreate is deliberately skipped: it's a+ // single-task add and the inspector chip already says `Creating task:+ // <subject>`, so the big "Todos N/M" panel adds noise without info.+ // TaskGet is read-only and falls through to the default tool card.+ [ClaudeCodeApiName.TaskList]: Task,+ [ClaudeCodeApiName.TaskUpdate]: Task,[ClaudeCodeApiName.TodoWrite]: TodoWrite,[ClaudeCodeApiName.WebFetch]: WebFetch,[ClaudeCodeApiName.WebSearch]: WebSearch,@@ -47,6 +57,8 @@ export const ClaudeCodeRenders = {*/export const ClaudeCodeRenderDisplayControls: Record<string, RenderDisplayControl> = {[ClaudeCodeApiName.Edit]: 'expand',+ [ClaudeCodeApiName.TaskList]: 'expand',+ [ClaudeCodeApiName.TaskUpdate]: 'expand',[ClaudeCodeApiName.TodoWrite]: 'expand',[ClaudeCodeApiName.Write]: 'expand',};diff --git a/packages/builtin-tool-claude-code/src/types.ts b/packages/builtin-tool-claude-code/src/types.tsindex f9295b2dd5d..f4af33609bf 100644--- a/packages/builtin-tool-claude-code/src/types.ts+++ b/packages/builtin-tool-claude-code/src/types.ts@@ -46,8 +46,26 @@ export enum ClaudeCodeApiName {Read = 'Read',ScheduleWakeup = 'ScheduleWakeup',Skill = 'Skill',+ /**+ * Imperative successor to {@link TodoWrite} in CC 2.1.143+. The model creates+ * one task per call (CC server assigns the numeric id) and mutates by id with+ * {@link TaskUpdate}. The adapter accumulates these into a per-session map+ * and synthesizes the shared `pluginState.todos` shape on each task-tool+ * result so the existing TodoProgress UI keeps working without renderer+ * changes.+ */+ TaskCreate = 'TaskCreate',+ /** Inspect a single task by id. Read-only — does not mutate adapter state. */+ TaskGet = 'TaskGet',+ /**+ * List all tasks. Read-only, but its plain-text output is the only+ * reconciliation signal available when resuming a CC session whose+ * TaskCreate / TaskUpdate calls happened before this adapter was started.+ */+ TaskList = 'TaskList',TaskOutput = 'TaskOutput',TaskStop = 'TaskStop',+ TaskUpdate = 'TaskUpdate',TodoWrite = 'TodoWrite',ToolSearch = 'ToolSearch',WebFetch = 'WebFetch',@@ -138,6 +156,51 @@ export interface ScheduleWakeupArgs {reason?: string;}+/**+ * Status of a single task in CC's `TaskCreate` / `TaskUpdate` flow. `deleted`+ * is only valid on TaskUpdate — it permanently removes the entry rather than+ * representing a steady state.+ */+export type ClaudeCodeTaskStatus = 'pending' | 'in_progress' | 'completed';++/**+ * Arguments for CC's built-in `TaskCreate`. Each call creates ONE task with+ * default status `pending`; the CC server assigns a numeric id that the+ * adapter must parse from the tool_result line `Task #N created successfully`.+ */+export interface TaskCreateArgs {+ /** Present continuous form shown while the task is in_progress. */+ activeForm?: string;+ description: string;+ metadata?: Record<string, unknown>;+ subject: string;+}++/**+ * Arguments for CC's built-in `TaskUpdate`. All fields except `taskId` are+ * optional — TaskUpdate is a merge. `status: 'deleted'` is the soft-delete+ * path; downstream the adapter drops the entry from its accumulator.+ */+export interface TaskUpdateArgs {+ activeForm?: string;+ addBlockedBy?: string[];+ addBlocks?: string[];+ description?: string;+ metadata?: Record<string, unknown>;+ owner?: string;+ status?: ClaudeCodeTaskStatus | 'deleted';+ subject?: string;+ taskId: string;+}++/** Arguments for CC's built-in `TaskList` — no parameters in current schema. */+export type TaskListArgs = Record<PropertyKey, never>;++/** Arguments for CC's built-in `TaskGet`. */+export interface TaskGetArgs {+ taskId: string;+}+/*** Arguments for CC's built-in `TaskOutput` tool. Retrieves output from a* running or completed background task (bash, agent, remote session) by id.diff --git a/packages/database/src/schemas/topic.ts b/packages/database/src/schemas/topic.tsindex db8fb18d330..a3f733efc48 100644--- a/packages/database/src/schemas/topic.ts+++ b/packages/database/src/schemas/topic.ts@@ -43,7 +43,7 @@ export const topics = pgTable(trigger: text('trigger'), // 'cron' | 'chat' | 'api' | 'eval' - topic creation trigger sourcemode: text('mode'), // 'temp' | 'test' | 'default' - topic usage scenariostatus: text('status', {- enum: ['active', 'running', 'paused', 'failed', 'completed', 'archived'],+ enum: ['active', 'running', 'paused', 'waitingForHuman', 'failed', 'completed', 'archived'],}),completedAt: timestamptz('completed_at'),...timestamps,diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.test.tsindex c896240b096..efecc426826 100644--- a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts@@ -518,7 +518,12 @@ describe('ClaudeCodeAdapter', () => {});const result = events.find((e) => e.type === 'tool_result');return result!.data.pluginState as- | { todos: { items: Array<{ status: string; text: string }>; updatedAt: string } }+ | {+ todos: {+ items: Array<{ id?: string; status: string; text: string }>;+ updatedAt: string;+ };+ }| undefined;};@@ -675,6 +680,409 @@ describe('ClaudeCodeAdapter', () => {});});+ describe('Task tools pluginState synthesis (CC 2.1.143+)', () => {+ // Helper: drive a TaskCreate (assistant tool_use → user tool_result).+ // Returns the synthesized pluginState (or undefined) from the tool_result event.+ const driveTaskCreate = (+ adapter: ClaudeCodeAdapter,+ input: { activeForm?: string; description?: string; subject: string },+ toolId: string,+ resultContent: string,+ msgId: string,+ opts?: { isError?: boolean },+ ) => {+ adapter.adapt({+ message: {+ id: msgId,+ content: [{ id: toolId, input, name: 'TaskCreate', type: 'tool_use' }],+ },+ type: 'assistant',+ });+ const events = adapter.adapt({+ message: {+ content: [+ {+ content: resultContent,+ is_error: opts?.isError,+ tool_use_id: toolId,+ type: 'tool_result',+ },+ ],+ role: 'user',+ },+ type: 'user',+ });+ return events.find((e) => e.type === 'tool_result')!.data.pluginState as+ | {+ todos: {+ items: Array<{ id?: string; status: string; text: string }>;+ updatedAt: string;+ };+ }+ | undefined;+ };++ const driveTaskUpdate = (+ adapter: ClaudeCodeAdapter,+ input: {+ activeForm?: string;+ description?: string;+ status?: 'pending' | 'in_progress' | 'completed' | 'deleted';+ subject?: string;+ taskId: string;+ },+ toolId: string,+ resultContent: string,+ msgId: string,+ opts?: { isError?: boolean },+ ) => {+ adapter.adapt({+ message: {+ id: msgId,+ content: [{ id: toolId, input, name: 'TaskUpdate', type: 'tool_use' }],+ },+ type: 'assistant',+ });+ const events = adapter.adapt({+ message: {+ content: [+ {+ content: resultContent,+ is_error: opts?.isError,+ tool_use_id: toolId,+ type: 'tool_result',+ },+ ],+ role: 'user',+ },+ type: 'user',+ });+ return events.find((e) => e.type === 'tool_result')!.data.pluginState as+ | {+ todos: {+ items: Array<{ id?: string; status: string; text: string }>;+ updatedAt: string;+ };+ }+ | undefined;+ };++ const driveTaskList = (+ adapter: ClaudeCodeAdapter,+ toolId: string,+ resultContent: string,+ msgId: string,+ ) => {+ adapter.adapt({+ message: {+ id: msgId,+ content: [{ id: toolId, input: {}, name: 'TaskList', type: 'tool_use' }],+ },+ type: 'assistant',+ });+ const events = adapter.adapt({+ message: {+ content: [{ content: resultContent, tool_use_id: toolId, type: 'tool_result' }],+ role: 'user',+ },+ type: 'user',+ });+ return events.find((e) => e.type === 'tool_result')!.data.pluginState as+ | {+ todos: {+ items: Array<{ id?: string; status: string; text: string }>;+ updatedAt: string;+ };+ }+ | undefined;+ };++ it('accumulates TaskCreate calls into pluginState ordered by CC-assigned id', () => {+ const adapter = new ClaudeCodeAdapter();+ adapter.adapt({ subtype: 'init', type: 'system' });++ const after1 = driveTaskCreate(+ adapter,+ { activeForm: 'Reading hosts', description: 'Read /etc/hosts', subject: 'Read hosts' },+ 'tu_create_1',+ 'Task #1 created successfully: Read hosts',+ 'msg_1',+ );+ expect(after1!.todos.items).toEqual([{ id: '1', status: 'todo', text: 'Read hosts' }]);++ const after2 = driveTaskCreate(+ adapter,+ { activeForm: 'Counting lines', description: 'Count lines', subject: 'Count lines' },+ 'tu_create_2',+ 'Task #2 created successfully: Count lines',+ 'msg_2',+ );+ expect(after2!.todos.items).toEqual([+ { id: '1', status: 'todo', text: 'Read hosts' },+ { id: '2', status: 'todo', text: 'Count lines' },+ ]);+ });++ it('uses activeForm for in_progress items and subject for the rest', () => {+ const adapter = new ClaudeCodeAdapter();+ adapter.adapt({ subtype: 'init', type: 'system' });++ driveTaskCreate(+ adapter,+ { activeForm: 'Reading hosts', description: 'Read /etc/hosts', subject: 'Read hosts' },+ 'tu_create_1',+ 'Task #1 created successfully: Read hosts',+ 'msg_1',+ );++ const afterUpdate = driveTaskUpdate(+ adapter,+ { status: 'in_progress', taskId: '1' },+ 'tu_update_1',+ 'Updated task #1 status',+ 'msg_2',+ );+ expect(afterUpdate!.todos.items).toEqual([+ { id: '1', status: 'processing', text: 'Reading hosts' },+ ]);++ const afterDone = driveTaskUpdate(+ adapter,+ { status: 'completed', taskId: '1' },+ 'tu_update_2',+ 'Updated task #1 status',+ 'msg_3',+ );+ expect(afterDone!.todos.items).toEqual([+ { id: '1', status: 'completed', text: 'Read hosts' },+ ]);+ });++ it('falls back to subject for in_progress when activeForm was never set', () => {+ const adapter = new ClaudeCodeAdapter();+ adapter.adapt({ subtype: 'init', type: 'system' });++ driveTaskCreate(+ adapter,+ { description: 'Read /etc/hosts', subject: 'Read hosts' },+ 'tu_create_1',+ 'Task #1 created successfully: Read hosts',+ 'msg_1',+ );++ const state = driveTaskUpdate(+ adapter,+ { status: 'in_progress', taskId: '1' },+ 'tu_update_1',+ 'Updated task #1 status',+ 'msg_2',+ );+ expect(state!.todos.items).toEqual([{ id: '1', status: 'processing', text: 'Read hosts' }]);+ });++ it('TaskUpdate with status: deleted removes the entry', () => {+ const adapter = new ClaudeCodeAdapter();+ adapter.adapt({ subtype: 'init', type: 'system' });++ driveTaskCreate(+ adapter,+ { description: 'A', subject: 'A' },+ 'tu_create_1',+ 'Task #1 created successfully: A',+ 'msg_1',+ );+ driveTaskCreate(+ adapter,+ { description: 'B', subject: 'B' },+ 'tu_create_2',+ 'Task #2 created successfully: B',+ 'msg_2',+ );++ const state = driveTaskUpdate(+ adapter,+ { status: 'deleted', taskId: '1' },+ 'tu_update_del',+ 'Updated task #1',+ 'msg_3',+ );+ expect(state!.todos.items).toEqual([{ id: '2', status: 'todo', text: 'B' }]);+ });++ it('does NOT mutate accumulator when TaskCreate tool_result is is_error', () => {+ const adapter = new ClaudeCodeAdapter();+ adapter.adapt({ subtype: 'init', type: 'system' });++ driveTaskCreate(+ adapter,+ { description: 'A', subject: 'A' },+ 'tu_create_1',+ 'Task #1 created successfully: A',+ 'msg_1',+ );++ const errorState = driveTaskCreate(+ adapter,+ { description: 'B', subject: 'B' },+ 'tu_create_2',+ 'Invalid subject',+ 'msg_2',+ { isError: true },+ );+ // Error path returns no pluginState — UI keeps the prior snapshot.+ expect(errorState).toBeUndefined();++ // A later successful create must not inherit the failed create's+ // cached input — the cache should have been drained.+ const next = driveTaskCreate(+ adapter,+ { description: 'C', subject: 'C' },+ 'tu_create_3',+ 'Task #3 created successfully: C',+ 'msg_3',+ );+ // Only entries: #1 (A, todo) and #3 (C, todo). #2 must NOT appear.+ expect(next!.todos.items).toEqual([+ { id: '1', status: 'todo', text: 'A' },+ { id: '3', status: 'todo', text: 'C' },+ ]);+ });++ it('TaskUpdate to a never-seen id seeds a placeholder so resume sessions still render', () => {+ const adapter = new ClaudeCodeAdapter();+ adapter.adapt({ subtype: 'init', type: 'system' });++ // Resume gap: no prior TaskCreate observed. The update should still+ // produce an entry, falling back to a synthetic subject until a+ // TaskList reconcile fills it in.+ const state = driveTaskUpdate(+ adapter,+ { status: 'in_progress', subject: 'Recovered subject', taskId: '7' },+ 'tu_update_orphan',+ 'Updated task #7 status',+ 'msg_1',+ );+ expect(state!.todos.items).toEqual([+ { id: '7', status: 'processing', text: 'Recovered subject' },+ ]);+ });++ it('TaskList rebuilds entries from plain-text output when the accumulator is empty', () => {+ const adapter = new ClaudeCodeAdapter();+ adapter.adapt({ subtype: 'init', type: 'system' });++ const state = driveTaskList(+ adapter,+ 'tu_list_1',+ '#1 [in_progress] Read hosts\n#2 [pending] Count lines\n#3 [completed] Report',+ 'msg_1',+ );+ expect(state!.todos.items).toEqual([+ { id: '1', status: 'processing', text: 'Read hosts' },+ { id: '2', status: 'todo', text: 'Count lines' },+ { id: '3', status: 'completed', text: 'Report' },+ ]);+ });++ it('TaskList preserves activeForm from earlier TaskCreate when reconciling', () => {+ const adapter = new ClaudeCodeAdapter();+ adapter.adapt({ subtype: 'init', type: 'system' });++ driveTaskCreate(+ adapter,+ { activeForm: 'Reading hosts', description: 'Read', subject: 'Read hosts' },+ 'tu_create_1',+ 'Task #1 created successfully: Read hosts',+ 'msg_1',+ );+ // TaskList output flips status to in_progress; activeForm should+ // survive the reconcile (TaskList itself doesn't carry it).+ const state = driveTaskList(adapter, 'tu_list_1', '#1 [in_progress] Read hosts', 'msg_2');+ expect(state!.todos.items).toEqual([+ { id: '1', status: 'processing', text: 'Reading hosts' },+ ]);+ });++ it('does not synthesize Task pluginState for subagent tool_results', () => {+ const adapter = new ClaudeCodeAdapter();+ adapter.adapt({ subtype: 'init', type: 'system' });++ // Subagent assistant carrying a TaskCreate (parent_tool_use_id set).+ adapter.adapt({+ message: {+ id: 'msg_sub_1',+ content: [+ {+ id: 'tu_sub_create',+ input: { description: 'Sub task', subject: 'Sub task' },+ name: 'TaskCreate',+ type: 'tool_use',+ },+ ],+ },+ parent_tool_use_id: 'tu_main_agent',+ type: 'assistant',+ });+ const events = adapter.adapt({+ message: {+ content: [+ {+ content: 'Task #99 created successfully: Sub task',+ tool_use_id: 'tu_sub_create',+ type: 'tool_result',+ },+ ],+ role: 'user',+ },+ parent_tool_use_id: 'tu_main_agent',+ type: 'user',+ });+ const result = events.find((e) => e.type === 'tool_result');+ // Subagent task tools are out-of-scope for the main todo plan UI.+ expect(result!.data.pluginState).toBeUndefined();+ });++ it('mixed TodoWrite + Task* flows are independent (TodoWrite path still wins on its own call)', () => {+ const adapter = new ClaudeCodeAdapter();+ adapter.adapt({ subtype: 'init', type: 'system' });++ // First, a TaskCreate snapshot.+ driveTaskCreate(+ adapter,+ { description: 'A', subject: 'A' },+ 'tu_create_1',+ 'Task #1 created successfully: A',+ 'msg_1',+ );++ // Then a TodoWrite from a legacy / resumed session — should produce+ // its own pluginState from its own input, NOT the Task accumulator.+ adapter.adapt({+ message: {+ id: 'msg_2',+ content: [+ {+ id: 'tu_todo',+ input: { todos: [{ activeForm: 'Doing X', content: 'X', status: 'completed' }] },+ name: 'TodoWrite',+ type: 'tool_use',+ },+ ],+ },+ type: 'assistant',+ });+ const todoEvents = adapter.adapt({+ message: {+ content: [{ content: 'ok', tool_use_id: 'tu_todo', type: 'tool_result' }],+ role: 'user',+ },+ type: 'user',+ });+ const todoState = todoEvents.find((e) => e.type === 'tool_result')!.data.pluginState;+ expect(todoState.todos.items).toEqual([{ status: 'completed', text: 'X' }]);+ });+ });+describe('multi-step execution (message.id boundary)', () => {it('does NOT emit step boundary for the first assistant after init', () => {const adapter = new ClaudeCodeAdapter();diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.tsindex 058e2ad921c..33a4867d8ab 100644--- a/packages/heterogeneous-agents/src/adapters/claudeCode.ts+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.ts@@ -62,6 +62,48 @@ import type {*/const CC_TODO_WRITE_TOOL_NAME = 'TodoWrite';+/**+ * CC 2.1.143+ replaced the declarative {@link CC_TODO_WRITE_TOOL_NAME} with+ * an imperative trio: one task per `TaskCreate` (server-assigned numeric id),+ * field-merge mutations via `TaskUpdate`, and `TaskList` as the only+ * full-state read. The adapter accumulates these into a per-session map and+ * synthesizes the shared `pluginState.todos` shape on each task-tool+ * tool_result so the existing TodoProgress UI keeps working.+ *+ * The old TodoWrite path stays alongside — resumed sessions started on an+ * older CC may still emit it, and CC's recent SDK reminder text doesn't+ * forbid the model from using TodoWrite if it really wants to.+ */+const CC_TASK_CREATE_TOOL_NAME = 'TaskCreate';+const CC_TASK_UPDATE_TOOL_NAME = 'TaskUpdate';+const CC_TASK_LIST_TOOL_NAME = 'TaskList';++/**+ * tool_result confirmation emitted by CC for a successful `TaskCreate`.+ * Observed shape on CC 2.1.143: `Task #1 created successfully: <subject>`.+ * The numeric id is the only place we can read the CC-assigned handle —+ * `TaskCreate.input` itself does not echo it.+ */+const TASK_CREATE_RESULT_PATTERN = /^Task #(\d+) created successfully/;++/**+ * tool_result confirmation emitted by CC for a successful `TaskUpdate`.+ * Suffix varies (`status`, blank if no field changed, etc.); we only need+ * the id to confirm the mutation landed — the field deltas are already+ * carried by the cached `TaskUpdate.input`.+ */+const TASK_UPDATE_RESULT_PATTERN = /^Updated task #\d+/;++/**+ * One line of `TaskList`'s plain-text output: `#1 [in_progress] 读 hosts`.+ * Used as the resume reconciliation path — when this adapter joins a CC+ * session mid-stream and missed earlier Create / Update events, parsing+ * TaskList rebuilds id / subject / status. `activeForm` and `description`+ * cannot be recovered (CC omits them) so resumed in_progress tasks fall+ * back to the subject text, same as TodoWrite's content-fallback.+ */+const TASK_LIST_LINE_PATTERN = /^#(\d+) \[(pending|in_progress|completed)\] (.+)$/;+/*** Tool name CC sees for the LobeHub-hosted MCP `ask_user_question` server.* Source of truth lives in `../askUser/constants.ts`; replicated here as a@@ -93,6 +135,43 @@ interface TodoWriteArgs {todos: ClaudeCodeTodoItem[];}+/**+ * Shared synthesized status alphabet (`pending|in_progress|completed` →+ * `todo|processing|completed`) used by both the TodoWrite and the Task*+ * pluginState paths. Aliased here so the two synthesizers stay aligned.+ */+type SynthesizedTodoStatus = 'todo' | 'processing' | 'completed';++/** Cached `TaskCreate.input`, keyed by `tool_use.id` until the matching tool_result arrives. */+interface CachedTaskCreateInput {+ activeForm?: string;+ description?: string;+ subject: string;+}++/** Cached `TaskUpdate.input`, keyed by `tool_use.id` until the matching tool_result arrives. */+interface CachedTaskUpdateInput {+ activeForm?: string;+ description?: string;+ status?: ClaudeCodeTodoStatus | 'deleted';+ subject?: string;+ taskId: string;+}++/**+ * Per-session accumulator entry — the adapter's running mirror of CC's+ * task list, keyed by the CC-assigned numeric id. Updated as Create /+ * Update tool_results land, and (when present) reconciled against+ * `TaskList` tool_results to recover from resume gaps.+ */+interface ClaudeCodeTaskEntry {+ /** Empty until a TaskCreate or TaskUpdate populated it; TaskList output cannot recover this. */+ activeForm?: string;+ description?: string;+ status: ClaudeCodeTodoStatus;+ subject: string;+}+const CLAUDE_CODE_CLI_INSTALL_DOCS_URL = 'https://docs.anthropic.com/en/docs/claude-code/setup';const CLI_AUTH_REQUIRED_PATTERNS = [@@ -196,27 +275,58 @@ const getRateLimitTerminalError = (* Text field: use `activeForm` while in progress (present-continuous is what* the header surfaces), fall back to `content` for every other state.*/-const synthesizeTodoWritePluginState = (- args: TodoWriteArgs,-): {+/**+ * Synthesized `pluginState.todos` shape consumed by `selectTodosFromMessages`.+ *+ * `id` is optional: legacy `TodoWrite` snapshots are positional and have no+ * stable id, while the CC 2.1.143+ Task* tools carry the CC-server-assigned+ * numeric id so per-call inspectors can resolve `args.taskId` → subject text+ * without falling back to a cryptic `#N` label.+ */+interface SynthesizedTodoPluginState {todos: {- items: Array<{ status: 'todo' | 'processing' | 'completed'; text: string }>;+ items: Array<{ id?: string; status: SynthesizedTodoStatus; text: string }>;updatedAt: string;};-} => {+}++const toSynthesizedStatus = (status: ClaudeCodeTodoStatus): SynthesizedTodoStatus =>+ status === 'in_progress' ? 'processing' : status === 'pending' ? 'todo' : 'completed';++const synthesizeTodoWritePluginState = (args: TodoWriteArgs): SynthesizedTodoPluginState => {const items = (args.todos || []).map((todo: ClaudeCodeTodoItem) => {- const status =- todo.status === 'in_progress'- ? 'processing'- : todo.status === 'pending'- ? 'todo'- : 'completed';const text = todo.status === 'in_progress' ? todo.activeForm || todo.content : todo.content;- return { status, text } as const;+ return { status: toSynthesizedStatus(todo.status), text } as const;});return { todos: { items, updatedAt: new Date().toISOString() } };};+/**+ * Snapshot the running `claudeCodeTasks` accumulator into the shared+ * `pluginState.todos` shape. Sorted by numeric id so the rendered order+ * matches CC's own TaskList output (insertion order = id order in practice,+ * but TaskUpdate can rearrange status without rearranging ids). Carries the+ * `id` per item so the TaskUpdate inspector can resolve `args.taskId` →+ * subject text without falling back to a `#N` label.+ *+ * Text resolution mirrors {@link synthesizeTodoWritePluginState}: use+ * `activeForm` while in progress so the spinner reads "Running tests"+ * rather than "Run tests"; fall back to `subject` whenever activeForm is+ * missing (TaskList-reconciled entries, or a TaskCreate that omitted it).+ */+const synthesizeTaskPluginState = (+ tasks: Map<string, ClaudeCodeTaskEntry>,+): SynthesizedTodoPluginState => {+ const items = [...tasks.entries()]+ .sort(([a], [b]) => Number(a) - Number(b))+ .map(([id, entry]) => {+ const text =+ entry.status === 'in_progress' ? entry.activeForm || entry.subject : entry.subject;+ return { id, status: toSynthesizedStatus(entry.status), text } as const;+ });+ return { todos: { items, updatedAt: new Date().toISOString() } };+};+/*** Convert a raw Anthropic-shape usage object (per-turn or grand-total from* Claude Code's `result` event) into the provider-agnostic `UsageData` shape.@@ -309,6 +419,34 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {* bounded.*/private todoWriteInputs = new Map<string, TodoWriteArgs>();+ /**+ * Cached `TaskCreate.input` keyed by `tool_use.id`. Drained in `handleUser`+ * once the matching tool_result lands: at that point we parse the+ * CC-assigned numeric id from `Task #N created successfully` and push the+ * cached fields into {@link claudeCodeTasks}. Cleared even on error to+ * keep long sessions bounded — failed creates never reach the accumulator.+ */+ private taskCreateInputs = new Map<string, CachedTaskCreateInput>();+ /**+ * Cached `TaskUpdate.input` keyed by `tool_use.id`. Drained on+ * tool_result; on success the cached fields merge into the targeted entry+ * in {@link claudeCodeTasks}. `status: 'deleted'` removes the entry.+ */+ private taskUpdateInputs = new Map<string, CachedTaskUpdateInput>();+ /**+ * Tool_use ids of `TaskList` calls awaiting their tool_result. Used to+ * dispatch the reconciliation parser without re-checking the tool name on+ * every user event. `TaskList.input` is empty so no payload to cache.+ */+ private pendingTaskListCalls = new Set<string>();+ /**+ * Adapter's running mirror of CC's task list, keyed by the CC-assigned+ * numeric task id. Survives across `result` events because CC keeps the+ * task list alive between turns within one session; cleared only when+ * the adapter is destroyed. This is what `synthesizeTaskPluginState`+ * snapshots on each task-tool tool_result.+ */+ private claudeCodeTasks = new Map<string, ClaudeCodeTaskEntry>();/*** Cached inputs for main-agent tool_uses keyed by their tool_use.id.* Populated for every main-agent tool_use (not just `Task`) because@@ -553,6 +691,19 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {if (block.name === CC_TODO_WRITE_TOOL_NAME && block.input) {this.todoWriteInputs.set(block.id, block.input as TodoWriteArgs);}+ // Task* tool inputs cached for the tool_result-time reducer.+ // Only TaskCreate / TaskUpdate carry payloads worth caching;+ // TaskList carries no input but we still need to remember the+ // tool_use.id so the result-side dispatcher can recognize it.+ if (block.name === CC_TASK_CREATE_TOOL_NAME && block.input) {+ this.taskCreateInputs.set(block.id, block.input as CachedTaskCreateInput);+ }+ if (block.name === CC_TASK_UPDATE_TOOL_NAME && block.input) {+ this.taskUpdateInputs.set(block.id, block.input as CachedTaskUpdateInput);+ }+ if (block.name === CC_TASK_LIST_TOOL_NAME) {+ this.pendingTaskListCalls.add(block.id);+ }break;}}@@ -832,23 +983,37 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {.join('\n'): JSON.stringify(block.content || '');- // Synthesize pluginState for tools whose input IS the target state.- // TodoWrite is currently the only such tool; future CC tools (Task,- // Skill activation, …) extend this same collection point.+ // Synthesize pluginState for tools whose input IS (or, for Task*,+ // imperatively mutates) the target state. Two independent paths:+ //+ // - TodoWrite: declarative snapshot — each call carries the complete+ // list. The cached input is the synthesizable state.+ // - TaskCreate / TaskUpdate / TaskList (CC 2.1.143+): imperative;+ // the adapter accumulates them into `claudeCodeTasks` and snapshots+ // that map.//- // Guard on `is_error`: a failed TodoWrite means the snapshot was never- // applied on CC's side, so we must not persist it here either. Since+ // Guard on `is_error` for both: a failed write was never applied on+ // CC's side, so we must not persist a derived snapshot —// `selectTodosFromMessages` picks the latest `pluginState.todos` from- // any producer, leaking a failed write would overwrite the live todo- // UI with changes that never actually happened. Drain the cache either- // way so a retry with a fresh tool_use id doesn't inherit stale args.+ // any producer, and leaking a failed write would overwrite the live+ // todo UI with changes that never actually happened. Drain the input+ // caches either way so a retry with a fresh tool_use id doesn't+ // inherit stale args. Subagent inner tools never participate (their+ // task state is per-subagent, not the main plan).const cachedTodoArgs = this.todoWriteInputs.get(toolCallId);if (cachedTodoArgs) this.todoWriteInputs.delete(toolCallId);- const pluginState =+ const todoWritePluginState =cachedTodoArgs && !block.is_error? synthesizeTodoWritePluginState(cachedTodoArgs): undefined;+ const taskPluginState =+ subagentCtx === undefined+ ? this.applyTaskToolResult(toolCallId, !!block.is_error, resultContent)+ : undefined;++ const pluginState = todoWritePluginState ?? taskPluginState;+// Emit tool_result for executor to persist content to tool messageevents.push(this.makeEvent('tool_result', {@@ -876,6 +1041,98 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {return events;}+ /**+ * Apply a Task* tool_result to the running {@link claudeCodeTasks}+ * accumulator and return a fresh synthesized `pluginState.todos` snapshot.+ * Returns `undefined` if the tool_result was for a non-Task tool, was an+ * error, or carried no state change (the snapshot is identical to the+ * pre-call one — but we still emit it so the UI re-syncs).+ *+ * Drain the input caches even on error to keep long sessions bounded;+ * the accumulator itself only mutates on success so a failed TaskUpdate+ * doesn't leak partial state into the rendered todo list.+ */+ private applyTaskToolResult(+ toolCallId: string,+ isError: boolean,+ resultContent: string,+ ): SynthesizedTodoPluginState | undefined {+ const cachedCreate = this.taskCreateInputs.get(toolCallId);+ if (cachedCreate) this.taskCreateInputs.delete(toolCallId);+ const cachedUpdate = this.taskUpdateInputs.get(toolCallId);+ if (cachedUpdate) this.taskUpdateInputs.delete(toolCallId);+ const wasTaskList = this.pendingTaskListCalls.has(toolCallId);+ if (wasTaskList) this.pendingTaskListCalls.delete(toolCallId);++ if (!cachedCreate && !cachedUpdate && !wasTaskList) return undefined;+ if (isError) return undefined;++ if (cachedCreate) {+ // CC assigns the task id server-side; parse it from the confirmation+ // line so the accumulator keys match the ids the model will use in+ // later TaskUpdate calls. Skip silently on a non-matching format —+ // future CC versions might rephrase the confirmation, and leaking a+ // garbage entry is worse than missing one row.+ const match = TASK_CREATE_RESULT_PATTERN.exec(resultContent);+ if (match) {+ const taskId = match[1];+ this.claudeCodeTasks.set(taskId, {+ activeForm: cachedCreate.activeForm,+ description: cachedCreate.description,+ status: 'pending',+ subject: cachedCreate.subject,+ });+ }+ } else if (cachedUpdate) {+ // Only apply the update if CC confirmed it. `Updated task #N` is the+ // success line; any other shape implies a failure CC didn't surface+ // as `is_error`, in which case we leave the accumulator alone.+ if (!TASK_UPDATE_RESULT_PATTERN.test(resultContent)) return undefined;+ if (cachedUpdate.status === 'deleted') {+ this.claudeCodeTasks.delete(cachedUpdate.taskId);+ } else {+ const existing = this.claudeCodeTasks.get(cachedUpdate.taskId);+ // TaskUpdate against an id we never saw a Create for can happen in+ // resume sessions; seed a placeholder entry from whatever fields+ // the update carried so the next TaskList reconcile fills the rest.+ const next: ClaudeCodeTaskEntry = existing ?? {+ status: 'pending',+ subject: cachedUpdate.subject ?? `Task #${cachedUpdate.taskId}`,+ };+ // `deleted` is handled in the outer branch — TS narrows it out here.+ if (cachedUpdate.status) next.status = cachedUpdate.status;+ if (cachedUpdate.subject !== undefined) next.subject = cachedUpdate.subject;+ if (cachedUpdate.description !== undefined) next.description = cachedUpdate.description;+ if (cachedUpdate.activeForm !== undefined) next.activeForm = cachedUpdate.activeForm;+ this.claudeCodeTasks.set(cachedUpdate.taskId, next);+ }+ } else if (wasTaskList) {+ // Reconciliation: rebuild id / status / subject from each line of+ // CC's plain-text list. activeForm / description aren't recoverable+ // — keep whatever we already had (e.g. from a prior Create) and+ // fall back to subject for the in-progress spinner text.+ for (const rawLine of resultContent.split('\n')) {+ const line = rawLine.trim();+ if (!line) continue;+ const m = TASK_LIST_LINE_PATTERN.exec(line);+ if (!m) continue;+ const [, taskId, status, subject] = m;+ const existing = this.claudeCodeTasks.get(taskId);+ if (existing) {+ existing.status = status as ClaudeCodeTodoStatus;+ existing.subject = subject;+ } else {+ this.claudeCodeTasks.set(taskId, {+ status: status as ClaudeCodeTodoStatus,+ subject,+ });+ }+ }+ }++ return synthesizeTaskPluginState(this.claudeCodeTasks);+ }+private handleResult(raw: any): HeterogeneousAgentEvent[] {// Emit authoritative grand-total usage from CC's result event. The// executor currently ignores this phase (it persists per-turn viadiff --git a/packages/heterogeneous-agents/src/askUser/AskUserMcpServer.ts b/packages/heterogeneous-agents/src/askUser/AskUserMcpServer.tsindex eb0dec35a58..448ae2a7499 100644--- a/packages/heterogeneous-agents/src/askUser/AskUserMcpServer.ts+++ b/packages/heterogeneous-agents/src/askUser/AskUserMcpServer.ts@@ -434,7 +434,19 @@ const formatAnswerForCC = (answer: InterventionAnswer, args: unknown) => {// Success: format the structured answer back as text. CC's built-in// AskUserQuestion returns "User answers:\n- <q>: <a>" style — match it// so the model handles our payload identically.+ //+ // Escape-mode response: when the renderer's "Or type directly" toggle is+ // active, the payload is just `{ __freeform__: <text> }` — picks are+ // intentionally absent. Forward the text verbatim as the user's reply, no+ // structured framing, since the user opted out of the multi-choice form.const answerObj = (answer.result ?? {}) as Record<string, unknown>;+ const freeform = answerObj['__freeform__'];+ if (typeof freeform === 'string' && freeform.trim().length > 0) {+ return {+ content: [{ text: freeform.trim(), type: 'text' as const }],+ };+ }+const questions = (args as { questions?: Array<{ question: string }> }).questions ?? [];const lines = ['User answers:'];for (const q of questions) {diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex 387bbe687d0..ec048672e90 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -168,7 +168,14 @@ export interface ChatTopicSummary {provider: string;}-export type ChatTopicStatus = 'active' | 'running' | 'paused' | 'failed' | 'completed' | 'archived';+export type ChatTopicStatus =+ | 'active'+ | 'running'+ | 'paused'+ | 'waitingForHuman'+ | 'failed'+ | 'completed'+ | 'archived';export interface ChatTopic extends Omit<BaseDataModel, 'meta'> {completedAt?: Date | null;diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsxindex 9bc65f42903..88da66929b8 100644--- a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx@@ -41,6 +41,11 @@ const styles = createStaticStyles(({ css, cssVar }) => ({--trees-padding-inline-override: 0px;--trees-font-size-override: 12px;--trees-border-radius-override: 6px;++ /* Drop the doubled outline pierre/trees draws via ::before on a+ * focused+selected row — the filled background from+ * --trees-selected-bg-override is already a clear selection signal. */+ --trees-selected-focused-border-color-override: transparent;`,}));diff --git a/src/features/DevPanel/RenderGallery/fixtures/claude-code.ts b/src/features/DevPanel/RenderGallery/fixtures/claude-code.tsindex c9f2bd15695..185937b38f3 100644--- a/src/features/DevPanel/RenderGallery/fixtures/claude-code.ts+++ b/src/features/DevPanel/RenderGallery/fixtures/claude-code.ts@@ -43,6 +43,18 @@ export default defineFixtures({description: 'Run a Claude Code skill.',name: 'Skill',},+ {+ description: 'Create a new task (CC 2.1.143+ replacement for TodoWrite).',+ name: 'TaskCreate',+ },+ {+ description: 'Inspect a single task by id.',+ name: 'TaskGet',+ },+ {+ description: 'List all tasks.',+ name: 'TaskList',+ },{description: 'Read output from a background task.',name: 'TaskOutput',@@ -52,7 +64,11 @@ export default defineFixtures({name: 'TaskStop',},{- description: 'Track todo progress.',+ description: 'Update an existing task by id.',+ name: 'TaskUpdate',+ },+ {+ description: 'Track todo progress (pre-2.1.143 legacy).',name: 'TodoWrite',},{@@ -165,6 +181,124 @@ export default defineFixtures({args: { task_id: 'task-build-2025-04-25' },content: 'Background task stopped (exit code 0).',}),+ // Task tools — the renderer reads `pluginState.todos.items`, which the+ // CC adapter synthesizes from the accumulated TaskCreate / TaskUpdate /+ // TaskList history. Fixtures supply that snapshot directly.+ TaskCreate: variants([+ {+ args: {+ activeForm: 'Reading hosts',+ description: 'Read /etc/hosts and capture the content.',+ subject: 'Read hosts',+ },+ content: 'Task #1 created successfully: Read hosts',+ label: 'First create',+ pluginState: {+ todos: {+ items: [{ id: '1', status: 'todo', text: 'Read hosts' }],+ updatedAt: '2026-05-16T07:23:19.639Z',+ },+ },+ },+ {+ args: {+ activeForm: 'Drafting summary',+ description: 'Summarize findings.',+ subject: 'Draft summary',+ },+ content: 'Task #3 created successfully: Draft summary',+ label: 'Third create with prior progress',+ pluginState: {+ todos: {+ items: [+ { id: '1', status: 'completed', text: 'Read hosts' },+ { id: '2', status: 'processing', text: 'Counting lines' },+ { id: '3', status: 'todo', text: 'Draft summary' },+ ],+ updatedAt: '2026-05-16T07:24:00.000Z',+ },+ },+ },+ ]),+ TaskGet: single({+ args: { taskId: '1' },+ content: 'Task #1: Read hosts\nStatus: in_progress\nDescription: Read /etc/hosts content',+ }),+ TaskList: variants([+ {+ args: {},+ content:+ '#1 [in_progress] Read hosts\n#2 [pending] Count lines\n#3 [pending] Draft summary',+ label: 'Mixed progress',+ pluginState: {+ todos: {+ items: [+ { id: '1', status: 'processing', text: 'Read hosts' },+ { id: '2', status: 'todo', text: 'Count lines' },+ { id: '3', status: 'todo', text: 'Draft summary' },+ ],+ updatedAt: '2026-05-16T07:24:30.000Z',+ },+ },+ },+ {+ args: {},+ content:+ '#1 [completed] Read hosts\n#2 [completed] Count lines\n#3 [completed] Draft summary',+ label: 'All done',+ pluginState: {+ todos: {+ items: [+ { id: '1', status: 'completed', text: 'Read hosts' },+ { id: '2', status: 'completed', text: 'Count lines' },+ { id: '3', status: 'completed', text: 'Draft summary' },+ ],+ updatedAt: '2026-05-16T07:25:00.000Z',+ },+ },+ },+ ]),+ TaskUpdate: variants([+ {+ args: { status: 'in_progress', taskId: '1' },+ content: 'Updated task #1 status',+ label: 'Mark in_progress',+ pluginState: {+ todos: {+ items: [+ { id: '1', status: 'processing', text: 'Read hosts' },+ { id: '2', status: 'todo', text: 'Count lines' },+ ],+ updatedAt: '2026-05-16T07:23:35.000Z',+ },+ },+ },+ {+ args: { status: 'completed', taskId: '1' },+ content: 'Updated task #1 status',+ label: 'Mark completed',+ pluginState: {+ todos: {+ items: [+ { id: '1', status: 'completed', text: 'Read hosts' },+ { id: '2', status: 'processing', text: 'Counting lines' },+ ],+ updatedAt: '2026-05-16T07:23:50.000Z',+ },+ },+ },+ {+ args: { status: 'deleted', taskId: '2' },+ content: 'Deleted task #2',+ label: 'Mark deleted',+ pluginState: {+ todos: {+ items: [{ id: '1', status: 'processing', text: 'Read hosts' }],+ updatedAt: '2026-05-16T07:24:10.000Z',+ },+ },+ },+ ]),TodoWrite: variants([{args: {diff --git a/src/locales/default/plugin.ts b/src/locales/default/plugin.tsindex a1ae9a62656..c5ccd6fd3d9 100644--- a/src/locales/default/plugin.ts+++ b/src/locales/default/plugin.ts@@ -62,6 +62,14 @@ export default {'builtins.lobe-agent.title': 'Lobe Agent','builtins.lobe-claude-code.agent.instruction': 'Instruction','builtins.lobe-claude-code.agent.result': 'Result',+ 'builtins.lobe-claude-code.task.createLabel': 'Creating task: ',+ 'builtins.lobe-claude-code.task.getLabel': 'Inspecting task #{{taskId}}',+ 'builtins.lobe-claude-code.task.listLabel': 'Listing tasks',+ 'builtins.lobe-claude-code.task.updateCompleted': 'Completed',+ 'builtins.lobe-claude-code.task.updateDeleted': 'Deleted',+ 'builtins.lobe-claude-code.task.updateInProgress': 'Started',+ 'builtins.lobe-claude-code.task.updateLabel': 'Updating task #{{taskId}}',+ 'builtins.lobe-claude-code.task.updatePending': 'Reset','builtins.lobe-claude-code.todoWrite.allDone': 'All tasks completed','builtins.lobe-claude-code.todoWrite.currentStep': 'Current step','builtins.lobe-claude-code.todoWrite.todos': 'Todos',diff --git a/src/locales/default/tool.ts b/src/locales/default/tool.tsindex 5efb02d1b98..8afb0d3b114 100644--- a/src/locales/default/tool.ts+++ b/src/locales/default/tool.ts@@ -42,6 +42,15 @@ export default {'agentMarketplace.render.alreadyInLibrary_other': '{{count}} already in library','agentMarketplace.picker.failedToLoad': 'Failed to load templates. Please try again later.','agentMarketplace.picker.summary': '{{filtered}} / {{total}} templates available.',+ 'claudeCode.askUserQuestion.escape.back': 'Back to options',+ 'claudeCode.askUserQuestion.escape.enter': 'Or type directly',+ 'claudeCode.askUserQuestion.escape.placeholder': 'Type your answer here…',+ 'claudeCode.askUserQuestion.multiSelectTag': '(multi-select)',+ 'claudeCode.askUserQuestion.skip': 'Skip',+ 'claudeCode.askUserQuestion.submit': 'Submit',+ 'claudeCode.askUserQuestion.timeExpired': 'Time expired — using option 1 of each question.',+ 'claudeCode.askUserQuestion.timeRemaining':+ 'Time remaining: {{time}} · unanswered questions default to option 1 on timeout.','codeInterpreter-legacy.error': 'Execution Error','codeInterpreter-legacy.executing': 'Executing...','codeInterpreter-legacy.files': 'Files:',diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsxindex 0940459b8a9..9945296493e 100644--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx@@ -1,7 +1,7 @@import type { ChatTopicMetadata, ChatTopicStatus } from '@lobechat/types';import { Flexbox, Icon, Skeleton, Tag } from '@lobehub/ui';import { createStaticStyles, cssVar, keyframes, useTheme } from 'antd-style';-import { CheckCircle2, HashIcon, MessageSquareDashed } from 'lucide-react';+import { CheckCircle2, Hand, HashIcon, MessageSquareDashed } from 'lucide-react';import { memo, Suspense, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -181,6 +181,7 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, metaconst isCompleted = status === 'completed';const isRunning = status === 'running';+ const isWaitingForHuman = status === 'waitingForHuman';const hasUnread = id && isUnreadCompleted;const unreadIcon = (@@ -235,6 +236,9 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, metahref={href}title={title === '...' ? <DotsLoading gap={3} size={4} /> : title}icon={(() => {+ if (isWaitingForHuman) {+ return <Icon icon={Hand} size={'small'} style={{ color: cssVar.colorWarning }} />;+ }if (isLoading || isRunning) {return (<RingLoadingIcondiff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/index.tsxindex 0064002a74a..2ccb7062ed3 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/index.tsx@@ -37,6 +37,11 @@ const styles = createStaticStyles(({ css, cssVar }) => ({--trees-font-size-override: 12px;--trees-border-radius-override: 6px;+ /* Drop the doubled outline pierre/trees draws via ::before on a+ * focused+selected row — the filled background from+ * --trees-selected-bg-override is already a clear selection signal. */+ --trees-selected-focused-border-color-override: transparent;+flex: 1;min-height: 0;`,diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsxindex 1d0d9337383..8cc20da9456 100644--- a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx@@ -1,7 +1,7 @@import type { ChatTopicStatus } from '@lobechat/types';import { Flexbox, Icon, Skeleton, Tag } from '@lobehub/ui';import { createStaticStyles, cssVar } from 'antd-style';-import { CheckCircle2, HashIcon, Loader2Icon, MessageSquareDashed } from 'lucide-react';+import { CheckCircle2, Hand, HashIcon, Loader2Icon, MessageSquareDashed } from 'lucide-react';import { AnimatePresence, m } from 'motion/react';import { memo, Suspense, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -153,6 +153,7 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, statconst isCompleted = status === 'completed';const isRunning = status === 'running';+ const isWaitingForHuman = status === 'waitingForHuman';const hasUnread = id && isUnreadCompleted;const infoColor = cssVar.colorInfo;@@ -237,6 +238,9 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, stathref={!editing ? href : undefined}title={title === '...' ? <DotsLoading gap={3} size={4} /> : title}icon={(() => {+ if (isWaitingForHuman) {+ return <Icon icon={Hand} size={'small'} style={{ color: cssVar.colorWarning }} />;+ }if (isLoading || isRunning) {return (<Icon spin icon={Loader2Icon} size={'small'} style={{ color: cssVar.colorWarning }} />diff --git a/src/server/routers/lambda/topic.ts b/src/server/routers/lambda/topic.tsindex b4dc4b371b3..47e57530ad3 100644--- a/src/server/routers/lambda/topic.ts+++ b/src/server/routers/lambda/topic.ts@@ -553,7 +553,15 @@ export const topicRouter = router({.optional(),sessionId: z.string().optional(),status: z- .enum(['active', 'running', 'paused', 'failed', 'completed', 'archived'])+ .enum([+ 'active',+ 'running',+ 'paused',+ 'waitingForHuman',+ 'failed',+ 'completed',+ 'archived',+ ]).nullable().optional(),title: z.string().optional(),diff --git a/src/store/chat/slices/aiChat/actions/conversationControl.ts b/src/store/chat/slices/aiChat/actions/conversationControl.tsindex 6fab53448e1..b5e6d99a92a 100644--- a/src/store/chat/slices/aiChat/actions/conversationControl.ts+++ b/src/store/chat/slices/aiChat/actions/conversationControl.ts@@ -815,7 +815,13 @@ export class ConversationControlActionImpl {console.error('[submitHeteroIntervention] IPC submitIntervention failed:', err);}- void effectiveContext;+ // Sidebar topic row was swapped to the `waitingForHuman` hand icon when+ // the intervention was raised; once the user submits/skips/cancels the+ // CC stream resumes so flip it back to `running`. The natural completion+ // (`runtime_end` → `writeTopicStatus('active')`) takes over from there.+ if (effectiveContext.topicId) {+ void this.#get().updateTopicStatus?.(effectiveContext.topicId, 'running');+ }};/**diff --git a/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts b/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.tsindex cf0630a3b01..957106452a2 100644--- a/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts@@ -1379,6 +1379,10 @@ export const executeHeterogeneousAgent = async ({ intervention: { status: 'pending' } },{ operationId },);+ // Sidebar topic row swaps the running spinner for a hand icon+ // so it's obvious from the topic list that this conversation is+ // blocked on the user, not still streaming.+ writeTopicStatus('waitingForHuman');} catch (err) {console.error('[HeterogeneousAgent] persist intervention pending failed:', err);}@@ -1413,6 +1417,10 @@ export const executeHeterogeneousAgent = async (},{ operationId },);+ // Bridge resolved without the user — drop the hand state so the+ // sidebar reflects that we're back to whatever the stream does+ // next (`active`/`failed` lands shortly after via runtime_end).+ writeTopicStatus('running');} catch (err) {console.error('[HeterogeneousAgent] persist intervention rejection failed:', err);}