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(codex): 子代理卡从 spawn item 建血缘,补实际模型显示与 0.145 终态收口 (#1700)

Chris Zhang10c481182350
diff --git a/apps/desktop/src/main/maker-host/__tests__/codex-subagent-config.test.ts b/apps/desktop/src/main/maker-host/__tests__/codex-subagent-config.test.ts
index b3ed81565b..f7088005f9 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codex-subagent-config.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codex-subagent-config.test.ts
@@ -4,7 +4,10 @@ import {
SUBAGENT_MODEL_SETTINGS_DEFAULTS,
type SubagentModelSettings,
} from '../../../shared/subagentModelSettings';
-import { buildCodexSubagentSpawnArgs } from '../codex-subagent-config';
+import {
+ buildCodexSubagentSpawnArgs,
+ resolveCodexSubagentModelFallback,
+} from '../codex-subagent-config';
function settings(partial: Partial<SubagentModelSettings> = {}): SubagentModelSettings {
return { ...SUBAGENT_MODEL_SETTINGS_DEFAULTS, ...partial };
@@ -153,3 +156,28 @@ describe('buildCodexSubagentSpawnArgs', () => {
).toEqual(['-c', 'agents.default_subagent_model="weird\\"model\\\\id"']);
});
});
+
+describe('resolveCodexSubagentModelFallback', () => {
+ it('returns the configured model for the local app-server', () => {
+ expect(resolveCodexSubagentModelFallback(settings({ codex: 'codex/gpt-5.5' }))).toBe(
+ 'codex/gpt-5.5',
+ );
+ });
+
+ it('does not project a local model setting onto an SSH remote daemon', () => {
+ expect(
+ resolveCodexSubagentModelFallback(
+ settings({ codex: 'codex/gpt-5.5' }),
+ 'remote-host-1',
+ ),
+ ).toBeUndefined();
+ });
+
+ it('returns no fallback when Codex subagents are disabled', () => {
+ expect(
+ resolveCodexSubagentModelFallback(
+ settings({ codexSubagentsEnabled: false, codex: 'codex/gpt-5.5' }),
+ ),
+ ).toBeUndefined();
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/codex-subagent-config.ts b/apps/desktop/src/main/maker-host/codex-subagent-config.ts
index 107c167871..7a5f48c7a6 100644
--- a/apps/desktop/src/main/maker-host/codex-subagent-config.ts
+++ b/apps/desktop/src/main/maker-host/codex-subagent-config.ts
@@ -82,3 +82,17 @@ export function buildCodexSubagentSpawnArgs(settings: SubagentModelSettings): st
}
return args;
}
+
+/**
+ * A display fallback is truthful only for the local app-server that receives
+ * the matching `agents.default_subagent_model` override. SSH remote daemons
+ * use their own isolated CODEX_HOME, so the local setting must not be shown as
+ * if it were the remote thread's actual model.
+ */
+export function resolveCodexSubagentModelFallback(
+ settings: SubagentModelSettings,
+ remoteHostId?: string,
+): string | undefined {
+ if (remoteHostId || !settings.codexSubagentsEnabled) return undefined;
+ return settings.codex?.trim() || undefined;
+}
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 807502b693..66e0faf1a5 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -171,7 +171,10 @@ import {
readDisabledBuiltinPluginIds,
} from '../mcp-integrations/codexBuiltinToolPolicy.js';
import { buildCodexProxySpawnArgs, CODEX_OPENAI_COMPACT_PROVIDER_ID } from './codex-gateway-config.js';
-import { buildCodexSubagentSpawnArgs } from './codex-subagent-config.js';
+import {
+ buildCodexSubagentSpawnArgs,
+ resolveCodexSubagentModelFallback,
+} from './codex-subagent-config.js';
import { readSubagentModelSettings } from './subagent-model-settings-store.js';
import { getOutboundPathSnapshotFor } from './outbound-proxy-resolver.js';
import {
@@ -1185,16 +1188,22 @@ export function getMaker(): Maker {
const endpoint = isControlPlane
? getCodexControlPlaneProxyEndpoint(authInjection)
: getCodexProxyEndpoint();
+ const subagentModelSettings = readSubagentModelSettings();
+ const subagentModelFallback = resolveCodexSubagentModelFallback(
+ subagentModelSettings,
+ ctx.remoteHostId,
+ );
return {
// 子代理护栏/默认模型每次 createHost 现读 store:DeferredCodexRestart 兑现
// (dispose host)后的新 spawn 自动带新值。agents.* 对 control-plane 的
// model/list 无影响,不加 hostPurpose 分支。
extraArgs: [
...mcpExtraArgs,
- ...buildCodexSubagentSpawnArgs(readSubagentModelSettings()),
+ ...buildCodexSubagentSpawnArgs(subagentModelSettings),
...buildCodexProxySpawnArgs(endpoint, authInjection),
],
extraEnv: mcpExtraEnv,
+ ...(subagentModelFallback ? { subagentModelFallback } : {}),
...(buildSessionMcpConfig ? { buildSessionMcpConfig } : {}),
codexProxyActive: ready,
codexBrowserUseAvailable: browserCompanionSpawnConfig.codexBrowserUseAvailable,
diff --git a/apps/desktop/src/renderer/__tests__/AgentTaskCard.test.ts b/apps/desktop/src/renderer/__tests__/AgentTaskCard.test.ts
index 1fe5ec65bb..8c6b0992e7 100644
--- a/apps/desktop/src/renderer/__tests__/AgentTaskCard.test.ts
+++ b/apps/desktop/src/renderer/__tests__/AgentTaskCard.test.ts
@@ -150,6 +150,29 @@ describe('AgentTaskCard', () => {
expect(modelChip(container)).toBeNull();
});
+ it('does not fall back to stale history or spawn input after an explicit model clear', () => {
+ const { container } = render(
+ React.createElement(AgentTaskCard, {
+ toolCall: {
+ clientId: 'c-clear',
+ role: 'tool_use',
+ content: '',
+ toolName: 'collab:spawn',
+ toolUseId: 'toolu_CLEAR',
+ toolInput: { model: 'gpt-5.6-terra' },
+ },
+ update: {
+ provider: 'codex',
+ taskId: 'task-clear',
+ status: 'running',
+ model: null,
+ },
+ subagentModel: 'codex/gpt-5.5',
+ }),
+ );
+ expect(modelChip(container)).toBeNull();
+ });
+
// bash-task-card + 停止按钮 ---------------------------------------------------
const stopButton = (container: HTMLElement) =>
container.querySelector<HTMLButtonElement>('[data-agent-task-stop="true"]');
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts
index f762dbdae1..e6a8d8b63f 100644
--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts
@@ -199,6 +199,39 @@ describe('makerChatStore agent task updates', () => {
title: 'Math quiz agent A',
});
});
+
+ it('clears a stale model when Codex aggregate evidence becomes ambiguous', () => {
+ const resolved = handleStreamEvent(
+ { ...EMPTY_SESSION_STATE, messages: [], taskUpdates: new Map() },
+ {
+ sessionId: 's1',
+ type: 'agent_task_update',
+ source: 'codex',
+ data: {
+ provider: 'codex',
+ taskId: 'codex-task-1',
+ status: 'running',
+ model: 'codex/gpt-5.5',
+ },
+ } as CCAgentStreamEvent,
+ );
+ const cleared = handleStreamEvent(
+ resolved,
+ {
+ sessionId: 's1',
+ type: 'agent_task_update',
+ source: 'codex',
+ data: {
+ provider: 'codex',
+ taskId: 'codex-task-1',
+ status: 'running',
+ model: null,
+ },
+ } as CCAgentStreamEvent,
+ );
+
+ expect(cleared.taskUpdates?.get('codex-task-1')?.model).toBeNull();
+ });
});
// ---------------------------------------------------------------------------
diff --git a/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx b/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx
index 14167f4985..6164abfbd0 100644
--- a/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx
@@ -61,6 +61,13 @@ function readInputString(input: unknown, keys: string[]): string | undefined {
return undefined;
}
+function readInputStringArray(input: unknown, key: string): string[] {
+ if (!input || typeof input !== 'object') return [];
+ const value = (input as Record<string, unknown>)[key];
+ if (!Array.isArray(value)) return [];
+ return value.filter((item): item is string => typeof item === 'string' && item.length > 0);
+}
+
function compactText(text: string | undefined, max = 260): string | undefined {
if (!text) return undefined;
const oneLine = text.replace(/\s+/g, ' ').trim();
@@ -134,9 +141,20 @@ export function AgentTaskCard({ toolCall, update, result, subagentModel, session
// subagent-model-chip: 子代理模型 —— 实时态优先 update.model(progress 事件
// 带),历史重载(update 缺省)回退到从子消息反查的 subagentModel;两者皆无时
// 再回退 spawn 参数里显式指定的 model(codex collab 卡,translator 透传
- // item.model)。默认继承主模型时 spawn 无 model 字段——不猜继承值,不渲染。
+ // item.model)。`model: null` 是实时聚合卡的显式清除指令,不能再落到历史/输入兜底,
+ // 否则多 receiver 模型冲突时旧徽标会被重新显示。V1 多 receiver 的实时聚合结论
+ // 不落库;重载后既无法证明所有 receiver 都已上报、也无法证明模型一致,所以历史态
+ // 同样不从首条子消息或 spawn 参数猜回单一徽标。默认继承主模型时 spawn 无 model
+ // 字段——不猜继承值,不渲染。
+ const receiverThreadIds = readInputStringArray(toolCall?.toolInput, 'receiverThreadIds');
+ const ambiguousMultiReceiverHistory =
+ !update && toolCall?.toolName?.startsWith('collab:') === true && receiverThreadIds.length > 1;
const modelLabel = formatModelShortLabel(
- update?.model ?? subagentModel ?? readInputString(toolCall?.toolInput, ['model']),
+ update?.model === null
+ ? undefined
+ : update?.model ?? (ambiguousMultiReceiverHistory
+ ? undefined
+ : subagentModel ?? readInputString(toolCall?.toolInput, ['model'])),
);
// codex spawn 可为子代理显式指定思考强度(translator 透传 reasoningEffort);
// 已知档位才走 effortLevels 词表,未知值不显示。CC 无此参数,行为不变。
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/AgentTaskCardModelChip.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/AgentTaskCardModelChip.test.tsx
index 2b192f1aab..44226bf505 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/AgentTaskCardModelChip.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/AgentTaskCardModelChip.test.tsx
@@ -128,4 +128,36 @@ describe('AgentTaskCard subagent model chip (codex collab)', () => {
);
expect(chipText(container)).toBe('claude-sonnet-5');
});
+
+ it.each([
+ ['partial observation', 'codex/gpt-5.5', 'gpt-5.6-terra'],
+ ['conflicting observations', 'codex/gpt-5.5', 'codex/gpt-5.6-sol'],
+ ])(
+ 'does not restore a cleared V1 multi-receiver model after reload (%s)',
+ (_caseName, firstObservedModel, spawnModel) => {
+ const toolCall = collabToolCall({
+ prompt: 'fan out',
+ receiverThreadIds: ['thread-a', 'thread-b'],
+ model: spawnModel,
+ });
+ const { container, rerender } = render(
+ <AgentTaskCard
+ toolCall={toolCall}
+ subagentModel={firstObservedModel}
+ update={{
+ provider: 'codex',
+ taskId: 'item_1',
+ status: 'running',
+ model: null,
+ }}
+ />,
+ );
+ expect(chipText(container)).toBeNull();
+
+ // agent_task_update 是 live-only;重载后 update 消失。多 receiver 的一致性
+ // 结论无法从首条子消息或 spawn 参数恢复,因此必须继续保持无徽标。
+ rerender(<AgentTaskCard toolCall={toolCall} subagentModel={firstObservedModel} />);
+ expect(chipText(container)).toBeNull();
+ },
+ );
});
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index f72a5f08e7..365e2abca9 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -585,7 +585,8 @@ export interface AgentTaskUpdate {
lastToolName?: string;
taskType?: string;
workflowName?: string;
- model?: string;
+ /** `null` is an explicit live-update instruction to clear a stale model badge. */
+ model?: string | null;
reasoningEffort?: string;
receiverThreadIds?: string[];
/**
@@ -4118,7 +4119,11 @@ function normalizeAgentTaskUpdate(
...(typeof raw.workflowName === 'string' && raw.workflowName
? { workflowName: raw.workflowName }
: {}),
- ...(typeof raw.model === 'string' && raw.model ? { model: raw.model } : {}),
+ ...(raw.model === null
+ ? { model: null }
+ : typeof raw.model === 'string' && raw.model
+ ? { model: raw.model }
+ : {}),
...(typeof raw.reasoningEffort === 'string' && raw.reasoningEffort
? { reasoningEffort: raw.reasoningEffort }
: {}),
@@ -4152,6 +4157,7 @@ function mergeAgentTaskUpdate(
// CLI 节流帧不带 workflowProgress(undefined = 沿用旧树),必须保留上一帧。
workflowProgress: next.workflowProgress ?? prev.workflowProgress,
createdAt: prev.createdAt ?? next.createdAt,
+ model: next.model === null ? null : next.model ?? prev.model,
updatedAt: next.updatedAt ?? prev.updatedAt,
};
}
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index 6f07097670..8fffad7270 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -213,6 +213,8 @@ export interface PiExtraSpawnConfigContext {
export interface CodexExtraSpawnConfig {
extraArgs: string[];
extraEnv: Record<string, string>;
+ /** Cindy-side display fallback for Codex subagent cards. */
+ subagentModelFallback?: string;
/** Whether this exact app-server spawn was provisioned with Codex Chrome. */
codexBrowserUseAvailable?: boolean;
/** Exact verified Chrome plugin version provisioned into this app-server. */
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 976f3a29ae..5489dc5a64 100644
--- a/packages/maker-core/src/agents/codex/__tests__/subagentLiveCards.test.ts
+++ b/packages/maker-core/src/agents/codex/__tests__/subagentLiveCards.test.ts
@@ -4,18 +4,19 @@ import { createSubagentLiveCardTracker } from '../subagent-live-cards.js';
import { readCodexSubagentSpawnRegistration } from '../translator.js';
/** V2(codex 0.145):spawn 只发瞬时 subAgentActivity,带 agentThreadId。 */
-function v2SpawnItem(id: string, agentThreadId: string, agentPath?: string) {
+function v2SpawnItem(id: string, agentThreadId: string, agentPath?: string, model?: string) {
return {
type: 'subAgentActivity',
id,
kind: 'started',
agentThreadId,
...(agentPath ? { agentPath } : {}),
+ ...(model ? { model } : {}),
};
}
/** V1(老模型 / 自定义接入模型):spawn 走 collabAgentToolCall,目标在 receiverThreadIds。 */
-function v1SpawnItem(id: string, receiverThreadIds: string[]) {
+function v1SpawnItem(id: string, receiverThreadIds: string[], model?: string) {
return {
type: 'collabAgentToolCall',
id,
@@ -23,6 +24,7 @@ function v1SpawnItem(id: string, receiverThreadIds: string[]) {
senderThreadId: 'root-1',
receiverThreadIds,
prompt: 'survey the repo rules',
+ ...(model ? { model } : {}),
};
}
@@ -32,17 +34,19 @@ function toolItem(id: string, type = 'commandExecution') {
describe('readCodexSubagentSpawnRegistration', () => {
it('maps V2 subAgentActivity to its child thread', () => {
- expect(readCodexSubagentSpawnRegistration(v2SpawnItem('i-1', 't-child', '/root/scout'))).toEqual({
+ expect(readCodexSubagentSpawnRegistration(v2SpawnItem('i-1', 't-child', '/root/scout', 'gpt-5.6-terra'))).toEqual({
taskId: 'i-1',
childThreadIds: ['t-child'],
agentPath: '/root/scout',
+ model: 'gpt-5.6-terra',
});
});
it('maps V1 collab spawn to every receiver thread', () => {
- expect(readCodexSubagentSpawnRegistration(v1SpawnItem('i-2', ['t-a', 't-b']))).toEqual({
+ expect(readCodexSubagentSpawnRegistration(v1SpawnItem('i-2', ['t-a', 't-b'], 'codex/gpt-5.5'))).toEqual({
taskId: 'i-2',
childThreadIds: ['t-a', 't-b'],
+ model: 'codex/gpt-5.5',
});
});
@@ -94,6 +98,84 @@ describe('createSubagentLiveCardTracker', () => {
expect(afterUsage?.toolUses).toBe(1);
});
+ it('uses Cindy configured model only until the child thread reports its actual model', () => {
+ const tracker = createSubagentLiveCardTracker({ now: () => 0, subagentModelFallback: 'gpt-5.6-terra' });
+ expect(tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'))).toMatchObject({
+ taskId: 'card-1',
+ model: 'gpt-5.6-terra',
+ });
+
+ expect(tracker.noteDescendantThread('t-child', 'root-thread', 'codex/gpt-5.5')).toMatchObject({
+ model: 'codex/gpt-5.5',
+ });
+ });
+
+ it('emits an observed model that arrived before a quiet spawn item', () => {
+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });
+ // thread/started 先到且之后没有 item/token/turn 通知:spawn 登记本身必须把
+ // 已缓存的实际模型发出来,不能等一条可能永远不来的 descendant 通知。
+ expect(
+ tracker.noteDescendantThread('t-child', 'root-thread', 'codex/gpt-5.5'),
+ ).toBeNull();
+ expect(tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'))).toMatchObject({
+ taskId: 'card-1',
+ model: 'codex/gpt-5.5',
+ });
+ });
+
+ it('retains an observed nested model when lineage arrives before attachment', () => {
+ const tracker = createSubagentLiveCardTracker({ now: () => 0, subagentModelFallback: 'gpt-5.6-terra' });
+ // 父线程从 spawn 参数拿到模型;孙线程的观测值只能靠 pendingThreadModels 保住——
+ // 徽标要求全员观测一致,retention 一丢徽标就灭。
+ tracker.noteSpawnItem(v2SpawnItem('card-parent', 't-parent', undefined, 'codex/gpt-5.5'));
+ expect(
+ tracker.noteDescendantThread('t-grandchild', 't-parent', 'codex/gpt-5.5'),
+ ).toMatchObject({ model: 'codex/gpt-5.5' });
+ });
+
+ it('hides the aggregate model badge until every thread has reported a consistent model', () => {
+ // 多 receiver 卡:只有部分线程报了模型时,不许把局部观测投影成全卡事实;
+ // 也不回退到配置兜底(已有相反观测,兜底反而更可能是错的)(codex review)。
+ const tracker = createSubagentLiveCardTracker({ now: () => 0, subagentModelFallback: 'gpt-5.6-terra' });
+ expect(tracker.noteSpawnItem(v1SpawnItem('card-v1', ['t-a', 't-b']))).toMatchObject({
+ model: 'gpt-5.6-terra',
+ });
+
+ const partial = tracker.noteDescendantThread('t-a', 'root-1', 'codex/gpt-5.5');
+ expect(partial).not.toBeNull();
+ expect(partial?.model).toBeNull();
+
+ // 全员报齐且一致 → 亮实际模型。
+ expect(tracker.noteDescendantThread('t-b', 'root-1', 'codex/gpt-5.5')).toMatchObject({
+ model: 'codex/gpt-5.5',
+ });
+ });
+
+ it('hides the aggregate model badge when receiver threads report different models', () => {
+ const tracker = createSubagentLiveCardTracker({ now: () => 0, subagentModelFallback: 'gpt-5.6-terra' });
+ tracker.noteSpawnItem(v1SpawnItem('card-v1', ['t-a', 't-b']));
+ tracker.noteDescendantThread('t-a', 'root-1', 'codex/gpt-5.5');
+ const conflicting = tracker.noteDescendantThread('t-b', 'root-1', 'gpt-5.6-terra');
+ expect(conflicting).not.toBeNull();
+ expect(conflicting?.model).toBeNull();
+ });
+
+ it('clears an observed model when a quiet descendant joins the card', () => {
+ const tracker = createSubagentLiveCardTracker({ now: () => 0, subagentModelFallback: 'gpt-5.6-terra' });
+ tracker.noteSpawnItem(v2SpawnItem('card-parent', 't-parent'));
+ expect(
+ tracker.noteDescendantThread('t-parent', 'root-thread', 'codex/gpt-5.5'),
+ ).toMatchObject({ model: 'codex/gpt-5.5' });
+
+ // 孙线程已加入但尚未报告模型,且之后可能没有任何通知。入卡这一刻就必须
+ // 发 model:null 清掉旧徽标,不能继续把父线程的模型投影到整张卡。
+ expect(tracker.noteDescendantThread('t-grandchild', 't-parent')).toMatchObject({
+ taskId: 'card-parent',
+ status: 'running',
+ model: null,
+ });
+ });
+
it('counts a tool item once even when both phases arrive', () => {
const tracker = createSubagentLiveCardTracker({ now: () => 0 });
tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'));
@@ -388,6 +470,28 @@ describe('createSubagentLiveCardTracker', () => {
).toBe('failed');
});
+ it('keeps receiver ids from a failed nested spawn terminal', () => {
+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });
+ tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'));
+
+ // The failed nested spawn can still carry receiver ids. Buffer any real
+ // work they emitted, but never attach them as an unbounded running child.
+ tracker.handleDescendantNotification('t-grand', 'item/started', toolItem('g-1'));
+ expect(tracker.noteDescendantThread('t-grand', 't-child', undefined, true)).toMatchObject({
+ status: 'running',
+ toolUses: 1,
+ });
+
+ // Late lifecycle events cannot reopen a receiver whose spawn itself failed.
+ expect(tracker.handleDescendantNotification('t-grand', 'turn/started', {})).toBeNull();
+ expect(
+ tracker.handleDescendantNotification('t-child', 'turn/completed', { turn: { status: 'completed' } })?.status,
+ ).toBe('failed');
+ expect(
+ tracker.handleDescendantNotification('t-grand', 'turn/completed', { turn: { status: 'completed' } }),
+ ).toBeNull();
+ });
+
it('ignores lineage for threads unrelated to any subagent card', () => {
const tracker = createSubagentLiveCardTracker({ now: () => 0 });
// 父线程不属于任何卡(例如主线程的后代未经 spawn 登记)→ 无副作用。
diff --git a/packages/maker-core/src/agents/codex/app-server/host.test.ts b/packages/maker-core/src/agents/codex/app-server/host.test.ts
index be97be52d6..95ce431913 100644
--- a/packages/maker-core/src/agents/codex/app-server/host.test.ts
+++ b/packages/maker-core/src/agents/codex/app-server/host.test.ts
@@ -404,6 +404,156 @@ describe('AppServerHost descendant thread routing', () => {
await host.shutdown();
});
+ it('registerDescendantLineage routes child notifications without any thread/started (codex 0.145)', async () => {
+ // 0.145 只对显式 thread/start / fork RPC 发 thread/started;spawn 出的子线程
+ // 只有 item / turn / tokenUsage 通知。血缘必须能由 Cindy 侧(从 spawn item)
+ // 主动登记,否则这些通知全部在 TTL 缓冲里过期,子代理卡永久转圈。
+ const transport = new NotificationTransport();
+ const host = new AppServerHost({
+ createTransport: () => transport,
+ logger,
+ clientInfo: { name: 'cindy-test', version: '0.0.0' },
+ });
+ await host.ensureStarted();
+
+ const descendantNotification = vi.fn();
+ const descendantThreadStarted = vi.fn();
+ const subscription = host.subscribeThread('root-thread', {
+ descendantNotification,
+ descendantThreadStarted,
+ });
+
+ // 早到:子线程通知先于 spawn item 被处理,落进 TTL 缓冲。
+ transport.emit({
+ method: 'turn/started',
+ params: { threadId: 'child-thread', turn: { id: 'turn-1' } },
+ });
+
+ host.registerDescendantLineage('child-thread', 'root-thread');
+
+ // 缓冲的早到通知按序补投,后续通知实时路由;全程没有任何 thread/started。
+ transport.emit({
+ method: 'turn/completed',
+ params: { threadId: 'child-thread', turn: { id: 'turn-1', status: 'completed' } },
+ });
+ expect(descendantNotification).toHaveBeenNthCalledWith(
+ 1,
+ 'child-thread',
+ 'turn/started',
+ { threadId: 'child-thread', turn: { id: 'turn-1' } },
+ );
+ expect(descendantNotification).toHaveBeenNthCalledWith(
+ 2,
+ 'child-thread',
+ 'turn/completed',
+ { threadId: 'child-thread', turn: { id: 'turn-1', status: 'completed' } },
+ );
+
+ // 血缘重复:新版 codex 补发同一条边的 thread/started 不重复建边、不重放缓冲,
+ // 但通知本身仍要转发——它携带的 thread.model 是实际模型的唯一观测入口(codex review)。
+ transport.emit({
+ method: 'thread/started',
+ params: { thread: { id: 'child-thread', parentThreadId: 'root-thread', model: 'gpt-5.6-terra' } },
+ });
+ expect(descendantThreadStarted).toHaveBeenCalledTimes(1);
+ expect(descendantThreadStarted).toHaveBeenCalledWith({
+ thread: { id: 'child-thread', parentThreadId: 'root-thread', model: 'gpt-5.6-terra' },
+ });
+ expect(descendantNotification).toHaveBeenCalledTimes(2);
+
+ await subscription.release();
+ await host.shutdown();
+ });
+
+ it('replays a buffered child thread/started before draining ordinary notifications', async () => {
+ const transport = new NotificationTransport();
+ const host = new AppServerHost({
+ createTransport: () => transport,
+ logger,
+ clientInfo: { name: 'cindy-test', version: '0.0.0' },
+ });
+ await host.ensureStarted();
+
+ // Root subscription is late. The child metadata and lifecycle arrive first,
+ // then the root spawn item is buffered under the root id.
+ transport.emit({
+ method: 'thread/started',
+ params: {
+ thread: {
+ id: 'child-thread',
+ parentThreadId: 'root-thread',
+ model: 'codex/gpt-5.6-sol',
+ },
+ },
+ });
+ transport.emit({
+ method: 'turn/started',
+ params: { threadId: 'child-thread', turn: { id: 'child-turn' } },
+ });
+ transport.emit({
+ method: 'item/started',
+ params: {
+ threadId: 'root-thread',
+ turnId: 'root-turn',
+ item: { id: 'spawn-1', type: 'subAgentActivity', agentThreadId: 'child-thread' },
+ },
+ });
+
+ const observed: string[] = [];
+ const subscription = host.subscribeThread('root-thread', {
+ itemStarted: () => {
+ observed.push('spawn');
+ host.registerDescendantLineage('child-thread', 'root-thread');
+ },
+ descendantThreadStarted: (params) => {
+ observed.push(`model:${params.thread.model ?? ''}`);
+ },
+ descendantNotification: (_threadId, method) => {
+ observed.push(method);
+ },
+ });
+
+ expect(observed).toEqual([
+ 'spawn',
+ 'model:codex/gpt-5.6-sol',
+ 'turn/started',
+ ]);
+
+ await subscription.release();
+ await host.shutdown();
+ });
+
+ it('registerDescendantLineage unlocks a buffered grandchild thread/started chain', async () => {
+ const transport = new NotificationTransport();
+ const host = new AppServerHost({
+ createTransport: () => transport,
+ logger,
+ clientInfo: { name: 'cindy-test', version: '0.0.0' },
+ });
+ await host.ensureStarted();
+
+ const descendantThreadStarted = vi.fn();
+ const subscription = host.subscribeThread('root-thread', {
+ descendantThreadStarted,
+ });
+
+ // 孙线程的 thread/started(新版 codex 才会发)先到,此时子线程尚无血缘,缓冲。
+ transport.emit({
+ method: 'thread/started',
+ params: { thread: { id: 'grandchild-thread', parentThreadId: 'child-thread' } },
+ });
+ expect(descendantThreadStarted).not.toHaveBeenCalled();
+
+ // 子线程血缘由 spawn item 路径登记 → 缓冲中的孙线程血缘应被递归重建。
+ host.registerDescendantLineage('child-thread', 'root-thread');
+ expect(descendantThreadStarted).toHaveBeenCalledWith({
+ thread: { id: 'grandchild-thread', parentThreadId: 'child-thread' },
+ });
+
+ await subscription.release();
+ await host.shutdown();
+ });
+
it('routes descendant server requests to the root subscription handlers', async () => {
const transport = new NotificationTransport();
const host = new AppServerHost({
@@ -603,6 +753,120 @@ describe('AppServerHost descendant thread routing', () => {
await host.shutdown();
});
+ it('keeps known descendant request dispatch synchronous before a resolved notification', async () => {
+ const transport = new NotificationTransport();
+ const host = new AppServerHost({
+ createTransport: () => transport,
+ logger,
+ clientInfo: { name: 'cindy-test', version: '0.0.0' },
+ });
+ await host.ensureStarted();
+
+ const order: string[] = [];
+ const subscription = host.subscribeThread('root-thread', {
+ requestUserInput: vi.fn(async () => {
+ order.push('request');
+ return { answers: {} };
+ }),
+ serverRequestResolved: vi.fn(() => {
+ order.push('resolved');
+ }),
+ });
+ transport.emit({
+ id: 'known-request',
+ method: 'item/tool/requestUserInput',
+ params: {
+ threadId: 'root-thread',
+ turnId: 'root-turn',
+ itemId: 'input',
+ questions: [{ id: 'q1', header: 'Q', question: 'Continue?', options: [] }],
+ },
+ });
+ transport.emit({
+ method: 'serverRequest/resolved',
+ params: { threadId: 'root-thread', requestId: 'known-request' },
+ });
+
+ await vi.waitFor(() => {
+ expect(order).toEqual(['request', 'resolved']);
+ });
+
+ await subscription.release();
+ await host.shutdown();
+ });
+
+ it('registers provisional descendant request brokers before replaying resolved notifications', async () => {
+ const transport = new NotificationTransport();
+ const host = new AppServerHost({
+ createTransport: () => transport,
+ logger,
+ clientInfo: { name: 'cindy-test', version: '0.0.0' },
+ });
+ await host.ensureStarted();
+
+ const order: string[] = [];
+ const subscription = host.subscribeThread('root-thread', {
+ requestUserInput: vi.fn(async (_params, meta) => {
+ order.push(`request:${String(meta.requestId)}`);
+ return { answers: {} };
+ }),
+ dynamicToolCall: vi.fn(async (_params, meta) => {
+ order.push(`request:${String(meta.requestId)}`);
+ return { contentItems: [], success: false };
+ }),
+ descendantNotification: (_threadId, method, params) => {
+ if (method !== 'serverRequest/resolved') return;
+ order.push(`resolved:${String((params as { requestId: string }).requestId)}`);
+ },
+ });
+
+ host.reserveDescendantLineage('child-thread', 'root-thread');
+ transport.emit({
+ id: 'pending-input',
+ method: 'item/tool/requestUserInput',
+ params: {
+ threadId: 'child-thread',
+ turnId: 'child-turn',
+ itemId: 'input',
+ questions: [{ id: 'q1', header: 'Q', question: 'Continue?', options: [] }],
+ },
+ });
+ transport.emit({
+ id: 'pending-tool',
+ method: 'item/tool/call',
+ params: {
+ threadId: 'child-thread',
+ turnId: 'child-turn',
+ callId: 'tool',
+ namespace: null,
+ tool: 'ask_user',
+ arguments: {},
+ },
+ });
+ transport.emit({
+ method: 'serverRequest/resolved',
+ params: { threadId: 'child-thread', requestId: 'pending-input' },
+ });
+ transport.emit({
+ method: 'serverRequest/resolved',
+ params: { threadId: 'child-thread', requestId: 'pending-tool' },
+ });
+
+ host.registerDescendantLineage('child-thread', 'root-thread');
+
+ await vi.waitFor(() => {
+ expect(order).toEqual([
+ 'request:pending-input',
+ 'request:pending-tool',
+ 'resolved:pending-input',
+ 'resolved:pending-tool',
+ ]);
+ });
+
+ await subscription.release();
+ await host.shutdown();
+ });
+
it('declines an MCP elicitation whose lineage stays unknown for the bounded window', async () => {
const transport = new NotificationTransport();
const host = new AppServerHost({
@@ -642,6 +906,122 @@ describe('AppServerHost descendant thread routing', () => {
await subscription.release();
await host.shutdown();
});
+
+ it('holds all descendant server requests behind a pending spawn claim until commit', async () => {
+ const transport = new NotificationTransport();
+ const host = new AppServerHost({
+ createTransport: () => transport,
+ logger,
+ clientInfo: { name: 'cindy-test', version: '0.0.0' },
+ notificationBufferTtlMs: 20,
+ });
+ await host.ensureStarted();
+
+ const subscription = host.subscribeThread('root-thread', {
+ commandExecutionApproval: vi.fn(async () => ({ decision: 'accept' as const })),
+ fileChangeApproval: vi.fn(async () => ({ decision: 'accept' as const })),
+ permissionsApproval: vi.fn(async () => ({ permissions: { network: true }, scope: 'turn' as const })),
+ requestUserInput: vi.fn(async () => ({ answers: { q1: { answers: ['ok'] } } })),
+ dynamicToolCall: vi.fn(async () => ({
+ contentItems: [{ type: 'inputText' as const, text: 'ok' }],
+ success: true,
+ })),
+ mcpServerElicitation: vi.fn(async () => ({
+ action: 'accept' as const,
+ content: { value: 'ok' },
+ _meta: null,
+ })),
+ });
+
+ const requests = [
+ { id: 'pending-command', method: 'item/commandExecution/requestApproval', params: { threadId: 'child-thread', turnId: 'child-turn', itemId: 'command' } },
+ { id: 'pending-file', method: 'item/fileChange/requestApproval', params: { threadId: 'child-thread', turnId: 'child-turn', itemId: 'file' } },
+ { id: 'pending-permissions', method: 'item/permissions/requestApproval', params: { threadId: 'child-thread', turnId: 'child-turn', itemId: 'permissions', permissions: { network: true } } },
+ { id: 'pending-input', method: 'item/tool/requestUserInput', params: { threadId: 'child-thread', turnId: 'child-turn', itemId: 'input', questions: [] } },
+ { id: 'pending-tool', method: 'item/tool/call', params: { threadId: 'child-thread', turnId: 'child-turn', callId: 'tool', namespace: null, tool: 'test', arguments: {} } },
+ { id: 'pending-elicitation', method: 'mcpServer/elicitation/request', params: { threadId: 'child-thread', turnId: 'child-turn', serverName: 'test-mcp', mode: 'form', _meta: null, message: 'Confirm', requestedSchema: {} } },
+ ] as const;
+ const initialLineCount = transport.lines.length;
+ for (const request of requests) transport.emit(request);
+
+ // The parent spawn is known, but not yet accepted by turn reconciliation.
+ host.reserveDescendantLineage('child-thread', 'root-thread');
+ await Promise.resolve();
+ expect(transport.lines).toHaveLength(initialLineCount);
+
+ host.registerDescendantLineage('child-thread', 'root-thread');
+ await vi.waitFor(() => {
+ expect(transport.lines).toHaveLength(initialLineCount + requests.length);
+ });
+
+ const responses = transport.lines
+ .slice(initialLineCount)
+ .map((line) => JSON.parse(line) as { id: string; result: unknown });
+ expect(responses.map((response) => response.id)).toEqual(requests.map((request) => request.id));
+
+ await subscription.release();
+ await host.shutdown();
+ });
+
+ it('keeps pending child buffers alive until commit and drops them on discard', async () => {
+ const transport = new NotificationTransport();
+ const host = new AppServerHost({
+ createTransport: () => transport,
+ logger,
+ clientInfo: { name: 'cindy-test', version: '0.0.0' },
+ notificationBufferTtlMs: 10,
+ });
+ await host.ensureStarted();
+
+ const descendantThreadStarted = vi.fn();
+ const descendantNotification = vi.fn();
+ const subscription = host.subscribeThread('root-thread', {
+ descendantThreadStarted,
+ descendantNotification,
+ });
+
+ host.reserveDescendantLineage('child-thread', 'root-thread');
+ transport.emit({
+ method: 'thread/started',
+ params: { thread: { id: 'child-thread', parentThreadId: 'root-thread', model: 'gpt-5.6-terra' } },
+ });
+ transport.emit({
+ method: 'turn/completed',
+ params: { threadId: 'child-thread', turn: { id: 'child-turn', status: 'completed' } },
+ });
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ expect(descendantThreadStarted).not.toHaveBeenCalled();
+ expect(descendantNotification).not.toHaveBeenCalled();
+
+ host.registerDescendantLineage('child-thread', 'root-thread');
+ expect(descendantThreadStarted).toHaveBeenCalledWith({
+ thread: { id: 'child-thread', parentThreadId: 'root-thread', model: 'gpt-5.6-terra' },
+ });
+ expect(descendantNotification).toHaveBeenCalledWith(
+ 'child-thread',
+ 'turn/completed',
+ { threadId: 'child-thread', turn: { id: 'child-turn', status: 'completed' } },
+ );
+
+ host.reserveDescendantLineage('orphan-child', 'root-thread');
+ transport.emit({
+ method: 'turn/completed',
+ params: { threadId: 'orphan-child', turn: { id: 'orphan-turn', status: 'completed' } },
+ });
+ host.discardPendingDescendantLineage('orphan-child', 'root-thread');
+ transport.emit({
+ method: 'turn/completed',
+ params: { threadId: 'orphan-child', turn: { id: 'late-turn', status: 'completed' } },
+ });
+ expect(descendantNotification).not.toHaveBeenCalledWith(
+ 'orphan-child',
+ expect.anything(),
+ expect.anything(),
+ );
+
+ await subscription.release();
+ await host.shutdown();
+ });
});
describe('AppServerHost descendant notification routing', () => {
diff --git a/packages/maker-core/src/agents/codex/app-server/host.ts b/packages/maker-core/src/agents/codex/app-server/host.ts
index 05f70c0888..04f4a11eaf 100644
--- a/packages/maker-core/src/agents/codex/app-server/host.ts
+++ b/packages/maker-core/src/agents/codex/app-server/host.ts
@@ -268,6 +268,8 @@ export interface AppServerHostOptions {
remoteCompactionProviderId?: string;
/** Per-thread host-owned MCP URL overrides keyed by the Session instance. */
buildSessionMcpConfig?: (sessionInstanceId: string) => Record<string, unknown>;
+ /** Cindy-side fallback used only when a subagent's actual model is not reported. */
+ subagentModelFallback?: string;
}
interface BufferedNotification {
@@ -289,6 +291,16 @@ export class AppServerHost {
private readonly subscribers = new Map<string, ThreadEventHandlers>();
/** root / descendant threadId → 当前拥有该子树订阅的 root threadId。 */
private readonly lineageRoots = new Map<string, string>();
+ /**
+ * 父 turn 尚在对账时的 provisional child claim。
+ *
+ * reserve 只保活 child 缓冲与 server request waiter,不安装 root 路由;
+ * 父 turn 被接受后由 registerDescendantLineage commit,判成孤儿则 discard。
+ */
+ private readonly pendingLineage = new Map<
+ string,
+ { parentThreadId: string; rootThreadId: string }
+ >();
/** Server request may race the child thread/started notification that establishes lineage. */
private readonly threadHandlerWaiters = new Map<string, Set<() => void>>();
/** One post-start MCP inventory probe per server/tool for this concrete process. */
@@ -413,6 +425,11 @@ export class AppServerHost {
return this.opts.buildSessionMcpConfig(sessionInstanceId);
}
+ /** Display metadata only; observed thread model always wins. */
+ getSubagentModelFallback(): string | undefined {
+ return this.opts.subagentModelFallback;
+ }
+
getConnectionId(): string {
return this.connectionId;
}
@@ -491,7 +508,10 @@ export class AppServerHost {
// 防 server 在握手过程中就发出 approval (虽然实际不会, 但 defensive)。
client.setRequestHandler(Method.CommandExecutionRequestApproval, async (rawParams) => {
const params = rawParams as CommandExecutionRequestApprovalParams;
- const handlers = this.handlersForThread(params.threadId);
+ const resolvedHandlers = this.resolveRequestHandlers(params.threadId);
+ const handlers = resolvedHandlers instanceof Promise
+ ? await resolvedHandlers
+ : resolvedHandlers;
if (!handlers?.commandExecutionApproval) {
this.logger.warn('commandExecution approval without subscriber → decline', {
threadId: params.threadId,
@@ -512,7 +532,10 @@ export class AppServerHost {
client.setRequestHandler(Method.FileChangeRequestApproval, async (rawParams) => {
const params = rawParams as FileChangeRequestApprovalParams;
- const handlers = this.handlersForThread(params.threadId);
+ const resolvedHandlers = this.resolveRequestHandlers(params.threadId);
+ const handlers = resolvedHandlers instanceof Promise
+ ? await resolvedHandlers
+ : resolvedHandlers;
if (!handlers?.fileChangeApproval) {
this.logger.warn('fileChange approval without subscriber → decline', {
threadId: params.threadId,
@@ -533,11 +556,10 @@ export class AppServerHost {
client.setRequestHandler(Method.McpServerElicitationRequest, async (rawParams) => {
const params = rawParams as McpServerElicitationRequestParams;
- const handlers =
- this.handlersForThread(params.threadId)
- ?? (this.subscribers.size > 0
- ? await this.waitForThreadHandlers(params.threadId)
- : undefined);
+ const resolvedHandlers = this.resolveRequestHandlers(params.threadId);
+ const handlers = resolvedHandlers instanceof Promise
+ ? await resolvedHandlers
+ : resolvedHandlers;
if (!handlers?.mcpServerElicitation) {
this.logger.warn('MCP server elicitation without subscriber -> decline', {
threadId: params.threadId,
@@ -559,7 +581,10 @@ export class AppServerHost {
client.setRequestHandler(Method.PermissionsRequestApproval, async (rawParams) => {
const params = rawParams as PermissionsRequestApprovalParams;
- const handlers = this.handlersForThread(params.threadId);
+ const resolvedHandlers = this.resolveRequestHandlers(params.threadId);
+ const handlers = resolvedHandlers instanceof Promise
+ ? await resolvedHandlers
+ : resolvedHandlers;
if (!handlers?.permissionsApproval) {
this.logger.warn('permissions approval without subscriber → decline', {
threadId: params.threadId,
@@ -579,7 +604,10 @@ export class AppServerHost {
client.setRequestHandler(Method.ToolRequestUserInput, async (rawParams, meta) => {
const params = rawParams as ToolRequestUserInputParams;
- const handlers = this.handlersForThread(params.threadId);
+ const resolvedHandlers = this.resolveRequestHandlers(params.threadId);
+ const handlers = resolvedHandlers instanceof Promise
+ ? await resolvedHandlers
+ : resolvedHandlers;
if (!handlers?.requestUserInput) {
this.logger.warn('requestUserInput without subscriber -> empty response', {
threadId: params.threadId,
@@ -601,7 +629,10 @@ export class AppServerHost {
client.setRequestHandler(Method.DynamicToolCall, async (rawParams, meta) => {
const params = rawParams as DynamicToolCallParams;
- const handlers = this.handlersForThread(params.threadId);
+ const resolvedHandlers = this.resolveRequestHandlers(params.threadId);
+ const handlers = resolvedHandlers instanceof Promise
+ ? await resolvedHandlers
+ : resolvedHandlers;
if (!handlers?.dynamicToolCall) {
this.logger.warn('dynamicToolCall without subscriber -> failed result', {
threadId: params.threadId,
@@ -729,6 +760,7 @@ export class AppServerHost {
this.mcpToolAvailability.clear();
this.subscribers.clear();
this.lineageRoots.clear();
+ this.pendingLineage.clear();
this.buffered.clear();
for (const threadId of this.threadHandlerWaiters.keys()) {
this.notifyThreadHandlerWaiters(threadId);
@@ -991,6 +1023,154 @@ export class AppServerHost {
return rootThreadId ? this.subscribers.get(rootThreadId) : undefined;
}
+ private resolveRequestHandlers(
+ threadId: string,
+ ): ThreadEventHandlers | Promise<ThreadEventHandlers | undefined> | undefined {
+ const current = this.handlersForThread(threadId);
+ // Keep known root/descendant dispatch synchronous. requestUserInput and
+ // dynamicToolCall register their broker entry in the first synchronous
+ // statements; yielding here would let a same-turn serverRequest/resolved
+ // notification cancel the request before that registration (Codex P1).
+ if (current || this.subscribers.size === 0) return current;
+ return this.waitForThreadHandlers(threadId);
+ }
+
+ /**
+ * 血缘边登记的共享核心:解析 root、幂等去重、写入 lineageRoots。
+ * null = 无法归属(参数非法 / root 不在 / handlers 已释放)。能归属时一定返回
+ * root 与 handlers;`establishedNewEdge` 区分本次是否真的落了新边——重复登记
+ * (spawn 路径已建边后新版 codex 补发 thread/started)不再落表,但调用方仍拿得到
+ * handlers 去转发 thread 元数据(model 等),不能把重复当成完全的 no-op 吞掉。
+ * 新边落表后唤醒该子线程上等待血缘的 server request(见 waitForThreadHandlers):
+ * spawn 登记与 thread/started 两条路径都可能是 waiter 等的那次解析。
+ */
+ private establishDescendantLineage(
+ childThreadId: string,
+ parentThreadId: string,
+ ): {
+ rootThreadId: string;
+ handlers: ThreadEventHandlers;
+ establishedNewEdge: boolean;
+ releasedRequestWaiters: boolean;
+ } | null {
+ if (!childThreadId || !parentThreadId || parentThreadId === childThreadId) return null;
+ const rootThreadId = this.lineageRoots.get(parentThreadId)
+ ?? (this.subscribers.has(parentThreadId) ? parentThreadId : null);
+ if (!rootThreadId || childThreadId === rootThreadId) return null;
+
+ const handlers = this.subscribers.get(rootThreadId);
+ if (!handlers) return null;
+
+ if (this.lineageRoots.get(childThreadId) === rootThreadId) {
+ return {
+ rootThreadId,
+ handlers,
+ establishedNewEdge: false,
+ releasedRequestWaiters: false,
+ };
+ }
+
+ this.lineageRoots.set(childThreadId, rootThreadId);
+ const releasedRequestWaiters = this.notifyThreadHandlerWaiters(childThreadId);
+ return { rootThreadId, handlers, establishedNewEdge: true, releasedRequestWaiters };
+ }
+
+ /**
+ * 保留一条待确认的 spawn 血缘,但不安装 root 路由。
+ *
+ * 这是 turn reconciliation 之前的 provisional 状态:child notification 会继续
+ * 留在 child 自己的缓冲里,child server request 会等待;只有父 turn 被确认后,
+ * registerDescendantLineage 才会把它变成 live route。重复 reserve 幂等。
+ */
+ reserveDescendantLineage(childThreadId: string, parentThreadId: string): void {
+ if (!childThreadId || !parentThreadId || childThreadId === parentThreadId) return;
+ if (this.lineageRoots.has(childThreadId)) return;
+ const rootThreadId = this.lineageRoots.get(parentThreadId)
+ ?? (this.subscribers.has(parentThreadId) ? parentThreadId : null);
+ if (!rootThreadId || !this.subscribers.has(rootThreadId)) return;
+ const existing = this.pendingLineage.get(childThreadId);
+ if (existing) {
+ if (existing.parentThreadId !== parentThreadId || existing.rootThreadId !== rootThreadId) {
+ this.logger.warn('ignoring conflicting pending descendant lineage', {
+ childThreadId,
+ parentThreadId,
+ existing,
+ });
+ }
+ return;
+ }
+ this.pendingLineage.set(childThreadId, { parentThreadId, rootThreadId });
+ }
+
+ /**
+ * 丢弃尚未 commit 的 spawn 血缘:清掉 child 缓冲并唤醒请求 waiter 走 fail-closed。
+ * parentThreadId 可选,用于防止迟到/重复的旧 turn 清掉新 claim。
+ */
+ discardPendingDescendantLineage(childThreadId: string, parentThreadId?: string): void {
+ const pending = this.pendingLineage.get(childThreadId);
+ if (!pending || (parentThreadId && pending.parentThreadId !== parentThreadId)) return;
+ this.pendingLineage.delete(childThreadId);
+ this.buffered.delete(childThreadId);
+ this.notifyThreadHandlerWaiters(childThreadId);
+ }
+
+ /**
+ * Cindy 侧主动登记「子线程 → 父线程」血缘(spawn item 是唯一可靠来源)。
+ *
+ * codex 0.145 会把 spawn 出的子线程自动 attach 到本连接并转发它的
+ * item / tokenUsage / turn 通知,但 `thread/started` 只在显式 thread/start /
+ * fork RPC 时发,**内部 spawn 的子线程从来不发**(codex-rs
+ * `thread_processor.rs` 仅两处 emit)。只等 thread/started 建血缘,子线程的全部
+ * 通知都会在 TTL 缓冲里静默过期:子代理卡没有任何实时数据、终态永远不到,
+ * 卡片停在 spawn 时的 running 帧永久转圈;子线程的 approval 请求也会因
+ * handlersForThread 查不到 root 而被自动 decline(2026-08-04 生产实测)。
+ *
+ * 调用方(codex session)从 spawn item 的 agentThreadId / receiverThreadIds
+ * 拿到子线程 id 后立即登记。幂等:更新版 codex 若补发 thread/started,
+ * routeDescendantThreadStarted 只跳过重复建边与缓冲重放,thread 元数据
+ * (model 等)仍会照常转发给订阅者。
+ */
+ registerDescendantLineage(childThreadId: string, parentThreadId: string): void {
+ const pending = this.pendingLineage.get(childThreadId);
+ if (pending && pending.parentThreadId !== parentThreadId) {
+ this.logger.warn('ignoring descendant lineage commit for a conflicting pending claim', {
+ childThreadId,
+ parentThreadId,
+ pending,
+ });
+ return;
+ }
+ if (pending && pending.parentThreadId === parentThreadId) {
+ this.pendingLineage.delete(childThreadId);
+ }
+ const established = this.establishDescendantLineage(childThreadId, parentThreadId);
+ if (!established) {
+ if (pending?.parentThreadId === parentThreadId) {
+ this.buffered.delete(childThreadId);
+ this.notifyThreadHandlerWaiters(childThreadId);
+ }
+ return;
+ }
+ if (!established.establishedNewEdge) return;
+ const replayBufferedNotifications = (): void => {
+ // `thread/started` may already be buffered under this child id when the
+ // root subscription replays a spawn item and establishes lineage late.
+ // Preserve and forward that metadata (notably thread.model) before the
+ // ordinary descendant drain deletes the whole buffer and skips starts.
+ this.replayBufferedThreadStarts(childThreadId);
+ // 子线程在登记前已到达的通知缓存在它自己的 id 下,补投进 descendant 通道;
+ // 它名下若已缓冲了孙线程的 thread/started,一并重建整条血缘链。
+ this.drainBufferedDescendantNotifications(childThreadId, established.rootThreadId, established.handlers);
+ this.replayBufferedDescendantThreadStarts(established.rootThreadId);
+ };
+ // Resolving a lineage waiter schedules the server-request handler's await
+ // continuation. Let that continuation register its broker entry before a
+ // buffered serverRequest/resolved notification is replayed; otherwise the
+ // cancellation is lost and a request the server already closed reaches UI.
+ if (established.releasedRequestWaiters) queueMicrotask(replayBufferedNotifications);
+ else replayBufferedNotifications();
+ }
+
/**
* Give an already-owned descendant a short window for its thread/started
* notification to establish lineage. This closes an observed ordering race
@@ -1003,20 +1183,30 @@ export class AppServerHost {
if (current) return Promise.resolve(current);
return new Promise((resolve) => {
let settled = false;
+ let timer: NodeJS.Timeout | null = null;
const finish = (): void => {
if (settled) return;
+ const handlers = this.handlersForThread(threadId);
+ // A reserved spawn may legitimately outlive the normal notification TTL while
+ // the parent turn is being reconciled. Keep waiting until commit/discard settles
+ // it; unknown threads still use the bounded fail-closed window below.
+ if (!handlers && this.pendingLineage.has(threadId) && !this.shuttingDown) {
+ timer = setTimeout(finish, this.bufferTtlMs);
+ timer.unref?.();
+ return;
+ }
settled = true;
- clearTimeout(timer);
+ if (timer) clearTimeout(timer);
const waiters = this.threadHandlerWaiters.get(threadId);
waiters?.delete(finish);
if (waiters?.size === 0) this.threadHandlerWaiters.delete(threadId);
- resolve(this.handlersForThread(threadId));
+ resolve(handlers);
};
// Use the same bounded lineage window as early thread notifications.
// Both races are caused by thread/started crossing the subscribe/request
// boundary, so they should expire together instead of using a shorter
// empirical timeout that can fail only under load.
- const timer = setTimeout(finish, this.bufferTtlMs);
+ timer = setTimeout(finish, this.bufferTtlMs);
timer.unref?.();
const waiters = this.threadHandlerWaiters.get(threadId) ?? new Set<() => void>();
waiters.add(finish);
@@ -1024,25 +1214,24 @@ export class AppServerHost {
});
}
- private notifyThreadHandlerWaiters(threadId: string): void {
- for (const finish of [...(this.threadHandlerWaiters.get(threadId) ?? [])]) finish();
+ private notifyThreadHandlerWaiters(threadId: string): boolean {
+ const waiters = [...(this.threadHandlerWaiters.get(threadId) ?? [])];
+ for (const finish of waiters) finish();
+ return waiters.length > 0;
}
private routeDescendantThreadStarted(params: ThreadStartedNotification['params']): void {
const childThreadId = params.thread.id;
const parentThreadId = params.thread.parentThreadId;
- if (!parentThreadId || parentThreadId === childThreadId) return;
-
- const rootThreadId = this.lineageRoots.get(parentThreadId)
- ?? (this.subscribers.has(parentThreadId) ? parentThreadId : null);
- if (!rootThreadId) return;
- if (this.lineageRoots.get(childThreadId) === rootThreadId) return;
-
- const handlers = this.subscribers.get(rootThreadId);
- if (!handlers) return;
-
- this.lineageRoots.set(childThreadId, rootThreadId);
- this.notifyThreadHandlerWaiters(childThreadId);
+ if (!parentThreadId) return;
+ // A provisional spawn claim owns this child until parent turn reconciliation. Do not let
+ // an early thread/started install a live root route for a turn that may later be orphaned.
+ if (this.pendingLineage.has(childThreadId)) return;
+ const established = this.establishDescendantLineage(childThreadId, parentThreadId);
+ if (!established) return;
+ const { rootThreadId, handlers, establishedNewEdge, releasedRequestWaiters } = established;
+ // 血缘重复(spawn 路径已建边)也要转发:thread/started 是 thread.model 等实际
+ // 元数据的唯一载体,吞掉它会让「实际线程模型优先」永远等不到观测值(codex review)。
if (handlers.descendantThreadStarted) {
try {
handlers.descendantThreadStarted(params);
@@ -1055,16 +1244,22 @@ export class AppServerHost {
});
}
}
- // 血缘刚建立:该子线程在此之前到达的 item / tokenUsage / turn 通知都缓存在**它自己的
- // id** 下(那时既不是 subscriber 也没有 lineage)。root 侧的 drain 只排空 root id 的队列,
- // 这些永远排不到 → 早期工具数、token 丢失,漏掉 turn/completed 还会让卡片永久停在
- // running(codex review)。这里按到达顺序补投进 descendant 通道。
- this.drainBufferedDescendantNotifications(childThreadId, rootThreadId, handlers);
- // 本次血缘建立可能解锁**孙**线程:孙的 thread/started 缓存在它自己的 id 下,上面的 drain
- // 只排空 childThreadId 的队列,而且它按契约会跳过 thread/started —— 不再扫一遍,孙线程的
- // 血缘永远建不起来,它的 tool / token / 终态通知会一直烂在缓冲区直到过期(卡片漏计,并
- // 可能一直显示运行中或提前完成)(review)。复用 root 订阅时那套迭代重建。
- this.replayBufferedDescendantThreadStarts(rootThreadId);
+ // 重复建边只补元数据转发:缓冲早已在首次建边时排空,重放在这里只会空转。
+ if (!establishedNewEdge) return;
+ const replayBufferedNotifications = (): void => {
+ // 血缘刚建立:该子线程在此之前到达的 item / tokenUsage / turn 通知都缓存在**它自己的
+ // id** 下(那时既不是 subscriber 也没有 lineage)。root 侧的 drain 只排空 root id 的队列,
+ // 这些永远排不到 → 早期工具数、token 丢失,漏掉 turn/completed 还会让卡片永久停在
+ // running(codex review)。这里按到达顺序补投进 descendant 通道。
+ this.drainBufferedDescendantNotifications(childThreadId, rootThreadId, handlers);
+ // 本次血缘建立可能解锁**孙**线程:孙的 thread/started 缓存在它自己的 id 下,上面的 drain
+ // 只排空 childThreadId 的队列,而且它按契约会跳过 thread/started —— 不再扫一遍,孙线程的
+ // 血缘永远建不起来,它的 tool / token / 终态通知会一直烂在缓冲区直到过期(卡片漏计,并
+ // 可能一直显示运行中或提前完成)(review)。复用 root 订阅时那套迭代重建。
+ this.replayBufferedDescendantThreadStarts(rootThreadId);
+ };
+ if (releasedRequestWaiters) queueMicrotask(replayBufferedNotifications);
+ else replayBufferedNotifications();
}
/**
@@ -1097,6 +1292,20 @@ export class AppServerHost {
}
}
+ /**
+ * Forward buffered starts for one thread without consuming its buffer.
+ * The following ordinary drain owns deletion and skips these entries, so
+ * starts are delivered exactly once and ahead of item/usage/turn replay.
+ */
+ private replayBufferedThreadStarts(threadId: string): void {
+ const buffered = this.buffered.get(threadId);
+ if (!buffered) return;
+ for (const item of buffered) {
+ if (item.method !== 'thread/started') continue;
+ this.routeDescendantThreadStarted(item.params as ThreadStartedNotification['params']);
+ }
+ }
+
private replayBufferedDescendantThreadStarts(rootThreadId: string): void {
// 重入保护:本方法会调用 routeDescendantThreadStarted,而后者现在又会回调本方法。
// 嵌套再扫一遍是纯重复劳动(外层的 for(;;) 本来就会继续迭代直到没有新发现),
@@ -1147,6 +1356,13 @@ export class AppServerHost {
this.lineageRoots.delete(threadId);
}
}
+ for (const [threadId, pending] of this.pendingLineage) {
+ if (pending.rootThreadId === rootThreadId) {
+ this.pendingLineage.delete(threadId);
+ this.buffered.delete(threadId);
+ this.notifyThreadHandlerWaiters(threadId);
+ }
+ }
}
private dispatchToHandlers(handlers: ThreadEventHandlers, method: string, params: unknown): void {
@@ -1190,6 +1406,10 @@ export class AppServerHost {
setTimeout(() => {
const cur = this.buffered.get(threadId);
if (!cur) return;
+ // A provisional spawn claim owns this buffer until parent turn reconciliation;
+ // do not expire the child lifecycle/terminal events just because the normal TTL elapsed.
+ // commit/discard removes it explicitly.
+ if (this.pendingLineage.has(threadId)) return;
const cutoff = Date.now() - this.bufferTtlMs;
const remaining = cur.filter((x) => x.ts > cutoff);
if (remaining.length === 0) {
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index 5dd0595297..7b981b8588 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -419,6 +419,11 @@ function installFakeHost(
getSessionMcpConfig,
getConnectionId: () => 'test-connection',
getThreadHandlers: () => threadHandlers,
+ // 0.145 不给 spawn 子线程发 thread/started,session 层改为从 spawn item 主动
+ // 登记血缘;fake 里只记录调用,路由行为由 host.test.ts 的真 transport 覆盖。
+ reserveDescendantLineage: vi.fn(),
+ registerDescendantLineage: vi.fn(),
+ discardPendingDescendantLineage: vi.fn(),
};
Object.defineProperty(agent, 'getHost', {
@@ -1640,6 +1645,204 @@ describe('CodexAgent capability routing', () => {
}
await handle.close();
});
+
+ it('inherits capability routing into descendant MCP items and clears it at child terminal', async () => {
+ const agent = new CodexAgent(
+ createDeps(
+ {},
+ {
+ capabilityRouting,
+ getMcpToolApprovalPolicy: () => 'auto-approve',
+ },
+ ),
+ );
+ const host = installFakeHost(
+ agent,
+ (method) => method === Method.TurnStart
+ ? { turn: { id: 'root-capability-turn' } }
+ : undefined,
+ { userAgent: 'mock-codex/0.145.0' },
+ );
+ const handle = await agent.startSession({
+ sessionId: 'session-descendant-capability-routing',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ await handle.send({
+ type: 'user',
+ content: '请用 $feishu-delegate:message-feishu-coworkers 查一下康康',
+ });
+
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.itemStarted || !handlers.descendantNotification || !handlers.mcpServerElicitation) {
+ throw new Error('expected descendant capability handlers');
+ }
+
+ handlers.itemStarted({
+ threadId: 'start-thread-id',
+ turnId: 'root-capability-turn',
+ item: {
+ id: 'root-spawn-capability',
+ type: 'subAgentActivity',
+ kind: 'started',
+ agentThreadId: 'child-capability-thread',
+ },
+ });
+ handlers.descendantNotification('child-capability-thread', 'item/started', {
+ threadId: 'child-capability-thread',
+ turnId: 'child-capability-turn',
+ item: {
+ id: 'child-routed-mcp',
+ type: 'mcpToolCall',
+ server: 'cindy-routed-feishu-delegate',
+ tool: 'feishu_read_messages',
+ pluginId: 'feishu-delegate@personal',
+ },
+ });
+
+ const childRequest = {
+ threadId: 'child-capability-thread',
+ turnId: 'child-capability-turn',
+ serverName: 'cindy-routed-feishu-delegate',
+ mode: 'form' as const,
+ _meta: {
+ codex_approval_kind: 'mcp_tool_call',
+ tool_name: 'feishu_read_messages',
+ },
+ message: 'Allow tool call',
+ requestedSchema: {},
+ };
+ await expect(handlers.mcpServerElicitation(childRequest)).resolves.toEqual({
+ action: 'accept',
+ content: null,
+ _meta: null,
+ });
+
+ // The same inherited selector must reach a nested grandchild as well.
+ handlers.descendantNotification('child-capability-thread', 'item/started', {
+ threadId: 'child-capability-thread',
+ turnId: 'child-capability-turn',
+ item: {
+ id: 'nested-capability-spawn',
+ type: 'subAgentActivity',
+ kind: 'started',
+ agentThreadId: 'grandchild-capability-thread',
+ },
+ });
+ handlers.descendantNotification('grandchild-capability-thread', 'item/started', {
+ threadId: 'grandchild-capability-thread',
+ turnId: 'grandchild-capability-turn',
+ item: {
+ id: 'grandchild-routed-mcp',
+ type: 'mcpToolCall',
+ server: 'cindy-routed-feishu-delegate',
+ tool: 'feishu_read_messages',
+ pluginId: 'feishu-delegate@personal',
+ },
+ });
+ await expect(
+ handlers.mcpServerElicitation({
+ ...childRequest,
+ threadId: 'grandchild-capability-thread',
+ turnId: 'grandchild-capability-turn',
+ }),
+ ).resolves.toEqual({ action: 'accept', content: null, _meta: null });
+
+ handlers.descendantNotification('child-capability-thread', 'turn/completed', {
+ threadId: 'child-capability-thread',
+ turn: { id: 'child-capability-turn', status: 'completed' },
+ });
+ await expect(handlers.mcpServerElicitation(childRequest)).resolves.toEqual({
+ action: 'decline',
+ content: null,
+ _meta: null,
+ });
+
+ await handle.close();
+ });
+
+ it('falls back to inherited thread selection when a child item predates turn binding', async () => {
+ const pendingTurnStart = deferred<{ turn: { id: string } }>();
+ const agent = new CodexAgent(
+ createDeps(
+ {},
+ {
+ capabilityRouting,
+ getMcpToolApprovalPolicy: () => 'auto-approve',
+ },
+ ),
+ );
+ const host = installFakeHost(
+ agent,
+ (method) => method === Method.TurnStart ? pendingTurnStart.promise : undefined,
+ { userAgent: 'mock-codex/0.145.0' },
+ );
+ const handle = await agent.startSession({
+ sessionId: 'session-descendant-capability-race',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const sendPromise = handle.send({
+ type: 'user',
+ content: '请用 $feishu-delegate:message-feishu-coworkers 查消息',
+ });
+ await vi.waitFor(() => {
+ expect(
+ host.request.mock.calls.filter(([method]) => method === Method.TurnStart),
+ ).toHaveLength(1);
+ });
+
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.turnStarted || !handlers.descendantThreadStarted || !handlers.descendantNotification || !handlers.mcpServerElicitation) {
+ throw new Error('expected descendant capability handlers');
+ }
+
+ // The child route is known before the root turn/start response binds the
+ // root selector. Its first item therefore cannot bind a child turn yet.
+ handlers.descendantThreadStarted({
+ thread: {
+ id: 'race-child-thread',
+ parentThreadId: 'start-thread-id',
+ model: 'gpt-5.4-mini',
+ },
+ });
+ handlers.descendantNotification('race-child-thread', 'item/started', {
+ threadId: 'race-child-thread',
+ turnId: 'race-child-turn',
+ item: {
+ id: 'race-child-routed-mcp',
+ type: 'mcpToolCall',
+ server: 'cindy-routed-feishu-delegate',
+ tool: 'feishu_read_messages',
+ pluginId: 'feishu-delegate@personal',
+ },
+ });
+
+ // This is the authoritative root acceptance, but it arrives after the
+ // child item. The child turn map remains empty; the thread map is not.
+ handlers.turnStarted({
+ threadId: 'start-thread-id',
+ turn: { id: 'race-root-turn' },
+ });
+ await expect(
+ handlers.mcpServerElicitation({
+ threadId: 'race-child-thread',
+ turnId: 'race-child-turn',
+ serverName: 'cindy-routed-feishu-delegate',
+ mode: 'form',
+ _meta: {
+ codex_approval_kind: 'mcp_tool_call',
+ tool_name: 'feishu_read_messages',
+ },
+ message: 'Allow tool call',
+ requestedSchema: {},
+ }),
+ ).resolves.toEqual({ action: 'accept', content: null, _meta: null });
+
+ pendingTurnStart.resolve({ turn: { id: 'race-root-turn' } });
+ await sendPromise;
+ await handle.close();
+ });
});
describe('CodexAgent reference directories', () => {
@@ -14124,6 +14327,161 @@ describe('CodexAgent turn lifecycle', () => {
await handle.close();
});
+ it('registers buffered spawn lineage before slow turn reconciliation and replays child terminal state', async () => {
+ const firstStart = deferred<unknown>();
+ const secondStart = deferred<unknown>();
+ let attempt = 0;
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) {
+ attempt += 1;
+ return attempt === 1 ? firstStart.promise : secondStart.promise;
+ }
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-buffered-subagent-spawn',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const events: AgentEvent[] = [];
+ void (async () => {
+ for await (const event of handle.events()) events.push(event);
+ })();
+ const subscribeCalls = host.subscribeThread.mock.calls as unknown as Array<[string, ThreadEventHandlers]>;
+ const handlers = subscribeCalls[0]?.[1];
+
+ // 第一轮失败只用于武装既有的 pre-turn 对账路径。
+ const send1 = handle.send({ type: 'user', content: 'first' });
+ await vi.waitFor(() => {
+ expect(host.request.mock.calls.filter(([method]) => method === Method.TurnStart)).toHaveLength(1);
+ });
+ firstStart.reject(new Error('codex app-server turn/start timed out after 60000ms'));
+ await send1;
+
+ // 第二轮的 started 与 spawn item 都先于 turn/start response。spawn 的卡片处理
+ // 仍应排队,但 child 血缘必须立刻登记,不能等可能超过 5s 的对账完成。
+ const send2 = handle.send({ type: 'user', content: 'second' });
+ await vi.waitFor(() => {
+ expect(host.request.mock.calls.filter(([method]) => method === Method.TurnStart)).toHaveLength(2);
+ });
+ handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-buffered-spawn' } });
+ handlers.itemStarted?.({
+ threadId: 'start-thread-id',
+ turnId: 'turn-buffered-spawn',
+ item: {
+ id: 'spawn-buffered-v2',
+ type: 'subAgentActivity',
+ kind: 'started',
+ agentThreadId: 'child-buffered-v2',
+ agentPath: '/root/slow-child',
+ },
+ });
+ expect(host.reserveDescendantLineage).toHaveBeenCalledWith(
+ 'child-buffered-v2',
+ 'start-thread-id',
+ );
+ expect(host.registerDescendantLineage).not.toHaveBeenCalled();
+ expect(events.some((event) => event.type === 'agent_task_update')).toBe(false);
+
+ // child 用量与终态在父 spawn 重放前到达:tracker 先缓冲,对账后必须和 spawn
+ // 同批重放,最终卡片直接收口 completed 而不是永久 running。
+ handlers.descendantNotification?.('child-buffered-v2', 'thread/tokenUsage/updated', {
+ threadId: 'child-buffered-v2',
+ tokenUsage: { total: { totalTokens: 7_777 } },
+ });
+ handlers.descendantNotification?.('child-buffered-v2', 'turn/completed', {
+ threadId: 'child-buffered-v2',
+ turn: { id: 'child-turn-buffered', status: 'completed' },
+ });
+
+ secondStart.resolve({ turn: { id: 'turn-buffered-spawn' } });
+ await send2;
+ expect(host.registerDescendantLineage).toHaveBeenCalledWith(
+ 'child-buffered-v2',
+ 'start-thread-id',
+ );
+ await vi.waitFor(() => {
+ const last = events
+ .filter((event) => event.type === 'agent_task_update')
+ .map((event) => event.data as {
+ taskId?: string;
+ status?: string;
+ usage?: { totalTokens?: number };
+ })
+ .filter((update) => update.taskId === 'spawn-buffered-v2')
+ .at(-1);
+ expect(last?.status).toBe('completed');
+ expect(last?.usage?.totalTokens).toBe(7_777);
+ });
+
+ await handle.close();
+ });
+
+ it('discards provisional spawn lineage when turn reconciliation proves the parent orphan', async () => {
+ const firstStart = deferred<unknown>();
+ const secondStart = deferred<unknown>();
+ let attempt = 0;
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) {
+ attempt += 1;
+ return attempt === 1 ? firstStart.promise : secondStart.promise;
+ }
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-orphaned-subagent-spawn',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const subscribeCalls = host.subscribeThread.mock.calls as unknown as Array<[string, ThreadEventHandlers]>;
+ const handlers = subscribeCalls[0]?.[1];
+
+ const send1 = handle.send({ type: 'user', content: 'first' });
+ await vi.waitFor(() => {
+ expect(host.request.mock.calls.filter(([method]) => method === Method.TurnStart)).toHaveLength(1);
+ });
+ firstStart.reject(new Error('codex app-server turn/start timed out after 60000ms'));
+ await send1;
+
+ const send2 = handle.send({ type: 'user', content: 'second' });
+ await vi.waitFor(() => {
+ expect(host.request.mock.calls.filter(([method]) => method === Method.TurnStart)).toHaveLength(2);
+ });
+ handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'orphan-parent-turn' } });
+ handlers.itemStarted?.({
+ threadId: 'start-thread-id',
+ turnId: 'orphan-parent-turn',
+ item: {
+ id: 'orphan-spawn',
+ type: 'subAgentActivity',
+ kind: 'started',
+ agentThreadId: 'orphan-child-thread',
+ },
+ });
+ expect(host.reserveDescendantLineage).toHaveBeenCalledWith(
+ 'orphan-child-thread',
+ 'start-thread-id',
+ );
+ expect(host.registerDescendantLineage).not.toHaveBeenCalled();
+
+ // A different response proves the buffered parent turn is an orphan. Its child route
+ // must be discarded rather than left attached to the live replacement turn.
+ secondStart.resolve({ turn: { id: 'replacement-parent-turn' } });
+ await send2;
+ expect(host.discardPendingDescendantLineage).toHaveBeenCalledWith(
+ 'orphan-child-thread',
+ 'start-thread-id',
+ );
+ expect(host.registerDescendantLineage).not.toHaveBeenCalledWith(
+ 'orphan-child-thread',
+ 'start-thread-id',
+ );
+
+ await handle.close();
+ });
+
it('holds a buffered turn approval request and declines it once the response proves the turn an orphan (codex R12 P1)', async () => {
// 孤儿 turn 在对账前发审批请求: 请求挂起不上 UI; 响应证明孤儿 →
// 按 decline 释放 — 用户不能为隐藏 turn 批准操作。
@@ -14654,6 +15012,127 @@ describe('CodexAgent turn lifecycle', () => {
await handle.close();
});
+ it('keeps verified descendant server requests outside the root orphan gate', async () => {
+ const failedStart = deferred<unknown>();
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) return failedStart.promise;
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-descendant-request-after-root-start-failure',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ permissionMode: 'ask',
+ });
+ const handlers = host.getThreadHandlers();
+ if (
+ !handlers?.commandExecutionApproval
+ || !handlers.fileChangeApproval
+ || !handlers.mcpServerElicitation
+ || !handlers.permissionsApproval
+ || !handlers.requestUserInput
+ || !handlers.dynamicToolCall
+ ) {
+ throw new Error('expected all descendant server request handlers');
+ }
+ const iterator = handle.events()[Symbol.asyncIterator]();
+ const resolver = vi.fn(async (request: InteractionRequest): Promise<InteractionDecision> => {
+ if (request.kind === 'permission') {
+ return { kind: 'permission', behavior: 'allow' };
+ }
+ if (request.kind !== 'ask_user_question') {
+ throw new Error(`unexpected interaction kind: ${request.kind}`);
+ }
+ return {
+ kind: 'ask_user_question',
+ answers: { [request.questions[0]?.question ?? '']: 'Continue' },
+ };
+ });
+ handle.setInteractionResolver(resolver);
+
+ const send = handle.send({ type: 'user', content: 'start root turn' });
+ for (let i = 0; i < 5; i += 1) {
+ if (host.request.mock.calls.some(([method]) => method === Method.TurnStart)) break;
+ await Promise.resolve();
+ }
+ failedStart.reject(new Error('codex app-server turn/start timed out after 60000ms'));
+ await send;
+ expect(await nextEvent(iterator)).toMatchObject({ type: 'status', data: { isRunning: true } });
+ expect(await nextEvent(iterator)).toMatchObject({ type: 'error', data: { isTerminal: true } });
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'status',
+ data: { status: 'Done', isRunning: false },
+ });
+ const interruptsBeforeRequests = host.request.mock.calls.filter(
+ ([method]) => method === Method.TurnInterrupt,
+ ).length;
+ const child = { threadId: 'child-thread-id', turnId: 'child-turn-id' };
+
+ await expect(handlers.commandExecutionApproval({
+ ...child,
+ itemId: 'child-command',
+ command: 'pwd',
+ cwd: '/repo',
+ })).resolves.toEqual({ decision: 'accept' });
+ await expect(handlers.fileChangeApproval({
+ ...child,
+ itemId: 'child-file-change',
+ grantRoot: '/repo',
+ })).resolves.toEqual({ decision: 'accept' });
+ await expect(handlers.mcpServerElicitation({
+ ...child,
+ serverName: 'cindy_contacts',
+ mode: 'form',
+ _meta: {
+ codex_approval_kind: 'mcp_tool_call',
+ tool_params: { name: 'contacts_search', args: { query: 'Carol' } },
+ },
+ message: 'Allow tool call',
+ requestedSchema: {},
+ })).resolves.toEqual({ action: 'accept', content: null, _meta: null });
+ await expect(handlers.permissionsApproval({
+ ...child,
+ itemId: 'child-permissions',
+ permissions: { network: true },
+ })).resolves.toEqual({ permissions: { network: true }, scope: 'turn' });
+ await expect(handlers.requestUserInput({
+ ...child,
+ itemId: 'child-input',
+ questions: [{
+ id: 'continue',
+ header: 'Continue',
+ question: 'Continue child task?',
+ isOther: false,
+ isSecret: false,
+ options: [],
+ }],
+ }, { requestId: 'child-input-request' })).resolves.toEqual({
+ answers: { continue: { answers: ['Continue'] } },
+ });
+ await expect(handlers.dynamicToolCall({
+ ...child,
+ callId: 'child-dynamic-call',
+ namespace: 'cindy',
+ tool: 'ask_user_question',
+ arguments: {
+ questions: [{
+ id: 'direction',
+ header: 'Direction',
+ question: 'Choose child direction?',
+ }],
+ },
+ }, { requestId: 'child-dynamic-request' })).resolves.toMatchObject({
+ success: true,
+ });
+
+ expect(resolver).toHaveBeenCalledTimes(6);
+ expect(host.request.mock.calls.filter(
+ ([method]) => method === Method.TurnInterrupt,
+ )).toHaveLength(interruptsBeforeRequests);
+ await handle.close();
+ });
+
it('rejects a late orphan server request after the replacement turn was accepted (codex R17 P1)', async () => {
// 替换 turn 已被接受 (currentTurnId 非 null): 孤儿迟到的审批请求既不是
// idle 也不是 buffered, gate 必须直接拒 — 否则为隐藏孤儿 turn 上 UI。
@@ -18611,7 +19090,11 @@ describe('CodexAgent context window reporting', () => {
// 映射已就位 → 子线程的实时事件应当当场路由成卡片更新,而不是被缓冲到 completed。
handlers.descendantThreadStarted({
- thread: { id: 'child-thread-1', parentThreadId: 'start-thread-id' },
+ thread: {
+ id: 'child-thread-1',
+ parentThreadId: 'start-thread-id',
+ model: 'codex/gpt-5.6-sol',
+ },
});
handlers.descendantNotification('child-thread-1', 'item/started', {
threadId: 'child-thread-1',
@@ -18630,17 +19113,274 @@ describe('CodexAgent context window reporting', () => {
});
const updates = events
.filter((e) => e.type === 'agent_task_update')
- .map((e) => e.data as { taskId?: string; status?: string; usage?: { totalTokens?: number; toolUses?: number } });
+ .map((e) => e.data as {
+ taskId?: string;
+ status?: string;
+ model?: string;
+ usage?: { totalTokens?: number; toolUses?: number };
+ });
// 运行期就能看到真实聚合(工具数与 token),不是等 completed 才补。
expect(updates.some((u) => u.taskId === 'spawn-item-1')).toBe(true);
const last = updates.filter((u) => u.taskId === 'spawn-item-1').at(-1);
expect(last?.usage?.toolUses).toBe(1);
expect(last?.usage?.totalTokens).toBe(4_242);
+ expect(last?.model).toBe('codex/gpt-5.6-sol');
expect(last?.status).toBe('running');
await handle.close();
});
+ it('completes the subagent card without any thread/started (codex 0.145 real behavior)', async () => {
+ // 生产实测(2026-08-04):0.145 只在显式 thread/start / fork RPC 时发
+ // thread/started,spawn 出的子线程从来不发。血缘必须在识别 spawn item 的那一刻
+ // 主动向 host 登记,子线程的实时用量与终态才路由得进来 —— 否则卡片停在 spawn
+ // 时的 running 帧,无用量、永不收口。
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-subagent-no-thread-started',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const events: AgentEvent[] = [];
+ void (async () => {
+ for await (const event of handle.events()) events.push(event);
+ })();
+
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.itemStarted || !handlers.descendantNotification) {
+ throw new Error('expected item/descendant handlers');
+ }
+ handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-v2' } });
+
+ // V2 spawn:瞬时 subAgentActivity。识别即应向 host 登记血缘。
+ handlers.itemStarted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-v2',
+ item: {
+ id: 'spawn-v2-1',
+ type: 'subAgentActivity',
+ kind: 'started',
+ agentThreadId: 'child-thread-v2',
+ agentPath: '/root/scout',
+ },
+ });
+ expect(host.registerDescendantLineage).toHaveBeenCalledWith('child-thread-v2', 'start-thread-id');
+
+ // 子线程全程只有 item / tokenUsage / turn 通知(0.145 真实形状),没有 thread/started。
+ handlers.descendantNotification('child-thread-v2', 'item/completed', {
+ threadId: 'child-thread-v2',
+ turnId: 'child-turn-v2',
+ item: { id: 'child-tool-v2', type: 'commandExecution' },
+ });
+ // 嵌套 spawn 只出现在子线程自己的流里 —— 必须也从 item 建立孙线程路由。
+ handlers.descendantNotification('child-thread-v2', 'item/started', {
+ threadId: 'child-thread-v2',
+ turnId: 'child-turn-v2',
+ item: {
+ id: 'spawn-v2-nested',
+ type: 'subAgentActivity',
+ kind: 'started',
+ agentThreadId: 'grandchild-thread-v2',
+ },
+ });
+ expect(host.registerDescendantLineage).toHaveBeenCalledWith('grandchild-thread-v2', 'child-thread-v2');
+ handlers.descendantNotification('grandchild-thread-v2', 'thread/tokenUsage/updated', {
+ threadId: 'grandchild-thread-v2',
+ tokenUsage: { total: { totalTokens: 1_000 } },
+ });
+ handlers.descendantNotification('grandchild-thread-v2', 'turn/completed', {
+ threadId: 'grandchild-thread-v2',
+ turn: { id: 'grandchild-turn', status: 'completed' },
+ });
+ handlers.descendantNotification('child-thread-v2', 'turn/completed', {
+ threadId: 'child-thread-v2',
+ turn: { id: 'child-turn-v2', status: 'completed' },
+ });
+
+ await vi.waitFor(() => {
+ const updates = events
+ .filter((e) => e.type === 'agent_task_update')
+ .map((e) => e.data as { taskId?: string; status?: string; usage?: { totalTokens?: number; toolUses?: number } })
+ .filter((u) => u.taskId === 'spawn-v2-1');
+ const last = updates.at(-1);
+ // 子线程 + 孙线程全部收口 → 卡片终态 completed,并带聚合用量。
+ expect(last?.status).toBe('completed');
+ expect(last?.usage?.toolUses).toBe(1);
+ expect(last?.usage?.totalTokens).toBe(1_000);
+ });
+
+ await handle.close();
+ });
+
+ it('does not keep failed nested spawn receiver ids running', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-subagent-failed-nested-spawn',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const events: AgentEvent[] = [];
+ void (async () => {
+ for await (const event of handle.events()) events.push(event);
+ })();
+
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.itemStarted || !handlers.descendantNotification) {
+ throw new Error('expected item/descendant handlers');
+ }
+ handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-root' } });
+ handlers.itemStarted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-root',
+ item: {
+ id: 'spawn-root',
+ type: 'subAgentActivity',
+ kind: 'started',
+ agentThreadId: 'child-thread',
+ },
+ });
+
+ // V1 can report a failed nested spawn with receiver ids even though no
+ // receiver thread was actually started. It must be latched as failed, not
+ // attached as a running descendant that blocks the ancestor card forever.
+ handlers.descendantNotification('child-thread', 'item/completed', {
+ threadId: 'child-thread',
+ turnId: 'turn-child',
+ item: {
+ id: 'spawn-nested-failed',
+ type: 'collabAgentToolCall',
+ tool: 'spawnAgent',
+ senderThreadId: 'child-thread',
+ receiverThreadIds: ['phantom-grandchild'],
+ status: 'failed',
+ agentsStates: [],
+ },
+ });
+ expect(host.registerDescendantLineage).toHaveBeenCalledWith(
+ 'phantom-grandchild',
+ 'child-thread',
+ );
+
+ // Even a late lifecycle event cannot reopen the failed nested spawn.
+ handlers.descendantNotification('phantom-grandchild', 'turn/started', {
+ threadId: 'phantom-grandchild',
+ turn: { id: 'turn-phantom' },
+ });
+ handlers.descendantNotification('child-thread', 'turn/completed', {
+ threadId: 'child-thread',
+ turn: { id: 'turn-child', status: 'completed' },
+ });
+
+ await vi.waitFor(() => {
+ const last = events
+ .filter((event) => event.type === 'agent_task_update')
+ .map((event) => event.data as { taskId?: string; status?: string })
+ .filter((update) => update.taskId === 'spawn-root')
+ .at(-1);
+ expect(last?.status).toBe('failed');
+ });
+
+ await handle.close();
+ });
+
+ it('registers a nested spawn completed after its parent turn already settled', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-subagent-late-nested-spawn',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const events: AgentEvent[] = [];
+ void (async () => {
+ for await (const event of handle.events()) events.push(event);
+ })();
+
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.itemStarted || !handlers.descendantNotification) {
+ throw new Error('expected item/descendant handlers');
+ }
+ handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-root' } });
+ handlers.itemStarted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-root',
+ item: {
+ id: 'spawn-root-late-nested',
+ type: 'subAgentActivity',
+ kind: 'started',
+ agentThreadId: 'child-thread-late-nested',
+ },
+ });
+
+ handlers.descendantNotification('child-thread-late-nested', 'turn/completed', {
+ threadId: 'child-thread-late-nested',
+ turn: { id: 'child-turn-late-nested', status: 'completed' },
+ });
+ await vi.waitFor(() => {
+ const last = events
+ .filter((event) => event.type === 'agent_task_update')
+ .map((event) => event.data as { taskId?: string; status?: string })
+ .filter((update) => update.taskId === 'spawn-root-late-nested')
+ .at(-1);
+ expect(last?.status).toBe('completed');
+ });
+
+ // App-server may deliver the spawning item's completed frame after the
+ // parent turn terminal. It remains authoritative for 0.145 lineage even
+ // though late tool provenance for the parent turn stays blocked.
+ handlers.descendantNotification('child-thread-late-nested', 'item/completed', {
+ threadId: 'child-thread-late-nested',
+ turnId: 'child-turn-late-nested',
+ item: {
+ id: 'spawn-grandchild-late',
+ type: 'collabAgentToolCall',
+ tool: 'spawnAgent',
+ senderThreadId: 'child-thread-late-nested',
+ receiverThreadIds: ['grandchild-thread-late'],
+ status: 'completed',
+ agentsStates: [],
+ },
+ });
+ expect(host.registerDescendantLineage).toHaveBeenCalledWith(
+ 'grandchild-thread-late',
+ 'child-thread-late-nested',
+ );
+ await vi.waitFor(() => {
+ const last = events
+ .filter((event) => event.type === 'agent_task_update')
+ .map((event) => event.data as { taskId?: string; status?: string })
+ .filter((update) => update.taskId === 'spawn-root-late-nested')
+ .at(-1);
+ expect(last?.status).toBe('running');
+ });
+
+ handlers.descendantNotification('grandchild-thread-late', 'thread/tokenUsage/updated', {
+ threadId: 'grandchild-thread-late',
+ tokenUsage: { total: { totalTokens: 2_468 } },
+ });
+ handlers.descendantNotification('grandchild-thread-late', 'turn/completed', {
+ threadId: 'grandchild-thread-late',
+ turn: { id: 'grandchild-turn-late', status: 'completed' },
+ });
+ await vi.waitFor(() => {
+ const last = events
+ .filter((event) => event.type === 'agent_task_update')
+ .map((event) => event.data as {
+ taskId?: string;
+ status?: string;
+ usage?: { totalTokens?: number };
+ })
+ .filter((update) => update.taskId === 'spawn-root-late-nested')
+ .at(-1);
+ expect(last?.status).toBe('completed');
+ expect(last?.usage?.totalTokens).toBe(2_468);
+ });
+
+ await handle.close();
+ });
+
it('closes out running subagent cards when the transport dies (app-server crash / IO disconnect)', async () => {
// 普通 transport 断连(app-server 崩溃 / stdio 断开)会作废订阅:后代通知**永远不会再到**,
// 而 tracker 的终态只由后代 turn/completed 写入。原来这条路径只广播 error 并清主线程缓存,
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index ed107cde7a..31c68d3728 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -117,6 +117,7 @@ import {
translateAccountRateLimitsUpdated,
translatePlanUpdatedNotification,
extractRolloutUpdatePlanFunctionCallEvent,
+ readCodexSubagentSpawnRegistration,
type CodexRuntimeState,
} from './translator.js';
import {
@@ -2037,6 +2038,7 @@ export class CodexAgent extends BaseAgent {
let codexBrowserUseStartupTimeoutMs: number | undefined;
let remoteCompactionProviderId: string | undefined;
let buildSessionMcpConfig: CodexExtraSpawnConfig['buildSessionMcpConfig'];
+ let subagentModelFallback: string | undefined;
for (;;) {
const upgradedToSuperset = spawnCredentialMode !== credentialMode;
onSpawnCredentialModeResolved?.(spawnCredentialMode);
@@ -2061,6 +2063,7 @@ export class CodexAgent extends BaseAgent {
codexBrowserUseStartupTimeoutMs = undefined;
remoteCompactionProviderId = undefined;
buildSessionMcpConfig = undefined;
+ subagentModelFallback = undefined;
if (this.deps.prepareCodexExtraSpawnConfig) {
try {
const cfg = await this.deps.prepareCodexExtraSpawnConfig(
@@ -2075,6 +2078,7 @@ export class CodexAgent extends BaseAgent {
Object.assign(env, cfg.extraEnv);
extraArgs = cfg.extraArgs;
buildSessionMcpConfig = cfg.buildSessionMcpConfig;
+ subagentModelFallback = cfg.subagentModelFallback;
codexProxyActive = cfg.codexProxyActive === true && !remoteHostId;
// Remote daemons own their browser companion and its CODEX_HOME;
// preserve the host-provided availability snapshot instead of
@@ -2160,6 +2164,7 @@ export class CodexAgent extends BaseAgent {
codexBrowserUseStartupTimeoutMs,
remoteCompactionProviderId,
buildSessionMcpConfig,
+ subagentModelFallback,
// app-server 对失败 RPC 返回 cloudRequirements + Auth/relogin 结构化错误时,当前 host
// 持有的 token 已不可用。stderr 与工具输出只做诊断,绝不驱动鉴权状态。保留 host 只会
// 持续撞鉴权失败; auth.invalidate 会触发 logout + 通知 UI 重登。延后到 microtask
@@ -2766,6 +2771,52 @@ export class CodexAgent extends BaseAgent {
// carried it. A global "last send text" can be poisoned by a turn/start
// that later fails, and can then unlock an unrelated surviving turn.
const capabilitySelectionTextByTurnId = new Map<string, string>();
+ /**
+ * Descendant turns do not have their own user-facing selector. Their
+ * capability choice is inherited from the root turn that spawned them.
+ * Keep that choice by thread as well as by turn so a child can spawn a
+ * grandchild after the root turn has already completed.
+ */
+ const capabilitySelectionTextByThreadId = new Map<string, string>();
+ const descendantParentThreadByThreadId = new Map<string, string>();
+ /** A terminal child turn must not re-register tool provenance from late items. */
+ const terminalDescendantTurnIds = new Set<string>();
+
+ const propagateCapabilitySelectionToDescendants = (
+ parentThreadId: string,
+ visited = new Set<string>(),
+ ): void => {
+ if (visited.has(parentThreadId)) return;
+ visited.add(parentThreadId);
+ const selectionText = capabilitySelectionTextByThreadId.get(parentThreadId);
+ if (selectionText === undefined) return;
+ for (const [childThreadId, parent] of descendantParentThreadByThreadId) {
+ if (parent !== parentThreadId) continue;
+ // Descendants have no independent user selector. Keep their inherited
+ // view in sync when the root accepts a later steer as well as when a
+ // route is first registered.
+ capabilitySelectionTextByThreadId.set(childThreadId, selectionText);
+ propagateCapabilitySelectionToDescendants(childThreadId, visited);
+ }
+ };
+
+ const bindCapabilitySelectionToDescendantTurn = (
+ childThreadId: string,
+ turnId: string | undefined,
+ ): void => {
+ if (!turnId || terminalDescendantTurnIds.has(turnId)) return;
+ const selectionText = capabilitySelectionTextByThreadId.get(childThreadId);
+ if (selectionText !== undefined) {
+ capabilitySelectionTextByTurnId.set(turnId, selectionText);
+ }
+ };
+
+ const bindRootCapabilitySelection = (turnId: string, selectionText: string): void => {
+ capabilitySelectionTextByTurnId.set(turnId, selectionText);
+ capabilitySelectionTextByThreadId.set(threadId, selectionText);
+ propagateCapabilitySelectionToDescendants(threadId);
+ };
+
type PendingCapabilitySteer = {
completion: Promise<void>;
resolve: () => void;
@@ -2796,6 +2847,13 @@ export class CodexAgent extends BaseAgent {
return;
}
appendCapabilitySelectionText(turnId, selectionText);
+ if (currentTurnId === turnId) {
+ capabilitySelectionTextByThreadId.set(
+ threadId,
+ capabilitySelectionTextByTurnId.get(turnId) ?? '',
+ );
+ propagateCapabilitySelectionToDescendants(threadId);
+ }
};
const registerPendingCapabilitySteer = (
@@ -3297,7 +3355,11 @@ export class CodexAgent extends BaseAgent {
* 只在同步的 emitSubagentCardUpdate 内为 true(见那里的注释)。
*/
let emittingDescendantUpdate = false;
- const subagentLiveCards = createSubagentLiveCardTracker();
+ const subagentLiveCards = createSubagentLiveCardTracker({
+ // Fake/legacy hosts used by older callers may not expose this optional
+ // Cindy metadata accessor; absence must remain an honest no-model state.
+ subagentModelFallback: host.getSubagentModelFallback?.(),
+ });
const emitSubagentCardUpdate = (update: SubagentLiveCardUpdate): void => {
// 子代理帧**不得**参与主 turn 的存活判定。eventQueue.push 上装了探针:每条事件都会刷新
@@ -3318,6 +3380,7 @@ export class CodexAgent extends BaseAgent {
parentToolUseId: update.taskId,
status: update.status,
...(update.agentPath ? { title: update.agentPath } : {}),
+ ...(update.model !== undefined ? { model: update.model } : {}),
usage: {
...(update.totalTokens > 0 ? { totalTokens: update.totalTokens } : {}),
...(update.toolUses > 0 ? { toolUses: update.toolUses } : {}),
@@ -3331,13 +3394,161 @@ export class CodexAgent extends BaseAgent {
}
};
+ /**
+ * 把一个子线程接进本会话的后代路由:host 血缘(通知与 approval 归 root)+
+ * MCP context + 宿主的 child-thread 登记。
+ *
+ * codex 0.145 对 spawn 出的子线程**从不发** `thread/started`(它只在显式
+ * thread/start / fork RPC 时发),所以血缘的唯一可靠来源是 spawn item 自带的
+ * agentThreadId / receiverThreadIds —— 识别 spawn 的那一刻就得登记,不能等一条
+ * 永远不会来的通知。等待的后果(2026-08-04 生产实测):子线程全部通知在 host 的
+ * 5s TTL 缓冲里静默过期,子代理卡没有任何实时数据、终态永远不到,永久转圈。
+ * 各步幂等:更新版 codex 若补发 thread/started,重复建边是 no-op,但 host 仍会
+ * 转发该通知——它携带的 thread.model 是实际模型的唯一观测入口(codex review)。
+ */
+ const registerDescendantThreadRouting = (
+ childThreadId: string,
+ parentThreadId: string,
+ ): void => {
+ if (!childThreadId || childThreadId === parentThreadId) return;
+ // 测试用的 fake host 可能没有这个方法;真实 AppServerHost 恒有。
+ host.registerDescendantLineage?.(childThreadId, parentThreadId);
+ descendantParentThreadByThreadId.set(childThreadId, parentThreadId);
+ const inheritedSelection = capabilitySelectionTextByThreadId.get(parentThreadId)
+ ?? (parentThreadId === threadId && currentTurnId
+ ? capabilitySelectionTextByTurnId.get(currentTurnId)
+ : undefined);
+ if (
+ inheritedSelection !== undefined
+ && !capabilitySelectionTextByThreadId.has(childThreadId)
+ ) {
+ capabilitySelectionTextByThreadId.set(childThreadId, inheritedSelection);
+ propagateCapabilitySelectionToDescendants(childThreadId);
+ }
+ registerDescendantCodexMcpContext(childThreadId);
+ this.deps.registerCodexChildThreadForParent?.({ parentThreadId, childThreadId });
+ };
+
+ const reserveDescendantThreadRouting = (
+ childThreadId: string,
+ parentThreadId: string,
+ ): void => {
+ if (!childThreadId || childThreadId === parentThreadId) return;
+ host.reserveDescendantLineage?.(childThreadId, parentThreadId);
+ };
+
+ /**
+ * 只登记 spawn item 暴露的血缘,不建卡、不发帧。
+ *
+ * pre-turn / turn-start 对账会把 item handler 整体排队;若连血缘也等到重放才登记,
+ * child 通知会在 AppServerHost 的 5s TTL 内过期。这里允许在归属尚未对账时先做
+ * 幂等路由登记,卡片 tracker 与 translator 仍严格留在原队列顺序里处理。
+ */
+ const reserveSubagentSpawnLineage = (item: unknown): string[] => {
+ const registration = readCodexSubagentSpawnRegistration(item);
+ if (!registration) return [];
+ for (const childThreadId of registration.childThreadIds) {
+ reserveDescendantThreadRouting(childThreadId, threadId);
+ }
+ return registration.childThreadIds;
+ };
+
+ const registerSubagentSpawnLineage = (item: unknown): boolean => {
+ const registration = readCodexSubagentSpawnRegistration(item);
+ if (!registration) return false;
+ for (const childThreadId of registration.childThreadIds) {
+ registerDescendantThreadRouting(childThreadId, threadId);
+ }
+ return true;
+ };
+
+ const pendingSpawnLineageByTurn = new Map<string, Set<string>>();
+ const rememberPendingSpawnLineage = (turnId: string | null | undefined, childThreadIds: string[]): void => {
+ if (!turnId || childThreadIds.length === 0) return;
+ const pending = pendingSpawnLineageByTurn.get(turnId) ?? new Set<string>();
+ for (const childThreadId of childThreadIds) pending.add(childThreadId);
+ pendingSpawnLineageByTurn.set(turnId, pending);
+ };
+ const discardPendingSpawnLineage = (turnId: string | null | undefined): void => {
+ if (!turnId) return;
+ const pending = pendingSpawnLineageByTurn.get(turnId);
+ if (!pending) return;
+ pendingSpawnLineageByTurn.delete(turnId);
+ for (const childThreadId of pending) {
+ host.discardPendingDescendantLineage?.(childThreadId, threadId);
+ }
+ };
+ const discardPendingSpawnLineageIds = (childThreadIds: string[]): void => {
+ for (const childThreadId of childThreadIds) {
+ host.discardPendingDescendantLineage?.(childThreadId, threadId);
+ }
+ };
+
const handleDescendantNotification = (
childThreadId: string,
method: string,
params: unknown,
): void => {
+ const record = params && typeof params === 'object'
+ ? params as Record<string, unknown>
+ : null;
+ const turnId = typeof record?.turnId === 'string'
+ ? record.turnId
+ : record?.turn && typeof record.turn === 'object'
+ && typeof (record.turn as Record<string, unknown>).id === 'string'
+ ? (record.turn as Record<string, unknown>).id as string
+ : undefined;
+ const isItemNotification =
+ method === 'item/started' || method === 'item/updated' || method === 'item/completed';
+ const descendantTurnIsTerminal = turnId !== undefined
+ && terminalDescendantTurnIds.has(turnId);
+
+ if (method === 'turn/started') {
+ bindCapabilitySelectionToDescendantTurn(childThreadId, turnId);
+ } else if (isItemNotification && !descendantTurnIsTerminal) {
+ bindCapabilitySelectionToDescendantTurn(childThreadId, turnId);
+ noteActiveToolContext(record?.item, turnId);
+ }
+
+ // 嵌套子代理:孙线程的 spawn item 只出现在**子线程自己**的事件流里,主线程的
+ // itemStarted 永远看不到。0.145 又没有 thread/started 可等,这里就是孙线程
+ // 唯一的入卡(和 approval 路由)入口。
+ // turn/completed 可以先于后台收尾的 item/completed。迟到 item 不得重建工具
+ // provenance,但 completed spawn 仍是 0.145 的权威血缘来源,不能一起被终态闩挡掉。
+ if (isItemNotification && (!descendantTurnIsTerminal || method === 'item/completed')) {
+ const nested = readCodexSubagentSpawnRegistration(
+ record?.item,
+ );
+ if (nested) {
+ for (const grandChildThreadId of nested.childThreadIds) {
+ registerDescendantThreadRouting(grandChildThreadId, childThreadId);
+ const replayedNested = subagentLiveCards.noteDescendantThread(
+ grandChildThreadId,
+ childThreadId,
+ nested.model,
+ nested.failed === true,
+ );
+ if (replayedNested) emitSubagentCardUpdate(replayedNested);
+ }
+ }
+ }
const update = subagentLiveCards.handleDescendantNotification(childThreadId, method, params);
if (update) emitSubagentCardUpdate(update);
+
+ if (method === 'turn/completed') {
+ const status = record?.turn && typeof record.turn === 'object'
+ ? (record.turn as Record<string, unknown>).status
+ : undefined;
+ if (turnId && status !== 'inProgress') {
+ terminalDescendantTurnIds.add(turnId);
+ capabilitySelectionTextByTurnId.delete(turnId);
+ clearActiveToolContextsForTurn(turnId);
+ }
+ } else if (method === 'error' && turnId && record?.willRetry !== true) {
+ terminalDescendantTurnIds.add(turnId);
+ capabilitySelectionTextByTurnId.delete(turnId);
+ clearActiveToolContextsForTurn(turnId);
+ }
};
/**
@@ -3351,6 +3562,10 @@ export class CodexAgent extends BaseAgent {
* 就会把运行中的子代理提前标成完成,还会抹掉先到的 failed/stopped(review)。
*/
const noteSubagentSpawnItem = (item: unknown): (() => void) | null => {
+ if (!registerSubagentSpawnLineage(item)) return null;
+ // 先接 host 路由再进 tracker:registerDescendantLineage 会把子线程 TTL 缓冲里的
+ // 早到通知同步补投进 handleDescendantNotification(tracker 缓冲),随后
+ // noteSpawnItem 建卡时统一重放,首帧就带上真实用量。
const replayed = subagentLiveCards.noteSpawnItem(item);
if (!replayed) return null;
return () => emitSubagentCardUpdate(replayed);
@@ -3361,6 +3576,11 @@ export class CodexAgent extends BaseAgent {
resetUpstreamIdleForTurnEnd();
unregisterCodexMcpContext(threadId);
unregisterDescendantCodexMcpContexts();
+ activeToolContexts.clear();
+ capabilitySelectionTextByTurnId.clear();
+ capabilitySelectionTextByThreadId.clear();
+ descendantParentThreadByThreadId.clear();
+ terminalDescendantTurnIds.clear();
// 与 close() 同规:handle 被终止后子代理卡不会再有消费者。同样先收终态再清 ——
// 这条路径(thread cleanup failure / 强制 retire)恰恰是最容易留下永久转圈卡的。
for (const update of subagentLiveCards.drainRunningForShutdown()) emitSubagentCardUpdate(update);
@@ -5117,7 +5337,7 @@ export class CodexAgent extends BaseAgent {
params: CommandExecutionRequestApprovalParams,
): Promise<CommandExecutionRequestApprovalResponse> => {
// buffered/墓碑 turn 的审批请求不得上 UI (codex R12 P1) — 孤儿直接拒。
- const turnGate = gateServerRequestTurn(params.turnId);
+ const turnGate = gateServerRequestTurn(params.turnId, params.threadId);
if (turnGate === false) return { decision: 'decline' };
if (turnGate instanceof Promise && !(await turnGate)) return { decision: 'decline' };
// requestId: approvalId 优先 (zsh-exec-bridge 多 callback 场景); 否则用 itemId
@@ -5151,7 +5371,7 @@ export class CodexAgent extends BaseAgent {
params: FileChangeRequestApprovalParams,
): Promise<FileChangeRequestApprovalResponse> => {
// buffered/墓碑 turn 的审批请求不得上 UI (codex R12 P1) — 孤儿直接拒。
- const turnGate = gateServerRequestTurn(params.turnId);
+ const turnGate = gateServerRequestTurn(params.turnId, params.threadId);
if (turnGate === false) return { decision: 'decline' };
if (turnGate instanceof Promise && !(await turnGate)) return { decision: 'decline' };
const requestId = params.itemId;
@@ -5283,7 +5503,7 @@ export class CodexAgent extends BaseAgent {
params: McpServerElicitationRequestParams,
): Promise<McpServerElicitationRequestResponse> => {
// buffered/墓碑 turn 的 elicitation 不得上 UI / auto-approve (codex R12 P1)。
- const turnGate = gateServerRequestTurn(params.turnId);
+ const turnGate = gateServerRequestTurn(params.turnId, params.threadId);
if (turnGate === false) return { action: 'decline', content: null, _meta: null };
if (turnGate instanceof Promise && !(await turnGate)) {
return { action: 'decline', content: null, _meta: null };
@@ -5335,8 +5555,10 @@ export class CodexAgent extends BaseAgent {
!isCapabilityRouteInvocationAllowed(
capabilityRoute,
params.turnId
- ? capabilitySelectionTextByTurnId.get(params.turnId) ?? ''
- : '',
+ ? capabilitySelectionTextByTurnId.get(params.turnId)
+ ?? capabilitySelectionTextByThreadId.get(params.threadId)
+ ?? ''
+ : capabilitySelectionTextByThreadId.get(params.threadId) ?? '',
)
) {
log.warn('Codex MCP invocation blocked by host capability routing', {
@@ -5418,7 +5640,7 @@ export class CodexAgent extends BaseAgent {
): Promise<PermissionsRequestApprovalResponse> => {
// buffered/墓碑 turn 的审批请求不得上 UI (codex R12 P1) — 孤儿直接拒
// (空 permissions 即拒绝授权, 与非 accept 分支同款)。
- const turnGate = gateServerRequestTurn(params.turnId);
+ const turnGate = gateServerRequestTurn(params.turnId, params.threadId);
if (turnGate === false) return { permissions: {}, scope: 'turn' };
if (turnGate instanceof Promise && !(await turnGate)) return { permissions: {}, scope: 'turn' };
const requestId = params.itemId ?? params.turnId;
@@ -5723,7 +5945,7 @@ export class CodexAgent extends BaseAgent {
meta: { requestId: string | number },
): Promise<ToolRequestUserInputResponse> => {
// buffered/墓碑 turn 的输入请求不得上 UI (codex R12 P1) — 空 answers 即拒。
- const turnGate = gateServerRequestTurn(params.turnId);
+ const turnGate = gateServerRequestTurn(params.turnId, params.threadId);
if (turnGate === false) return { answers: {} };
if (turnGate instanceof Promise && !(await turnGate)) return { answers: {} };
const requestId = String(meta.requestId);
@@ -5770,7 +5992,7 @@ export class CodexAgent extends BaseAgent {
meta: { requestId: string | number },
): Promise<DynamicToolCallResponse> => {
// buffered/墓碑 turn 的 tool call 不得上 UI (codex R12 P1)。
- const turnGate = gateServerRequestTurn(params.turnId);
+ const turnGate = gateServerRequestTurn(params.turnId, params.threadId);
if (turnGate === false) {
return {
contentItems: [
@@ -6028,6 +6250,7 @@ export class CodexAgent extends BaseAgent {
});
const settleBufferedTurnReconcile = (turnId: string, valid: boolean): void => {
+ if (!valid) discardPendingSpawnLineage(turnId);
const waiters = bufferedReconcileWaiters.get(turnId);
if (!waiters) return;
bufferedReconcileWaiters.delete(turnId);
@@ -6039,11 +6262,14 @@ export class CodexAgent extends BaseAgent {
// settle — handler 永远悬挂, dispatchServerRequest 永不返回, server
// 侧请求卡死。所有不走路径对账的退出点都必须调用。
const abandonBufferedTurns = (reason: string): void => {
- if (bufferedOrphanTurnIds.size === 0) return;
+ if (bufferedOrphanTurnIds.size === 0 && pendingSpawnLineageByTurn.size === 0) return;
log.debug('abandoning buffered turns', { reason, turnIds: [...bufferedOrphanTurnIds] });
for (const bufferedId of bufferedOrphanTurnIds) {
settleBufferedTurnReconcile(bufferedId, false);
}
+ for (const turnId of pendingSpawnLineageByTurn.keys()) {
+ discardPendingSpawnLineage(turnId);
+ }
bufferedOrphanTurnIds.clear();
bufferedTurnEventQueues.clear();
};
@@ -6054,7 +6280,16 @@ export class CodexAgent extends BaseAgent {
// 同步快速路径不引入 microtask 延迟 — handler 第一行的 broker.track 与
// 紧随其后的 serverRequest/resolved 存在竞态, 哪怕一跳 await 也会让
// resolved 抢在 track 之前到达 (测试回归实证)。
- const gateServerRequestTurn = (turnId: string | null | undefined): boolean | Promise<boolean> => {
+ const gateServerRequestTurn = (
+ turnId: string | null | undefined,
+ requestThreadId: string | null | undefined,
+ ): boolean | Promise<boolean> => {
+ // AppServerHost only forwards descendant requests after it has verified that
+ // requestThreadId belongs to this root subscription. Child turn ids live in a
+ // different namespace/state machine, so applying root orphan/tombstone guards
+ // here would reject valid child interactions after an unrelated root start
+ // failure (and may interrupt the root thread with the child turn id).
+ if (requestThreadId && requestThreadId !== threadId) return true;
if (!turnId) return true;
if (terminalErroredTurnIds.has(turnId) || completedTurnIds.has(turnId)) return false;
// idle 孤儿 (greptile R16 P1): 无 RPC 在飞时未知 id 的请求只可能来自
@@ -6485,6 +6720,9 @@ export class CodexAgent extends BaseAgent {
const completedCapabilitySelectionText =
capabilitySelectionTextByTurnId.get(turn.id) ?? '';
capabilitySelectionTextByTurnId.delete(turn.id);
+ if (currentTurnId === turn.id || currentTurnId === null) {
+ capabilitySelectionTextByThreadId.delete(threadId);
+ }
const suppressTerminalUi = terminalErroredTurnIds.has(turn.id);
deferredTerminalTurnCompletions.delete(turn.id);
if (currentTurnId === turn.id || currentTurnId === null) {
@@ -7366,6 +7604,10 @@ export class CodexAgent extends BaseAgent {
dismissAllPending('app_server_force_retired', 'deny');
dismissAllPendingUserInput('transport_error');
activeToolContexts.clear();
+ capabilitySelectionTextByTurnId.clear();
+ capabilitySelectionTextByThreadId.clear();
+ descendantParentThreadByThreadId.clear();
+ terminalDescendantTurnIds.clear();
stopActiveRolloutPlanFallback();
resetUpstreamIdleForTurnEnd();
if (currentTurnId) terminalErroredTurnIds.add(currentTurnId);
@@ -7403,18 +7645,18 @@ export class CodexAgent extends BaseAgent {
}
},
descendantThreadStarted: (params) => {
+ // 0.145 不会为 spawn 出的子线程发 thread/started(血缘主路径已改走 spawn item,
+ // 见 registerDescendantThreadRouting);保留本 handler 兼容会发的新版 codex,
+ // 它还带 thread.model —— 实际模型观测值优先于 spawn 参数与配置兜底。
const childThreadId = params.thread.id;
const parentThreadId = params.thread.parentThreadId;
if (!parentThreadId || childThreadId === parentThreadId) return;
- registerDescendantCodexMcpContext(childThreadId);
- this.deps.registerCodexChildThreadForParent?.({
- parentThreadId,
- childThreadId,
- });
- // 嵌套子代理:孙线程的 spawn item 只出现在**子线程自己**的事件流里,主线程的
- // itemStarted 看不到,所以只能靠血缘把它并进父线程所属的那张卡 —— 否则孙线程的
- // 工具调用与 token 全部进 pending 且再也没有登记路径可以重放(greptile P1)。
- const replayed = subagentLiveCards.noteDescendantThread(childThreadId, parentThreadId);
+ const childModel =
+ typeof params.thread.model === 'string' && params.thread.model.length > 0
+ ? params.thread.model
+ : undefined;
+ registerDescendantThreadRouting(childThreadId, parentThreadId);
+ const replayed = subagentLiveCards.noteDescendantThread(childThreadId, parentThreadId, childModel);
if (replayed) emitSubagentCardUpdate(replayed);
},
descendantNotification: handleDescendantNotification,
@@ -7486,7 +7728,7 @@ export class CodexAgent extends BaseAgent {
!startedOwner[1].quarantined &&
!startedOwner[1].terminalSettled
) {
- capabilitySelectionTextByTurnId.set(
+ bindRootCapabilitySelection(
params.turn.id,
startedOwner[1].capabilitySelectionText,
);
@@ -7627,11 +7869,24 @@ export class CodexAgent extends BaseAgent {
handleTurnCompleted(params);
},
itemStarted: (params) => {
+ // 血缘不能跟着 turn 对账队列一起迟到:AppServerHost 只为未知 child 缓冲 5s。
+ // 卡片/翻译仍在队列内,这里只保留 provisional claim;父 turn 被接受后
+ // 重放 item 才 commit root route,孤儿则 discard。
+ const reservedChildThreadIds = reserveSubagentSpawnLineage(params.item);
if (enqueueIfBufferedTurn(params.turnId, () => handlers.itemStarted?.(params), {
modelWork: itemRepresentsModelWork(params.item),
- })) return;
- if (shouldIgnoreStaleTurnEvent(params.turnId)) return;
- if (interceptProposedPlanItem(params.item)) return;
+ })) {
+ rememberPendingSpawnLineage(params.turnId, reservedChildThreadIds);
+ return;
+ }
+ if (shouldIgnoreStaleTurnEvent(params.turnId)) {
+ discardPendingSpawnLineageIds(reservedChildThreadIds);
+ return;
+ }
+ if (interceptProposedPlanItem(params.item)) {
+ discardPendingSpawnLineageIds(reservedChildThreadIds);
+ return;
+ }
// 模型已开始产出 → 本 turn 不再适合被过载重投整体重放。SDK echo 类 item
// (userMessage 等)不算产出, 见 itemRepresentsModelWork。
if (itemRepresentsModelWork(params.item)) producedOutputTurnIds.add(params.turnId);
@@ -7649,11 +7904,21 @@ export class CodexAgent extends BaseAgent {
emitReplayedSubagentUpdate?.();
},
itemUpdated: (params) => {
+ const reservedChildThreadIds = reserveSubagentSpawnLineage(params.item);
if (enqueueIfBufferedTurn(params.turnId, () => handlers.itemUpdated?.(params), {
modelWork: itemRepresentsModelWork(params.item),
- })) return;
- if (shouldIgnoreStaleTurnEvent(params.turnId)) return;
- if (interceptProposedPlanItem(params.item)) return;
+ })) {
+ rememberPendingSpawnLineage(params.turnId, reservedChildThreadIds);
+ return;
+ }
+ if (shouldIgnoreStaleTurnEvent(params.turnId)) {
+ discardPendingSpawnLineageIds(reservedChildThreadIds);
+ return;
+ }
+ if (interceptProposedPlanItem(params.item)) {
+ discardPendingSpawnLineageIds(reservedChildThreadIds);
+ return;
+ }
if (itemRepresentsModelWork(params.item)) producedOutputTurnIds.add(params.turnId);
noteActiveToolContext(params.item, params.turnId);
// updated 也要登记映射,顺序与 started / completed 一致(先登记 → 翻译 → 后发重放帧)。
@@ -7670,11 +7935,21 @@ export class CodexAgent extends BaseAgent {
emitReplayedSubagentUpdateOnUpdated?.();
},
itemCompleted: (params) => {
+ const reservedChildThreadIds = reserveSubagentSpawnLineage(params.item);
if (enqueueIfBufferedTurn(params.turnId, () => handlers.itemCompleted?.(params), {
modelWork: itemRepresentsModelWork(params.item),
- })) return;
- if (shouldIgnoreStaleTurnEvent(params.turnId)) return;
- if (interceptProposedPlanItem(params.item)) return;
+ })) {
+ rememberPendingSpawnLineage(params.turnId, reservedChildThreadIds);
+ return;
+ }
+ if (shouldIgnoreStaleTurnEvent(params.turnId)) {
+ discardPendingSpawnLineageIds(reservedChildThreadIds);
+ return;
+ }
+ if (interceptProposedPlanItem(params.item)) {
+ discardPendingSpawnLineageIds(reservedChildThreadIds);
+ return;
+ }
if (itemRepresentsModelWork(params.item)) producedOutputTurnIds.add(params.turnId);
noteActiveToolContext(params.item, params.turnId);
noteToolItemLifecycle(params.item, 'completed');
@@ -7795,6 +8070,10 @@ export class CodexAgent extends BaseAgent {
subagentLiveCards.clear();
dismissAllPendingUserInput('transport_error');
activeToolContexts.clear();
+ capabilitySelectionTextByTurnId.clear();
+ capabilitySelectionTextByThreadId.clear();
+ descendantParentThreadByThreadId.clear();
+ terminalDescendantTurnIds.clear();
submittedUserInputByTurn.clear();
clearAllPendingUserInputInteractions();
}
@@ -8076,6 +8355,11 @@ export class CodexAgent extends BaseAgent {
resetUpstreamIdleForTurnEnd();
unregisterCodexMcpContext(threadId);
unregisterDescendantCodexMcpContexts();
+ activeToolContexts.clear();
+ capabilitySelectionTextByTurnId.clear();
+ capabilitySelectionTextByThreadId.clear();
+ descendantParentThreadByThreadId.clear();
+ terminalDescendantTurnIds.clear();
// 会话收口后子代理卡不再有消费者。清状态**之前**必须先把仍在跑的卡收成终态:
// 之后后代通知永远不会再到,只清内部状态会让渲染端一直留着最后一帧 running,卡片
// 永久转圈(review)。
@@ -8404,7 +8688,7 @@ export class CodexAgent extends BaseAgent {
// The app-server has now acknowledged which turn owns this
// input. Bind explicit source selection before buffered tool
// requests are released, and never on a pre-accept failure.
- capabilitySelectionTextByTurnId.set(
+ bindRootCapabilitySelection(
resp.turn.id,
capabilitySelectionText,
);
@@ -8437,6 +8721,9 @@ export class CodexAgent extends BaseAgent {
});
for (const replay of replayQueue) replay();
}
+ // Any claim not consumed by a replayed spawn item is stale residue from a
+ // malformed/duplicate queue entry; clear it without touching committed routes.
+ discardPendingSpawnLineage(resp.turn.id);
} else {
// 未激活 (墓碑): 队列丢弃, 挂起请求按拒绝释放 — 不得穿透。
bufferedTurnEventQueues.delete(resp.turn.id);
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 05325948d2..4fb641d794 100644
--- a/packages/maker-core/src/agents/codex/subagent-live-cards.ts
+++ b/packages/maker-core/src/agents/codex/subagent-live-cards.ts
@@ -39,6 +39,8 @@ export interface SubagentLiveCardUpdate {
taskId: string;
status: SubagentLiveCardStatus;
agentPath?: string;
+ /** Observed child-thread model, or Cindy's explicit display fallback. `null` clears a stale badge. */
+ model?: string | null;
/** 本卡全部子线程的累计 token 之和;未知为 0。 */
totalTokens: number;
/** 本卡全部子线程内的工具类 item 数;未知为 0。 */
@@ -71,7 +73,12 @@ export interface SubagentLiveCardTracker {
* 返回聚合快照 = 有早到通知被重放出状态,**或**新线程并入改变了聚合状态(例如已显示完成的
* 卡因为孙线程仍在跑而必须回到 running);否则 null。
*/
- noteDescendantThread(childThreadId: string, parentThreadId: string): SubagentLiveCardUpdate | null;
+ noteDescendantThread(
+ childThreadId: string,
+ parentThreadId: string,
+ model?: string,
+ spawnFailed?: boolean,
+ ): SubagentLiveCardUpdate | null;
/**
* 消费一条子线程通知。返回聚合快照表示卡片需要刷新;返回 null = 与子代理卡无关
* (不关心的 method、无效载荷),或该子线程尚未登记(已缓冲,等 spawn 到达后重放)。
@@ -138,6 +145,8 @@ const MAX_PENDING_PER_THREAD = 64;
/** 未归属血缘边的缓冲上限(父线程数 × 每父线程子线程数),同样防无界堆积。 */
const MAX_PENDING_LINEAGE_PARENTS = 32;
const MAX_PENDING_LINEAGE_CHILDREN = 32;
+/** Observed models can arrive before lineage; keep this side buffer bounded too. */
+const MAX_PENDING_THREAD_MODELS = MAX_PENDING_LINEAGE_PARENTS * MAX_PENDING_LINEAGE_CHILDREN;
/**
* 单卡工具 item 去重登记的条数上限。去重登记必须活到卡片淘汰(turn/completed 可能早于
* 后台 item/completed,提前清会让迟到的 completed 重复计数),所以只能按条数封顶。
@@ -148,6 +157,10 @@ interface ThreadState {
status: SubagentLiveCardStatus;
/** 该子线程最新的**累计** token(tokenUsage.total 是快照,按线程覆盖而非相加)。 */
totalTokens: number;
+ /** Model observed from thread metadata or a spawn item. */
+ model?: string;
+ /** A failed nested spawn remains terminal despite late lifecycle events. */
+ spawnFailed: boolean;
}
interface TrackedCard {
@@ -174,9 +187,13 @@ interface PendingNotification {
export function createSubagentLiveCardTracker(opts: {
now?: () => number;
maxTrackedCards?: number;
+ subagentModelFallback?: string;
} = {}): SubagentLiveCardTracker {
const now = opts.now ?? (() => Date.now());
const maxTrackedCards = opts.maxTrackedCards ?? DEFAULT_MAX_TRACKED_CARDS;
+ const subagentModelFallback = typeof opts.subagentModelFallback === 'string' && opts.subagentModelFallback.trim()
+ ? opts.subagentModelFallback.trim()
+ : undefined;
const cards = new Map<string, TrackedCard>();
const taskIdByThread = new Map<string, string>();
const pending = new Map<string, PendingNotification[]>();
@@ -189,6 +206,10 @@ export function createSubagentLiveCardTracker(opts: {
* 显示完成(review)。这里先记下,父线程一归属就**递归**补绑整条血缘链。
*/
const pendingLineage = new Map<string, Set<string>>();
+ /** Model observed on thread/started before its parent spawn is registered. */
+ const pendingThreadModels = new Map<string, string>();
+ /** Failed nested spawns can be observed before their parent card is attached. */
+ const pendingFailedThreads = new Set<string>();
/**
* 子线程**第一次被看见**的时刻(第一条缓冲通知或第一条未归属血缘边)。
*
@@ -232,10 +253,32 @@ export function createSubagentLiveCardTracker(opts: {
return 'completed';
};
+ const aggregateModel = (card: TrackedCard): string | null | undefined => {
+ const observedModels = new Set<string>();
+ let threadsWithModel = 0;
+ for (const thread of card.threads.values()) {
+ if (thread.model) {
+ threadsWithModel += 1;
+ observedModels.add(thread.model);
+ }
+ }
+ // V1 can aggregate multiple receiver threads into one card. A singular
+ // model label is truthful only when **every** thread has reported one and
+ // all values agree — partial observation must not be projected onto the
+ // whole card (codex review). With zero reports, use Cindy's explicit
+ // configured fallback.
+ return threadsWithModel === 0
+ ? subagentModelFallback
+ : threadsWithModel === card.threads.size && observedModels.size === 1
+ ? observedModels.values().next().value
+ : null;
+ };
+
const snapshot = (card: TrackedCard): SubagentLiveCardUpdate => {
let totalTokens = 0;
for (const thread of card.threads.values()) totalTokens += thread.totalTokens;
const status = aggregateStatus(card);
+ const model = aggregateModel(card);
// 这里**不能**因为收口就清 countedItemIds:app-server 允许 turn/completed 先发、后台
// 收尾的 item/completed 随后才到(codex/index.ts 的终态墓碑注释写明了这个顺序)。清掉
// 之后那条迟到的 completed 会被当成一个新工具再加一次,卡片最终工具数虚高(review)。
@@ -244,6 +287,7 @@ export function createSubagentLiveCardTracker(opts: {
taskId: card.taskId,
status,
...(card.agentPath ? { agentPath: card.agentPath } : {}),
+ ...(model !== undefined ? { model } : {}),
totalTokens,
toolUses: card.toolUses,
durationMs: Math.max(0, now() - card.startedAt),
@@ -353,9 +397,11 @@ export function createSubagentLiveCardTracker(opts: {
return true;
}
case 'turn/started':
+ if (thread.spawnFailed) return false;
thread.status = 'running';
return true;
case 'turn/completed': {
+ if (thread.spawnFailed) return false;
const turnStatus = (params as { turn?: { status?: unknown } } | null)?.turn?.status;
thread.status = turnStatus === 'failed'
? 'failed'
@@ -378,29 +424,50 @@ export function createSubagentLiveCardTracker(opts: {
* itemStarted 钩子永远看不到,所以除了这条路径没有别的机会把孙线程并进卡。
*
* `visited` 防环:血缘理论上是树,但通知来自外部进程,不能假定它一定是树。
- * 返回是否有内容被重放(调用方据此判断要不要发帧)。
+ * 返回是否有可见快照变化:早到通知被重放,或实际模型在本次绑定时首次落到线程上。
*/
- const attachThread = (card: TrackedCard, childThreadId: string, visited: Set<string>): boolean => {
+ const attachThread = (
+ card: TrackedCard,
+ childThreadId: string,
+ visited: Set<string>,
+ spawnModel?: string,
+ spawnFailed = false,
+ ): boolean => {
if (visited.has(childThreadId)) return false;
visited.add(childThreadId);
if (taskIdByThread.get(childThreadId) !== card.taskId) unbindThread(childThreadId);
+ const failedBeforeAttachment = pendingFailedThreads.delete(childThreadId);
+ const latchSpawnFailure = spawnFailed || failedBeforeAttachment;
+ let changed = false;
if (!card.threads.has(childThreadId)) {
+ const observedModel = pendingThreadModels.get(childThreadId);
+ pendingThreadModels.delete(childThreadId);
+ const initialModel = observedModel ?? spawnModel;
+ changed = Boolean(initialModel);
// 已上终态闩的卡,新并入的线程直接算失败,别让它把卡拉回 running。
card.threads.set(childThreadId, {
- status: card.spawnFailed ? 'failed' : 'running',
+ status: card.spawnFailed || latchSpawnFailure ? 'failed' : 'running',
totalTokens: 0,
+ ...(initialModel ? { model: initialModel } : {}),
+ spawnFailed: latchSpawnFailure,
});
+ } else if (spawnModel && !card.threads.get(childThreadId)?.model) {
+ card.threads.get(childThreadId)!.model = spawnModel;
+ changed = true;
}
taskIdByThread.set(childThreadId, card.taskId);
const thread = card.threads.get(childThreadId)!;
+ if (latchSpawnFailure) {
+ thread.spawnFailed = true;
+ thread.status = 'failed';
+ }
- let replayed = false;
const queued = pending.get(childThreadId);
if (queued) {
pending.delete(childThreadId);
for (const entry of queued) {
- if (applyNotification(card, thread, entry.method, entry.params)) replayed = true;
+ if (applyNotification(card, thread, entry.method, entry.params)) changed = true;
}
}
@@ -408,10 +475,10 @@ export function createSubagentLiveCardTracker(opts: {
if (descendants) {
pendingLineage.delete(childThreadId);
for (const grandChildId of descendants) {
- if (attachThread(card, grandChildId, visited)) replayed = true;
+ if (attachThread(card, grandChildId, visited)) changed = true;
}
}
- return replayed;
+ return changed;
};
return {
@@ -444,7 +511,7 @@ export function createSubagentLiveCardTracker(opts: {
const visited = new Set<string>();
let replayedOnFailure = false;
for (const childThreadId of registration.childThreadIds) {
- if (attachThread(card, childThreadId, visited)) replayedOnFailure = true;
+ if (attachThread(card, childThreadId, visited, registration.model)) replayedOnFailure = true;
const thread = card.threads.get(childThreadId);
if (thread) thread.status = 'failed';
}
@@ -452,13 +519,15 @@ export function createSubagentLiveCardTracker(opts: {
// 重放出来;若此后再无通知,无条件返回 null 就意味着这些用量永远不显示 —— 而 translator
// 的 failed 帧本身不带 usage(review)。有了 spawnFailed 闩,snapshot() 恒为 failed,
// 补发这一帧不会重现"把失败盖回运行中"的老问题。
- return replayedOnFailure ? snapshot(card) : null;
+ return replayedOnFailure || registration.model || subagentModelFallback
+ ? snapshot(card)
+ : null;
}
const visited = new Set<string>();
let replayed = false;
for (const childThreadId of registration.childThreadIds) {
- if (attachThread(card, childThreadId, visited)) replayed = true;
+ if (attachThread(card, childThreadId, visited, registration.model)) replayed = true;
}
// 已登记过的 spawn(同一 collabAgentToolCall 的 started/completed 两个 phase 都会到
@@ -468,11 +537,53 @@ export function createSubagentLiveCardTracker(opts: {
// 跑的子线程会被提前标成完成,先到的 failed/stopped 也会被抹掉。
// (attachThread 幂等:已在卡上的线程不会被重置计数。)
if (existing) return snapshot(card);
- return replayed ? snapshot(card) : null;
+ return replayed || registration.model || subagentModelFallback
+ ? snapshot(card)
+ : null;
},
- noteDescendantThread(childThreadId: string, parentThreadId: string): SubagentLiveCardUpdate | null {
+ noteDescendantThread(
+ childThreadId: string,
+ parentThreadId: string,
+ model?: string,
+ spawnFailed = false,
+ ): SubagentLiveCardUpdate | null {
if (!childThreadId || !parentThreadId || childThreadId === parentThreadId) return null;
+ const directTaskId = taskIdByThread.get(childThreadId);
+ if (directTaskId !== undefined) {
+ pendingThreadModels.delete(childThreadId);
+ pendingFailedThreads.delete(childThreadId);
+ const directCard = cards.get(directTaskId);
+ const directThread = directCard?.threads.get(childThreadId);
+ if (directCard && directThread) {
+ let changed = false;
+ if (model && directThread.model !== model) {
+ directThread.model = model;
+ changed = true;
+ }
+ if (spawnFailed && !directThread.spawnFailed) {
+ directThread.spawnFailed = true;
+ directThread.status = 'failed';
+ changed = true;
+ }
+ if (changed) return snapshot(directCard);
+ }
+ return null;
+ }
+ if (model) {
+ 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, model);
+ }
+ if (spawnFailed) {
+ if (!pendingFailedThreads.has(childThreadId) && pendingFailedThreads.size >= MAX_PENDING_THREAD_MODELS) {
+ const oldest = pendingFailedThreads.values().next();
+ if (!oldest.done) pendingFailedThreads.delete(oldest.value);
+ }
+ pendingFailedThreads.add(childThreadId);
+ }
const taskId = taskIdByThread.get(parentThreadId);
if (taskId === undefined) {
// 父线程还没归属:**不能丢**。它可能只是 spawn item 尚未到达(乱序),而本次血缘正是
@@ -483,13 +594,16 @@ export function createSubagentLiveCardTracker(opts: {
const card = cards.get(taskId);
if (!card) return null;
// 已并入同一张卡:幂等,不重置计数。
- if (taskIdByThread.get(childThreadId) === taskId && card.threads.has(childThreadId)) return null;
-
// 新线程并入会改变聚合状态(比如把已显示完成的卡拉回 running —— 孙线程还在跑,卡片就
// 不该说完成),所以发帧条件不只看有没有重放内容,还看聚合状态是否因此改变。
- const before = aggregateStatus(card);
- const replayed = attachThread(card, childThreadId, new Set<string>());
- return replayed || aggregateStatus(card) !== before ? snapshot(card) : null;
+ const beforeStatus = aggregateStatus(card);
+ const beforeModel = aggregateModel(card);
+ const replayed = attachThread(card, childThreadId, new Set<string>(), model, spawnFailed);
+ return replayed
+ || aggregateStatus(card) !== beforeStatus
+ || aggregateModel(card) !== beforeModel
+ ? snapshot(card)
+ : null;
},
handleDescendantNotification(
@@ -523,7 +637,7 @@ export function createSubagentLiveCardTracker(opts: {
if (card.threads.size === 0) {
// 一个线程都还没登记上的卡(spawn 刚认出、子线程尚未 started):补一个占位线程,
// 否则 aggregateStatus 对空集合返回 running,这张卡还是会留在转圈状态。
- card.threads.set('__shutdown__', { status: 'stopped', totalTokens: 0 });
+ card.threads.set('__shutdown__', { status: 'stopped', totalTokens: 0, spawnFailed: false });
}
out.push(snapshot(card));
}
@@ -535,6 +649,8 @@ export function createSubagentLiveCardTracker(opts: {
taskIdByThread.clear();
pending.clear();
pendingLineage.clear();
+ pendingThreadModels.clear();
+ pendingFailedThreads.clear();
firstSeenAt.clear();
},
diff --git a/packages/maker-core/src/agents/codex/translator.test.ts b/packages/maker-core/src/agents/codex/translator.test.ts
index 8f2a1bfd57..4f985af58f 100644
--- a/packages/maker-core/src/agents/codex/translator.test.ts
+++ b/packages/maker-core/src/agents/codex/translator.test.ts
@@ -1153,7 +1153,7 @@ describe('translateItemNotification collabAgentToolCall', () => {
});
describe('translateItemNotification subAgentActivity', () => {
- function activityParams(kind: string, id = 'spawn-1') {
+ function activityParams(kind: string, id = 'spawn-1', model?: string) {
return {
threadId: 'thread-1',
turnId: 'turn-1',
@@ -1163,6 +1163,7 @@ describe('translateItemNotification subAgentActivity', () => {
kind,
agentThreadId: 'thread-2',
agentPath: '/root/survey_startup',
+ ...(model ? { model } : {}),
},
};
}
@@ -1172,7 +1173,7 @@ describe('translateItemNotification subAgentActivity', () => {
const q = createAsyncQueue<AgentEvent>();
const ctx = makeCtx(rt);
- translateItemNotification('started', activityParams('started'), q, ctx);
+ translateItemNotification('started', activityParams('started', 'spawn-1', 'gpt-5.6-terra'), q, ctx);
const events = await collect(q);
expect(events.map((event) => event.type)).toEqual([
@@ -1184,7 +1185,7 @@ describe('translateItemNotification subAgentActivity', () => {
expect(events[0].data).toMatchObject({
toolUseId: 'spawn-1',
toolName: 'collab:spawn',
- input: { name: '/root/survey_startup', agentThreadId: 'thread-2' },
+ input: { name: '/root/survey_startup', agentThreadId: 'thread-2', model: 'gpt-5.6-terra' },
});
// fullText 是纯数据(agentPath 原文),本地化句子由 renderer 组装,不持久化英文。
expect(events[1].data).toMatchObject({
@@ -1200,6 +1201,7 @@ describe('translateItemNotification subAgentActivity', () => {
parentToolUseId: 'spawn-1',
status: 'running',
title: '/root/survey_startup',
+ model: 'gpt-5.6-terra',
});
});
diff --git a/packages/maker-core/src/agents/codex/translator.ts b/packages/maker-core/src/agents/codex/translator.ts
index b52698951f..9ebc32b548 100644
--- a/packages/maker-core/src/agents/codex/translator.ts
+++ b/packages/maker-core/src/agents/codex/translator.ts
@@ -1584,6 +1584,8 @@ interface SubAgentActivityItem {
kind: string;
agentThreadId?: string;
agentPath?: string;
+ /** Newer Codex builds may include the selected child model on the activity. */
+ model?: string;
}
/**
@@ -1598,6 +1600,7 @@ export function readCodexSubagentSpawnRegistration(item: unknown): {
taskId: string;
childThreadIds: string[];
agentPath?: string;
+ model?: string;
/**
* spawn **本身**收口为失败(V1 `collabAgentToolCall.status === 'failed'`)。
* translator 此时已推过 failed 帧,聚合器据此不得再用快照(仍是 running)盖回去。
@@ -1618,6 +1621,7 @@ export function readCodexSubagentSpawnRegistration(item: unknown): {
taskId,
childThreadIds: [childThreadId],
...(typeof record.agentPath === 'string' && record.agentPath ? { agentPath: record.agentPath } : {}),
+ ...(typeof record.model === 'string' && record.model ? { model: record.model } : {}),
};
}
@@ -1632,6 +1636,7 @@ export function readCodexSubagentSpawnRegistration(item: unknown): {
return {
taskId,
childThreadIds: receivers,
+ ...(typeof record.model === 'string' && record.model ? { model: record.model } : {}),
...(record.status === 'failed' ? { failed: true } : {}),
};
}
@@ -1655,9 +1660,11 @@ function handleSubAgentActivity(
// started phase 登记等 completed 清理;只收到 completed(防御)时无后续 phase,不登记。
if (phase === 'started') ctx.rt.emittedToolUse.add(item.id);
const agentPath = typeof item.agentPath === 'string' ? item.agentPath : undefined;
+ const model = typeof item.model === 'string' && item.model ? item.model : undefined;
const input: Record<string, unknown> = {};
if (agentPath) input.name = agentPath;
if (item.agentThreadId) input.agentThreadId = item.agentThreadId;
+ if (model) input.model = model;
queue.push({
type: 'tool_use',
data: { toolUseId: item.id, toolName: 'collab:spawn', input },
@@ -1686,6 +1693,7 @@ function handleSubAgentActivity(
parentToolUseId: item.id,
status: 'running',
...(agentPath ? { title: agentPath } : {}),
+ ...(model ? { model } : {}),
},
source: 'codex',
});
diff --git a/packages/maker-core/src/types/events.ts b/packages/maker-core/src/types/events.ts
index 4a368f67ad..94182f19c8 100644
--- a/packages/maker-core/src/types/events.ts
+++ b/packages/maker-core/src/types/events.ts
@@ -74,7 +74,11 @@ export interface AgentTaskUpdateEventData {
lastToolName?: string;
taskType?: string;
workflowName?: string;
- model?: string;
+ /**
+ * 实际模型名;`null` 是子代理多 receiver 观测冲突/显式清除的合法值,
+ * 用于让下游清掉旧模型徽标,而不是回退到未经证明的旧值。
+ */
+ model?: string | null;
reasoningEffort?: string;
receiverThreadIds?: string[];
/**
diff --git a/packages/maker-shared/src/__tests__/agentTask.test.ts b/packages/maker-shared/src/__tests__/agentTask.test.ts
index 253b0edf28..5ebcc9ee14 100644
--- a/packages/maker-shared/src/__tests__/agentTask.test.ts
+++ b/packages/maker-shared/src/__tests__/agentTask.test.ts
@@ -84,6 +84,22 @@ describe('mergeAgentTaskUpdate', () => {
const next: AgentTaskUpdate = { provider: 'codex', taskId: 't1', status: 'running' };
expect(mergeAgentTaskUpdate(undefined, next)).toBe(next);
});
+
+ it('clears a stale model when a live update explicitly sends null', () => {
+ const first = applyAgentTaskUpdateEvent(
+ undefined,
+ { provider: 'codex', taskId: 't1', status: 'running', model: 'codex/gpt-5.5' },
+ 'codex',
+ NOW,
+ )!;
+ const cleared = applyAgentTaskUpdateEvent(
+ first,
+ { provider: 'codex', taskId: 't1', status: 'running', model: null },
+ 'codex',
+ '2026-06-24T00:00:01.000Z',
+ )!;
+ expect(cleared.get('t1')?.model).toBeNull();
+ });
});
describe('applyAgentTaskUpdateEvent', () => {
diff --git a/packages/maker-shared/src/agentTask.ts b/packages/maker-shared/src/agentTask.ts
index 2da9e4ebd3..22c76eacad 100644
--- a/packages/maker-shared/src/agentTask.ts
+++ b/packages/maker-shared/src/agentTask.ts
@@ -140,7 +140,8 @@ export interface AgentTaskUpdate {
lastToolName?: string;
taskType?: string;
workflowName?: string;
- model?: string;
+ /** `null` is an explicit live-update instruction to clear a stale model badge. */
+ model?: string | null;
reasoningEffort?: string;
receiverThreadIds?: string[];
/**
@@ -216,7 +217,11 @@ export function normalizeAgentTaskUpdate(
...(typeof raw.lastToolName === 'string' && raw.lastToolName ? { lastToolName: raw.lastToolName } : {}),
...(typeof raw.taskType === 'string' && raw.taskType ? { taskType: raw.taskType } : {}),
...(typeof raw.workflowName === 'string' && raw.workflowName ? { workflowName: raw.workflowName } : {}),
- ...(typeof raw.model === 'string' && raw.model ? { model: raw.model } : {}),
+ ...(raw.model === null
+ ? { model: null }
+ : typeof raw.model === 'string' && raw.model
+ ? { model: raw.model }
+ : {}),
...(typeof raw.reasoningEffort === 'string' && raw.reasoningEffort ? { reasoningEffort: raw.reasoningEffort } : {}),
...(Array.isArray(raw.receiverThreadIds)
? { receiverThreadIds: raw.receiverThreadIds.filter((id): id is string => typeof id === 'string') }
@@ -242,6 +247,7 @@ export function mergeAgentTaskUpdate(prev: AgentTaskUpdate | undefined, next: Ag
// CLI 节流帧不带 workflowProgress(undefined = 沿用旧树),必须保留上一帧。
workflowProgress: next.workflowProgress ?? prev.workflowProgress,
createdAt: prev.createdAt ?? next.createdAt,
+ model: next.model === null ? null : next.model ?? prev.model,
updatedAt: next.updatedAt ?? prev.updatedAt,
};
}