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(subagent): 修复乱序模型与同步持久化

davidfbc2c0c9f361
diff --git a/apps/desktop/src/main/localDb/__tests__/subagentRuns.test.ts b/apps/desktop/src/main/localDb/__tests__/subagentRuns.test.ts
index d8837dd2d2..7051864d08 100644
--- a/apps/desktop/src/main/localDb/__tests__/subagentRuns.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/subagentRuns.test.ts
@@ -386,6 +386,56 @@ describe('durable Subagent runs', () => {
});
});
+ it('persists a synchronous completed Claude Agent result as its first observation', async () => {
+ insertMessage(
+ 'claude-sync-tool-use',
+ 'tool_use',
+ '{}',
+ 'toolu_sync_agent',
+ 900,
+ );
+
+ const orphanTerminal = await persistSubagentTaskUpdate(
+ 'session-1',
+ observed(
+ {
+ provider: 'claude-code',
+ taskId: 'orphan-terminal',
+ status: 'completed',
+ },
+ { kind: 'terminal' },
+ ),
+ 'claude-code',
+ );
+ expect(orphanTerminal).toBeNull();
+
+ const created = await persistSubagentTaskUpdate(
+ 'session-1',
+ observed(
+ {
+ provider: 'claude-code',
+ taskId: 'agent-sync',
+ parentToolUseId: 'toolu_sync_agent',
+ status: 'completed',
+ model: 'vendor-a/model-sol',
+ usage: { totalTokens: 22_113, toolUses: 0, durationMs: 4_949 },
+ updatedAt: '1970-01-01T00:00:01.000Z',
+ },
+ { kind: 'spawn' },
+ ),
+ 'claude-code',
+ );
+
+ expect(created).toMatchObject({ created: true, firstForSession: true });
+ expect(await getSubagentRunDetail('session-1', 'claude-code', created!.runId)).toMatchObject({
+ logicalAgentId: 'agent-sync',
+ parentToolUseId: 'toolu_sync_agent',
+ status: 'completed',
+ model: 'vendor-a/model-sol',
+ usage: { totalTokens: 22_113, toolUses: 0, durationMs: 4_949 },
+ });
+ });
+
it('honors message rewind and clear boundaries without deleting audit rows', async () => {
insertMessage('tool-use-2', 'tool_use', '{}', 'parent-tool-2', 900);
insertMessage('tool-result-before-clear', 'tool_result', 'old result', 'parent-tool-2', 950);
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/translator-subagent-model.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/translator-subagent-model.test.ts
index 4358f72963..f16ecdd176 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/translator-subagent-model.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/translator-subagent-model.test.ts
@@ -512,7 +512,7 @@ describe('Claude Code translator subagent model attribution', () => {
model: 'vendor-a/model-sol',
usage: { totalTokens: 22_113, toolUses: 0, durationMs: 4_949 },
subagentObservation: {
- kind: 'terminal',
+ kind: 'spawn',
logicalSubagentId: 'agent-sync',
parentToolUseId: 'toolu_sync_agent',
},
@@ -552,11 +552,11 @@ describe('Claude Code translator subagent model attribution', () => {
status: 'completed',
model: 'provider-b/model-terra',
usage: { totalTokens: 84, toolUses: 2, durationMs: 1_250 },
- subagentObservation: { kind: 'terminal' },
+ subagentObservation: { kind: 'spawn' },
});
});
- it('does not guess a requested model when a completed Agent result has no actual model', async () => {
+ it('uses a child runtime model when a completed Agent result has no resolvedModel', async () => {
const queue = createAsyncQueue<AgentEvent>();
const ctx = createCtx();
@@ -578,6 +578,15 @@ describe('Claude Code translator subagent model attribution', () => {
queue,
ctx,
);
+ translateSdkMessage(
+ {
+ type: 'assistant',
+ parent_tool_use_id: 'toolu_sync_agent',
+ message: { model: 'vendor-runtime/model-actual', content: [] },
+ },
+ queue,
+ ctx,
+ );
translateSdkMessage(
{
type: 'user',
@@ -600,9 +609,103 @@ describe('Claude Code translator subagent model attribution', () => {
taskId: 'agent-sync',
parentToolUseId: 'toolu_sync_agent',
status: 'completed',
+ model: 'vendor-runtime/model-actual',
+ subagentObservation: { kind: 'spawn' },
+ });
+ expect(taskUpdates.at(-1)?.data).not.toMatchObject({ model: 'requested-model' });
+ });
+
+ it('lets a full child assistant replace an earlier stream model when no resolvedModel exists', async () => {
+ const queue = createAsyncQueue<AgentEvent>();
+ const ctx = createCtx();
+
+ translateSdkMessage(
+ {
+ type: 'stream_event',
+ parent_tool_use_id: 'toolu_sync_agent',
+ event: {
+ type: 'message_start',
+ message: { model: 'vendor-stream/model-early', usage: { input_tokens: 0 } },
+ },
+ },
+ queue,
+ ctx,
+ );
+ translateSdkMessage(
+ {
+ type: 'user',
+ message: {
+ content: [{ type: 'tool_result', tool_use_id: 'toolu_sync_agent', content: 'done' }],
+ },
+ toolUseResult: { status: 'completed', agentId: 'agent-sync' },
+ },
+ queue,
+ ctx,
+ );
+ translateSdkMessage(
+ {
+ type: 'assistant',
+ parent_tool_use_id: 'toolu_sync_agent',
+ message: { model: 'vendor-assistant/model-actual', content: [] },
+ },
+ queue,
+ ctx,
+ );
+
+ const taskUpdates = (await collect(queue)).filter(
+ (event) => event.type === 'agent_task_update',
+ );
+ expect(taskUpdates.at(-2)?.data).toMatchObject({
+ taskId: 'agent-sync',
+ status: 'completed',
+ model: 'vendor-stream/model-early',
+ subagentObservation: { kind: 'spawn' },
+ });
+ expect(taskUpdates.at(-1)?.data).toMatchObject({
+ taskId: 'agent-sync',
+ status: 'completed',
+ model: 'vendor-assistant/model-actual',
subagentObservation: { kind: 'terminal' },
});
- expect(taskUpdates.at(-1)?.data).not.toHaveProperty('model');
+ });
+
+ it('keeps resolvedModel authoritative over a later full child assistant', async () => {
+ const queue = createAsyncQueue<AgentEvent>();
+ const ctx = createCtx();
+
+ translateSdkMessage(
+ {
+ type: 'user',
+ message: {
+ content: [{ type: 'tool_result', tool_use_id: 'toolu_sync_agent', content: 'done' }],
+ },
+ toolUseResult: {
+ status: 'completed',
+ agentId: 'agent-sync',
+ resolvedModel: 'vendor-resolved/model-authoritative',
+ },
+ },
+ queue,
+ ctx,
+ );
+ translateSdkMessage(
+ {
+ type: 'assistant',
+ parent_tool_use_id: 'toolu_sync_agent',
+ message: { model: 'vendor-assistant/model-late', content: [] },
+ },
+ queue,
+ ctx,
+ );
+
+ const taskUpdates = (await collect(queue)).filter(
+ (event) => event.type === 'agent_task_update',
+ );
+ expect(taskUpdates.at(-1)?.data).toMatchObject({
+ taskId: 'agent-sync',
+ status: 'completed',
+ model: 'vendor-resolved/model-authoritative',
+ });
});
it('repairs zero task tokens from host usage and preserves zero tool uses', async () => {
diff --git a/packages/maker-core/src/agents/claude-code/translator.ts b/packages/maker-core/src/agents/claude-code/translator.ts
index f30bde0ecc..6a4dccdd43 100644
--- a/packages/maker-core/src/agents/claude-code/translator.ts
+++ b/packages/maker-core/src/agents/claude-code/translator.ts
@@ -601,16 +601,21 @@ export function translateSdkMessage(
const subagentResult = extractSubagentToolResult(msg);
if (subagentResult) {
const { taskId, parentToolUseId, model, prompt, status, usage } = subagentResult;
+ const actualModel = model
+ ?? ctx.rt.resolvedSubagentModelByParentToolUseId.get(parentToolUseId)
+ ?? ctx.rt.streamModelByParentToolUseId.get(parentToolUseId);
ctx.rt.subagentParentToolUseIdByTaskId.set(taskId, parentToolUseId);
ctx.rt.confirmedSubagentTaskIds.add(taskId);
ctx.rt.excludedSubagentTaskIds.delete(taskId);
ctx.rt.subagentStatusByParentToolUseId.set(parentToolUseId, status);
if (model) {
ctx.rt.resolvedSubagentModelByParentToolUseId.set(parentToolUseId, model);
- ctx.rt.publishedSubagentModelByParentToolUseId.set(parentToolUseId, model);
+ }
+ if (actualModel) {
+ ctx.rt.publishedSubagentModelByParentToolUseId.set(parentToolUseId, actualModel);
}
if (status === 'running' && prompt) {
- ctx.onSubagentTaskLaunched?.({ taskId, parentToolUseId, prompt, model });
+ ctx.onSubagentTaskLaunched?.({ taskId, parentToolUseId, prompt, model: actualModel });
}
queue.push({
type: 'agent_task_update',
@@ -620,11 +625,14 @@ export function translateSdkMessage(
parentToolUseId,
status,
subagentObservation: {
- kind: status === 'running' ? 'spawn' : 'terminal',
+ // A synchronous completed Agent result may be the first and only
+ // lifecycle observation. It is authoritative to create the run,
+ // while the completed status still keeps the record terminal.
+ kind: 'spawn',
logicalSubagentId: taskId,
parentToolUseId,
},
- ...(model ? { model } : {}),
+ ...(actualModel ? { model: actualModel } : {}),
...(usage ? { usage } : {}),
},
source: 'claude-code',
diff --git a/packages/maker-core/src/agents/codex/__tests__/subagentLiveCards.test.ts b/packages/maker-core/src/agents/codex/__tests__/subagentLiveCards.test.ts
index d207ec6ec9..a2861c245f 100644
--- a/packages/maker-core/src/agents/codex/__tests__/subagentLiveCards.test.ts
+++ b/packages/maker-core/src/agents/codex/__tests__/subagentLiveCards.test.ts
@@ -362,6 +362,46 @@ describe('createSubagentLiveCardTracker', () => {
).toMatchObject({ model: 'provider-b/model-actual' });
});
+ it('does not let a late nested spawn fallback replace an observed runtime model', () => {
+ const tracker = createSubagentLiveCardTracker({
+ now: () => 0,
+ subagentModelFallback: 'provider-config/model-child',
+ });
+ tracker.noteSpawnItem(v2SpawnItem('card-parent', 't-parent'));
+ tracker.noteDescendantThread('t-parent', 'root-thread', 'provider-runtime/model-actual');
+ tracker.noteDescendantThread('t-grandchild', 't-parent', 'provider-runtime/model-actual');
+
+ // The nested spawn item can arrive after thread/started. Its configured
+ // fallback is lower-confidence than the already observed runtime model.
+ expect(
+ tracker.noteDescendantThread('t-grandchild', 't-parent', undefined, false, true),
+ ).toBeNull();
+ expect(
+ tracker.handleDescendantNotification('t-grandchild', 'turn/started', {
+ turn: { id: 'grandchild-turn' },
+ }),
+ ).toMatchObject({ model: 'provider-runtime/model-actual' });
+ });
+
+ it('preserves a buffered runtime model when lower-priority nested spawn metadata arrives later', () => {
+ const tracker = createSubagentLiveCardTracker({
+ now: () => 0,
+ subagentModelFallback: 'provider-config/model-child',
+ });
+ tracker.noteDescendantThread('t-grandchild', 't-parent', 'provider-runtime/model-actual');
+ tracker.noteDescendantThread('t-grandchild', 't-parent', undefined, false, true);
+ tracker.noteSpawnItem(v2SpawnItem('card-parent', 't-parent'));
+
+ expect(
+ tracker.handleDescendantNotification('t-grandchild', 'turn/started', {
+ turn: { id: 'grandchild-turn' },
+ }),
+ ).toMatchObject({ model: null });
+ expect(
+ tracker.noteDescendantThread('t-parent', 'root-thread', 'provider-runtime/model-actual'),
+ ).toMatchObject({ model: 'provider-runtime/model-actual' });
+ });
+
it('preserves nested inheritance when lineage arrives before the parent spawn item', () => {
const tracker = createSubagentLiveCardTracker({ now: () => 0 });
expect(
@@ -614,6 +654,31 @@ describe('createSubagentLiveCardTracker', () => {
expect(tracker.noteSpawnItem(v1SpawnItem('card-v1', ['t-a', 't-b']))?.status).toBe('failed');
});
+ it('re-asserts running for a fresh completed-only spawn whose agents are still active', () => {
+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });
+ const completedOnly = {
+ ...v1SpawnItem('card-v1', ['t-a']),
+ status: 'completed',
+ agentsStates: { 't-a': { status: 'running' } },
+ };
+
+ expect(tracker.noteSpawnItem(completedOnly, undefined, 'completed')).toMatchObject({
+ taskId: 'card-v1',
+ status: 'running',
+ });
+ });
+
+ it('does not add a redundant frame for a fresh completed-only spawn whose agents are terminal', () => {
+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });
+ const completedOnly = {
+ ...v1SpawnItem('card-v1', ['t-a']),
+ status: 'completed',
+ agentsStates: { 't-a': { status: 'completed' } },
+ };
+
+ expect(tracker.noteSpawnItem(completedOnly, undefined, 'completed')).toBeNull();
+ });
+
it('never overwrites a failed spawn terminal state with a running aggregate', () => {
// V1 的 spawn 以 status:'failed' 收口时,translator 已推过 failed 帧。此前"已登记就回传
// 快照"会补一帧聚合状态,而那时子线程还标着 running → 真实失败被盖回运行中(review)。
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index 15969fc603..238de3751d 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -19216,6 +19216,81 @@ describe('CodexAgent turn lifecycle', () => {
await handle.close();
});
+ it('REPRO: keeps a completed-only spawn running while its agentsStates are active', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-completed-only-running-collab',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const handlers = host.getThreadHandlers();
+ expect(handlers).toBeDefined();
+ const iterator = handle.events()[Symbol.asyncIterator]();
+
+ handlers!.turnStarted?.({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-parent' },
+ });
+ handlers!.turnCompleted?.({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-parent', status: 'completed' },
+ });
+ expect(await nextEvent(iterator)).toMatchObject({ type: 'status' });
+ expect(await nextEvent(iterator)).toMatchObject({ type: 'done' });
+
+ handlers!.itemCompleted?.({
+ threadId: 'start-thread-id',
+ turnId: 'turn-parent',
+ item: {
+ type: 'collabAgentToolCall',
+ id: 'collab-completed-only-running',
+ tool: 'spawnAgent',
+ status: 'completed',
+ senderThreadId: 'start-thread-id',
+ receiverThreadIds: ['child-thread'],
+ prompt: 'continue after the spawn tool returns',
+ agentsStates: { 'child-thread': { status: 'running' } },
+ },
+ } as never);
+
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'tool_use',
+ turnScope: 'background',
+ data: { toolUseId: 'collab-completed-only-running' },
+ });
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'tool_result_full',
+ turnScope: 'background',
+ });
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'tool_result',
+ turnScope: 'background',
+ });
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'agent_task_update',
+ turnScope: 'background',
+ data: { taskId: 'collab-completed-only-running', status: 'completed' },
+ });
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'agent_task_update',
+ turnScope: 'background',
+ data: { taskId: 'collab-completed-only-running', status: 'running' },
+ });
+
+ handlers!.descendantNotification?.('child-thread', 'turn/completed', {
+ threadId: 'child-thread',
+ turn: { id: 'child-turn', status: 'completed' },
+ });
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'agent_task_update',
+ turnScope: 'background',
+ data: { taskId: 'collab-completed-only-running', status: 'completed' },
+ });
+
+ await handle.close();
+ });
+
it('REPRO: preserves a late collab-agent terminal update after a terminal error', async () => {
const agent = new CodexAgent(createDeps());
const host = installFakeHost(agent);
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 0e2c8177d9..6712d0a90f 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -140,6 +140,7 @@ import {
import {
createSubagentLiveCardTracker,
type SubagentLiveCardUpdate,
+ type SubagentSpawnItemPhase,
} from './subagent-live-cards.js';
import {
TurnRetryTracker,
@@ -4470,12 +4471,13 @@ export class CodexAgent extends BaseAgent {
const noteSubagentSpawnItem = (
item: unknown,
rootTurnId: string,
+ phase: SubagentSpawnItemPhase,
): SubagentLiveCardUpdate | null => {
if (!registerSubagentSpawnLineage(item, rootTurnId)) return null;
// 先接 host 路由再进 tracker:registerDescendantLineage 会把子线程 TTL 缓冲里的
// 早到通知同步补投进 handleDescendantNotification(tracker 缓冲),随后
// noteSpawnItem 建卡时统一重放,首帧就带上真实用量。
- return subagentLiveCards.noteSpawnItem(item);
+ return subagentLiveCards.noteSpawnItem(item, undefined, phase);
};
const terminateHandleAfterThreadCleanupFailure = (reason: string): void => {
if (closed) return;
@@ -9360,7 +9362,11 @@ export class CodexAgent extends BaseAgent {
const translatedParams = translatedItem === params.item
? params
: { ...params, item: translatedItem };
- const replayedSubagentUpdate = noteSubagentSpawnItem(translatedItem, params.turnId);
+ const replayedSubagentUpdate = noteSubagentSpawnItem(
+ translatedItem,
+ params.turnId,
+ 'started',
+ );
pushItemStatus(translatedItem);
translateItemNotification('started', translatedParams, eventQueue, {
rt: translatorRt,
@@ -9401,7 +9407,11 @@ export class CodexAgent extends BaseAgent {
const translatedParams = translatedItem === params.item
? params
: { ...params, item: translatedItem };
- const replayedSubagentUpdateOnUpdated = noteSubagentSpawnItem(translatedItem, params.turnId);
+ const replayedSubagentUpdateOnUpdated = noteSubagentSpawnItem(
+ translatedItem,
+ params.turnId,
+ 'updated',
+ );
translateItemNotification('updated', translatedParams, eventQueue, {
rt: translatorRt,
log,
@@ -9464,6 +9474,7 @@ export class CodexAgent extends BaseAgent {
const replayedSubagentUpdateOnCompleted = noteSubagentSpawnItem(
translatedItem,
params.turnId,
+ 'completed',
);
const itemEventQueue = isLateCollabTerminal
? {
diff --git a/packages/maker-core/src/agents/codex/subagent-live-cards.ts b/packages/maker-core/src/agents/codex/subagent-live-cards.ts
index 0690234d08..1d0c719aac 100644
--- a/packages/maker-core/src/agents/codex/subagent-live-cards.ts
+++ b/packages/maker-core/src/agents/codex/subagent-live-cards.ts
@@ -33,6 +33,7 @@
import { readCodexSubagentSpawnRegistration } from './translator.js';
export type SubagentLiveCardStatus = 'running' | 'completed' | 'failed' | 'stopped';
+export type SubagentSpawnItemPhase = 'started' | 'updated' | 'completed';
/** 一次聚合结果:调用方据此发 `agent_task_update`(字段与 `AgentTaskUsage` 对齐)。 */
export interface SubagentLiveCardUpdate {
@@ -59,7 +60,11 @@ export interface SubagentLiveCardTracker {
* 返回 null = 非 spawn item,或 fresh spawn 没有早到状态需要重放(初始模型已由
* translator 合并进原有启动帧),或 spawn 自身失败且没有早到 usage 可补。
*/
- noteSpawnItem(item: unknown, inheritedModel?: string): SubagentLiveCardUpdate | null;
+ noteSpawnItem(
+ item: unknown,
+ inheritedModel?: string,
+ phase?: SubagentSpawnItemPhase,
+ ): SubagentLiveCardUpdate | null;
/**
* 登记「子线程 → 其父线程」的血缘(host 的 `descendantThreadStarted` 对**每一代**都触发)。
*
@@ -169,10 +174,50 @@ interface ThreadState {
observedLiveTurnIds: Set<string>;
/** Model observed from thread metadata, an explicit spawn, or frozen parent inheritance. */
model?: string;
+ /** Keep lower-confidence late spawn metadata from replacing a runtime observation. */
+ modelSource?: ThreadModelSource;
/** A failed nested spawn remains terminal despite late lifecycle events. */
spawnFailed: boolean;
}
+type ThreadModelSource = 'inherited' | 'configured' | 'explicit' | 'runtime';
+
+const MODEL_SOURCE_PRIORITY: Record<ThreadModelSource, number> = {
+ inherited: 0,
+ configured: 1,
+ explicit: 2,
+ runtime: 3,
+};
+
+interface ThreadModelObservation {
+ model: string;
+ source: ThreadModelSource;
+}
+
+function spawnItemHasRunningAgentState(item: unknown): boolean {
+ if (!item || typeof item !== 'object') return false;
+ const record = item as { type?: unknown; agentsStates?: unknown };
+ if (
+ record.type !== 'collabAgentToolCall'
+ || !record.agentsStates
+ || typeof record.agentsStates !== 'object'
+ ) return false;
+ return Object.values(record.agentsStates as Record<string, unknown>).some((state) => {
+ let label: unknown = typeof state === 'string' ? state : undefined;
+ if (!label && state && typeof state === 'object') {
+ const stateRecord = state as Record<string, unknown>;
+ for (const key of ['status', 'state', 'phase']) {
+ if (typeof stateRecord[key] === 'string') {
+ label = stateRecord[key];
+ break;
+ }
+ }
+ }
+ return typeof label === 'string'
+ && /^(running|in[_-]?progress|started|active)$/i.test(label.trim());
+ });
+}
+
interface TrackedCard {
taskId: string;
agentPath?: string;
@@ -217,7 +262,7 @@ export function createSubagentLiveCardTracker(opts: {
*/
const pendingLineage = new Map<string, Set<string>>();
/** Model observed on thread/started before its parent spawn is registered. */
- const pendingThreadModels = new Map<string, string>();
+ const pendingThreadModels = new Map<string, ThreadModelObservation>();
/** Failed nested spawns can be observed before their parent card is attached. */
const pendingFailedThreads = new Set<string>();
/**
@@ -381,6 +426,47 @@ export function createSubagentLiveCardTracker(opts: {
thread.observedLiveTurnIds.add(turnId);
};
+ const updateThreadModel = (
+ thread: ThreadState,
+ observation: ThreadModelObservation | undefined,
+ ): boolean => {
+ if (!observation) return false;
+ const previousPriority = thread.modelSource === undefined
+ ? -1
+ : MODEL_SOURCE_PRIORITY[thread.modelSource];
+ const nextPriority = MODEL_SOURCE_PRIORITY[observation.source];
+ if (
+ nextPriority < previousPriority
+ || (nextPriority === previousPriority && observation.source !== 'runtime')
+ ) return false;
+ const changed = thread.model !== observation.model;
+ thread.model = observation.model;
+ thread.modelSource = observation.source;
+ return changed;
+ };
+
+ const bufferThreadModel = (
+ childThreadId: string,
+ observation: ThreadModelObservation,
+ ): void => {
+ const previous = pendingThreadModels.get(childThreadId);
+ if (
+ previous
+ && (
+ MODEL_SOURCE_PRIORITY[previous.source] > MODEL_SOURCE_PRIORITY[observation.source]
+ || (
+ previous.source === observation.source
+ && observation.source !== 'runtime'
+ )
+ )
+ ) return;
+ if (!previous && pendingThreadModels.size >= MAX_PENDING_THREAD_MODELS) {
+ const oldest = pendingThreadModels.keys().next();
+ if (!oldest.done) pendingThreadModels.delete(oldest.value);
+ }
+ pendingThreadModels.set(childThreadId, observation);
+ };
+
/** 应用一条通知到卡上;返回是否产生了变化(无变化不必发帧)。 */
const applyNotification = (
card: TrackedCard,
@@ -512,6 +598,7 @@ export function createSubagentLiveCardTracker(opts: {
childThreadId: string,
visited: Set<string>,
spawnModel?: string,
+ spawnModelSource: ThreadModelSource = 'inherited',
spawnFailed = false,
inheritedModel?: string,
): boolean => {
@@ -525,7 +612,9 @@ export function createSubagentLiveCardTracker(opts: {
if (!card.threads.has(childThreadId)) {
const observedModel = pendingThreadModels.get(childThreadId);
pendingThreadModels.delete(childThreadId);
- const initialModel = observedModel ?? spawnModel ?? inheritedModel;
+ const initialModel = observedModel?.model ?? spawnModel ?? inheritedModel;
+ const initialModelSource = observedModel?.source
+ ?? (spawnModel ? spawnModelSource : inheritedModel ? 'inherited' : undefined);
// spawn item 自己携带的显式/默认/继承模型会由 translator 合并进原有启动帧;
// 只有 spawn 到达前已经观测到的实际模型才需要在登记后额外重放。
changed = Boolean(observedModel);
@@ -535,11 +624,14 @@ export function createSubagentLiveCardTracker(opts: {
totalTokens: 0,
observedLiveTurnIds: new Set<string>(),
...(initialModel ? { model: initialModel } : {}),
+ ...(initialModelSource ? { modelSource: initialModelSource } : {}),
spawnFailed: latchSpawnFailure,
});
- } else if (spawnModel && !card.threads.get(childThreadId)?.model) {
- card.threads.get(childThreadId)!.model = spawnModel;
- changed = true;
+ } else if (spawnModel) {
+ changed = updateThreadModel(card.threads.get(childThreadId)!, {
+ model: spawnModel,
+ source: spawnModelSource,
+ }) || changed;
}
taskIdByThread.set(childThreadId, card.taskId);
const thread = card.threads.get(childThreadId)!;
@@ -560,19 +652,30 @@ export function createSubagentLiveCardTracker(opts: {
if (descendants) {
pendingLineage.delete(childThreadId);
for (const grandChildId of descendants) {
- if (attachThread(card, grandChildId, visited, undefined, false, thread.model)) changed = true;
+ if (attachThread(card, grandChildId, visited, undefined, 'inherited', false, thread.model)) changed = true;
}
}
return changed;
};
return {
- noteSpawnItem(item: unknown, inheritedModel?: string): SubagentLiveCardUpdate | null {
+ noteSpawnItem(
+ item: unknown,
+ inheritedModel?: string,
+ phase: SubagentSpawnItemPhase = 'started',
+ ): SubagentLiveCardUpdate | null {
const registration = readCodexSubagentSpawnRegistration(item);
if (!registration) return null;
// 模型优先级在 spawn 当刻冻结:显式参数 > Cindy 个性化默认 > Codex 原生父线程继承。
// 后续 thread/started 的实际 model 仍可通过 noteDescendantThread 覆盖。
const spawnModel = registration.model ?? subagentModelFallback ?? inheritedModel;
+ const spawnModelSource: ThreadModelSource | undefined = registration.model
+ ? 'explicit'
+ : subagentModelFallback
+ ? 'configured'
+ : inheritedModel
+ ? 'inherited'
+ : undefined;
const existing = cards.get(registration.taskId);
const card: TrackedCard = existing ?? {
@@ -599,7 +702,7 @@ export function createSubagentLiveCardTracker(opts: {
const visited = new Set<string>();
let replayedOnFailure = false;
for (const childThreadId of registration.childThreadIds) {
- if (attachThread(card, childThreadId, visited, spawnModel)) replayedOnFailure = true;
+ if (attachThread(card, childThreadId, visited, spawnModel, spawnModelSource)) replayedOnFailure = true;
const thread = card.threads.get(childThreadId);
if (thread) thread.status = 'failed';
}
@@ -613,7 +716,7 @@ export function createSubagentLiveCardTracker(opts: {
const visited = new Set<string>();
let replayed = false;
for (const childThreadId of registration.childThreadIds) {
- if (attachThread(card, childThreadId, visited, spawnModel)) replayed = true;
+ if (attachThread(card, childThreadId, visited, spawnModel, spawnModelSource)) replayed = true;
}
// 已登记过的 spawn(同一 collabAgentToolCall 的 started/completed 两个 phase 都会到
@@ -623,6 +726,10 @@ export function createSubagentLiveCardTracker(opts: {
// 跑的子线程会被提前标成完成,先到的 failed/stopped 也会被抹掉。
// (attachThread 幂等:已在卡上的线程不会被重置计数。)
if (existing) return snapshot(card);
+ // app-server 可能省略 started/updated,首个可见帧直接是 completed。此时
+ // collabAgentToolCall 的完成只代表 spawn 工具已返回;agentsStates 仍明确 running
+ // 时必须让 tracker 发出 running 快照,覆盖 translator 合成的 completed。
+ if (phase === 'completed' && spawnItemHasRunningAgentState(item)) return snapshot(card);
return replayed ? snapshot(card) : null;
},
@@ -642,6 +749,13 @@ export function createSubagentLiveCardTracker(opts: {
// 普通 thread/started 观测不走此兜底,避免把“没上报”误当成一次覆盖。
const effectiveModel = model
?? (inheritParentModel ? subagentModelFallback ?? parentModel : undefined);
+ const effectiveModelSource: ThreadModelSource | undefined = model
+ ? inheritParentModel ? 'explicit' : 'runtime'
+ : inheritParentModel && subagentModelFallback
+ ? 'configured'
+ : inheritParentModel && parentModel
+ ? 'inherited'
+ : undefined;
const directTaskId = taskIdByThread.get(childThreadId);
if (directTaskId !== undefined) {
pendingThreadModels.delete(childThreadId);
@@ -650,9 +764,11 @@ export function createSubagentLiveCardTracker(opts: {
const directThread = directCard?.threads.get(childThreadId);
if (directCard && directThread) {
let changed = false;
- if (effectiveModel && directThread.model !== effectiveModel) {
- directThread.model = effectiveModel;
- changed = true;
+ if (effectiveModel && effectiveModelSource) {
+ changed = updateThreadModel(directThread, {
+ model: effectiveModel,
+ source: effectiveModelSource,
+ }) || changed;
}
if (spawnFailed && !directThread.spawnFailed) {
directThread.spawnFailed = true;
@@ -663,12 +779,11 @@ export function createSubagentLiveCardTracker(opts: {
}
return null;
}
- if (effectiveModel) {
- if (!pendingThreadModels.has(childThreadId) && pendingThreadModels.size >= MAX_PENDING_THREAD_MODELS) {
- const oldest = pendingThreadModels.keys().next();
- if (!oldest.done) pendingThreadModels.delete(oldest.value);
- }
- pendingThreadModels.set(childThreadId, effectiveModel);
+ if (effectiveModel && effectiveModelSource) {
+ bufferThreadModel(childThreadId, {
+ model: effectiveModel,
+ source: effectiveModelSource,
+ });
}
if (spawnFailed) {
if (!pendingFailedThreads.has(childThreadId) && pendingFailedThreads.size >= MAX_PENDING_THREAD_MODELS) {
@@ -691,7 +806,14 @@ export function createSubagentLiveCardTracker(opts: {
// 不该说完成),所以发帧条件不只看有没有重放内容,还看聚合状态是否因此改变。
const beforeStatus = aggregateStatus(card);
const beforeModel = aggregateModel(card);
- const replayed = attachThread(card, childThreadId, new Set<string>(), effectiveModel, spawnFailed);
+ const replayed = attachThread(
+ card,
+ childThreadId,
+ new Set<string>(),
+ effectiveModel,
+ effectiveModelSource,
+ spawnFailed,
+ );
return replayed
|| aggregateStatus(card) !== beforeStatus
|| aggregateModel(card) !== beforeModel