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.

✨ feat(device): give the Local Sandbox a working directory instead of refusing (#18180)

LiJian9b4f944cb36a
diff --git a/apps/desktop/src/main/controllers/ShellCommandCtr.ts b/apps/desktop/src/main/controllers/ShellCommandCtr.ts
index 3dcd7a0a603..046d9a904b1 100644
--- a/apps/desktop/src/main/controllers/ShellCommandCtr.ts
+++ b/apps/desktop/src/main/controllers/ShellCommandCtr.ts
@@ -1,8 +1,14 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
import type { SandboxCapability } from '@lobechat/device-sandbox';
import type {
DesktopShellSettings,
DeviceSandboxCapabilityResult,
DeviceSandboxInstallResult,
+ EnsureSandboxWorkspaceParams,
+ EnsureSandboxWorkspaceResult,
GetCommandOutputParams,
GetCommandOutputResult,
KillCommandParams,
@@ -28,6 +34,12 @@ const logger = createLogger('controllers:ShellCommandCtr');
const processManager = new ShellProcessManager();
+/**
+ * Agent ids are opaque to this process, and they end up as a path segment —
+ * so anything that is not plainly a name is stripped rather than trusted.
+ */
+const safeSegment = (value: string): string => value.replaceAll(/[^\w-]/g, '') || 'default';
+
/** Prefix for a simple `lh`/`lobe`/`lobehub` invocation (keyword + boundary, args via slice). */
const SIMPLE_LH_PREFIX = /^\s*(?:lh|lobe|lobehub)(?=\s|$)/;
@@ -165,6 +177,40 @@ export default class ShellCommandCtr extends ControllerModule {
* Always clears the cached verdict first: the whole point is to re-evaluate a
* host that previously said no, including one downgraded by a failed launch.
*/
+ /**
+ * Create the default workspace a sandboxed agent runs in, and return its real
+ * path.
+ *
+ * The sandbox fences writes to the run's working directory, so without one
+ * there is nothing to fence and the command is refused. Making the user go
+ * find a folder before the feature does anything is a poor first run, so the
+ * picker calls this and then *writes the result into the visible working-
+ * directory setting* — a default the user can see and change, not a hidden
+ * one. A directory nobody can point at is how "the UI says one thing, the run
+ * does another" starts.
+ *
+ * Created eagerly rather than lazily at launch because the policy layer
+ * resolves its roots with `realpath` and rejects a path that does not exist
+ * yet.
+ */
+ @IpcMethod()
+ async ensureSandboxWorkspace({
+ agentId,
+ }: EnsureSandboxWorkspaceParams): Promise<EnsureSandboxWorkspaceResult> {
+ const target = path.join(os.homedir(), 'LobeHub', 'sandbox', safeSegment(agentId));
+ try {
+ fs.mkdirSync(target, { recursive: true });
+ // Resolve symlinks now: this exact string becomes the fence root, and the
+ // policy layer compares realpaths.
+ const resolved = fs.realpathSync.native(target);
+ logger.info('Prepared sandbox workspace:', resolved);
+ return { path: resolved };
+ } catch (error) {
+ logger.error('Failed to prepare sandbox workspace:', error);
+ return { reason: (error as Error).message };
+ }
+ }
+
@IpcMethod()
async installSandbox(): Promise<DeviceSandboxInstallResult> {
const { installDeviceSandbox } = await import('@lobechat/device-sandbox');
diff --git a/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts
index c8abb893d11..c007efc62f8 100644
--- a/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts
@@ -1,4 +1,6 @@
-import { writeSync } from 'node:fs';
+import { existsSync, rmSync, writeSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { join, relative } from 'node:path';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -510,6 +512,35 @@ describe('ShellCommandCtr (thin wrapper)', () => {
});
});
+ describe('default workspace', () => {
+ it('creates a per-agent directory and returns its real path', async () => {
+ const result = await ctr.ensureSandboxWorkspace({ agentId: 'agt_abc123' });
+
+ expect(result.path).toBeDefined();
+ expect(result.path).toContain('LobeHub');
+ expect(result.path).toContain('agt_abc123');
+ // The policy layer resolves fence roots with realpath and rejects a
+ // path that does not exist, so the directory must be real by now.
+ expect(existsSync(result.path!)).toBe(true);
+
+ rmSync(result.path!, { force: true, recursive: true });
+ });
+
+ it('never lets an agent id escape the workspace root', async () => {
+ // The id becomes a path segment and is opaque to this process, so a
+ // traversal attempt must land inside the sandbox root like any other
+ // name — this directory is about to become a writable fence root.
+ const root = join(homedir(), 'LobeHub', 'sandbox');
+ const result = await ctr.ensureSandboxWorkspace({ agentId: '../../Windows/System32' });
+
+ expect(result.path).toBeDefined();
+ expect(result.path!.startsWith(root)).toBe(true);
+ expect(relative(root, result.path!)).not.toContain('..');
+
+ rmSync(result.path!, { force: true, recursive: true });
+ });
+ });
+
it('treats a crashing probe as no sandbox', async () => {
mockProbeSandboxCapability.mockRejectedValue(new Error('module not found'));
diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.ts
index 57ee51364f6..f59a5c44ace 100644
--- a/packages/electron-client-ipc/src/types/localSystem.ts
+++ b/packages/electron-client-ipc/src/types/localSystem.ts
@@ -376,6 +376,22 @@ export interface DeviceSandboxInstallResult {
status: 'cancelled' | 'failed' | 'installed' | 'not-installable';
}
+export interface EnsureSandboxWorkspaceParams {
+ /** Scopes the workspace per agent, so two agents never share a fence root. */
+ agentId: string;
+}
+
+export interface EnsureSandboxWorkspaceResult {
+ /**
+ * Absolute path of the created directory. Absent when it could not be
+ * created — the caller then leaves the working directory unset rather than
+ * pointing it at something that does not exist.
+ */
+ path?: string;
+ /** Why the directory could not be created. */
+ reason?: string;
+}
+
export interface RunCommandResult {
duration_ms?: number;
error?: string;
diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
index 4ef88e4d14f..36d51f6eb40 100644
--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
@@ -37,11 +37,13 @@ import {
} from '@/helpers/executionTarget';
import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';
import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
+import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';
import { localFileService } from '@/services/electron/localFileService';
import { useAgentStore } from '@/store/agent';
import { useElectronStore } from '@/store/electron';
import { formatLockedControlTooltip } from '../utils/lockedControlTooltip';
+import { useCommitWorkingDirectory } from './useCommitWorkingDirectory';
const styles = createStaticStyles(({ css }) => ({
button: css`
@@ -458,13 +460,43 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
void revalidateSandboxCapability();
}, [open, revalidateSandboxCapability]);
+ // `homeFallback: false` on purpose — this must reflect whether the user has
+ // actually chosen a directory, not the runtime's convenience fallback.
+ const configuredWorkingDirectory = useEffectiveWorkingDirectory(agentId, { homeFallback: false });
+ const { commit: commitWorkingDirectory } = useCommitWorkingDirectory(agentId);
+
+ /**
+ * Give a sandboxed agent somewhere to work when the user has not picked a
+ * directory yet.
+ *
+ * The fence is scoped to the working directory, so without one the run is
+ * refused — a first use that fails on a requirement the picker never
+ * mentioned. Rather than fence a directory nobody chose *silently*, the
+ * default is written into the same setting the chip reads, so the answer to
+ * "where is this running?" stays visible and changeable.
+ */
+ const ensureSandboxWorkingDirectory = useCallback(async () => {
+ if (configuredWorkingDirectory) return;
+
+ const { path } = await localFileService.ensureSandboxWorkspace({ agentId });
+ // Leave it unset if the directory could not be created: pointing the fence
+ // at a path that does not exist would fail later and less clearly.
+ //
+ // `localTarget` because the sandbox pick is about to make `local` the
+ // target: the config still describes the previous one here, so without it a
+ // workspace member's first pick would file the path against the shared
+ // target (or nowhere) and the very next command would refuse again.
+ if (path) await commitWorkingDirectory({ path }, { localTarget: true });
+ }, [agentId, commitWorkingDirectory, configuredWorkingDirectory]);
+
const selectExecutionTarget = useSelectExecutionTarget(agentId);
const handleSelect = useCallback(
async (target: DeviceExecutionTarget, deviceId?: string, localSandbox?: boolean) => {
setOpen(false);
+ if (localSandbox) await ensureSandboxWorkingDirectory();
await selectExecutionTarget(target, deviceId, { localSandbox });
},
- [selectExecutionTarget],
+ [ensureSandboxWorkingDirectory, selectExecutionTarget],
);
// Setting up the backend raises an elevation prompt and creates a dedicated
diff --git a/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx b/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx
new file mode 100644
index 00000000000..74deded2737
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx
@@ -0,0 +1,127 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useCommitWorkingDirectory } from '../useCommitWorkingDirectory';
+
+const testState = vi.hoisted(() => ({
+ agent: {
+ agencyConfig: undefined as Record<string, unknown> | undefined,
+ agentMap: {} as Record<string, { visibility?: string; workspaceId?: string | null }>,
+ localAgentWorkingDirectoryMap: {} as Record<string, string>,
+ updateAgentConfigById: vi.fn(),
+ updateAgentRuntimeEnvConfigById: vi.fn(),
+ },
+ chat: { activeTopicId: undefined as string | undefined, updateTopicMetadata: vi.fn() },
+ currentDeviceId: 'this-machine' as string | undefined,
+ effective: {
+ agencyConfig: undefined as Record<string, unknown> | undefined,
+ workspaceScoped: false,
+ },
+}));
+
+vi.mock('@lobehub/ui/base-ui', () => ({ confirmModal: vi.fn() }));
+
+vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({
+ useEffectiveAgencyConfig: () => testState.effective,
+}));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (s: typeof testState.agent) => unknown) => selector(testState.agent),
+}));
+
+vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: { getAgencyConfigById: () => (s: typeof testState.agent) => s.agencyConfig },
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (s: typeof testState.chat) => unknown) => selector(testState.chat),
+}));
+
+vi.mock('@/store/chat/selectors', () => ({
+ topicSelectors: { getTopicById: () => () => undefined },
+}));
+
+vi.mock('@/store/device', () => ({
+ useDeviceStore: (selector: (s: { updateDeviceCwd: unknown }) => unknown) =>
+ selector({ updateDeviceCwd: vi.fn() }),
+}));
+
+vi.mock('@/store/electron', () => ({
+ useElectronStore: (selector: (s: { gatewayDeviceInfo?: { deviceId?: string } }) => unknown) =>
+ selector({ gatewayDeviceInfo: { deviceId: testState.currentDeviceId } }),
+}));
+
+vi.mock('@/helpers/heteroSessionByWorkingDirectory', () => ({
+ getHeteroSessionIdForWorkingDirectory: () => undefined,
+}));
+
+describe('useCommitWorkingDirectory — localTarget', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ testState.agent.agencyConfig = undefined;
+ testState.agent.agentMap = {};
+ testState.agent.localAgentWorkingDirectoryMap = {};
+ testState.agent.updateAgentConfigById = vi.fn();
+ testState.agent.updateAgentRuntimeEnvConfigById = vi.fn();
+ testState.chat.activeTopicId = undefined;
+ testState.currentDeviceId = 'this-machine';
+ testState.effective = { agencyConfig: undefined, workspaceScoped: false };
+ });
+
+ it('files a workspace member’s first sandbox pick against their own machine', async () => {
+ // The caller selects `local` as part of the same action, so the config here
+ // still describes the previous (workspace-shared) target — and selecting
+ // first would not re-render in time. Without `localTarget` the path lands
+ // in the shared row or nowhere, and the next command refuses again for
+ // want of a working directory.
+ testState.agent.agentMap = { 'agent-id': { visibility: 'public', workspaceId: 'ws-1' } };
+ testState.effective = {
+ agencyConfig: { boundDeviceId: 'shared-device', executionTarget: 'device' },
+ workspaceScoped: true,
+ };
+
+ const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));
+ await result.current.commit(
+ { path: 'C:/Users/me/LobeHub/sandbox/agent-id' },
+ {
+ localTarget: true,
+ },
+ );
+
+ // Per-user slot — never the workspace-shared row.
+ expect(testState.agent.updateAgentRuntimeEnvConfigById).toHaveBeenCalledWith('agent-id', {
+ workingDirectory: 'C:/Users/me/LobeHub/sandbox/agent-id',
+ });
+ expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();
+ });
+
+ it('keeps a personal agent’s write on this device', async () => {
+ const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));
+ await result.current.commit({ path: 'C:/work' }, { localTarget: true });
+
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-id', {
+ agencyConfig: { workingDirByDevice: { 'this-machine': { path: 'C:/work' } } },
+ });
+ });
+
+ it('leaves ordinary writes routed by the resolved config', async () => {
+ // No override: a `device` target still files against its bound device, so
+ // the new option cannot change how the directory picker behaves.
+ testState.effective = {
+ agencyConfig: { boundDeviceId: 'other-device', executionTarget: 'device' },
+ workspaceScoped: false,
+ };
+ testState.agent.agencyConfig = { boundDeviceId: 'other-device', executionTarget: 'device' };
+
+ const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));
+ await result.current.commit({ path: 'C:/work' });
+
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-id', {
+ agencyConfig: {
+ boundDeviceId: 'other-device',
+ executionTarget: 'device',
+ workingDirByDevice: { 'other-device': { path: 'C:/work' } },
+ },
+ });
+ });
+});
diff --git a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts
index bd6df06b391..99b5499d7f1 100644
--- a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts
+++ b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts
@@ -20,6 +20,17 @@ import { topicSelectors } from '@/store/chat/selectors';
import { useDeviceStore } from '@/store/device';
import { useElectronStore } from '@/store/electron';
+export interface CommitWorkingDirectoryOptions {
+ /**
+ * Persist against the `local` execution target on this machine, regardless of
+ * what the agent's config currently says. For callers that select the local
+ * target as part of the same action — the resolved config still describes the
+ * previous target at that point, and selecting first does not re-render in
+ * time to help.
+ */
+ localTarget?: boolean;
+}
+
const normalizeWorkingDirEntry = (entry: WorkingDirEntry): WorkingDirEntry | undefined => {
const path = entry.path.trim();
if (!path) return undefined;
@@ -126,7 +137,19 @@ export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: string
(effectiveAgencyConfig?.executionTarget === 'local' || targetDeviceId === currentDeviceId);
const writeCwd = useCallback(
- async (entry?: WorkingDirEntry) => {
+ async (entry?: WorkingDirEntry, options?: CommitWorkingDirectoryOptions) => {
+ // A caller that is *about to* select the local target cannot rely on the
+ // resolved config yet: this callback closes over the config as it is now,
+ // and selecting first would not re-render in time either. `localTarget`
+ // lets it state the destination it is creating, so the cwd lands in the
+ // same slot the pending `local` pick will read from.
+ const localTarget = options?.localTarget === true;
+ const writeDeviceId = localTarget ? currentDeviceId : targetDeviceId;
+ // A `local` pick on a workspace agent always means this member's own
+ // machine, which routes to the per-user slot rather than the shared row.
+ const writePersonalSlot = localTarget
+ ? isWorkspaceAgent && !!currentDeviceId
+ : isPersonalDeviceTarget;
const effectivePath = getWorkingDirEffectivePath(entry);
// The session cwd anchors to the source repo for hetero (stable across
// worktree switches) and to the effective/worktree path otherwise.
@@ -153,7 +176,7 @@ export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: string
workingDirectoryConfig: entry ? toAgentWorkingDirConfig(entry) : undefined,
});
} else {
- if (targetDeviceId && isPersonalDeviceTarget) {
+ if (writeDeviceId && writePersonalSlot) {
// Per-user slot (see `isPersonalDeviceTarget`) — never the shared row.
// The legacy slot stores a plain path, so persist the SESSION cwd
// (source repo for hetero — anchoring a CLI session to a worktree
@@ -164,14 +187,14 @@ export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: string
await updateAgentRuntimeEnvConfigById(agentId, {
workingDirectory: sessionCwd || undefined,
});
- } else if (targetDeviceId) {
+ } else if (writeDeviceId) {
const prev = agencyConfig?.workingDirByDevice ?? {};
// Clearing sends `undefined` rather than dropping the key: deep-merge
// (client store + server persist) can't remove a key, so the delete is
// carried as an explicit `undefined` and pruned after each merge.
const nextMap: Record<string, WorkingDirConfigValue | undefined> = {
...prev,
- [targetDeviceId]: entry ? toAgentWorkingDirConfig(entry) : undefined,
+ [writeDeviceId]: entry ? toAgentWorkingDirConfig(entry) : undefined,
};
const configPatch = {
agencyConfig: { ...agencyConfig, workingDirByDevice: nextMap },
@@ -183,7 +206,7 @@ export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: string
// level and Clear looks dead. (Only clears the localStorage map; no
// network round-trip since `workingDirectory` is stripped before send.)
// The personal-device branch above already wrote that same slot.
- if (!isPersonalDeviceTarget && !effectivePath && legacyAgentWorkingDirectory) {
+ if (!writePersonalSlot && !effectivePath && legacyAgentWorkingDirectory) {
await updateAgentRuntimeEnvConfigById(agentId, { workingDirectory: undefined });
}
}
@@ -257,12 +280,12 @@ export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: string
/** Pick a directory (with the CC-session-reset guard). */
const commit = useCallback(
- async (entry: WorkingDirEntry) => {
+ async (entry: WorkingDirEntry, options?: CommitWorkingDirectoryOptions) => {
const normalizedEntry = normalizeWorkingDirEntry(entry);
const effectivePath = getWorkingDirEffectivePath(normalizedEntry);
if (!normalizedEntry || !effectivePath) return;
- const run = () => writeCwd(normalizedEntry);
+ const run = () => writeCwd(normalizedEntry, options);
// Warn about losing the CLI session only when the SESSION cwd changes.
// For hetero that's the source repo — a worktree switch within the same
diff --git a/src/services/electron/localFileService.ts b/src/services/electron/localFileService.ts
index 3a2fc746ad2..da22bfbcbaf 100644
--- a/src/services/electron/localFileService.ts
+++ b/src/services/electron/localFileService.ts
@@ -6,6 +6,8 @@ import {
type DeviceSandboxInstallResult,
type EditLocalFileParams,
type EditLocalFileResult,
+ type EnsureSandboxWorkspaceParams,
+ type EnsureSandboxWorkspaceResult,
type GetCommandOutputParams,
type GetCommandOutputResult,
type GlobFilesParams,
@@ -280,6 +282,17 @@ class LocalFileService {
return ensureElectronIpc().shellCommand.installSandbox();
}
+ /**
+ * Create (and return) the default directory a sandboxed agent should work in.
+ * The caller persists it as the agent's working directory, so the default is
+ * visible and changeable rather than hidden.
+ */
+ async ensureSandboxWorkspace(
+ params: EnsureSandboxWorkspaceParams,
+ ): Promise<EnsureSandboxWorkspaceResult> {
+ return ensureElectronIpc().shellCommand.ensureSandboxWorkspace(params);
+ }
+
async getCommandOutput(params: GetCommandOutputParams): Promise<GetCommandOutputResult> {
return ensureElectronIpc().shellCommand.handleGetCommandOutput(params);
}