Skip to content

Commit 76c1188

Browse files
committed
refactor: simplify conversation binding and command ownership
1 parent 144633b commit 76c1188

16 files changed

Lines changed: 300 additions & 603 deletions

‎qa/scenarios/channels/subagent-thread-spawn.yaml‎

Lines changed: 124 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
title: Matrix subagent thread spawn
1+
title: Matrix subagent thread spawn and unbind
22

33
scenario:
44
id: subagent-thread-spawn
@@ -7,7 +7,7 @@ scenario:
77
primary:
88
- channels.native-threads
99
- agent-runtime.subagent-turns-subagents
10-
objective: Verify sessions_spawn(thread=true, mode=session) creates a persistent Matrix child thread and delivers the child result there.
10+
objective: Verify a persistent Matrix child thread routes follow-ups to its child session until /session unbind restores ordinary thread routing without deleting the child.
1111
gatewayConfigPatch:
1212
tools:
1313
profile: coding
@@ -28,19 +28,26 @@ scenario:
2828
- The parent calls sessions_spawn with thread=true and mode=session.
2929
- Matrix emits the child-session introduction.
3030
- The child completion carries the introduction message as its normalized thread id.
31+
- A bound follow-up is recorded in the child session history.
32+
- /session unbind acknowledges the detach in the same thread without deleting the child session.
33+
- The next follow-up is recorded only in a different session and replies once in the same thread.
3134
docsRefs:
3235
- docs/channels/matrix.md
3336
- docs/tools/subagents.md
3437
codeRefs:
3538
- src/agents/tools/sessions-spawn-tool.ts
39+
- src/auto-reply/reply/commands-session.ts
40+
- extensions/matrix/src/matrix/monitor/route.ts
3641
- extensions/qa-lab/src/live-transports/matrix/adapter.runtime.ts
3742
execution:
3843
kind: flow
3944
channel: matrix
40-
summary: Spawn a bound Matrix child session and require native thread relation evidence on completion.
45+
summary: Spawn a bound Matrix child session, prove its inbound routing, then unbind and prove follow-up history moves to an ordinary thread session.
4146
config:
4247
conversationId: main
4348
childMarker: QA-MATRIX-SUBAGENT-THREAD-OK
49+
boundMarker: QA-MATRIX-BOUND-FOLLOWUP-OK
50+
unboundMarker: QA-MATRIX-UNBOUND-FOLLOWUP-OK
4451
prompt: 'Use sessions_spawn for this QA check. task="Finish with exactly QA-MATRIX-SUBAGENT-THREAD-OK." label=qa-thread-subagent thread=true mode=session. After spawn returns status="accepted", wait for the child session reply in the spawned Matrix thread. Do not write QA-MATRIX-SUBAGENT-THREAD-OK in the parent response.'
4552

