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(hetero): keep a Claude Code sub-agent's thread, stop route and session (#23763)

AmAzing-e54d6e87b956
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.codexDeviceRuntime.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.codexDeviceRuntime.test.ts
index 0cb60cf1077..bae21372639 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.codexDeviceRuntime.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.codexDeviceRuntime.test.ts
@@ -199,6 +199,7 @@ vi.mock('@/server/services/heterogeneousAgent', () => ({
HeterogeneousAgentService: vi.fn().mockImplementation(function () {
return {
getHeterogeneousResumeSessionId: mockGetHeterogeneousResumeSessionId,
+ getThreadResumeSessionId: vi.fn().mockResolvedValue(undefined),
};
}),
}));
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroComposerUserMessage.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroComposerUserMessage.test.ts
index e515ab32ff3..d3277b40f9f 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroComposerUserMessage.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroComposerUserMessage.test.ts
@@ -193,6 +193,7 @@ vi.mock('@/server/services/heterogeneousAgent', () => ({
HeterogeneousAgentService: vi.fn().mockImplementation(function () {
return {
getHeterogeneousResumeSessionId: mockGetHeterogeneousResumeSessionId,
+ getThreadResumeSessionId: vi.fn().mockResolvedValue(undefined),
};
}),
}));
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 d6ba3bf81a5..6fc65804042 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
@@ -194,6 +194,7 @@ vi.mock('@/server/services/heterogeneousAgent', () => ({
HeterogeneousAgentService: vi.fn().mockImplementation(function () {
return {
getHeterogeneousResumeSessionId: mockGetHeterogeneousResumeSessionId,
+ getThreadResumeSessionId: vi.fn().mockResolvedValue(undefined),
};
}),
}));
@@ -2364,8 +2365,7 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>
await service.execAgent(isolatedChildInput() as any);
- // Otherwise this child would never be recognized by
- // heteroIngest/heteroFinish at all.
+ // Otherwise this child would never be recognized by heteroIngest/heteroFinish at all.
expect(findRunningOpSeed()).toBeDefined();
});
});
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroInterruptedResume.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroInterruptedResume.test.ts
index 150ce2e1c71..d6ee1ea1bb1 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroInterruptedResume.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroInterruptedResume.test.ts
@@ -194,6 +194,7 @@ vi.mock('@/server/services/heterogeneousAgent', () => ({
HeterogeneousAgentService: vi.fn().mockImplementation(function () {
return {
getHeterogeneousResumeSessionId: mockGetHeterogeneousResumeSessionId,
+ getThreadResumeSessionId: vi.fn().mockResolvedValue(undefined),
};
}),
}));
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroRunFee.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroRunFee.test.ts
index 2583d528e6d..0ae1c1da5b9 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroRunFee.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroRunFee.test.ts
@@ -182,6 +182,7 @@ vi.mock('@/server/services/heterogeneousAgent', () => ({
HeterogeneousAgentService: vi.fn().mockImplementation(function () {
return {
getHeterogeneousResumeSessionId: mockGetHeterogeneousResumeSessionId,
+ getThreadResumeSessionId: vi.fn().mockResolvedValue(undefined),
};
}),
}));
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroViewedTask.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroViewedTask.test.ts
index ac40a86c2e1..bef42b3a05b 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroViewedTask.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroViewedTask.test.ts
@@ -194,6 +194,7 @@ vi.mock('@/server/services/heterogeneousAgent', () => ({
HeterogeneousAgentService: vi.fn().mockImplementation(function () {
return {
getHeterogeneousResumeSessionId: mockGetHeterogeneousResumeSessionId,
+ getThreadResumeSessionId: vi.fn().mockResolvedValue(undefined),
};
}),
}));
diff --git a/apps/server/src/services/aiAgent/hooks/__tests__/threadRunHooks.test.ts b/apps/server/src/services/aiAgent/hooks/__tests__/threadRunHooks.test.ts
index b8a8936f265..17af95c6ee7 100644
--- a/apps/server/src/services/aiAgent/hooks/__tests__/threadRunHooks.test.ts
+++ b/apps/server/src/services/aiAgent/hooks/__tests__/threadRunHooks.test.ts
@@ -32,9 +32,15 @@ describe('createThreadHooks thread-completion', () => {
operationId: 'child-op',
};
- const runCompletion = async (options?: { updateSourceMessage?: boolean }) => {
+ const runCompletion = async (
+ options?: { updateSourceMessage?: boolean },
+ liveMetadata?: Record<string, unknown>,
+ ) => {
const messageModel = { update: vi.fn().mockResolvedValue(undefined) };
- const threadModel = { update: vi.fn().mockResolvedValue(undefined) };
+ const threadModel = {
+ findById: vi.fn().mockResolvedValue(liveMetadata ? { metadata: liveMetadata } : undefined),
+ update: vi.fn().mockResolvedValue(undefined),
+ };
const hooks = createThreadHooks(
{} as any,
threadModel as any,
@@ -79,4 +85,18 @@ describe('createThreadHooks thread-completion', () => {
}),
);
});
+
+ // An external sub-agent binds its native session to the thread while it
+ // runs; a run ended by the watchdog never reaches heteroFinish, so this
+ // write must not put back the session the run was claimed with.
+ it('keeps the live external-agent session instead of the claim-time one', async () => {
+ const { threadModel } = await runCompletion(undefined, { heteroSessionId: 'cc-live' });
+
+ expect(threadModel.update).toHaveBeenCalledWith(
+ 'thread-1',
+ expect.objectContaining({
+ metadata: expect.objectContaining({ heteroSessionId: 'cc-live' }),
+ }),
+ );
+ });
});
diff --git a/apps/server/src/services/aiAgent/hooks/threadRunHooks.ts b/apps/server/src/services/aiAgent/hooks/threadRunHooks.ts
index 98340c7035f..c490cadcf8d 100644
--- a/apps/server/src/services/aiAgent/hooks/threadRunHooks.ts
+++ b/apps/server/src/services/aiAgent/hooks/threadRunHooks.ts
@@ -28,11 +28,13 @@ export function calculateTotalTokens(usage?: AgentState['usage']): number | unde
* What a thread's metadata carries from one write and one run to the next.
* Every thread write replaces `metadata`, so each writer spreads these back
* in: the tool call that spawned the thread (how the UI tells a sub-agent
- * from an ordinary thread), and the usage of earlier runs, which a follow-up
- * run adds its own usage on top of.
+ * from an ordinary thread), the usage of earlier runs, which a follow-up
+ * run adds its own usage on top of, and an external agent's native session,
+ * which a follow-up resumes.
*/
export type ThreadCarryOver = Pick<
ThreadMetadata,
+ | 'heteroSessionId'
| 'runUsageBaseline'
| 'sourceToolCallId'
| 'totalCost'
@@ -43,6 +45,7 @@ export type ThreadCarryOver = Pick<
>;
export const pickThreadCarryOver = (metadata?: ThreadMetadata | null): ThreadCarryOver => ({
+ heteroSessionId: metadata?.heteroSessionId,
runUsageBaseline: {
totalCost: metadata?.totalCost,
totalLlmCalls: metadata?.totalLlmCalls,
@@ -57,6 +60,20 @@ export const pickThreadCarryOver = (metadata?: ThreadMetadata | null): ThreadCar
totalToolCalls: metadata?.totalToolCalls,
});
+/** Best-effort read of the native session an external agent bound to the thread. */
+const readLiveHeteroSessionId = async (
+ threadModel: ThreadModel,
+ threadId: string,
+): Promise<string | undefined> => {
+ try {
+ const metadata = (await threadModel.findById(threadId))?.metadata as ThreadMetadata | null;
+ return metadata?.heteroSessionId;
+ } catch (error) {
+ log('reading the live session of thread %s failed: %O', threadId, error);
+ return undefined;
+ }
+};
+
const addUsage = (baseline?: number, run?: number): number | undefined =>
baseline === undefined ? run : baseline + (run ?? 0);
@@ -225,6 +242,7 @@ export function createThreadHooks(
try {
await threadModel.update(threadId, {
metadata: {
+ heteroSessionId: carryOver.heteroSessionId,
operationId: event.operationId,
sourceToolCallId: carryOver.sourceToolCallId,
startedAt,
@@ -299,12 +317,17 @@ export function createThreadHooks(
}
const formattedError = formatErrorForMetadata(finalState.error);
+ // An external agent records its native session on the thread while it
+ // runs; the claim-time copy predates it. Keep the live one, or a run
+ // ended without `heteroFinish` (watchdog abandon) loses its resume.
+ const liveSessionId = await readLiveHeteroSessionId(threadModel, threadId);
await threadModel.update(threadId, {
metadata: {
completedAt,
duration,
error: formattedError,
+ heteroSessionId: liveSessionId ?? carryOver.heteroSessionId,
operationId: finalState.operationId,
sourceToolCallId: carryOver.sourceToolCallId,
startedAt,
diff --git a/apps/server/src/services/aiAgent/intervention/InterventionController.test.ts b/apps/server/src/services/aiAgent/intervention/InterventionController.test.ts
index b7ef461ae16..990421d4c8a 100644
--- a/apps/server/src/services/aiAgent/intervention/InterventionController.test.ts
+++ b/apps/server/src/services/aiAgent/intervention/InterventionController.test.ts
@@ -100,4 +100,36 @@ describe('InterventionController.interruptTask', () => {
expect(consoleError).toHaveBeenCalled();
consoleError.mockRestore();
});
+
+ // A background sub-agent outlives its parent's marker entry; its own
+ // operation row still names the device.
+ it('stops a device run the topic marker no longer lists, from its operation row', async () => {
+ executeToolCall.mockResolvedValue({ state: { exited: true }, success: true });
+ const { controller, deps } = createController();
+ deps.topicModel.findById.mockResolvedValue({ id: TOPIC_ID, metadata: {} } as any);
+ deps.agentOperationModel.findById.mockResolvedValue({
+ createdAt: new Date(),
+ id: OPERATION_ID,
+ metadata: {
+ heteroDeviceRoute: {
+ deviceId: 'device_1',
+ deviceUserId: 'user_1',
+ heteroType: 'claude-code',
+ },
+ },
+ topicId: TOPIC_ID,
+ } as any);
+
+ const result = await controller.interruptTask({ operationId: OPERATION_ID });
+
+ expect(executeToolCall).toHaveBeenCalledWith(
+ expect.objectContaining({ deviceId: 'device_1', userId: 'user_1' }),
+ expect.objectContaining({
+ apiName: 'cancelHeteroTask',
+ arguments: JSON.stringify({ signal: 'SIGINT', taskId: OPERATION_ID }),
+ }),
+ 10_000,
+ );
+ expect(result).toMatchObject({ deviceCancellationConfirmed: true, success: true });
+ });
});
diff --git a/apps/server/src/services/aiAgent/intervention/InterventionController.ts b/apps/server/src/services/aiAgent/intervention/InterventionController.ts
index ec8e4fe3273..cc72ec86c2e 100644
--- a/apps/server/src/services/aiAgent/intervention/InterventionController.ts
+++ b/apps/server/src/services/aiAgent/intervention/InterventionController.ts
@@ -22,6 +22,7 @@ import type { AgentRuntimeService } from '@/server/services/agentRuntime';
import { deviceGateway } from '@/server/services/deviceGateway';
import { STOPPED_TOOL_CONTENT } from '../helpers/agentFactory';
+import { readHeteroDeviceRoute } from '../pipeline/heteroDispatch/deviceRoute';
import { releaseHeteroSteers } from '../steerQueue/hetero';
const log = debug('lobe-server:ai-agent-service');
@@ -144,9 +145,19 @@ export class InterventionController {
// bot/messenger stop). Recover it from the owner-scoped operation row so
// device cancellation is symmetric across every caller.
let resolvedTopicId = topicId;
+ let operationRow: Awaited<ReturnType<AgentOperationModel['findById']>> | undefined;
+ // Best-effort: without the row there is just no topic or device route to use.
+ const readOperationRow = async () => {
+ operationRow ??= await this.deps.agentOperationModel
+ .findById(resolvedOperationId!)
+ .catch((error: unknown) => {
+ log('interruptTask: reading operation %s failed: %O', resolvedOperationId, error);
+ return undefined;
+ });
+ return operationRow;
+ };
if (!resolvedTopicId) {
- const operation = await this.deps.agentOperationModel.findById(resolvedOperationId);
- resolvedTopicId = operation?.topicId ?? undefined;
+ resolvedTopicId = (await readOperationRow())?.topicId ?? undefined;
}
// 2. Cancel a device-hosted hetero process if applicable.
@@ -171,10 +182,14 @@ export class InterventionController {
}>;
}
| undefined;
+ // A background sub-agent outlives its parent's marker entry; its own
+ // operation row keeps the device route.
const targetOperation =
- runningOp?.operationId === resolvedOperationId
+ (runningOp?.operationId === resolvedOperationId
? runningOp
- : runningOp?.childOperations?.find((child) => child.operationId === resolvedOperationId);
+ : runningOp?.childOperations?.find(
+ (child) => child.operationId === resolvedOperationId,
+ )) ?? readHeteroDeviceRoute((await readOperationRow())?.metadata);
if (
targetOperation?.deviceId &&
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts
index ea1fc3656b0..36f841fd4d5 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts
@@ -29,6 +29,7 @@ import type { ExecRunContext } from '../../types';
import { selectCodexDeviceDispatch } from '../codexDeviceRuntime';
import { traceHeteroStage } from '../sendTracing';
import { forDeviceRuntime } from './codexCollaboration';
+import { recordHeteroDeviceRoute } from './deviceRoute';
import type { PreparedHeteroRun } from './prepare';
import { scheduleTimedOutDispatchConfirmation } from './timeoutConfirmation';
import type { HeteroDispatchDeps, HeteroDispatchInput, HeteroRun } from './types';
@@ -389,6 +390,16 @@ export const dispatchToCliDevice = async (
heteroType,
}),
);
+ // A background sub-agent outlives its parent's marker; keep the route
+ // where a later Stop can still find it.
+ if (dispatchDeviceId) {
+ await recordHeteroDeviceRoute(deps, operationId, {
+ deviceId: dispatchDeviceId,
+ deviceUserId: deps.userId,
+ deviceWorkspaceId: dispatchWorkspaceId,
+ heteroType,
+ });
+ }
log(
'execAgent: patch runningOperation device info=%s deviceId=%s heteroType=%s op=%s',
patched,
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/deviceRoute.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/deviceRoute.ts
new file mode 100644
index 00000000000..ff56a6f6783
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/deviceRoute.ts
@@ -0,0 +1,48 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import debug from 'debug';
+
+import { AgentOperationModel } from '@/database/models/agentOperation';
+
+const log = debug('lobe-server:ai-agent-service');
+
+/**
+ * Where a device-hosted heterogeneous run's process lives, so a Stop can reach
+ * it. The topic's `runningOperation` marker carries the same route, but a
+ * sub-agent child only appears there while its parent's turn is running: a
+ * background child outlives it, and stopping it must still find the device.
+ * The operation row is that durable copy.
+ */
+export interface HeteroDeviceRoute {
+ deviceId: string;
+ deviceUserId?: string;
+ deviceWorkspaceId?: string;
+ heteroType: string;
+ /** Same shape as a marker entry; the route's own run. */
+ operationId?: string;
+}
+
+const ROUTE_KEY = 'heteroDeviceRoute';
+
+/** Record the route on the operation row. Never throws. */
+export const recordHeteroDeviceRoute = async (
+ scope: { db: LobeChatDatabase; userId: string; workspaceId?: string },
+ operationId: string,
+ route: HeteroDeviceRoute,
+): Promise<void> => {
+ try {
+ await new AgentOperationModel(scope.db, scope.userId, scope.workspaceId).mergeMetadata(
+ operationId,
+ { [ROUTE_KEY]: route },
+ );
+ } catch (error) {
+ log('recordHeteroDeviceRoute: op=%s failed: %O', operationId, error);
+ }
+};
+
+/** The route recorded on an operation row's metadata, when there is one. */
+export const readHeteroDeviceRoute = (metadata: unknown): HeteroDeviceRoute | undefined => {
+ const route = (metadata as Record<string, unknown> | null | undefined)?.[ROUTE_KEY] as
+ Partial<HeteroDeviceRoute> | undefined;
+ if (typeof route?.deviceId !== 'string' || typeof route.heteroType !== 'string') return;
+ return route as HeteroDeviceRoute;
+};
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts
index 19e086368e5..8abf5914dc1 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts
@@ -52,7 +52,10 @@ vi.mock('@/server/services/agentRuntime/hooks', () => ({
vi.mock('@/server/services/heterogeneousAgent', () => ({
HeterogeneousAgentService: vi.fn().mockImplementation(function () {
- return { getHeterogeneousResumeSessionId: vi.fn().mockResolvedValue(undefined) };
+ return {
+ getHeterogeneousResumeSessionId: vi.fn().mockResolvedValue(undefined),
+ getThreadResumeSessionId: vi.fn().mockResolvedValue(undefined),
+ };
}),
}));
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.deferredDispatch.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.deferredDispatch.test.ts
index 9b89b75d0d3..6c2d5d04812 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.deferredDispatch.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.deferredDispatch.test.ts
@@ -83,7 +83,10 @@ vi.mock('@/server/services/agentRuntime/hooks', () => ({
vi.mock('@/server/services/heterogeneousAgent', () => ({
HeterogeneousAgentService: vi.fn().mockImplementation(function () {
- return { getHeterogeneousResumeSessionId: vi.fn().mockResolvedValue(undefined) };
+ return {
+ getHeterogeneousResumeSessionId: vi.fn().mockResolvedValue(undefined),
+ getThreadResumeSessionId: vi.fn().mockResolvedValue(undefined),
+ };
}),
}));
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.ts
index 051e32393a8..116e2fcbdde 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.ts
@@ -19,6 +19,7 @@ import type { ExecRunContext } from '../../types';
import { traceHeteroStage } from '../sendTracing';
import { isDeferredHeteroDispatchEnabled, shouldDeferHeteroDispatch } from './deferDispatchGate';
import { deferCliDeviceDispatch, dispatchToCliDevice, dispatchToWakingCliDevice } from './device';
+import { recordHeteroDeviceRoute } from './deviceRoute';
import { prepareHeteroRun } from './prepare';
import { dispatchToPlatformDevice } from './remote';
import { resolveHeteroRouting } from './routing';
@@ -233,6 +234,16 @@ const dispatchHeteroAgentImpl = async (
scope: appContext?.scope ?? undefined,
threadId: appContext?.threadId ?? undefined,
};
+ // A sub-agent child is only in the marker while its parent's turn runs;
+ // keep the device route on its own row for a Stop that comes later.
+ if (appContext?.isolationThread && childOperation.deviceId) {
+ await recordHeteroDeviceRoute(deps, operationId, {
+ deviceId: childOperation.deviceId,
+ deviceUserId: childOperation.deviceUserId,
+ deviceWorkspaceId: childOperation.deviceWorkspaceId,
+ heteroType,
+ });
+ }
if (topicStartOwnerOperationId) {
const attached = await traceHeteroStage('running_marker', () =>
deps.topicModel.appendRunningOperationChild(
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.parallelReads.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.parallelReads.test.ts
index 4ebc1b029d5..2805ba5de2d 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.parallelReads.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.parallelReads.test.ts
@@ -36,6 +36,7 @@ const mocks = vi.hoisted(() => {
gated,
getFullFileUrl: vi.fn(),
getResumeSessionId: vi.fn(),
+ getThreadResumeSessionId: vi.fn(),
reset: () => {
started.length = 0;
spans.ended.length = 0;
@@ -61,7 +62,10 @@ vi.mock('@lobechat/observability-otel/modules/agent-runtime', () => ({
vi.mock('@/server/services/heterogeneousAgent', () => ({
HeterogeneousAgentService: vi.fn().mockImplementation(function () {
- return { getHeterogeneousResumeSessionId: mocks.getResumeSessionId };
+ return {
+ getHeterogeneousResumeSessionId: mocks.getResumeSessionId,
+ getThreadResumeSessionId: mocks.getThreadResumeSessionId,
+ };
}),
}));
@@ -187,6 +191,46 @@ describe('prepareHeteroRun β€” overlapping reads', () => {
expect(mocks.spans.failed).toEqual([]);
});
+ // A sub-agent resumes its own session, never the topic's.
+ it('resumes a sub-agent run from its isolation thread', async () => {
+ const { deps } = createDeps();
+ mocks.getThreadResumeSessionId.mockImplementation(
+ mocks.gated('resume_session', () => 'cc-thread-sess'),
+ );
+
+ const prepared = await prepareHeteroRun(
+ deps,
+ { ...ctx, appContext: { isolationThread: true, threadId: 'thread-1' } },
+ input,
+ 'op-1',
+ );
+
+ expect(mocks.getThreadResumeSessionId).toHaveBeenCalledWith('thread-1', 'topic-1');
+ expect(mocks.getResumeSessionId).not.toHaveBeenCalled();
+ expect(prepared.resumeSessionId).toBe('cc-thread-sess');
+ });
+
+ // A message the user sends in that thread later is an ordinary run: it has
+ // the thread but not the spawn-time `isolationThread` flag. It still writes
+ // its session to the thread, so it has to read it from there too.
+ it('resumes a later message in the sub-agent thread from that thread', async () => {
+ const { deps } = createDeps();
+ mocks.getThreadResumeSessionId.mockImplementation(
+ mocks.gated('resume_session', () => 'cc-thread-sess'),
+ );
+
+ const prepared = await prepareHeteroRun(
+ deps,
+ { ...ctx, appContext: { threadId: 'thread-1' } },
+ input,
+ 'op-1',
+ );
+
+ expect(mocks.getThreadResumeSessionId).toHaveBeenCalledWith('thread-1', 'topic-1');
+ expect(mocks.getResumeSessionId).not.toHaveBeenCalled();
+ expect(prepared.resumeSessionId).toBe('cc-thread-sess');
+ });
+
it('keeps the best-effort reads best-effort when they fail', async () => {
const { deps, messageModel, topicModel } = createDeps();
deps.getMarketService.mockRejectedValue(new Error('market down'));
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts
index 80de2a4277e..082e2a4751d 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts
@@ -194,8 +194,14 @@ export const prepareHeteroRun = async (
const githubTokenPromise = traceHeteroStage('github_token', resolveGithubToken);
const recentMessagesPromise = traceHeteroStage('history', loadRecentMessages);
const [resumeSessionId, operationJwt, topic] = await settleInOrder([
+ // A sub-agent resumes its own session, never the topic's: the topic's
+ // belongs to the conversation's agent or to another sub-agent. The thread
+ // decides, not `isolationThread`: that flag is only set when the sub-agent
+ // is spawned, and a later message in its thread has to resume it too.
traceHeteroStage('resume_session', () =>
- heteroService.getHeterogeneousResumeSessionId(topicId),
+ appContext?.threadId
+ ? heteroService.getThreadResumeSessionId(appContext.threadId, topicId)
+ : heteroService.getHeterogeneousResumeSessionId(topicId),
),
traceHeteroStage('sign_operation_jwt', signOperationJwt),
// Read repos from topic metadata for sandbox setup (web/cloud only).
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.isolationSubAgent.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.isolationSubAgent.test.ts
new file mode 100644
index 00000000000..1c773c9f156
--- /dev/null
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.isolationSubAgent.test.ts
@@ -0,0 +1,101 @@
+// @vitest-environment node
+import { ThreadType } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { __resetOperationStatesForTesting } from '.';
+import { buildEvent, createHarness } from './testUtils';
+
+/**
+ * An external agent (Claude Code) running as a sub-agent sits in an isolation
+ * thread. It appears in the topic marker only while its parent's turn runs; a
+ * background one outlives that, and its batches then arrive with no marker.
+ */
+const subAgentHarness = (marker: 'none' | 'present') => {
+ const h = createHarness({
+ assistantMessageId: 'thread-asst-1',
+ isOperationLiveOnTopic: async () => true,
+ operationId: 'op-child',
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ });
+ h.threads.set('thread-1', {
+ id: 'thread-1',
+ metadata: { sourceToolCallId: 'call-1' },
+ status: 'processing',
+ title: 'Fix',
+ topicId: 'topic-1',
+ type: ThreadType.Isolation,
+ });
+ if (marker === 'none') {
+ h.topicModel.findById.mockResolvedValue({ agentId: null, id: 'topic-1', metadata: {} });
+ }
+ return h;
+};
+
+describe('HeterogeneousPersistenceHandler β€” external sub-agent in an isolation thread', () => {
+ beforeEach(__resetOperationStatesForTesting);
+ afterEach(__resetOperationStatesForTesting);
+
+ it.each(['none', 'present'] as const)(
+ 'binds the session to the thread, never the topic (marker: %s)',
+ async (marker) => {
+ const h = subAgentHarness(marker);
+
+ await h.handler.ingest({
+ events: [buildEvent('stream_start', 0, { sessionId: 'cc-sess-1' })],
+ assistantMessageId: 'thread-asst-1',
+ operationId: 'op-child',
+ topicId: 'topic-1',
+ });
+
+ expect(h.threads.get('thread-1')?.metadata).toEqual({
+ heteroSessionId: 'cc-sess-1',
+ sourceToolCallId: 'call-1',
+ });
+ expect(h.topicModel.updateMetadata).not.toHaveBeenCalledWith(
+ 'topic-1',
+ expect.objectContaining({ heteroSessionId: expect.anything() }),
+ );
+ },
+ );
+
+ // Without the marker the run used to lose its thread, so every later step
+ // landed in the parent conversation.
+ it('keeps later steps in the thread when the marker no longer names the run', async () => {
+ const h = subAgentHarness('none');
+
+ await h.handler.ingest({
+ events: [
+ buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'step one' }),
+ buildEvent('stream_start', 1, { newStep: true }),
+ ],
+ assistantMessageId: 'thread-asst-1',
+ operationId: 'op-child',
+ topicId: 'topic-1',
+ });
+
+ const later = [...h.messages.values()].filter(
+ (message) => message.role === 'assistant' && message.id !== 'thread-asst-1',
+ );
+ expect(later.length).toBeGreaterThan(0);
+ expect(later.every((message) => message.threadId === 'thread-1')).toBe(true);
+ });
+
+ it('keeps binding the conversation agent itself to the topic', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-main',
+ topicId: 'topic-1',
+ });
+
+ await h.handler.ingest({
+ events: [buildEvent('stream_start', 0, { sessionId: 'cc-main' })],
+ operationId: 'op-main',
+ topicId: 'topic-1',
+ });
+
+ expect(h.topicModel.updateMetadata).toHaveBeenCalledWith('topic-1', {
+ heteroSessionId: 'cc-main',
+ });
+ });
+});
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts
index a8b75e9834b..8b5cd39902b 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts
@@ -15,6 +15,7 @@ import {
} from '@lobechat/heterogeneous-agents/codexPlanMode';
import { isEchoedErrorText } from '@lobechat/heterogeneous-agents/errors';
import { isHeteroStatusGuideErrorData } from '@lobechat/heterogeneous-agents/processFailure';
+import { ThreadType } from '@lobechat/types';
import { createNanoId } from '@lobechat/utils';
import debug from 'debug';
@@ -339,16 +340,30 @@ export class HeterogeneousPersistenceHandler {
}
/**
- * Persist the CLI's native session id onto `topic.metadata.heteroSessionId`.
- * `TopicModel.updateMetadata` merges into existing JSONB so this does NOT
- * clobber `runningOperation` / `workingDirectory` / other peer fields.
+ * Persist the CLI's native session id as the run's resume binding: on
+ * `topic.metadata.heteroSessionId` for the conversation's own agent, or on
+ * the isolation thread's metadata for a sub-agent (the topic's binding is
+ * not its to take). `TopicModel.updateMetadata` merges into existing JSONB
+ * so this does NOT clobber `runningOperation` / `workingDirectory` / other
+ * peer fields.
*/
- private async persistSessionId(topicId: string, sessionId: string): Promise<void> {
+ private async persistSessionId(state: OperationState, sessionId: string): Promise<void> {
+ const { threadId, topicId } = state;
try {
+ if (threadId) {
+ const thread = await this.deps.threadModel.findById(threadId);
+ if (thread?.type === ThreadType.Isolation) {
+ await this.deps.threadModel.update(threadId, {
+ metadata: { ...thread.metadata, heteroSessionId: sessionId },
+ });
+ log('persisted sessionId thread=%s sessionId=%s', threadId, sessionId);
+ return;
+ }
+ }
await this.deps.topicModel.updateMetadata(topicId, { heteroSessionId: sessionId });
log('persisted sessionId topic=%s sessionId=%s', topicId, sessionId);
} catch (err) {
- log('persistSessionId failed topic=%s err=%O', topicId, err);
+ log('persistSessionId failed topic=%s thread=%s err=%O', topicId, threadId, err);
}
}
@@ -434,7 +449,7 @@ export class HeterogeneousPersistenceHandler {
// next turn to spawn a fresh CC session and drop all `--resume` history.
// Writing it here makes resume survive abandon. The terminal service
// path may still overwrite it after verifying topic ownership.
- await this.persistSessionId(state.topicId, sid);
+ await this.persistSessionId(state, sid);
}
}
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts
index 5c5513809b6..781fd5632c5 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts
@@ -185,7 +185,10 @@ export async function loadOrCreateState(
streamStartAssistantIds: new Map(),
streamStartParentMessages: new Map(),
toolMsgIdByCallId: new Map(),
- threadId: running?.threadId ?? undefined,
+ // A sub-agent run in an isolation thread is only in the topic marker while
+ // its parent's turn runs (never once a background child outlives it); its
+ // seeded assistant message always sits in that thread.
+ threadId: running?.threadId ?? baseAssistantMessage?.threadId ?? undefined,
topicId,
};
await refreshToolMessageIndex(deps, state);
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/sessionResume.isolationThread.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/sessionResume.isolationThread.test.ts
new file mode 100644
index 00000000000..2850c65b55c
--- /dev/null
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/sessionResume.isolationThread.test.ts
@@ -0,0 +1,132 @@
+// @vitest-environment node
+import { ThreadType } from '@lobechat/types';
+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 } from '..';
+
+const { threads } = vi.hoisted(() => ({
+ threads: new Map<string, { id: string; metadata?: Record<string, unknown>; type: string }>(),
+}));
+
+vi.mock('@/database/models/thread', () => ({
+ ThreadModel: vi.fn(function () {
+ return {
+ findById: vi.fn(async (id: string) => threads.get(id)),
+ update: vi.fn(async (id: string, value: { metadata?: Record<string, unknown> }) => {
+ const thread = threads.get(id);
+ if (thread && value.metadata) threads.set(id, { ...thread, metadata: value.metadata });
+ }),
+ };
+ }),
+}));
+
+const createService = (operation: { parentOperationId?: string; threadId?: string | null }) => {
+ const topicModel = {
+ findById: vi.fn(async () => ({ id: 'topic-1', metadata: { heteroSessionId: 'topic-sess' } })),
+ settleRunningOperation: vi.fn(async () => ({ status: 'not_owner' as const })),
+ updateMetadata: vi.fn(async () => undefined),
+ };
+ const service = new HeterogeneousAgentService({} as any, 'user-1', {
+ agentOperationModel: {
+ findById: vi.fn(async () => ({ id: 'op-1', metadata: {}, ...operation })),
+ settleRunning: vi.fn(async () => undefined),
+ } as any,
+ persistenceHandler: { finish: vi.fn(async () => undefined) } as any,
+ snapshotStore: null,
+ streamEventManager: {
+ publishStreamEvent: vi.fn(async () => 'ok'),
+ } as unknown as IStreamEventManager,
+ topicModel: topicModel as any,
+ });
+ return { service, topicModel };
+};
+
+const finish = (service: HeterogeneousAgentService, sessionId = 'cc-thread-sess') =>
+ service.heteroFinish({
+ agentType: 'claude-code',
+ operationId: 'op-1',
+ result: 'success',
+ sessionId,
+ topicId: 'topic-1',
+ });
+
+// An external agent running as a sub-agent keeps its session on its isolation
+// thread, so a follow-up resumes it and the topic's own binding is untouched.
+describe('HeterogeneousAgentService β€” sub-agent session per isolation thread', () => {
+ beforeEach(() => {
+ threads.clear();
+ vi.spyOn(CompletionLifecycle.prototype, 'completeOperation').mockImplementation(async () => {
+ // The thread hooks rewrite the metadata from what the run claimed it with.
+ const thread = threads.get('thread-1');
+ if (thread) threads.set('thread-1', { ...thread, metadata: { operationId: 'op-1' } });
+ });
+ });
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('binds the session to the isolation thread, not the topic', async () => {
+ threads.set('thread-1', { id: 'thread-1', metadata: {}, type: ThreadType.Isolation });
+ const { service, topicModel } = createService({
+ parentOperationId: 'op-parent',
+ threadId: 'thread-1',
+ });
+
+ await finish(service);
+
+ expect(topicModel.updateMetadata).not.toHaveBeenCalledWith(
+ 'topic-1',
+ expect.objectContaining({ heteroSessionId: expect.anything() }),
+ );
+ // Re-bound after the completion hooks rewrote the metadata.
+ expect(threads.get('thread-1')?.metadata).toMatchObject({ heteroSessionId: 'cc-thread-sess' });
+ });
+
+ it('keeps binding a run in an ordinary thread to the topic', async () => {
+ threads.set('thread-1', { id: 'thread-1', metadata: {}, type: ThreadType.Continuation });
+ const { service, topicModel } = createService({ threadId: 'thread-1' });
+
+ await finish(service);
+
+ expect(topicModel.updateMetadata).toHaveBeenCalledWith('topic-1', {
+ heteroSessionId: 'cc-thread-sess',
+ });
+ expect(threads.get('thread-1')?.metadata).not.toHaveProperty('heteroSessionId');
+ });
+
+ it('resumes a sub-agent from its thread session', async () => {
+ threads.set('thread-1', {
+ id: 'thread-1',
+ metadata: { heteroSessionId: 'cc-thread-sess' },
+ type: ThreadType.Isolation,
+ });
+ const { service } = createService({});
+
+ await expect(service.getThreadResumeSessionId('thread-1', 'topic-1')).resolves.toBe(
+ 'cc-thread-sess',
+ );
+ });
+
+ // A new sub-agent starts fresh: the topic's session is the conversation's.
+ it('does not hand a new sub-agent the topic session', async () => {
+ threads.set('thread-new', { id: 'thread-new', metadata: {}, type: ThreadType.Isolation });
+ const { service } = createService({});
+
+ await expect(
+ service.getThreadResumeSessionId('thread-new', 'topic-1'),
+ ).resolves.toBeUndefined();
+ });
+
+ // Reads follow the same rule the writes bind by.
+ it('resumes a run in an ordinary thread from the topic session', async () => {
+ threads.set('thread-1', { id: 'thread-1', metadata: {}, type: ThreadType.Continuation });
+ const { service } = createService({});
+
+ await expect(service.getThreadResumeSessionId('thread-1', 'topic-1')).resolves.toBe(
+ 'topic-sess',
+ );
+ });
+});
diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.ts
index cde04bc1126..97e9efad1c9 100644
--- a/apps/server/src/services/heterogeneousAgent/index.ts
+++ b/apps/server/src/services/heterogeneousAgent/index.ts
@@ -10,7 +10,7 @@ import {
classifyHeteroProcessFailure,
isHeteroStatusGuideErrorData,
} from '@lobechat/heterogeneous-agents/processFailure';
-import { type ChatMessageError, ThreadStatus } from '@lobechat/types';
+import { type ChatMessageError, ThreadStatus, ThreadType } from '@lobechat/types';
import debug from 'debug';
import {
@@ -584,7 +584,13 @@ export class HeterogeneousAgentService {
: result === 'error' && resumeSessionInvalidated
? { heteroSessionId: undefined }
: undefined;
- if (resumeBindingUpdate) {
+ // A sub-agent run in an isolation thread keeps its session on that thread:
+ // the topic's binding belongs to the conversation's own agent.
+ const bindsThreadSession =
+ !!resumeBindingUpdate &&
+ !!isolationThreadId &&
+ (await this.bindIsolationThreadSession(isolationThreadId, resumeBindingUpdate));
+ if (resumeBindingUpdate && !bindsThreadSession) {
try {
// Only the producer can distinguish a missing native session from a
// transient pre-init error such as Codex's "already has an active writer".
@@ -788,6 +794,12 @@ export class HeterogeneousAgentService {
await lifecycle.completeOperation({ ...completionInput, worksRegistered }, completionReason);
log('heteroFinish: dispatched completion lifecycle for op=%s result=%s', operationId, result);
+ // The completion's thread hooks rewrite the thread's metadata from what the
+ // run claimed it with, which predates this run's session. Bind it again.
+ if (bindsThreadSession && resumeBindingUpdate && isolationThreadId) {
+ await this.bindIsolationThreadSession(isolationThreadId, resumeBindingUpdate);
+ }
+
// Follow-ups the user queued behind this run start as the next turn here,
// as they do when a native run ends. The completion above released the
// topic, which the next turn has to claim. A failed run leaves its queue
@@ -815,6 +827,44 @@ export class HeterogeneousAgentService {
}
}
+ /**
+ * Record an external agent's native session on the isolation thread it runs
+ * in (a sub-agent), so a follow-up to that sub-agent resumes it. Returns
+ * false when the thread is not an isolation thread β€” the session then binds
+ * to the topic as before. Never throws.
+ */
+ private async bindIsolationThreadSession(
+ threadId: string,
+ update: { heteroSessionId?: string },
+ ): Promise<boolean> {
+ try {
+ const threadModel = new ThreadModel(this.db, this.userId, this.workspaceId);
+ const thread = await threadModel.findById(threadId);
+ if (thread?.type !== ThreadType.Isolation) return false;
+ await threadModel.update(threadId, {
+ metadata: { ...thread.metadata, heteroSessionId: update.heteroSessionId },
+ });
+ return true;
+ } catch (err) {
+ log('heteroFinish: binding thread %s session failed (non-fatal): %O', threadId, err);
+ return true;
+ }
+ }
+
+ /**
+ * Resume session for a run inside a thread. An isolation thread (a
+ * sub-agent) holds its own session, undefined while it is new; any other
+ * thread shares the topic's. The thread's type decides, as it does for the
+ * writes ({@link bindIsolationThreadSession}): a message the user sends in a
+ * sub-agent's thread later is an ordinary run, and still resumes what that
+ * sub-agent started.
+ */
+ async getThreadResumeSessionId(threadId: string, topicId: string): Promise<string | undefined> {
+ const thread = await new ThreadModel(this.db, this.userId, this.workspaceId).findById(threadId);
+ if (thread?.type === ThreadType.Isolation) return thread.metadata?.heteroSessionId;
+ return this.getHeterogeneousResumeSessionId(topicId);
+ }
+
/**
* Look up the persisted CLI session id for a topic so the orchestrator
* (phase 3 cloud sandbox) can pass `--resume <sessionId>` to the next
diff --git a/packages/database/src/models/__tests__/thread.coverage.test.ts b/packages/database/src/models/__tests__/thread.coverage.test.ts
index 53690556375..dda37ce08c0 100644
--- a/packages/database/src/models/__tests__/thread.coverage.test.ts
+++ b/packages/database/src/models/__tests__/thread.coverage.test.ts
@@ -47,6 +47,29 @@ describe('ThreadModel coverage', () => {
expect((await findThread('thread-attach-live'))?.metadata).toEqual({ operationId: 'op-1' });
});
+ // An external agent binds its session at stream start, which can land
+ // before the dispatch that started it records the operation.
+ it('keeps a session the run already bound to the thread', async () => {
+ await serverDB.insert(threads).values({
+ id: 'thread-attach-session',
+ metadata: { heteroSessionId: 'cc-live', startedAt: '2026-10-01T00:00:00.000Z' },
+ status: ThreadStatus.Processing,
+ topicId,
+ type: ThreadType.Isolation,
+ userId,
+ });
+
+ await threadModel.attachRunOperation('thread-attach-session', {
+ heteroSessionId: 'cc-claimed',
+ operationId: 'op-1',
+ });
+
+ expect((await findThread('thread-attach-session'))?.metadata).toEqual({
+ heteroSessionId: 'cc-live',
+ operationId: 'op-1',
+ });
+ });
+
it('keeps the metadata of a run that already settled', async () => {
await insertThread('thread-attach-settled', ThreadStatus.Completed);
diff --git a/packages/database/src/models/thread.ts b/packages/database/src/models/thread.ts
index d4b148d7492..28c2cac2623 100644
--- a/packages/database/src/models/thread.ts
+++ b/packages/database/src/models/thread.ts
@@ -207,11 +207,16 @@ export class ThreadModel {
* Record the operation id of a run that just started. The run is scheduled
* before its id is known here, so it may already have settled the thread;
* that metadata holds its final usage and error and must not be replaced.
+ * An external agent may also have bound its native session to the thread by
+ * now (`heteroSessionId`, written at its stream start); that one is kept.
*/
attachRunOperation = async (id: string, metadata: ThreadMetadata) => {
return this.db
.update(threads)
- .set({ metadata, updatedAt: new Date() })
+ .set({
+ metadata: sql`${JSON.stringify(metadata)}::jsonb || jsonb_strip_nulls(jsonb_build_object('heteroSessionId', ${threads.metadata} -> 'heteroSessionId'))`,
+ updatedAt: new Date(),
+ })
.where(
and(eq(threads.id, id), this.ownership(), eq(threads.status, ThreadStatus.Processing)),
);
diff --git a/packages/types/src/topic/thread.ts b/packages/types/src/topic/thread.ts
index fa85f34c457..2c4bdf6c19b 100644
--- a/packages/types/src/topic/thread.ts
+++ b/packages/types/src/topic/thread.ts
@@ -43,6 +43,13 @@ export interface ThreadMetadata {
duration?: number;
/** Error details when task failed */
error?: any;
+ /**
+ * Native session of the external agent (Claude Code, Codex, …) that runs in
+ * this isolation thread. Kept per thread rather than on the topic, so a
+ * follow-up to that sub-agent resumes its own session and two external
+ * sub-agents in one conversation never share one.
+ */
+ heteroSessionId?: string;
/**
* Model the subagent ran on (e.g. CC's per-turn `message.model`). Pinned
* once for the run and rolled up here on finalize so historical / cold-load