π€― 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(device): probe the sandbox helper this app ships, not the one the backend guesses (#18176)
LiJian95dfa1d3898b
diff --git a/apps/desktop/electron-builder.mjs b/apps/desktop/electron-builder.mjsindex b38bdd866cc..fdc3e419484 100644--- a/apps/desktop/electron-builder.mjs+++ b/apps/desktop/electron-builder.mjs@@ -304,6 +304,15 @@ const config = {from: 'node_modules/@anthropic-ai/sandbox-runtime/vendor',to: 'sandbox-runtime/vendor',},+ // Carried alongside the binaries so the staging directory stays keyed on the+ // backend's real version. Without it the version lookup falls back to the+ // binary's size β which still works, but would defeat the per-version+ // isolation in exactly the case it exists for: an installed app being+ // updated.+ {+ from: 'node_modules/@anthropic-ai/sandbox-runtime/package.json',+ to: 'sandbox-runtime/package.json',+ },],win: {diff --git a/packages/device-sandbox/src/__tests__/capability.test.ts b/packages/device-sandbox/src/__tests__/capability.test.tsnew file mode 100644index 00000000000..1f4d26cf4e7--- /dev/null+++ b/packages/device-sandbox/src/__tests__/capability.test.ts@@ -0,0 +1,146 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { probeSandboxCapability } from '../capability';++const {+ mockCheckDependencies,+ mockGetSrtWinPath,+ mockIsSupportedPlatform,+ mockResolveEffectiveSrtWin,+ mockResolveSrtWin,+ mockUserStatus,+ mockWfpStatus,+} = vi.hoisted(() => ({+ mockCheckDependencies: vi.fn(),+ mockGetSrtWinPath: vi.fn(),+ mockIsSupportedPlatform: vi.fn(),+ mockResolveEffectiveSrtWin: vi.fn(),+ mockResolveSrtWin: vi.fn(),+ mockUserStatus: vi.fn(),+ mockWfpStatus: vi.fn(),+}));++vi.mock('@anthropic-ai/sandbox-runtime', () => ({+ SandboxManager: {+ checkDependencies: mockCheckDependencies,+ isSupportedPlatform: mockIsSupportedPlatform,+ },+ getSrtWinPath: mockGetSrtWinPath,+ getWindowsSandboxUserStatus: mockUserStatus,+ getWindowsWfpStatus: mockWfpStatus,+ resolveSrtWin: mockResolveSrtWin,+ windowsInstallInstructions: () => 'run the installer',+}));++vi.mock('../srtWinStaging', () => ({+ resolveEffectiveSrtWin: mockResolveEffectiveSrtWin,+}));++const setPlatform = (platform: NodeJS.Platform) => {+ Object.defineProperty(process, 'platform', { configurable: true, value: platform });+};++describe('probeSandboxCapability', () => {+ const realPlatform = process.platform;++ beforeEach(() => {+ vi.clearAllMocks();+ mockIsSupportedPlatform.mockReturnValue(true);+ mockResolveEffectiveSrtWin.mockReturnValue('C:\\ProgramData\\LobeHub\\srt-win.exe');+ mockResolveSrtWin.mockImplementation((cfg: { path: string }) => ({+ exe: cfg.path,+ prependArgs: ['--srt-win'],+ }));+ mockUserStatus.mockReturnValue({ credPresent: true, provisioned: true });+ mockWfpStatus.mockReturnValue({ filters: 4, state: 'installed' });+ mockCheckDependencies.mockReturnValue({ errors: [], warnings: [] });+ });++ afterEach(() => setPlatform(realPlatform));++ describe('windows', () => {+ beforeEach(() => setPlatform('win32'));++ it('checks the helper this app ships instead of the backend-guessed path', async () => {+ // The regression: the backend resolves its helper relative to its own+ // package directory, which lands inside app.asar once bundled β a+ // correctly installed app then reported "srt-win.exe not found".+ const capability = await probeSandboxCapability();++ expect(capability.available).toBe(true);+ expect(mockCheckDependencies).not.toHaveBeenCalled();+ expect(mockResolveSrtWin).toHaveBeenCalledWith({+ path: 'C:\\ProgramData\\LobeHub\\srt-win.exe',+ });+ expect(mockUserStatus).toHaveBeenCalledWith({+ srtWin: { exe: 'C:\\ProgramData\\LobeHub\\srt-win.exe', prependArgs: ['--srt-win'] },+ });+ });++ it('reports unavailable when no helper can be found', async () => {+ mockResolveEffectiveSrtWin.mockReturnValue(undefined);++ const capability = await probeSandboxCapability();++ expect(capability.available).toBe(false);+ expect(capability.reason).toContain('Sandbox helper not found');+ expect(mockUserStatus).not.toHaveBeenCalled();+ });++ it('reports unavailable while the sandbox account is not provisioned', async () => {+ // This is the state the Set-up button exists to fix, so it must be+ // distinguishable from a missing binary, which that button cannot fix.+ mockUserStatus.mockReturnValue({ credPresent: false, provisioned: false });++ const capability = await probeSandboxCapability();++ expect(capability.available).toBe(false);+ expect(capability.reason).toContain('not provisioned');+ });++ it('treats unreadable filter enumeration as available', async () => {+ // BFE enumeration is admin-gated; the behavioural egress check at+ // initialize() is what actually fails closed, so `cannot-read` from a+ // non-elevated probe must not disable the option.+ mockWfpStatus.mockReturnValue({ filters: 0, state: 'cannot-read' });++ expect((await probeSandboxCapability()).available).toBe(true);+ });++ it('reports unavailable when the filters are absent', async () => {+ mockWfpStatus.mockReturnValue({ filters: 0, state: 'absent' });++ const capability = await probeSandboxCapability();++ expect(capability.available).toBe(false);+ expect(capability.reason).toContain('WFP filters');+ });+ });++ describe('other platforms', () => {+ beforeEach(() => setPlatform('darwin'));++ it('keeps using the backend check, which resolves nothing app-relative', async () => {+ const capability = await probeSandboxCapability();++ expect(capability.available).toBe(true);+ expect(mockCheckDependencies).toHaveBeenCalled();+ expect(mockResolveEffectiveSrtWin).not.toHaveBeenCalled();+ });++ it('surfaces backend dependency errors', async () => {+ mockCheckDependencies.mockReturnValue({ errors: ['bubblewrap not found'], warnings: [] });++ const capability = await probeSandboxCapability();++ expect(capability.available).toBe(false);+ expect(capability.reason).toContain('bubblewrap not found');+ });+ });++ it('reports unavailable on a platform the backend does not support', async () => {+ mockIsSupportedPlatform.mockReturnValue(false);++ expect((await probeSandboxCapability()).available).toBe(false);+ });+});diff --git a/packages/device-sandbox/src/__tests__/launchPlan.test.ts b/packages/device-sandbox/src/__tests__/launchPlan.test.tsindex 7ef2a928fa0..9363e01e931 100644--- a/packages/device-sandbox/src/__tests__/launchPlan.test.ts+++ b/packages/device-sandbox/src/__tests__/launchPlan.test.ts@@ -82,16 +82,19 @@ describe('device sandbox launch plan', () => {});it('maps the LobeHub policy to a fail-closed Sandbox Runtime configuration', () => {- expect(- createSrtConfig({- ...policy,- allowedNetworkDomains: ['api.github.com'],- allowNetwork: true,- deniedReadRoots: ['/tmp'],- deniedWriteRoots: ['/tmp'],- readableRoots: ['/tmp'],- }),- ).toEqual({+ const config = createSrtConfig({+ ...policy,+ allowedNetworkDomains: ['api.github.com'],+ allowNetwork: true,+ deniedReadRoots: ['/tmp'],+ deniedWriteRoots: ['/tmp'],+ readableRoots: ['/tmp'],+ });++ // `windows` is asserted separately below: it carries an absolute path to the+ // staged helper, which exists only on Windows and differs per machine.+ const { windows: _windows, ...portable } = config;+ expect(portable).toEqual({allowAppleEvents: false,allowPty: false,enableWeakerNestedSandbox: false,@@ -113,4 +116,18 @@ describe('device sandbox launch plan', () => {},});});++ it('overrides the helper path on Windows and nowhere else', () => {+ // The backend resolves its helper relative to its own package directory,+ // which stops being a real location once bundled β so Windows must be told+ // explicitly where the shipped binary is. Other platforms have nothing to+ // relocate and must not carry a stray override.+ const { windows } = createSrtConfig(policy);++ if (process.platform === 'win32') {+ expect(windows?.srtWin?.path).toMatch(/srt-win\.exe$/);+ } else {+ expect(windows).toBeUndefined();+ }+ });});diff --git a/packages/device-sandbox/src/capability.ts b/packages/device-sandbox/src/capability.tsindex a459518da33..cc16a443426 100644--- a/packages/device-sandbox/src/capability.ts+++ b/packages/device-sandbox/src/capability.ts@@ -1,26 +1,94 @@-import { SandboxManager } from '@anthropic-ai/sandbox-runtime';+import {+ getSrtWinPath,+ getWindowsSandboxUserStatus,+ getWindowsWfpStatus,+ resolveSrtWin,+ SandboxManager,+ windowsInstallInstructions,+} from '@anthropic-ai/sandbox-runtime';+import { resolveEffectiveSrtWin } from './srtWinStaging';import type { SandboxCapability } from './types';+const unavailable = (reason: string, warnings?: string[]): SandboxCapability => ({+ available: false,+ backend: 'none',+ networkIsolation: false,+ reason,+ warnings,+});++/**+ * Windows readiness, checked against the helper *this app actually ships*.+ *+ * `SandboxManager.checkDependencies()` cannot be used here: it resolves the+ * helper through the backend's own `getSrtWinPath()`, which is relative to the+ * backend's package directory. Once that package is bundled into the main+ * process, the computed path points inside `app.asar` β where no file exists β+ * so a correctly installed app reported "srt-win.exe not found" and offered a+ * Set-up button that could never change the answer. Observed on a released+ * build whose `resources/sandbox-runtime/vendor/` held the binary all along.+ *+ * So the checks are run directly against the resolved path instead, mirroring+ * the backend's own sequence: binary present β sandbox user provisioned with a+ * readable credential β WFP filters installed. `cannot-read` on the filter+ * enumeration is not a failure β it is admin-gated, and the behavioural egress+ * check at `initialize()` is what actually fails closed.+ */+const probeWindows = (): SandboxCapability => {+ // Exactly the path the launch will use: `resolveEffectiveSrtWin` is the one+ // place that resolves and stages, so the probe can never bless a path the+ // launch would not take.+ const path = resolveEffectiveSrtWin(getSrtWinPath);+ if (!path) {+ return unavailable(`Sandbox helper not found. ${windowsInstallInstructions(undefined)}`);+ }++ const srtWin = resolveSrtWin({ path });++ let user;+ try {+ user = getWindowsSandboxUserStatus({ srtWin });+ } catch (error) {+ return unavailable(`srt-win user status failed: ${(error as Error).message}`);+ }++ if (!user.provisioned || !user.credPresent) {+ return unavailable(+ `Sandbox user is not provisioned (user=${user.provisioned}, cred=${user.credPresent}).`,+ );+ }++ try {+ const wfp = getWindowsWfpStatus({ srtWin });+ // `absent` is the only real failure: `cannot-read` just means the caller is+ // not elevated enough to enumerate BFE filters.+ if (wfp.state !== 'installed' && wfp.state !== 'cannot-read') {+ return unavailable('WFP filters are not installed.');+ }+ } catch (error) {+ return unavailable(`srt-win wfp status failed: ${(error as Error).message}`);+ }++ return { available: true, backend: 'srt', networkIsolation: true };+};+export const probeSandboxCapability = async (): Promise<SandboxCapability> => {if (!SandboxManager.isSupportedPlatform()) {- return {- available: false,- backend: 'none',- networkIsolation: false,- reason: `Sandbox Runtime does not support ${process.platform}`,- };+ return unavailable(`Sandbox Runtime does not support ${process.platform}`);}+ if (process.platform === 'win32') return probeWindows();++ // macOS ships Seatbelt with the OS and Linux's dependencies are ordinary+ // system packages resolved from PATH, so neither is affected by where this+ // app happens to be installed β the backend's own check is accurate there.const dependencies = SandboxManager.checkDependencies();if (dependencies.errors.length > 0) {- return {- available: false,- backend: 'none',- networkIsolation: false,- reason: `Sandbox Runtime dependencies are unavailable: ${dependencies.errors.join(', ')}`,- warnings: dependencies.warnings,- };+ return unavailable(+ `Sandbox Runtime dependencies are unavailable: ${dependencies.errors.join(', ')}`,+ dependencies.warnings,+ );}return {diff --git a/packages/device-sandbox/src/index.ts b/packages/device-sandbox/src/index.tsindex a9ab35ed38c..857d0157b92 100644--- a/packages/device-sandbox/src/index.ts+++ b/packages/device-sandbox/src/index.ts@@ -10,7 +10,7 @@ export {export { SrtSandboxRuntime, srtSandboxRuntime } from './runtime';export { canInstallSandbox, installDeviceSandbox } from './setup';export { createSrtConfig } from './srt';-export { ensureStagedSrtWin, resolveSrtWinSource } from './srtWinStaging';+export { ensureStagedSrtWin, resolveEffectiveSrtWin, resolveSrtWinSource } from './srtWinStaging';export type {CreateSandboxLaunchPlanOptions,SandboxBackend,diff --git a/packages/device-sandbox/src/setup.ts b/packages/device-sandbox/src/setup.tsindex 34072c16464..4de41a5e0f9 100644--- a/packages/device-sandbox/src/setup.ts+++ b/packages/device-sandbox/src/setup.ts@@ -50,13 +50,12 @@ export const installDeviceSandbox = async (): Promise<SandboxSetupResult> => {const { getSrtWinPath, installWindowsSandbox, resolveSrtWin } =await import('@anthropic-ai/sandbox-runtime');- const { ensureStagedSrtWin, resolveSrtWinSource } = await import('./srtWinStaging');+ const { resolveEffectiveSrtWin } = await import('./srtWinStaging');// Stage the helper as part of setup, not lazily at first use: this is the// moment the user asked us to make the machine ready, and a first run that// failed on file permissions would look like the setup itself hadn't worked.- const source = resolveSrtWinSource(getSrtWinPath);- const staged = source ? ensureStagedSrtWin(source) : undefined;+ const staged = resolveEffectiveSrtWin(getSrtWinPath);const srtWin = staged ? resolveSrtWin({ path: staged }) : undefined;const result = installWindowsSandbox(srtWin ? { srtWin } : {});diff --git a/packages/device-sandbox/src/srt.ts b/packages/device-sandbox/src/srt.tsindex 446f27beec8..7bd99f1f090 100644--- a/packages/device-sandbox/src/srt.ts+++ b/packages/device-sandbox/src/srt.ts@@ -2,24 +2,24 @@ import type { SandboxRuntimeConfig } from '@anthropic-ai/sandbox-runtime';import { getSrtWinPath } from '@anthropic-ai/sandbox-runtime';import { normalizeSandboxPolicy } from './policy';-import { ensureStagedSrtWin, resolveSrtWinSource } from './srtWinStaging';+import { resolveEffectiveSrtWin } from './srtWinStaging';import type { SandboxPolicy } from './types';/**- * Point the backend at a helper the sandbox user can read. See- * {@link ensureStagedSrtWin} β without this, a per-user app install puts the- * helper somewhere the sandbox account has no rights to, and every launch dies- * with an unexplained ACCESS_DENIED.+ * Point the backend at the same helper the capability probe validated. See+ * {@link resolveEffectiveSrtWin} β leaving the backend to resolve its own+ * package-relative path lands inside `app.asar` once bundled, and a per-user+ * install puts the shipped copy somewhere the sandbox account cannot read.*- * Silent no-op off Windows and whenever staging isn't possible; the backend- * then resolves its own packaged binary exactly as before.+ * Silent no-op off Windows, and when no helper can be found at all β the+ * backend then fails loudly at launch rather than being told a path that does+ * not exist.*/const resolveWindowsConfig = (): SandboxRuntimeConfig['windows'] => {if (process.platform !== 'win32') return undefined;try {- const source = resolveSrtWinSource(getSrtWinPath);- const staged = source ? ensureStagedSrtWin(source) : undefined;- return staged ? { srtWin: { path: staged } } : undefined;+ const path = resolveEffectiveSrtWin(getSrtWinPath);+ return path ? { srtWin: { path } } : undefined;} catch {return undefined;}diff --git a/packages/device-sandbox/src/srtWinStaging.ts b/packages/device-sandbox/src/srtWinStaging.tsindex f182383d1d0..3a975b3de22 100644--- a/packages/device-sandbox/src/srtWinStaging.ts+++ b/packages/device-sandbox/src/srtWinStaging.ts@@ -124,3 +124,23 @@ export const ensureStagedSrtWin = (packagedExe: string): string | undefined => {return undefined;}};++/**+ * The helper path every caller must use β the probe, the launch, and setup.+ *+ * Resolution and staging are combined here on purpose. When they were separate,+ * the probe fell back to the unstaged source while the launch fell back to *no+ * override at all*, letting the backend resolve its own package-relative path β+ * which is inside `app.asar` once bundled. A host where staging fails+ * (ProgramData locked down, disk full) would then be advertised as available and+ * fail on the first command. One function, one answer.+ *+ * Falling back to the unstaged source rather than giving up is deliberate: a+ * per-machine install already lives somewhere the sandbox account can read, so+ * staging is an accommodation for per-user installs, not a precondition.+ */+export const resolveEffectiveSrtWin = (packagedFallback?: () => string): string | undefined => {+ const source = resolveSrtWinSource(packagedFallback);+ if (!source) return undefined;+ return ensureStagedSrtWin(source) ?? source;+};diff --git a/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts b/packages/tool-runtime/src/LocalSystemExecutionRuntime.tsindex 3e7c4678208..fe8c1c3f0f9 100644--- a/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts+++ b/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts@@ -409,6 +409,16 @@ export class LocalSystemExecutionRuntime extends ComputerRuntime {case 'runCommand': {// RunCommandResult has snake_case fields from local-file-shellreturn {+ // Surface raw.error at the top level so ComputerRuntime.errorOutput+ // has a real message to render. Its priority chain reads the+ // ServiceResult's own `error`, then `state.stderr`, then+ // `state.error` β a runCommand that fails before spawning fills none+ // of those (there is no process, so no stderr), so every such failure+ // collapsed to the generic "[UNKNOWN_EXEC_ERROR] Tool execution+ // failed" with the reason discarded. That hid, among others, every+ // Local Sandbox refusal: "requires a working directory", "unavailable+ // on this device". Mirrors editLocalFile / grep / glob below.+ error: raw.error ? { message: String(raw.error) } : undefined,result: {error: raw.error,exitCode: raw.exit_code,diff --git a/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts b/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.tsindex b2d7048b1b2..c5f7bf5fe5f 100644--- a/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts+++ b/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts@@ -544,3 +544,41 @@ describe('LocalSystemExecutionRuntime.executeToolCall β dispatch', () => {expect(await runtime.executeToolCall('runHeteroTask', {})).toBeNull();});});++describe('LocalSystemExecutionRuntime.runCommand', () => {+ it('surfaces a pre-spawn failure reason instead of UNKNOWN_EXEC_ERROR', async () => {+ // A command that never starts has no process, so no stderr and no exit+ // code β the exact shape every Local Sandbox refusal takes. The reason used+ // to be dropped, leaving the user (and the model) with a generic failure+ // and nothing to act on.+ const service = createService({+ runCommand: vi.fn().mockResolvedValue({+ error:+ 'Local Sandbox requires a working directory. Set one for this agent (or topic) and run the command again.',+ success: false,+ }),+ });+ const runtime = new LocalSystemExecutionRuntime(service);++ const output = await runtime.runCommand({ command: 'whoami' } as never);++ expect(output.content).toContain('Local Sandbox requires a working directory');+ expect(output.content).not.toContain('UNKNOWN_EXEC_ERROR');+ });++ it('reports whether the command was actually sandboxed', async () => {+ const service = createService({+ runCommand: vi.fn().mockResolvedValue({+ exit_code: 0,+ sandboxed: true,+ stdout: 'srt-sandbox',+ success: true,+ }),+ });+ const runtime = new LocalSystemExecutionRuntime(service);++ const output = await runtime.runCommand({ command: 'whoami' } as never);++ expect((output.state as { sandboxed?: boolean }).sandboxed).toBe(true);+ });+});