4653
flow:
@@ -89,3 +96,117 @@ flow:
8996
expr: "!env.mock || debugRequests.some((request) => request.plannedToolName === 'sessions_spawn' && /thread=true mode=session/i.test(String(request.allInputText ?? '')))"
9097
message: expected sessions_spawn(thread=true, mode=session) tool call
9198
detailsExpr: "`${completion.threadId}: ${completion.text}`"
99+
- name: restores ordinary thread routing without deleting the child
100+
actions:
101+
- call: waitForCondition
102+
saveAs: childSession
103+
args:
104+
- lambda:
105+
async: true
106+
params: []
107+
expr: "env.gateway.call('sessions.list', { agentId: 'qa', label: 'qa-thread-subagent' }, { timeoutMs: 30000 }).then((result) => result.sessions?.find((session) => session.hasActiveRun === false))"
108+
- expr: liveTurnTimeoutMs(env, 180000)
109+
- sendInbound:
110+
conversation: { id: { ref: config.conversationId }, kind: channel }
111+
senderId: "@driver:matrix.test"
112+
senderName: QA Driver
113+
text:
114+
expr: "`@openclaw Reply exactly: ${config.boundMarker}`"
115+
threadId:
116+
ref: intro.id
117+
- waitForOutbound:
118+
conversation: { id: { ref: config.conversationId }, kind: channel }
119+
textIncludes:
120+
ref: config.boundMarker
121+
threadId:
122+
ref: intro.id
123+
timeoutMs:
124+
expr: liveTurnTimeoutMs(env, 180000)
125+
- call: waitForAgentHistoryReply
126+
args:
127+
- ref: env
128+
- ref: childSession.key
129+
- lambda:
130+
params: [text]
131+
expr: text.includes(config.boundMarker)
132+
- expr: liveTurnTimeoutMs(env, 180000)
133+
- call: env.gateway.call
134+
saveAs: sessionsBeforeUnbind
135+
args:
136+
- sessions.list
137+
- agentId: qa
138+
- timeoutMs: 30000
139+
- sendInbound:
140+
conversation: { id: { ref: config.conversationId }, kind: channel }
141+
senderId: "@driver:matrix.test"
142+
senderName: QA Driver
143+
text: /session unbind
144+
threadId:
145+
ref: intro.id
146+
- waitForOutbound:
147+
conversation: { id: { ref: config.conversationId }, kind: channel }
148+
textIncludes: Conversation unbound.
149+
threadId:
150+
ref: intro.id
151+
timeoutMs:
152+
expr: liveTurnTimeoutMs(env, 45000)
153+
- sendInbound:
154+
conversation: { id: { ref: config.conversationId }, kind: channel }
155+
senderId: "@driver:matrix.test"
156+
senderName: QA Driver
157+
text:
158+
expr: "`@openclaw Reply exactly: ${config.unboundMarker}`"
159+
threadId:
160+
ref: intro.id
161+
- waitForOutbound:
162+
conversation: { id: { ref: config.conversationId }, kind: channel }
163+
textIncludes:
164+
ref: config.unboundMarker
165+
threadId:
166+
ref: intro.id
167+
timeoutMs:
168+
expr: liveTurnTimeoutMs(env, 180000)
169+
- call: waitForCondition
170+
saveAs: unboundSession
171+
args:
172+
- lambda:
173+
async: true
174+
params: []
175+
expr: "env.gateway.call('sessions.list', { agentId: 'qa' }, { timeoutMs: 30000 }).then((result) => result.sessions?.find((session) => session.hasActiveRun === false && !sessionsBeforeUnbind.sessions.some((previous) => previous.key === session.key)))"
176+
- expr: liveTurnTimeoutMs(env, 180000)
177+
- call: waitForAgentHistoryReply
178+
args:
179+
- ref: env
180+
- ref: unboundSession.key
181+
- lambda:
182+
params: [text]
183+
expr: text.includes(config.unboundMarker)
184+
- expr: liveTurnTimeoutMs(env, 180000)
185+
- call: env.gateway.call
186+
saveAs: sessionsAfterUnbind
187+
args:
188+
- sessions.list
189+
- agentId: qa
190+
label: qa-thread-subagent
191+
- timeoutMs: 30000
192+
- assert:
193+
expr: "sessionsAfterUnbind.sessions.some((session) => session.key === childSession.key && session.sessionId === childSession.sessionId)"
194+
message: unbinding removed or replaced the child session
195+
- call: readSessionTranscriptSummary
196+
saveAs: childHistoryAfterUnbind
197+
args:
198+
- ref: env
199+
- ref: childSession.key
200+
- probeText:
201+
ref: config.unboundMarker
202+
- assert:
203+
expr: "!childHistoryAfterUnbind.probeTextEndLine && unboundSession.sessionId !== childSession.sessionId"
204+
message: the detached follow-up still reached the child transcript
205+
- set: followupReplies
206+
value:
207+
expr: "state.getSnapshot().messages.filter((message) => message.direction === 'outbound' && !message.deleted && String(message.text ?? '').includes(config.unboundMarker))"
208+
- assert:
209+
expr: "followupReplies.length === 1 && followupReplies[0].conversation.id === config.conversationId && followupReplies[0].threadId === intro.id"
210+
message:
211+
expr: "`expected one detached follow-up in thread ${intro.id}, saw ${JSON.stringify(followupReplies)}`"
212+
detailsExpr: "JSON.stringify({ verdict: 'PASS', threadId: intro.id, boundSessionKey: childSession.key, unboundSessionKey: unboundSession.key, childSessionPreserved: true, detachedFollowupReplies: followupReplies.length })"

