Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(task-status): surface Claude subagent launch failures on Desktop/Mobile (#3024)

Battleplusb2b9e7a0904c
diff --git a/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx b/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx
index b25ed01710..c4e9937533 100644
--- a/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx
@@ -14,8 +14,9 @@ import {
import { useTranslation } from 'react-i18next';
import {
deriveAgentTaskStatus,
- formatAgentTaskTitle,
+
type AgentTaskStatus,
+
type AgentTaskTerminalStatus,
} from '@cindy/maker-shared/agent-task';
@@ -44,6 +45,9 @@ import { formatCompactTokens } from '@/lib/usageFormat';
import { CODEX_SUBAGENT_EFFORTS } from '../../../shared/subagentModelSettings';
import {
PI_SUBAGENT_TOOL_NAME,
+ formatAgentTaskTitle,
+ isClaudeSubagentToolName,
+ isSubagentResultError,
subagentSpawnReceiptName,
subagentSpawnResultIndicatesRunning,
} from '@cindy/maker-shared/agent-task';
@@ -241,6 +245,27 @@ export function AgentTaskCard({
};
}, [isWorkflow, update?.status, sessionId, workflowTaskId]);
+
+
+ // bash-task-card: 后台 Bash(run_in_background)与子 Agent 共用本卡,但视觉上
+ // 是「后台命令」—— 终端图标 + shell provider 标签,避免用户把跑测试的 bash
+ // 误读成一个子 Agent。
+ const isBash = update?.taskType === 'local_bash';
+ const isSubagent = !isWorkflow && !isBash;
+ const provider = update?.provider
+ ?? (toolCall?.toolName?.startsWith('collab:')
+ ? 'codex'
+ : toolCall?.toolName === PI_SUBAGENT_TOOL_NAME ? 'pi' : 'claude-code');
+ // `<tool_use_error>` 是 Claude SDK 协议级标记,只对 Claude 子任务(Agent/Task)的
+ // 结果有意义。后台 Bash、PI subagent 与 Codex `collab:*` 的成功产物可能合法地以
+ // 该前缀开头,无条件判定会把成功任务误标成 failed。工具名已知时按工具名收窄,
+ // 只有历史回放(update 卡无 toolCall)才退回 provider 判定。
+ const claudeProtocolResult =
+ isSubagent
+ && (toolCall?.toolName !== undefined
+ ? isClaudeSubagentToolName(toolCall.toolName)
+ : provider === 'claude-code');
+
const status = isWorkflow
? (update?.status ?? historyFileStatus ?? (result ? 'completed' : 'running'))
: deriveAgentTaskStatus(update?.status, result, {
@@ -249,21 +274,13 @@ export function AgentTaskCard({
resultIsLaunchReceipt:
subagentSpawnReceiptName(toolCall?.toolName, toolCall?.toolInput, result) !== undefined
|| subagentSpawnResultIndicatesRunning(toolCall?.toolName, result),
+ resultIsError: claudeProtocolResult && isSubagentResultError(result),
});
const StatusIcon = statusIcon(status);
const statusIconClassName = cn(
'text-[var(--text-secondary)]',
status === 'failed' && 'text-[var(--error-fg)]',
);
- // bash-task-card: 后台 Bash(run_in_background)与子 Agent 共用本卡,但视觉上
- // 是「后台命令」—— 终端图标 + shell provider 标签,避免用户把跑测试的 bash
- // 误读成一个子 Agent。
- const isBash = update?.taskType === 'local_bash';
- const isSubagent = !isWorkflow && !isBash;
- const provider = update?.provider
- ?? (toolCall?.toolName?.startsWith('collab:')
- ? 'codex'
- : toolCall?.toolName === PI_SUBAGENT_TOOL_NAME ? 'pi' : 'claude-code');
const AvatarIcon = isWorkflow ? Workflow : isBash ? SquareTerminal : Bot;
const title = compactText(
formatAgentTaskTitle(provider, (isWorkflow ? update?.workflowName : undefined) ??
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/__tests__/listSessionTasks.test.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/__tests__/listSessionTasks.test.ts
index 947fb883a1..603912a720 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/__tests__/listSessionTasks.test.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/__tests__/listSessionTasks.test.ts
@@ -156,6 +156,59 @@ describe('listSessionTasks 配对', () => {
]));
});
+ it('无 update 的历史回放读取持久化终态(与聊天卡同源,避免重载后终态漂移)', () => {
+ // tool_use 行的 agentMeta.agentTaskStatus 是 messagePersistBroadcaster 落库的
+ // 权威终态:重载(update 清空)后列表必须读它,而不是只看 isSubagentResultError。
+ const persisted = (status: 'completed' | 'failed' | 'stopped', clientId: string, toolUseId: string) =>
+ baseMessage({
+ clientId,
+ role: 'tool_use',
+ toolUseId,
+ content: { toolName: 'Task', input: {} },
+ agentMeta: { agentTaskStatus: status } as Message['agentMeta'],
+ });
+ const { completed } = listSessionTasks({
+ messages: [
+ persisted('stopped', 'c-stopped', 'toolu-stopped'),
+ toolResult('r-stopped', 'toolu-stopped', '<tool_use_error>Interrupted</tool_use_error>'),
+ persisted('completed', 'c-completed', 'toolu-completed'),
+ toolResult('r-completed', 'toolu-completed', '<tool_use_error>transient</tool_use_error>'),
+ ],
+ taskUpdates: undefined,
+ isSessionStreaming: false,
+ });
+
+ // 持久化 stopped 优先于错误回执(与 deriveAgentTaskStatus 的 persistedStatus 语义一致)。
+ expect(completed.find((it) => it.toolUseId === 'toolu-stopped')?.status).toBe('stopped');
+ // 持久化 completed 也优先于错误回执 —— 与聊天卡同源,不会重载后一边失败一边完成。
+ expect(completed.find((it) => it.toolUseId === 'toolu-completed')?.status).toBe('completed');
+ });
+
+ it('无 update 且未 settled 时,持久化终态(仅写 agentTaskStatus、无 tool result)优先', () => {
+ // 启动失败只写回 tool-use 的 agentTaskStatus、未产生 tool result:settled 与 update
+ // 都为 false。此时必须无条件采用持久化终态,而不是空闲显示 stopped / 流式显示
+ // running —— 与聊天卡(MessageStream 传终态)同口径。
+ const persistedOnly = (status: 'completed' | 'failed' | 'stopped', clientId: string, toolUseId: string) =>
+ baseMessage({
+ clientId,
+ role: 'tool_use',
+ toolUseId,
+ content: { toolName: 'Task', input: {} },
+ agentMeta: { agentTaskStatus: status } as Message['agentMeta'],
+ });
+ const { completed } = listSessionTasks({
+ messages: [
+ persistedOnly('failed', 'c-fail', 'toolu-fail'),
+ persistedOnly('stopped', 'c-stop', 'toolu-stop'),
+ ],
+ taskUpdates: undefined,
+ isSessionStreaming: true, // 即便流式,持久化 failed/stopped 也不得退化成 running
+ });
+
+ expect(completed.find((it) => it.toolUseId === 'toolu-fail')?.status).toBe('failed');
+ expect(completed.find((it) => it.toolUseId === 'toolu-stop')?.status).toBe('stopped');
+ });
+
it('历史 workflow(无 update):从结果文本「Task ID: xxx」提取 taskId(详情读 wf 文件用)', () => {
const { completed } = listSessionTasks({
messages: [
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts
index 71278953f8..d7c8d784c2 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts
@@ -19,8 +19,13 @@
import {
deriveAgentTaskStatus,
isAgentTaskToolName,
+
+ isClaudeSubagentToolName,
+ isSubagentResultError,
+
lookupSubagentRunStatus,
normalizeAgentTaskTerminalStatus,
+
subagentSpawnReceiptName,
subagentSpawnResultIndicatesRunning,
type SubagentRunStatusIndex,
@@ -280,9 +285,9 @@ export function listSessionTasks(input: {
if (m.role !== 'tool_result') continue;
if (typeof m.toolUseId === 'string' && m.toolUseId.length > 0) {
settledToolUseIds.add(m.toolUseId);
- if (!resultContentByToolUseId.has(m.toolUseId)) {
- resultContentByToolUseId.set(m.toolUseId, m.content);
- }
+ // 同一 toolUseId 多行结果按「末条胜出」覆盖(与共享 buildMessageToolResultPairing
+ // 及聊天流一致):先写中间 <tool_use_error>、后写最终成功结果时,不得因首条误判 failed。
+ resultContentByToolUseId.set(m.toolUseId, m.content);
}
}
@@ -339,6 +344,13 @@ export function listSessionTasks(input: {
// 的死任务(同步 Task 没有启动回执,永远不会有结果),断言 running 会让它
// 永久转圈且无任何收口路径,按 stopped(被中断)呈现。
const resultText = typeof resultContent === 'string' ? resultContent : undefined;
+ // 重载后与聊天卡(AgentTaskCard)共用 deriveAgentTaskStatus:持久化终态
+ // (agentMeta.agentTaskStatus)必须传入,否则列表与卡片会对同一任务给出不同终态。
+ const persistedStatus = msg.agentMeta?.agentTaskStatus;
+ // `<tool_use_error>` 是 Claude SDK 协议级标记,只对 Claude 子任务(Agent/Task)的结果
+ // 有意义。后台 Bash、PI subagent 与 Codex `collab:*` 的成功产物可能合法地以该前缀
+ // 开头,无条件判定会把成功任务误标成 failed(与 AgentTaskCard 同口径)。
+ const resultIsError = isClaudeSubagentToolName(toolName) && isSubagentResultError(resultText);
const durableStatus = isWorkflowTool
? undefined
: lookupSubagentRunStatus(subagentRunStatuses, toolUseId, update);
@@ -346,13 +358,27 @@ export function listSessionTasks(input: {
? update?.status ?? (settled ? 'completed' : isSessionStreaming ? 'running' : 'stopped')
: update
? deriveAgentTaskStatus(update.status, resultText, {
+
+ persistedStatus,
+
durableStatus,
+
resultIsLaunchReceipt:
subagentSpawnReceiptName(toolName, toolInput, resultText) !== undefined
|| subagentSpawnResultIndicatesRunning(toolName, resultText),
+ resultIsError,
})
: normalizeAgentTaskTerminalStatus(durableStatus)
- ?? (settled ? 'completed' : isSessionStreaming ? 'running' : 'stopped');
+ ?? (settled
+ // 无 live update 的历史回放:settled 即终态。也走 deriveAgentTaskStatus:
+ // 持久化终态优先;错误结果收口为 failed;普通结果 completed。未 settled
+ // 时持久化终态仍优先(启动失败只写 agentTaskStatus、无 tool result 的
+ // 场景),否则沿用 running/stopped 的死任务语义 —— 与聊天卡同口径。
+ ? deriveAgentTaskStatus(resultIsError ? undefined : 'completed', resultText, {
+ persistedStatus,
+ resultIsError,
+ })
+ : (persistedStatus ?? (isSessionStreaming ? 'running' : 'stopped')));
const provider: SessionTaskItem['provider'] =
update?.provider ?? (toolName.startsWith('collab:') ? 'codex' : 'claude-code');
diff --git a/apps/mobile/src/__tests__/subagentGrouping.test.ts b/apps/mobile/src/__tests__/subagentGrouping.test.ts
index 31022dea66..d99f61aba2 100644
--- a/apps/mobile/src/__tests__/subagentGrouping.test.ts
+++ b/apps/mobile/src/__tests__/subagentGrouping.test.ts
@@ -50,6 +50,11 @@ function agentResult(toolUseId: string, content: string, createdAt?: string): Re
return msg({ role: 'tool_result', content, toolUseId, createdAt });
}
+/** 显式 id / toolUseId 的 tool_result:模拟邻接的、非子任务自己的工具结果。 */
+function toolResult(id: string, toolUseId: string, content: string, createdAt?: string): RemoteMessage {
+ return msg({ id, role: 'tool_result', content, toolUseId, createdAt });
+}
+
function subagentGroups(items: readonly MobileMessageRenderItem[]): MobileSubagentGroupItem[] {
return items.filter((item): item is MobileSubagentGroupItem => item.type === 'subagent_group');
}
@@ -155,6 +160,45 @@ describe('subagent grouping (buildMobileMessageRenderItems)', () => {
expect(groups[0].status).toBe('completed');
});
+ it('历史 Agent 缺 toolUseId 时,从已配对的 secondaryBody 恢复 failed 终态', () => {
+ // buildSubagentResultMeta 对无 toolUseId 的结果没有条目;归一化层经 adjacency
+ // 把 tool_result 配对进 secondaryBody。若这里不读 secondaryBody,重连后同一失败
+ // 会被显示成 completed(streaming 时为 running)而不是承诺的 failed。
+ const items = buildMobileMessageRenderItems([
+ msg({
+ id: 'legacy-agent',
+ role: 'tool_use',
+ content: { toolUseId: null, toolName: 'Agent', input: { description: 'legacy' } },
+ toolUseId: null,
+ createdAt: '2026-01-01T00:00:01.000Z',
+ }),
+ msg({
+ id: 'legacy-result',
+ role: 'tool_result',
+ content: '<tool_use_error>legacy boom</tool_use_error>',
+ toolUseId: null,
+ createdAt: '2026-01-01T00:00:02.000Z',
+ }),
+ ]);
+ const groups = subagentGroups(items);
+ expect(groups).toHaveLength(1);
+ expect(groups[0].status).toBe('failed');
+ });
+
+ it('带 toolUseId 的在跑 Agent 即使有邻接 secondaryBody 也不提前收口', () => {
+ // 带 ID 的 Agent 尚无自身 result,归一化层可能把下一行其他工具的 result 经
+ // adjacency 临时借进 secondaryBody —— 该借用非权威,不得让任务提前 completed/
+ // failed(尤其邻接文本以 <tool_use_error> 开头时不能误判 failed)。
+ const items = buildMobileMessageRenderItems([
+ agentToolUse('A1', { subagentType: 'Explore', createdAt: '2026-01-01T00:00:01.000Z' }),
+ childTool('Bash', 'A1', '2026-01-01T00:00:02.000Z'),
+ toolResult('other-1', 'tu-other', '<tool_use_error>not the agent result</tool_use_error>'),
+ ], { isSessionStreaming: true });
+ const groups = subagentGroups(items);
+ expect(groups).toHaveLength(1);
+ expect(groups[0].status).toBe('running');
+ });
+
it('marks status running when no closing tool_result and session is streaming', () => {
const items = buildMobileMessageRenderItems([
agentToolUse('A1', { subagentType: 'Explore', createdAt: '2026-01-01T00:00:01.000Z' }),
@@ -202,6 +246,53 @@ describe('subagent grouping (buildMobileMessageRenderItems)', () => {
},
);
+ it('restores failed for a replayed protocol error result (<tool_use_error>)', () => {
+ // 回归(#3024):Mobile 重连/历史回放只有配对的 `<tool_use_error>` 结果、无 agentTaskStatus 时,
+ // subagent_group 曾只凭"存在 result"判 completed,同一启动失败在 Desktop 显示 failed、Mobile 显示
+ // completed(跨端终态不一致)。现与 Desktop deriveAgentTaskStatus 同口径恢复 failed。
+ const items = buildMobileMessageRenderItems([
+ agentToolUse('A1', { subagentType: 'Explore', createdAt: '2026-01-01T00:00:01.000Z' }),
+ agentResult('A1', '<tool_use_error>Agent launch failed: model unavailable</tool_use_error>', '2026-01-01T00:00:02.000Z'),
+ ]);
+ const group = subagentGroups(items)[0];
+ expect(group.status).toBe('failed');
+ });
+
+ it('keeps completed when only a nested block array result mentions tool_use_error mid-text (prefix match only)', () => {
+ // 防误报:只有以 `<tool_use_error>` 开头才是协议错误;正文中段出现不算(block 数组形态)。
+ const items = buildMobileMessageRenderItems([
+ agentToolUse('A1', { subagentType: 'Explore', createdAt: '2026-01-01T00:00:01.000Z' }),
+ msg({
+ role: 'tool_result',
+ toolUseId: 'A1',
+ createdAt: '2026-01-01T00:00:02.000Z',
+ content: [{ type: 'text', text: '总结:<tool_use_error> 是 SDK 的错误标记格式,本次任务已完整解析并修复它。' }],
+ }),
+ ]);
+ expect(subagentGroups(items)[0].status).toBe('completed');
+ });
+
+ it('still prefers the persisted terminal status over the protocol error fallback', () => {
+ // persisted agentTaskStatus 优先级不变:即使结果以 <tool_use_error> 开头,
+ // 已持久化的终态(如 failed→重试后 succeeded 场景的 stopped)不被覆盖。
+ const items = buildMobileMessageRenderItems([
+ msg({
+ id: 'agent',
+ role: 'tool_use',
+ toolUseId: 'toolu-agent',
+ content: { toolUseId: 'toolu-agent', toolName: 'Agent', input: { description: 'Retry' } },
+ agentMeta: { agentTaskStatus: 'stopped' },
+ }),
+ msg({
+ id: 'result',
+ role: 'tool_result',
+ toolUseId: 'toolu-agent',
+ content: '<tool_use_error>stale error from earlier attempt</tool_use_error>',
+ }),
+ ]);
+ expect(subagentGroups(items)[0].status).toBe('stopped');
+ });
+
it('leaves an ordinary session (no Agent / no parentUuid) byte-identical to the shared builder', () => {
const messages = [
msg({ id: 'u', role: 'user', content: { text: 'hi' }, createdAt: '2026-01-01T00:00:01.000Z' }),
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index f6bea0bfef..332f8b2fe4 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -4461,8 +4461,7 @@ function AgentTaskCard({
toolName: item.toolCall?.label,
toolInput: readAgentTaskToolInput(item.toolCall),
update: item.update,
- // 重连后 live update 为空:结构化终态优先,存量历史再由配对结果兜底 completed。
- // summary 仍来自 secondaryBody,与 desktop 对齐。
+ // 重连后 live update 为空:协议级子任务错误结果必须恢复为 failed。
result: item.toolCall?.secondaryBody,
persistedStatus: item.toolCall?.agentTaskStatus,
}),
diff --git a/apps/mobile/src/session/subagentGrouping.ts b/apps/mobile/src/session/subagentGrouping.ts
index b86ae0b866..b1c89b194b 100644
--- a/apps/mobile/src/session/subagentGrouping.ts
+++ b/apps/mobile/src/session/subagentGrouping.ts
@@ -12,6 +12,7 @@ import {
buildMessageRenderItems,
type MessageRenderOptions,
} from '@cindy/maker-shared/message-render';
+import { isSubagentResultError } from '@cindy/maker-shared/agent-task';
import type { NormalizedRemoteMessage } from '@/session/messageNormalize';
import type { RemoteMessage } from '@/session/types';
import type { MobileMessageRenderItem, MobileSubagentGroupItem } from '@/session/messageRenderModel';
@@ -23,6 +24,27 @@ export const MAX_SUBAGENT_NEST_DEPTH = 5;
export interface SubagentResultMeta {
createdAtMs: number;
+ /** 配对 tool_result 是否为 Claude 协议级错误(`<tool_use_error>` 开头,与共享 deriveAgentTaskStatus 同口径)。 */
+ isError?: boolean;
+}
+
+/** 从原始 tool_result 行抽文本(与共享 messageContentToPreview 同形态:字符串 / block 数组 / {text} / {content} 对象)。 */
+function resultTextOf(content: unknown): string | undefined {
+ if (typeof content === 'string') return content;
+ if (Array.isArray(content)) {
+ const joined = content
+ .map((block) => {
+ const record = readRecord(block);
+ return typeof record?.text === 'string' ? record.text : '';
+ })
+ .filter(Boolean)
+ .join('\n');
+ return joined || undefined;
+ }
+ const record = readRecord(content);
+ return typeof record?.text === 'string'
+ ? record.text
+ : typeof record?.content === 'string' ? record.content : undefined;
}
/** 从原始消息建 `toolUseId → tool_result.createdAt(ms)` 映射(归一化层会丢弃 tool_result,故从 raw 取)。 */
@@ -33,7 +55,11 @@ export function buildSubagentResultMeta(messages: readonly RemoteMessage[]): Map
const id = rawToolUseId(message);
if (!id) continue;
const ms = Date.parse(message.createdAt);
- if (Number.isFinite(ms)) map.set(id, { createdAtMs: ms });
+ if (!Number.isFinite(ms)) continue;
+ // 同一 toolUseId 多行时保留最后一条(与共享 buildMessageToolResultPairing 的
+ // 覆盖语义一致),避免回放多条结果时取到旧的中间态;协议错误判定与共享
+ // deriveAgentTaskStatus 同口径。
+ map.set(id, { createdAtMs: ms, isError: isSubagentResultError(resultTextOf(message.content)) });
}
return map;
}
@@ -145,10 +171,20 @@ function buildSubagentGroup(
const subagentType = readString(input?.subagent_type);
const summary = agent.secondaryBody && agent.secondaryBody.trim() ? agent.secondaryBody : null;
const result = id ? resultMeta.get(id) : undefined;
+ // 历史 Agent 缺 toolUseId 时 buildSubagentResultMeta 无条目,但归一化层已通过
+ // adjacency 把配对 tool_result 放进 secondaryBody —— 这份兜底只对无 ID 的旧任务
+ // 生效:带 ID 的任务必须等待精确配对结果,否则邻接借用(可能是另一工具的 result)
+ // 会在真正结果到达前把任务误判为 completed/failed。
+ const legacyAdjacencyFallback = !id;
+ const hasResult = !!result || (legacyAdjacencyFallback && !!summary);
+ const resultIsError =
+ result?.isError === true
+ || (legacyAdjacencyFallback && isSubagentResultError(agent.secondaryBody ?? undefined));
const status = computeStatus(
agent.agentTaskStatus,
- !!result,
+ hasResult,
options.isSessionStreaming === true,
+ resultIsError,
);
const startMs = Date.parse(agent.createdAt);
const durationMs = result && Number.isFinite(startMs) && result.createdAtMs >= startMs
@@ -166,13 +202,16 @@ function buildSubagentGroup(
};
}
-// 精确结构化终态优先;存量历史缺字段时保留原有 result/streaming 兼容兜底。
+// 精确结构化终态优先;协议错误结果(`<tool_use_error>`)恢复 failed;存量历史缺字段时
+// 保留原有 result/streaming 兼容兜底(普通结果不误判,与 Desktop deriveAgentTaskStatus 同口径)。
function computeStatus(
persistedStatus: MobileSubagentGroupItem['status'] | undefined,
hasResult: boolean,
streaming: boolean,
+ resultIsError: boolean,
): MobileSubagentGroupItem['status'] {
if (persistedStatus) return persistedStatus;
+ if (resultIsError && hasResult) return 'failed';
if (hasResult) return 'completed';
return streaming ? 'running' : 'completed';
}
diff --git a/packages/maker-shared/src/__tests__/agentTask.test.ts b/packages/maker-shared/src/__tests__/agentTask.test.ts
index cc8d84790f..cb323f71af 100644
--- a/packages/maker-shared/src/__tests__/agentTask.test.ts
+++ b/packages/maker-shared/src/__tests__/agentTask.test.ts
@@ -6,6 +6,8 @@ import {
deriveAgentTaskStatus,
findAgentTaskUpdate,
isAgentTaskToolName,
+ isClaudeSubagentToolName,
+ isSubagentResultError,
isSubagentSpawnToolName,
lookupSubagentRunStatus,
mergeAgentTaskUpdate,
@@ -138,6 +140,49 @@ describe('deriveAgentTaskStatus', () => {
})).toBe('completed');
});
+
+ it('returns failed when resultIsError is true and result is non-empty', () => {
+ expect(deriveAgentTaskStatus(undefined, '<tool_use_error>Auth failed</tool_use_error>', {
+ resultIsError: true,
+ })).toBe('failed');
+ });
+
+ it('returns failed even when updateStatus is running when resultIsError is true', () => {
+ expect(deriveAgentTaskStatus('running', '<tool_use_error>timeout</tool_use_error>', {
+ resultIsError: true,
+ })).toBe('failed');
+ });
+
+ it('shared card model projects protocol error results as failed', () => {
+ expect(buildAgentTaskCardModel({
+ toolName: 'Task',
+ result: '<tool_use_error>launch failed</tool_use_error>',
+ }).status).toBe('failed');
+ });
+
+ it('persisted status wins over resultIsError', () => {
+ expect(deriveAgentTaskStatus(undefined, '<tool_use_error>fail</tool_use_error>', {
+ resultIsError: true,
+ persistedStatus: 'completed',
+ })).toBe('completed');
+ });
+
+ it('resultIsError is ignored when result is empty', () => {
+ expect(deriveAgentTaskStatus(undefined, '', {
+ resultIsError: true,
+ })).toBe('running');
+ });
+
+ it('explicit stopped / failed terminal status survives a paired error result', () => {
+ // live 用户中断 + SDK <tool_use_error> 回执:显式 stopped 不得被降级成 failed。
+ expect(deriveAgentTaskStatus('stopped', '<tool_use_error>Interrupted</tool_use_error>', {
+ resultIsError: true,
+ })).toBe('stopped');
+ expect(deriveAgentTaskStatus('failed', '<tool_use_error>crash</tool_use_error>', {
+ resultIsError: true,
+ })).toBe('failed');
+ });
+
it('keeps a live running task running when the durable run is running, whatever the result text', () => {
expect(deriveAgentTaskStatus('running', 'Some future receipt wording', {
durableStatus: 'running',
@@ -195,6 +240,7 @@ describe('buildSubagentRunStatusIndex / lookupSubagentRunStatus', () => {
it('skips runs with an unknown status', () => {
const index = buildSubagentRunStatusIndex([{ parentToolUseId: 'toolu_1', status: 'queued' }]);
expect(index.size).toBe(0);
+
});
});
@@ -425,6 +471,51 @@ describe('findAgentTaskUpdate', () => {
});
describe('buildAgentTaskCardModel', () => {
+ // Review #3024 (head 954ed53) P1: the shared card model must narrow
+ // `<tool_use_error>` by tool name like the desktop callers — PI subagent /
+ // Codex collab work products may legitimately start with that marker.
+ it('does not project a PI subagent protocol-marker work product as failed', () => {
+ const model = buildAgentTaskCardModel({
+ toolName: 'subagent',
+ toolInput: { prompt: 'write the report' },
+ result: '<tool_use_error>校验报告:3 处不一致</tool_use_error>',
+ });
+ expect(model.status).toBe('completed');
+ expect(model.provider).toBe('pi');
+ });
+
+ it('does not project a Codex collab protocol-marker work product as failed', () => {
+ const model = buildAgentTaskCardModel({
+ toolName: 'collab:spawn',
+ result: '<tool_use_error>errors: none</tool_use_error>',
+ });
+ expect(model.status).toBe('completed');
+ expect(model.provider).toBe('codex');
+ });
+
+ it('still projects a Claude tool protocol-marker result as failed', () => {
+ const model = buildAgentTaskCardModel({
+ toolName: 'Task',
+ result: '<tool_use_error>launch failed</tool_use_error>',
+ });
+ expect(model.status).toBe('failed');
+ });
+
+ it('keeps the provider fallback (claude-code) for history replay without toolName', () => {
+ const model = buildAgentTaskCardModel({
+ result: '<tool_use_error>launch failed</tool_use_error>',
+ });
+ expect(model.status).toBe('failed');
+ });
+
+ it('history replay with an explicit non-Claude provider stays completed', () => {
+ const model = buildAgentTaskCardModel({
+ result: '<tool_use_error>报告正文</tool_use_error>',
+ update: { provider: 'codex', taskId: 'c1', parentToolUseId: 'c1', status: 'running' },
+ });
+ expect(model.status).toBe('completed');
+ });
+
it('REPRO: treats a paired final result as terminal when the live update is stale running', () => {
const model = buildAgentTaskCardModel({
toolName: 'collab:spawnAgent',
@@ -660,3 +751,57 @@ describe('buildAgentTaskCardModel', () => {
expect(model.summary).toBe('thread-2: done');
});
});
+
+describe('isSubagentResultError', () => {
+ it('returns false for empty/undefined/null', () => {
+ expect(isSubagentResultError(undefined)).toBe(false);
+ expect(isSubagentResultError('')).toBe(false);
+ expect(isSubagentResultError(' ')).toBe(false);
+ });
+
+ it('returns true for Claude protocol <tool_use_error>', () => {
+ expect(isSubagentResultError('<tool_use_error>Authentication failed</tool_use_error>')).toBe(true);
+ });
+
+ it('returns false for generic <error> prefix (too generic for work product)', () => {
+ // A subagent returning <error>校验报告</error> as valid output must not be
+ // misclassified as failure. Only <tool_use_error> is a reliable protocol marker.
+ expect(isSubagentResultError('<error>Transport failure</error>')).toBe(false);
+ expect(isSubagentResultError('<error>校验报告</error>')).toBe(false);
+ });
+
+ it('returns false for JSON with error-looking fields (authority boundary)', () => {
+ // Subagent result content is arbitrary user work product.
+ // Fields like "errors", "status", "stderr" are data, not execution signals.
+ expect(isSubagentResultError('{"errors":["not found"]}')).toBe(false);
+ expect(isSubagentResultError('{"status":"failed"}')).toBe(false);
+ expect(isSubagentResultError('{"stderr":"something went wrong"}')).toBe(false);
+ expect(isSubagentResultError('{"error":"custom message"}')).toBe(false);
+ expect(isSubagentResultError('{"success":false}')).toBe(false);
+ expect(isSubagentResultError('{"ok":false}')).toBe(false);
+ });
+
+ it('returns false for natural language error phrases', () => {
+ expect(isSubagentResultError('failed to launch')).toBe(false);
+ expect(isSubagentResultError('unable to start the service')).toBe(false);
+ expect(isSubagentResultError('Error: something happened')).toBe(false);
+ });
+});
+
+describe('isClaudeSubagentToolName', () => {
+ it('accepts only Claude subagent tools', () => {
+ expect(isClaudeSubagentToolName('Agent')).toBe(true);
+ expect(isClaudeSubagentToolName('Task')).toBe(true);
+ });
+
+ it('rejects tools whose successful output may legitimately start with <tool_use_error>', () => {
+ // 后台 Bash 把该标记当搜索命中打印、PI subagent / Codex collab 透传工作产物时,
+ // 按 Claude 协议收口会把成功任务误标成 failed。
+ expect(isClaudeSubagentToolName('Bash')).toBe(false);
+ expect(isClaudeSubagentToolName(PI_SUBAGENT_TOOL_NAME)).toBe(false);
+ expect(isClaudeSubagentToolName('collab:spawn')).toBe(false);
+ expect(isClaudeSubagentToolName('collab:spawnAgent')).toBe(false);
+ expect(isClaudeSubagentToolName('Workflow')).toBe(false);
+ expect(isClaudeSubagentToolName(undefined)).toBe(false);
+ });
+});
diff --git a/packages/maker-shared/src/agentTask.ts b/packages/maker-shared/src/agentTask.ts
index dda4cfa28f..5837d87d95 100644
--- a/packages/maker-shared/src/agentTask.ts
+++ b/packages/maker-shared/src/agentTask.ts
@@ -180,7 +180,11 @@ export function deriveAgentTaskStatus(
options?: {
resultIsLaunchReceipt?: boolean;
persistedStatus?: AgentTaskTerminalStatus;
+
+ resultIsError?: boolean;
+
durableStatus?: AgentTaskStatus;
+
},
): AgentTaskStatus {
const persistedStatus = normalizeAgentTaskTerminalStatus(options?.persistedStatus);
@@ -190,10 +194,54 @@ export function deriveAgentTaskStatus(
const resultIsLaunchReceipt =
options?.resultIsLaunchReceipt === true || options?.durableStatus === 'running';
const hasResult = typeof result === 'string' && result.trim().length > 0;
+ // resultIsError 只应收口 stale `running` / 缺失 live update 的历史回放;显式
+ // failed / stopped 是用户或系统声明的终态,不得被配对的 tool result 覆盖 ——
+ // live `stopped`(用户中断)配上 SDK 的 <tool_use_error> 回执会被误显示为失败。
+ if (
+ options?.resultIsError
+ && hasResult
+ && (updateStatus === undefined || updateStatus === 'running')
+ ) {
+ return 'failed';
+ }
if (updateStatus === 'running' && hasResult && !resultIsLaunchReceipt) return 'completed';
return updateStatus ?? (hasResult ? 'completed' : 'running');
}
+/**
+
+ * 判断子任务工具结果是否以协议级错误收尾(历史回放恢复 failed 的依据)。
+ *
+ * 仅识别 Claude SDK 协议标记 `<tool_use_error>` — 这是 SDK 在 tool call 失败时
+ * 发出的结构化错误格式。不解析任意 JSON 字段或自然语言错误短语,因为子任务结果
+ * 内容是用户工作产物,其中 "errors"/"status"/"stderr" 等字段是数据而非执行信号。
+ *
+ * 调用方约束:此函数仅应在已确认为子任务上下文的调用点使用
+ * (AgentTaskCard / listSessionTasks)。普通工具结果包含 `<tool_use_error>` 时
+ * 不应传入此函数,否则会将非子任务结果误判为失败。
+ *
+ * Authority: Claude protocol `<tool_use_error>` — SDK 在 tool call 失败时发出。
+ */
+export function isSubagentResultError(result: string | undefined): boolean {
+ const text = typeof result === 'string' ? result.trim() : '';
+ if (text.length === 0) return false;
+ // Only trust protocol-level error markers. Subagent result content is arbitrary
+ // user work product -- fields like "errors", "status", "stderr" in JSON output
+ // are data, not execution failure signals. Parsing arbitrary body for
+ // error-looking fields creates false positives that mark successful tasks as
+ // failed after Desktop reload / Mobile reconnect.
+ //
+ // Authority sources:
+ // 1. Claude protocol <tool_use_error> -- emitted by the SDK when a tool call fails
+ // 2. Persisted structured terminal status (agentTaskStatus) -- written by
+ // messagePersistBroadcaster on terminal observations
+ //
+ // Note: <error> prefix removed -- too generic. A subagent returning
+ // `<error>校验报告</error>` as work output would be misclassified as failure.
+ // Only <tool_use_error> is a reliable protocol-owned error marker.
+ return text.startsWith('<tool_use_error>');
+}
+
/**
* Durable `subagent_runs` status, keyed by every id a spawning tool call or its
* live update may carry (parent tool-use id, harness task id, Cindy aliases).
@@ -243,6 +291,7 @@ export function lookupSubagentRunStatus(
if (status) return status;
}
return undefined;
+
}
/**
@@ -263,6 +312,18 @@ export function isAgentTaskToolName(toolName: string): boolean {
return isSubagentSpawnToolName(toolName) || toolName.startsWith('collab:');
}
+/**
+ * Claude 子任务工具名(`Agent` / `Task`)。
+ *
+ * `isSubagentResultError` 识别的 `<tool_use_error>` 是 Claude SDK 协议级标记,只对这两个
+ * 工具的结果有意义。后台 Bash、PI subagent 与 Codex `collab:*` 的成功产物可能合法地以该
+ * 前缀开头(例如把该标记当成搜索命中打印出来),无条件按它收口会把成功任务误标成
+ * `failed`。调用方必须先确认工具名属于 Claude 子任务,再把结果交给 `isSubagentResultError`。
+ */
+export function isClaudeSubagentToolName(toolName: string | undefined): boolean {
+ return toolName === 'Agent' || toolName === 'Task';
+}
+
/** PI 子代理工具名 —— maker-core 的 pi 扩展注册端与本文件的卡片判据共用,不各写字面量。 */
export const PI_SUBAGENT_TOOL_NAME = 'subagent';
@@ -520,20 +581,32 @@ export function buildAgentTaskCardModel(input: {
durableStatus?: AgentTaskStatus;
}): AgentTaskCardModel {
const { toolName, toolInput, update, result, persistedStatus, durableStatus } = input;
+ // `<tool_use_error>` is only a trustworthy failure witness for Claude
+ // subagent tools (Agent/Task). PI `subagent` / Codex `collab:*` results are
+ // arbitrary work products that may legitimately start with that marker, so
+ // the shared card model narrows by tool name exactly like the desktop
+ // callers (AgentTaskCard / listSessionTasks). With no tool name (history
+ // replay of a legacy update card) fall back to the provider heuristic below,
+ // matching AgentTaskCard's claudeProtocolResult.
+ const providerFallback: 'claude-code' | 'codex' | 'pi' =
+ update?.provider
+ ?? (toolName?.startsWith('collab:')
+ ? 'codex'
+ : toolName === PI_SUBAGENT_TOOL_NAME
+ ? 'pi'
+ : 'claude-code');
+ const claudeProtocolResult = toolName !== undefined
+ ? isClaudeSubagentToolName(toolName)
+ : providerFallback === 'claude-code';
const status = deriveAgentTaskStatus(update?.status, result, {
persistedStatus,
durableStatus,
resultIsLaunchReceipt:
subagentSpawnReceiptName(toolName, toolInput, result) !== undefined
|| subagentSpawnResultIndicatesRunning(toolName, result),
+ resultIsError: claudeProtocolResult && isSubagentResultError(result),
});
- const provider: 'claude-code' | 'codex' | 'pi' =
- update?.provider
- ?? (toolName?.startsWith('collab:')
- ? 'codex'
- : toolName === PI_SUBAGENT_TOOL_NAME
- ? 'pi'
- : 'claude-code');
+ const provider = providerFallback;
const title = compactText(
formatAgentTaskTitle(provider, update?.title
?? readInputString(toolInput, ['description', 'task', 'name'])