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(portal): copy outside-workspace publish assets into the workspace (#19447)

Inneif4d21a6e1e0c
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
index a71545708c1..f29775d2258 100644
--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
@@ -415,6 +415,7 @@ export default class GatewayConnectionCtr extends ControllerModule {
getLocalFilePreview: (params) => this.localFileCtr.getLocalFilePreview(params),
readExternalAssetForPublish: (params) =>
this.localFileCtr.readExternalAssetForPublish(params),
+ copyAssetForPublish: (params) => this.localFileCtr.copyAssetForPublish(params),
getProjectFileIndex: (params) => this.localFileCtr.getProjectFileIndex(params),
listHeterogeneousAgentModels: (params) => this.heterogeneousAgentCtr.listModels(params),
searchProjectFiles: (params) => this.localFileCtr.searchProjectFiles(params),
diff --git a/apps/desktop/src/main/controllers/LocalFileCtr.ts b/apps/desktop/src/main/controllers/LocalFileCtr.ts
index 779aaae134b..3af6f808b2c 100644
--- a/apps/desktop/src/main/controllers/LocalFileCtr.ts
+++ b/apps/desktop/src/main/controllers/LocalFileCtr.ts
@@ -4,6 +4,8 @@ import { access, readFile, realpath, stat } from 'node:fs/promises';
import path from 'node:path';
import type {
+ CopyAssetForPublishParams,
+ CopyAssetForPublishResult,
ExternalAssetForPublishParams,
ExternalAssetForPublishResult,
SkillDirectoryDeps,
@@ -612,6 +614,27 @@ export default class LocalFileCtr extends ControllerModule {
}
}
+ @IpcMethod()
+ async copyAssetForPublish({
+ from,
+ to,
+ workingDirectory,
+ }: CopyAssetForPublishParams): Promise<CopyAssetForPublishResult> {
+ try {
+ const copied = await this.app.localFileProtocolManager.copyExternalFileForPublish({
+ filePath: from,
+ targetPath: to,
+ workspaceRoot: workingDirectory,
+ });
+ return copied
+ ? { success: true }
+ : { error: 'Failed to copy publish asset into the workspace', success: false };
+ } catch (error) {
+ logger.error('Failed to copy publish asset:', error);
+ return { error: (error as Error).message, success: false };
+ }
+ }
+
@IpcMethod()
async getLocalFilePreview({
accept,
diff --git a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
index f2357b6916e..0f024bcad21 100644
--- a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
@@ -82,6 +82,7 @@ const mockLocalFileProtocolManager = {
approveIndexedProjectRoot: vi.fn(),
approveProjectRootFromScope: vi.fn(),
createPreviewUrl: vi.fn(),
+ copyExternalFileForPublish: vi.fn(),
readExternalFileForPublish: vi.fn(),
readPreviewFile: vi.fn(),
};
@@ -374,6 +375,37 @@ describe('LocalFileCtr', () => {
});
});
+ describe('copyAssetForPublish', () => {
+ it('copies through the protocol manager gate', async () => {
+ mockLocalFileProtocolManager.copyExternalFileForPublish.mockResolvedValue(true);
+
+ const result = await localFileCtr.copyAssetForPublish({
+ from: '/outside/image.png',
+ to: '/workspace/.lobe-artifacts/site/image.png',
+ workingDirectory: '/workspace',
+ });
+
+ expect(mockLocalFileProtocolManager.copyExternalFileForPublish).toHaveBeenCalledWith({
+ filePath: '/outside/image.png',
+ targetPath: '/workspace/.lobe-artifacts/site/image.png',
+ workspaceRoot: '/workspace',
+ });
+ expect(result).toEqual({ success: true });
+ });
+
+ it('reports a refused copy as a failure', async () => {
+ mockLocalFileProtocolManager.copyExternalFileForPublish.mockResolvedValue(false);
+
+ const result = await localFileCtr.copyAssetForPublish({
+ from: '/outside/image.png',
+ to: '/elsewhere/image.png',
+ workingDirectory: '/workspace',
+ });
+
+ expect(result.success).toBe(false);
+ });
+ });
+
describe('getLocalFilePreview', () => {
it('should return text preview content for an approved workspace file', async () => {
mockLocalFileProtocolManager.readPreviewFile.mockResolvedValue({
diff --git a/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.ts b/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.ts
index 33fcb00991e..201f1cc382c 100644
--- a/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.ts
+++ b/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.ts
@@ -1,5 +1,5 @@
import { randomUUID } from 'node:crypto';
-import { readFile, realpath, stat } from 'node:fs/promises';
+import { copyFile, mkdir, readFile, realpath, stat } from 'node:fs/promises';
import { homedir } from 'node:os';
import path from 'node:path';
@@ -469,6 +469,40 @@ export class LocalFileProtocolManager {
};
}
+ async copyExternalFileForPublish({
+ filePath,
+ targetPath,
+ workspaceRoot,
+ }: {
+ filePath: string;
+ targetPath: string;
+ workspaceRoot: string;
+ }): Promise<boolean> {
+ const normalizedTarget = normalizeAbsolutePath(targetPath);
+ const normalizedRoot = normalizeAbsolutePath(workspaceRoot);
+ if (!normalizedTarget || !normalizedRoot) return false;
+ const realRoot = normalizeAbsolutePath(await realpath(normalizedRoot));
+ if (!realRoot || !isPathWithinRoot(normalizedTarget, realRoot)) return false;
+
+ const realFilePath = await this.resolveApprovedPreviewPath({
+ allowExternalFile: true,
+ filePath,
+ persistExternalApproval: false,
+ workspaceRoot,
+ });
+ if (!realFilePath) return false;
+
+ const fileStat = await stat(realFilePath);
+ if (!fileStat.isFile()) return false;
+ if (fileStat.size > EXTERNAL_PUBLISH_ASSET_MAX_BYTES) {
+ throw new Error('File is too large to publish');
+ }
+
+ await mkdir(path.dirname(normalizedTarget), { recursive: true });
+ await copyFile(realFilePath, normalizedTarget);
+ return true;
+ }
+
/**
* Decode the URL pathname back into an absolute filesystem path.
*
diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/LocalFileProtocolManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/LocalFileProtocolManager.test.ts
index 0ac8a0206ce..17e2063ea59 100644
--- a/apps/desktop/src/main/core/infrastructure/__tests__/LocalFileProtocolManager.test.ts
+++ b/apps/desktop/src/main/core/infrastructure/__tests__/LocalFileProtocolManager.test.ts
@@ -3,26 +3,36 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { LocalFileProtocolManager } from '../LocalFileProtocolManager';
-const { mockApp, mockProtocol, mockReadFile, mockRealpath, mockStat, protocolHandlerRef } =
- vi.hoisted(() => {
- const protocolHandlerRef = { current: null as any };
-
- return {
- mockApp: {
- isReady: vi.fn().mockReturnValue(true),
- whenReady: vi.fn().mockResolvedValue(undefined),
- },
- mockProtocol: {
- handle: vi.fn((_scheme: string, handler: any) => {
- protocolHandlerRef.current = handler;
- }),
- },
- mockReadFile: vi.fn(),
- mockRealpath: vi.fn(),
- mockStat: vi.fn(),
- protocolHandlerRef,
- };
- });
+const {
+ mockApp,
+ mockCopyFile,
+ mockMkdir,
+ mockProtocol,
+ mockReadFile,
+ mockRealpath,
+ mockStat,
+ protocolHandlerRef,
+} = vi.hoisted(() => {
+ const protocolHandlerRef = { current: null as any };
+
+ return {
+ mockApp: {
+ isReady: vi.fn().mockReturnValue(true),
+ whenReady: vi.fn().mockResolvedValue(undefined),
+ },
+ mockProtocol: {
+ handle: vi.fn((_scheme: string, handler: any) => {
+ protocolHandlerRef.current = handler;
+ }),
+ },
+ mockCopyFile: vi.fn(),
+ mockMkdir: vi.fn(),
+ mockReadFile: vi.fn(),
+ mockRealpath: vi.fn(),
+ mockStat: vi.fn(),
+ protocolHandlerRef,
+ };
+});
vi.mock('electron', () => ({
app: mockApp,
@@ -30,6 +40,8 @@ vi.mock('electron', () => ({
}));
vi.mock('node:fs/promises', () => ({
+ copyFile: mockCopyFile,
+ mkdir: mockMkdir,
realpath: mockRealpath,
readFile: mockReadFile,
stat: mockStat,
@@ -486,6 +498,45 @@ describe('LocalFileProtocolManager', () => {
).resolves.toBeNull();
});
+ it('copies an external publish asset into the workspace without lasting approval', async () => {
+ const manager = new LocalFileProtocolManager();
+
+ await expect(
+ manager.copyExternalFileForPublish({
+ filePath: '/outside/logo.png',
+ targetPath: '/Users/alice/project/.lobe-artifacts/site/logo.png',
+ workspaceRoot: '/Users/alice/project',
+ }),
+ ).resolves.toBe(true);
+
+ expect(mockMkdir).toHaveBeenCalledWith('/Users/alice/project/.lobe-artifacts/site', {
+ recursive: true,
+ });
+ expect(mockCopyFile).toHaveBeenCalledWith(
+ '/outside/logo.png',
+ '/Users/alice/project/.lobe-artifacts/site/logo.png',
+ );
+ await expect(
+ manager.createPreviewUrl({
+ filePath: '/outside/logo.png',
+ workspaceRoot: '/Users/alice/project',
+ }),
+ ).resolves.toBeNull();
+ });
+
+ it('refuses to copy a publish asset to a path outside the workspace', async () => {
+ const manager = new LocalFileProtocolManager();
+
+ await expect(
+ manager.copyExternalFileForPublish({
+ filePath: '/outside/logo.png',
+ targetPath: '/Users/alice/project/../elsewhere/logo.png',
+ workspaceRoot: '/Users/alice/project',
+ }),
+ ).resolves.toBe(false);
+ expect(mockCopyFile).not.toHaveBeenCalled();
+ });
+
it('rejects an external publish asset over the limit before reading it', async () => {
mockStat.mockResolvedValue({
isFile: () => true,
diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.ts
index c6a36bc3afd..eaf4506c23e 100644
--- a/apps/server/src/routers/lambda/device.ts
+++ b/apps/server/src/routers/lambda/device.ts
@@ -716,6 +716,19 @@ export const deviceRouter = router({
});
}),
+ copyAssetForPublish: workspaceFileProcedure
+ .input(z.object({ from: z.string(), to: z.string() }))
+ .mutation(async ({ ctx, input }) =>
+ deviceGateway.copyAssetForPublish({
+ deviceId: input.deviceId,
+ from: input.from,
+ to: input.to,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ workingDirectory: input.workingDirectory,
+ }),
+ ),
+
readExternalAssetForPublish: workspaceFileProcedure
.input(z.object({ path: z.string() }))
.query(async ({ ctx, input }) =>
diff --git a/apps/server/src/services/deviceGateway/__tests__/index.test.ts b/apps/server/src/services/deviceGateway/__tests__/index.test.ts
index 29991ef33ed..12a5bf86006 100644
--- a/apps/server/src/services/deviceGateway/__tests__/index.test.ts
+++ b/apps/server/src/services/deviceGateway/__tests__/index.test.ts
@@ -900,6 +900,53 @@ describe('DeviceGateway', () => {
});
});
+ describe('copyAssetForPublish', () => {
+ it('invokes the copy RPC when the destination is inside the workspace', async () => {
+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';
+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';
+ mockClient.invokeRpc.mockResolvedValue({ data: { success: true }, success: true });
+
+ const proxy = new DeviceGateway();
+ const result = await proxy.copyAssetForPublish({
+ deviceId: 'dev-1',
+ from: '/outside/image.png',
+ to: '/proj/.lobe-artifacts/site/image.png',
+ userId: 'user-1',
+ workingDirectory: '/proj',
+ });
+
+ expect(result).toEqual({ success: true });
+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(
+ { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },
+ {
+ method: 'copyAssetForPublish',
+ params: {
+ from: '/outside/image.png',
+ to: '/proj/.lobe-artifacts/site/image.png',
+ workingDirectory: '/proj',
+ },
+ },
+ );
+ });
+
+ it('throws without invoking the rpc when the destination escapes the workspace', async () => {
+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';
+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';
+ const proxy = new DeviceGateway();
+
+ await expect(
+ proxy.copyAssetForPublish({
+ deviceId: 'dev-1',
+ from: '/outside/image.png',
+ to: '/proj/../image.png',
+ userId: 'user-1',
+ workingDirectory: '/proj',
+ }),
+ ).rejects.toThrow(/outside the approved workspace/);
+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();
+ });
+ });
+
describe('file mutation containment', () => {
const configure = () => {
mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';
diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.ts
index 1c3dc77ac4d..aede3e31501 100644
--- a/apps/server/src/services/deviceGateway/index.ts
+++ b/apps/server/src/services/deviceGateway/index.ts
@@ -13,6 +13,7 @@ import {
import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';
import type { ClaudeCodeQuotaSnapshot } from '@lobechat/heterogeneous-agents/quota';
import type {
+ DeviceCopyAssetForPublishResult,
DeviceDirectoryBrowseResult,
DeviceExternalAssetForPublishResult,
DeviceGitAddWorktreeResult,
@@ -1160,6 +1161,36 @@ export class DeviceGateway {
}
}
+ async copyAssetForPublish(params: {
+ deviceId: string;
+ from: string;
+ timeout?: number;
+ to: string;
+ userId: string;
+ workingDirectory: string;
+ workspaceId?: string;
+ }): Promise<DeviceCopyAssetForPublishResult> {
+ const { userId, deviceId, from, to, workingDirectory, timeout = 30_000, workspaceId } = params;
+ const client = this.getClient();
+ if (!client) return { error: 'Device gateway not configured', success: false };
+
+ assertPathsWithinWorkspace(workingDirectory, [to]);
+
+ try {
+ const result = await client.invokeRpc<DeviceCopyAssetForPublishResult>(
+ { deviceId, timeout, userId, workspaceId },
+ { method: 'copyAssetForPublish', params: { from, to, workingDirectory } },
+ );
+ if (!result.success || !result.data) {
+ return { error: result.error || 'Failed to copy publish asset', success: false };
+ }
+ return result.data;
+ } catch (error) {
+ log('copyAssetForPublish: error for deviceId=%s — %O', deviceId, error);
+ return { error: (error as Error).message, success: false };
+ }
+ }
+
async readExternalAssetForPublish(params: {
deviceId: string;
path: string;
diff --git a/packages/device-control/src/__tests__/dispatch.test.ts b/packages/device-control/src/__tests__/dispatch.test.ts
index 13219804d34..0db7f958879 100644
--- a/packages/device-control/src/__tests__/dispatch.test.ts
+++ b/packages/device-control/src/__tests__/dispatch.test.ts
@@ -38,6 +38,7 @@ const makeDeps = (): DeviceControlDeps => ({
root: '',
source: 'glob' as const,
})),
+ copyAssetForPublish: vi.fn(async () => ({ success: true })),
readExternalAssetForPublish: vi.fn(async () => ({
base64: 'AQID',
contentType: 'image/png',
@@ -213,6 +214,14 @@ describe('executeDeviceRpc', () => {
await executeDeviceRpc('readExternalAssetForPublish', previewParams, deps);
expect(deps.readExternalAssetForPublish).toHaveBeenCalledWith(previewParams);
+
+ const copyParams = {
+ from: previewParams.path,
+ to: path.join(root, 'copy.md'),
+ workingDirectory: root,
+ };
+ await executeDeviceRpc('copyAssetForPublish', copyParams, deps);
+ expect(deps.copyAssetForPublish).toHaveBeenCalledWith(copyParams);
});
it('routes a git method (listGitBranches) without touching deps', async () => {
diff --git a/packages/device-control/src/__tests__/filePreview.test.ts b/packages/device-control/src/__tests__/filePreview.test.ts
index 62df5372e69..9d76b91dd29 100644
--- a/packages/device-control/src/__tests__/filePreview.test.ts
+++ b/packages/device-control/src/__tests__/filePreview.test.ts
@@ -1,10 +1,11 @@
-import { mkdtemp, rm, truncate, writeFile } from 'node:fs/promises';
+import { mkdtemp, readFile, rm, truncate, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import {
+ defaultCopyAssetForPublish,
defaultGetLocalFilePreview,
defaultReadExternalAssetForPublish,
EXTERNAL_PUBLISH_ASSET_MAX_BYTES,
@@ -185,3 +186,40 @@ describe('defaultReadExternalAssetForPublish', () => {
expect(result).toEqual({ error: 'File is too large to publish', success: false });
});
});
+
+describe('defaultCopyAssetForPublish', () => {
+ it('copies an outside file into a nested workspace directory', async () => {
+ const to = path.join(root, '.lobe-artifacts', 'site', 'secret.txt');
+ const result = await defaultCopyAssetForPublish({
+ from: path.join(outside, 'secret.txt'),
+ to,
+ workingDirectory: root,
+ });
+
+ expect(result).toEqual({ success: true });
+ expect(await readFile(to, 'utf8')).toBe('do not read\n');
+ });
+
+ it('refuses a destination outside the workspace', async () => {
+ const result = await defaultCopyAssetForPublish({
+ from: path.join(outside, 'secret.txt'),
+ to: path.join(outside, 'copy.txt'),
+ workingDirectory: root,
+ });
+
+ expect(result).toEqual({
+ error: 'Destination is outside the approved workspace',
+ success: false,
+ });
+ });
+
+ it('refuses a destination that escapes through dot segments', async () => {
+ const result = await defaultCopyAssetForPublish({
+ from: path.join(outside, 'secret.txt'),
+ to: path.join(root, '..', path.basename(outside), 'copy.txt'),
+ workingDirectory: root,
+ });
+
+ expect(result.success).toBe(false);
+ });
+});
diff --git a/packages/device-control/src/dispatch.ts b/packages/device-control/src/dispatch.ts
index 168b5a6135c..0cb44cb5622 100644
--- a/packages/device-control/src/dispatch.ts
+++ b/packages/device-control/src/dispatch.ts
@@ -21,11 +21,12 @@ import {
} from '@lobechat/local-file-shell/git';
import { getClaudeCodeQuota, type GetClaudeCodeQuotaParams } from './claudeCodeQuota';
-import { defaultReadExternalAssetForPublish } from './filePreview';
+import { defaultCopyAssetForPublish, defaultReadExternalAssetForPublish } from './filePreview';
import { defaultListProjectDirectory } from './projectFileIndex';
import { prepareSkillDirectory } from './skillDirectory';
import type {
BrowseDirectoryParams,
+ CopyAssetForPublishParams,
DeviceControlDeps,
EnrollWorkspaceParams,
ExternalAssetForPublishParams,
@@ -62,6 +63,7 @@ export const DEVICE_RPC_METHODS = [
'searchProjectFiles',
'getLocalFilePreview',
'readExternalAssetForPublish',
+ 'copyAssetForPublish',
'moveLocalFiles',
'renameLocalFile',
'writeLocalFile',
@@ -172,6 +174,12 @@ export const executeDeviceRpc = async (
);
}
+ case 'copyAssetForPublish': {
+ return (deps.copyAssetForPublish ?? defaultCopyAssetForPublish)(
+ params as CopyAssetForPublishParams,
+ );
+ }
+
case 'moveLocalFiles': {
return moveLocalFiles(params as { items: { newPath: string; oldPath: string }[] });
}
diff --git a/packages/device-control/src/filePreview.ts b/packages/device-control/src/filePreview.ts
index db6698fc403..2f9eb2b8940 100644
--- a/packages/device-control/src/filePreview.ts
+++ b/packages/device-control/src/filePreview.ts
@@ -1,4 +1,4 @@
-import { readFile, realpath, stat } from 'node:fs/promises';
+import { copyFile, mkdir, readFile, realpath, stat } from 'node:fs/promises';
import { homedir } from 'node:os';
import path from 'node:path';
@@ -6,6 +6,8 @@ import { WORKSPACE_HTML_ARTIFACT_MAX_FILE_BYTES } from '@lobechat/html-artifact/
import { getMimeType, resolveMimeType } from '@lobechat/utils/mimeType';
import type {
+ CopyAssetForPublishParams,
+ CopyAssetForPublishResult,
ExternalAssetForPublishParams,
ExternalAssetForPublishResult,
LocalFilePreview,
@@ -189,3 +191,56 @@ export const defaultReadExternalAssetForPublish = async ({
return { error: (error as Error).message, success: false };
}
};
+
+const resolvePublishPath = (target: string, workingDirectory: string): string => {
+ const expanded = expandHomePath(target);
+ return path.isAbsolute(expanded)
+ ? expanded
+ : path.resolve(expandHomePath(workingDirectory), expanded);
+};
+
+// The destination usually does not exist yet, so realpath the nearest existing
+// ancestor and re-append the missing tail; otherwise a symlinked tmp root
+// (`/var` → `/private/var`) never matches the realpath'd workspace root.
+const realpathForCreate = async (target: string): Promise<string> => {
+ const missing: string[] = [];
+ let current = path.resolve(target);
+ for (;;) {
+ try {
+ return path.join(await realpath(current), ...missing);
+ } catch {
+ const parent = path.dirname(current);
+ if (parent === current) return path.join(current, ...missing);
+ missing.unshift(path.basename(current));
+ current = parent;
+ }
+ }
+};
+
+export const defaultCopyAssetForPublish = async ({
+ from,
+ to,
+ workingDirectory,
+}: CopyAssetForPublishParams): Promise<CopyAssetForPublishResult> => {
+ try {
+ if (!workingDirectory) return { error: 'Missing working directory', success: false };
+ const realRoot = await safeRealpath(expandHomePath(workingDirectory));
+ const target = await realpathForCreate(resolvePublishPath(to, workingDirectory));
+ if (!target.startsWith(`${realRoot}${path.sep}`)) {
+ return { error: 'Destination is outside the approved workspace', success: false };
+ }
+
+ const realSource = await realpath(resolvePublishPath(from, workingDirectory));
+ const stats = await stat(realSource);
+ if (!stats.isFile()) return { error: 'Path is not a file', success: false };
+ if (stats.size > EXTERNAL_PUBLISH_ASSET_MAX_BYTES) {
+ return { error: 'File is too large to publish', success: false };
+ }
+
+ await mkdir(path.dirname(target), { recursive: true });
+ await copyFile(realSource, target);
+ return { success: true };
+ } catch (error) {
+ return { error: (error as Error).message, success: false };
+ }
+};
diff --git a/packages/device-control/src/index.ts b/packages/device-control/src/index.ts
index 0020ff92bb2..642c30c478f 100644
--- a/packages/device-control/src/index.ts
+++ b/packages/device-control/src/index.ts
@@ -1,5 +1,6 @@
export { DEVICE_RPC_METHODS, type DeviceRpcMethod, executeDeviceRpc } from './dispatch';
export {
+ defaultCopyAssetForPublish,
defaultGetLocalFilePreview,
defaultReadExternalAssetForPublish,
EXTERNAL_PUBLISH_ASSET_MAX_BYTES,
diff --git a/packages/device-control/src/types.ts b/packages/device-control/src/types.ts
index 392b861d4c5..96869352f8a 100644
--- a/packages/device-control/src/types.ts
+++ b/packages/device-control/src/types.ts
@@ -97,6 +97,17 @@ export interface LocalFilePreviewUrlParams {
workingDirectory: string;
}
+export interface CopyAssetForPublishParams {
+ from: string;
+ to: string;
+ workingDirectory: string;
+}
+
+export interface CopyAssetForPublishResult {
+ error?: string;
+ success: boolean;
+}
+
export interface ExternalAssetForPublishParams {
path: string;
workingDirectory: string;
@@ -262,6 +273,8 @@ export interface WorkspaceScanDeps {
* (`defaultGetLocalFilePreview`, `defaultGetProjectFileIndex`).
*/
export interface DeviceControlDeps extends SkillDirectoryDeps, WorkspaceScanDeps {
+ /** Copy a publish asset (possibly outside the workspace) to a path inside the workspace. */
+ copyAssetForPublish?: (params: CopyAssetForPublishParams) => Promise<CopyAssetForPublishResult>;
/**
* Enroll this machine into a workspace pool: derive the workspace-scoped
* deviceId and open a second gateway connection authenticated with `token`
diff --git a/packages/types/src/device.ts b/packages/types/src/device.ts
index 2a69956941a..28d1f3919aa 100644
--- a/packages/types/src/device.ts
+++ b/packages/types/src/device.ts
@@ -722,6 +722,11 @@ export interface DeviceLocalFilePreviewResult {
success: boolean;
}
+export interface DeviceCopyAssetForPublishResult {
+ error?: string;
+ success: boolean;
+}
+
export interface DeviceExternalAssetForPublishResult {
base64?: string;
contentType?: string;
diff --git a/src/features/Portal/LocalFile/PreviewToolbar.tsx b/src/features/Portal/LocalFile/PreviewToolbar.tsx
index c87de152092..31d0381b932 100644
--- a/src/features/Portal/LocalFile/PreviewToolbar.tsx
+++ b/src/features/Portal/LocalFile/PreviewToolbar.tsx
@@ -1,6 +1,6 @@
import { Flexbox, Icon, Tooltip } from '@lobehub/ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
-import type { LucideIcon } from 'lucide-react';
+import { Loader2Icon, type LucideIcon } from 'lucide-react';
import type { MouseEventHandler, ReactNode } from 'react';
import { memo } from 'react';
@@ -125,7 +125,7 @@ export const ToolbarActionButton = memo<ToolbarActionButtonProps>(
type={'button'}
onClick={onClick}
>
- <Icon icon={icon} size={14} spin={loading} />
+ <Icon icon={loading ? Loader2Icon : icon} size={14} spin={loading} />
{label && <span className={styles.actionLabel}>{label}</span>}
</button>
);
diff --git a/src/features/Portal/LocalFile/useBlockedWorkspaceHtmlPublish.test.ts b/src/features/Portal/LocalFile/useBlockedWorkspaceHtmlPublish.test.ts
index 2aeab4a9f00..90376aa4c8f 100644
--- a/src/features/Portal/LocalFile/useBlockedWorkspaceHtmlPublish.test.ts
+++ b/src/features/Portal/LocalFile/useBlockedWorkspaceHtmlPublish.test.ts
@@ -134,6 +134,22 @@ describe('useBlockedWorkspaceHtmlPublish', () => {
expect(mocks.openConfirm).toHaveBeenCalledOnce();
});
+ it('hands the confirmed plan to runPublish instead of publishing inline', async () => {
+ mocks.prepare.mockResolvedValueOnce(ready).mockResolvedValueOnce(ready);
+ mocks.copy.mockResolvedValue(copied);
+ const runPublish = vi.fn();
+ const { result } = renderHook(() => useBlockedWorkspaceHtmlPublish({ ...input, runPublish }));
+
+ await act(() => result.current.handleContinue());
+ mocks.openConfirm.mock.calls[0][0].onOk();
+
+ expect(runPublish).toHaveBeenCalledWith({
+ plan: ready,
+ successMessage: 'workingPanel.localFile.publish.outsideWorkspace.copiedToast',
+ });
+ expect(mocks.publishPrepared).not.toHaveBeenCalled();
+ });
+
it('shows newly discovered closure files and requires a second click before copying', async () => {
const localResource = {
absolutePath: '/project/assets/app.css',
diff --git a/src/features/Portal/LocalFile/useBlockedWorkspaceHtmlPublish.ts b/src/features/Portal/LocalFile/useBlockedWorkspaceHtmlPublish.ts
index 401c839b42b..cea6314cea3 100644
--- a/src/features/Portal/LocalFile/useBlockedWorkspaceHtmlPublish.ts
+++ b/src/features/Portal/LocalFile/useBlockedWorkspaceHtmlPublish.ts
@@ -41,6 +41,7 @@ export interface BlockedWorkspaceHtmlPublishInput {
) => void;
plan: OutsideWorkspacePlan;
publish: WorkspaceHtmlArtifactPublisher['publish'];
+ runPublish?: (input: { plan: ReadyWorkspaceHtmlPublishPlan; successMessage?: string }) => void;
sandboxTopicId?: string;
topicId: string;
workingDirectory: string;
@@ -58,6 +59,7 @@ export const useBlockedWorkspaceHtmlPublish = ({
onPublished,
plan,
publish,
+ runPublish,
sandboxTopicId,
topicId,
workingDirectory,
@@ -98,20 +100,23 @@ export const useBlockedWorkspaceHtmlPublish = ({
const openConfirm = (ready: ReadyWorkspaceHtmlPublishPlan, copiedDirectory?: string) => {
close();
+ const successMessage = copiedDirectory
+ ? t('workingPanel.localFile.publish.outsideWorkspace.copiedToast', { dir: copiedDirectory })
+ : undefined;
openWorkspaceHtmlPublishConfirm({
hasExisting,
plan: ready,
onOk: () => {
+ if (runPublish) {
+ runPublish({ plan: ready, successMessage });
+ return;
+ }
void publishPreparedWorkspaceHtml({
agentId,
onError,
plan: ready,
publish,
- successMessage: copiedDirectory
- ? t('workingPanel.localFile.publish.outsideWorkspace.copiedToast', {
- dir: copiedDirectory,
- })
- : undefined,
+ successMessage,
topicId,
}).then((result) => {
if (result) onPublished?.(result, ready);
diff --git a/src/features/Portal/LocalFile/workspaceHtmlPublishFileOps.test.ts b/src/features/Portal/LocalFile/workspaceHtmlPublishFileOps.test.ts
new file mode 100644
index 00000000000..c8ed7929034
--- /dev/null
+++ b/src/features/Portal/LocalFile/workspaceHtmlPublishFileOps.test.ts
@@ -0,0 +1,79 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cloudSandboxService } from '@/services/cloudSandbox';
+import { projectFileService } from '@/services/projectFile';
+
+import { createWorkspaceHtmlPublishFileOps } from './workspaceHtmlPublishFileOps';
+
+vi.mock('@/services/cloudSandbox', () => ({
+ cloudSandboxService: { callTool: vi.fn() },
+}));
+vi.mock('@/services/projectFile', () => ({
+ projectFileService: { copyAssetForPublish: vi.fn(), writeProjectFile: vi.fn() },
+}));
+
+describe('createWorkspaceHtmlPublishFileOps', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('routes local and device files through projectFileService', async () => {
+ vi.mocked(projectFileService.copyAssetForPublish).mockResolvedValue({ success: true });
+ vi.mocked(projectFileService.writeProjectFile).mockResolvedValue({ success: true });
+ const ops = createWorkspaceHtmlPublishFileOps({ deviceId: 'dev-1', workingDirectory: '/ws' });
+
+ await ops.copyFile('/outside/logo.png', '/ws/.lobe-artifacts/site/logo.png');
+ await ops.writeFile('/ws/.lobe-artifacts/site/index.html', '<html/>');
+
+ expect(projectFileService.copyAssetForPublish).toHaveBeenCalledWith({
+ deviceId: 'dev-1',
+ from: '/outside/logo.png',
+ to: '/ws/.lobe-artifacts/site/logo.png',
+ workingDirectory: '/ws',
+ });
+ expect(projectFileService.writeProjectFile).toHaveBeenCalledWith({
+ content: '<html/>',
+ deviceId: 'dev-1',
+ path: '/ws/.lobe-artifacts/site/index.html',
+ workingDirectory: '/ws',
+ });
+ });
+
+ it('throws the transport error when a copy is refused', async () => {
+ vi.mocked(projectFileService.copyAssetForPublish).mockResolvedValue({
+ error: 'Destination is outside the approved workspace',
+ success: false,
+ });
+ const ops = createWorkspaceHtmlPublishFileOps({ workingDirectory: '/ws' });
+
+ await expect(ops.copyFile('/outside/logo.png', '/elsewhere/logo.png')).rejects.toThrow(
+ 'Destination is outside the approved workspace',
+ );
+ });
+
+ it('routes sandbox files through shell copy and writeFile tools', async () => {
+ vi.mocked(cloudSandboxService.callTool).mockResolvedValue({ result: {}, success: true });
+ const ops = createWorkspaceHtmlPublishFileOps({
+ sandboxTopicId: 'topic-1',
+ workingDirectory: '/ws',
+ });
+
+ await ops.copyFile("/outside/it's.png", '/ws/.lobe-artifacts/site/logo.png');
+ await ops.writeFile('/ws/.lobe-artifacts/site/index.html', '<html/>');
+
+ expect(cloudSandboxService.callTool).toHaveBeenNthCalledWith(
+ 1,
+ 'runCommand',
+ expect.objectContaining({
+ command: `mkdir -p '/ws/.lobe-artifacts/site' && cp '/outside/it'\\''s.png' '/ws/.lobe-artifacts/site/logo.png'`,
+ }),
+ { topicId: 'topic-1' },
+ );
+ expect(cloudSandboxService.callTool).toHaveBeenNthCalledWith(
+ 2,
+ 'writeFile',
+ { content: '<html/>', createDirectories: true, path: '/ws/.lobe-artifacts/site/index.html' },
+ { topicId: 'topic-1' },
+ );
+ });
+});
diff --git a/src/features/Portal/LocalFile/workspaceHtmlPublishFileOps.ts b/src/features/Portal/LocalFile/workspaceHtmlPublishFileOps.ts
new file mode 100644
index 00000000000..e44c3f06381
--- /dev/null
+++ b/src/features/Portal/LocalFile/workspaceHtmlPublishFileOps.ts
@@ -0,0 +1,77 @@
+import { cloudSandboxService } from '@/services/cloudSandbox';
+import { projectFileService } from '@/services/projectFile';
+
+interface WorkspaceHtmlPublishFileOpsInput {
+ deviceId?: string;
+ sandboxTopicId?: string;
+ workingDirectory: string;
+}
+
+export interface WorkspaceHtmlPublishFileOps {
+ copyFile: (from: string, to: string) => Promise<void>;
+ writeFile: (path: string, content: string) => Promise<void>;
+}
+
+const quoteShellArg = (value: string): string => `'${value.replaceAll("'", `'\\''`)}'`;
+
+const posixDirname = (path: string): string => path.slice(0, path.lastIndexOf('/')) || '/';
+
+const assertSuccess = (
+ result: { error?: string | { message?: string }; success: boolean },
+ fallback: string,
+) => {
+ if (result.success) return;
+ const message = typeof result.error === 'string' ? result.error : result.error?.message;
+ throw new Error(message || fallback);
+};
+
+export const createWorkspaceHtmlPublishFileOps = ({
+ deviceId,
+ sandboxTopicId,
+ workingDirectory,
+}: WorkspaceHtmlPublishFileOpsInput): WorkspaceHtmlPublishFileOps => {
+ if (sandboxTopicId) {
+ return {
+ copyFile: async (from, to) => {
+ const result = await cloudSandboxService.callTool(
+ 'runCommand',
+ {
+ command: `mkdir -p ${quoteShellArg(posixDirname(to))} && cp ${quoteShellArg(from)} ${quoteShellArg(to)}`,
+ description: 'Copy publish asset into workspace',
+ },
+ { topicId: sandboxTopicId },
+ );
+ assertSuccess(result, 'Failed to copy publish asset');
+ },
+ writeFile: async (path, content) => {
+ const result = await cloudSandboxService.callTool(
+ 'writeFile',
+ { content, createDirectories: true, path },
+ { topicId: sandboxTopicId },
+ );
+ assertSuccess(result, 'Failed to write publish file');
+ },
+ };
+ }
+
+ return {
+ copyFile: async (from, to) => {
+ const result = await projectFileService.copyAssetForPublish({
+ deviceId,
+ from,
+ to,
+ workingDirectory,
+ });
+ assertSuccess(result, 'Failed to copy publish asset');
+ },
+ writeFile: async (path, content) => {
+ const result = await projectFileService.writeProjectFile({
+ content,
+ deviceId,
+ path,
+ workingDirectory,
+ });
+ assertSuccess(result, 'Failed to write publish file');
+ },
+ };
+};
diff --git a/src/services/electron/localFileService.ts b/src/services/electron/localFileService.ts
index 792c66009d6..ab37eca0b94 100644
--- a/src/services/electron/localFileService.ts
+++ b/src/services/electron/localFileService.ts
@@ -282,6 +282,14 @@ class LocalFileService {
return fetchLocalFileBytes(result.url);
}
+ async copyAssetForPublish(params: {
+ from: string;
+ to: string;
+ workingDirectory: string;
+ }): Promise<{ error?: string; success: boolean }> {
+ return ensureElectronIpc().localSystem.copyAssetForPublish(params);
+ }
+
async prepareSkillDirectory(
params: PrepareSkillDirectoryParams,
): Promise<PrepareSkillDirectoryResult> {
diff --git a/src/services/projectFile.test.ts b/src/services/projectFile.test.ts
index 653c0853bb4..55d50015158 100644
--- a/src/services/projectFile.test.ts
+++ b/src/services/projectFile.test.ts
@@ -1,6 +1,7 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
const mockDeviceClient = vi.hoisted(() => ({
+ copyAssetForPublish: { mutate: vi.fn() },
getLocalFilePreview: { query: vi.fn() },
getProjectFileIndex: { query: vi.fn() },
readExternalAssetForPublish: { query: vi.fn() },
@@ -8,6 +9,7 @@ const mockDeviceClient = vi.hoisted(() => ({
}));
const mockLocalFileService = vi.hoisted(() => ({
+ copyAssetForPublish: vi.fn(),
getLocalFilePreview: vi.fn(),
getProjectFileIndex: vi.fn(),
readExternalAssetForPublish: vi.fn(),
@@ -186,6 +188,30 @@ describe('projectFileService', () => {
expect(mockLocalFileService.getLocalFilePreview).not.toHaveBeenCalled();
});
+ it('copies a publish asset through the remote RPC or the desktop service', async () => {
+ const { projectFileService } = await import('./projectFile');
+ const params = {
+ from: '/outside/logo.png',
+ to: '/repo/.lobe-artifacts/site/logo.png',
+ workingDirectory: '/repo',
+ };
+ mockDeviceClient.copyAssetForPublish.mutate.mockResolvedValue({ success: true });
+ mockLocalFileService.copyAssetForPublish.mockResolvedValue({ success: true });
+
+ await expect(
+ projectFileService.copyAssetForPublish({ deviceId: 'device-1', ...params }),
+ ).resolves.toEqual({ success: true });
+ expect(mockDeviceClient.copyAssetForPublish.mutate).toHaveBeenCalledWith({
+ deviceId: 'device-1',
+ ...params,
+ });
+
+ await expect(projectFileService.copyAssetForPublish(params)).resolves.toEqual({
+ success: true,
+ });
+ expect(mockLocalFileService.copyAssetForPublish).toHaveBeenCalledWith(params);
+ });
+
it('searches remote project files through device RPC', async () => {
const { projectFileService } = await import('./projectFile');
mockDeviceClient.searchProjectFiles.query.mockResolvedValue({
diff --git a/src/services/projectFile.ts b/src/services/projectFile.ts
index e2c8aa9a615..0b92073a9a3 100644
--- a/src/services/projectFile.ts
+++ b/src/services/projectFile.ts
@@ -170,6 +170,22 @@ class ProjectFileService {
};
}
+ async copyAssetForPublish({
+ deviceId,
+ from,
+ to,
+ workingDirectory,
+ }: {
+ deviceId?: string;
+ from: string;
+ to: string;
+ workingDirectory: string;
+ }): Promise<{ error?: string; success: boolean }> {
+ return deviceId
+ ? lambdaClient.device.copyAssetForPublish.mutate({ deviceId, from, to, workingDirectory })
+ : localFileService.copyAssetForPublish({ from, to, workingDirectory });
+ }
+
/**
* Move one or more files/folders within a project working directory. Batched:
* each item succeeds or fails independently.