‎src/acp/translator.session-updates.test.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ function createUpdates(params: {
2424
sessionUpdate: params.sessionUpdate ?? vi.fn(async () => {}),
2525
},
2626
eventLedger: params.ledger,
27-
getAvailableCommands: async () => [],
2827
log: () => {},
2928
});
3029
}

‎src/acp/translator.session-updates.ts‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,6 @@
11
/** Emits ACP session updates and mirrors replayable updates into the event ledger. */
2-
import type {
3-
AgentSideConnection,
4-
AvailableCommand,
5-
PromptRequest,
6-
SessionUpdate,
7-
} from "@agentclientprotocol/sdk";
2+
import type { AgentSideConnection, PromptRequest, SessionUpdate } from "@agentclientprotocol/sdk";
3+
import { getAvailableCommands } from "./commands.js";
84
import type { AcpEventLedger, AcpEventLedgerReplay } from "./event-ledger.js";
95

106
/** Session identity used when emitting and recording ACP translator updates. */
@@ -22,7 +18,6 @@ type AcpTranslatorLedgerSessionRef = AcpTranslatorSessionRef & {
2218
type AcpTranslatorSessionUpdatesOptions = {
2319
connection: Pick<AgentSideConnection, "sessionUpdate">;
2420
eventLedger: AcpEventLedger;
25-
getAvailableCommands: () => Promise<AvailableCommand[]>;
2621
log: (message: string) => void;
2722
};
2823

@@ -178,7 +173,7 @@ export class AcpTranslatorSessionUpdates {
178173
record: options.record,
179174
update: {
180175
sessionUpdate: "available_commands_update",
181-
availableCommands: await this.options.getAvailableCommands(),
176+
availableCommands: getAvailableCommands(),
182177
},
183178
});
184179
}

‎src/acp/translator.ts‎

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -42,14 +42,8 @@ import { ACP_AGENT_INFO } from "./types.js";
4242
const SESSION_CREATE_RATE_LIMIT_DEFAULT_MAX_REQUESTS = 120;
4343
const SESSION_CREATE_RATE_LIMIT_DEFAULT_WINDOW_MS = 10_000;
4444

45-
const loadAcpCommandsModule = createLazyRuntimeModule(() => import("./commands.js"));
4645
const loadAcpSdkModule = createLazyRuntimeModule(() => import("@agentclientprotocol/sdk"));
4746

