Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(web): 子智能体落在派发它的那个 run_subagent 调用上

lmlihengf91cbfdad983
diff --git a/changelog/unreleased/2026-10-28-subagent-card-binding.md b/changelog/unreleased/2026-10-28-subagent-card-binding.md
new file mode 100644
index 00000000..78d180c6
--- /dev/null
+++ b/changelog/unreleased/2026-10-28-subagent-card-binding.md
@@ -0,0 +1,43 @@
+# A subagent lands on the `run_subagent` call that spawned it
+
+- **Date:** 2026-10-28
+- **Type:** fix
+- **Scope:** `web`
+- **Breaking:** no
+
+[中文](2026-10-28-subagent-card-binding.zh.md)
+
+Ported from PenguinHarness `3fa746b2` (`#1107`).
+
+A child session used to be placed on "the latest allowed `run_subagent` card that has no child yet",
+which is only right while one call runs at a time. Several calls at once could give a child another
+call's card: the card showed the wrong description, took the wrong thinking level as its fallback,
+and the transcript chip next to a card named the other conversation.
+
+The child's first model message is the opening prompt its spawning call handed it, verbatim (live
+and in a spliced Trace alike), so it now settles the binding: the child moves onto the card whose
+prompt that is, with the `agent_id`, `model_id` and `provider` the child's `session_meta` records
+— inherited parent values included, so an inherited self-spawn cannot capture an explicitly chosen
+reviewer or another model just because the prompts match. When missing metadata leaves different
+selectors ambiguous, or the child was bound standalone, the positional binding stands; a denied
+call never takes a child.
+
+No message protocol, wire record or stored data changes: the reducer only reads the child's
+existing `session_meta` and opening user-text records.
+
+## Details
+
+- `packages/web/src/lib/omni/stream-model.ts`: `StreamModel.unconfirmedSubagents` marks children
+ bound by position before their opening prompt arrived; the first model message routed into that
+ child moves it with `moveToSpawningCard`, which picks the card through `spawningCard` (prompt +
+ resolved identity, earliest still-running or else latest finished among identical calls) and
+ swaps with an unconfirmed child already sitting there.
+- `packages/web/test/agent-topology.test.ts`: four cases — mixed inherited/explicit agent, model
+ and provider with the explicit child arriving first, plus an ambiguous match without parent
+ metadata — alongside the existing parallel-launch, background-launch, denied-call and
+ history-replay scenarios.
+
+## Compatibility
+
+- No dependency, API, wire-protocol or stored-data change. A conversation with one call at a time
+ binds exactly as before.
diff --git a/changelog/unreleased/2026-10-28-subagent-card-binding.zh.md b/changelog/unreleased/2026-10-28-subagent-card-binding.zh.md
new file mode 100644
index 00000000..0d405c46
--- /dev/null
+++ b/changelog/unreleased/2026-10-28-subagent-card-binding.zh.md
@@ -0,0 +1,36 @@
+# 子智能体落在派发它的那个 `run_subagent` 调用上
+
+- **Date:** 2026-10-28
+- **Type:** fix
+- **Scope:** `web`
+- **Breaking:** no
+
+[English](2026-10-28-subagent-card-binding.md)
+
+移植自 PenguinHarness `3fa746b2`(`#1107`)。
+
+子会话过去被放到「最近一张已放行、还没有孩子的 `run_subagent` 卡片」上 —— 只有在一次只跑一个调用时这才是对的。
+同时跑几个调用时,孩子可能挂到别人的卡片上:卡片显示的是另一个描述、思考等级回落取的是另一个值,
+卡片旁边转写区的芯片指着另一条对话。
+
+子会话的第一条模型消息就是派发它的那个调用交给它的开头提示词(原样,实时流与拼回来的 Trace 都一样),
+所以现在由它来定绑定:孩子移到提示词正是这一句的那张卡片上,并按孩子 `session_meta` 里记的 `agent_id` /
+`model_id` / `provider`(含从父级继承来的取值)核对 —— 因此一个继承了父级取值的自发派发,不能只因为提示词
+相同就抢走显式选定评审者或另一个模型的那张卡。元数据缺失导致不同的选择器无从分辨时,或者孩子本来就没有卡片
+可绑(独立成一个条目)时,按位置的那次绑定照旧;被拒的调用永远拿不到孩子。
+
+消息协议、线上记录与已存数据都没变:归约器只读孩子已有的 `session_meta` 与开头那条用户文本记录。
+
+## 细节
+
+- `packages/web/src/lib/omni/stream-model.ts`:`StreamModel.unconfirmedSubagents` 记下「开头提示词还没到、
+ 只按位置绑过」的孩子;送进这个孩子的第一条模型消息由 `moveToSpawningCard` 把它移到正确的卡片上 ——
+ 目标由 `spawningCard` 挑(提示词 + 解析后的身份;完全相同的几个调用取最早还在跑的那张,否则取最后结束的那张),
+ 若那张卡上正坐着一个同样未确认的孩子,两者互换位置。
+- `packages/web/test/agent-topology.test.ts`:四条用例 —— 继承与显式两种 agent / model / provider 混用、
+ 显式的那个孩子先到,以及缺父级元数据时无从分辨的一条 —— 与既有的并发派发、后台派发、被拒调用与
+ 历史回放场景并列。
+
+## 兼容性
+
+- 不改依赖、接口、线上协议与已存数据。一次只派一个调用的对话,绑定与以前逐字一致。
diff --git a/packages/web/src/lib/omni/stream-model.ts b/packages/web/src/lib/omni/stream-model.ts
index d3afd845..a5f3c9a2 100644
--- a/packages/web/src/lib/omni/stream-model.ts
+++ b/packages/web/src/lib/omni/stream-model.ts
@@ -17,9 +17,11 @@
* on a sub-session's first message it binds to "the most recent allowed
* (decision=allow) and not-yet-complete run_subagent tool card that
* hasn't been bound to an origin yet", falling back to a standalone
- * SubagentItem if none is found; inside the nested model, the same
- * reducer recurses (with the first origin hop stripped). Sub-session
- * token_usage counts toward this level's stats (same convention as the CLI).
+ * SubagentItem if none is found; its opening prompt then moves it onto the
+ * card of the call that carried that prompt (see moveToSpawningCard).
+ * Inside the nested model, the same reducer recurses (with the first
+ * origin hop stripped). Sub-session token_usage counts toward this
+ * level's stats (same convention as the CLI).
* - Events: approval_decision annotates the corresponding tool card
* (labeled "manual" if clicked on this end, "automatic" otherwise);
* abort → an interruption marker item; request_end ending in any status
@@ -52,6 +54,7 @@
*/
import {
isEventMessage,
+ isModelMessage,
isPartialPayload,
normalizeSessionSource,
parseBackgroundTaskDoneMessage,
@@ -572,6 +575,12 @@ export interface StreamModel {
toolCards: Map<string, ToolCallItem>;
/** Direct child Session id → nested model. */
subagents: Map<string, StreamModel>;
+ /**
+ * Direct children bound before their opening prompt arrived, by position alone: the prompt
+ * names the call that spawned them, and may still move them onto its card (see
+ * moveToSpawningCard).
+ */
+ unconfirmedSubagents: Set<string>;
/** toolCallIds whose approval was clicked on this end (shares the reference with nested models, labeled "manual"). */
localDecisions: Set<string>;
/** Approval decisions that arrived before their tool card (backfilled when the card is created). */
@@ -681,6 +690,7 @@ function newModel(nested: boolean, localDecisions: Set<string>): StreamModel {
openSteering: null,
toolCards: new Map(),
subagents: new Map(),
+ unconfirmedSubagents: new Set(),
localDecisions,
pendingDecisions: new Map(),
pendingDecisionTs: new Map(),
@@ -2115,6 +2125,16 @@ function routeNested(model: StreamModel, msg: OmniMessage, nowMs: number): void
sub.firstSeenLocalMs = nowMs;
model.subagents.set(head, sub);
bindSubagent(model, head, sub);
+ model.unconfirmedSubagents.add(head);
+ }
+ // The child's first model message is the opening prompt its spawning call handed it — right
+ // behind its session_meta, live and in its spliced Trace alike — and that prompt settles which
+ // card it belongs on. A deeper descendant's message reaching it first means the prompt was
+ // missed, and the binding by position stands.
+ if (model.unconfirmedSubagents.has(head) && isModelMessage(msg)) {
+ model.unconfirmedSubagents.delete(head);
+ const prompt = msg.origin!.length === 1 ? openingPrompt(msg) : null;
+ if (prompt !== null) moveToSpawningCard(model, head, sub, prompt);
}
// Elapsed-time stamps (see the StreamModel field docs): every message routed into this child's
// subtree — its own or a deeper descendant's — counts as its activity; the recursive pushMessage
@@ -2158,6 +2178,109 @@ function bindSubagent(model: StreamModel, sessionId: string, sub: StreamModel):
model.items.push({ kind: "subagent", id: nextId(model), sessionId, model: sub });
}
+/**
+ * Moves a child onto the card of the run_subagent call that spawned it. Its first binding goes
+ * by position, which picks the wrong card as soon as several calls run at once; the opening
+ * prompt is exact, because core starts a child with the call's `prompt` argument verbatim as its
+ * first user text. The spawning card is an allowed run_subagent card with that prompt, whose
+ * `agent_id`, `model_id` and `provider` (including inherited parent values) are what the child's
+ * session_meta records, and which holds no child yet or one still unconfirmed. When missing
+ * metadata leaves different selectors ambiguous, its positional binding stands. Otherwise,
+ * calls identical in all of that use the earliest one still running (calls start in
+ * order), else the latest finished one (a background launch returns before its child's prompt
+ * has streamed in). An unconfirmed child already on the spawning card trades places with this
+ * one and moves again on its own prompt. A child bound standalone stays: no open card was left
+ * for it, so its own was not open either.
+ */
+function moveToSpawningCard(
+ model: StreamModel,
+ sessionId: string,
+ sub: StreamModel,
+ prompt: string,
+): void {
+ const from = model.items.find(
+ (item): item is ToolCallItem =>
+ item.kind === "tool_call" && item.subagentSessionId === sessionId,
+ );
+ if (!from) return;
+ const target = spawningCard(model, sessionId, prompt, sub.meta);
+ if (target === null || target === from) return;
+ const displacedId = target.subagentSessionId;
+ const displaced = target.subagent;
+ target.subagent = sub;
+ target.subagentSessionId = sessionId;
+ if (displaced !== undefined && displacedId !== undefined) {
+ from.subagent = displaced;
+ from.subagentSessionId = displacedId;
+ } else {
+ delete from.subagent;
+ delete from.subagentSessionId;
+ }
+}
+
+/** The opening prompt a child's first model message carries: a user text from its parent agent (or, in a Trace older than `sender`, from no one named). */
+function openingPrompt(msg: OmniMessage): string | null {
+ const p = msg.payload as { type?: string; role?: string; text?: unknown; sender?: string };
+ if (p.type !== "text" || p.role !== "user" || typeof p.text !== "string") return null;
+ return p.sender === undefined || p.sender === "parent_agent" ? p.text : null;
+}
+
+/** The card of the call that spawned `sessionId`, judged by its opening prompt (see moveToSpawningCard). */
+function spawningCard(
+ model: StreamModel,
+ sessionId: string,
+ prompt: string,
+ meta: NestedSessionMeta | null,
+): ToolCallItem | null {
+ const inherited = [
+ model.agentState === null ? null : agentIdFromStatePath(model.agentState),
+ model.contextModel?.modelId ?? null,
+ model.contextModel?.provider ?? null,
+ ];
+ const actual = meta === null ? null : [meta.agentId, meta.modelId, meta.provider];
+ let matchedIdentity: (string | null)[] | null = null;
+ let earliestRunning: ToolCallItem | null = null;
+ let latestFinished: ToolCallItem | null = null;
+ for (const item of model.items) {
+ if (item.kind !== "tool_call" || item.name !== "run_subagent" || item.decision !== "allow") {
+ continue;
+ }
+ const holder = item.subagentSessionId;
+ if (holder !== undefined && holder !== sessionId && !model.unconfirmedSubagents.has(holder)) {
+ continue;
+ }
+ const args = callArguments(item.argumentsText);
+ if (args === null || args.prompt !== prompt) continue;
+ const expected = ["agent_id", "model_id", "provider"].map((field, i) =>
+ typeof args[field] === "string" ? args[field] : inherited[i]!,
+ );
+ if (
+ actual !== null &&
+ expected.some((value, i) => value !== null && actual[i] !== null && value !== actual[i])
+ ) {
+ continue;
+ }
+ // A window without parent metadata cannot distinguish inheritance from an override.
+ // Preserve the existing binding instead of confirming an arbitrary same-prompt card.
+ if (matchedIdentity !== null && expected.some((value, i) => value !== matchedIdentity![i])) {
+ return null;
+ }
+ matchedIdentity = expected;
+ if (!item.outputComplete) earliestRunning ??= item;
+ else latestFinished = item;
+ }
+ return earliestRunning ?? latestFinished;
+}
+
+function callArguments(argumentsText: string): Record<string, unknown> | null {
+ try {
+ const args: unknown = JSON.parse(argumentsText);
+ return typeof args === "object" && args !== null ? (args as Record<string, unknown>) : null;
+ } catch {
+ return null;
+ }
+}
+
// ---------------------------------------------------------------------------
// Overlap dedup (connect-first + dedup)
// ---------------------------------------------------------------------------
diff --git a/packages/web/test/agent-topology.test.ts b/packages/web/test/agent-topology.test.ts
index 76d00f9e..e3d775b2 100644
--- a/packages/web/test/agent-topology.test.ts
+++ b/packages/web/test/agent-topology.test.ts
@@ -7,6 +7,21 @@
* parsing), the pending-approval subtree predicate, and layered-tree layout
* determinism/geometry.
*
+ * Which call a child belongs to (its node shows that call's description and thinking level):
+ * - Given three run_subagent calls running at once, when their children start and finish in
+ * another order than the calls were made, then each child shows its own call's description
+ * and thinking level — live, and rebuilt from history alike.
+ * - Given two calls with the same prompt to different agents, when the second agent's child
+ * speaks first, then each child stays on the call that named its agent.
+ * - Given an inherited and an explicit agent or model share a prompt, when either child
+ * starts first, then their descriptions and thinking levels stay with their own calls.
+ * - Given the parent metadata is missing and same-prompt calls have different selectors,
+ * when a child's prompt arrives, then an ambiguous match does not move it to another card.
+ * - Given two background launches whose cards finish before their children's prompts arrive,
+ * then each child still lands on its own launch.
+ * - Given a denied call carrying the same prompt as a child with no open call, then the denied
+ * call never takes the child.
+ *
* - Given an earlier child is still running, when a later task spawns another child,
* then the default panel keeps both visible with their own conversations.
* - Given two children are spawned during one task, when both continue streaming,
@@ -296,6 +311,292 @@ describe("extractTopology", () => {
});
});
+describe("which call a child belongs to", () => {
+ interface Call {
+ toolCallId: string;
+ child: string;
+ agent: string;
+ args: Record<string, unknown>;
+ }
+
+ const CALLS: Call[] = [
+ {
+ toolCallId: "call-a",
+ child: "child-a",
+ agent: "web_scout",
+ args: {
+ description: "Collect the pricing pages",
+ prompt: "Task A: collect the pricing pages of the three vendors.",
+ agent_id: "web_scout",
+ },
+ },
+ {
+ toolCallId: "call-b",
+ child: "child-b",
+ agent: "data_analyst",
+ args: {
+ description: "Compare the plans",
+ prompt: "Task B: compare the plans and flag per-seat billing.",
+ agent_id: "data_analyst",
+ thinking_level: "high",
+ },
+ },
+ {
+ toolCallId: "call-c",
+ child: "child-c",
+ agent: "default_agent",
+ args: { description: "Draft the summary table", prompt: "Task C: draft the summary table." },
+ },
+ ];
+ const [A, B, C] = CALLS as [Call, Call, Call];
+
+ const card = (call: Call): OmniMessage[] => [
+ toolCall({
+ name: "run_subagent",
+ arguments: JSON.stringify(call.args),
+ toolCallId: call.toolCallId,
+ }),
+ approvalDecision("allow", call.toolCallId),
+ ];
+ const childMeta = (call: Call): OmniMessage =>
+ withOrigin(meta(call.child, `/data/p/agents/${call.agent}/agent_state`), call.child);
+ const childPrompt = (call: Call): OmniMessage =>
+ withOrigin(userText(call.args.prompt as string, "parent_agent"), call.child);
+ const childReply = (call: Call): OmniMessage =>
+ withOrigin(assistantText(`${call.child} done`), call.child);
+ const output = (call: Call, text = "done"): OmniMessage =>
+ toolCallOutput({ output: text, toolCallId: call.toolCallId });
+
+ const shown = (m: StreamModel) =>
+ Object.fromEntries(
+ extractTopology(m, "root", false)
+ .slice(1)
+ .map((n) => [n.sessionId, [n.description, n.spawnThinkingLevel]]),
+ );
+ const OWN_CALLS = {
+ "child-a": ["Collect the pricing pages", null],
+ "child-b": ["Compare the plans", "high"],
+ "child-c": ["Draft the summary table", null],
+ };
+
+ const build = (messages: OmniMessage[]): StreamModel => {
+ const m = createStreamModel();
+ for (const msg of messages) pushMessage(m, msg);
+ return m;
+ };
+
+ it("live: children starting and finishing out of call order each show their own call", () => {
+ const m = build([
+ userText("go"),
+ ...card(A),
+ ...card(B),
+ ...card(C),
+ // B and C start before A, both session_metas ahead of either prompt.
+ childMeta(B),
+ childMeta(C),
+ childPrompt(C),
+ childMeta(A),
+ childPrompt(B),
+ childPrompt(A),
+ childReply(C),
+ output(C),
+ childReply(A),
+ output(A),
+ childReply(B),
+ output(B),
+ ]);
+ expect(shown(m)).toEqual(OWN_CALLS);
+ });
+
+ it("history: the same run rebuilt from its Trace (each child's Trace spliced at its start) shows the same", () => {
+ const spliced = (call: Call): OmniMessage[] => [
+ childMeta(call),
+ childPrompt(call),
+ childReply(call),
+ ];
+ const m = build([
+ userText("go"),
+ ...card(A),
+ ...card(B),
+ ...card(C),
+ ...spliced(B),
+ ...spliced(C),
+ ...spliced(A),
+ output(C),
+ output(A),
+ output(B),
+ ]);
+ expect(shown(m)).toEqual(OWN_CALLS);
+ });
+
+ it("the same prompt to two agents: each child stays on the call that named its agent", () => {
+ const ask = (toolCallId: string, child: string, agent: string, description: string): Call => ({
+ toolCallId,
+ child,
+ agent,
+ args: { description, prompt: "Which plan is cheapest for ten seats?", agent_id: agent },
+ });
+ const scout = ask("call-1", "child-1", "web_scout", "Ask the scout");
+ const analyst = ask("call-2", "child-2", "data_analyst", "Ask the analyst");
+ const m = build([
+ userText("go"),
+ ...card(scout),
+ ...card(analyst),
+ childMeta(analyst),
+ childMeta(scout),
+ childPrompt(analyst),
+ childPrompt(scout),
+ ]);
+ expect(shown(m)).toEqual({
+ "child-1": ["Ask the scout", null],
+ "child-2": ["Ask the analyst", null],
+ });
+ });
+
+ it.each(
+ [
+ {
+ name: "agent",
+ agent: "reviewer",
+ model: "m",
+ provider: "custom",
+ args: { agent_id: "reviewer" },
+ },
+ {
+ name: "model",
+ agent: "parent",
+ model: "other",
+ provider: "custom",
+ args: { model_id: "other", provider: "custom" },
+ },
+ {
+ name: "provider",
+ agent: "parent",
+ model: "m",
+ provider: "other",
+ args: { model_id: "m", provider: "other" },
+ },
+ ].flatMap((variant) => [true, false].map((explicitFirst) => ({ ...variant, explicitFirst }))),
+ )(
+ "inherits the parent's $name when omitted (explicit child first: $explicitFirst)",
+ (variant) => {
+ const inherited: Call = {
+ toolCallId: "inherited-call",
+ child: "inherited-child",
+ agent: "parent",
+ args: {
+ prompt: "Review this change",
+ description: "Inherited settings",
+ thinking_level: "low",
+ },
+ };
+ const explicit: Call = {
+ toolCallId: "explicit-call",
+ child: "explicit-child",
+ agent: variant.agent,
+ args: {
+ ...variant.args,
+ prompt: inherited.args.prompt,
+ description: "Explicit settings",
+ thinking_level: "high",
+ },
+ };
+ const explicitMeta = meta(explicit.child, `/data/p/agents/${explicit.agent}/agent_state`);
+ const first = variant.explicitFirst ? explicit : inherited;
+ const second = variant.explicitFirst ? inherited : explicit;
+ const records = new Map([
+ [inherited.child, childMeta(inherited)],
+ [
+ explicit.child,
+ withOrigin(
+ {
+ ...explicitMeta,
+ payload: {
+ ...explicitMeta.payload,
+ model_id: variant.model,
+ provider: variant.provider,
+ },
+ },
+ explicit.child,
+ ),
+ ],
+ ]);
+ const m = build([
+ meta("root", "/data/p/agents/parent/agent_state"),
+ userText("go"),
+ ...card(inherited),
+ ...card(explicit),
+ records.get(first.child)!,
+ records.get(second.child)!,
+ childPrompt(first),
+ childPrompt(second),
+ ]);
+ expect(shown(m)).toEqual({
+ "inherited-child": ["Inherited settings", "low"],
+ "explicit-child": ["Explicit settings", "high"],
+ });
+ },
+ );
+
+ it("keeps a positional binding when missing parent metadata leaves the same prompt ambiguous", () => {
+ const inherited: Call = {
+ ...C,
+ args: { prompt: "Review this change", description: "Self review" },
+ };
+ const explicit: Call = {
+ ...A,
+ args: { prompt: inherited.args.prompt, agent_id: A.agent, description: "Scout review" },
+ };
+ const m = build([
+ userText("go"),
+ ...card(inherited),
+ ...card(explicit),
+ childMeta(explicit),
+ childMeta(inherited),
+ childPrompt(explicit),
+ childPrompt(inherited),
+ ]);
+ expect(shown(m)).toEqual({
+ "child-c": ["Self review", null],
+ "child-a": ["Scout review", null],
+ });
+ });
+
+ it("background launches: a card that finished before its child's prompt arrived still gets that child", () => {
+ const launch = (call: Call): Call => ({
+ ...call,
+ args: { ...call.args, run_in_background: true },
+ });
+ const [bgA, bgB] = [launch(A), launch(B)];
+ const m = build([
+ userText("go"),
+ ...card(bgA),
+ ...card(bgB),
+ childMeta(bgA),
+ childMeta(bgB),
+ output(bgA, "[subagent running in background with subagent_id subagent-aaaa1111]"),
+ output(bgB, "[subagent running in background with subagent_id subagent-bbbb2222]"),
+ childPrompt(bgA),
+ childPrompt(bgB),
+ ]);
+ expect(shown(m)).toEqual({
+ "child-a": ["Collect the pricing pages", null],
+ "child-b": ["Compare the plans", "high"],
+ });
+ });
+
+ it("a denied call carrying the child's prompt never takes the child", () => {
+ const m = build([
+ userText("go"),
+ toolCall({ name: "run_subagent", arguments: JSON.stringify(A.args), toolCallId: "denied" }),
+ approvalDecision("deny", "denied"),
+ childMeta(A),
+ childPrompt(A),
+ ]);
+ expect(shown(m)).toEqual({ "child-a": [null, null] });
+ });
+});
+
describe("extractTopologyForChild (historical Task slice)", () => {
/** Task 1 spawns child1 (finished), then Task 2 spawns child2 (still running). */
const twoTasks = (): StreamModel => {