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: interrupt agent before releasing environment copy (#21119)

AmAzing-748fb82d2ed1
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
index 242ffd45b68..793891d067d 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
@@ -3684,14 +3684,14 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
state: {},
success: false,
});
- const loadAgentState = vi.fn().mockResolvedValue({ status: 'interrupted' });
-
+ const loadAgentState = vi.fn(async () => ({
+ status: mockToolExecutionService.executeTool.mock.calls.length ? 'interrupted' : 'running',
+ }));
const executors = createRuntimeExecutors({
...ctx,
loadAgentState,
});
const state = createMockState();
-
const instruction = {
payload: {
parentMessageId: 'assistant-msg-123',
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.stop.test.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.stop.test.ts
new file mode 100644
index 00000000000..1aabf8d6d30
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.stop.test.ts
@@ -0,0 +1,176 @@
+import type { AgentRuntimeHost, AgentState } from '@lobechat/agent-runtime';
+import {
+ AgentRuntime,
+ createAgentRuntimeExecutors,
+ GeneralChatAgent,
+} from '@lobechat/agent-runtime';
+import type { ChatToolPayload } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { AgentHook } from '@/server/services/agentRuntime/hooks';
+import { HookDispatcher } from '@/server/services/agentRuntime/hooks';
+
+import type { RuntimeExecutorContext } from '../context';
+import { ServerToolTransport } from './ServerToolTransport';
+
+const { dispatchClient, fetchHook, getEmailsByIds, queueMode, isInterrupted } = vi.hoisted(() => ({
+ dispatchClient: vi.fn(),
+ fetchHook: vi.fn(),
+ getEmailsByIds: vi.fn(),
+ queueMode: vi.fn(),
+ isInterrupted: vi.fn(),
+}));
+vi.mock('../dispatchClientTool', () => ({ dispatchClientTool: dispatchClient }));
+vi.mock('@/database/models/user', () => ({ UserModel: { getEmailsByIds } }));
+vi.mock('@/database/server', () => ({ getServerDB: async () => ({}) }));
+vi.mock('@/server/services/queue/impls', () => ({ isQueueAgentRuntimeEnabled: queueMode }));
+vi.mock('@/libs/qstash', () => ({ OtelQstashClient: class {} }));
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: class {
+ getAgentVisibility = async () => 'private';
+ },
+}));
+vi.mock('../executorHelpers', () => ({
+ archiveRuntimeToolResult: async (result: unknown) => result,
+ buildServerAgentMemberRunner: () => undefined,
+ buildServerVirtualSubAgentRunner: () => undefined,
+ GEN_AI_FUNCTION_TOOL_TYPE: 'function',
+ isOperationInterrupted: isInterrupted,
+ log: () => {},
+ registerWorkFromIntent: vi.fn(),
+ TOOL_MAX_RETRIES: 2,
+ TOOL_PRICING: { 'fs/write': 5 },
+}));
+
+const call = (id = 'native-1'): ChatToolPayload => ({
+ id,
+ apiName: 'write',
+ identifier: 'fs',
+ arguments: '{"path":"a"}',
+ type: 'builtin',
+});
+const response = (decision: 'allow' | 'deny', reason?: string) =>
+ new Response(JSON.stringify(decision === 'deny' ? { decision, reason } : { decision }));
+
+function setup(hooks: AgentHook[], signal?: AbortSignal, restore = false) {
+ const registered = new HookDispatcher();
+ registered.register('op', hooks);
+ const dispatcher = restore ? new HookDispatcher() : registered;
+ const execute = vi.fn().mockResolvedValue({ content: 'executed', success: true });
+ const rows: Record<string, unknown>[] = [];
+ const state: AgentState = {
+ cost: {
+ calculatedAt: '',
+ currency: 'USD',
+ llm: { byModel: [], currency: 'USD', total: 0 },
+ tools: { byTool: [], currency: 'USD', total: 0 },
+ total: 0,
+ },
+ usage: {
+ humanInteraction: {
+ approvalRequests: 0,
+ promptRequests: 0,
+ selectRequests: 0,
+ totalWaitingTimeMs: 0,
+ },
+ llm: { apiCalls: 0, processingTimeMs: 0, tokens: { input: 0, output: 0, total: 0 } },
+ tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },
+ },
+ createdAt: '',
+ lastModified: '',
+ messages: [],
+ operationId: 'op',
+ status: 'running',
+ stepCount: 0,
+ origin: { agentId: 'agent', topicId: 'topic' },
+ // Serialize to model a worker boundary, not merely an in-memory clone.
+ // eslint-disable-next-line unicorn/prefer-structured-clone
+ host: { hooks: JSON.parse(JSON.stringify(registered.getSerializedHooks('op') ?? [])) },
+ userInterventionConfig: { approvalMode: 'auto-run' },
+ };
+ const transport = new ServerToolTransport({
+ operationId: 'op',
+ stepIndex: 1,
+ userId: 'user',
+ hookDispatcher: dispatcher,
+ abortSignal: signal,
+ serverDB: {},
+ streamManager: { sendToolExecute: vi.fn() },
+ toolExecutionService: { executeTool: execute },
+ } as unknown as RuntimeExecutorContext);
+ const host: AgentRuntimeHost = {
+ operation: { operationId: 'op', stepIndex: 1, agentId: 'agent', abortSignal: signal },
+ transports: {
+ tools: transport,
+ messages: {
+ createToolMessage: vi.fn(async (row) => {
+ rows.push(row);
+ return { ...row, id: `row-${rows.length}` };
+ }),
+ query: vi.fn(async () => rows),
+ updateToolMessage: vi.fn(),
+ updateToolIntervention: vi.fn(),
+ update: vi.fn(),
+ findToolMessageIdByToolCallId: vi.fn(),
+ } as unknown as AgentRuntimeHost['transports']['messages'],
+ stream: { publishEvent: vi.fn(), publishChunk: vi.fn() },
+ },
+ };
+ const executors = createAgentRuntimeExecutors(host);
+ const runtime = new AgentRuntime(new GeneralChatAgent({ operationId: 'op' }), {
+ executors,
+ });
+ const step = (calls = [call()]) =>
+ runtime.step(state, {
+ phase: 'llm_result',
+ payload: { hasToolsCalling: true, parentMessageId: 'assistant', toolsCalling: calls },
+ });
+ return { dispatcher, execute, executors, host, rows, runtime, state, step };
+}
+
+beforeEach(() => {
+ vi.stubGlobal('fetch', fetchHook);
+ getEmailsByIds.mockReset().mockResolvedValue([]);
+ fetchHook.mockReset().mockImplementation(async () => response('allow'));
+ queueMode.mockReturnValue(false);
+ isInterrupted.mockReset().mockResolvedValue(false);
+ dispatchClient.mockReset().mockResolvedValue({ content: 'client result', success: true });
+});
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+describe('environment stop between tool steps', () => {
+ it('does not launch another server tool after the persisted interrupt, before local polling catches up', async () => {
+ const controller = new AbortController();
+ const fixture = setup([], controller.signal);
+ isInterrupted.mockResolvedValue(true);
+ await fixture.step();
+ expect(controller.signal.aborted).toBe(false);
+ expect(fixture.execute).not.toHaveBeenCalled();
+ });
+ it.each(['server', 'client'] as const)(
+ 'does not launch %s work when abort arrives during the sentinel read',
+ async (target) => {
+ const controller = new AbortController();
+ const fixture = setup([], controller.signal);
+ isInterrupted.mockResolvedValueOnce(false).mockImplementationOnce(
+ () =>
+ new Promise<boolean>((resolve) => {
+ queueMicrotask(() => {
+ controller.abort();
+ resolve(false);
+ });
+ }),
+ );
+ await fixture.step([
+ { ...call(), ...(target === 'client' ? { executor: 'client' as const } : {}) },
+ ]);
+ // The runtime can settle its abort race before the transport resumes.
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(fixture.execute).not.toHaveBeenCalled();
+ expect(dispatchClient).not.toHaveBeenCalled();
+ },
+ );
+});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
index 0d7a0790070..a4494787bb1 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
@@ -166,7 +166,12 @@ export class ServerToolTransport implements ToolTransport {
try {
const hookResult = await this.dispatchBeforeToolCall(chatToolPayload, context);
- if (context.abortSignal?.aborted) return this.abortedBeforeLaunch();
+ if (
+ context.abortSignal?.aborted ||
+ (await isOperationInterrupted(this.ctx)) ||
+ context.abortSignal?.aborted
+ )
+ return this.abortedBeforeLaunch();
let toolCallMocked = false;
if (isDeviceToolIdentifier(chatToolPayload.identifier) && !hookResult?.isMocked) {
@@ -208,7 +213,12 @@ export class ServerToolTransport implements ToolTransport {
// so Stop can land between entering `run` and reaching this line. The
// executor's race has already settled the call by then β€” launching now
// would start side-effecting work for a cancelled operation.
- if (context.abortSignal?.aborted) return this.abortedBeforeLaunch();
+ if (
+ context.abortSignal?.aborted ||
+ (await isOperationInterrupted(this.ctx)) ||
+ context.abortSignal?.aborted
+ )
+ return this.abortedBeforeLaunch();
const dispatchResult = await dispatchClientTool(chatToolPayload, {
agentId: context.state.origin?.agentId,
@@ -240,7 +250,12 @@ export class ServerToolTransport implements ToolTransport {
// Re-checked after the visibility await for the same reason as above:
// every await between entry and launch reopens the cancellation window.
- if (context.abortSignal?.aborted) return this.abortedBeforeLaunch();
+ if (
+ context.abortSignal?.aborted ||
+ (await isOperationInterrupted(this.ctx)) ||
+ context.abortSignal?.aborted
+ )
+ return this.abortedBeforeLaunch();
log(`[${operationLogId}] Executing tool ${context.toolName} ...`);
execution = await executeToolWithRetry(
diff --git a/apps/server/src/modules/AgentRuntime/context.ts b/apps/server/src/modules/AgentRuntime/context.ts
index f83e96b5390..32c9b910e1c 100644
--- a/apps/server/src/modules/AgentRuntime/context.ts
+++ b/apps/server/src/modules/AgentRuntime/context.ts
@@ -61,6 +61,7 @@ export interface RuntimeExecutorContext {
*/
execVirtualSubAgent?: (params: ExecVirtualSubAgentParams) => Promise<ExecSubAgentResult>;
hookDispatcher?: HookDispatcher;
+ isInterrupted?: (operationId: string) => Promise<boolean>;
loadAgentState?: (operationId: string) => Promise<AgentState | null>;
messageModel: MessageModel;
modelRuntimeConfig?: AgentState['modelRuntimeConfig'];
diff --git a/apps/server/src/modules/AgentRuntime/executorHelpers.stop.test.ts b/apps/server/src/modules/AgentRuntime/executorHelpers.stop.test.ts
new file mode 100644
index 00000000000..85a1cfbfd85
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/executorHelpers.stop.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import type { RuntimeExecutorContext } from './context';
+import { isOperationInterrupted } from './executorHelpers';
+
+describe('persisted tool interruption guard', () => {
+ it('honors the sentinel even when an in-flight worker overwrote the state blob', async () => {
+ const loadAgentState = vi.fn().mockResolvedValue({ status: 'running' });
+ const context = {
+ isInterrupted: vi.fn().mockResolvedValue(true),
+ loadAgentState,
+ operationId: 'stopped-operation',
+ } as unknown as RuntimeExecutorContext;
+ await expect(isOperationInterrupted(context)).resolves.toBe(true);
+ expect(loadAgentState).not.toHaveBeenCalled();
+ });
+
+ it('fails closed if the authoritative interruption store is unavailable', async () => {
+ const context = {
+ isInterrupted: vi.fn().mockRejectedValue(new Error('store unavailable')),
+ operationId: 'operation',
+ } as unknown as RuntimeExecutorContext;
+ await expect(isOperationInterrupted(context)).rejects.toThrow('store unavailable');
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/executorHelpers.ts b/apps/server/src/modules/AgentRuntime/executorHelpers.ts
index 91eb991db78..79bbfc4f241 100644
--- a/apps/server/src/modules/AgentRuntime/executorHelpers.ts
+++ b/apps/server/src/modules/AgentRuntime/executorHelpers.ts
@@ -630,6 +630,8 @@ export const buildServerAgentMemberRunner = (
export const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
export const isOperationInterrupted = async (ctx: RuntimeExecutorContext) => {
+ // The sentinel survives stale in-flight state writes and is cheaper than loading the state blob.
+ if (ctx.isInterrupted) return ctx.isInterrupted(ctx.operationId);
if (!ctx.loadAgentState) return false;
try {
diff --git a/apps/server/src/routers/lambda/__tests__/sandboxStorage.defaultInstance.test.ts b/apps/server/src/routers/lambda/__tests__/sandboxStorage.defaultInstance.test.ts
index ae91be40e13..9d1281b3eb0 100644
--- a/apps/server/src/routers/lambda/__tests__/sandboxStorage.defaultInstance.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/sandboxStorage.defaultInstance.test.ts
@@ -30,9 +30,9 @@ const plane = vi.hoisted(() => ({
readOccupancy: vi.fn(),
}));
-vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {
+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async (importOriginal) => {
const mod = await vi.importActual<{ trpc: any }>('@/libs/trpc/lambda/init');
- return { wsCompatProcedure: mod.trpc.procedure };
+ return { ...(await importOriginal<object>()), wsCompatProcedure: mod.trpc.procedure };
});
vi.mock('@/libs/trpc/lambda/middleware', () => ({
diff --git a/apps/server/src/routers/lambda/__tests__/sandboxStorage.test.ts b/apps/server/src/routers/lambda/__tests__/sandboxStorage.test.ts
index aec6294cf29..41acfcb3cf8 100644
--- a/apps/server/src/routers/lambda/__tests__/sandboxStorage.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/sandboxStorage.test.ts
@@ -99,6 +99,7 @@ vi.mock('@/server/services/market', () => ({
readOccupancy: mockReadOccupancy,
refreshUsage: mockRefreshUsage,
stopInstance: mockStopInstance,
+ readStopTarget: async () => ({ sessionId: 'session-1', topicId: null }),
writeFile: mockWriteFile,
}),
};
@@ -294,12 +295,11 @@ describe('sandboxStorageRouter', () => {
sandboxStorageRouter.createCaller(ctx).stopInstance({ id: instanceId }),
).resolves.toEqual({ stopped: true });
- expect(mockStopInstance).toHaveBeenCalledWith({ name: instanceId });
+ expect(mockStopInstance.mock.calls[0][0].expectedSessionId).toBe('session-1');
});
it('refuses an instance the caller does not own, before reaching the execution plane', async () => {
- // A published instance is usually held by a colleague's conversation;
- // reading access must not be enough to cut that run off.
+ // Reading a colleague's instance does not grant authority to stop it.
mockInstanceFindOwnedById.mockResolvedValue(undefined);
await expect(
diff --git a/apps/server/src/routers/lambda/sandboxStorage/instances.ts b/apps/server/src/routers/lambda/sandboxStorage/instances.ts
index 52fb3db67b1..cd60c94ef0e 100644
--- a/apps/server/src/routers/lambda/sandboxStorage/instances.ts
+++ b/apps/server/src/routers/lambda/sandboxStorage/instances.ts
@@ -5,6 +5,7 @@ import { z } from 'zod';
import { TopicModel } from '@/database/models/topic';
import { router } from '@/libs/trpc/lambda';
+import { stopSandboxInstance } from '@/server/services/sandbox/stopInstance';
import { rethrowDuplicateInstanceDirectory } from './constraintErrors';
import {
@@ -391,12 +392,9 @@ export const instancesRouter = router({
*/
stopInstance: instanceProcedure
.input(z.object({ id: idSchema }))
- .mutation(async ({ ctx, input }) => {
- const instance = await ctx.instanceModel.findOwnedById(input.id);
- if (!instance) throw new TRPCError({ code: 'NOT_FOUND', message: 'Instance not found' });
-
- return ctx.client.stopInstance({ name: instance.id }).catch(mapStorageError);
- }),
+ .mutation(async ({ ctx, input }) =>
+ stopSandboxInstance({ ...ctx, id: input.id }).catch(mapStorageError),
+ ),
renameInstance: instanceProcedure
.input(z.object({ id: idSchema, name: nameSchema }))
.mutation(async ({ ctx, input }) => {
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts
index 8d013da09ea..534061ad97a 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts
@@ -220,6 +220,7 @@ export async function createAgentRuntime(
execGroupMember: deps.delegate.execGroupMember,
onGroupMemberResult: (params) => deps.completeGroupMemberBarrier(params),
hookDispatcher,
+ isInterrupted: deps.coordinator.isInterrupted.bind(deps.coordinator),
loadAgentState: deps.coordinator.loadAgentState.bind(deps.coordinator),
messageModel: deps.messageModel,
modelRuntimeConfig,
diff --git a/apps/server/src/services/sandbox/stopInstance.test.ts b/apps/server/src/services/sandbox/stopInstance.test.ts
new file mode 100644
index 00000000000..9663860bcb6
--- /dev/null
+++ b/apps/server/src/services/sandbox/stopInstance.test.ts
@@ -0,0 +1,180 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { stopSandboxInstance } from './stopInstance';
+
+const mocks = vi.hoisted(() => ({
+ findByIds: vi.fn(),
+ findLiveByTopic: vi.fn(),
+ findTopic: vi.fn(),
+ interrupt: vi.fn(),
+ runtimeActors: [] as string[],
+}));
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: class {
+ findById = mocks.findTopic;
+ },
+}));
+vi.mock('@/database/models/agentOperation', () => ({
+ AgentOperationModel: class {
+ findByIds = mocks.findByIds;
+ findLiveByTopic = mocks.findLiveByTopic;
+ },
+}));
+vi.mock('@/server/services/agentRuntime/AgentRuntimeService', () => ({
+ AgentRuntimeService: class {
+ constructor(_db: unknown, userId: string) {
+ mocks.runtimeActors.push(userId);
+ }
+ interruptOperation = mocks.interrupt;
+ },
+}));
+
+const fixture = () => ({
+ client: {
+ prepareStop: vi.fn().mockResolvedValue({ prepared: true }),
+ readStopTarget: vi.fn().mockResolvedValue({ sessionId: 'session-1', topicId: 'topic-1' }),
+ stopInstance: vi.fn().mockResolvedValue({ stopped: true }),
+ },
+ id: 'instance-1',
+ instanceModel: { findOwnedById: vi.fn().mockResolvedValue({ id: 'instance-1' }) },
+ serverDB: {} as LobeChatDatabase,
+ userId: 'environment-owner',
+ workspaceId: 'workspace-1',
+});
+
+describe('stopSandboxInstance', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.runtimeActors.length = 0;
+ mocks.findTopic.mockResolvedValue({
+ id: 'topic-1',
+ metadata: { runningOperation: { operationId: 'op-1' } },
+ });
+ mocks.findByIds.mockResolvedValue([
+ { id: 'op-1', status: 'running', topicId: 'topic-1', userId: 'running-member' },
+ ]);
+ mocks.findLiveByTopic.mockImplementation(() => mocks.findByIds());
+ mocks.interrupt.mockResolvedValue(true);
+ });
+
+ it('retains the live operation and lease when fence preparation fails', async () => {
+ const options = fixture();
+ options.client.prepareStop.mockRejectedValue(new Error('fence unavailable'));
+ await expect(stopSandboxInstance(options)).rejects.toThrow('fence unavailable');
+ expect(mocks.interrupt).not.toHaveBeenCalled();
+ expect(options.client.stopInstance).not.toHaveBeenCalled();
+ });
+
+ it('persists the operation fence before a parked run can settle, retaining it across retry', async () => {
+ const options = fixture();
+ const fenced = new Set<string>();
+ options.client.prepareStop.mockImplementation(async (params: any) => {
+ for (const id of params.operationIds) fenced.add(id);
+ return { prepared: true };
+ });
+ mocks.interrupt.mockImplementation(async (id) => {
+ expect(fenced.has(id)).toBe(true);
+ mocks.findByIds.mockResolvedValue([]); // waiting_for_client settled synchronously
+ return true;
+ });
+ options.client.stopInstance.mockRejectedValueOnce(new Error('provider unavailable'));
+ await expect(stopSandboxInstance(options)).rejects.toThrow('provider unavailable');
+ await expect(stopSandboxInstance(options)).resolves.toEqual({ stopped: true });
+ expect(fenced.has('op-1')).toBe(true);
+ });
+
+ it('interrupts a durable live row when the rendering marker is absent', async () => {
+ mocks.findTopic.mockResolvedValue({ id: 'topic-1', metadata: {} });
+ await stopSandboxInstance(fixture());
+ expect(mocks.interrupt).toHaveBeenCalledWith('op-1');
+ });
+
+ it.each(['waiting_for_human', 'waiting_for_async_tool', 'waiting_for_client'])(
+ 'interrupts a parked %s operation',
+ async (status) => {
+ mocks.findByIds.mockResolvedValue([
+ { id: 'op-1', status, topicId: 'topic-1', userId: 'running-member' },
+ ]);
+ await stopSandboxInstance(fixture());
+ expect(mocks.interrupt).toHaveBeenCalledWith('op-1');
+ },
+ );
+
+ it('interrupts the holding member before releasing the sandbox', async () => {
+ const options = fixture();
+ let interrupted = false;
+ mocks.interrupt.mockImplementation(async () => {
+ interrupted = true;
+ return true;
+ });
+ options.client.stopInstance.mockImplementation(async () => {
+ expect(interrupted).toBe(true);
+ return { stopped: true };
+ });
+ await expect(stopSandboxInstance(options)).resolves.toEqual({ stopped: true });
+ expect(mocks.runtimeActors).toEqual(['running-member']);
+ expect(mocks.interrupt).toHaveBeenCalledWith('op-1');
+ expect(options.client.stopInstance).toHaveBeenCalledWith({
+ expectedSessionId: 'session-1',
+ name: 'instance-1',
+ operationIds: ['op-1'],
+ });
+ });
+
+ it('denies a member who does not own the environment before reading the holder', async () => {
+ const options = fixture();
+ options.instanceModel.findOwnedById.mockResolvedValue(undefined);
+ await expect(stopSandboxInstance(options)).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(options.client.readStopTarget).not.toHaveBeenCalled();
+ expect(mocks.interrupt).not.toHaveBeenCalled();
+ });
+
+ it('does not cancel a topic outside the caller workspace', async () => {
+ const options = fixture();
+ mocks.findTopic.mockResolvedValue(undefined);
+ await expect(stopSandboxInstance(options)).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(mocks.interrupt).not.toHaveBeenCalled();
+ expect(options.client.stopInstance).not.toHaveBeenCalled();
+ });
+
+ it('does not release the instance when interruption is unconfirmed', async () => {
+ const options = fixture();
+ mocks.interrupt.mockResolvedValue(false);
+ await expect(stopSandboxInstance(options)).rejects.toMatchObject({ code: 'CONFLICT' });
+ expect(options.client.stopInstance).not.toHaveBeenCalled();
+ });
+
+ it('preserves a replacement holder that arrived during operation lookup', async () => {
+ const options = fixture();
+ options.client.readStopTarget
+ .mockResolvedValueOnce({ sessionId: 'session-1', topicId: 'topic-1' })
+ .mockResolvedValue({ sessionId: 'session-2', topicId: 'topic-2' });
+ await expect(stopSandboxInstance(options)).rejects.toMatchObject({ code: 'CONFLICT' });
+ expect(mocks.interrupt).not.toHaveBeenCalled();
+ expect(options.client.stopInstance).not.toHaveBeenCalled();
+ });
+
+ it('does not acknowledge a conditional stop that lost its lease', async () => {
+ const options = fixture();
+ options.client.stopInstance.mockResolvedValue({ stopped: false });
+ await expect(stopSandboxInstance(options)).rejects.toMatchObject({ code: 'CONFLICT' });
+ });
+
+ it('stops an idle or management session without inventing an operation', async () => {
+ const options = fixture();
+ options.client.readStopTarget.mockResolvedValue({ sessionId: 'session-1', topicId: null });
+ await expect(stopSandboxInstance(options)).resolves.toEqual({ stopped: true });
+ expect(mocks.interrupt).not.toHaveBeenCalled();
+ });
+
+ it('fails closed if the running marker refers to another topic', async () => {
+ const options = fixture();
+ mocks.findByIds.mockResolvedValue([
+ { id: 'op-1', status: 'running', topicId: 'other-topic', userId: 'other-user' },
+ ]);
+ await expect(stopSandboxInstance(options)).rejects.toMatchObject({ code: 'CONFLICT' });
+ expect(mocks.interrupt).not.toHaveBeenCalled();
+ expect(options.client.stopInstance).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/sandbox/stopInstance.ts b/apps/server/src/services/sandbox/stopInstance.ts
new file mode 100644
index 00000000000..99108b180f5
--- /dev/null
+++ b/apps/server/src/services/sandbox/stopInstance.ts
@@ -0,0 +1,88 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import { TRPCError } from '@trpc/server';
+
+import { AgentOperationModel } from '@/database/models/agentOperation';
+import type { EnvironmentInstanceModel } from '@/database/models/environmentInstance';
+import { TopicModel } from '@/database/models/topic';
+import { AgentRuntimeService } from '@/server/services/agentRuntime/AgentRuntimeService';
+
+import type { SandboxStorageClient } from './storageFiles';
+
+interface StopInstanceOptions {
+ client: Pick<SandboxStorageClient, 'prepareStop' | 'readStopTarget' | 'stopInstance'>;
+ id: string;
+ instanceModel: Pick<EnvironmentInstanceModel, 'findOwnedById'>;
+ serverDB: LobeChatDatabase;
+ userId: string;
+ workspaceId?: string | null;
+}
+
+/** Stop the run before releasing its sandbox, so recovery cannot reacquire it. */
+export const stopSandboxInstance = async (options: StopInstanceOptions) => {
+ const { client, id, instanceModel, serverDB, userId } = options;
+ const workspaceId = options.workspaceId ?? undefined;
+ // Being a workspace member is not authority to stop every member's copies.
+ if (!(await instanceModel.findOwnedById(id))) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment instance not found' });
+ }
+
+ const target = await client.readStopTarget({ name: id });
+ if (!target) return { stopped: false };
+
+ let operationIds: string[] = [];
+ if (target.topicId) {
+ // The execution plane proves which topic holds this copy. Never accept a
+ // topic/operation from the UI or infer it from historical session rows.
+ const topic = await new TopicModel(serverDB, userId, workspaceId).findById(target.topicId);
+ if (!topic) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'Cannot resolve the holding conversation',
+ });
+ }
+ const model = new AgentOperationModel(serverDB, userId, workspaceId);
+ const operations = await model.findLiveByTopic(topic.id);
+ operationIds = operations.map((operation) => operation.id);
+ if (operations.some((op) => op.topicId !== topic.id)) {
+ throw new TRPCError({ code: 'CONFLICT', message: 'Cannot resolve the holding operation' });
+ }
+
+ // Recheck after DB IO. A stop prepared for one holder must not interrupt a
+ // different topic that acquired the instance while the lookup was pending.
+ const current = await client.readStopTarget({ name: id });
+ if (current?.sessionId !== target.sessionId || current.topicId !== target.topicId) {
+ throw new TRPCError({ code: 'CONFLICT', message: 'Environment instance holder changed' });
+ }
+ // Persist cancellation before interruption can make a live row terminal.
+ // The fence survives retries even when the next query no longer returns it.
+ const prepared = await client.prepareStop({
+ expectedSessionId: target.sessionId,
+ name: id,
+ operationIds,
+ });
+ if (!prepared.prepared) {
+ throw new TRPCError({ code: 'CONFLICT', message: 'Environment instance holder changed' });
+ }
+ for (const operation of operations) {
+ // Shared topics may run as another member. Use the scoped operation row's
+ // actor, never the execution plane's organization-level session identity.
+ const runtime = new AgentRuntimeService(serverDB, operation.userId, { workspaceId });
+ if (!(await runtime.interruptOperation(operation.id))) {
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message: 'Agent interruption could not be confirmed',
+ });
+ }
+ }
+ }
+
+ const result = await client.stopInstance({
+ expectedSessionId: target.sessionId,
+ name: id,
+ operationIds,
+ });
+ if (!result.stopped) {
+ throw new TRPCError({ code: 'CONFLICT', message: 'Environment instance holder changed' });
+ }
+ return result;
+};
diff --git a/apps/server/src/services/sandbox/storageFiles.ts b/apps/server/src/services/sandbox/storageFiles.ts
index d314a1fff13..b714998ad01 100644
--- a/apps/server/src/services/sandbox/storageFiles.ts
+++ b/apps/server/src/services/sandbox/storageFiles.ts
@@ -342,10 +342,43 @@ export const createSandboxStorageClient = ({ baseURL, headers }: SandboxStorageC
* packing. `stopped: false` means nothing held it. Control plane only β€”
* stopping a sandbox never starts one.
*/
- stopInstance: async (params: { name: string }): Promise<{ stopped: boolean }> =>
- request(`${CURRENT_STORAGE}/instances/${encodeURIComponent(params.name)}/stop`, {
- method: 'POST',
- }),
+ readStopTarget: async (params: {
+ name: string;
+ }): Promise<{ sessionId: string; topicId: string | null } | null> =>
+ request(`${CURRENT_STORAGE}/instances/${encodeURIComponent(params.name)}/stop-target`),
+
+ prepareStop: async (params: {
+ expectedSessionId: string;
+ name: string;
+ operationIds: string[];
+ }): Promise<{ prepared: boolean }> => {
+ const query = new URLSearchParams({
+ expectedSessionId: params.expectedSessionId,
+ prepare: 'true',
+ });
+ for (const id of params.operationIds) query.append('operationId', id);
+ return request(
+ `${CURRENT_STORAGE}/instances/${encodeURIComponent(params.name)}/stop?${query}`,
+ { method: 'POST' },
+ );
+ },
+
+ stopInstance: async (params: {
+ expectedSessionId?: string;
+ name: string;
+ operationIds?: string[];
+ }): Promise<{ stopped: boolean }> => {
+ const query = new URLSearchParams();
+ if (params.expectedSessionId) query.set('expectedSessionId', params.expectedSessionId);
+ for (const id of params.operationIds ?? []) query.append('operationId', id);
+ const suffix = query.size ? `?${query.toString()}` : '';
+ return request(
+ `${CURRENT_STORAGE}/instances/${encodeURIComponent(params.name)}/stop${suffix}`,
+ {
+ method: 'POST',
+ },
+ );
+ },
/**
* Start building an environment from its specification.
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts b/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts
index ae55249273a..70fb51c6a81 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts
@@ -4,7 +4,6 @@ import debug from 'debug';
import { UserModel } from '@/database/models/user';
import { FileService } from '@/server/services/file';
-import { MarketService } from '@/server/services/market';
import { createSandboxService, resolveSandboxSessionConfig } from '@/server/services/sandbox';
import {
isDirectLhInvocation,
@@ -14,6 +13,7 @@ import {
} from '@/server/services/toolExecution/preprocessLhCommand';
import { resolveContentWorkspaceId } from './resolveWorkspaceScope';
+import { createSandboxMarketService } from './sandboxMarket';
import { type ServerRuntimeRegistration } from './types';
const log = debug('lobe-server:cloud-sandbox');
@@ -151,14 +151,12 @@ export const cloudSandboxRuntime: ServerRuntimeRegistration = {
workspaceId,
});
- const marketService = new MarketService({
+ const marketService = createSandboxMarketService(
+ context,
accessToken,
- userInfo: {
- sandboxStorage: sandbox.claim,
- userId: context.userId,
- workspaceId,
- },
- });
+ workspaceId,
+ sandbox.claim,
+ );
const fileService = new FileService(context.serverDB, context.userId, workspaceId);
const sandboxService = createSandboxService({
fileService,
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/creds.ts b/apps/server/src/services/toolExecution/serverRuntimes/creds.ts
index 1095c629c12..bcebcd5eae4 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/creds.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/creds.ts
@@ -4,10 +4,11 @@ import debug from 'debug';
import { UserModel } from '@/database/models/user';
import { WorkspaceMemberModel } from '@/database/models/workspaceMember';
-import { MarketService } from '@/server/services/market';
+import type { MarketService } from '@/server/services/market';
import { resolveSandboxSessionConfig } from '@/server/services/sandbox';
import { resolveContentWorkspaceId } from './resolveWorkspaceScope';
+import { createSandboxMarketService } from './sandboxMarket';
import { type ServerRuntimeRegistration } from './types';
const log = debug('lobe-server:creds-runtime');
@@ -234,14 +235,12 @@ export const credsRuntime: ServerRuntimeRegistration = {
workspaceId,
});
- const marketService = new MarketService({
+ const marketService = createSandboxMarketService(
+ context,
accessToken,
- userInfo: {
- sandboxStorage: sandbox.claim,
- userId: context.userId,
- workspaceId,
- },
- });
+ workspaceId,
+ sandbox.claim,
+ );
const credsService = new ServerCredsService(
marketService,
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/sandboxMarket.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/sandboxMarket.test.ts
new file mode 100644
index 00000000000..afe7797f11f
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/sandboxMarket.test.ts
@@ -0,0 +1,20 @@
+import { expect, it, vi } from 'vitest';
+
+import type { ToolExecutionContext } from '../types';
+import { createSandboxMarketService } from './sandboxMarket';
+
+const construct = vi.hoisted(() => vi.fn());
+vi.mock('@/server/services/market', () => ({
+ MarketService: class {
+ constructor(options: unknown) {
+ construct(options);
+ }
+ },
+}));
+
+it('requires a runtime owner before issuing an execution identity', () => {
+ expect(() =>
+ createSandboxMarketService({} as ToolExecutionContext, undefined, undefined, null),
+ ).toThrow('userId is required');
+ expect(construct).not.toHaveBeenCalled();
+});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/sandboxMarket.ts b/apps/server/src/services/toolExecution/serverRuntimes/sandboxMarket.ts
new file mode 100644
index 00000000000..bc3846c81a3
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/sandboxMarket.ts
@@ -0,0 +1,27 @@
+import type { SandboxStorageClaim } from '@lobechat/builtin-tool-cloud-sandbox';
+
+import { MarketService } from '@/server/services/market';
+
+import type { ToolExecutionContext } from '../types';
+
+/** The runtime context supplies identity; tool arguments cannot select another operation. */
+export const createSandboxMarketService = (
+ context: ToolExecutionContext,
+ accessToken: string | undefined,
+ workspaceId: string | undefined,
+ sandboxStorage: SandboxStorageClaim | null | undefined,
+) => {
+ if (!context.userId) throw new Error('userId is required for sandbox execution');
+ return new MarketService({
+ accessToken,
+ userInfo: {
+ sandboxOperation:
+ context.operationId && context.topicId
+ ? { operationId: context.operationId, topicId: context.topicId }
+ : undefined,
+ sandboxStorage,
+ userId: context.userId,
+ workspaceId,
+ },
+ });
+};
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
index e291b920f22..34f6d83d6f7 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
@@ -37,7 +37,7 @@ import { AgentDocumentsService } from '@/server/services/agentDocuments';
import { deviceGateway } from '@/server/services/deviceGateway';
import { executeAuthorizedDeviceToolCall } from '@/server/services/deviceGateway/authorizedToolCall';
import { FileService } from '@/server/services/file';
-import { MarketService } from '@/server/services/market';
+import type { MarketService } from '@/server/services/market';
import {
createSandboxService,
normalizeSandboxCommandResult,
@@ -58,6 +58,7 @@ import {
} from '@/server/services/userSkill';
import { resolveContentWorkspaceId, resolveRunWorkspaceId } from './resolveWorkspaceScope';
+import { createSandboxMarketService } from './sandboxMarket';
import { type ServerRuntimeRegistration } from './types';
const log = debug('lobe-server:skills-runtime');
@@ -912,14 +913,12 @@ export const skillsRuntime: ServerRuntimeRegistration = {
workspaceId,
});
- const marketService = new MarketService({
- accessToken: marketAccessToken,
- userInfo: {
- sandboxStorage: sandbox.claim,
- userId: context.userId,
- workspaceId,
- },
- });
+ const marketService = createSandboxMarketService(
+ context,
+ marketAccessToken,
+ workspaceId,
+ sandbox.claim,
+ );
const fileService = new FileService(context.serverDB, context.userId, workspaceId);
const fileModel = new FileModel(context.serverDB, context.userId, workspaceId);
diff --git a/packages/database/src/models/__tests__/agentOperation.stop.test.ts b/packages/database/src/models/__tests__/agentOperation.stop.test.ts
new file mode 100644
index 00000000000..61aac442fa2
--- /dev/null
+++ b/packages/database/src/models/__tests__/agentOperation.stop.test.ts
@@ -0,0 +1,62 @@
+// @vitest-environment node
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { agentOperations, topics, users, workspaces } from '../../schemas';
+import { AgentOperationModel } from '../agentOperation';
+
+const db = await getTestDB();
+const owner = 'stop-query-owner';
+const member = 'stop-query-member';
+const workspace = 'stop-query-workspace';
+
+beforeAll(async () => {
+ await db.insert(users).values([{ id: owner }, { id: member }]);
+ await db
+ .insert(workspaces)
+ .values({ id: workspace, name: 'Stop query test', slug: workspace, primaryOwnerId: owner });
+ await db.insert(topics).values([
+ { id: 'stop-personal', userId: owner },
+ { id: 'stop-team', userId: member, workspaceId: workspace },
+ ]);
+});
+afterAll(async () => {
+ const { eq, inArray } = await import('drizzle-orm');
+ await db.delete(agentOperations).where(inArray(agentOperations.userId, [owner, member]));
+ await db.delete(topics).where(inArray(topics.id, ['stop-personal', 'stop-team']));
+ await db.delete(workspaces).where(eq(workspaces.id, workspace));
+ await db.delete(users).where(inArray(users.id, [owner, member]));
+});
+
+describe('durable live operations for stopping a topic', () => {
+ it('finds all live states without a topic rendering marker and excludes terminal or foreign rows', async () => {
+ const personal = new AgentOperationModel(db, owner);
+ const team = new AgentOperationModel(db, member, workspace);
+ const states = [
+ 'running',
+ 'waiting_for_human',
+ 'waiting_for_async_tool',
+ 'waiting_for_client',
+ 'done',
+ ] as const;
+ await db.insert(agentOperations).values(
+ states.map((status) => ({
+ id: `stop-personal-${status}`,
+ status,
+ topicId: 'stop-personal',
+ userId: owner,
+ })),
+ );
+ await team.recordStart({ operationId: 'stop-team-live', topicId: 'stop-team' });
+ expect((await personal.findLiveByTopic('stop-personal')).map((op) => op.status).sort()).toEqual(
+ states.filter((status) => status !== 'done').sort(),
+ );
+ expect(await new AgentOperationModel(db, member).findLiveByTopic('stop-personal')).toEqual([]);
+ expect(await personal.findLiveByTopic('stop-team')).toEqual([]);
+ expect(
+ (await new AgentOperationModel(db, owner, workspace).findLiveByTopic('stop-team')).map(
+ (op) => op.userId,
+ ),
+ ).toEqual([member]);
+ });
+});
diff --git a/packages/database/src/models/agentOperation.ts b/packages/database/src/models/agentOperation.ts
index fa57ca16e6e..f346fe2a2cf 100644
--- a/packages/database/src/models/agentOperation.ts
+++ b/packages/database/src/models/agentOperation.ts
@@ -19,6 +19,7 @@ import { agentOperations } from '../schemas/agentOperations';
import type { LobeChatDatabase } from '../type';
import { notShareVisitorTopicRef } from '../utils/shareVisitor';
import { buildWorkspaceWhere } from '../utils/workspace';
+import { findLiveTopicOperations, findScopedOperation } from './agentOperationQueries';
/**
* Verify rollup states. Aliases the single `VerifyRunStatus` source of truth in
@@ -660,17 +661,16 @@ export class AgentOperationModel {
* Raw ownership-scoped lookup. Agent-share visitor runs execute under the
* CREATOR's identity, so this DOES return their operations β€” required by the
* agent runtime (execution, intervention, completion, verify, abandon), which
- * has to resolve the operation it is currently driving no matter who started
- * it. Creator-facing read entry points must use
+ * resolves its current operation regardless of who started it. Creator-facing reads use
* {@link AgentOperationModel.findOwnOperationById} instead.
*/
async findById(operationId: string) {
- const [row] = await this.db
- .select()
- .from(agentOperations)
- .where(and(eq(agentOperations.id, operationId), this.ownership()))
- .limit(1);
- return row ?? null;
+ return findScopedOperation(this.db, this.ownership(), operationId);
+ }
+
+ /** All resumable operations in a proven topic, independent of its UI marker. */
+ async findLiveByTopic(topicId: string) {
+ return findLiveTopicOperations(this.db, this.ownership(), topicId);
}
/** Batch lookup for callers that would otherwise issue one query per id. */
diff --git a/packages/database/src/models/agentOperationQueries.ts b/packages/database/src/models/agentOperationQueries.ts
new file mode 100644
index 00000000000..12c70c3e0e1
--- /dev/null
+++ b/packages/database/src/models/agentOperationQueries.ts
@@ -0,0 +1,38 @@
+import { and, eq, inArray, type SQL } from 'drizzle-orm';
+
+import { agentOperations } from '../schemas/agentOperations';
+import type { LobeChatDatabase } from '../type';
+
+export const findScopedOperation = async (
+ db: LobeChatDatabase,
+ ownership: SQL | undefined,
+ operationId: string,
+) => {
+ const [row] = await db
+ .select()
+ .from(agentOperations)
+ .where(and(eq(agentOperations.id, operationId), ownership))
+ .limit(1);
+ return row ?? null;
+};
+
+export const findLiveTopicOperations = (
+ db: LobeChatDatabase,
+ ownership: SQL | undefined,
+ topicId: string,
+) =>
+ db
+ .select()
+ .from(agentOperations)
+ .where(
+ and(
+ ownership,
+ eq(agentOperations.topicId, topicId),
+ inArray(agentOperations.status, [
+ 'running',
+ 'waiting_for_human',
+ 'waiting_for_async_tool',
+ 'waiting_for_client',
+ ]),
+ ),
+ );
diff --git a/src/libs/trusted-client/index.ts b/src/libs/trusted-client/index.ts
index 3703300f41d..101ae538d71 100644
--- a/src/libs/trusted-client/index.ts
+++ b/src/libs/trusted-client/index.ts
@@ -18,6 +18,7 @@ export interface TrustedClientUserInfo {
* It rides the token rather than the request body on purpose: it is the one
* thing the execution plane must not let a caller choose for itself.
*/
+ sandboxOperation?: { operationId: string; topicId: string };
sandboxStorage?: SandboxStorageClaim | null;
userId: string;
/**
@@ -89,9 +90,11 @@ export const generateTrustedClientToken = (userInfo: TrustedClientUserInfo): str
// Omitted when there is no entitlement, which is the free-tier shape and
// leaves today's tokens unchanged.
// TODO: pass through buildTrustedClientPayload once the SDK carries it.
- const signedPayload: TrustedClientPayload = userInfo.sandboxStorage
- ? ({ ...payload, sandboxStorage: userInfo.sandboxStorage } as TrustedClientPayload)
- : payload;
+ const signedPayload: TrustedClientPayload = {
+ ...payload,
+ ...(userInfo.sandboxStorage && { sandboxStorage: userInfo.sandboxStorage }),
+ ...(userInfo.sandboxOperation && { sandboxOperation: userInfo.sandboxOperation }),
+ };
return createTrustedClientToken(signedPayload, MARKET_TRUSTED_CLIENT_SECRET);
} catch (error) {