48-
async function getAvailableCommandsForAcp() {
49-
const { getAvailableCommands } = await loadAcpCommandsModule();
50-
return getAvailableCommands();
51-
}
52-
5347
type AcpGatewayAgentOptions = AcpServerOptions & {
5448
eventLedger?: AcpEventLedger;
5549
sessionStore?: AcpSessionStore;
@@ -82,7 +76,6 @@ export class AcpGatewayAgent implements Agent {
8276
this.sessionUpdates = new AcpTranslatorSessionUpdates({
8377
connection,
8478
eventLedger: opts.eventLedger ?? createInMemoryAcpEventLedger(),
85-
getAvailableCommands: getAvailableCommandsForAcp,
8679
log: this.log,
8780
});
8881
const sessionState = new AcpTranslatorSessionState(gateway, this.sessionUpdates, this.log);

‎src/agents/spawn-plan.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ export function resolveConversationRefForThreadBinding(params: {
8181
threadId?: string | number;
8282
groupId?: string;
8383
}): { conversationId: string; parentConversationId?: string } | null {
84-
const resolution = resolveInboundConversationResolution({
84+
return resolveInboundConversationResolution({
8585
cfg: params.cfg,
8686
channel: params.channel,
8787
accountId: params.accountId,
@@ -90,7 +90,6 @@ export function resolveConversationRefForThreadBinding(params: {
9090
groupId: params.groupId,
9191
isGroup: true,
9292
});
93-
return resolution?.canonical ?? null;
9493
}
9594

9695
function resolveRequesterBoundConversationRef(params: {

‎src/agents/subagents/spawn/acp-spawn.test.ts‎

Lines changed: 21 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
} from "../../../acp/runtime/registry.js";
1313
import { createExecutionIdentityAdmissionToken } from "../../../audit/execution-identity-admission.js";
1414
import type { ThinkLevel } from "../../../auto-reply/thinking.shared.js";
15+
import { getLoadedChannelPluginForRead } from "../../../channels/plugins/registry-loaded.js";
1516
import type { SessionEntry } from "../../../config/sessions/types.js";
1617
import type { OpenClawConfig } from "../../../config/types.openclaw.js";
1718
import { readAgentRuntimeExecutionLineage } from "../../../gateway/agent-runtime-execution-lineage.js";
@@ -29,6 +30,11 @@ import {
2930
type SessionBindingPlacement,
3031
type SessionBindingRecord,
3132
} from "../../../infra/outbound/session-binding-service.js";
33+
import { setActivePluginRegistry } from "../../../plugins/runtime.js";
34+
import {
35+
createChannelTestPluginBase,
36+
createTestRegistry,
37+
} from "../../../test-utils/channel-plugins.js";
3238
import { normalizeSessionDeliveryState } from "../../../utils/delivery-context.shared.js";
3339
import { createOperationalRunInstanceRef } from "../../admitted-run-context.js";
3440
import { reserveChildAdmissionSlot } from "../../child-admission.js";
@@ -79,8 +85,6 @@ const hoisted = vi.hoisted(() => {
7985
const resolveStorePathMock = vi.fn();
8086
const resolveSessionTranscriptFileMock = vi.fn();
8187
const areHeartbeatsEnabledMock = vi.fn();
82-
const getChannelPluginMock = vi.fn();
83-
const getLoadedChannelPluginMock = vi.fn();
8488
const normalizeChannelIdMock = vi.fn((channelId: string) => {
8589
const normalized = channelId.trim().toLowerCase();
8690
return normalized || null;
@@ -176,8 +180,6 @@ const hoisted = vi.hoisted(() => {
176180
resolveStorePathMock,
177181
resolveSessionTranscriptFileMock,
178182
areHeartbeatsEnabledMock,
179-
getChannelPluginMock,
180-
getLoadedChannelPluginMock,
181183
normalizeChannelIdMock,
182184
cleanupFailedAcpSpawnMock,
183185
registerSubagentRunMock,
@@ -203,14 +205,14 @@ vi.mock("../../../acp/runtime/session-meta.js", () => ({
203205
}));
204206

205207
vi.mock("../../../channels/plugins/index.js", () => ({
206-
getChannelPlugin: hoisted.getChannelPluginMock,
207-
getLoadedChannelPlugin: hoisted.getLoadedChannelPluginMock,
208+
getChannelPlugin: (channelId: string) => getLoadedChannelPluginForRead(channelId),
209+
getLoadedChannelPlugin: (channelId: string) => getLoadedChannelPluginForRead(channelId),
208210
normalizeChannelId: hoisted.normalizeChannelIdMock,
209211
}));
210212

211213
vi.mock("../../../channels/plugins/registry.js", () => ({
212-
getChannelPlugin: hoisted.getChannelPluginMock,
213-
getLoadedChannelPlugin: hoisted.getLoadedChannelPluginMock,
214+
getChannelPlugin: (channelId: string) => getLoadedChannelPluginForRead(channelId),
215+
getLoadedChannelPlugin: (channelId: string) => getLoadedChannelPluginForRead(channelId),
214216
normalizeChannelId: hoisted.normalizeChannelIdMock,
215217
}));
216218

@@ -551,6 +553,7 @@ function enableMatrixAcpThreadBindings(): void {
551553
},
552554
};
553555
const matrixPlugin = {
556+
...createChannelTestPluginBase({ id: "matrix" }),
554557
conversationBindings: {
555558
defaultTopLevelPlacement: "child",
556559
},
@@ -583,11 +586,8 @@ function enableMatrixAcpThreadBindings(): void {
583586
},
584587
},
585588
};
586-
hoisted.getChannelPluginMock.mockImplementation((channelId: string) =>
587-
channelId === "matrix" ? matrixPlugin : undefined,
588-
);
589-
hoisted.getLoadedChannelPluginMock.mockImplementation((channelId: string) =>
590-
channelId === "matrix" ? matrixPlugin : undefined,
589+
setActivePluginRegistry(
590+
createTestRegistry([{ pluginId: "matrix", plugin: matrixPlugin, source: "test" }]),
591591
);
592592
registerSessionBindingAdapter({
593593
channel: "matrix",
@@ -614,6 +614,7 @@ function enableLineCurrentConversationBindings(): void {
614614
},
615615
});
616616
const linePlugin = {
617+
...createChannelTestPluginBase({ id: "line" }),
617618
messaging: {
618619
resolveInboundConversation: ({
619620
conversationId,
@@ -629,11 +630,8 @@ function enableLineCurrentConversationBindings(): void {
629630
},
630631
},
631632
};
632-
hoisted.getChannelPluginMock.mockImplementation((channelId: string) =>
633-
channelId === "line" ? linePlugin : undefined,
634-
);
635-
hoisted.getLoadedChannelPluginMock.mockImplementation((channelId: string) =>
636-
channelId === "line" ? linePlugin : undefined,
633+
setActivePluginRegistry(
634+
createTestRegistry([{ pluginId: "line", plugin: linePlugin, source: "test" }]),
637635
);
638636
registerSessionBindingAdapter({
639637
channel: "line",
@@ -662,6 +660,7 @@ function enableTelegramCurrentConversationBindings(): void {
662660
},
663661
});
664662
const telegramPlugin = {
663+
...createChannelTestPluginBase({ id: "telegram" }),
665664
messaging: {
666665
resolveInboundConversation: ({
667666
conversationId,
@@ -686,11 +685,8 @@ function enableTelegramCurrentConversationBindings(): void {
686685
},
687686
},
688687
};
689-
hoisted.getChannelPluginMock.mockImplementation((channelId: string) =>
690-
channelId === "telegram" ? telegramPlugin : undefined,
691-
);
692-
hoisted.getLoadedChannelPluginMock.mockImplementation((channelId: string) =>
693-
channelId === "telegram" ? telegramPlugin : undefined,
688+
setActivePluginRegistry(
689+
createTestRegistry([{ pluginId: "telegram", plugin: telegramPlugin, source: "test" }]),
694690
);
695691
registerSessionBindingAdapter({
696692
channel: "telegram",
@@ -709,11 +705,10 @@ function enableTelegramCurrentConversationBindings(): void {
709705

710706
describe("spawnAcpDirect", () => {
711707
beforeEach(() => {
708+
setActivePluginRegistry(createTestRegistry());
712709
acpRuntimeRegistryTesting.resetAcpRuntimeBackendsForTests();
713710
replaceSpawnConfig(createDefaultSpawnConfig());
714711
hoisted.areHeartbeatsEnabledMock.mockReset().mockReturnValue(true);
715-
hoisted.getChannelPluginMock.mockReset().mockReturnValue(undefined);
716-
hoisted.getLoadedChannelPluginMock.mockReset().mockReturnValue(undefined);
717712
hoisted.cleanupFailedAcpSpawnMock.mockReset().mockResolvedValue(undefined);
718713
hoisted.registerSubagentRunMock.mockReset();
719714
hoisted.countActiveRunsForSessionMock.mockReset().mockReturnValue(0);
@@ -859,6 +854,7 @@ describe("spawnAcpDirect", () => {
859854
});
860855

861856
afterEach(() => {
857+
setActivePluginRegistry(createTestRegistry());
862858
acpRuntimeRegistryTesting.resetAcpRuntimeBackendsForTests();
863859
sessionBindingServiceTesting.resetSessionBindingAdaptersForTests();
864860
});

0 commit comments

Comments
 (0)