π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(sandbox): export files from the session the conversation's commands run in (#23442)
AmAzing-e6bcd1368253
diff --git a/apps/server/src/routers/tools/market.test.ts b/apps/server/src/routers/tools/market.test.tsindex 42c042ae3b5..9964b8f670b 100644--- a/apps/server/src/routers/tools/market.test.ts+++ b/apps/server/src/routers/tools/market.test.ts@@ -2,17 +2,24 @@import { MarketAPIError } from '@lobehub/market-sdk';import { beforeEach, describe, expect, it, vi } from 'vitest';+import type * as MarketServiceModule from '@/server/services/market';+import { marketRouter } from './market';const mockPreprocessLhCommand = vi.hoisted(() => vi.fn());const mockSandboxCallTool = vi.hoisted(() => vi.fn());+const mockSandboxExportAndUploadFile = vi.hoisted(() => vi.fn());const mockCreateSandboxService = vi.hoisted(() =>vi.fn(function () {return {callTool: mockSandboxCallTool,+ exportAndUploadFile: mockSandboxExportAndUploadFile,};}),);+// Records what each MarketService was built with, so a test can see whether+// the storage claim rode on the token a sandbox call is signed with.+const mockMarketServiceOptions = vi.hoisted(() => [] as unknown[]);const mockResolveSandboxSessionConfig = vi.hoisted(() =>vi.fn(async () => ({ claim: null, mode: 'ephemeral' as const })),);@@ -56,6 +63,17 @@ vi.mock('@/server/services/file', () => ({}),}));+vi.mock('@/server/services/market', async (importOriginal) => {+ const actual = await importOriginal<typeof MarketServiceModule>();+ return {+ ...actual,+ MarketService: vi.fn(function (options: unknown) {+ mockMarketServiceOptions.push(options);+ return new actual.MarketService(options as never);+ }),+ };+});+vi.mock('@/server/services/sandbox', () => ({createSandboxService: mockCreateSandboxService,resolveSandboxSessionConfig: mockResolveSandboxSessionConfig,@@ -74,6 +92,7 @@ vi.mock('debug', () => ({describe('tools marketRouter', () => {beforeEach(() => {vi.clearAllMocks();+ mockMarketServiceOptions.length = 0;});it('should pass workspace scope when preprocessing sandbox lh commands', async () => {@@ -180,6 +199,132 @@ describe('tools marketRouter', () => {);});+ // Regression (T-14039): the export route opened its session with only+ // `topicId` and `userId` β no mode, no directory, no claim β while+ // `execInSandbox` opened the topic's persistent one. The execution plane+ // routed the export to the ephemeral runtime, so a file a command wrote under+ // `/mnt/workspace/ws-user_*` was "not found" in `/workspace`, `/root` and+ // `/tmp`, whatever path the model passed, and copies made there did not help.+ it('exports from the session the conversation commands run in', async () => {+ const caller = marketRouter.createCaller({+ serverDB: {},+ userId: 'caller-user',+ workspaceId: 'ws-1',+ } as any);+ const claim = { drive: 'personal', key: 'ws-user_caller-user', quotaBytes: 1024 };+ const specification = { env: { NODE_ENV: 'production' } };+ mockResolveSandboxSessionConfig.mockResolvedValueOnce({+ claim,+ cwd: 'reports',+ environment: 'env-1',+ mode: 'drive',+ specification,+ workingDir: '/home/user/reports',+ } as never);+ mockSandboxExportAndUploadFile.mockResolvedValue({+ fileId: 'file-1',+ filename: 'report.pdf',+ success: true,+ url: '/f/file-1',+ });++ const result = await caller.exportAndUploadFile({+ filename: 'report.pdf',+ path: '/mnt/workspace/ws-user_caller-user/reports/report.pdf',+ topicId: 'topic-1',+ });++ expect(result).toMatchObject({ fileId: 'file-1', success: true });+ expect(mockResolveSandboxSessionConfig).toHaveBeenCalledWith(+ expect.objectContaining({+ isShareVisitorRun: false,+ topicId: 'topic-1',+ userId: 'caller-user',+ workspaceId: 'ws-1',+ }),+ );+ expect(mockCreateSandboxService).toHaveBeenCalledWith(+ expect.objectContaining({+ sandboxCwd: 'reports',+ sandboxInstanceId: 'env-1',+ sandboxMode: 'drive',+ sandboxSpecification: specification,+ sandboxWorkingDir: '/home/user/reports',+ topicId: 'topic-1',+ userId: 'caller-user',+ }),+ );+ // The entitlement is read off the token, so it has to be on the one the+ // export is signed with, not only on the request.+ expect(mockMarketServiceOptions).toContainEqual(+ expect.objectContaining({+ userInfo: expect.objectContaining({ sandboxStorage: claim, userId: 'caller-user' }),+ }),+ );+ expect(mockSandboxExportAndUploadFile).toHaveBeenCalledWith(+ '/mnt/workspace/ws-user_caller-user/reports/report.pdf',+ 'report.pdf',+ );+ });++ // The two routes the client-side executor uses must agree on the session:+ // a call that names another placement for the same topic runs elsewhere, and+ // can tear down the live session on the way.+ it('opens the same session for an export as for a command', async () => {+ const caller = marketRouter.createCaller({+ serverDB: {},+ userId: 'caller-user',+ workspaceId: 'ws-1',+ } as any);+ const sessionConfig = {+ claim: { key: 'ws-org-ws-1', quotaBytes: 1024 },+ cwd: 'lobehub-dev',+ environment: 'env-1',+ mode: 'persistent',+ workingDir: '/home/user/lobehub-dev',+ };+ mockResolveSandboxSessionConfig+ .mockResolvedValueOnce(sessionConfig as never)+ .mockResolvedValueOnce(sessionConfig as never);+ mockSandboxCallTool.mockResolvedValue({ result: { ok: true }, success: true });+ mockSandboxExportAndUploadFile.mockResolvedValue({ filename: 'out.csv', success: true });++ await caller.execInSandbox({+ params: { command: 'python make_csv.py' },+ toolName: 'runCommand',+ topicId: 'topic-1',+ });+ await caller.exportAndUploadFile({ filename: 'out.csv', path: 'out.csv', topicId: 'topic-1' });++ const [commandSession, exportSession] = mockCreateSandboxService.mock.calls.map(+ ([options]: any[]) => {+ const { marketService: _marketService, ...rest } = options;+ return rest;+ },+ );+ expect(exportSession).toEqual(commandSession);+ });++ it('keeps an ephemeral topic on the caller market service when no claim resolves', async () => {+ const caller = marketRouter.createCaller({+ serverDB: {},+ userId: 'caller-user',+ workspaceId: null,+ } as any);+ mockSandboxExportAndUploadFile.mockResolvedValue({ filename: 'a.txt', success: true });++ await caller.exportAndUploadFile({ filename: 'a.txt', path: 'a.txt', topicId: 'topic-1' });++ expect(mockCreateSandboxService).toHaveBeenCalledWith(+ expect.objectContaining({ sandboxMode: 'ephemeral', topicId: 'topic-1' }),+ );+ expect(mockMarketServiceOptions).not.toContainEqual(+ expect.objectContaining({+ userInfo: expect.objectContaining({ sandboxStorage: expect.anything() }),+ }),+ );+ });+// Regression: `input.userId` used to override `ctx.userId`, so any// authenticated caller could make the server mint another user's JWT into a// sandbox command they control (and read their skills/files).diff --git a/apps/server/src/routers/tools/market.ts b/apps/server/src/routers/tools/market.tsindex 1d5d3f57ee7..57700d5e3a1 100644--- a/apps/server/src/routers/tools/market.ts+++ b/apps/server/src/routers/tools/market.ts@@ -179,19 +179,72 @@ export interface ExportAndUploadFileResult {}// ============================== Sandbox Handler ==============================+interface SandboxRouteContext {+ fileService: FileService;+ marketAccessToken?: string;+ marketService: MarketService;+ marketUserInfo?: TrustedClientUserInfo;+ serverDB: any;+ userId: string;+ workspaceId?: string | null;+}++/**+ * The topic's sandbox, opened the way the server runtimes open it: with the+ * persistence the topic resolved and, when it has one, the storage claim on+ * the token the call is signed with.+ *+ * Every route here that reaches a topic's sandbox must open it through this.+ * The execution plane binds a topic's session to the placement its call names,+ * and a token without the claim routes to the ephemeral runtime. A route that+ * skipped it ran in another sandbox than the conversation's commands. This+ * happened to `exportAndUploadFile`: files a command wrote under+ * `/mnt/workspace/ws-*` were "not found" in `/workspace`, `/root` and `/tmp`,+ * and the live session could be torn down on the way.+ */+const createTopicSandboxService = async (ctx: SandboxRouteContext, topicId: string) => {+ // The persistent workspace, resolved the same way the server runtimes do.+ // These routes are the client-side executor's way into the sandbox β the one+ // a conversation uses when its tool calls are not dispatched server-side.+ const sandbox = await resolveSandboxSessionConfig({+ // Direct client call, so the caller is always acting as themselves.+ isShareVisitorRun: false,+ serverDB: ctx.serverDB,+ topicId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId ?? undefined,+ });++ // The claim has to ride on the identity this call is signed with, not just+ // on the request: the execution plane reads the entitlement off the trusted+ // client token, and `ctx.marketService` was built before it was known.+ const marketService = sandbox.claim+ ? new MarketService({+ accessToken: ctx.marketAccessToken,+ userInfo: { ...ctx.marketUserInfo, sandboxStorage: sandbox.claim, userId: ctx.userId },+ })+ : ctx.marketService;++ return createSandboxService({+ fileService: ctx.fileService,+ marketService,+ sandboxCwd: sandbox.cwd,+ sandboxInitialization: sandbox.initialization,+ sandboxInstanceId: sandbox.environment,+ sandboxMode: sandbox.mode,+ sandboxSpecification: sandbox.specification,+ sandboxWorkingDir: sandbox.workingDir,+ serverDB: ctx.serverDB,+ topicId,+ userId: ctx.userId,+ });+};+const execInSandboxHandler = async ({input,ctx,}: {- ctx: {- fileService: FileService;- marketAccessToken?: string;- marketService: MarketService;- marketUserInfo?: TrustedClientUserInfo;- serverDB: any;- userId: string;- workspaceId?: string | null;- };+ ctx: SandboxRouteContext;input: ExecInSandboxInput;}): Promise<CallToolResult> => {const { toolName, params, topicId } = input;@@ -277,45 +330,10 @@ const execInSandboxHandler = async ({}}- // The persistent workspace, resolved the same way the server runtimes do.- // This route is the client-side executor's way into the sandbox β the one a- // conversation uses when its tool calls are not dispatched server-side β- // and it used to open a session with no mode, no directory and no claim.- // Every run through here was therefore ephemeral: the composer showed the- // instance the topic had chosen while `pwd` answered `/workspace`, and- // whatever the run wrote went nowhere the file browser reads.- const sandbox = await resolveSandboxSessionConfig({- // Direct client call, so the caller is always acting as themselves.- isShareVisitorRun: false,- serverDB: ctx.serverDB,- topicId,- userId,- workspaceId: ctx.workspaceId ?? undefined,- });-- // The claim has to ride on the identity this call is signed with, not just- // on the request: the execution plane reads the entitlement off the trusted- // client token, and `ctx.marketService` was built before it was known.- const marketService = sandbox.claim- ? new MarketService({- accessToken: ctx.marketAccessToken,- userInfo: { ...ctx.marketUserInfo, sandboxStorage: sandbox.claim, userId: ctx.userId },- })- : ctx.marketService;-- const sandboxService = createSandboxService({- fileService: ctx.fileService,- marketService,- sandboxCwd: sandbox.cwd,- sandboxInitialization: sandbox.initialization,- sandboxInstanceId: sandbox.environment,- sandboxMode: sandbox.mode,- sandboxSpecification: sandbox.specification,- sandboxWorkingDir: sandbox.workingDir,- serverDB: ctx.serverDB,- topicId,- userId,- });+ // This route used to open a session with no mode, no directory and no+ // claim, so every run through it was ephemeral: the composer showed the+ // instance the topic had chosen while `pwd` answered `/workspace`.+ const sandboxService = await createTopicSandboxService(ctx, topicId);const response = await sandboxService.callTool(toolName, enhancedParams);@@ -746,12 +764,10 @@ export const marketRouter = router({log('Exporting and uploading file: %s from path: %s in topic: %s', filename, path, topicId);try {- const sandboxService = createSandboxService({- fileService: ctx.fileService,- marketService: ctx.marketService,- topicId,- userId: ctx.userId,- });+ // The same session `execInSandbox` opens for this topic. An export+ // opened with only `topicId` and `userId` ran ephemeral, in a sandbox+ // that could not see what the conversation's commands had written.+ const sandboxService = await createTopicSandboxService(ctx, topicId);const result = await sandboxService.exportAndUploadFile(path, filename);if (!result.success && isSandboxAuthError(result.error)) {