Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(group): allow members to start under active supervisor (#18242)

orangeboya7bd223bfa16
diff --git a/apps/cli/src/commands/notify.ts b/apps/cli/src/commands/notify.ts
index a16b51fa88c..3a0060caa09 100644
--- a/apps/cli/src/commands/notify.ts
+++ b/apps/cli/src/commands/notify.ts
@@ -53,6 +53,7 @@ export function registerNotifyCommand(program: Command) {
content: options.content,
continue: options.continue,
messageId: options.messageId,
+ operationId: process.env.LOBEHUB_OPERATION_ID,
role: options.role,
threadId: options.threadId,
topicId: options.topic,
diff --git a/apps/cli/src/daemon/taskRegistry.ts b/apps/cli/src/daemon/taskRegistry.ts
index 9dcd98d8cff..9e1e537189d 100644
--- a/apps/cli/src/daemon/taskRegistry.ts
+++ b/apps/cli/src/daemon/taskRegistry.ts
@@ -6,6 +6,7 @@ export interface TaskEntry {
agentId?: string;
agentType: 'hermes' | 'openclaw';
operationId: string;
+ parentOperationId?: string;
pid: number;
startedAt: string;
taskId: string;
diff --git a/apps/cli/src/tools/__tests__/heteroTask.test.ts b/apps/cli/src/tools/__tests__/heteroTask.test.ts
index 6da743e5550..4ec23ec435c 100644
--- a/apps/cli/src/tools/__tests__/heteroTask.test.ts
+++ b/apps/cli/src/tools/__tests__/heteroTask.test.ts
@@ -227,6 +227,37 @@ describe('runHeteroTask (openclaw)', () => {
expect(spawnMock).toHaveBeenCalledTimes(2);
});
+ it('isolates concurrent group members that share a topic', async () => {
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ spawnMock.mockReturnValueOnce(makeMockChild(1111)).mockReturnValueOnce(makeMockChild(2222));
+
+ await runHeteroTask({
+ agentType: 'openclaw',
+ operationId: 'op-child-1',
+ parentOperationId: 'op-parent',
+ prompt: 'member one',
+ taskId: 'task-child-1',
+ topicId: 'topic-shared',
+ });
+ await runHeteroTask({
+ agentType: 'openclaw',
+ operationId: 'op-child-2',
+ parentOperationId: 'op-parent',
+ prompt: 'member two',
+ taskId: 'task-child-2',
+ topicId: 'topic-shared',
+ });
+
+ expect(killSpy).not.toHaveBeenCalled();
+ const firstArgs = spawnMock.mock.calls[0][1] as string[];
+ const secondArgs = spawnMock.mock.calls[1][1] as string[];
+ expect(firstArgs[firstArgs.indexOf('--session-id') + 1]).toBe('op-child-1');
+ expect(secondArgs[secondArgs.indexOf('--session-id') + 1]).toBe('op-child-2');
+ expect(saveTask).toHaveBeenLastCalledWith(
+ expect.objectContaining({ parentOperationId: 'op-parent', taskId: 'task-child-2' }),
+ );
+ });
+
it('does not kill processes for a different topicId', async () => {
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
@@ -348,6 +379,7 @@ describe('runHeteroTask (openclaw)', () => {
string[],
{ env: NodeJS.ProcessEnv },
];
+ expect(spawnOpts.env.LOBEHUB_OPERATION_ID).toBe('op-ws');
expect(spawnOpts.env.LOBEHUB_WORKSPACE_ID).toBe('ws-42');
});
@@ -378,6 +410,81 @@ describe('runHeteroTask (openclaw)', () => {
expect(call[0]).toBe('ws-99');
}
});
+
+ it('reports a signal exit as a cancelled terminal signal', async () => {
+ const child = makeMockChild(7788);
+ spawnMock.mockReturnValue(child);
+
+ await runHeteroTask({
+ agentType: 'openclaw',
+ operationId: 'op-cancelled',
+ prompt: 'cancel me',
+ taskId: 'task-cancelled',
+ topicId: 'topic-cancelled',
+ });
+
+ child._emit('close', null, 'SIGINT');
+ await new Promise((resolve) => setImmediate(resolve));
+
+ expect(notifyMutateMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ cancelled: true,
+ done: true,
+ operationId: 'op-cancelled',
+ role: 'assistant',
+ topicId: 'topic-cancelled',
+ }),
+ );
+ });
+});
+
+describe('runHeteroTask retry ownership', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ fsState.content = undefined;
+ for (const key of Object.keys(taskStore)) delete taskStore[key];
+ execFileSyncMock.mockReturnValue('/usr/local/bin/lh\n');
+ resetTrpcClientMock();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it.each(['openclaw', 'hermes'] as const)(
+ 'ignores the stale %s close callback after an exact task retry',
+ async (agentType) => {
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ const oldChild = makeMockChild(1111);
+ const replacementChild = makeMockChild(2222);
+ spawnMock.mockReturnValueOnce(oldChild).mockReturnValueOnce(replacementChild);
+
+ await runHeteroTask({
+ agentType,
+ operationId: 'op-old',
+ prompt: 'first attempt',
+ taskId: 'task-retry',
+ topicId: 'topic-retry',
+ });
+ await runHeteroTask({
+ agentType,
+ operationId: 'op-replacement',
+ prompt: 'retry',
+ taskId: 'task-retry',
+ topicId: 'topic-retry',
+ });
+
+ expect(killSpy).toHaveBeenCalledWith(1111, 'SIGTERM');
+ expect(taskStore['task-retry']).toEqual(expect.objectContaining({ pid: 2222 }));
+
+ oldChild._emit('close', null, 'SIGTERM');
+ await new Promise((resolve) => setImmediate(resolve));
+
+ expect(taskStore['task-retry']).toEqual(expect.objectContaining({ pid: 2222 }));
+ expect(getTrpcClientMock).not.toHaveBeenCalled();
+ expect(notifyMutateMock).not.toHaveBeenCalled();
+ },
+ );
});
describe('runHeteroTask (hermes)', () => {
diff --git a/apps/cli/src/tools/heteroTask.ts b/apps/cli/src/tools/heteroTask.ts
index 007b13ff69f..d2d21a4993a 100644
--- a/apps/cli/src/tools/heteroTask.ts
+++ b/apps/cli/src/tools/heteroTask.ts
@@ -63,6 +63,7 @@ export interface RunHeteroTaskParams {
agentType: RemoteHeterogeneousAgentType;
cwd?: string;
operationId: string;
+ parentOperationId?: string;
platformAgentId?: string;
prompt: string;
taskId: string;
@@ -86,6 +87,7 @@ async function sendAutoNotify(
taskId: string,
text: string,
agentId?: string,
+ operationId?: string,
workspaceId?: string,
): Promise<void> {
try {
@@ -93,6 +95,7 @@ async function sendAutoNotify(
await client.agentNotify.notify.mutate({
agentId,
content: text,
+ operationId,
role: 'assistant',
topicId,
});
@@ -106,15 +109,17 @@ async function sendAutoNotify(
* `agent_runtime_end`, close the frontend subscription, and fire the run's
* lifecycle hooks (task lifecycle + IM bot callback).
*
- * Pass `error` to finalize the run as FAILED (non-zero process exit) — the
- * server marks the owning task failed and renders the error. Omit it for a
- * clean completion (the agent already sent its final message via `lh notify`).
+ * Pass `error` to finalize the run as FAILED (non-zero process exit), or
+ * `cancelled` to finalize it as INTERRUPTED (signal exit). Omit both for a clean
+ * completion (the agent already sent its final message via `lh notify`).
*/
async function sendTerminalSignal(
topicId: string,
agentId?: string,
+ operationId?: string,
workspaceId?: string,
error?: { message: string; type?: string },
+ cancelled = false,
): Promise<void> {
try {
const client = await getTrpcClient(workspaceId);
@@ -122,6 +127,8 @@ async function sendTerminalSignal(
agentId,
content: '',
done: true,
+ operationId,
+ ...(cancelled ? { cancelled: true } : {}),
...(error ? { error } : {}),
role: 'assistant',
topicId,
@@ -169,6 +176,7 @@ export async function runHeteroTask(params: RunHeteroTaskParams): Promise<string
agentType,
cwd,
operationId,
+ parentOperationId,
platformAgentId,
prompt,
taskId,
@@ -180,9 +188,12 @@ export async function runHeteroTask(params: RunHeteroTaskParams): Promise<string
// Propagate workspace scope into the spawned child so its own `lh notify`
// invocations (and any grandchildren it shells out) inherit the same scope
// via getTrpcClient → resolveWorkspaceId.
- const childEnv: NodeJS.ProcessEnv = workspaceId
- ? { ...process.env, LOBEHUB_WORKSPACE_ID: workspaceId }
- : { ...process.env };
+ const childEnv: NodeJS.ProcessEnv = {
+ ...process.env,
+ LOBEHUB_OPERATION_ID: operationId,
+ ...(workspaceId && { LOBEHUB_WORKSPACE_ID: workspaceId }),
+ };
+ const sessionKey = parentOperationId ? operationId : topicId;
if (agentType === 'openclaw') {
// openclaw agent --local is one-shot: each invocation processes one message and exits.
@@ -195,11 +206,16 @@ export async function runHeteroTask(params: RunHeteroTaskParams): Promise<string
// history was not cleanly committed.
const enrichedPrompt = `${prompt}\n\n${buildNotifyProtocol(lhPath, topicId)}`;
- // Kill any existing openclaw process for this topicId before spawning a new one.
+ // Top-level turns reuse one topic session and replace an older process. Group
+ // members intentionally share a topic, so isolate them by operation instead.
// openclaw serialises session writes; a concurrent process holding the session
// lock will cause the new one to exit with code 1.
for (const existing of listTasks()) {
- if (existing.topicId === topicId && existing.agentType === 'openclaw') {
+ if (
+ existing.agentType === 'openclaw' &&
+ (existing.taskId === taskId ||
+ (!parentOperationId && !existing.parentOperationId && existing.topicId === topicId))
+ ) {
try {
process.kill(existing.pid, 'SIGTERM');
} catch {
@@ -216,7 +232,7 @@ export async function runHeteroTask(params: RunHeteroTaskParams): Promise<string
'--agent',
openclawAgent,
'--session-id',
- topicId,
+ sessionKey,
'--message',
enrichedPrompt,
'--local',
@@ -239,6 +255,7 @@ export async function runHeteroTask(params: RunHeteroTaskParams): Promise<string
agentId,
agentType,
operationId,
+ parentOperationId,
pid,
startedAt: new Date().toISOString(),
taskId,
@@ -255,6 +272,7 @@ export async function runHeteroTask(params: RunHeteroTaskParams): Promise<string
// - Clean exit (code=0, no signal): openclaw already sent its final message via
// `lh notify`; just send a terminal signal to publish `agent_runtime_end`.
child.on('close', (code, signal) => {
+ if (getTask(taskId)?.pid !== pid) return;
removeTask(taskId);
if (code !== 0 || signal !== null) {
const cancelled = signal !== null;
@@ -263,17 +281,19 @@ export async function runHeteroTask(params: RunHeteroTaskParams): Promise<string
: `Task failed (exit code: ${code})`;
// Write the notice bubble first, THEN signal terminal (sequential).
// Fire-and-forget both, but ensure the terminal signal is always sent.
- void sendAutoNotify(topicId, taskId, text, agentId, workspaceId).finally(() =>
+ void sendAutoNotify(topicId, taskId, text, agentId, operationId, workspaceId).finally(() =>
sendTerminalSignal(
topicId,
agentId,
+ operationId,
workspaceId,
cancelled ? undefined : { message: text, type: 'HeteroProcessError' },
+ cancelled,
),
);
} else {
// Clean exit — openclaw already sent its final message; just signal done.
- void sendTerminalSignal(topicId, agentId, workspaceId);
+ void sendTerminalSignal(topicId, agentId, operationId, workspaceId);
}
});
@@ -281,9 +301,14 @@ export async function runHeteroTask(params: RunHeteroTaskParams): Promise<string
}
if (agentType === 'hermes') {
- // Kill any existing hermes process for this topicId before spawning a new one.
+ // Preserve parallel group members; only top-level turns replace the previous
+ // topic process, while an exact task retry replaces itself.
for (const existing of listTasks()) {
- if (existing.topicId === topicId && existing.agentType === 'hermes') {
+ if (
+ existing.agentType === 'hermes' &&
+ (existing.taskId === taskId ||
+ (!parentOperationId && !existing.parentOperationId && existing.topicId === topicId))
+ ) {
try {
process.kill(existing.pid, 'SIGTERM');
} catch {
@@ -294,7 +319,7 @@ export async function runHeteroTask(params: RunHeteroTaskParams): Promise<string
}
// Resume the previous session for this topic if one exists.
- const existingSessionId = getHermesSessionId(topicId);
+ const existingSessionId = getHermesSessionId(sessionKey);
const hermesArgs: string[] = ['chat', '--query', prompt, '--quiet', '--accept-hooks'];
if (existingSessionId) {
hermesArgs.push('--resume', existingSessionId);
@@ -317,6 +342,7 @@ export async function runHeteroTask(params: RunHeteroTaskParams): Promise<string
agentId,
agentType,
operationId,
+ parentOperationId,
pid,
startedAt: new Date().toISOString(),
taskId,
@@ -335,6 +361,7 @@ export async function runHeteroTask(params: RunHeteroTaskParams): Promise<string
});
child.on('close', (code, signal) => {
+ if (getTask(taskId)?.pid !== pid) return;
removeTask(taskId);
if (code !== 0 || signal !== null) {
@@ -342,12 +369,14 @@ export async function runHeteroTask(params: RunHeteroTaskParams): Promise<string
const text = cancelled
? `Task cancelled (signal: ${signal})`
: `Task failed (exit code: ${code})`;
- void sendAutoNotify(topicId, taskId, text, agentId, workspaceId).finally(() =>
+ void sendAutoNotify(topicId, taskId, text, agentId, operationId, workspaceId).finally(() =>
sendTerminalSignal(
topicId,
agentId,
+ operationId,
workspaceId,
cancelled ? undefined : { message: text, type: 'HeteroProcessError' },
+ cancelled,
),
);
return;
@@ -358,14 +387,14 @@ export async function runHeteroTask(params: RunHeteroTaskParams): Promise<string
const sessionId = parseHermesSessionId(stderr);
const response = stdout.trim();
- if (sessionId) saveHermesSessionId(topicId, sessionId);
+ if (sessionId) saveHermesSessionId(sessionKey, sessionId);
if (response) {
- void sendAutoNotify(topicId, taskId, response, agentId, workspaceId).finally(() =>
- sendTerminalSignal(topicId, agentId, workspaceId),
+ void sendAutoNotify(topicId, taskId, response, agentId, operationId, workspaceId).finally(
+ () => sendTerminalSignal(topicId, agentId, operationId, workspaceId),
);
} else {
- void sendTerminalSignal(topicId, agentId, workspaceId);
+ void sendTerminalSignal(topicId, agentId, operationId, workspaceId);
}
});
@@ -397,6 +426,7 @@ export async function cancelHeteroTask(params: CancelHeteroTaskParams): Promise<
taskId,
'Task already completed or cancelled',
entry.agentId,
+ entry.operationId,
entry.workspaceId,
);
}
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
index eedd6b5bed1..8f7268178f0 100644
--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
@@ -75,6 +75,7 @@ interface PlatformTaskEntry {
agentId?: string;
agentType: string;
operationId: string;
+ parentOperationId?: string;
pid: number;
topicId: string;
/**
@@ -437,6 +438,7 @@ export default class GatewayConnectionCtr extends ControllerModule {
agentType: string;
cwd?: string;
operationId: string;
+ parentOperationId?: string;
platformAgentId?: string;
prompt: string;
taskId: string;
@@ -678,6 +680,7 @@ export default class GatewayConnectionCtr extends ControllerModule {
agentType: string;
cwd?: string;
operationId: string;
+ parentOperationId?: string;
platformAgentId?: string;
prompt: string;
taskId: string;
@@ -689,6 +692,7 @@ export default class GatewayConnectionCtr extends ControllerModule {
agentType,
cwd,
operationId,
+ parentOperationId,
platformAgentId,
prompt,
taskId,
@@ -709,9 +713,11 @@ export default class GatewayConnectionCtr extends ControllerModule {
const childEnv: NodeJS.ProcessEnv = {
...process.env,
...(accessToken && { LOBEHUB_JWT: accessToken }),
+ LOBEHUB_OPERATION_ID: operationId,
...(serverUrl && { LOBEHUB_SERVER: serverUrl }),
...(workspaceId && { LOBEHUB_WORKSPACE_ID: workspaceId }),
};
+ const sessionKey = parentOperationId ? operationId : topicId;
if (agentType === 'openclaw') {
const commandStatus = await resolveRemotePlatformCommand('openclaw');
@@ -731,7 +737,11 @@ export default class GatewayConnectionCtr extends ControllerModule {
// openclaw serialises session writes; a concurrent process holding the session
// lock will cause the new one to exit with code 1.
for (const [existingTaskId, entry] of this.platformTasks) {
- if (entry.topicId === topicId && entry.agentType === 'openclaw') {
+ if (
+ entry.agentType === 'openclaw' &&
+ (existingTaskId === taskId ||
+ (!parentOperationId && !entry.parentOperationId && entry.topicId === topicId))
+ ) {
this.killPlatformProcessTree(entry.pid, 'SIGTERM');
this.platformTasks.delete(existingTaskId);
}
@@ -742,7 +752,7 @@ export default class GatewayConnectionCtr extends ControllerModule {
'--agent',
openclawAgent,
'--session-id',
- topicId,
+ sessionKey,
'--message',
enrichedPrompt,
'--local',
@@ -771,6 +781,7 @@ export default class GatewayConnectionCtr extends ControllerModule {
agentId,
agentType,
operationId,
+ parentOperationId,
pid,
topicId,
workspaceId,
@@ -787,17 +798,22 @@ export default class GatewayConnectionCtr extends ControllerModule {
const text = signal
? `Task cancelled (signal: ${signal})`
: `Task failed (exit code: ${code})`;
+ const terminalError = signal ? undefined : { message: text, type: 'HeteroProcessError' };
void this.sendNotify({
agentId,
content: text,
+ operationId,
role: 'assistant',
topicId,
workspaceId,
}).finally(() =>
this.sendNotify({
agentId,
+ cancelled: !!signal,
content: '',
done: true,
+ error: terminalError,
+ operationId,
role: 'assistant',
topicId,
workspaceId,
@@ -808,6 +824,7 @@ export default class GatewayConnectionCtr extends ControllerModule {
agentId,
content: '',
done: true,
+ operationId,
role: 'assistant',
topicId,
workspaceId,
@@ -826,14 +843,18 @@ export default class GatewayConnectionCtr extends ControllerModule {
if (commandStatus.resolvedPathEnv) childEnv.PATH = commandStatus.resolvedPathEnv;
// Kill any existing hermes process for this topicId before spawning a new one.
for (const [existingTaskId, entry] of this.platformTasks) {
- if (entry.topicId === topicId && entry.agentType === 'hermes') {
+ if (
+ entry.agentType === 'hermes' &&
+ (existingTaskId === taskId ||
+ (!parentOperationId && !entry.parentOperationId && entry.topicId === topicId))
+ ) {
this.killPlatformProcessTree(entry.pid, 'SIGTERM');
this.platformTasks.delete(existingTaskId);
}
}
// Resume the previous session for this topic if one exists.
- const existingSessionId = this.hermesSessionMap.get(topicId);
+ const existingSessionId = this.hermesSessionMap.get(sessionKey);
const hermesArgs: string[] = ['chat', '--query', prompt, '--quiet', '--accept-hooks'];
if (existingSessionId) {
hermesArgs.push('--resume', existingSessionId);
@@ -867,6 +888,7 @@ export default class GatewayConnectionCtr extends ControllerModule {
agentId,
agentType,
operationId,
+ parentOperationId,
pid,
topicId,
workspaceId,
@@ -891,17 +913,22 @@ export default class GatewayConnectionCtr extends ControllerModule {
const text = signal
? `Task cancelled (signal: ${signal})`
: `Task failed (exit code: ${code})`;
+ const terminalError = signal ? undefined : { message: text, type: 'HeteroProcessError' };
void this.sendNotify({
agentId,
content: text,
+ operationId,
role: 'assistant',
topicId,
workspaceId,
}).finally(() =>
this.sendNotify({
agentId,
+ cancelled: !!signal,
content: '',
done: true,
+ error: terminalError,
+ operationId,
role: 'assistant',
topicId,
workspaceId,
@@ -915,12 +942,13 @@ export default class GatewayConnectionCtr extends ControllerModule {
const sessionId = parseHermesSessionId(stderr);
const response = stdout.trim();
- if (sessionId) this.hermesSessionMap.set(topicId, sessionId);
+ if (sessionId) this.hermesSessionMap.set(sessionKey, sessionId);
if (response) {
void this.sendNotify({
agentId,
content: response,
+ operationId,
role: 'assistant',
topicId,
workspaceId,
@@ -929,6 +957,7 @@ export default class GatewayConnectionCtr extends ControllerModule {
agentId,
content: '',
done: true,
+ operationId,
role: 'assistant',
topicId,
workspaceId,
@@ -939,6 +968,7 @@ export default class GatewayConnectionCtr extends ControllerModule {
agentId,
content: '',
done: true,
+ operationId,
role: 'assistant',
topicId,
workspaceId,
@@ -1035,8 +1065,11 @@ export default class GatewayConnectionCtr extends ControllerModule {
*/
private async sendNotify(params: {
agentId?: string;
+ cancelled?: boolean;
content: string;
done?: boolean;
+ error?: { message: string; type?: string };
+ operationId?: string;
role: string;
topicId: string;
/**
diff --git a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
index a5c666d99a3..4fe10c9a97a 100644
--- a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
@@ -1087,11 +1087,61 @@ describe('GatewayConnectionCtr', () => {
];
expect(spawnCommand).toBe('/resolved/bin/openclaw');
expect(spawnOptions.env.PATH).toBe('/resolved/bin:/usr/bin');
+ expect(spawnOptions.env.LOBEHUB_OPERATION_ID).toBe('op-1');
const messageArg = spawnArgs[spawnArgs.indexOf('--message') + 1];
expect(messageArg).toContain('hello');
expect(messageArg).toContain('lh notify');
});
+ it('reports a failed child process as a terminal error', async () => {
+ const child = makeMockChild();
+ const notifySpy = vi.spyOn(ctr as any, 'sendNotify').mockResolvedValue(undefined);
+ spawnMock.mockReturnValue(child);
+
+ await (ctr as any).runHeteroTask({
+ agentType: 'openclaw',
+ operationId: 'op-failed-child',
+ prompt: 'hello',
+ taskId: 'task-failed-child',
+ topicId: 'topic-failed-child',
+ });
+ child._emit('close', 1, null);
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(notifySpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ done: true,
+ error: { message: 'Task failed (exit code: 1)', type: 'HeteroProcessError' },
+ operationId: 'op-failed-child',
+ }),
+ );
+ });
+
+ it('reports a signal exit as a cancelled terminal signal', async () => {
+ const child = makeMockChild();
+ const notifySpy = vi.spyOn(ctr as any, 'sendNotify').mockResolvedValue(undefined);
+ spawnMock.mockReturnValue(child);
+
+ await (ctr as any).runHeteroTask({
+ agentType: 'openclaw',
+ operationId: 'op-cancelled-child',
+ prompt: 'hello',
+ taskId: 'task-cancelled-child',
+ topicId: 'topic-cancelled-child',
+ });
+ child._emit('close', null, 'SIGINT');
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(notifySpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ cancelled: true,
+ done: true,
+ error: undefined,
+ operationId: 'op-cancelled-child',
+ }),
+ );
+ });
+
it.each([
{
environmentAgentId: 'ops-default',
@@ -1191,6 +1241,39 @@ describe('GatewayConnectionCtr', () => {
killSpy.mockRestore();
});
+ it('isolates concurrent group members that share a topic', async () => {
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ spawnMock.mockReturnValueOnce(makeMockChild(1111)).mockReturnValueOnce(makeMockChild(2222));
+
+ await (ctr as any).runHeteroTask({
+ agentType: 'openclaw',
+ operationId: 'op-child-1',
+ parentOperationId: 'op-parent',
+ prompt: 'member one',
+ taskId: 'task-child-1',
+ topicId: 'topic-shared',
+ });
+ await (ctr as any).runHeteroTask({
+ agentType: 'openclaw',
+ operationId: 'op-child-2',
+ parentOperationId: 'op-parent',
+ prompt: 'member two',
+ taskId: 'task-child-2',
+ topicId: 'topic-shared',
+ });
+
+ expect(killSpy).not.toHaveBeenCalled();
+ const firstArgs = spawnMock.mock.calls[0][1] as string[];
+ const secondArgs = spawnMock.mock.calls[1][1] as string[];
+ expect(firstArgs[firstArgs.indexOf('--session-id') + 1]).toBe('op-child-1');
+ expect(secondArgs[secondArgs.indexOf('--session-id') + 1]).toBe('op-child-2');
+ expect((ctr as any).platformTasks.get('task-child-2')).toMatchObject({
+ parentOperationId: 'op-parent',
+ });
+
+ killSpy.mockRestore();
+ });
+
it('kills the complete detached process group when cancelling a task', async () => {
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
const child = makeMockChild(5555);
@@ -1397,6 +1480,7 @@ describe('GatewayConnectionCtr', () => {
expect(notifySpy).toHaveBeenCalledWith(
expect.objectContaining({
content: 'session_id: part of the final answer\nHello from Hermes',
+ operationId: 'op-hermes-1',
topicId: 'topic-hermes',
}),
);
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.test.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.test.ts
index cf33e9d8e13..677732dcbc9 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.test.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.test.ts
@@ -6,7 +6,7 @@ import { ServerOperationStore } from './ServerOperationStore';
const topicMock = {
findById: vi.fn(),
- updateMetadata: vi.fn(),
+ takeRunningOperation: vi.fn(),
};
vi.mock('@/database/models/topic', () => ({
@@ -28,7 +28,7 @@ const markedWith = (operationId: string) => ({
describe('ServerOperationStore', () => {
beforeEach(() => {
vi.clearAllMocks();
- topicMock.updateMetadata.mockResolvedValue(undefined);
+ topicMock.takeRunningOperation.mockResolvedValue(undefined);
});
describe('clearRunningMark', () => {
@@ -37,7 +37,7 @@ describe('ServerOperationStore', () => {
await createStore('op-main').clearRunningMark();
- expect(topicMock.updateMetadata).toHaveBeenCalledWith('topic-1', { runningOperation: null });
+ expect(topicMock.takeRunningOperation).toHaveBeenCalledWith('topic-1', 'op-main');
});
it('leaves the mark alone when it belongs to another operation', async () => {
@@ -50,7 +50,7 @@ describe('ServerOperationStore', () => {
await createStore('op-child').clearRunningMark();
- expect(topicMock.updateMetadata).not.toHaveBeenCalled();
+ expect(topicMock.takeRunningOperation).not.toHaveBeenCalled();
});
it('is a no-op when the topic carries no mark', async () => {
@@ -58,21 +58,36 @@ describe('ServerOperationStore', () => {
await createStore('op-main').clearRunningMark();
- expect(topicMock.updateMetadata).not.toHaveBeenCalled();
+ expect(topicMock.takeRunningOperation).not.toHaveBeenCalled();
});
it('skips the lookup entirely without a topic', async () => {
await createTopiclessStore().clearRunningMark();
expect(topicMock.findById).not.toHaveBeenCalled();
- expect(topicMock.updateMetadata).not.toHaveBeenCalled();
+ expect(topicMock.takeRunningOperation).not.toHaveBeenCalled();
});
it('swallows lookup failures — clearing the mark is best-effort', async () => {
topicMock.findById.mockRejectedValue(new Error('db down'));
await expect(createStore('op-main').clearRunningMark()).resolves.toBeUndefined();
- expect(topicMock.updateMetadata).not.toHaveBeenCalled();
+ expect(topicMock.takeRunningOperation).not.toHaveBeenCalled();
+ });
+
+ it('takes a matching child marker without clearing its parent', async () => {
+ topicMock.findById.mockResolvedValue({
+ metadata: {
+ runningOperation: {
+ ...markedWith('op-parent').metadata.runningOperation,
+ childOperations: [{ assistantMessageId: 'asst-child', operationId: 'op-child' }],
+ },
+ },
+ });
+
+ await createStore('op-child').clearRunningMark();
+
+ expect(topicMock.takeRunningOperation).toHaveBeenCalledWith('topic-1', 'op-child');
});
});
});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.ts
index b614681b515..e76b9d3cbc5 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.ts
@@ -37,11 +37,15 @@ export class ServerOperationStore implements OperationStore {
try {
const topicModel = new TopicModel(this.serverDB, this.userId, this.workspaceId);
const topic = await topicModel.findById(this.topicId);
- const markedOperationId = topic?.metadata?.runningOperation?.operationId;
+ const marker = topic?.metadata?.runningOperation;
+ const markedOperationId = marker?.operationId;
+ const isChild = marker?.childOperations?.some(
+ (child) => child.operationId === this.operationId,
+ );
// No mark (already cleared) or someone else's mark — nothing of ours to drop.
- if (!markedOperationId || markedOperationId !== this.operationId) return;
+ if (!markedOperationId || (markedOperationId !== this.operationId && !isChild)) return;
- await topicModel.updateMetadata(this.topicId, { runningOperation: null });
+ await topicModel.takeRunningOperation(this.topicId, this.operationId!);
} catch {
// best-effort — swallow
}
diff --git a/apps/server/src/routers/lambda/__tests__/agentNotify.test.ts b/apps/server/src/routers/lambda/__tests__/agentNotify.test.ts
index d2f9172c1b6..424037d6f3a 100644
--- a/apps/server/src/routers/lambda/__tests__/agentNotify.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/agentNotify.test.ts
@@ -16,7 +16,9 @@ vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({
}));
const mockTopicFindById = vi.fn();
+const mockTopicTakeRunningOperation = vi.fn();
const mockTopicUpdateMetadata = vi.fn();
+const mockTopicRemoveRunningOperationChild = vi.fn();
const mockMessageFindById = vi.fn();
const mockMessageUpdate = vi.fn();
const mockMessageCreate = vi.fn();
@@ -37,6 +39,8 @@ vi.mock('@/server/services/verify', async (orig) => ({
vi.mock('@/database/models/topic', () => ({
TopicModel: vi.fn(() => ({
findById: mockTopicFindById,
+ removeRunningOperationChild: mockTopicRemoveRunningOperationChild,
+ takeRunningOperation: mockTopicTakeRunningOperation,
updateMetadata: mockTopicUpdateMetadata,
})),
}));
@@ -62,6 +66,7 @@ vi.mock('@/server/modules/AgentRuntime/factory', async (orig) => ({
}));
// Imported after the mocks above are registered.
+const { CompletionLifecycle } = await import('@/server/services/agentRuntime/CompletionLifecycle');
const { agentNotifyRouter } = await import('../agentNotify');
const OP = 'op-remote-1';
@@ -97,10 +102,19 @@ describe('agentNotifyRouter.notify — remote hetero terminal signal', () => {
},
},
});
+ mockTopicTakeRunningOperation.mockResolvedValue({
+ isRoot: true,
+ operation: {
+ assistantMessageId: FINAL_MSG_ID,
+ hooks: [{ id: 'task-on-complete', type: 'onComplete', webhook: { url: '/wh' } }],
+ operationId: OP,
+ },
+ });
// The placeholder message holds the agent's final reply (written in-place
// by earlier `lh notify` calls).
mockMessageFindById.mockResolvedValue({ content: 'the final reply', topicId: TOPIC });
mockTopicUpdateMetadata.mockResolvedValue(undefined);
+ mockTopicRemoveRunningOperationChild.mockResolvedValue(undefined);
// Default: a non-task op so the plan-instantiation guard no-ops unless a
// test opts into a task-bound op.
mockOpFindById.mockResolvedValue({ parentOperationId: null, taskId: null });
@@ -133,10 +147,129 @@ describe('agentNotifyRouter.notify — remote hetero terminal signal', () => {
});
expect(onError).not.toHaveBeenCalled();
- // Running marker dropped so a duplicate done can't re-fire.
- await vi.waitFor(() =>
- expect(mockTopicUpdateMetadata).toHaveBeenCalledWith(TOPIC, { runningOperation: null }),
+ expect(mockTopicTakeRunningOperation).toHaveBeenCalledWith(TOPIC, OP);
+ });
+
+ it('cancelled terminal signal finalizes the run as interrupted', async () => {
+ const { onComplete, onError } = registerHooks();
+
+ await createCaller().notify({
+ cancelled: true,
+ content: '',
+ done: true,
+ operationId: OP,
+ role: 'assistant',
+ topicId: TOPIC,
+ });
+
+ expect(mockPublishAgentRuntimeEnd).toHaveBeenCalledWith(
+ expect.objectContaining({
+ finalState: { reason: 'interrupted' },
+ operationId: OP,
+ reason: 'interrupted',
+ }),
);
+ await vi.waitFor(() => expect(onComplete).toHaveBeenCalledTimes(1));
+ expect(onComplete.mock.calls[0][0]).toMatchObject({
+ operationId: OP,
+ reason: 'interrupted',
+ });
+ expect(onError).not.toHaveBeenCalled();
+ expect(mockInstantiateVerifyPlan).not.toHaveBeenCalled();
+ expect(mockTopicTakeRunningOperation).toHaveBeenCalledWith(TOPIC, OP);
+ });
+
+ it('uses the marker snapshot read before terminal lifecycle completion', async () => {
+ const completeOperationSpy = vi
+ .spyOn(CompletionLifecycle.prototype, 'completeOperation')
+ .mockResolvedValue(undefined);
+
+ await createCaller().notify({ content: '', done: true, role: 'assistant', topicId: TOPIC });
+
+ await vi.waitFor(() => expect(completeOperationSpy).toHaveBeenCalledTimes(1));
+ expect(completeOperationSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ orchestrationRole: undefined,
+ serializedHooks: expect.arrayContaining([
+ expect.objectContaining({ id: 'task-on-complete' }),
+ ]),
+ }),
+ 'done',
+ expect.anything(),
+ );
+ // The lifecycle must not issue a second topic lookup for its hooks.
+ expect(mockTopicFindById).toHaveBeenCalledTimes(1);
+ completeOperationSpy.mockRestore();
+ });
+
+ it('leaves the marker intact so a failed terminal lifecycle can retry', async () => {
+ const completeOperationSpy = vi
+ .spyOn(CompletionLifecycle.prototype, 'completeOperation')
+ .mockRejectedValueOnce(new Error('lifecycle failed'))
+ .mockResolvedValue(undefined);
+
+ await expect(
+ createCaller().notify({ content: '', done: true, role: 'assistant', topicId: TOPIC }),
+ ).rejects.toMatchObject({ code: 'INTERNAL_SERVER_ERROR' });
+
+ expect(mockPublishAgentRuntimeEnd).not.toHaveBeenCalled();
+ expect(mockTopicTakeRunningOperation).not.toHaveBeenCalled();
+
+ await expect(
+ createCaller().notify({ content: '', done: true, role: 'assistant', topicId: TOPIC }),
+ ).resolves.toMatchObject({ messageId: FINAL_MSG_ID, topicId: TOPIC });
+
+ expect(completeOperationSpy).toHaveBeenCalledTimes(2);
+ expect(mockPublishAgentRuntimeEnd).toHaveBeenCalledTimes(1);
+ expect(mockTopicTakeRunningOperation).toHaveBeenCalledWith(TOPIC, OP);
+ completeOperationSpy.mockRestore();
+ });
+
+ it('retries a failed stream publish without firing completion hooks again', async () => {
+ const completeOperationSpy = vi
+ .spyOn(CompletionLifecycle.prototype, 'completeOperation')
+ .mockResolvedValue(undefined);
+ mockTopicFindById
+ .mockResolvedValueOnce({
+ agentId: 'agent-1',
+ metadata: { runningOperation: { operationId: OP, assistantMessageId: FINAL_MSG_ID } },
+ })
+ .mockResolvedValueOnce({ agentId: 'agent-1', metadata: { runningOperation: null } });
+ mockTopicTakeRunningOperation.mockResolvedValueOnce({
+ isRoot: true,
+ operation: { operationId: OP, assistantMessageId: FINAL_MSG_ID },
+ });
+ mockOpFindById.mockResolvedValue({
+ completedAt: new Date(),
+ parentOperationId: null,
+ taskId: null,
+ });
+ mockPublishAgentRuntimeEnd
+ .mockRejectedValueOnce(new Error('stream unavailable'))
+ .mockResolvedValue(undefined);
+
+ await expect(
+ createCaller().notify({
+ content: '',
+ done: true,
+ operationId: OP,
+ role: 'assistant',
+ topicId: TOPIC,
+ }),
+ ).rejects.toMatchObject({ code: 'INTERNAL_SERVER_ERROR' });
+
+ await createCaller().notify({
+ content: '',
+ done: true,
+ operationId: OP,
+ role: 'assistant',
+ topicId: TOPIC,
+ });
+
+ expect(completeOperationSpy).toHaveBeenCalledTimes(1);
+ expect(mockPublishAgentRuntimeEnd).toHaveBeenCalledTimes(2);
+ expect(mockTopicTakeRunningOperation).toHaveBeenCalledTimes(1);
+ completeOperationSpy.mockRestore();
});
it('durably ensures the verify plan for a task-bound run before the gate', async () => {
@@ -172,9 +305,7 @@ describe('agentNotifyRouter.notify — remote hetero terminal signal', () => {
await createCaller().notify({ content: '', done: true, role: 'assistant', topicId: TOPIC });
- await vi.waitFor(() =>
- expect(mockTopicUpdateMetadata).toHaveBeenCalledWith(TOPIC, { runningOperation: null }),
- );
+ expect(mockTopicTakeRunningOperation).toHaveBeenCalledWith(TOPIC, OP);
expect(mockInstantiateVerifyPlan).not.toHaveBeenCalled();
});
@@ -200,4 +331,180 @@ describe('agentNotifyRouter.notify — remote hetero terminal signal', () => {
});
expect(onComplete).toHaveBeenCalledTimes(1);
});
+
+ it('finalizes a child operation without clearing the supervisor marker', async () => {
+ const childOperationId = 'op-child-1';
+ const completeOperationSpy = vi
+ .spyOn(CompletionLifecycle.prototype, 'completeOperation')
+ .mockResolvedValue(undefined);
+ mockTopicFindById.mockResolvedValue({
+ agentId: 'agent-1',
+ metadata: {
+ runningOperation: {
+ childOperations: [{ operationId: childOperationId, orchestrationRole: 'member' }],
+ operationId: OP,
+ },
+ },
+ });
+ mockTopicTakeRunningOperation.mockResolvedValue({
+ isRoot: false,
+ operation: { operationId: childOperationId, orchestrationRole: 'member' },
+ });
+
+ await createCaller().notify({
+ content: '',
+ done: true,
+ operationId: childOperationId,
+ role: 'assistant',
+ topicId: TOPIC,
+ });
+
+ expect(mockPublishAgentRuntimeEnd).toHaveBeenCalledWith(
+ expect.objectContaining({ operationId: childOperationId, reason: 'success' }),
+ );
+ expect(mockTopicTakeRunningOperation).toHaveBeenCalledWith(TOPIC, childOperationId);
+ expect(completeOperationSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ operationId: childOperationId, orchestrationRole: 'member' }),
+ 'done',
+ expect.anything(),
+ );
+ expect(mockTopicUpdateMetadata).not.toHaveBeenCalledWith(TOPIC, { runningOperation: null });
+ completeOperationSpy.mockRestore();
+ });
+
+ it('accepts a legacy callback when there is one remote child', async () => {
+ const childOperationId = 'op-child-legacy';
+ const completeOperationSpy = vi
+ .spyOn(CompletionLifecycle.prototype, 'completeOperation')
+ .mockResolvedValue(undefined);
+ mockTopicFindById.mockResolvedValue({
+ agentId: 'agent-1',
+ metadata: {
+ runningOperation: {
+ childOperations: [
+ { operationId: childOperationId, heteroType: 'openclaw', orchestrationRole: 'member' },
+ ],
+ operationId: OP,
+ },
+ },
+ });
+ mockTopicTakeRunningOperation.mockResolvedValue({
+ isRoot: false,
+ operation: { operationId: childOperationId, orchestrationRole: 'member' },
+ });
+
+ await createCaller().notify({ content: '', done: true, role: 'assistant', topicId: TOPIC });
+
+ expect(completeOperationSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ operationId: childOperationId }),
+ 'done',
+ expect.anything(),
+ );
+ expect(mockTopicTakeRunningOperation).toHaveBeenCalledWith(TOPIC, childOperationId);
+ completeOperationSpy.mockRestore();
+ });
+
+ it('requires operationId when multiple remote children are active', async () => {
+ mockTopicFindById.mockResolvedValue({
+ agentId: 'agent-1',
+ metadata: {
+ runningOperation: {
+ childOperations: [
+ { operationId: 'op-child-1', heteroType: 'openclaw', orchestrationRole: 'member' },
+ { operationId: 'op-child-2', heteroType: 'hermes', orchestrationRole: 'member' },
+ ],
+ operationId: OP,
+ },
+ },
+ });
+
+ await expect(
+ createCaller().notify({ content: '', done: true, role: 'assistant', topicId: TOPIC }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+
+ expect(mockTopicTakeRunningOperation).not.toHaveBeenCalled();
+ });
+
+ it('ignores a repeated child terminal callback after its marker was removed', async () => {
+ const childOperationId = 'op-child-1';
+ const activeTopic = {
+ agentId: 'agent-1',
+ metadata: {
+ runningOperation: {
+ childOperations: [{ operationId: childOperationId, orchestrationRole: 'member' }],
+ operationId: OP,
+ },
+ },
+ };
+ const completeOperationSpy = vi
+ .spyOn(CompletionLifecycle.prototype, 'completeOperation')
+ .mockResolvedValue(undefined);
+ mockTopicFindById.mockResolvedValueOnce(activeTopic).mockResolvedValueOnce({
+ ...activeTopic,
+ metadata: {
+ runningOperation: {
+ childOperations: [],
+ operationId: OP,
+ },
+ },
+ });
+ mockTopicTakeRunningOperation
+ .mockResolvedValueOnce({
+ isRoot: false,
+ operation: { operationId: childOperationId, orchestrationRole: 'member' },
+ })
+ .mockResolvedValueOnce(undefined);
+
+ await createCaller().notify({
+ content: '',
+ done: true,
+ operationId: childOperationId,
+ role: 'assistant',
+ topicId: TOPIC,
+ });
+ await vi.waitFor(() => expect(completeOperationSpy).toHaveBeenCalledTimes(1));
+
+ const duplicate = await createCaller().notify({
+ content: '',
+ done: true,
+ operationId: childOperationId,
+ role: 'assistant',
+ topicId: TOPIC,
+ });
+
+ expect(duplicate).toEqual({ messageId: undefined, operationId: undefined, topicId: TOPIC });
+ expect(completeOperationSpy).toHaveBeenCalledTimes(1);
+ completeOperationSpy.mockRestore();
+ });
+
+ it('writes a child notification to its own placeholder message', async () => {
+ const childOperationId = 'op-child-1';
+ const childMessageId = 'msg-child';
+ const supervisorMessageId = 'msg-supervisor';
+ mockTopicFindById.mockResolvedValue({
+ agentId: 'agent-1',
+ metadata: {
+ runningOperation: {
+ assistantMessageId: supervisorMessageId,
+ childOperations: [{ assistantMessageId: childMessageId, operationId: childOperationId }],
+ operationId: OP,
+ },
+ },
+ });
+ mockMessageFindById.mockResolvedValue({ content: '', topicId: TOPIC });
+
+ await createCaller().notify({
+ content: 'child response',
+ operationId: childOperationId,
+ role: 'assistant',
+ topicId: TOPIC,
+ });
+
+ expect(mockMessageUpdate).toHaveBeenCalledWith(childMessageId, { content: 'child response' });
+ expect(mockMessageUpdate).not.toHaveBeenCalledWith(supervisorMessageId, expect.anything());
+ expect(mockPublishStreamEvent).toHaveBeenCalledWith(
+ childOperationId,
+ expect.objectContaining({ type: 'notify_update' }),
+ );
+ });
});
diff --git a/apps/server/src/routers/lambda/agentNotify.ts b/apps/server/src/routers/lambda/agentNotify.ts
index 52dfe8a358c..10c2b8b9d68 100644
--- a/apps/server/src/routers/lambda/agentNotify.ts
+++ b/apps/server/src/routers/lambda/agentNotify.ts
@@ -1,4 +1,5 @@
import { isFullAccessApiKey } from '@lobechat/const/apiKeyScope';
+import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';
import { RequestTrigger } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import debug from 'debug';
@@ -48,6 +49,8 @@ const agentNotifyWriteProcedure = agentNotifyProcedure.use(withScopedPermission(
const NotifySchema = z.object({
/** Agent ID to trigger (overrides the topic's default agent) */
agentId: z.string().optional(),
+ /** Signal that the remote hetero run was cancelled by a process signal. */
+ cancelled: z.boolean().optional(),
/** Message content from the external agent */
content: z.string(),
/**
@@ -79,6 +82,12 @@ const NotifySchema = z.object({
* in-place, keeping a single bubble in the UI.
*/
messageId: z.string().optional(),
+ /**
+ * Server-assigned operation identity for this callback. Remote CLI/Desktop
+ * clients propagate it through LOBEHUB_OPERATION_ID; assistant callbacks
+ * need it to distinguish concurrent group members sharing one topic.
+ */
+ operationId: z.string().optional(),
/**
* Role of the message to write:
* - 'user' (default): write as user message and trigger the agent to reply
@@ -108,6 +117,7 @@ export const agentNotifyRouter = router({
threadId,
role = 'user',
continue: shouldContinue = false,
+ cancelled = false,
done = false,
error: terminalError,
messageId,
@@ -115,7 +125,8 @@ export const agentNotifyRouter = router({
// An error is itself a terminal signal — finalize the run even if the
// remote agent didn't also set `done`.
- const isTerminal = done || !!terminalError;
+ const isTerminal = done || !!terminalError || cancelled;
+ const completionReason = terminalError ? 'error' : cancelled ? 'interrupted' : 'done';
log(
'notify: topicId=%s, agentId=%s, role=%s, continue=%s, done=%s, messageId=%s, content=%s',
@@ -139,8 +150,35 @@ export const agentNotifyRouter = router({
// Extract the operationId seeded by execAgent for remote hetero agents.
// Used to publish notify_update / agent_runtime_end events to the gateway WS.
- const remoteOperationId = (topic.metadata as any)?.runningOperation?.operationId as
- string | undefined;
+ const marker = (topic.metadata as any)?.runningOperation;
+ let remoteOperationId = input.operationId ?? marker?.operationId;
+ let activeOperation =
+ remoteOperationId && marker
+ ? marker.operationId === remoteOperationId
+ ? marker
+ : marker.childOperations?.find((child: any) => child.operationId === remoteOperationId)
+ : marker;
+
+ // Legacy CLI clients do not send operationId. Keep them working when the
+ // topic has exactly one remote operation; concurrent remote members remain
+ // ambiguous and must use an operation-scoped client.
+ if (role === 'assistant' && !input.operationId && marker?.childOperations?.length) {
+ const remoteCandidates = [marker, ...(marker.childOperations ?? [])].filter((operation) =>
+ isRemoteHeterogeneousType(operation.heteroType),
+ );
+ if (remoteCandidates.length === 1) {
+ [activeOperation] = remoteCandidates;
+ remoteOperationId = activeOperation.operationId;
+ } else {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message:
+ remoteCandidates.length > 1
+ ? 'operationId is required when multiple remote operations are active'
+ : 'operationId is required for child operations',
+ });
+ }
+ }
const agentId = inputAgentId ?? topic.agentId;
if (!agentId) {
@@ -160,6 +198,25 @@ export const agentNotifyRouter = router({
workspaceId: ctx.workspaceId,
});
+ // Reject late callbacks after their exact operation marker has been removed.
+ // This applies to progress as well as terminal delivery: a delayed update must
+ // not overwrite a completed member's final message.
+ let terminalRetry = false;
+ if (role === 'assistant' && input.operationId && !activeOperation) {
+ const operation = await new AgentOperationModel(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ ).findById(input.operationId);
+ terminalRetry = isTerminal && !!operation?.completedAt;
+ if (!terminalRetry) {
+ log('notify: ignoring stale callback for operationId=%s', input.operationId);
+ return { messageId: undefined, operationId: undefined, topicId };
+ }
+ }
+
+ const terminalOperation = activeOperation;
+
/**
* Publish a stream event for remote hetero agents (openclaw / hermes).
* Fire-and-forget — stream publish failures must not break the notify response.
@@ -169,18 +226,6 @@ export const agentNotifyRouter = router({
try {
const stream = getStreamManager();
if (isTerminal) {
- // Signal task completion — frontend gateway WS subscription closes.
- // A `terminalError` finalizes the run as failed; otherwise it succeeded.
- await stream.publishAgentRuntimeEnd({
- finalState: terminalError
- ? { error: terminalError.message, reason: 'error' }
- : { reason: 'success' },
- operationId: remoteOperationId,
- reason: terminalError ? 'error' : 'success',
- reasonDetail: terminalError?.message ?? 'Remote hetero agent task completed',
- stepIndex: 0,
- });
-
// Remote hetero (openclaw / hermes) has no `heteroFinish` callback, so
// this is its terminal funnel. Route it through CompletionLifecycle's
// single entry — the SAME owner the CLI / in-process paths use — so
@@ -189,20 +234,20 @@ export const agentNotifyRouter = router({
// success the delivery-checker verify gate runs against the task's plan.
// (Previously this fired the stripped-down dispatchTerminalHooks, which
// skipped persist + verify — so openclaw/hermes tasks never auto-verified.)
- // Hooks were serialized onto runningOperation at dispatch time.
- const serializedHooks = (topic.metadata as any)?.runningOperation?.hooks as
- SerializedHook[] | undefined;
+ // Use the terminal claim snapshot. Publishing the end event lets a
+ // connected client clear the live marker before this continuation runs.
+ const serializedHooks = terminalOperation?.hooks as SerializedHook[] | undefined;
let lastAssistantContent: string | undefined = content || undefined;
if (!lastAssistantContent && writtenMessageId) {
const msg = await ctx.messageModel.findById(writtenMessageId).catch(() => undefined);
lastAssistantContent = (msg?.content as string | undefined) ?? undefined;
}
// Mirror heteroFinish's done-path prep (this is the openclaw/hermes
- // equivalent terminal funnel). Skipped on the error path (verify is
- // done-only). Each step is self-guarded so a failure degrades instead
+ // equivalent terminal funnel). Only needed for successful completion
+ // (verify is done-only). Each step is self-guarded so a failure degrades instead
// of aborting the terminal funnel.
let goal: unknown = '';
- if (!terminalError) {
+ if (completionReason === 'done') {
// Guarantee the task's verify plan is DURABLY persisted before the gate
// (completeOperation → runVerifyOnCompletion) reads it. The start-side
// instantiation in execAgent is fire-and-forget on a SEPARATE
@@ -239,32 +284,54 @@ export const agentNotifyRouter = router({
log('notify: failed to resolve verify goal (non-fatal): %O', err);
}
}
- await new CompletionLifecycle(
- ctx.serverDB,
- ctx.userId,
- ctx.workspaceId ?? undefined,
- ).completeOperation(
- {
- agentId,
- assistantMessageId: writtenMessageId,
- deliverable: lastAssistantContent,
- error: terminalError ?? undefined,
- goal,
- operationId: remoteOperationId,
- serializedHooks,
- topicId,
- userId: ctx.userId,
- },
- terminalError ? 'error' : 'done',
- // openclaw/hermes surface their failure via the runtime-end stream event
- // + their own message write, not the lifecycle's assistant-row error
- // write — keep that prior behavior on the error path.
- { skipErrorMessageWrite: true },
- );
-
- // The operation is finished — drop the running marker so a duplicate
- // terminal signal / reconnect doesn't re-fire the hooks.
- await ctx.topicModel.updateMetadata(topicId, { runningOperation: null }).catch(() => {});
+ if (!terminalRetry) {
+ await new CompletionLifecycle(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ ).completeOperation(
+ {
+ agentId,
+ assistantMessageId: writtenMessageId,
+ deliverable: lastAssistantContent,
+ error: terminalError ?? undefined,
+ goal,
+ operationId: remoteOperationId,
+ orchestrationRole: terminalOperation?.orchestrationRole,
+ serializedHooks,
+ topicId,
+ userId: ctx.userId,
+ },
+ completionReason,
+ // openclaw/hermes surface their failure via the runtime-end stream event
+ // + their own message write, not the lifecycle's assistant-row error
+ // write — keep that prior behavior on the error path.
+ { skipErrorMessageWrite: true },
+ );
+ }
+
+ // Claim the marker before publishing. A retry after a successful
+ // lifecycle can then publish the missing stream event without firing
+ // completion hooks a second time.
+ if (!terminalRetry) {
+ const claimed = await ctx.topicModel.takeRunningOperation(topicId, remoteOperationId);
+ if (!claimed) return;
+ }
+
+ const streamReason = completionReason === 'done' ? 'success' : completionReason;
+ await stream.publishAgentRuntimeEnd({
+ finalState: terminalError
+ ? { error: terminalError.message, reason: 'error' }
+ : { reason: streamReason },
+ operationId: remoteOperationId,
+ reason: streamReason,
+ reasonDetail:
+ terminalError?.message ??
+ (cancelled
+ ? 'Remote hetero agent task cancelled'
+ : 'Remote hetero agent task completed'),
+ stepIndex: 0,
+ });
} else {
// Lightweight invalidation — frontend calls fetchAndReplaceMessages.
await stream.publishStreamEvent(remoteOperationId, {
@@ -279,6 +346,7 @@ export const agentNotifyRouter = router({
remoteOperationId,
err,
);
+ if (isTerminal) throw err;
}
};
@@ -289,8 +357,7 @@ export const agentNotifyRouter = router({
// 1. Caller-supplied messageId (subsequent notify calls with --message-id)
// 2. Placeholder assistantMessageId seeded by execAgent (first notify call for remote hetero)
// Using the placeholder avoids creating a second empty bubble in the UI.
- const placeholderMessageId = (topic.metadata as any)?.runningOperation
- ?.assistantMessageId as string | undefined;
+ const placeholderMessageId = terminalOperation?.assistantMessageId as string | undefined;
const resolvedMessageId = messageId ?? placeholderMessageId;
// Update existing message if we have a resolved target
@@ -313,11 +380,12 @@ export const agentNotifyRouter = router({
// `lastAssistantContent` — bot completion callbacks and the task
// lifecycle follow-ups (handoff / auto-review / brief) depend on it.
if (isTerminal && !content) {
- void publishRemoteHeteroEvent(resolvedMessageId);
+ await publishRemoteHeteroEvent(resolvedMessageId);
return { messageId: resolvedMessageId, operationId: undefined, topicId };
}
await ctx.messageModel.update(resolvedMessageId, { content });
- void publishRemoteHeteroEvent(resolvedMessageId);
+ if (isTerminal) await publishRemoteHeteroEvent(resolvedMessageId);
+ else void publishRemoteHeteroEvent(resolvedMessageId);
if (shouldContinue) {
const result = await ctx.aiAgentService.execAgent({
agentId,
@@ -335,7 +403,7 @@ export const agentNotifyRouter = router({
// Terminal signal (done or error) with no messageId and empty content →
// just finalize the run, no DB write.
if (isTerminal && !content) {
- void publishRemoteHeteroEvent();
+ await publishRemoteHeteroEvent();
return { messageId: undefined, operationId: undefined, topicId };
}
@@ -347,7 +415,8 @@ export const agentNotifyRouter = router({
topicId,
});
- void publishRemoteHeteroEvent(msg.id);
+ if (isTerminal) await publishRemoteHeteroEvent(msg.id);
+ else void publishRemoteHeteroEvent(msg.id);
// Optionally trigger a follow-up agent turn.
// Use resume=true + parentMessageId so execAgent skips creating an
diff --git a/apps/server/src/services/agentRuntime/AbandonOperationService.ts b/apps/server/src/services/agentRuntime/AbandonOperationService.ts
index ed8505b14cd..c7d9cfd8a09 100644
--- a/apps/server/src/services/agentRuntime/AbandonOperationService.ts
+++ b/apps/server/src/services/agentRuntime/AbandonOperationService.ts
@@ -160,28 +160,27 @@ export class AbandonOperationService {
}
}
- if (!metadata.isSubAgent && metadata.userId) {
- if (metadata.topicId) {
- try {
- const topicModel = new TopicModel(this.db, metadata.userId, metadata.workspaceId);
- await topicModel.settleRunningOperation(metadata.topicId, operationId);
- } catch (e) {
- log('[%s] abandoned op runningOperation cleanup failed (non-fatal): %O', operationId, e);
- }
+ if (metadata.topicId && metadata.userId) {
+ try {
+ const topicModel = new TopicModel(this.db, metadata.userId, metadata.workspaceId);
+ await topicModel.settleRunningOperation(metadata.topicId, operationId);
+ } catch (e) {
+ log('[%s] abandoned op runningOperation cleanup failed (non-fatal): %O', operationId, e);
}
+ }
- if (shouldDispatchAbandonedLifecycle) {
- try {
- await new CompletionLifecycle(
- this.db,
- metadata.userId,
- metadata.workspaceId,
- ).dispatchHooks(operationId, finalState, 'error', {
+ if (!metadata.isSubAgent && metadata.userId && shouldDispatchAbandonedLifecycle) {
+ try {
+ await new CompletionLifecycle(this.db, metadata.userId, metadata.workspaceId).dispatchHooks(
+ operationId,
+ finalState,
+ 'error',
+ {
skipErrorMessageWrite: result.assistantMessageUpdated,
- });
- } catch (e) {
- log('[%s] abandoned op lifecycle dispatch failed (non-fatal): %O', operationId, e);
- }
+ },
+ );
+ } catch (e) {
+ log('[%s] abandoned op lifecycle dispatch failed (non-fatal): %O', operationId, e);
}
}
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
index 533983af8ab..8ad6d383391 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
@@ -73,6 +73,8 @@ export interface OperationCompletionInput {
/** Executed model — the verify gate keys off `op.model`, so hetero backfills it. */
model?: string | null;
operationId: string;
+ /** Group orchestration role; members must not trigger user-facing completion recalls. */
+ orchestrationRole?: 'member' | 'supervisor';
/** Executed provider — see {@link OperationCompletionInput.model}. */
provider?: string | null;
/** Serialized webhook hooks (queue mode); ignored in local in-memory mode. */
@@ -517,6 +519,7 @@ export class CompletionLifecycle {
_hooks: input.serializedHooks,
agentId: input.agentId,
assistantMessageId: input.assistantMessageId,
+ orchestrationRole: input.orchestrationRole,
topicId: input.topicId,
userId: input.userId ?? this.userId,
},
@@ -597,7 +600,7 @@ export class CompletionLifecycle {
*/
async completeOperation(
input: OperationCompletionInput,
- reason: 'done' | 'error',
+ reason: 'done' | 'error' | 'interrupted',
options?: CompleteOperationOptions,
): Promise<void> {
await this.dispatchHooks(input.operationId, this.buildStateFromInput(input), reason, options);
diff --git a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts
index b4c01772859..763e1a0e43a 100644
--- a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts
@@ -247,6 +247,36 @@ describe('AbandonOperationService', () => {
expect(messageUpdateMock).not.toHaveBeenCalled();
});
+ it('cleans up a no-state child marker and errors its own placeholder', async () => {
+ const coord = buildCoordinator({ loadAgentState: vi.fn().mockResolvedValue(null) });
+ const db = buildDb({
+ operationRow: {
+ id: 'op_child',
+ startedAt: new Date('2026-06-30T11:51:14.745Z'),
+ status: 'running',
+ topicId: 'tpc_x',
+ userId: 'user_x',
+ },
+ });
+ topicSettleRunningOperationMock.mockResolvedValue({
+ assistantMessageId: 'msg_child',
+ orchestrationRole: 'member',
+ status: 'settled',
+ });
+
+ const result = await new AbandonOperationService(db, {
+ coordinator: coord as any,
+ snapshotStore: buildStore() as any,
+ }).finalizeAbandoned('op_child', 'inactivity_watchdog');
+
+ expect(result.assistantMessageUpdated).toBe(true);
+ expect(topicSettleRunningOperationMock).toHaveBeenCalledWith('tpc_x', 'op_child');
+ expect(messageUpdateMock).toHaveBeenCalledWith(
+ 'msg_child',
+ expect.objectContaining({ error: expect.anything() }),
+ );
+ });
+
it('finalizes snapshot and marks assistant message errored when state + partial exist', async () => {
const coord = buildCoordinator({
loadAgentState: vi.fn().mockResolvedValue(stateWith()),
@@ -474,6 +504,7 @@ describe('AbandonOperationService', () => {
isSubAgent: true,
orchestrationRole: 'member',
threadId: 'thread_g',
+ topicId: 'tpc_x',
userId: 'user_x',
workspaceId: 'ws_1',
},
@@ -495,6 +526,7 @@ describe('AbandonOperationService', () => {
// coordinator state is cleaned up normally.
expect(result.subAgentResume).toBeUndefined();
expect(findOperationMock).not.toHaveBeenCalled();
+ expect(topicSettleRunningOperationMock).toHaveBeenCalledWith('tpc_x', 'op_member');
expect(coord.deleteAgentOperation).toHaveBeenCalledWith('op_member');
});
diff --git a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
index 38e4e73b824..0e09d4c2977 100644
--- a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
@@ -732,6 +732,17 @@ describe('CompletionLifecycle.dispatchHooks — completion notification', () =>
expect(mockNotifyAgentRunCompleted).not.toHaveBeenCalled();
});
+ it('preserves an in-group member role in synthesized completion state', () => {
+ const lifecycle = buildLifecycle();
+
+ const state = (lifecycle as any).buildStateFromInput({
+ operationId: 'op-member',
+ orchestrationRole: 'member',
+ });
+
+ expect(state.metadata.orchestrationRole).toBe('member');
+ });
+
it.each(['max_steps', 'cost_limit'])(
'notifies on the success-like capped terminal %s (still produced a deliverable)',
async (reason) => {
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
index dbaece47994..23546b6b0bd 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
@@ -6,6 +6,7 @@ const {
mockDeviceFindByDeviceId,
mockDeviceFindWorkspaceDeviceById,
mockBuildRemoteDeviceHeteroContext,
+ mockCreateOperationMetadata,
mockDispatchAgentRun,
mockExecuteToolCall,
mockGetHeterogeneousResumeSessionId,
@@ -18,6 +19,7 @@ const {
mockPublishAgentRuntimeEnd,
} = vi.hoisted(() => ({
mockBuildRemoteDeviceHeteroContext: vi.fn().mockReturnValue('device context'),
+ mockCreateOperationMetadata: vi.fn().mockResolvedValue(undefined),
mockDeviceFindByDeviceId: vi.fn(),
mockDeviceFindWorkspaceDeviceById: vi.fn(),
mockDispatchAgentRun: vi.fn().mockResolvedValue({ success: true }),
@@ -37,7 +39,9 @@ const {
// the assertion below can verify the init, and so the real one (which probes
// Redis synchronously) doesn't throw a server-env error in the test env.
vi.mock('@/server/modules/AgentRuntime/factory', () => ({
- createAgentStateManager: vi.fn(),
+ createAgentStateManager: vi.fn(() => ({
+ createOperationMetadata: mockCreateOperationMetadata,
+ })),
createStreamEventManager: () => ({
publishAgentRuntimeEnd: mockPublishAgentRuntimeEnd,
publishAgentRuntimeInit: mockPublishAgentRuntimeInit,
@@ -121,8 +125,11 @@ vi.mock('@/database/models/plugin', () => ({
}));
const topicMock = {
+ appendRunningOperationChild: vi.fn().mockResolvedValue(true),
create: vi.fn().mockResolvedValue({ id: 'topic-1', metadata: undefined }),
findById: vi.fn().mockResolvedValue(undefined),
+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),
+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),
updateMetadata: vi.fn().mockResolvedValue(undefined),
};
vi.mock('@/database/models/topic', () => ({
@@ -210,8 +217,11 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>
beforeEach(() => {
vi.clearAllMocks();
+ topicMock.appendRunningOperationChild.mockResolvedValue(true);
topicMock.create.mockResolvedValue({ id: 'topic-1', metadata: undefined });
topicMock.findById.mockResolvedValue(undefined);
+ topicMock.releaseTaskCallbackReservation.mockResolvedValue(undefined);
+ topicMock.tryReserveTaskCallback.mockResolvedValue(true);
topicMock.updateMetadata.mockResolvedValue(undefined);
mockMessageCreate.mockResolvedValue({ id: 'msg-1' });
mockMessageQuery.mockResolvedValue([]);
@@ -226,6 +236,7 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>
);
mockDeviceFindByDeviceId.mockResolvedValue({ defaultCwd: '/Users/alice/repo' });
mockDeviceFindWorkspaceDeviceById.mockResolvedValue(undefined);
+ mockCreateOperationMetadata.mockResolvedValue(undefined);
mockIngestAttachment.mockReset();
heteroAgentConfig.agencyConfig = { heterogeneousProvider: { type: 'claude-code' } } as any;
heteroAgentConfig.model = 'claude-code';
@@ -962,12 +973,117 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>
},
};
- // Pick out the updateMetadata call that persists the running operation.
const findRunningOpSeed = () =>
topicMock.updateMetadata.mock.calls
.map((call) => call[1])
.find((patch: any) => patch?.runningOperation?.operationId);
+ it('keeps the supervisor marker when an in-group hetero child is dispatched', async () => {
+ topicMock.findById.mockResolvedValue({
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'supervisor-assistant',
+ operationId: 'parent-operation',
+ },
+ },
+ });
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ appContext: {
+ isolationThread: false,
+ orchestrationRole: 'member',
+ topicId: 'topic-1',
+ },
+ parentOperationId: 'parent-operation',
+ prompt: 'speak as member',
+ topicStartOwnerOperationId: 'parent-operation',
+ } as any);
+
+ expect(topicMock.appendRunningOperationChild).toHaveBeenCalledWith(
+ 'topic-1',
+ 'parent-operation',
+ expect.objectContaining({ operationId: expect.stringContaining('op_') }),
+ );
+ expect(topicMock.tryReserveTaskCallback).toHaveBeenCalledWith(
+ 'topic-1',
+ expect.any(String),
+ 'parent-operation',
+ undefined,
+ );
+ expect(mockCreateOperationMetadata).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ mirrorToOperationId: 'parent-operation' }),
+ );
+ expect(mockPublishAgentRuntimeInit).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ mirrorToOperationId: 'parent-operation' }),
+ );
+ });
+
+ it('threads the parent operation through remote member dispatch', async () => {
+ heteroAgentConfig.agencyConfig = {
+ executionTarget: 'local',
+ heterogeneousProvider: { type: 'openclaw' },
+ } as any;
+ heteroAgentConfig.model = 'openclaw';
+ heteroAgentConfig.provider = 'lobehub';
+ topicMock.findById.mockResolvedValue({
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'supervisor-assistant',
+ operationId: 'parent-operation',
+ },
+ },
+ });
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ appContext: {
+ orchestrationRole: 'member',
+ topicId: 'topic-1',
+ },
+ localDeviceId: 'personal-desktop',
+ parentOperationId: 'parent-operation',
+ prompt: 'run this member',
+ topicStartOwnerOperationId: 'parent-operation',
+ } as any);
+
+ expect(mockPublishAgentRuntimeInit).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ mirrorToOperationId: 'parent-operation' }),
+ );
+ expect(mockCreateOperationMetadata).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ mirrorToOperationId: 'parent-operation' }),
+ );
+ const toolCall = mockExecuteToolCall.mock.calls.at(-1)?.[1];
+ expect(JSON.parse(toolCall.arguments)).toEqual(
+ expect.objectContaining({ parentOperationId: 'parent-operation' }),
+ );
+ });
+
+ it('does not dispatch a member after its supervisor marker was cleared', async () => {
+ topicMock.appendRunningOperationChild.mockResolvedValue(false);
+
+ const result = await service.execAgent({
+ agentId: 'agent-1',
+ appContext: {
+ isolationThread: false,
+ orchestrationRole: 'member',
+ topicId: 'topic-1',
+ },
+ parentOperationId: 'parent-operation',
+ prompt: 'speak as member',
+ topicStartOwnerOperationId: 'parent-operation',
+ } as any);
+
+ expect(result).toMatchObject({ status: 'error', success: false });
+ expect(mockSpawnHeteroSandbox).not.toHaveBeenCalled();
+ expect(mockDispatchAgentRun).not.toHaveBeenCalled();
+ expect(mockExecuteToolCall).not.toHaveBeenCalled();
+ });
+
it('serializes the onComplete webhook hook onto runningOperation (sandbox dispatch)', async () => {
await service.execAgent({
agentId: 'agent-1',
@@ -1202,6 +1318,42 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>
);
});
+ it('cancels a remote child operation without touching the supervisor device', async () => {
+ topicMock.findById.mockResolvedValue({
+ metadata: {
+ runningOperation: {
+ deviceId: 'supervisor-desktop',
+ deviceUserId: 'supervisor-user',
+ heteroType: 'openclaw',
+ operationId: 'operation-parent',
+ childOperations: [
+ {
+ deviceId: 'member-desktop',
+ deviceUserId: 'member-user',
+ heteroType: 'hermes',
+ operationId: 'operation-child',
+ },
+ ],
+ },
+ },
+ });
+
+ await service.interruptTask({ operationId: 'operation-child', topicId: 'topic-1' });
+
+ expect(mockExecuteToolCall).toHaveBeenCalledWith(
+ {
+ deviceId: 'member-desktop',
+ userId: 'member-user',
+ workspaceId: undefined,
+ },
+ expect.objectContaining({
+ apiName: 'cancelHeteroTask',
+ arguments: JSON.stringify({ signal: 'SIGINT', taskId: 'operation-child' }),
+ }),
+ 5_000,
+ );
+ });
+
it('recovers the topic from the operation when the cancellation caller omits it', async () => {
(service as any).agentOperationModel.findById = vi
.fn()
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.ts
index e5a3583c777..9db08e26cd7 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.ts
@@ -205,6 +205,7 @@ describe('AiAgentService.execAgent - user turn spine anchoring', () => {
'topic-1',
expect.stringMatching(/^agent-start-/),
undefined,
+ undefined,
);
expect(mockReleaseReservation).toHaveBeenCalledWith(
'topic-1',
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.threadId.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.threadId.test.ts
index a964ccd847a..8e9f6dbfad2 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.threadId.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.threadId.test.ts
@@ -4,10 +4,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AiAgentService } from '../index';
// Use vi.hoisted to ensure mock functions are available before vi.mock runs
-const { mockMessageCreate, mockTopicUpdateMetadata } = vi.hoisted(() => ({
- mockMessageCreate: vi.fn(),
- mockTopicUpdateMetadata: vi.fn(),
-}));
+const { mockMessageCreate, mockTopicAppendRunningOperationChild, mockTopicUpdateMetadata } =
+ vi.hoisted(() => ({
+ mockMessageCreate: vi.fn(),
+ mockTopicAppendRunningOperationChild: vi.fn(),
+ mockTopicUpdateMetadata: vi.fn(),
+ }));
// Mock trusted client to avoid server-side env access
vi.mock('@/libs/trusted-client', () => ({
@@ -69,6 +71,7 @@ vi.mock('@/database/models/plugin', () => ({
// Mock TopicModel
vi.mock('@/database/models/topic', () => ({
TopicModel: vi.fn().mockImplementation(() => ({
+ appendRunningOperationChild: mockTopicAppendRunningOperationChild,
releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),
tryReserveTaskCallback: vi.fn().mockResolvedValue(true),
create: vi.fn().mockResolvedValue({ id: 'topic-1' }),
@@ -175,6 +178,7 @@ describe('AiAgentService.execAgent - threadId handling', () => {
// Explicitly clear the shared mock to prevent state pollution between tests
mockMessageCreate.mockClear();
mockMessageCreate.mockResolvedValue({ id: 'msg-1' });
+ mockTopicAppendRunningOperationChild.mockReset().mockResolvedValue(true);
mockTopicUpdateMetadata.mockClear();
mockTopicUpdateMetadata.mockResolvedValue(undefined);
@@ -251,6 +255,16 @@ describe('AiAgentService.execAgent - threadId handling', () => {
});
});
+ it('does not trust a public member role to suppress the marker', async () => {
+ await service.execAgent({
+ agentId: 'agent-1',
+ appContext: { orchestrationRole: 'member', topicId: 'topic-1' },
+ prompt: 'Test prompt',
+ });
+
+ expect(runningMarkCalls()).toHaveLength(1);
+ });
+
it('does not claim the mark for an isolation-thread run', async () => {
// A callAgent / callSubAgent / group-member child executes on the PARENT's
// topic. Claiming the mark pointed every client reconnect at the child's
@@ -265,6 +279,33 @@ describe('AiAgentService.execAgent - threadId handling', () => {
expect(runningMarkCalls()).toHaveLength(0);
});
+
+ it('registers an owned isolation-thread run as a child marker', async () => {
+ await service.execAgent({
+ agentId: 'agent-1',
+ appContext: {
+ isolationThread: true,
+ orchestrationRole: 'member',
+ threadId: 'thread-123',
+ topicId: 'topic-1',
+ },
+ parentOperationId: 'parent-operation',
+ prompt: 'Test prompt',
+ topicStartOwnerOperationId: 'parent-operation',
+ } as any);
+
+ expect(mockTopicAppendRunningOperationChild).toHaveBeenCalledWith(
+ 'topic-1',
+ 'parent-operation',
+ expect.objectContaining({
+ assistantMessageId: 'msg-1',
+ operationId: expect.stringContaining('op_'),
+ orchestrationRole: 'member',
+ threadId: 'thread-123',
+ }),
+ );
+ expect(runningMarkCalls()).toHaveLength(0);
+ });
});
describe('when threadId is not provided in appContext', () => {
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 2b840d53d40..7ee91e546af 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -129,7 +129,10 @@ import { shouldEnableBuiltinSkill } from '@/helpers/skillFilters';
import { buildConnectorManifests } from '@/libs/mcp/buildConnectorManifests';
import { patchManifestWithPermissions } from '@/libs/mcp/connectorPermissionCheck';
import { signOperationJwt, signUserJWT } from '@/libs/trpc/utils/internalJwt';
-import { createStreamEventManager } from '@/server/modules/AgentRuntime/factory';
+import {
+ createAgentStateManager,
+ createStreamEventManager,
+} from '@/server/modules/AgentRuntime/factory';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
import type { EvalContext, ServerAgentToolsContext } from '@/server/modules/Mecha';
import { createServerAgentToolsEngine } from '@/server/modules/Mecha';
@@ -530,6 +533,8 @@ interface InternalExecAgentParams extends ExecAgentParams {
* chatConfig AND workspace member-mode overrides.
*/
toolModeOverride?: 'agent' | 'chat';
+ /** Running operation that owns the topic for an internally spawned child run. */
+ topicStartOwnerOperationId?: string;
/**
* Re-enter a topic-start reservation already acquired by an upstream caller,
* such as TaskResultBridgeService.
@@ -814,7 +819,7 @@ export class AiAgentService {
// 3. The operation never started — drop the running marker so reconnect /
// heteroIngest validation and the next turn don't see a stale operation.
try {
- await this.topicModel.updateMetadata(topicId, { runningOperation: null });
+ await this.topicModel.takeRunningOperation(topicId, operationId);
} catch (err) {
log('finalizeHeteroDispatchError: clear runningOperation failed (non-fatal): %O', err);
}
@@ -1272,11 +1277,14 @@ export class AiAgentService {
// advance the topic's main spine. They may start while their parent
// operation owns `runningOperation` (for example callAgent/callSubAgent),
// so making them wait for the topic-start claim deadlocks the child start.
- if (!topicId || params.appContext?.threadId) return this.execAgentWithReservation(params);
+ if (!topicId || params.appContext?.threadId) {
+ return this.execAgentWithReservation(params);
+ }
const reservationId = params.topicStartReservationId ?? `agent-start-${nanoid()}`;
const reserved = await acquireTopicStartReservation({
replacesOperationId: params.replacesOperationId,
+ allowRunningOperationId: params.topicStartOwnerOperationId,
reservationId,
topicId,
topicModel: this.topicModel,
@@ -2468,24 +2476,74 @@ export class AiAgentService {
// operation, and so every terminal site (heteroFinish, agentNotify done,
// dispatch failure) can re-fire the serialized hooks across a process
// boundary in queue mode.
- await this.topicModel.updateMetadata(topicId, {
- runningOperation: {
- assistantMessageId: assistantMessageRecord.id,
- hooks: serializedHooks,
- // Store deviceId + heteroType so interruptTask can cancel remote processes
- ...(isRemoteHetero && remoteDeviceId
- ? {
- deviceId: remoteDeviceId,
- deviceUserId: remoteDeviceUserId,
- deviceWorkspaceId: remoteDeviceWorkspaceId,
- heteroType,
- }
- : undefined),
- operationId,
- scope: appContext?.scope ?? undefined,
- threadId: appContext?.threadId ?? undefined,
- },
- });
+ const childOperation = {
+ assistantMessageId: assistantMessageRecord.id,
+ hooks: serializedHooks,
+ ...(isRemoteHetero && remoteDeviceId
+ ? {
+ deviceId: remoteDeviceId,
+ deviceUserId: remoteDeviceUserId,
+ deviceWorkspaceId: remoteDeviceWorkspaceId,
+ heteroType,
+ }
+ : {}),
+ operationId,
+ orchestrationRole: appContext?.orchestrationRole,
+ scope: appContext?.scope ?? undefined,
+ threadId: appContext?.threadId ?? undefined,
+ };
+ if (params.topicStartOwnerOperationId) {
+ const attached = await this.topicModel.appendRunningOperationChild(
+ topicId,
+ params.topicStartOwnerOperationId,
+ childOperation,
+ );
+ if (!attached) {
+ const message = 'Group supervisor finished before this member could start.';
+ await new CompletionLifecycle(this.db, this.userId, this.workspaceId).completeOperation(
+ {
+ agentId: persistAgentId,
+ assistantMessageId: assistantMessageRecord.id,
+ error: { message, type: 'AgentRuntimeError' },
+ operationId,
+ orchestrationRole: appContext?.orchestrationRole,
+ serializedHooks,
+ topicId,
+ userId: this.userId,
+ },
+ 'error',
+ );
+ return {
+ agentId: resolvedAgentId,
+ assistantMessageId: assistantMessageRecord.id,
+ autoStarted: false,
+ createdAt: new Date().toISOString(),
+ error: message,
+ message,
+ operationId,
+ status: 'error',
+ success: false,
+ timestamp: new Date().toISOString(),
+ topicId,
+ userMessageId: userMessageRecord?.id ?? parentMessageId ?? '',
+ };
+ }
+ } else {
+ await this.topicModel.updateMetadata(topicId, { runningOperation: childOperation });
+ }
+
+ const persistMirrorTarget = async () => {
+ if (!params.topicStartOwnerOperationId) return;
+ try {
+ await createAgentStateManager().createOperationMetadata(operationId, {
+ mirrorToOperationId: params.topicStartOwnerOperationId,
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ });
+ } catch (err) {
+ log('execAgent: failed to persist hetero mirror target: %O', err);
+ }
+ };
if (
agentConfig.agencyConfig?.heterogeneousProvider?.type === 'claude-code' &&
@@ -2580,12 +2638,14 @@ export class AiAgentService {
// Open the stream channel so the gateway WS subscription can receive
// notify_update events published by agentNotify.notify.
+ await persistMirrorTarget();
const streamManager = createStreamEventManager();
await streamManager
.publishAgentRuntimeInit(operationId, {
agentId: resolvedAgentId,
assistantMessageId: assistantMessageRecord.id,
heteroType,
+ mirrorToOperationId: params.topicStartOwnerOperationId,
topicId,
userId: this.userId,
})
@@ -2606,6 +2666,7 @@ export class AiAgentService {
agentType: heteroType,
cwd: undefined,
operationId,
+ parentOperationId: params.topicStartOwnerOperationId,
platformAgentId: agentConfig.agencyConfig?.heterogeneousProvider?.platformAgentId,
prompt,
taskId: operationId,
@@ -2680,10 +2741,12 @@ export class AiAgentService {
// the init only powers reconnect, not the run. `createStreamEventManager`
// probes Redis synchronously, so guard construction too, not just publish.
try {
+ await persistMirrorTarget();
await createStreamEventManager().publishAgentRuntimeInit(operationId, {
agentId: resolvedAgentId,
assistantMessageId: assistantMessageRecord.id,
heteroType,
+ mirrorToOperationId: params.topicStartOwnerOperationId,
topicId,
userId: this.userId,
});
@@ -4186,6 +4249,38 @@ export class AiAgentService {
const timestamp = Date.now();
const operationId = `op_${timestamp}_${resolvedAgentId}_${topicId}_${nanoid(8)}`;
+ if (params.topicStartOwnerOperationId) {
+ const attached = await this.topicModel.appendRunningOperationChild(
+ topicId,
+ params.topicStartOwnerOperationId,
+ {
+ assistantMessageId: assistantMessageRecord.id,
+ operationId,
+ orchestrationRole: appContext?.orchestrationRole,
+ scope: appContext?.scope ?? undefined,
+ threadId: appContext?.threadId ?? undefined,
+ },
+ );
+ if (!attached) {
+ const errorMessage = 'Group supervisor finished before this member could start.';
+ await updateAbortedAssistantMessage(errorMessage);
+ return {
+ agentId: resolvedAgentId,
+ assistantMessageId: assistantMessageRecord.id,
+ autoStarted: false,
+ createdAt: new Date().toISOString(),
+ error: errorMessage,
+ message: errorMessage,
+ operationId,
+ status: 'error',
+ success: false,
+ timestamp: new Date().toISOString(),
+ topicId,
+ userMessageId: userMessageRecord?.id ?? parentMessageId ?? '',
+ };
+ }
+ }
+
// 16. Create initial context
let initialContext: AgentRuntimeContext = {
payload: {
@@ -4698,7 +4793,9 @@ export class AiAgentService {
// WebSocket for the rest of the run. The parent's mark stays authoritative;
// a child's live progress already rides down the parent channel via
// `appContext.subAgentProgress`.
- if (!appContext?.isolationThread) {
+ // `orchestrationRole` is public rendering metadata. Only the internally
+ // propagated parent operation id proves child ownership of this topic.
+ if (!appContext?.isolationThread && !params.topicStartOwnerOperationId) {
await this.topicModel.updateMetadata(topicId, {
runningOperation: {
assistantMessageId: assistantMessageRecord.id,
@@ -4735,6 +4832,9 @@ export class AiAgentService {
userMessageId: userMessageRecord?.id ?? parentMessageId ?? '',
};
} catch (error) {
+ if (params.topicStartOwnerOperationId) {
+ await this.topicModel.removeRunningOperationChild(topicId, operationId).catch(() => false);
+ }
if (isAbortError(error)) {
await updateAbortedAssistantMessage(error.message);
log('execAgent: createOperation aborted for %s: %s', operationId, error.message);
@@ -5058,6 +5158,7 @@ export class AiAgentService {
parentOperationId,
prompt: speakerInstruction,
suppressUserMessage: true,
+ topicStartOwnerOperationId: parentOperationId,
trigger: inheritedTrigger,
userInterventionConfig: { approvalMode: 'headless' },
});
@@ -5739,29 +5840,40 @@ export class AiAgentService {
deviceWorkspaceId?: string;
heteroType?: string;
operationId?: string;
+ childOperations?: Array<{
+ deviceId?: string;
+ deviceUserId?: string;
+ deviceWorkspaceId?: string;
+ heteroType?: string;
+ operationId?: string;
+ }>;
}
| undefined;
+ const targetOperation =
+ runningOp?.operationId === resolvedOperationId
+ ? runningOp
+ : runningOp?.childOperations?.find((child) => child.operationId === resolvedOperationId);
if (
- runningOp?.deviceId &&
- runningOp.heteroType &&
- runningOp.operationId === resolvedOperationId &&
- isRemoteHeterogeneousType(runningOp.heteroType)
+ targetOperation?.deviceId &&
+ targetOperation.heteroType &&
+ isRemoteHeterogeneousType(targetOperation.heteroType)
) {
- const taskId = runningOp.operationId ?? resolvedOperationId;
+ const taskId = targetOperation.operationId ?? resolvedOperationId;
log(
'interruptTask: cancelling remote hetero process heteroType=%s deviceId=%s taskId=%s',
- runningOp.heteroType,
- runningOp.deviceId,
+ targetOperation.heteroType,
+ targetOperation.deviceId,
taskId,
);
const cancelWorkspaceId =
- runningOp.deviceWorkspaceId ?? (await this.resolveDeviceWorkspaceId(runningOp.deviceId));
+ targetOperation.deviceWorkspaceId ??
+ (await this.resolveDeviceWorkspaceId(targetOperation.deviceId));
await deviceGateway
.executeToolCall(
{
- deviceId: runningOp.deviceId,
- userId: runningOp.deviceUserId ?? this.userId,
+ deviceId: targetOperation.deviceId,
+ userId: targetOperation.deviceUserId ?? this.userId,
workspaceId: cancelWorkspaceId,
},
{
diff --git a/apps/server/src/services/aiAgent/topicStartReservation.test.ts b/apps/server/src/services/aiAgent/topicStartReservation.test.ts
index f4fa4c2e732..3702aff2aa2 100644
--- a/apps/server/src/services/aiAgent/topicStartReservation.test.ts
+++ b/apps/server/src/services/aiAgent/topicStartReservation.test.ts
@@ -53,6 +53,32 @@ describe('acquireTopicStartReservation', () => {
topicModel,
});
- expect(tryReserveTaskCallback).toHaveBeenCalledWith('topic-1', 'new-start', 'old-operation');
+ expect(tryReserveTaskCallback).toHaveBeenCalledWith(
+ 'topic-1',
+ 'new-start',
+ undefined,
+ 'old-operation',
+ );
+ });
+
+ it('passes the parent operation ownership through for in-group children', async () => {
+ const tryReserveTaskCallback = vi.fn().mockResolvedValue(true);
+ const topicModel = { tryReserveTaskCallback } as unknown as TopicModel;
+
+ await expect(
+ acquireTopicStartReservation({
+ allowRunningOperationId: 'parent-operation',
+ reservationId: 'child-operation',
+ topicId: 'topic-1',
+ topicModel,
+ }),
+ ).resolves.toBe(true);
+
+ expect(tryReserveTaskCallback).toHaveBeenCalledWith(
+ 'topic-1',
+ 'child-operation',
+ 'parent-operation',
+ undefined,
+ );
});
});
diff --git a/apps/server/src/services/aiAgent/topicStartReservation.ts b/apps/server/src/services/aiAgent/topicStartReservation.ts
index f0ce652ee9e..f537d80b528 100644
--- a/apps/server/src/services/aiAgent/topicStartReservation.ts
+++ b/apps/server/src/services/aiAgent/topicStartReservation.ts
@@ -18,11 +18,13 @@ const delay = (milliseconds: number): Promise<void> =>
* 500 response, while interactive callers receive a finite busy failure.
*/
export const acquireTopicStartReservation = async ({
+ allowRunningOperationId,
replacesOperationId,
reservationId,
topicId,
topicModel,
}: {
+ allowRunningOperationId?: string;
replacesOperationId?: string;
reservationId: string;
topicId: string;
@@ -32,6 +34,7 @@ export const acquireTopicStartReservation = async ({
const reservation = await topicModel.tryReserveTaskCallback(
topicId,
reservationId,
+ allowRunningOperationId,
replacesOperationId,
);
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
index 90ac39c2c0c..57a37985c96 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
@@ -414,7 +414,11 @@ export class HeterogeneousPersistenceHandler {
}
const topic = await this.deps.topicModel.findById(topicId);
- const running = topic?.metadata?.runningOperation;
+ const marker = topic?.metadata?.runningOperation;
+ const running =
+ marker?.operationId === operationId
+ ? marker
+ : marker?.childOperations?.find((child) => child.operationId === operationId);
if (!running && !(allowMissingRunningOperation && seedAssistantMessageId)) {
throw new StaleHeteroOperationError(
@@ -422,9 +426,9 @@ export class HeterogeneousPersistenceHandler {
);
}
- if (running && running.operationId !== operationId) {
+ if (!running && !(allowMissingRunningOperation && seedAssistantMessageId)) {
throw new StaleHeteroOperationError(
- `Stale hetero operation ${operationId} on topic ${topicId}; current operation is ${running.operationId}`,
+ `Stale hetero operation ${operationId} on topic ${topicId}; current operation is ${marker?.operationId ?? 'unknown'}`,
);
}
@@ -797,11 +801,15 @@ export class HeterogeneousPersistenceHandler {
private async syncAssistantPointerForAdvancedStep(state: OperationState): Promise<void> {
const topic = await this.deps.topicModel.findById(state.topicId);
- const running = topic?.metadata?.runningOperation;
+ const marker = topic?.metadata?.runningOperation;
+ const running =
+ marker?.operationId === state.operationId
+ ? marker
+ : marker?.childOperations?.find((child) => child.operationId === state.operationId);
- if (running && running.operationId !== state.operationId) {
+ if (!running) {
throw new StaleHeteroOperationError(
- `Stale hetero operation ${state.operationId} on topic ${state.topicId}; current operation is ${running.operationId}`,
+ `Stale hetero operation ${state.operationId} on topic ${state.topicId}; current operation is ${marker?.operationId ?? 'unknown'}`,
);
}
@@ -939,9 +947,17 @@ export class HeterogeneousPersistenceHandler {
intent.messageId,
);
- await this.deps.topicModel.updateMetadata(state.topicId, {
- heteroCurrentMsgId: { msgId: intent.messageId, operationId: state.operationId },
- });
+ if (this.deps.topicModel.updateRunningOperationAssistantMessage) {
+ await this.deps.topicModel.updateRunningOperationAssistantMessage(
+ state.topicId,
+ state.operationId,
+ intent.messageId,
+ );
+ } else {
+ await this.deps.topicModel.updateMetadata(state.topicId, {
+ heteroCurrentMsgId: { msgId: intent.messageId, operationId: state.operationId },
+ });
+ }
return;
}
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
index 20015c07c0a..a399a6e1db0 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
@@ -1760,6 +1760,29 @@ describe('HeterogeneousPersistenceHandler', () => {
});
describe('warm replica step resync', () => {
+ it('reports a late advanced batch as stale after its operation was removed', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await h.handler.ingest({
+ events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'step1' })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+ h.topicModel.findById.mockResolvedValue({ agentId: null, id: 'topic-1', metadata: {} });
+
+ await expect(
+ h.handler.ingest({
+ events: [buildEvent('stream_chunk', 1, { chunkType: 'text', content: 'late' })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ }),
+ ).rejects.toThrow('Stale hetero operation op-1');
+ });
+
it('switches to the DB-persisted step assistant when a later-step batch lands on a stale warm replica', async () => {
const h = createHarness({
assistantMessageId: 'asst-1',
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts
index 1eb4503468b..40cc496b344 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts
@@ -76,14 +76,24 @@ const buildEvent = (
type,
});
-const createService = (overrides: { streamEventManager?: IStreamEventManager } = {}) => {
+const createService = (
+ overrides: { operationId?: string; streamEventManager?: IStreamEventManager } = {},
+) => {
const { manager, published } = createFakeStreamManager();
const persistenceHandler = createFakePersistenceHandler();
+ const topicModel = {
+ settleRunningOperation: vi.fn(async (_topicId: string, operationId: string): Promise<any> => ({
+ assistantMessageId: 'asst-1',
+ operationId,
+ status: 'settled',
+ })),
+ };
const service = new HeterogeneousAgentService({} as any, 'user-test', {
persistenceHandler,
streamEventManager: overrides.streamEventManager ?? manager,
+ topicModel: topicModel as any,
});
- return { manager, persistenceHandler, published, service };
+ return { manager, persistenceHandler, published, service, topicModel };
};
describe('HeterogeneousAgentService', () => {
@@ -406,7 +416,7 @@ describe('HeterogeneousAgentService', () => {
});
it('forwards classified error details when the run failed', async () => {
- const { published, service } = createService();
+ const { published, service } = createService({ operationId: 'op-2' });
await service.heteroFinish({
agentType: 'codex',
@@ -425,7 +435,7 @@ describe('HeterogeneousAgentService', () => {
});
it('persists and publishes a structured auth_required error from a flattened finish', async () => {
- const { persistenceHandler, published, service } = createService();
+ const { persistenceHandler, published, service } = createService({ operationId: 'op-auth' });
await service.heteroFinish({
agentType: 'claude-code',
@@ -516,7 +526,7 @@ describe('HeterogeneousAgentService', () => {
};
it('fires onComplete (reason=done) hooks on a successful run', async () => {
- const { service } = createService();
+ const { service } = createService({ operationId: 'op-hook-success' });
const { onComplete, onError } = registerHook('op-hook-success');
await service.heteroFinish({
@@ -537,7 +547,7 @@ describe('HeterogeneousAgentService', () => {
});
it('fires both onComplete and onError (reason=error) hooks on a failed run', async () => {
- const { service } = createService();
+ const { service } = createService({ operationId: 'op-hook-error' });
const { onComplete, onError } = registerHook('op-hook-error');
await service.heteroFinish({
@@ -564,7 +574,7 @@ describe('HeterogeneousAgentService', () => {
// gate on success — and the gate bails unless op.model/provider are set, so the
// synthetic state MUST carry the model/provider backfilled from the CLI stream.
it('routes the terminal transition through CompletionLifecycle with backfilled model/provider', async () => {
- const { service } = createService();
+ const { service } = createService({ operationId: 'op-verify-align' });
const finalizeSpy = vi.spyOn(HeteroTraceRecorder.prototype, 'finalize').mockResolvedValue({
llmCalls: 3,
@@ -609,13 +619,38 @@ describe('HeterogeneousAgentService', () => {
dispatchSpy.mockRestore();
});
+ it('forwards a group member role to the completion lifecycle', async () => {
+ const { service, topicModel } = createService({ operationId: 'op-member' });
+ topicModel.settleRunningOperation.mockResolvedValue({
+ assistantMessageId: 'asst-member',
+ orchestrationRole: 'member',
+ status: 'settled',
+ });
+ const completeOperationSpy = vi
+ .spyOn(CompletionLifecycle.prototype, 'completeOperation')
+ .mockResolvedValue(undefined);
+
+ await service.heteroFinish({
+ agentType: 'claude-code',
+ operationId: 'op-member',
+ result: 'success',
+ topicId: 'topic-member',
+ });
+
+ expect(completeOperationSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ operationId: 'op-member', orchestrationRole: 'member' }),
+ 'done',
+ );
+ completeOperationSpy.mockRestore();
+ });
+
// Cross-instance race guard: recordStart's in-memory verify-plan promise lives
// on a DIFFERENT CompletionLifecycle (execAgent), so heteroFinish can't await
// it. A fast run could reach the gate before the plan persists. heteroFinish
// must therefore re-run the idempotent durable instantiation and AWAIT it
// before dispatching the gate.
it('awaits durable verify-plan instantiation before the completion gate for a task-bound run', async () => {
- const { service } = createService();
+ const { service } = createService({ operationId: 'op-race-guard' });
const findByIdSpy = vi
.spyOn(AgentOperationModel.prototype, 'findById')
@@ -652,7 +687,7 @@ describe('HeterogeneousAgentService', () => {
});
it('skips verify-plan instantiation for a non-task hetero run', async () => {
- const { service } = createService();
+ const { service } = createService({ operationId: 'op-no-task' });
const findByIdSpy = vi
.spyOn(AgentOperationModel.prototype, 'findById')
@@ -838,7 +873,13 @@ describe('HeterogeneousAgentService', () => {
status: 'missing' as const,
};
}
- if (runningOperation.operationId !== operationId) {
+ const isRoot = runningOperation.operationId === operationId;
+ const operation = isRoot
+ ? runningOperation
+ : runningOperation.childOperations?.find(
+ (candidate: any) => candidate.operationId === operationId,
+ );
+ if (!operation) {
return {
activeOperationId: runningOperation.operationId,
status: 'conflict' as const,
@@ -846,15 +887,26 @@ describe('HeterogeneousAgentService', () => {
}
const currentMessage = meta.heteroCurrentMsgId;
- meta = { ...meta, runningOperation: null };
+ meta = {
+ ...meta,
+ runningOperation: isRoot
+ ? null
+ : {
+ ...runningOperation,
+ childOperations: runningOperation.childOperations.filter(
+ (candidate: any) => candidate.operationId !== operationId,
+ ),
+ },
+ };
return {
assistantMessageId:
currentMessage?.operationId === operationId
? currentMessage.msgId
- : runningOperation.assistantMessageId,
- hooks: runningOperation.hooks,
+ : operation.assistantMessageId,
+ hooks: operation.hooks,
+ orchestrationRole: operation.orchestrationRole,
status: 'settled' as const,
- threadId: runningOperation.threadId,
+ threadId: operation.threadId,
};
}),
updateMetadata: vi.fn(async (_id: string, patch: Record<string, any>, mergeBase?: any) => {
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/sessionResume.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/sessionResume.test.ts
index f1912c8b0e3..f60ce96c9b2 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/sessionResume.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/sessionResume.test.ts
@@ -2,6 +2,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { type IStreamEventManager } from '@/server/modules/AgentRuntime/types';
+import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLifecycle';
import { HeterogeneousAgentService, HeterogeneousPersistenceHandler } from '..';
import { __resetOperationStatesForTesting } from '../HeterogeneousPersistenceHandler';
@@ -12,8 +13,14 @@ const createSilentStreamManager = (): IStreamEventManager =>
}) as unknown as IStreamEventManager;
describe('HeterogeneousAgentService — phase 2c session id persistence + resume', () => {
- beforeEach(() => __resetOperationStatesForTesting());
- afterEach(() => __resetOperationStatesForTesting());
+ beforeEach(() => {
+ __resetOperationStatesForTesting();
+ vi.spyOn(CompletionLifecycle.prototype, 'completeOperation').mockResolvedValue(undefined);
+ });
+ afterEach(() => {
+ __resetOperationStatesForTesting();
+ vi.restoreAllMocks();
+ });
describe('heteroFinish persists sessionId via TopicModel.updateMetadata', () => {
it('writes the CLI session id to topic.metadata.heteroSessionId', async () => {
@@ -59,6 +66,11 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
const service = new HeterogeneousAgentService({} as any, 'user-1', {
persistenceHandler: handler,
streamEventManager: createSilentStreamManager(),
+ topicModel: {
+ findById,
+ settleRunningStatus: vi.fn(async () => undefined),
+ takeRunningOperation: vi.fn(async () => ({ isRoot: true, operation: {} })),
+ } as any,
});
await service.heteroFinish({
@@ -114,6 +126,11 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
const service = new HeterogeneousAgentService({} as any, 'user-1', {
persistenceHandler: handler,
streamEventManager: createSilentStreamManager(),
+ topicModel: {
+ findById,
+ settleRunningStatus: vi.fn(async () => undefined),
+ takeRunningOperation: vi.fn(async () => ({ isRoot: true, operation: {} })),
+ } as any,
});
await service.heteroFinish({
@@ -166,6 +183,11 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
const service = new HeterogeneousAgentService({} as any, 'user-1', {
persistenceHandler: handler,
streamEventManager: createSilentStreamManager(),
+ topicModel: {
+ findById,
+ settleRunningStatus: vi.fn(async () => undefined),
+ takeRunningOperation: vi.fn(async () => ({ isRoot: true, operation: {} })),
+ } as any,
});
// Simulate: sandbox was recycled, CC exited before emitting system.init
@@ -222,6 +244,11 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
const service = new HeterogeneousAgentService({} as any, 'user-1', {
persistenceHandler: handler,
streamEventManager: createSilentStreamManager(),
+ topicModel: {
+ findById,
+ settleRunningStatus: vi.fn(async () => undefined),
+ takeRunningOperation: vi.fn(async () => ({ isRoot: true, operation: {} })),
+ } as any,
});
await service.heteroFinish({
@@ -282,6 +309,11 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
const service = new HeterogeneousAgentService({} as any, 'user-1', {
persistenceHandler: handler,
streamEventManager: createSilentStreamManager(),
+ topicModel: {
+ findById,
+ settleRunningStatus: vi.fn(async () => undefined),
+ takeRunningOperation: vi.fn(async () => ({ isRoot: true, operation: {} })),
+ } as any,
});
await service.heteroFinish({
@@ -346,6 +378,11 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
const service = new HeterogeneousAgentService({} as any, 'user-1', {
persistenceHandler: handler,
streamEventManager: stream,
+ topicModel: {
+ findById,
+ settleRunningStatus: vi.fn(async () => undefined),
+ takeRunningOperation: vi.fn(async () => ({ isRoot: true, operation: {} })),
+ } as any,
});
// Should not throw — sessionId persistence is best-effort
diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.ts
index e3509b805b2..6afed1caa1b 100644
--- a/apps/server/src/services/heterogeneousAgent/index.ts
+++ b/apps/server/src/services/heterogeneousAgent/index.ts
@@ -282,23 +282,13 @@ export class HeterogeneousAgentService {
topicId,
});
- // Drive the run's lifecycle hooks (onComplete / onError) through the same
- // `hookDispatcher` the normal LLM runtime uses, so the task lifecycle
- // (onTopicComplete → task done/failed) and any IM bot completion callback
- // fire uniformly. The hooks were registered in-memory (local mode) and
- // serialized onto runningOperation (queue mode) at dispatch time.
- //
- // Skip on `cancelled` — heteroFinish may be called twice: first with
- // result=cancelled (termination signal) then with result=success/error
- // (normal process exit). We must NOT clear runningOperation or fire hooks on
- // cancelled so the subsequent success/error call still finds the hooks +
- // assistantMessageId and dispatches exactly once. (cancelled→interrupted is a
- // no-op for the task lifecycle anyway — onTopicComplete has no interrupted
- // branch — and suppresses a spurious bot "stopped" message before the real
- // result lands.)
let serializedHooks: SerializedHook[] | undefined;
let assistantMessageId = seedAssistantMessageId;
let isolationThreadId: string | undefined;
+ let orchestrationRole: 'member' | 'supervisor' | undefined;
+
+ // `cancelled` is only an intermediate process signal. Keep the marker for
+ // the following success/error terminal callback, which owns completion.
if (result !== 'cancelled') {
try {
const settled = await this.topicModel.settleRunningOperation(topicId, operationId);
@@ -316,6 +306,7 @@ export class HeterogeneousAgentService {
if (settled.status === 'settled') {
serializedHooks = settled.hooks as SerializedHook[] | undefined;
isolationThreadId = settled.threadId;
+ orchestrationRole = settled.orchestrationRole;
}
} catch (err) {
log('heteroFinish: failed to settle runningOperation (non-fatal): %O', err);
@@ -323,9 +314,8 @@ export class HeterogeneousAgentService {
}
// Emit a terminal `agent_runtime_end` so renderer subscribers shut down even
- // if the CLI stream missed it (process killed mid-flight, network drop on
- // last batch). A stale finish that conflicts with a newer operation returns
- // above instead of projecting the old terminal state into the active run.
+ // if the CLI stream missed it. A stale callback that belongs to neither the
+ // root operation nor one of its children returns above.
await this.streamEventManager.publishStreamEvent(operationId, {
data: {
agentType,
@@ -338,6 +328,20 @@ export class HeterogeneousAgentService {
type: 'agent_runtime_end',
});
+ // Drive the run's lifecycle hooks (onComplete / onError) through the same
+ // `hookDispatcher` the normal LLM runtime uses, so the task lifecycle
+ // (onTopicComplete → task done/failed) and any IM bot completion callback
+ // fire uniformly. The hooks were registered in-memory (local mode) and
+ // serialized onto runningOperation (queue mode) at dispatch time.
+ //
+ // Skip on `cancelled` — heteroFinish may be called twice: first with
+ // result=cancelled (termination signal) then with result=success/error
+ // (normal process exit). We must NOT clear runningOperation or fire hooks on
+ // cancelled so the subsequent success/error call still finds the hooks +
+ // assistantMessageId and dispatches exactly once. (cancelled→interrupted is a
+ // no-op for the task lifecycle anyway — onTopicComplete has no interrupted
+ // branch — and suppresses a spurious bot "stopped" message before the real
+ // result lands.)
if (result === 'cancelled') return;
// The owning agentId is authoritatively encoded in the operationId
@@ -475,6 +479,7 @@ export class HeterogeneousAgentService {
// Backfilled executed model/provider — the verify gate bails when absent.
model: totals?.model,
operationId,
+ orchestrationRole,
provider: totals?.provider,
serializedHooks,
stepCount: totals?.stepCount ?? null,
diff --git a/packages/database/src/models/__tests__/topic.test.ts b/packages/database/src/models/__tests__/topic.test.ts
index a27f897c3c2..b096e8e0cf4 100644
--- a/packages/database/src/models/__tests__/topic.test.ts
+++ b/packages/database/src/models/__tests__/topic.test.ts
@@ -595,6 +595,7 @@ describe('TopicModel', () => {
expect(settled).toEqual({
assistantMessageId: 'msg-current',
hooks,
+ orchestrationRole: undefined,
status: 'settled',
threadId: 'thread-old',
});
@@ -603,6 +604,54 @@ describe('TopicModel', () => {
expect(row?.status).toBe('unread');
});
+ it('atomically removes only a matching child operation', async () => {
+ const childHooks = [
+ {
+ id: 'hook-child',
+ type: 'onComplete',
+ webhook: { url: '/child-callback' },
+ },
+ ];
+ const topic = await topicModel.create({
+ metadata: {
+ heteroCurrentMsgId: { msgId: 'msg-child-current', operationId: 'op-child' },
+ runningOperation: {
+ assistantMessageId: 'msg-parent',
+ childOperations: [
+ {
+ assistantMessageId: 'msg-child',
+ hooks: childHooks,
+ operationId: 'op-child',
+ orchestrationRole: 'member',
+ threadId: 'thread-child',
+ },
+ ],
+ operationId: 'op-parent',
+ orchestrationRole: 'supervisor',
+ },
+ },
+ title: 'matching child operation',
+ });
+ await topicModel.update(topic.id, { status: 'running' });
+
+ const settled = await topicModel.settleRunningOperation(topic.id, 'op-child');
+
+ expect(settled).toEqual({
+ assistantMessageId: 'msg-child-current',
+ hooks: childHooks,
+ orchestrationRole: 'member',
+ status: 'settled',
+ threadId: 'thread-child',
+ });
+ const row = await topicModel.findById(topic.id);
+ expect(row?.metadata?.runningOperation).toMatchObject({
+ operationId: 'op-parent',
+ orchestrationRole: 'supervisor',
+ });
+ expect(row?.metadata?.runningOperation?.childOperations).toEqual([]);
+ expect(row?.status).toBe('running');
+ });
+
it('does not let an old watchdog settle a newer operation', async () => {
const topic = await topicModel.create({
metadata: {
diff --git a/packages/database/src/models/__tests__/topics/topic.update.test.ts b/packages/database/src/models/__tests__/topics/topic.update.test.ts
index b09cd2474a9..3c0f29ada53 100644
--- a/packages/database/src/models/__tests__/topics/topic.update.test.ts
+++ b/packages/database/src/models/__tests__/topics/topic.update.test.ts
@@ -185,10 +185,10 @@ describe('TopicModel - Update', () => {
});
await expect(
- topicModel.tryReserveTaskCallback(topicId, 'new-start', 'different-operation'),
+ topicModel.tryReserveTaskCallback(topicId, 'new-start', undefined, 'different-operation'),
).resolves.toBe(false);
await expect(
- topicModel.tryReserveTaskCallback(topicId, 'new-start', 'old-operation'),
+ topicModel.tryReserveTaskCallback(topicId, 'new-start', undefined, 'old-operation'),
).resolves.toBe(true);
const topic = await serverDB.query.topics.findFirst({ where: eq(topics.id, topicId) });
@@ -196,6 +196,141 @@ describe('TopicModel - Update', () => {
expect(topic?.metadata?.taskCallbackReservation?.messageId).toBe('new-start');
});
+ it('allows a child operation to re-enter its parent running operation', async () => {
+ const topicId = 'task-callback-parent-operation';
+ await serverDB.insert(topics).values({
+ userId,
+ id: topicId,
+ title: 'Test',
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'assistant-parent',
+ operationId: 'operation-parent',
+ },
+ },
+ });
+
+ await expect(
+ topicModel.tryReserveTaskCallback(topicId, 'child-operation-1', 'operation-parent'),
+ ).resolves.toBe(true);
+ await expect(
+ topicModel.tryReserveTaskCallback(topicId, 'child-operation-2', 'operation-parent'),
+ ).resolves.toBe(true);
+ await expect(
+ topicModel.tryReserveTaskCallback(topicId, 'unrelated-operation', 'operation-other'),
+ ).resolves.toBe(false);
+
+ const topic = await topicModel.findById(topicId);
+ expect(topic?.metadata?.taskCallbackReservation).toBeUndefined();
+ expect(topic?.metadata?.runningOperation?.operationId).toBe('operation-parent');
+ });
+
+ it('atomically appends children to the parent running operation', async () => {
+ const topicId = 'task-callback-parent-operation-children';
+ await serverDB.insert(topics).values({
+ userId,
+ id: topicId,
+ title: 'Test',
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'assistant-parent',
+ operationId: 'parent-operation',
+ },
+ },
+ });
+
+ await Promise.all([
+ topicModel.appendRunningOperationChild(topicId, 'parent-operation', {
+ assistantMessageId: 'assistant-child-1',
+ operationId: 'child-operation-1',
+ }),
+ topicModel.appendRunningOperationChild(topicId, 'parent-operation', {
+ assistantMessageId: 'assistant-child-2',
+ operationId: 'child-operation-2',
+ }),
+ ]);
+
+ const topic = await topicModel.findById(topicId);
+ expect(topic?.metadata?.runningOperation?.childOperations).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ operationId: 'child-operation-1' }),
+ expect.objectContaining({ operationId: 'child-operation-2' }),
+ ]),
+ );
+ });
+
+ it('atomically takes a child running operation once', async () => {
+ const topicId = 'task-callback-take-child-operation';
+ await serverDB.insert(topics).values({
+ userId,
+ id: topicId,
+ title: 'Test',
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'assistant-parent',
+ childOperations: [
+ { assistantMessageId: 'assistant-child', operationId: 'child-operation' },
+ ],
+ operationId: 'parent-operation',
+ },
+ },
+ });
+
+ const claims = await Promise.all([
+ topicModel.takeRunningOperation(topicId, 'child-operation'),
+ topicModel.takeRunningOperation(topicId, 'child-operation'),
+ ]);
+
+ expect(claims.filter(Boolean)).toHaveLength(1);
+ expect(claims.find(Boolean)).toMatchObject({
+ isRoot: false,
+ operation: { operationId: 'child-operation' },
+ });
+ const topic = await topicModel.findById(topicId);
+ expect(topic?.metadata?.runningOperation).toMatchObject({ operationId: 'parent-operation' });
+ expect(topic?.metadata?.runningOperation?.childOperations).toEqual([]);
+ });
+
+ it('updates only the matching child assistant message pointer', async () => {
+ const topicId = 'task-callback-update-child-message';
+ await serverDB.insert(topics).values({
+ id: topicId,
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'assistant-parent',
+ childOperations: [
+ { assistantMessageId: 'assistant-child-1', operationId: 'child-operation-1' },
+ { assistantMessageId: 'assistant-child-2', operationId: 'child-operation-2' },
+ ],
+ operationId: 'parent-operation',
+ },
+ },
+ title: 'Test',
+ userId,
+ });
+
+ await expect(
+ topicModel.updateRunningOperationAssistantMessage(
+ topicId,
+ 'child-operation-1',
+ 'assistant-child-1-next',
+ ),
+ ).resolves.toBe(true);
+
+ const topic = await topicModel.findById(topicId);
+ expect(topic?.metadata?.runningOperation).toMatchObject({
+ assistantMessageId: 'assistant-parent',
+ childOperations: [
+ { assistantMessageId: 'assistant-child-1-next', operationId: 'child-operation-1' },
+ { assistantMessageId: 'assistant-child-2', operationId: 'child-operation-2' },
+ ],
+ });
+ expect(topic?.metadata?.heteroCurrentMsgId).toEqual({
+ msgId: 'assistant-child-1-next',
+ operationId: 'child-operation-1',
+ });
+ });
+
it('recovers a stale reservation left by a crashed delivery worker', async () => {
const topicId = 'task-callback-stale-reservation';
await serverDB.insert(topics).values({
diff --git a/packages/database/src/models/session.ts b/packages/database/src/models/session.ts
index 0d912bfb0bd..3f51efdbda3 100644
--- a/packages/database/src/models/session.ts
+++ b/packages/database/src/models/session.ts
@@ -621,13 +621,14 @@ export class SessionModel {
});
// Filter and map results, ensuring valid session associations
- return (
- results
- .filter((item) => item.agentsToSessions && item.agentsToSessions.length > 0)
- // @ts-expect-error
- .map((item) => item.agentsToSessions[0].session)
- .filter((session) => session !== null && session !== undefined)
- );
+ return results
+ .filter((item) => item.agentsToSessions && item.agentsToSessions.length > 0)
+ .map(
+ (item) =>
+ (item.agentsToSessions as Array<{ session: SessionItem | null | undefined }>)[0]
+ ?.session,
+ )
+ .filter((session) => session !== null && session !== undefined);
} catch (e) {
console.error('findSessionsByKeywords error:', e, { keyword });
return [];
diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.ts
index a7c43f71673..00d89a00eb9 100644
--- a/packages/database/src/models/topic.ts
+++ b/packages/database/src/models/topic.ts
@@ -1326,20 +1326,31 @@ export class TopicModel {
status: 'missing' as const,
};
}
- if (runningOperation.operationId !== operationId) {
+ const isRoot = runningOperation.operationId === operationId;
+ const operation = isRoot
+ ? runningOperation
+ : runningOperation.childOperations?.find((child) => child.operationId === operationId);
+ if (!operation) {
return { activeOperationId: runningOperation.operationId, status: 'conflict' as const };
}
const metadata = {
...existing.metadata,
- runningOperation: null,
+ runningOperation: isRoot
+ ? null
+ : {
+ ...runningOperation,
+ childOperations: runningOperation.childOperations?.filter(
+ (child) => child.operationId !== operationId,
+ ),
+ },
} as ChatTopicMetadata;
await tx
.update(topics)
.set({
metadata,
- ...(existing.status === 'running' ? { status: 'unread' as const } : {}),
+ ...(isRoot && existing.status === 'running' ? { status: 'unread' as const } : {}),
updatedAt: new Date(),
})
.where(and(eq(topics.id, id), this.ownership()));
@@ -1349,10 +1360,11 @@ export class TopicModel {
assistantMessageId:
currentMessage?.operationId === operationId
? currentMessage.msgId
- : runningOperation.assistantMessageId,
- hooks: runningOperation.hooks,
+ : operation.assistantMessageId,
+ hooks: operation.hooks,
+ orchestrationRole: operation.orchestrationRole,
status: 'settled' as const,
- threadId: runningOperation.threadId ?? undefined,
+ threadId: operation.threadId ?? undefined,
};
});
};
@@ -1477,6 +1489,163 @@ export class TopicModel {
});
};
+ appendRunningOperationChild = async (
+ id: string,
+ parentOperationId: string,
+ child: NonNullable<ChatTopicMetadata['runningOperation']>,
+ ): Promise<boolean> =>
+ this.db.transaction(async (tx) => {
+ const [existing] = await tx
+ .select({ metadata: topics.metadata })
+ .from(topics)
+ .where(and(eq(topics.id, id), this.ownership()))
+ .for('update');
+ const runningOperation = existing?.metadata?.runningOperation;
+ if (!existing || runningOperation?.operationId !== parentOperationId) return false;
+
+ await tx
+ .update(topics)
+ .set({
+ metadata: {
+ ...existing.metadata,
+ runningOperation: {
+ ...runningOperation,
+ childOperations: [
+ ...(runningOperation.childOperations ?? []).filter(
+ (operation) => operation.operationId !== child.operationId,
+ ),
+ child,
+ ],
+ },
+ },
+ })
+ .where(and(eq(topics.id, id), this.ownership()));
+ return true;
+ });
+
+ removeRunningOperationChild = async (id: string, operationId: string): Promise<boolean> =>
+ this.db.transaction(async (tx) => {
+ const [existing] = await tx
+ .select({ metadata: topics.metadata })
+ .from(topics)
+ .where(and(eq(topics.id, id), this.ownership()))
+ .for('update');
+ const runningOperation = existing?.metadata?.runningOperation;
+ if (!existing || !runningOperation?.childOperations) return false;
+ await tx
+ .update(topics)
+ .set({
+ metadata: {
+ ...existing.metadata,
+ runningOperation: {
+ ...runningOperation,
+ childOperations: runningOperation.childOperations.filter(
+ (child) => child.operationId !== operationId,
+ ),
+ },
+ },
+ })
+ .where(and(eq(topics.id, id), this.ownership()));
+ return true;
+ });
+
+ updateRunningOperationAssistantMessage = async (
+ id: string,
+ operationId: string,
+ assistantMessageId: string,
+ ): Promise<boolean> =>
+ this.db.transaction(async (tx) => {
+ const [existing] = await tx
+ .select({ metadata: topics.metadata })
+ .from(topics)
+ .where(and(eq(topics.id, id), this.ownership()))
+ .for('update');
+ const runningOperation = existing?.metadata?.runningOperation;
+ if (!existing || !runningOperation) return false;
+
+ if (runningOperation.operationId === operationId) {
+ await tx
+ .update(topics)
+ .set({
+ metadata: {
+ ...existing.metadata,
+ heteroCurrentMsgId: { msgId: assistantMessageId, operationId },
+ runningOperation: { ...runningOperation, assistantMessageId },
+ },
+ })
+ .where(and(eq(topics.id, id), this.ownership()));
+ return true;
+ }
+
+ const childOperations = runningOperation.childOperations?.map((child) =>
+ child.operationId === operationId ? { ...child, assistantMessageId } : child,
+ );
+ if (!childOperations?.some((child) => child.operationId === operationId)) return false;
+
+ await tx
+ .update(topics)
+ .set({
+ metadata: {
+ ...existing.metadata,
+ heteroCurrentMsgId: { msgId: assistantMessageId, operationId },
+ runningOperation: { ...runningOperation, childOperations },
+ },
+ })
+ .where(and(eq(topics.id, id), this.ownership()));
+ return true;
+ });
+
+ takeRunningOperation = async (
+ id: string,
+ operationId: string,
+ ): Promise<
+ | {
+ isRoot: boolean;
+ operation: NonNullable<ChatTopicMetadata['runningOperation']>;
+ }
+ | undefined
+ > =>
+ this.db.transaction(async (tx) => {
+ const [existing] = await tx
+ .select({ metadata: topics.metadata })
+ .from(topics)
+ .where(and(eq(topics.id, id), this.ownership()))
+ .for('update');
+ const runningOperation = existing?.metadata?.runningOperation;
+ if (!existing || !runningOperation) return undefined;
+
+ if (runningOperation.operationId === operationId) {
+ await tx
+ .update(topics)
+ .set({
+ metadata: { ...existing.metadata, runningOperation: null },
+ })
+ .where(and(eq(topics.id, id), this.ownership()));
+ return { isRoot: true, operation: runningOperation };
+ }
+
+ const child = runningOperation.childOperations?.find(
+ (candidate) => candidate.operationId === operationId,
+ );
+ if (!child) return undefined;
+
+ await tx
+ .update(topics)
+ .set({
+ metadata: {
+ ...existing.metadata,
+ runningOperation: {
+ ...runningOperation,
+ childOperations: runningOperation.childOperations?.filter(
+ (candidate) => candidate.operationId !== operationId,
+ ),
+ },
+ },
+ })
+ .where(and(eq(topics.id, id), this.ownership()));
+ return { isRoot: false, operation: child };
+ });
+
/**
* Atomically reserve an idle topic for one task-callback delivery.
*
@@ -1489,6 +1658,7 @@ export class TopicModel {
tryReserveTaskCallback = async (
id: string,
messageId: string,
+ allowRunningOperationId?: string,
replacesOperationId?: string,
): Promise<boolean | null> =>
this.db.transaction(async (tx) => {
@@ -1509,6 +1679,9 @@ export class TopicModel {
if (reservation?.messageId === messageId && hasLiveReservation) return true;
const runningOperation = existing.metadata?.runningOperation;
+ const ownedRunningOperation =
+ !!allowRunningOperationId && runningOperation?.operationId === allowRunningOperationId;
+ if (allowRunningOperationId) return ownedRunningOperation;
const canReplaceRunningOperation =
!!replacesOperationId && runningOperation?.operationId === replacesOperationId;
if ((runningOperation && !canReplaceRunningOperation) || hasLiveReservation) return false;
diff --git a/packages/types/src/topic/topic.test.ts b/packages/types/src/topic/topic.test.ts
index 87ba9c9db11..a4659767dfe 100644
--- a/packages/types/src/topic/topic.test.ts
+++ b/packages/types/src/topic/topic.test.ts
@@ -38,6 +38,25 @@ describe('chatTopicMetadataUpdateSchema', () => {
expect(chatTopicMetadataUpdateSchema.parse(metadata)).toEqual(metadata);
});
+ it('preserves orchestration roles on running operations', () => {
+ const metadata = {
+ runningOperation: {
+ assistantMessageId: 'assistant-supervisor',
+ childOperations: [
+ {
+ assistantMessageId: 'assistant-member',
+ operationId: 'operation-member',
+ orchestrationRole: 'member' as const,
+ },
+ ],
+ operationId: 'operation-supervisor',
+ orchestrationRole: 'supervisor' as const,
+ },
+ };
+
+ expect(chatTopicMetadataUpdateSchema.parse(metadata)).toEqual(metadata);
+ });
+
it('rejects a delayed start with no user message — the persisted turn IS the prompt', () => {
const result = chatTopicMetadataUpdateSchema.safeParse({
scheduledRun: {
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index 2587ba392ea..992086446ad 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -214,6 +214,18 @@ export interface ChatTopicMetadata {
*/
runningOperation?: {
assistantMessageId: string;
+ childOperations?: Array<{
+ assistantMessageId: string;
+ deviceId?: string;
+ deviceUserId?: string;
+ deviceWorkspaceId?: string;
+ heteroType?: string;
+ hooks?: SerializedAgentHook[];
+ operationId: string;
+ orchestrationRole?: 'supervisor' | 'member';
+ scope?: string;
+ threadId?: string | null;
+ }>;
/** Device selected for a notify-based platform task. */
deviceId?: string;
/** Personal-device owner used to route dispatch and cancellation through the same principal. */
@@ -238,6 +250,7 @@ export interface ChatTopicMetadata {
*/
hooks?: SerializedAgentHook[];
operationId: string;
+ orchestrationRole?: 'supervisor' | 'member';
scope?: string;
threadId?: string | null;
} | null;
@@ -476,12 +489,29 @@ export const chatTopicMetadataUpdateSchema = z.object({
runningOperation: z
.object({
assistantMessageId: z.string(),
+ childOperations: z
+ .array(
+ z.object({
+ assistantMessageId: z.string(),
+ deviceId: z.string().optional(),
+ deviceUserId: z.string().optional(),
+ deviceWorkspaceId: z.string().optional(),
+ heteroType: z.string().optional(),
+ hooks: z.array(serializedAgentHookSchema).optional(),
+ operationId: z.string(),
+ orchestrationRole: z.enum(['supervisor', 'member']).optional(),
+ scope: z.string().optional(),
+ threadId: z.string().nullish(),
+ }),
+ )
+ .optional(),
deviceId: z.string().optional(),
deviceUserId: z.string().optional(),
deviceWorkspaceId: z.string().optional(),
heteroType: z.string().optional(),
hooks: z.array(serializedAgentHookSchema).optional(),
operationId: z.string(),
+ orchestrationRole: z.enum(['supervisor', 'member']).optional(),
scope: z.string().optional(),
threadId: z.string().nullish(),
})