🤯 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: surface sandbox recreation in tool results (#19329)
YuTengjing6261fa7f84b8
diff --git a/apps/server/src/services/sandbox/__tests__/computerRuntime.test.ts b/apps/server/src/services/sandbox/__tests__/computerRuntime.test.tsindex c0e33136810..7e9f0110c2f 100644--- a/apps/server/src/services/sandbox/__tests__/computerRuntime.test.ts+++ b/apps/server/src/services/sandbox/__tests__/computerRuntime.test.ts@@ -1,6 +1,7 @@+import { CloudSandboxExecutionRuntime } from '@lobechat/builtin-tool-cloud-sandbox/executionRuntime';import type { ServiceResult } from '@lobechat/tool-runtime';import { ComputerRuntime } from '@lobechat/tool-runtime';-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';class TestComputerRuntime extends ComputerRuntime {constructor(private readonly serviceResult: ServiceResult) {@@ -12,6 +13,34 @@ class TestComputerRuntime extends ComputerRuntime {}}+describe.each(['runCommand', 'executeCode', 'getCommandOutput'] as const)(+ 'CloudSandbox %s recreation',+ (api) => {+ it.each([true, false])('surfaces recreation with transport success %s', async (success) => {+ const runtime = new CloudSandboxExecutionRuntime({+ callTool: vi.fn().mockResolvedValue({+ error: success ? undefined : { message: 'missing input file' },+ result: { exitCode: success ? 0 : 1, output: 'partial output' },+ sessionExpiredAndRecreated: true,+ success,+ }),+ exportAndUploadFile: vi.fn(),+ });++ const result =+ api === 'runCommand'+ ? await runtime.runCommand({ command: 'cat /tmp/input' })+ : api === 'executeCode'+ ? await runtime.executeCode({ code: 'print("output")' })+ : await runtime.getCommandOutput({ commandId: 'task-1' });++ expect(result.content).toContain('sandbox session expired and was recreated');+ expect(result.content).toContain(success ? 'partial output' : 'missing input file');+ expect(result.state).toMatchObject({ sessionExpiredAndRecreated: true, success });+ });+ },+);+describe('ComputerRuntime command status mapping', () => {it('uses command result success when command transport succeeds with non-zero exit code', async () => {const runtime = new TestComputerRuntime({diff --git a/apps/server/src/services/sandbox/__tests__/service.test.ts b/apps/server/src/services/sandbox/__tests__/service.test.tsindex c51d15742a3..72f1bea351e 100644--- a/apps/server/src/services/sandbox/__tests__/service.test.ts+++ b/apps/server/src/services/sandbox/__tests__/service.test.ts@@ -5,6 +5,51 @@ import type { MarketService } from '@/server/services/market';import type { SandboxProvider } from '../types';+describe('normalizeSandboxCommandResult', () => {+ it('preserves recreation when the command fails inside a successful response', async () => {+ const { normalizeSandboxCommandResult } = await import('../service');++ expect(+ normalizeSandboxCommandResult({+ result: { exitCode: 1, stderr: 'missing input file', stdout: '' },+ sessionExpiredAndRecreated: true,+ success: true,+ }),+ ).toEqual({+ exitCode: 1,+ output: '',+ sessionExpiredAndRecreated: true,+ stderr: 'missing input file',+ success: false,+ });+ });++ it.each([undefined, false])('does not report recreation for flag %s', async (flag) => {+ const { normalizeSandboxCommandResult } = await import('../service');++ expect(+ normalizeSandboxCommandResult({+ result: { exitCode: 0, stdout: 'output' },+ sessionExpiredAndRecreated: flag,+ success: true,+ }),+ ).toEqual({ exitCode: 0, output: 'output', stderr: undefined, success: true });+ });++ it.each([true, false])('preserves recreation when transport success is %s', async (success) => {+ const { normalizeSandboxCommandResult } = await import('../service');++ expect(+ normalizeSandboxCommandResult({+ error: success ? undefined : { message: 'missing file' },+ result: { exitCode: 0, stdout: 'output' },+ sessionExpiredAndRecreated: true,+ success,+ }),+ ).toMatchObject({ sessionExpiredAndRecreated: true, success });+ });+});+describe('SandboxMiddlewareService', () => {beforeEach(() => {vi.resetModules();diff --git a/apps/server/src/services/sandbox/service.ts b/apps/server/src/services/sandbox/service.tsindex d1dc408f8f4..7b0826acde6 100644--- a/apps/server/src/services/sandbox/service.ts+++ b/apps/server/src/services/sandbox/service.ts@@ -197,8 +197,12 @@ export class SandboxMiddlewareService implements SandboxService {export const normalizeSandboxCommandResult = (result: SandboxCallToolResult,): SandboxCommandResult => {+ const sessionState = result.sessionExpiredAndRecreated+ ? { sessionExpiredAndRecreated: true }+ : {};if (!result.success) {return {+ ...sessionState,exitCode: 1,output: '',stderr: result.error?.message || 'Command execution failed',@@ -214,6 +218,7 @@ export const normalizeSandboxCommandResult = (const success = typeof raw.success === 'boolean' ? raw.success : exitCode === 0;return {+ ...sessionState,exitCode,output,stderr,diff --git a/apps/server/src/services/sandbox/types.ts b/apps/server/src/services/sandbox/types.tsindex bc732bbd52e..1ab05d880b5 100644--- a/apps/server/src/services/sandbox/types.ts+++ b/apps/server/src/services/sandbox/types.ts@@ -72,6 +72,8 @@ export interface SandboxProviderFileExportResult {export interface SandboxCommandResult {exitCode: number;output: string;+ /** The provider recreated the workspace before executing this command. */+ sessionExpiredAndRecreated?: boolean;stderr?: string;success: boolean;}diff --git a/packages/builtin-tool-cloud-sandbox/package.json b/packages/builtin-tool-cloud-sandbox/package.jsonindex 619a8172fd5..14f9e85bff8 100644--- a/packages/builtin-tool-cloud-sandbox/package.json+++ b/packages/builtin-tool-cloud-sandbox/package.json@@ -11,6 +11,7 @@"main": "./src/index.ts","dependencies": {"@lobechat/builtin-tool-local-system": "workspace:*",+ "@lobechat/prompts": "workspace:*","@lobechat/shared-tool-ui": "workspace:*","@lobechat/tool-runtime": "workspace:*"},diff --git a/packages/builtin-tool-cloud-sandbox/src/ExecutionRuntime/index.ts b/packages/builtin-tool-cloud-sandbox/src/ExecutionRuntime/index.tsindex dce15a1578c..9f21250027e 100644--- a/packages/builtin-tool-cloud-sandbox/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-cloud-sandbox/src/ExecutionRuntime/index.ts@@ -1,3 +1,4 @@+import { formatSandboxRecreation } from '@lobechat/prompts/fileSystem';import { ComputerRuntime } from '@lobechat/tool-runtime';import type { BuiltinServerRuntimeOutput } from '@lobechat/types';@@ -46,6 +47,7 @@ export class CloudSandboxExecutionRuntime extends ComputerRuntime {});const state: ExecuteCodeState = {+ ...(result.sessionExpiredAndRecreated && { sessionExpiredAndRecreated: true }),error: result.result?.error,exitCode: result.result?.exitCode,language,@@ -56,14 +58,20 @@ export class CloudSandboxExecutionRuntime extends ComputerRuntime {if (!result.success) {return {- content: result.error?.message || JSON.stringify(result.error),+ content: formatSandboxRecreation(+ result.error?.message || JSON.stringify(result.error),+ result.sessionExpiredAndRecreated,+ ),state,success: true,};}return {- content: JSON.stringify(result.result),+ content: formatSandboxRecreation(+ JSON.stringify(result.result),+ result.sessionExpiredAndRecreated,+ ),state,success: true,};diff --git a/packages/builtin-tool-cloud-sandbox/src/systemRole.ts b/packages/builtin-tool-cloud-sandbox/src/systemRole.tsindex 6dc01224d06..f2da055c319 100644--- a/packages/builtin-tool-cloud-sandbox/src/systemRole.ts+++ b/packages/builtin-tool-cloud-sandbox/src/systemRole.ts@@ -222,7 +222,7 @@ When generating PDFs with Chinese text, you MUST:<session_behavior>- Your sandbox session is automatically managed per conversation topic- If a session expires, it will be automatically recreated-- Files from previous sessions may not persist; recreate them as needed+- Files from previous sessions may not persist- The sessionExpiredAndRecreated flag in responses indicates if this occurred</session_behavior>diff --git a/packages/builtin-tool-cloud-sandbox/src/types/state.ts b/packages/builtin-tool-cloud-sandbox/src/types/state.tsindex e07930151f6..340f214eebf 100644--- a/packages/builtin-tool-cloud-sandbox/src/types/state.ts+++ b/packages/builtin-tool-cloud-sandbox/src/types/state.ts@@ -42,6 +42,8 @@ export interface ExecuteCodeState {language: 'javascript' | 'python' | 'typescript';/** Standard output from execution */output?: string;+ /** The sandbox workspace was recreated before this code executed. */+ sessionExpiredAndRecreated?: boolean;/** Standard error from execution */stderr?: string;/** Whether the execution was successful */diff --git a/packages/builtin-tool-skills/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-skills/src/ExecutionRuntime/index.test.tsindex 2a4aa435ef6..933a9dedd44 100644--- a/packages/builtin-tool-skills/src/ExecutionRuntime/index.test.ts+++ b/packages/builtin-tool-skills/src/ExecutionRuntime/index.test.ts@@ -12,6 +12,29 @@ const createMockService = (overrides?: Partial<SkillRuntimeService>): SkillRunti});describe('SkillsExecutionRuntime', () => {+ describe.each(['runCommand', 'execScript'] as const)('%s sandbox recreation', (api) => {+ it.each([true, false])('reports workspace loss when command success is %s', async (success) => {+ const commandResult = {+ exitCode: success ? 0 : 1,+ output: 'command output',+ sessionExpiredAndRecreated: true,+ stderr: success ? undefined : 'missing input file',+ success,+ } satisfies CommandResult;+ const runtime = new SkillsExecutionRuntime({+ service: createMockService({ [api]: vi.fn().mockResolvedValue(commandResult) }),+ });++ const result = await runtime[api]({ command: 'cat /tmp/input', description: 'Read input' });++ expect(result.content).toContain('sandbox session expired and was recreated');+ expect(result.content).toContain('Inform the user and ask before regenerating previous work');+ expect(result.content).toContain('command output');+ expect(result.state).toMatchObject({ sessionExpiredAndRecreated: true, success });+ expect(result.success).toBe(success);+ });+ });+describe('execScript', () => {const args = { command: 'echo hello', description: 'test command' };diff --git a/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts b/packages/builtin-tool-skills/src/ExecutionRuntime/index.tsindex 8f1fcd204ee..59836837cf6 100644--- a/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts@@ -1,5 +1,9 @@import { AGENT_SKILLS_IDENTIFIER_PREFIX } from '@lobechat/const';-import { formatCommandResult, resourcesTreePrompt } from '@lobechat/prompts';+import {+ formatCommandResult,+ formatSandboxRecreation,+ resourcesTreePrompt,+} from '@lobechat/prompts';import type {BuiltinServerRuntimeOutput,BuiltinSkill,@@ -525,9 +529,10 @@ export class SkillsExecutionRuntime {});return {- content,+ content: formatSandboxRecreation(content, result.sessionExpiredAndRecreated),state: {command,+ ...(result.sessionExpiredAndRecreated && { sessionExpiredAndRecreated: true }),...(result.executionEnv && { executionEnv: result.executionEnv }),exitCode: result.exitCode,...(result.outputFiles && { outputFiles: result.outputFiles }),diff --git a/packages/builtin-tool-skills/src/types.ts b/packages/builtin-tool-skills/src/types.tsindex 81693ba2593..021e7f86731 100644--- a/packages/builtin-tool-skills/src/types.ts+++ b/packages/builtin-tool-skills/src/types.ts@@ -54,6 +54,8 @@ export interface ExecScriptState {*/exitCode?: number;outputFiles?: CommandResult['outputFiles'];+ /** The sandbox workspace was recreated before this command. */+ sessionExpiredAndRecreated?: boolean;/*** Shell handle for a still-running command, pollable via* `local-system.getCommandOutput`.@@ -88,6 +90,8 @@ export interface CommandResult {stderr?: { path: string; size?: number; truncated?: boolean };stdout?: { path: string; size?: number; truncated?: boolean };};+ /** The sandbox workspace was recreated before this command. */+ sessionExpiredAndRecreated?: boolean;/*** Shell handle for a still-running command, pollable via* `local-system.getCommandOutput`.diff --git a/packages/prompts/src/prompts/fileSystem/formatSandboxRecreation.ts b/packages/prompts/src/prompts/fileSystem/formatSandboxRecreation.tsnew file mode 100644index 00000000000..b9130d82e15--- /dev/null+++ b/packages/prompts/src/prompts/fileSystem/formatSandboxRecreation.ts@@ -0,0 +1,5 @@+/** Keep workspace loss visible even when the command itself completed successfully. */+export const formatSandboxRecreation = (content: string, recreated?: boolean): string =>+ recreated+ ? `Warning: The sandbox session expired and was recreated. Files from the previous session may have been lost. Inform the user and ask before regenerating previous work.\n\n${content}`+ : content;diff --git a/packages/prompts/src/prompts/fileSystem/index.ts b/packages/prompts/src/prompts/fileSystem/index.tsindex 46a3b46c324..c9bfe5007d0 100644--- a/packages/prompts/src/prompts/fileSystem/index.ts+++ b/packages/prompts/src/prompts/fileSystem/index.ts@@ -10,4 +10,5 @@ export * from './formatKillResult';export * from './formatMoveResults';export * from './formatMultipleFiles';export * from './formatRenameResult';+export * from './formatSandboxRecreation';export * from './formatWriteResult';diff --git a/packages/tool-runtime/src/ComputerRuntime.ts b/packages/tool-runtime/src/ComputerRuntime.tsindex 973aabd6edb..c19d711fd3d 100644--- a/packages/tool-runtime/src/ComputerRuntime.ts+++ b/packages/tool-runtime/src/ComputerRuntime.ts@@ -10,6 +10,7 @@ import {formatKillResult,formatMoveResults,formatRenameResult,+ formatSandboxRecreation,formatWriteResult,} from '@lobechat/prompts/fileSystem';import type { BuiltinServerRuntimeOutput } from '@lobechat/types';@@ -322,9 +323,13 @@ export abstract class ComputerRuntime {async runCommand(args: RunCommandParams): Promise<BuiltinServerRuntimeOutput> {try {const result = await this.callService('runCommand', args);+ const sessionState = result.sessionExpiredAndRecreated+ ? { sessionExpiredAndRecreated: true }+ : {};if (!result.success) {- return this.errorOutput(result, {+ const output = this.errorOutput(result, {+ ...sessionState,error: result.error?.message,exitCode: result.result?.exitCode ?? result.result?.exit_code,isBackground: args.background || false,@@ -332,6 +337,10 @@ export abstract class ComputerRuntime {stdout: result.result?.stdout,success: false,});+ return {+ ...output,+ content: formatSandboxRecreation(output.content, result.sessionExpiredAndRecreated),+ };}const r = result.result || {};@@ -339,6 +348,7 @@ export abstract class ComputerRuntime {const outputFiles = r.outputFiles ?? r.output_files;const state: RunCommandState = {+ ...sessionState,commandId: r.commandId || r.shell_id,error: r.error,exitCode: r.exitCode ?? r.exit_code,@@ -361,7 +371,11 @@ export abstract class ComputerRuntime {success: commandSuccess,});- return { content, state, success: true };+ return {+ content: formatSandboxRecreation(content, result.sessionExpiredAndRecreated),+ state,+ success: true,+ };} catch (error) {return this.handleError(error);}@@ -370,12 +384,20 @@ export abstract class ComputerRuntime {async getCommandOutput(args: GetCommandOutputParams): Promise<BuiltinServerRuntimeOutput> {try {const result = await this.callService('getCommandOutput', args);+ const sessionState = result.sessionExpiredAndRecreated+ ? { sessionExpiredAndRecreated: true }+ : {};if (!result.success) {- return this.errorOutput(result, {+ const output = this.errorOutput(result, {+ ...sessionState,error: result.error?.message,success: false,});+ return {+ ...output,+ content: formatSandboxRecreation(output.content, result.sessionExpiredAndRecreated),+ };}const r = result.result || {};@@ -383,6 +405,7 @@ export abstract class ComputerRuntime {const outputFiles = r.outputFiles ?? r.output_files;const state: GetCommandOutputState = {+ ...sessionState,durationMs: r.durationMs ?? r.duration_ms,error: r.error,exitCode: r.exitCode ?? r.exit_code,@@ -404,7 +427,11 @@ export abstract class ComputerRuntime {success: outputSuccess,});- return { content, state, success: true };+ return {+ content: formatSandboxRecreation(content, result.sessionExpiredAndRecreated),+ state,+ success: true,+ };} catch (error) {return this.handleError(error);}diff --git a/packages/tool-runtime/src/types.ts b/packages/tool-runtime/src/types.tsindex 3c3d87e48f9..7dbb0c46a9f 100644--- a/packages/tool-runtime/src/types.ts+++ b/packages/tool-runtime/src/types.ts@@ -5,6 +5,8 @@export interface ServiceResult {error?: { message: string; name?: string };result: any;+ /** The execution workspace was recreated before this call. */+ sessionExpiredAndRecreated?: boolean;success: boolean;}@@ -271,6 +273,8 @@ export interface RunCommandState {* Undefined when no sandbox was requested.*/sandboxed?: boolean;+ /** The execution workspace was recreated before this command. */+ sessionExpiredAndRecreated?: boolean;stderr?: string;stdout?: string;success: boolean;@@ -285,6 +289,8 @@ export interface GetCommandOutputState {stdout: { path: string; size: number; truncated: boolean };};running?: boolean;+ /** The sandbox workspace was recreated before polling this command. */+ sessionExpiredAndRecreated?: boolean;stderr?: string;stdout?: string;success: boolean;diff --git a/src/store/tool/slices/builtin/executors/__tests__/lobe-skills.test.ts b/src/store/tool/slices/builtin/executors/__tests__/lobe-skills.test.tsnew file mode 100644index 00000000000..41a27c9fb24--- /dev/null+++ b/src/store/tool/slices/builtin/executors/__tests__/lobe-skills.test.ts@@ -0,0 +1,39 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { cloudSandboxService } from '@/services/cloudSandbox';++import { skillsExecutor } from '../lobe-skills';++vi.mock('@lobechat/builtin-skills', () => ({ builtinSkills: [] }));+vi.mock('@/helpers/skillFilters', () => ({ filterBuiltinSkills: () => [] }));+vi.mock('@/services/cloudSandbox', () => ({ cloudSandboxService: { callTool: vi.fn() } }));+vi.mock('@/services/skill', () => ({ agentSkillService: {} }));+vi.mock('@/store/chat', () => ({+ useChatStore: { getState: () => ({ activeTopicId: 'test-topic' }) },+}));++describe.each(['runCommand', 'execScript'] as const)('Web Skills %s recreation', (api) => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it.each([true, false])('warns when sandbox transport success is %s', async (success) => {+ vi.mocked(cloudSandboxService.callTool).mockResolvedValue({+ error: success ? undefined : { message: 'missing input file' },+ result: { exitCode: success ? 0 : 1, stdout: 'command output' },+ sessionExpiredAndRecreated: true,+ success,+ });++ const result = await skillsExecutor.invoke(+ api,+ { command: 'cat /tmp/input', description: 'Read input' },+ { messageId: 'test-message', operationId: 'test-operation' },+ );++ expect(result.content).toContain('sandbox session expired and was recreated');+ expect(result.content).toContain(success ? 'command output' : 'missing input file');+ expect(result.success).toBe(success);+ if (success) expect(result.state).toMatchObject({ sessionExpiredAndRecreated: true });+ });+});diff --git a/src/store/tool/slices/builtin/executors/lobe-skills.ts b/src/store/tool/slices/builtin/executors/lobe-skills.tsindex 5f1cf342d49..4a7e83d6218 100644--- a/src/store/tool/slices/builtin/executors/lobe-skills.ts+++ b/src/store/tool/slices/builtin/executors/lobe-skills.ts@@ -42,6 +42,7 @@ const runtime = new SkillsExecutionRuntime({executionEnv: 'sandbox' as const,exitCode: 1,output: '',+ ...(result.sessionExpiredAndRecreated && { sessionExpiredAndRecreated: true }),stderr: result.error?.message || 'Command execution failed',success: false,};@@ -57,6 +58,7 @@ const runtime = new SkillsExecutionRuntime({executionEnv: 'sandbox' as const,exitCode: sandboxResult.exitCode ?? (result.success ? 0 : 1),output: sandboxResult.stdout || sandboxResult.output || '',+ ...(result.sessionExpiredAndRecreated && { sessionExpiredAndRecreated: true }),stderr: sandboxResult.stderr || '',success:result.success &&@@ -124,6 +126,7 @@ const runtime = new SkillsExecutionRuntime({executionEnv: 'sandbox' as const,exitCode: 1,output: '',+ ...(result.sessionExpiredAndRecreated && { sessionExpiredAndRecreated: true }),stderr: result.error?.message || 'Command execution failed',success: false,};@@ -136,6 +139,7 @@ const runtime = new SkillsExecutionRuntime({executionEnv: 'sandbox' as const,exitCode: sandboxResult.exitCode ?? (result.success ? 0 : 1),output: sandboxResult.stdout || sandboxResult.output || '',+ ...(result.sessionExpiredAndRecreated && { sessionExpiredAndRecreated: true }),stderr: sandboxResult.stderr || '',success:result.success &&