🤯 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(portal): guide outside-workspace HTML publishing (#19338)
Innei07fb75254723
diff --git a/apps/cli/pnpm-workspace.yaml b/apps/cli/pnpm-workspace.yamlindex fcc6ed93919..03bb2caeef7 100644--- a/apps/cli/pnpm-workspace.yaml+++ b/apps/cli/pnpm-workspace.yaml@@ -6,6 +6,7 @@ packages:- '../../packages/device-gateway-client'- '../../packages/device-identity'- '../../packages/heterogeneous-agents'+ - '../../packages/html-artifact'- '../../packages/local-file-shell'- '../../packages/tool-runtime'- '../../packages/prompts'diff --git a/apps/desktop/pnpm-lock.yaml b/apps/desktop/pnpm-lock.yamlindex 59e19577143..8ad70aa7c4f 100644--- a/apps/desktop/pnpm-lock.yaml+++ b/apps/desktop/pnpm-lock.yaml@@ -325,6 +325,9 @@ importers:'@lobechat/heterogeneous-agents':specifier: workspace:*version: link:../heterogeneous-agents+ '@lobechat/html-artifact':+ specifier: workspace:*+ version: link:../html-artifact'@lobechat/local-file-shell':specifier: workspace:*version: link:../local-file-shelldiff --git a/apps/desktop/pnpm-workspace.yaml b/apps/desktop/pnpm-workspace.yamlindex cac3d11578b..d3b06613e09 100644--- a/apps/desktop/pnpm-workspace.yaml+++ b/apps/desktop/pnpm-workspace.yaml@@ -4,6 +4,7 @@ packages:- '../../packages/agent-tracing'- '../../packages/chat-adapter-imessage'- '../../packages/heterogeneous-agents'+ - '../../packages/html-artifact'- '../../packages/const'- '../../packages/eval-rubric'- '../../packages/electron-server-ipc'diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.tsindex b8729e18f89..a71545708c1 100644--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts@@ -413,6 +413,8 @@ export default class GatewayConnectionCtr extends ControllerModule {// the gateway connections, so both handlers route straight to it.enrollWorkspace: (params) => this.service.enrollWorkspace(params),getLocalFilePreview: (params) => this.localFileCtr.getLocalFilePreview(params),+ readExternalAssetForPublish: (params) =>+ this.localFileCtr.readExternalAssetForPublish(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.tsindex d95fef62423..6fbefb72a5c 100644--- a/apps/desktop/src/main/controllers/LocalFileCtr.ts+++ b/apps/desktop/src/main/controllers/LocalFileCtr.ts@@ -3,7 +3,11 @@ import { constants, createReadStream } from 'node:fs';import { access, readFile, realpath, stat } from 'node:fs/promises';import path from 'node:path';-import type { SkillDirectoryDeps } from '@lobechat/device-control';+import type {+ ExternalAssetForPublishParams,+ ExternalAssetForPublishResult,+ SkillDirectoryDeps,+} from '@lobechat/device-control';import {defaultGetProjectFileIndex,defaultSearchProjectFiles,@@ -559,6 +563,49 @@ export default class LocalFileCtr extends ControllerModule {}}+ @IpcMethod()+ async getExternalAssetForPublishUrl({+ path: filePath,+ workingDirectory,+ }: ExternalAssetForPublishParams): Promise<LocalFilePreviewUrlResult> {+ try {+ const url = await this.app.localFileProtocolManager.createPreviewUrl({+ allowExternalFile: true,+ filePath,+ persistExternalApproval: false,+ workspaceRoot: workingDirectory,+ });+ return url+ ? { success: true, url }+ : { error: 'Failed to approve external publish asset', success: false };+ } catch (error) {+ logger.error('Failed to create external publish asset URL:', error);+ return { error: (error as Error).message, success: false };+ }+ }++ async readExternalAssetForPublish({+ path: filePath,+ workingDirectory,+ }: ExternalAssetForPublishParams): Promise<ExternalAssetForPublishResult> {+ try {+ const asset = await this.app.localFileProtocolManager.readExternalFileForPublish({+ filePath,+ workspaceRoot: workingDirectory,+ });+ if (!asset) return { error: 'Failed to approve external publish asset', success: false };++ return {+ base64: asset.buffer.toString('base64'),+ contentType: asset.contentType,+ success: true,+ };+ } catch (error) {+ logger.error('Failed to read external 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.tsindex e4ba87bc23e..87a7669cbfe 100644--- a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts@@ -81,6 +81,7 @@ const mockLocalFileProtocolManager = {approveIndexedProjectRoot: vi.fn(),approveProjectRootFromScope: vi.fn(),createPreviewUrl: vi.fn(),+ readExternalFileForPublish: vi.fn(),readPreviewFile: vi.fn(),};@@ -325,6 +326,53 @@ describe('LocalFileCtr', () => {});});+ describe('external publish asset channels', () => {+ it('creates a URL with external access only on the publish-scoped IPC method', async () => {+ mockLocalFileProtocolManager.createPreviewUrl.mockResolvedValue(+ 'localfile://publish/outside.css?token=abc',+ );++ const result = await localFileCtr.getExternalAssetForPublishUrl({+ path: '/outside/app.css',+ workingDirectory: '/workspace',+ });++ expect(mockLocalFileProtocolManager.createPreviewUrl).toHaveBeenCalledWith({+ allowExternalFile: true,+ filePath: '/outside/app.css',+ persistExternalApproval: false,+ workspaceRoot: '/workspace',+ });+ expect(result).toEqual({+ success: true,+ url: 'localfile://publish/outside.css?token=abc',+ });+ });++ it('returns raw bytes for the publish-scoped device RPC handler', async () => {+ mockLocalFileProtocolManager.readExternalFileForPublish.mockResolvedValue({+ buffer: Buffer.from([1, 2, 3]),+ contentType: 'image/png',+ realPath: '/outside/image.png',+ });++ const result = await localFileCtr.readExternalAssetForPublish({+ path: '/outside/image.png',+ workingDirectory: '/workspace',+ });++ expect(mockLocalFileProtocolManager.readExternalFileForPublish).toHaveBeenCalledWith({+ filePath: '/outside/image.png',+ workspaceRoot: '/workspace',+ });+ expect(result).toEqual({+ base64: 'AQID',+ contentType: 'image/png',+ success: true,+ });+ });+ });+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.tsindex 94186c48a52..33fcb00991e 100644--- a/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.ts+++ b/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.ts@@ -3,6 +3,7 @@ import { readFile, realpath, stat } from 'node:fs/promises';import { homedir } from 'node:os';import path from 'node:path';+import { EXTERNAL_PUBLISH_ASSET_MAX_BYTES } from '@lobechat/device-control/file-preview';import { getMimeType, resolveMimeType } from '@lobechat/utils/mimeType';import { app, protocol } from 'electron';@@ -318,12 +319,14 @@ export class LocalFileProtocolManager {accept,allowExternalFile,filePath,+ persistExternalApproval = true,resourceScope,workspaceRoot,}: {accept?: PreviewFileAccept;allowExternalFile?: boolean;filePath: string;+ persistExternalApproval?: boolean;resourceScope?: 'workspace';workspaceRoot: string;}): Promise<string | null> {@@ -339,7 +342,12 @@ export class LocalFileProtocolManager {workspaceRoot,}))?.realPath- : await this.resolveApprovedPreviewPath({ allowExternalFile, filePath, workspaceRoot });+ : await this.resolveApprovedPreviewPath({+ allowExternalFile,+ filePath,+ persistExternalApproval,+ workspaceRoot,+ });if (!realFilePath) return null;this.cleanupExpiredTokens();@@ -430,6 +438,37 @@ export class LocalFileProtocolManager {};}+ async readExternalFileForPublish({+ filePath,+ workspaceRoot,+ }: {+ filePath: string;+ workspaceRoot: string;+ }): Promise<PreviewFileReadResult | null> {+ const realFilePath = await this.resolveApprovedPreviewPath({+ allowExternalFile: true,+ filePath,+ persistExternalApproval: false,+ workspaceRoot,+ });+ if (!realFilePath) return null;++ const fileStat = await stat(realFilePath);+ if (!fileStat.isFile()) return null;+ // Reject by size before reading: the renderer's limit check only runs after+ // the whole file has been read and base64-encoded into a gateway response.+ if (fileStat.size > EXTERNAL_PUBLISH_ASSET_MAX_BYTES) {+ throw new Error('File is too large to publish');+ }+ const buffer = await readFile(realFilePath);++ return {+ buffer,+ contentType: await resolveMimeType(realFilePath, buffer),+ realPath: realFilePath,+ };+ }+/*** 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.tsindex 9a30571b145..0ac8a0206ce 100644--- a/apps/desktop/src/main/core/infrastructure/__tests__/LocalFileProtocolManager.test.ts+++ b/apps/desktop/src/main/core/infrastructure/__tests__/LocalFileProtocolManager.test.ts@@ -1,3 +1,4 @@+import { EXTERNAL_PUBLISH_ASSET_MAX_BYTES } from '@lobechat/device-control/file-preview';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { LocalFileProtocolManager } from '../LocalFileProtocolManager';@@ -447,6 +448,60 @@ describe('LocalFileProtocolManager', () => {expect(neighborUrl).toBeNull();});+ it('can mint one external URL without granting lasting preview access', async () => {+ const manager = new LocalFileProtocolManager();+ const url = await manager.createPreviewUrl({+ allowExternalFile: true,+ filePath: '/outside/app.css',+ persistExternalApproval: false,+ workspaceRoot: '/Users/alice/project',+ });++ expect(url).toContain('token=');+ await expect(+ manager.createPreviewUrl({+ filePath: '/outside/app.css',+ workspaceRoot: '/Users/alice/project',+ }),+ ).resolves.toBeNull();+ });++ it('reads an external publish asset without the preview cap or lasting approval', async () => {+ mockStat.mockResolvedValue({ isFile: () => true, size: 20 * 1024 * 1024 + 1 });+ mockReadFile.mockResolvedValue(Buffer.from('%PDF publish bytes'));+ const manager = new LocalFileProtocolManager();++ const result = await manager.readExternalFileForPublish({+ filePath: '/outside/big.pdf',+ workspaceRoot: '/Users/alice/project',+ });++ expect(result?.buffer).toEqual(Buffer.from('%PDF publish bytes'));+ expect(mockReadFile).toHaveBeenCalledWith('/outside/big.pdf');+ await expect(+ manager.createPreviewUrl({+ filePath: '/outside/big.pdf',+ workspaceRoot: '/Users/alice/project',+ }),+ ).resolves.toBeNull();+ });++ it('rejects an external publish asset over the limit before reading it', async () => {+ mockStat.mockResolvedValue({+ isFile: () => true,+ size: EXTERNAL_PUBLISH_ASSET_MAX_BYTES + 1,+ });+ const manager = new LocalFileProtocolManager();++ await expect(+ manager.readExternalFileForPublish({+ filePath: '/outside/huge.mp4',+ workspaceRoot: '/Users/alice/project',+ }),+ ).rejects.toThrow('File is too large to publish');+ expect(mockReadFile).not.toHaveBeenCalled();+ });+it('can approve a project root derived from an already approved nested scope', async () => {const manager = new LocalFileProtocolManager();await manager.approveWorkspaceRoot('/Users/alice/project/packages/app');diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.tsindex a6715ff7ab4..ef75e28b309 100644--- a/apps/server/src/routers/lambda/device.ts+++ b/apps/server/src/routers/lambda/device.ts@@ -698,6 +698,18 @@ export const deviceRouter = router({});}),+ readExternalAssetForPublish: workspaceFileProcedure+ .input(z.object({ path: z.string() }))+ .query(async ({ ctx, input }) =>+ deviceGateway.readExternalAssetForPublish({+ deviceId: input.deviceId,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ workingDirectory: input.workingDirectory,+ }),+ ),+/*** Project skills (`.agents/skills` / `.claude/skills`) for a directory on a* remote device, via the device's `listProjectSkills` RPC. Powers thediff --git a/apps/server/src/services/deviceGateway/__tests__/index.test.ts b/apps/server/src/services/deviceGateway/__tests__/index.test.tsindex ff741a6305e..29991ef33ed 100644--- a/apps/server/src/services/deviceGateway/__tests__/index.test.ts+++ b/apps/server/src/services/deviceGateway/__tests__/index.test.ts@@ -874,6 +874,32 @@ describe('DeviceGateway', () => {});});+ describe('readExternalAssetForPublish', () => {+ it('invokes only the dedicated publish RPC method', async () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ const data = { base64: 'AQID', contentType: 'image/png', success: true };+ mockClient.invokeRpc.mockResolvedValue({ data, success: true });++ const proxy = new DeviceGateway();+ const result = await proxy.readExternalAssetForPublish({+ deviceId: 'dev-1',+ path: '/outside/image.png',+ userId: 'user-1',+ workingDirectory: '/proj',+ });++ expect(result).toEqual(data);+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(+ { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },+ {+ method: 'readExternalAssetForPublish',+ params: { path: '/outside/image.png', workingDirectory: '/proj' },+ },+ );+ });+ });+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.tsindex 54d6c3db999..f0a08f5f4a7 100644--- a/apps/server/src/services/deviceGateway/index.ts+++ b/apps/server/src/services/deviceGateway/index.ts@@ -14,6 +14,7 @@ import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';import type { ClaudeCodeQuotaSnapshot } from '@lobechat/heterogeneous-agents/quota';import type {DeviceDirectoryBrowseResult,+ DeviceExternalAssetForPublishResult,DeviceGitAddWorktreeResult,DeviceGitAheadBehind,DeviceGitBranchDiffPatches,@@ -1124,6 +1125,33 @@ export class DeviceGateway {}}+ async readExternalAssetForPublish(params: {+ deviceId: string;+ path: string;+ timeout?: number;+ userId: string;+ workingDirectory: string;+ workspaceId?: string;+ }): Promise<DeviceExternalAssetForPublishResult> {+ const { userId, deviceId, path, workingDirectory, timeout = 30_000, workspaceId } = params;+ const client = this.getClient();+ if (!client) return { error: 'Device gateway not configured', success: false };++ try {+ const result = await client.invokeRpc<DeviceExternalAssetForPublishResult>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'readExternalAssetForPublish', params: { path, workingDirectory } },+ );+ if (!result.success || !result.data) {+ return { error: result.error || 'Failed to read external publish asset', success: false };+ }+ return result.data;+ } catch (error) {+ log('readExternalAssetForPublish: error for deviceId=%s — %O', deviceId, error);+ return { error: (error as Error).message, success: false };+ }+ }+/*** Project skills (`.agents/skills` / `.claude/skills`) for a directory on a* remote device via the `listProjectSkills` device RPC — the Resources tab'sdiff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 781caec2bf9..dc55a519f1e 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -2472,6 +2472,24 @@"workingPanel.localFile.publish.noLocalFiles": "This page has no local files besides the HTML.","workingPanel.localFile.publish.noTopic": "Open a topic to publish this page","workingPanel.localFile.publish.note": "You can unpublish it at any time.",+ "workingPanel.localFile.publish.outsideWorkspace.closureDescription": "More local files were found. Review the complete list, then click copy again to continue.",+ "workingPanel.localFile.publish.outsideWorkspace.copiedToast": "Published from the workspace copy at {{dir}}",+ "workingPanel.localFile.publish.outsideWorkspace.copyAction": "Copy to workspace and publish",+ "workingPanel.localFile.publish.outsideWorkspace.copyFailed": "Could not copy these files: {{list}}",+ "workingPanel.localFile.publish.outsideWorkspace.copyFailedEntry": "Could not copy the page file. Please try again.",+ "workingPanel.localFile.publish.outsideWorkspace.copyHint_one": "The page and its 1 local file will be copied to {{dir}} in this workspace and published from there.",+ "workingPanel.localFile.publish.outsideWorkspace.copyHint_other": "The page and its {{count}} local files will be copied to {{dir}} in this workspace and published from there.",+ "workingPanel.localFile.publish.outsideWorkspace.copying": "Copying files…",+ "workingPanel.localFile.publish.outsideWorkspace.description_one": "This page references 1 file outside the current workspace. That file would stop working after publish.",+ "workingPanel.localFile.publish.outsideWorkspace.description_other": "This page references {{count}} files outside the current workspace. Those files would stop working after publish.",+ "workingPanel.localFile.publish.outsideWorkspace.forceAction": "Publish anyway (include files outside the workspace)",+ "workingPanel.localFile.publish.outsideWorkspace.forceHint": "This publish will include content read from outside the workspace. Use only with files you trust.",+ "workingPanel.localFile.publish.outsideWorkspace.forceLabel": "Still read and pack these files outside the workspace",+ "workingPanel.localFile.publish.outsideWorkspace.source.nested": "Nested dependency",+ "workingPanel.localFile.publish.outsideWorkspace.source.workspace": "Workspace file",+ "workingPanel.localFile.publish.outsideWorkspace.stillBlocked": "The workspace copy still has missing or outside-workspace files, so it cannot be published yet.",+ "workingPanel.localFile.publish.outsideWorkspace.title": "Cannot publish this page directly",+ "workingPanel.localFile.publish.outsideWorkspace.workspace": "Current workspace: {{path}}","workingPanel.localFile.publish.oversized": "These files are too large to publish: {{list}}","workingPanel.localFile.publish.privacy": "Anyone with the link can open this page. Before publishing, make sure it does not contain anything you would rather keep private, such as credentials, API keys, personal information, uploaded files, or images.","workingPanel.localFile.publish.remotes": "These remote URLs stay as they are. After publish they still load from the original hosts.",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 45e84fb8ded..8fa5cede77d 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -2472,6 +2472,24 @@"workingPanel.localFile.publish.noLocalFiles": "此页面除 HTML 外没有本地文件。","workingPanel.localFile.publish.noTopic": "打开一个话题后再发布此页面","workingPanel.localFile.publish.note": "你可以随时取消发布。",+ "workingPanel.localFile.publish.outsideWorkspace.closureDescription": "发现了更多本地文件。请检查完整清单,然后再次点击拷贝以继续。",+ "workingPanel.localFile.publish.outsideWorkspace.copiedToast": "已从工作区副本 {{dir}} 发布",+ "workingPanel.localFile.publish.outsideWorkspace.copyAction": "拷贝到工作区并发布",+ "workingPanel.localFile.publish.outsideWorkspace.copyFailed": "无法拷贝这些文件:{{list}}",+ "workingPanel.localFile.publish.outsideWorkspace.copyFailedEntry": "页面文件拷贝失败,请重试。",+ "workingPanel.localFile.publish.outsideWorkspace.copyHint_one": "页面及其 {{count}} 个本地文件将被拷贝到工作区的 {{dir}} 目录,并从那里发布。",+ "workingPanel.localFile.publish.outsideWorkspace.copyHint_other": "页面及其 {{count}} 个本地文件将被拷贝到工作区的 {{dir}} 目录,并从那里发布。",+ "workingPanel.localFile.publish.outsideWorkspace.copying": "正在拷贝文件…",+ "workingPanel.localFile.publish.outsideWorkspace.description_one": "该页面引用了当前工作区之外的 {{count}} 个文件,直接发布后这些资源将失效。",+ "workingPanel.localFile.publish.outsideWorkspace.description_other": "该页面引用了当前工作区之外的 {{count}} 个文件,直接发布后这些资源将失效。",+ "workingPanel.localFile.publish.outsideWorkspace.forceAction": "仍然发布(包含工作区外文件)",+ "workingPanel.localFile.publish.outsideWorkspace.forceHint": "本次发布会包含从工作区外读取的文件内容,仅对你信任的文件使用。",+ "workingPanel.localFile.publish.outsideWorkspace.forceLabel": "仍然读取并打包这些文件",+ "workingPanel.localFile.publish.outsideWorkspace.source.nested": "嵌套依赖",+ "workingPanel.localFile.publish.outsideWorkspace.source.workspace": "工作区内资源",+ "workingPanel.localFile.publish.outsideWorkspace.stillBlocked": "工作区副本仍有缺失或位于工作区外的文件,暂时无法发布。",+ "workingPanel.localFile.publish.outsideWorkspace.title": "无法直接发布此页面",+ "workingPanel.localFile.publish.outsideWorkspace.workspace": "当前工作区:{{path}}","workingPanel.localFile.publish.oversized": "这些文件过大,无法发布:{{list}}","workingPanel.localFile.publish.privacy": "任何拥有链接的人都可以打开此页面。发布前请确认其中不含你希望保密的内容,例如凭证、API 密钥、个人信息、上传的文件或图片。","workingPanel.localFile.publish.remotes": "这些外部地址会保持原样,发布后仍从原站点加载。",diff --git a/packages/device-control/package.json b/packages/device-control/package.jsonindex cbb2dc6ce78..27247160b56 100644--- a/packages/device-control/package.json+++ b/packages/device-control/package.json@@ -5,6 +5,7 @@"sideEffects": false,"exports": {".": "./src/index.ts",+ "./file-preview": "./src/filePreview.ts","./project-file-index": "./src/projectFileIndex.ts","./skill-directory": "./src/skillDirectory.ts","./workspace": "./src/workspace.ts"@@ -17,6 +18,7 @@},"dependencies": {"@lobechat/heterogeneous-agents": "workspace:*",+ "@lobechat/html-artifact": "workspace:*","@lobechat/local-file-shell": "workspace:*","@lobechat/utils": "workspace:*","fast-glob": "^3.3.3",diff --git a/packages/device-control/src/__tests__/dispatch.test.ts b/packages/device-control/src/__tests__/dispatch.test.tsindex 0496ba6705f..13219804d34 100644--- a/packages/device-control/src/__tests__/dispatch.test.ts+++ b/packages/device-control/src/__tests__/dispatch.test.ts@@ -38,6 +38,11 @@ const makeDeps = (): DeviceControlDeps => ({root: '',source: 'glob' as const,})),+ readExternalAssetForPublish: vi.fn(async () => ({+ base64: 'AQID',+ contentType: 'image/png',+ success: true,+ })),searchProjectFiles: vi.fn(async () => ({entries: [],root: '',@@ -205,6 +210,9 @@ describe('executeDeviceRpc', () => {const previewParams = { path: path.join(root, 'AGENTS.md'), workingDirectory: root };await executeDeviceRpc('getLocalFilePreview', previewParams, deps);expect(deps.getLocalFilePreview).toHaveBeenCalledWith(previewParams);++ await executeDeviceRpc('readExternalAssetForPublish', previewParams, deps);+ expect(deps.readExternalAssetForPublish).toHaveBeenCalledWith(previewParams);});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.tsindex 2cd5479a0bd..62df5372e69 100644--- a/packages/device-control/src/__tests__/filePreview.test.ts+++ b/packages/device-control/src/__tests__/filePreview.test.ts@@ -1,10 +1,14 @@-import { mkdtemp, rm, writeFile } from 'node:fs/promises';+import { mkdtemp, 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 { defaultGetLocalFilePreview } from '../filePreview';+import {+ defaultGetLocalFilePreview,+ defaultReadExternalAssetForPublish,+ EXTERNAL_PUBLISH_ASSET_MAX_BYTES,+} from '../filePreview';const mockedHome = vi.hoisted(() => ({ dir: '' }));@@ -153,3 +157,31 @@ describe('defaultGetLocalFilePreview', () => {expect(result.success).toBe(false);});});++describe('defaultReadExternalAssetForPublish', () => {+ it('reads a file outside the workspace through the dedicated publish method', async () => {+ const result = await defaultReadExternalAssetForPublish({+ path: path.join(outside, 'secret.txt'),+ workingDirectory: root,+ });++ expect(result).toMatchObject({+ base64: Buffer.from('do not read\n').toString('base64'),+ contentType: 'text/plain; charset=utf-8',+ success: true,+ });+ });++ it('rejects a file over the publish limit without reading it', async () => {+ const huge = path.join(outside, 'huge.bin');+ await writeFile(huge, '');+ await truncate(huge, EXTERNAL_PUBLISH_ASSET_MAX_BYTES + 1);++ const result = await defaultReadExternalAssetForPublish({+ path: huge,+ workingDirectory: root,+ });++ expect(result).toEqual({ error: 'File is too large to publish', success: false });+ });+});diff --git a/packages/device-control/src/dispatch.ts b/packages/device-control/src/dispatch.tsindex 959205a3bf6..7c70cee6f3a 100644--- a/packages/device-control/src/dispatch.ts+++ b/packages/device-control/src/dispatch.ts@@ -21,11 +21,13 @@ import {} from '@lobechat/local-file-shell/git';import { getClaudeCodeQuota, type GetClaudeCodeQuotaParams } from './claudeCodeQuota';+import { defaultReadExternalAssetForPublish } from './filePreview';import { prepareSkillDirectory } from './skillDirectory';import type {BrowseDirectoryParams,DeviceControlDeps,EnrollWorkspaceParams,+ ExternalAssetForPublishParams,InitWorkspaceParams,ListHeterogeneousAgentModelsParams,ListProjectSkillsParams,@@ -56,6 +58,7 @@ export const DEVICE_RPC_METHODS = ['getProjectFileIndex','searchProjectFiles','getLocalFilePreview',+ 'readExternalAssetForPublish','moveLocalFiles','renameLocalFile','writeLocalFile',@@ -156,6 +159,12 @@ export const executeDeviceRpc = async (return deps.getLocalFilePreview(params as LocalFilePreviewUrlParams);}+ case 'readExternalAssetForPublish': {+ return (deps.readExternalAssetForPublish ?? defaultReadExternalAssetForPublish)(+ params as ExternalAssetForPublishParams,+ );+ }+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.tsindex ee9f4f85ab8..db6698fc403 100644--- a/packages/device-control/src/filePreview.ts+++ b/packages/device-control/src/filePreview.ts@@ -2,9 +2,19 @@ import { readFile, realpath, stat } from 'node:fs/promises';import { homedir } from 'node:os';import path from 'node:path';+import { WORKSPACE_HTML_ARTIFACT_MAX_FILE_BYTES } from '@lobechat/html-artifact/limits';import { getMimeType, resolveMimeType } from '@lobechat/utils/mimeType';-import type { LocalFilePreview, LocalFilePreviewResult, LocalFilePreviewUrlParams } from './types';+import type {+ ExternalAssetForPublishParams,+ ExternalAssetForPublishResult,+ LocalFilePreview,+ LocalFilePreviewResult,+ LocalFilePreviewUrlParams,+} from './types';++/** Device-side ceiling for a single publish asset, shared with the Electron main process. */+export const EXTERNAL_PUBLISH_ASSET_MAX_BYTES = WORKSPACE_HTML_ARTIFACT_MAX_FILE_BYTES;const TEXT_PREVIEW_MIME_TYPES = new Set(['application/graphql',@@ -149,3 +159,33 @@ export const defaultGetLocalFilePreview = async (return { error: (error as Error).message, success: false };}};++export const defaultReadExternalAssetForPublish = async ({+ path: filePath,+ workingDirectory,+}: ExternalAssetForPublishParams): Promise<ExternalAssetForPublishResult> => {+ try {+ if (!workingDirectory) return { error: 'Missing working directory', success: false };+ const expandedPath = expandHomePath(filePath);+ const resolvedPath = path.isAbsolute(expandedPath)+ ? expandedPath+ : path.resolve(expandHomePath(workingDirectory), expandedPath);+ const realFile = await realpath(resolvedPath);+ const stats = await stat(realFile);+ if (!stats.isFile()) return { error: 'Path is not a file', success: false };+ // Reject by size before reading: the renderer's limit check only runs after+ // the whole file has been read and base64-encoded into a gateway response.+ if (stats.size > EXTERNAL_PUBLISH_ASSET_MAX_BYTES) {+ return { error: 'File is too large to publish', success: false };+ }++ const buffer = await readFile(realFile);+ return {+ base64: buffer.toString('base64'),+ contentType: await resolveMimeType(realFile, buffer),+ 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.tsindex ddcaae52894..d7f2c04a29e 100644--- a/packages/device-control/src/index.ts+++ b/packages/device-control/src/index.ts@@ -1,5 +1,9 @@export { DEVICE_RPC_METHODS, type DeviceRpcMethod, executeDeviceRpc } from './dispatch';-export { defaultGetLocalFilePreview } from './filePreview';+export {+ defaultGetLocalFilePreview,+ defaultReadExternalAssetForPublish,+ EXTERNAL_PUBLISH_ASSET_MAX_BYTES,+} from './filePreview';export { defaultGetProjectFileIndex, defaultSearchProjectFiles } from './projectFileIndex';export { defaultSkillCacheRoot, prepareSkillDirectory } from './skillDirectory';export * from './types';diff --git a/packages/device-control/src/types.ts b/packages/device-control/src/types.tsindex 8b1bec28891..a3d475bf4f2 100644--- a/packages/device-control/src/types.ts+++ b/packages/device-control/src/types.ts@@ -97,6 +97,18 @@ export interface LocalFilePreviewUrlParams {workingDirectory: string;}+export interface ExternalAssetForPublishParams {+ path: string;+ workingDirectory: string;+}++export interface ExternalAssetForPublishResult {+ base64?: string;+ contentType?: string;+ error?: string;+ success: boolean;+}+export interface LocalFilePreviewText {content: string;contentType: string;@@ -246,6 +258,10 @@ export interface DeviceControlDeps extends SkillDirectoryDeps, WorkspaceScanDepslistHeterogeneousAgentModels?: (params: ListHeterogeneousAgentModelsParams,) => Promise<HeterogeneousAgentModelCatalog>;+ /** Read raw bytes after the user explicitly approved an external publish closure. */+ readExternalAssetForPublish?: (+ params: ExternalAssetForPublishParams,+ ) => Promise<ExternalAssetForPublishResult>;/** Search project files without shipping the whole index to the caller. */searchProjectFiles: (params: ProjectFileSearchParams) => Promise<ProjectFileSearchResult>;/**diff --git a/packages/html-artifact/package.json b/packages/html-artifact/package.jsonindex cdfc16c71c7..3a95fe52a33 100644--- a/packages/html-artifact/package.json+++ b/packages/html-artifact/package.json@@ -4,7 +4,8 @@"private": true,"sideEffects": false,"exports": {- ".": "./src/index.ts"+ ".": "./src/index.ts",+ "./limits": "./src/limits.ts"},"main": "./src/index.ts","types": "./src/index.ts",diff --git a/packages/html-artifact/src/collectHtmlLocalResources.test.ts b/packages/html-artifact/src/collectHtmlLocalResources.test.tsindex 0668f7adccf..164436c4d7f 100644--- a/packages/html-artifact/src/collectHtmlLocalResources.test.ts+++ b/packages/html-artifact/src/collectHtmlLocalResources.test.ts@@ -142,6 +142,27 @@ describe('collectLocalResourceRefs', () => {expect(result.refs).toEqual([{ absolutePath: '/project/shared/logo.png', href: 'logo.png' }]);});+ it('keeps a base that escapes the workspace so its refs report the real files', () => {+ const escaped = {+ content: `+ <base href="../../shared/">+ <img src="logo.png">+ `,+ sourceKind: 'html' as const,+ sourcePath: htmlFilePath,+ workingDirectory,+ };++ expect(collectLocalResourceRefs(escaped).skipped).toContainEqual({+ absolutePath: '/shared/logo.png',+ href: 'logo.png',+ reason: 'escape',+ });+ expect(collectLocalResourceRefs({ ...escaped, allowExternalReads: true }).refs).toEqual([+ { absolutePath: '/shared/logo.png', href: 'logo.png' },+ ]);+ });+it('collects css url and import refs from the stylesheet directory', () => {const result = collectLocalResourceRefs({content: `@@ -266,6 +287,12 @@ describe('path helpers', () => {'/project',),).toBe('/project');+ expect(+ lowestCommonAncestorDirectory(+ ['/project/pages/index.html', '/outside/assets/logo.png'],+ '/project',+ ),+ ).toBe('/');});it('builds a stable artifact identifier from the html relative path', () => {@@ -330,5 +357,4 @@ describe('path helpers', () => {expect(collectCssResourceHrefs(pathological)).toEqual(['late.png']);expect(Date.now() - started).toBeLessThan(1000);});-});diff --git a/packages/html-artifact/src/collectHtmlLocalResources.ts b/packages/html-artifact/src/collectHtmlLocalResources.tsindex e2f653a089c..95b77eb9907 100644--- a/packages/html-artifact/src/collectHtmlLocalResources.ts+++ b/packages/html-artifact/src/collectHtmlLocalResources.ts@@ -49,6 +49,7 @@ export interface CollectedLocalResourceRef {}export interface SkippedLocalResourceRef {+ absolutePath?: string;href: string;reason: LocalResourceSkipReason;}@@ -75,6 +76,7 @@ const pushRef = (result: CollectLocalResourceResult,seenRefs: Set<string>,resolved: ReturnType<typeof resolveLocalResourceHref>,+ allowExternalReads: boolean,) => {if (resolved.kind === 'empty') {result.skipped.push({ href: resolved.href, reason: 'empty' });@@ -86,8 +88,12 @@ const pushRef = (return;}- if (resolved.kind === 'escape' || !resolved.absolutePath) {- result.skipped.push({ href: resolved.href, reason: 'escape' });+ if ((resolved.kind === 'escape' && !allowExternalReads) || !resolved.absolutePath) {+ result.skipped.push({+ absolutePath: resolved.absolutePath,+ href: resolved.href,+ reason: 'escape',+ });return;}@@ -302,9 +308,10 @@ const resolveHtmlResourceBasePath = (});if (resolved.kind === 'remote') return { remote: true, sourcePath: htmlFilePath };- if (resolved.kind !== 'resolved' || !resolved.absolutePath) {- return { remote: false, sourcePath: htmlFilePath };- }+ // A base that points outside the workspace still decides where every relative+ // href resolves. Keep it: `pushRef` is what refuses to read escaped targets,+ // so honouring it here is what lets the page report its real dependencies.+ if (!resolved.absolutePath) return { remote: false, sourcePath: htmlFilePath };const extension = getFileExtension(resolved.absolutePath);const directory = extension ? parentDirectory(resolved.absolutePath) : resolved.absolutePath;@@ -331,12 +338,14 @@ const walkHtmlTags = (html: string, onTag: (tagName: string, tagText: string) =>};export const collectLocalResourceRefs = ({+ allowExternalReads = false,content,rootDirectory,sourceKind,sourcePath,workingDirectory,}: {+ allowExternalReads?: boolean;content: string;rootDirectory?: string;sourceKind: 'css' | 'html' | 'js';@@ -359,6 +368,7 @@ export const collectLocalResourceRefs = ({sourcePath,workingDirectory,}),+ allowExternalReads,);}return result;@@ -380,7 +390,7 @@ export const collectLocalResourceRefs = ({return;}- pushRef(result, seenRefs, resolved);+ pushRef(result, seenRefs, resolved, allowExternalReads);};walkHtmlTags(content, (tagName, tagText) => {diff --git a/packages/html-artifact/src/gatherWorkspaceHtmlArtifact.test.ts b/packages/html-artifact/src/gatherWorkspaceHtmlArtifact.test.tsindex 293c1d28761..0c7f3283359 100644--- a/packages/html-artifact/src/gatherWorkspaceHtmlArtifact.test.ts+++ b/packages/html-artifact/src/gatherWorkspaceHtmlArtifact.test.ts@@ -1,4 +1,4 @@-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import { gatherWorkspaceHtmlArtifact } from './gatherWorkspaceHtmlArtifact';import type { ReadWorkspaceAssetResult } from './limits';@@ -282,4 +282,94 @@ describe('gatherWorkspaceHtmlArtifact', () => {expect(result.unsupported).toEqual(['./site.webmanifest', '../fonts/brand.fontkit']);expect(result.missing).toEqual([]);});++ it('reports workspace escapes with every href spelling without reading them', async () => {+ const readAsset = vi.fn();+ const result = await gatherWorkspaceHtmlArtifact({+ htmlContent:+ '<html><img src="../../outside/logo.png"><img src="../../outside/logo.png?v=2"></html>',+ htmlFilePath: '/project/pages/index.html',+ readAsset,+ workingDirectory: '/project',+ });++ expect(result.escaped).toEqual([+ {+ absolutePath: '/outside/logo.png',+ hrefs: ['../../outside/logo.png', '../../outside/logo.png?v=2'],+ },+ ]);+ expect(result.missing).toEqual([]);+ expect(readAsset).not.toHaveBeenCalled();+ });++ it('reads and packs workspace escapes only when external reads are allowed', async () => {+ const readAsset = vi.fn(async () => ({+ bytes: new Uint8Array([1, 2, 3]),+ contentType: 'image/png',+ ok: true as const,+ }));+ const result = await gatherWorkspaceHtmlArtifact({+ allowExternalReads: true,+ htmlContent: '<html><img src="../../outside/logo.png"></html>',+ htmlFilePath: '/project/pages/index.html',+ readAsset,+ workingDirectory: '/project',+ });++ expect(result.escaped).toEqual([]);+ expect(readAsset).toHaveBeenCalledWith('/outside/logo.png');+ expect(result.resources).toEqual([+ expect.objectContaining({+ absolutePath: '/outside/logo.png',+ hrefs: ['../../outside/logo.png'],+ }),+ ]);+ expect(result.files.map((file) => file.path).sort()).toEqual([+ 'outside/logo.png',+ 'project/pages/index.html',+ ]);+ });++ it('returns the complete readable closure for copying', async () => {+ const files = new Map<string, ReadWorkspaceAssetResult>([+ ['/outside/app.css', textAsset('body { background: url("image.png") }', 'text/css')],+ ['/outside/image.png', { bytes: new Uint8Array([1]), contentType: 'image/png', ok: true }],+ ['/project/local.js', textAsset('console.log("ok")', 'text/javascript')],+ ]);++ const result = await gatherWorkspaceHtmlArtifact({+ allowExternalReads: true,+ htmlContent:+ '<html><link rel="stylesheet" href="../outside/app.css"><script src="local.js"></script></html>',+ htmlFilePath: '/project/index.html',+ readAsset: async (absolutePath) =>+ files.get(absolutePath) ?? { ok: false, reason: 'missing' },+ workingDirectory: '/project',+ });++ expect(result.resources).toEqual([+ expect.objectContaining({ absolutePath: '/outside/app.css', hrefs: ['../outside/app.css'] }),+ expect.objectContaining({ absolutePath: '/project/local.js', hrefs: ['local.js'] }),+ expect.objectContaining({ absolutePath: '/outside/image.png', hrefs: ['image.png'] }),+ ]);+ });++ it('counts unread external closure files toward the 64-file cap', async () => {+ const readAsset = vi.fn();+ const refs = Array.from(+ { length: 64 },+ (_, index) => `<img src="../../outside/a${index}.png">`,+ ).join('');++ const result = await gatherWorkspaceHtmlArtifact({+ htmlContent: `<html>${refs}</html>`,+ htmlFilePath: '/project/pages/index.html',+ readAsset,+ workingDirectory: '/project',+ });++ expect(result.blocked).toBe('too-many');+ expect(readAsset).not.toHaveBeenCalled();+ });});diff --git a/packages/html-artifact/src/gatherWorkspaceHtmlArtifact.ts b/packages/html-artifact/src/gatherWorkspaceHtmlArtifact.tsindex 7d0b0923901..93ea338e48a 100644--- a/packages/html-artifact/src/gatherWorkspaceHtmlArtifact.ts+++ b/packages/html-artifact/src/gatherWorkspaceHtmlArtifact.ts@@ -25,17 +25,29 @@ import {export interface GatheredWorkspaceHtmlArtifact {blocked?: 'too-large' | 'too-many';entryPath: string;+ escaped: EscapedResourceRef[];files: WorkspaceHtmlArtifactFile[];identifier: string;missing: string[];oversized: string[];remotes: string[];+ resources: GatheredWorkspaceHtmlResource[];title: string;totalBytes: number;unsupported: string[];}-const READ_CONCURRENCY = 5;+export interface EscapedResourceRef {+ absolutePath: string;+ hrefs: string[];+}++export interface GatheredWorkspaceHtmlResource extends EscapedResourceRef {+ contentType?: string;+ text?: string;+}++export const READ_CONCURRENCY = 5;const isWalkableAssetPath = (absolutePath: string): boolean =>isCssAssetPath(absolutePath) || isJsAssetPath(absolutePath);@@ -64,11 +76,13 @@ const toArtifactFile = (};export const gatherWorkspaceHtmlArtifact = async ({+ allowExternalReads = false,htmlContent,htmlFilePath,readAsset,workingDirectory,}: {+ allowExternalReads?: boolean;htmlContent: string;htmlFilePath: string;readAsset: (absolutePath: string) => Promise<ReadWorkspaceAssetResult>;@@ -76,31 +90,69 @@ export const gatherWorkspaceHtmlArtifact = async ({}): Promise<GatheredWorkspaceHtmlArtifact> => {const absoluteHtmlPath = toWorkspaceAbsolutePath(htmlFilePath, workingDirectory);const htmlRefs = collectLocalResourceRefs({+ allowExternalReads,content: htmlContent,sourceKind: 'html',sourcePath: absoluteHtmlPath,workingDirectory,});- const pending = [...htmlRefs.refs];- const seen = new Set(pending.map((ref) => ref.absolutePath));+ const pending: string[] = [];+ const resources = new Map<string, GatheredWorkspaceHtmlResource>();const handled = new Set<string>();- const walkQueue = pending.filter((ref) => isWalkableAssetPath(ref.absolutePath));+ const walkQueue: string[] = [];const missing: string[] = [];+ const escaped: EscapedResourceRef[] = [];const oversized: string[] = [];const remotes: string[] = [];const unsupported: string[] = [];const htmlDirectory = parentDirectory(absoluteHtmlPath);+ const escapedByPath = new Map<string, EscapedResourceRef>();+ const htmlBytes = new TextEncoder().encode(htmlContent);+ let totalBytes = htmlBytes.byteLength;+ let blocked: GatheredWorkspaceHtmlArtifact['blocked'] =+ totalBytes > WORKSPACE_HTML_ARTIFACT_MAX_TOTAL_BYTES ? 'too-large' : undefined;++ const addResource = ({ absolutePath, href }: CollectedLocalResourceRef) => {+ const existing = resources.get(absolutePath);+ if (existing) {+ if (!existing.hrefs.includes(href)) existing.hrefs.push(href);+ return false;+ }++ resources.set(absolutePath, { absolutePath, hrefs: [href] });+ if (resources.size + 1 > WORKSPACE_HTML_ARTIFACT_MAX_FILES) blocked = 'too-many';+ return true;+ };++ const addPending = (ref: CollectedLocalResourceRef) => {+ if (!addResource(ref)) return;+ pending.push(ref.absolutePath);+ if (isWalkableAssetPath(ref.absolutePath)) walkQueue.push(ref.absolutePath);+ };++ for (const ref of htmlRefs.refs) addPending(ref);+const bucketForSkipReason = (reason: LocalResourceSkipReason): string[] | undefined => {if (reason === 'remote') return remotes;- if (reason === 'escape') return missing;if (reason === 'extension') return unsupported;return;};const collectSkipped = (skipped: typeof htmlRefs.skipped) => {for (const item of skipped) {+ if (item.reason === 'escape' && item.absolutePath) {+ addResource({ absolutePath: item.absolutePath, href: item.href });+ const existing = escapedByPath.get(item.absolutePath);+ if (existing) {+ if (!existing.hrefs.includes(item.href)) existing.hrefs.push(item.href);+ } else {+ const escapedRef = { absolutePath: item.absolutePath, hrefs: [item.href] };+ escapedByPath.set(item.absolutePath, escapedRef);+ escaped.push(escapedRef);+ }+ }const bucket = bucketForSkipReason(item.reason);if (!bucket || bucket.includes(item.href)) continue;bucket.push(item.href);@@ -115,41 +167,41 @@ export const gatherWorkspaceHtmlArtifact = async ({text?: string;}> = [];- const htmlBytes = new TextEncoder().encode(htmlContent);- let totalBytes = htmlBytes.byteLength;- let blocked: GatheredWorkspaceHtmlArtifact['blocked'] =- totalBytes > WORKSPACE_HTML_ARTIFACT_MAX_TOTAL_BYTES ? 'too-large' : undefined;-const registerAsset = (asset: (typeof resolvedAssets)[number]) => {resolvedAssets.push(asset);+ const resource = resources.get(asset.absolutePath);+ if (resource) {+ resource.contentType = asset.contentType;+ resource.text = asset.text;+ }totalBytes += asset.bytes.byteLength;- if (resolvedAssets.length + 1 > WORKSPACE_HTML_ARTIFACT_MAX_FILES) blocked = 'too-many';- else if (totalBytes > WORKSPACE_HTML_ARTIFACT_MAX_TOTAL_BYTES) blocked = 'too-large';+ if (totalBytes > WORKSPACE_HTML_ARTIFACT_MAX_TOTAL_BYTES) blocked = 'too-large';};const registerReadFailure = (asset: Extract<ReadWorkspaceAssetResult, { ok: false }>,- href: string,+ hrefs: string[],) => {if (asset.reason !== 'oversized') {- missing.push(href);+ for (const href of hrefs) if (!missing.includes(href)) missing.push(href);return;}- oversized.push(href);+ for (const href of hrefs) if (!oversized.includes(href)) oversized.push(href);totalBytes += asset.sizeBytes ?? WORKSPACE_HTML_ARTIFACT_MAX_TOTAL_BYTES + 1;blocked = 'too-large';};- const readLeafAsset = async (ref: CollectedLocalResourceRef) => {- const asset = await readAsset(ref.absolutePath);+ const readLeafAsset = async (absolutePath: string) => {+ const resource = resources.get(absolutePath)!;+ const asset = await readAsset(absolutePath);if (!asset.ok) {- registerReadFailure(asset, ref.href);+ registerReadFailure(asset, resource.hrefs);return;}registerAsset({- absolutePath: ref.absolutePath,+ absolutePath,bytes: asset.bytes,contentType: asset.contentType,text: asset.text,@@ -157,25 +209,24 @@ export const gatherWorkspaceHtmlArtifact = async ({};while (!blocked && walkQueue.length > 0) {- const walkRef = walkQueue.shift();- if (!walkRef) break;- if (handled.has(walkRef.absolutePath)) continue;- handled.add(walkRef.absolutePath);+ const absolutePath = walkQueue.shift();+ if (!absolutePath) break;+ if (handled.has(absolutePath)) continue;+ handled.add(absolutePath);+ const resource = resources.get(absolutePath)!;- const asset = await readAsset(walkRef.absolutePath);+ const asset = await readAsset(absolutePath);if (!asset.ok) {- registerReadFailure(asset, walkRef.href);+ registerReadFailure(asset, resource.hrefs);continue;}const text =asset.text ??- (isWalkableAssetPath(walkRef.absolutePath)- ? new TextDecoder().decode(asset.bytes)- : undefined);+ (isWalkableAssetPath(absolutePath) ? new TextDecoder().decode(asset.bytes) : undefined);registerAsset({- absolutePath: walkRef.absolutePath,+ absolutePath,bytes: asset.bytes,contentType: asset.contentType,text,@@ -184,27 +235,23 @@ export const gatherWorkspaceHtmlArtifact = async ({if (!text) continue;const nested = collectLocalResourceRefs({+ allowExternalReads,content: text,- rootDirectory: isJsAssetPath(walkRef.absolutePath) ? htmlDirectory : undefined,- sourceKind: isJsAssetPath(walkRef.absolutePath) ? 'js' : 'css',- sourcePath: walkRef.absolutePath,+ rootDirectory: isJsAssetPath(absolutePath) ? htmlDirectory : undefined,+ sourceKind: isJsAssetPath(absolutePath) ? 'js' : 'css',+ sourcePath: absolutePath,workingDirectory,});collectSkipped(nested.skipped);- for (const ref of nested.refs) {- if (seen.has(ref.absolutePath)) continue;- seen.add(ref.absolutePath);- pending.push(ref);- if (isWalkableAssetPath(ref.absolutePath)) walkQueue.push(ref);- }+ for (const ref of nested.refs) addPending(ref);}// Leaf assets are independent reads; batch them so remote transports// (sandbox runCommand round trips) don't serialize into seconds.- const leaves = pending.filter((ref) => {- if (handled.has(ref.absolutePath)) return false;- handled.add(ref.absolutePath);+ const leaves = pending.filter((absolutePath) => {+ if (handled.has(absolutePath)) return false;+ handled.add(absolutePath);return true;});@@ -236,11 +283,13 @@ export const gatherWorkspaceHtmlArtifact = async ({return {blocked,entryPath,+ escaped,files,identifier: workspaceHtmlArtifactIdentifierForFile(htmlFilePath, workingDirectory),missing,oversized,remotes,+ resources: [...resources.values()],title: extractHtmlTitle(htmlContent) || filename,totalBytes,unsupported,diff --git a/packages/html-artifact/src/htmlTagScanner.ts b/packages/html-artifact/src/htmlTagScanner.tsindex 1e5d4f785b8..fa1ba7e96b0 100644--- a/packages/html-artifact/src/htmlTagScanner.ts+++ b/packages/html-artifact/src/htmlTagScanner.ts@@ -101,3 +101,22 @@ export const extractHtmlTitle = (html: string): string | undefined => {const title = match?.[1]?.replaceAll(/\s+/g, ' ').trim();return title || undefined;};++const isRemoteHref = (href: string): boolean =>+ /^[a-z][a-z\d+.-]*:/i.test(href) || href.startsWith('//');++/**+ * Drop a workspace-local `<base href>` from a relocated copy. Every resource+ * href in the copy is rewritten relative to the copy's own directory, so a+ * surviving base would send resolution back to the original layout. A remote+ * base is left alone: it governs refs this pipeline never copies.+ */+export const removeLocalBaseTag = (html: string): string => {+ const baseTag = findOpeningTag(html, 'base');+ if (!baseTag) return html;++ const href = findAttribute(baseTag.text, 'href')?.value;+ if (!href || isRemoteHref(href)) return html;++ return html.slice(0, baseTag.start) + html.slice(baseTag.end);+};diff --git a/packages/html-artifact/src/packWorkspaceHtmlDocument.ts b/packages/html-artifact/src/packWorkspaceHtmlDocument.tsindex 5e053169a20..109bd7e4b0b 100644--- a/packages/html-artifact/src/packWorkspaceHtmlDocument.ts+++ b/packages/html-artifact/src/packWorkspaceHtmlDocument.ts@@ -62,7 +62,7 @@ const isCssFile = (file: WorkspaceHtmlArtifactFile) =>const isJsFile = (file: WorkspaceHtmlArtifactFile) =>file.contentType.includes('javascript') || isJsAssetPath(file.path);-const replaceHrefToken = (source: string, href: string, replacement: string): string => {+export const replaceHrefToken = (source: string, href: string, replacement: string): string => {const escaped = escapeRegExp(href);return sourcediff --git a/packages/html-artifact/src/workspaceHtmlPath.ts b/packages/html-artifact/src/workspaceHtmlPath.tsindex 1196a18c584..5d6224a36af 100644--- a/packages/html-artifact/src/workspaceHtmlPath.ts+++ b/packages/html-artifact/src/workspaceHtmlPath.ts@@ -114,13 +114,12 @@ export const lowestCommonAncestorDirectory = (): string => {if (absolutePaths.length === 0) return workingDirectory;- const relativeDirs = absolutePaths.map((absolutePath) => {- const relativePath = toWorkspaceRelativePath(absolutePath, workingDirectory);- const segments = relativePath.split('/').filter(Boolean);- return segments.slice(0, -1);+ const directorySegments = absolutePaths.map((absolutePath) => {+ const canonical = canonicalizeWorkspacePath(absolutePath);+ return canonical.slice(0, canonical.lastIndexOf('/')).split('/');});- const [first, ...rest] = relativeDirs;+ const [first, ...rest] = directorySegments;const common: string[] = [];for (const [index, segment] of first.entries()) {@@ -131,9 +130,7 @@ export const lowestCommonAncestorDirectory = (break;}- if (common.length === 0) return workingDirectory;-- const slashRoot = `${stripTrailingSlash(toSlashPath(workingDirectory))}/${common.join('/')}`;+ const slashRoot = common.join('/') || '/';return fromSlashPath(slashRoot, workingDirectory);};@@ -185,14 +182,17 @@ export const resolveLocalResourceHref = ({return { absolutePath: resolvedPath, href, kind: 'resolved' };};-export const createWorkspaceHtmlArtifactIdentifier = (relativePath: string): string => {+export const createWorkspaceHtmlArtifactIdentifier = (+ relativePath: string,+ digestPath = relativePath,+): string => {const normalized = relativePath.replaceAll('\\', '/').replace(/^\/+/u, '');const slug = normalized.replaceAll(/[^a-z0-9]+/gi, '-').replaceAll(/^-+|-+$/g, '').toLowerCase().slice(0, 48);- const digest = sha256(normalized).slice(0, 10);+ const digest = sha256(digestPath.replaceAll('\\', '/')).slice(0, 10);return `workspace-html-${slug || 'page'}-${digest}`;};@@ -201,13 +201,16 @@ export const workspaceHtmlArtifactIdentifierForFile = (filePath: string,workingDirectory: string,): string => {+ const absolutePath = toWorkspaceAbsolutePath(filePath, workingDirectory);const relativePath =- toWorkspaceRelativePath(- toWorkspaceAbsolutePath(filePath, workingDirectory),- workingDirectory,- ) ||+ toWorkspaceRelativePath(absolutePath, workingDirectory) ||(stripTrailingSlash(toSlashPath(filePath)).split('/').at(-1) ?? filePath);- return createWorkspaceHtmlArtifactIdentifier(relativePath);+ return createWorkspaceHtmlArtifactIdentifier(+ relativePath,+ isPathInsideWorkspace(absolutePath, workingDirectory)+ ? relativePath+ : canonicalizeWorkspacePath(absolutePath),+ );};export { parentDirectory };diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 270215c5b2d..3802eec4ced 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -2765,6 +2765,36 @@ export default {'workingPanel.localFile.publish.noTopic': 'Open a topic to publish this page','workingPanel.localFile.publish.note': 'You can unpublish it at any time.','workingPanel.localFile.publish.oversized': 'These files are too large to publish: {{list}}',+ 'workingPanel.localFile.publish.outsideWorkspace.copiedToast':+ 'Published from the workspace copy at {{dir}}',+ 'workingPanel.localFile.publish.outsideWorkspace.closureDescription':+ 'More local files were found. Review the complete list, then click copy again to continue.',+ 'workingPanel.localFile.publish.outsideWorkspace.copyAction': 'Copy to workspace and publish',+ 'workingPanel.localFile.publish.outsideWorkspace.copyFailed':+ 'Could not copy these files: {{list}}',+ 'workingPanel.localFile.publish.outsideWorkspace.copyFailedEntry':+ 'Could not copy the page file. Please try again.',+ 'workingPanel.localFile.publish.outsideWorkspace.copyHint_one':+ 'The page and its 1 local file will be copied to {{dir}} in this workspace and published from there.',+ 'workingPanel.localFile.publish.outsideWorkspace.copyHint_other':+ 'The page and its {{count}} local files will be copied to {{dir}} in this workspace and published from there.',+ 'workingPanel.localFile.publish.outsideWorkspace.copying': 'Copying files…',+ 'workingPanel.localFile.publish.outsideWorkspace.description_one':+ 'This page references 1 file outside the current workspace. That file would stop working after publish.',+ 'workingPanel.localFile.publish.outsideWorkspace.description_other':+ 'This page references {{count}} files outside the current workspace. Those files would stop working after publish.',+ 'workingPanel.localFile.publish.outsideWorkspace.forceAction':+ 'Publish anyway (include files outside the workspace)',+ 'workingPanel.localFile.publish.outsideWorkspace.forceHint':+ 'This publish will include content read from outside the workspace. Use only with files you trust.',+ 'workingPanel.localFile.publish.outsideWorkspace.forceLabel':+ 'Still read and pack these files outside the workspace',+ 'workingPanel.localFile.publish.outsideWorkspace.stillBlocked':+ 'The workspace copy still has missing or outside-workspace files, so it cannot be published yet.',+ 'workingPanel.localFile.publish.outsideWorkspace.source.nested': 'Nested dependency',+ 'workingPanel.localFile.publish.outsideWorkspace.source.workspace': 'Workspace file',+ 'workingPanel.localFile.publish.outsideWorkspace.title': 'Cannot publish this page directly',+ 'workingPanel.localFile.publish.outsideWorkspace.workspace': 'Current workspace: {{path}}','workingPanel.localFile.publish.remotes':'These remote URLs stay as they are. After publish they still load from the original hosts.','workingPanel.localFile.publish.scanning': 'Preparing this page…',diff --git a/packages/types/src/device.ts b/packages/types/src/device.tsindex c1b661e643c..c7afb2c8bbb 100644--- a/packages/types/src/device.ts+++ b/packages/types/src/device.ts@@ -711,6 +711,13 @@ export interface DeviceLocalFilePreviewResult {success: boolean;}+export interface DeviceExternalAssetForPublishResult {+ base64?: string;+ contentType?: string;+ error?: string;+ success: boolean;+}+/** One file/folder to move within a directory on a remote device. Mirrors `MoveLocalFileParams`. */export interface DeviceMoveProjectFileItem {newPath: string;diff --git a/src/features/Portal/LocalFile/PublishHtmlArtifactBlockedConfirm.tsx b/src/features/Portal/LocalFile/PublishHtmlArtifactBlockedConfirm.tsxnew file mode 100644index 00000000000..3bebe9ed847--- /dev/null+++ b/src/features/Portal/LocalFile/PublishHtmlArtifactBlockedConfirm.tsx@@ -0,0 +1,166 @@+import { workspaceHtmlArtifactIdentifierForFile } from '@lobechat/html-artifact';+import { Flexbox } from '@lobehub/ui';+import {+ Accordion,+ Button,+ Checkbox,+ createModal,+ ScrollArea,+ Text,+ useModalContext,+} from '@lobehub/ui/base-ui';+import { cssVar } from 'antd-style';+import { t } from 'i18next';+import { useTranslation } from 'react-i18next';++import {+ type BlockedWorkspaceHtmlPublishInput,+ useBlockedWorkspaceHtmlPublish,+} from './useBlockedWorkspaceHtmlPublish';++const BODY_MAX_HEIGHT = 'min(52vh, 360px)';++export type OpenWorkspaceHtmlPublishBlockedConfirmInput = Omit<+ BlockedWorkspaceHtmlPublishInput,+ 'close'+>;++const BlockedConfirmContent = (input: OpenWorkspaceHtmlPublishBlockedConfirmInput) => {+ const { t } = useTranslation(['chat', 'common']);+ const { close } = useModalContext();+ const { busy, cancel, failed, force, handleContinue, handleForceChange, resources } =+ useBlockedWorkspaceHtmlPublish({+ ...input,+ close,+ });+ const { filePath, plan, workingDirectory } = input;+ const identifier = workspaceHtmlArtifactIdentifierForFile(filePath, workingDirectory);+ const relativeTargetDirectory = `.lobe-artifacts/${identifier}`;+ const failedPaths = new Set(failed.map((item) => item.absolutePath));+ return (+ <>+ <ScrollArea+ disableContentFit+ scrollFade+ style={{ maxHeight: BODY_MAX_HEIGHT, overflow: 'hidden' }}+ viewportProps={{ style: { height: 'auto', maxHeight: BODY_MAX_HEIGHT } }}+ >+ <Flexbox gap={12} style={{ paddingBlock: 12, paddingInline: 16 }}>+ <Text>+ {t('workingPanel.localFile.publish.outsideWorkspace.description', {+ count: plan.escaped.length,+ ns: 'chat',+ })}+ </Text>+ <Text type={'secondary'}>+ {t('workingPanel.localFile.publish.outsideWorkspace.workspace', {+ ns: 'chat',+ path: workingDirectory,+ })}+ </Text>+ {resources.some((item) => item.source) && (+ <Text type={'secondary'}>+ {t('workingPanel.localFile.publish.outsideWorkspace.closureDescription', {+ ns: 'chat',+ })}+ </Text>+ )}+ <Accordion+ indicatorPlacement={'start'}+ variant={'borderless'}+ items={[+ {+ children: (+ <Flexbox gap={8} paddingBlock={'4px 0'}>+ {resources.map((item) => (+ <Flexbox gap={2} key={item.absolutePath}>+ <Text>{item.hrefs.join(', ')}</Text>+ {item.source && (+ <Text fontSize={12} type={'secondary'}>+ {t(+ `workingPanel.localFile.publish.outsideWorkspace.source.${item.source}`,+ { ns: 'chat' },+ )}+ </Text>+ )}+ <Text+ type={'secondary'}+ style={{+ color: failedPaths.has(item.absolutePath)+ ? cssVar.colorError+ : undefined,+ fontFamily: cssVar.fontFamilyCode,+ wordBreak: 'break-all',+ }}+ >+ {item.absolutePath}+ </Text>+ </Flexbox>+ ))}+ </Flexbox>+ ),+ key: 'paths',+ title: (+ <Text fontSize={12} type={'secondary'} weight={500}>+ {t('workingPanel.localFile.publish.details', { ns: 'chat' })}+ </Text>+ ),+ },+ ]}+ />+ <Text type={'secondary'}>+ {t('workingPanel.localFile.publish.outsideWorkspace.copyHint', {+ count: resources.length,+ dir: relativeTargetDirectory,+ ns: 'chat',+ })}+ </Text>+ {failed.length > 0 && (+ <Text style={{ color: cssVar.colorError }}>+ {t('workingPanel.localFile.publish.outsideWorkspace.copyFailed', {+ list: failed.map((item) => item.absolutePath).join(', '),+ ns: 'chat',+ })}+ </Text>+ )}+ </Flexbox>+ </ScrollArea>+ <Flexbox style={{ paddingBlock: '8px 4px', paddingInline: 16 }}>+ <Checkbox checked={force} onChange={handleForceChange}>+ <Text fontSize={12}>+ {t('workingPanel.localFile.publish.outsideWorkspace.forceLabel', { ns: 'chat' })}+ </Text>+ </Checkbox>+ </Flexbox>+ <Flexbox+ horizontal+ gap={8}+ justify={'flex-end'}+ style={{ paddingBlock: 12, paddingInline: 16 }}+ >+ <Button onClick={cancel}>{t('cancel', { ns: 'common' })}</Button>+ <Button loading={busy} type={'primary'} onClick={() => void handleContinue()}>+ {busy && !force+ ? t('workingPanel.localFile.publish.outsideWorkspace.copying', { ns: 'chat' })+ : t(+ force+ ? 'workingPanel.localFile.publish.outsideWorkspace.forceAction'+ : 'workingPanel.localFile.publish.outsideWorkspace.copyAction',+ { ns: 'chat' },+ )}+ </Button>+ </Flexbox>+ </>+ );+};++export const openWorkspaceHtmlPublishBlockedConfirm = (+ input: OpenWorkspaceHtmlPublishBlockedConfirmInput,+) =>+ createModal({+ content: <BlockedConfirmContent {...input} />,+ footer: null,+ styles: { content: { minHeight: 0, overflow: 'hidden', padding: 0 } },+ title: t('workingPanel.localFile.publish.outsideWorkspace.title', { ns: 'chat' }),+ width: 420,+ });diff --git a/src/features/Portal/LocalFile/copyWorkspaceHtmlArtifactIntoWorkspace.test.ts b/src/features/Portal/LocalFile/copyWorkspaceHtmlArtifactIntoWorkspace.test.tsnew file mode 100644index 00000000000..ba036907b81--- /dev/null+++ b/src/features/Portal/LocalFile/copyWorkspaceHtmlArtifactIntoWorkspace.test.ts@@ -0,0 +1,213 @@+import { sha256 } from 'js-sha256';+import { describe, expect, it, vi } from 'vitest';++import { copyWorkspaceHtmlArtifactIntoWorkspace } from './copyWorkspaceHtmlArtifactIntoWorkspace';++const resource = (absolutePath: string, hrefs: string[], text?: string) => ({+ absolutePath,+ contentType: text === undefined ? 'image/png' : 'text/css',+ hrefs,+ text,+});++describe('copyWorkspaceHtmlArtifactIntoWorkspace', () => {+ it('copies the complete closure and persists the final HTML entry', async () => {+ const copyFile = vi.fn().mockResolvedValue(undefined);+ const writeFile = vi.fn().mockResolvedValue(undefined);+ const htmlContent = '<html><img src="logo.png"></html>';++ const result = await copyWorkspaceHtmlArtifactIntoWorkspace({+ copyFile,+ htmlContent,+ htmlFilePath: '/tmp/site/index.html',+ resources: [resource('/tmp/site/logo.png', ['logo.png'])],+ workingDirectory: '/project',+ writeFile,+ });++ expect(result.entryPath).toBe(`${result.targetDirectory}/index.html`);+ expect(result.htmlContent).toBe(htmlContent);+ expect(result.failed).toEqual([]);+ expect(copyFile.mock.calls).toEqual([+ ['/tmp/site/index.html', result.entryPath],+ ['/tmp/site/logo.png', `${result.targetDirectory}/logo.png`],+ ]);+ expect(writeFile).toHaveBeenCalledWith(result.entryPath, htmlContent);+ });++ it('drops a local base tag so the copy resolves against its own directory', async () => {+ const copyFile = vi.fn().mockResolvedValue(undefined);+ const writeFile = vi.fn().mockResolvedValue(undefined);+ const source = '/tmp/shared/logo.png';++ const result = await copyWorkspaceHtmlArtifactIntoWorkspace({+ copyFile,+ htmlContent: '<html><head><base href="../shared/"></head><img src="logo.png"></html>',+ htmlFilePath: '/tmp/site/index.html',+ resources: [resource(source, ['logo.png'])],+ workingDirectory: '/project',+ writeFile,+ });++ expect(result.htmlContent).not.toContain('<base');+ expect(result.htmlContent).toContain(+ `src="__external__/${sha256(source).slice(0, 8)}/logo.png"`,+ );+ });++ it('keeps a remote base tag, which governs refs the copy never relocates', async () => {+ const copyFile = vi.fn().mockResolvedValue(undefined);+ const writeFile = vi.fn().mockResolvedValue(undefined);++ const result = await copyWorkspaceHtmlArtifactIntoWorkspace({+ copyFile,+ htmlContent: '<html><head><base href="https://cdn.example.com/app/"></head></html>',+ htmlFilePath: '/tmp/site/index.html',+ resources: [],+ workingDirectory: '/project',+ writeFile,+ });++ expect(result.htmlContent).toContain('<base href="https://cdn.example.com/app/">');+ });++ it('copies one file and rewrites every spelling of its external href', async () => {+ const copyFile = vi.fn().mockResolvedValue(undefined);+ const writeFile = vi.fn().mockResolvedValue(undefined);+ const source = '/tmp/shared/logo.png';+ const result = await copyWorkspaceHtmlArtifactIntoWorkspace({+ copyFile,+ htmlContent: '<html><img src="../shared/logo.png"><img src="../shared/logo.png?v=2"></html>',+ htmlFilePath: '/tmp/site/index.html',+ resources: [resource(source, ['../shared/logo.png', '../shared/logo.png?v=2'])],+ workingDirectory: '/project',+ writeFile,+ });+ const relativeTarget = `__external__/${sha256(source).slice(0, 8)}/logo.png`;++ expect(copyFile).toHaveBeenCalledTimes(2);+ expect(copyFile).toHaveBeenLastCalledWith(+ source,+ `${result.targetDirectory}/${relativeTarget}`,+ );+ expect(result.htmlContent).toBe(+ `<html><img src="${relativeTarget}"><img src="${relativeTarget}?v=2"></html>`,+ );+ expect(writeFile).toHaveBeenLastCalledWith(result.entryPath, result.htmlContent);+ });++ it('rewrites nested references inside copied external CSS', async () => {+ const copyFile = vi.fn().mockResolvedValue(undefined);+ const writeFile = vi.fn().mockResolvedValue(undefined);+ const cssPath = '/tmp/shared/app.css';+ const imagePath = '/tmp/shared/image.png';++ const result = await copyWorkspaceHtmlArtifactIntoWorkspace({+ copyFile,+ htmlContent: '<html><link rel="stylesheet" href="../shared/app.css"></html>',+ htmlFilePath: '/tmp/site/index.html',+ resources: [+ resource(cssPath, ['../shared/app.css'], 'body { background: url("image.png") }'),+ resource(imagePath, ['image.png']),+ ],+ workingDirectory: '/project',+ writeFile,+ });+ const cssTarget = `__external__/${sha256(cssPath).slice(0, 8)}/app.css`;+ const imageTarget = `__external__/${sha256(imagePath).slice(0, 8)}/image.png`;+ const cssToImage = `../${sha256(imagePath).slice(0, 8)}/image.png`;++ expect(result.htmlContent).toContain(cssTarget);+ expect(copyFile).toHaveBeenCalledWith(imagePath, `${result.targetDirectory}/${imageTarget}`);+ expect(writeFile).toHaveBeenCalledWith(+ `${result.targetDirectory}/${cssTarget}`,+ `body { background: url("${cssToImage}") }`,+ );+ });++ it('copies workspace-local and external resources from the same closure', async () => {+ const copyFile = vi.fn().mockResolvedValue(undefined);+ const writeFile = vi.fn().mockResolvedValue(undefined);++ const result = await copyWorkspaceHtmlArtifactIntoWorkspace({+ copyFile,+ htmlContent:+ '<html><link rel="stylesheet" href="/assets/app.css"><script src="../outside/app.js"></script></html>',+ htmlFilePath: '/tmp/site/index.html',+ resources: [+ resource('/project/assets/app.css', ['/assets/app.css'], 'body{}'),+ {+ ...resource('/tmp/outside/app.js', ['../outside/app.js'], 'console.log(1)'),+ contentType: 'text/javascript',+ },+ ],+ workingDirectory: '/project',+ writeFile,+ });++ expect(copyFile).toHaveBeenCalledTimes(3);+ expect(result.htmlContent).not.toContain('/assets/app.css');+ expect(result.htmlContent).not.toContain('../outside/app.js');+ });++ it('keeps external entry identifiers distinct and canonical', async () => {+ const input = {+ copyFile: vi.fn().mockResolvedValue(undefined),+ htmlContent: '<html></html>',+ resources: [],+ workingDirectory: '/project',+ writeFile: vi.fn().mockResolvedValue(undefined),+ };++ const siteA = await copyWorkspaceHtmlArtifactIntoWorkspace({+ ...input,+ htmlFilePath: '/tmp/site-a/index.html',+ });+ const siteARepeat = await copyWorkspaceHtmlArtifactIntoWorkspace({+ ...input,+ htmlFilePath: '/tmp/site-a/index.html',+ });+ const privateSiteA = await copyWorkspaceHtmlArtifactIntoWorkspace({+ ...input,+ htmlFilePath: '/private/tmp/site-a/index.html',+ });+ const siteB = await copyWorkspaceHtmlArtifactIntoWorkspace({+ ...input,+ htmlFilePath: '/tmp/site-b/index.html',+ });++ expect(siteA.targetDirectory).toBe(siteARepeat.targetDirectory);+ expect(siteA.targetDirectory).toBe(privateSiteA.targetDirectory);+ expect(siteA.targetDirectory).not.toBe(siteB.targetDirectory);+ });++ it('returns copy failures and bounds resource concurrency at five', async () => {+ let active = 0;+ let maxActive = 0;+ const copyFile = vi.fn(async (from: string) => {+ if (from.endsWith('index.html')) return;+ active += 1;+ maxActive = Math.max(maxActive, active);+ await Promise.resolve();+ active -= 1;+ if (from.endsWith('gone.png')) throw new Error('gone');+ });+ const writeFile = vi.fn().mockResolvedValue(undefined);+ const resources = Array.from({ length: 7 }, (_, index) =>+ resource(`/tmp/site/${index === 6 ? 'gone' : index}.png`, [`${index}.png`]),+ );++ const result = await copyWorkspaceHtmlArtifactIntoWorkspace({+ copyFile,+ htmlContent: '<html></html>',+ htmlFilePath: '/tmp/site/index.html',+ resources,+ workingDirectory: '/project',+ writeFile,+ });++ expect(maxActive).toBe(5);+ expect(result.failed).toEqual([resources[6]]);+ expect(copyFile).toHaveBeenCalledTimes(8);+ });+});diff --git a/src/features/Portal/LocalFile/copyWorkspaceHtmlArtifactIntoWorkspace.ts b/src/features/Portal/LocalFile/copyWorkspaceHtmlArtifactIntoWorkspace.tsnew file mode 100644index 00000000000..7130f9ddcab--- /dev/null+++ b/src/features/Portal/LocalFile/copyWorkspaceHtmlArtifactIntoWorkspace.ts@@ -0,0 +1,140 @@+import {+ collectLocalResourceRefs,+ type GatheredWorkspaceHtmlResource,+ isCssAssetPath,+ isJsAssetPath,+ READ_CONCURRENCY,+ removeLocalBaseTag,+ replaceHrefToken,+ workspaceHtmlArtifactIdentifierForFile,+} from '@lobechat/html-artifact';+import { sha256 } from 'js-sha256';+import path from 'path-browserify-esm';++export interface CopyWorkspaceHtmlArtifactResult {+ entryPath: string;+ failed: GatheredWorkspaceHtmlResource[];+ htmlContent: string;+ targetDirectory: string;+}++const hrefSuffix = (href: string): string => href.match(/[?#].*$/u)?.[0] ?? '';++export const copyWorkspaceHtmlArtifactIntoWorkspace = async ({+ copyFile,+ htmlContent,+ htmlFilePath,+ resources,+ workingDirectory,+ writeFile,+}: {+ copyFile: (from: string, to: string) => Promise<void>;+ htmlContent: string;+ htmlFilePath: string;+ resources: GatheredWorkspaceHtmlResource[];+ workingDirectory: string;+ writeFile: (path: string, content: string) => Promise<void>;+}): Promise<CopyWorkspaceHtmlArtifactResult> => {+ const pathApi = (workingDirectory.includes('\\') ? path.win32 : path.posix)!;+ const identifier = workspaceHtmlArtifactIdentifierForFile(htmlFilePath, workingDirectory);+ const targetDirectory = pathApi.join(workingDirectory, '.lobe-artifacts', identifier);+ const entryPath = pathApi.join(targetDirectory, pathApi.basename(htmlFilePath));+ const htmlDirectory = pathApi.dirname(htmlFilePath);+ const failed: GatheredWorkspaceHtmlResource[] = [];+ const copiedPaths = new Set<string>();++ const targetRelativePath = (absolutePath: string) => {+ const relativePath = pathApi.relative(htmlDirectory, absolutePath);+ const keepsLayout =+ relativePath !== '' &&+ relativePath.split(/[\\/]/, 1)[0] !== '..' &&+ !pathApi.isAbsolute(relativePath);++ return keepsLayout+ ? relativePath+ : pathApi.join(+ '__external__',+ sha256(absolutePath).slice(0, 8),+ pathApi.basename(absolutePath),+ );+ };++ const targets = new Map(+ resources.map((resource) => [resource.absolutePath, targetRelativePath(resource.absolutePath)]),+ );++ const rewrite = (+ content: string,+ sourcePath: string,+ sourceTarget: string,+ sourceKind: 'css' | 'html' | 'js',+ ) => {+ const refs = collectLocalResourceRefs({+ allowExternalReads: true,+ content,+ rootDirectory: sourceKind === 'js' ? htmlDirectory : undefined,+ sourceKind,+ sourcePath,+ workingDirectory,+ });+ let rewritten = content;++ for (const ref of refs.refs) {+ const target = targets.get(ref.absolutePath);+ if (!target) continue;+ // path-browserify drops the first character for `relative('.', value)`;+ // root both artifact-relative paths before comparing them.+ const relativeTarget = pathApi+ .relative(+ pathApi.dirname(pathApi.join(pathApi.sep, sourceTarget)),+ pathApi.join(pathApi.sep, target),+ )+ .replaceAll('\\', '/');+ rewritten = replaceHrefToken(rewritten, ref.href, `${relativeTarget}${hrefSuffix(ref.href)}`);+ }++ return rewritten;+ };++ await copyFile(htmlFilePath, entryPath);++ for (let index = 0; index < resources.length; index += READ_CONCURRENCY) {+ await Promise.all(+ resources.slice(index, index + READ_CONCURRENCY).map(async (resource) => {+ try {+ await copyFile(+ resource.absolutePath,+ pathApi.join(targetDirectory, targets.get(resource.absolutePath)!),+ );+ copiedPaths.add(resource.absolutePath);+ } catch {+ failed.push(resource);+ }+ }),+ );+ }++ await Promise.all(+ resources.map(async (resource) => {+ if (!copiedPaths.has(resource.absolutePath) || resource.text === undefined) return;+ const sourceKind = isCssAssetPath(resource.absolutePath)+ ? 'css'+ : isJsAssetPath(resource.absolutePath)+ ? 'js'+ : undefined;+ if (!sourceKind) return;+ const target = targets.get(resource.absolutePath)!;+ const rewritten = rewrite(resource.text, resource.absolutePath, target, sourceKind);+ if (rewritten !== resource.text) {+ await writeFile(pathApi.join(targetDirectory, target), rewritten);+ }+ }),+ );++ const copiedHtml = removeLocalBaseTag(+ rewrite(htmlContent, htmlFilePath, pathApi.basename(entryPath), 'html'),+ );+ await writeFile(entryPath, copiedHtml);++ return { entryPath, failed, htmlContent: copiedHtml, targetDirectory };+};diff --git a/src/features/Portal/LocalFile/prepareWorkspaceHtmlPublish.test.ts b/src/features/Portal/LocalFile/prepareWorkspaceHtmlPublish.test.tsindex aeedc8417a8..6969a305ab0 100644--- a/src/features/Portal/LocalFile/prepareWorkspaceHtmlPublish.test.ts+++ b/src/features/Portal/LocalFile/prepareWorkspaceHtmlPublish.test.ts@@ -1,12 +1,15 @@+import * as packModule from '@lobechat/html-artifact';import { beforeEach, describe, expect, it, vi } from 'vitest';import {getWorkspaceHtmlPublishSizeBytes,+ notifyWorkspaceHtmlPublishBlocked,prepareWorkspaceHtmlPublish,publishPreparedWorkspaceHtml,} from './prepareWorkspaceHtmlPublish';const readWorkspaceAsset = vi.hoisted(() => vi.fn());+const readExternalAssetForPublish = vi.hoisted(() => vi.fn());const toastError = vi.hoisted(() => vi.fn());const toastSuccess = vi.hoisted(() => vi.fn());@@ -23,9 +26,14 @@ vi.mock('./readWorkspaceAsset', async (importOriginal) => {};});+vi.mock('./readExternalAssetForPublish', () => ({+ readExternalAssetForPublish: (...args: unknown[]) => readExternalAssetForPublish(...args),+}));+describe('prepareWorkspaceHtmlPublish', () => {beforeEach(() => {readWorkspaceAsset.mockReset();+ readExternalAssetForPublish.mockReset();toastError.mockReset();toastSuccess.mockReset();});@@ -67,6 +75,84 @@ describe('prepareWorkspaceHtmlPublish', () => {expect(plan.gathered.title).toBe('From disk');});+ it('uses the publish-only reader for external refs and the normal reader inside the workspace', async () => {+ readWorkspaceAsset.mockResolvedValue({+ bytes: new TextEncoder().encode('console.log(1)'),+ contentType: 'text/javascript',+ ok: true,+ text: 'console.log(1)',+ });+ readExternalAssetForPublish.mockResolvedValue({+ bytes: new Uint8Array([1, 2, 3]),+ contentType: 'image/png',+ ok: true,+ });+ const input = {+ content: '<html><script src="../app.js"></script><img src="../../outside/logo.png"></html>',+ filePath: '/repo/pages/index.html',+ workingDirectory: '/repo',+ };++ const blocked = await prepareWorkspaceHtmlPublish(input);+ expect(blocked).toMatchObject({+ blocked: 'outside-workspace',+ escaped: [{ absolutePath: '/outside/logo.png', hrefs: ['../../outside/logo.png'] }],+ });+ expect(readWorkspaceAsset).toHaveBeenCalledWith({+ deviceId: undefined,+ path: '/repo/app.js',+ sandboxTopicId: undefined,+ workingDirectory: '/repo',+ });+ readWorkspaceAsset.mockClear();++ const ready = await prepareWorkspaceHtmlPublish({ ...input, allowExternalReads: true });+ expect('blocked' in ready).toBe(false);+ expect(readExternalAssetForPublish).toHaveBeenCalledWith({+ deviceId: undefined,+ path: '/outside/logo.png',+ sandboxTopicId: undefined,+ workingDirectory: '/repo',+ });+ expect(readWorkspaceAsset).toHaveBeenCalledWith({+ deviceId: undefined,+ path: '/repo/app.js',+ sandboxTopicId: undefined,+ workingDirectory: '/repo',+ });+ if ('blocked' in ready) return;+ expect(ready.packed.html).not.toContain('../../outside/logo.png');+ });++ it('keeps unresolved as a defensive fallback for an unexpected pack result', async () => {+ const pack = vi.spyOn(packModule, 'packWorkspaceHtmlDocument').mockReturnValueOnce({+ html: '<html></html>',+ inlinedPaths: [],+ sidecars: [],+ unresolvedHrefs: ['unexpected.png'],+ });++ await expect(+ prepareWorkspaceHtmlPublish({+ content: '<html></html>',+ filePath: '/repo/index.html',+ workingDirectory: '/repo',+ }),+ ).resolves.toEqual({ blocked: 'unresolved', unresolvedHrefs: ['unexpected.png'] });++ pack.mockRestore();+ });++ it('does not toast for outside-workspace because the caller owns its modal', async () => {+ notifyWorkspaceHtmlPublishBlocked({+ blocked: 'outside-workspace',+ escaped: [],+ gathered: {} as never,+ });++ expect(toastError).not.toHaveBeenCalled();+ });+it('returns unreadable when the HTML file cannot be loaded', async () => {readWorkspaceAsset.mockResolvedValue({ ok: false, reason: 'missing' });diff --git a/src/features/Portal/LocalFile/prepareWorkspaceHtmlPublish.ts b/src/features/Portal/LocalFile/prepareWorkspaceHtmlPublish.tsindex ac2adfe2dee..006cafbff11 100644--- a/src/features/Portal/LocalFile/prepareWorkspaceHtmlPublish.ts+++ b/src/features/Portal/LocalFile/prepareWorkspaceHtmlPublish.ts@@ -1,6 +1,8 @@import {+ type EscapedResourceRef,type GatheredWorkspaceHtmlArtifact,gatherWorkspaceHtmlArtifact,+ isPathInsideWorkspace,type PackedWorkspaceHtmlSite,packWorkspaceHtmlDocument,type WorkspaceHtmlArtifactPublisher,@@ -9,6 +11,7 @@ import {import { toast } from '@lobehub/ui/base-ui';import { t } from 'i18next';+import { readExternalAssetForPublish } from './readExternalAssetForPublish';import { readWorkspaceAsset } from './readWorkspaceAsset';export interface ReadyWorkspaceHtmlPublishPlan {@@ -41,13 +44,19 @@ export type WorkspaceHtmlPublishPlan =| {blocked: 'unreadable';}+ | {+ blocked: 'outside-workspace';+ escaped: EscapedResourceRef[];+ gathered: GatheredWorkspaceHtmlArtifact;+ }| {blocked: 'unresolved';unresolvedHrefs: string[];}| ReadyWorkspaceHtmlPublishPlan;-interface PrepareWorkspaceHtmlPublishInput {+export interface PrepareWorkspaceHtmlPublishInput {+ allowExternalReads?: boolean;content?: string;deviceId?: string;filePath: string;@@ -56,6 +65,7 @@ interface PrepareWorkspaceHtmlPublishInput {}export const prepareWorkspaceHtmlPublish = async ({+ allowExternalReads = false,content,deviceId,filePath,@@ -75,10 +85,13 @@ export const prepareWorkspaceHtmlPublish = async ({}const gathered = await gatherWorkspaceHtmlArtifact({+ allowExternalReads,htmlContent,htmlFilePath: filePath,readAsset: (absolutePath) =>- readWorkspaceAsset({+ (allowExternalReads && !isPathInsideWorkspace(absolutePath, workingDirectory)+ ? readExternalAssetForPublish+ : readWorkspaceAsset)({deviceId,path: absolutePath,sandboxTopicId,@@ -91,13 +104,20 @@ export const prepareWorkspaceHtmlPublish = async ({return { blocked: gathered.blocked, totalBytes: gathered.totalBytes };}+ if (!allowExternalReads && gathered.escaped.length > 0) {+ return { blocked: 'outside-workspace', escaped: gathered.escaped, gathered };+ }+const packed = packWorkspaceHtmlDocument({entryPath: gathered.entryPath,files: gathered.files,});- if (packed.unresolvedHrefs.length > 0) {- return { blocked: 'unresolved', unresolvedHrefs: packed.unresolvedHrefs };+ const unexpectedUnresolved = packed.unresolvedHrefs.filter(+ (href) => !gathered.missing.includes(href),+ );+ if (unexpectedUnresolved.length > 0) {+ return { blocked: 'unresolved', unresolvedHrefs: unexpectedUnresolved };}return { gathered, packed };@@ -116,6 +136,8 @@ export const notifyWorkspaceHtmlPublishBlocked = (return;}+ if (plan.blocked === 'outside-workspace') return;+toast.error(t(plan.blocked === 'too-many'@@ -141,6 +163,7 @@ export const publishPreparedWorkspaceHtml = async ({plan,publish,signal,+ successMessage,topicId,}: {agentId?: string | null;@@ -150,6 +173,7 @@ export const publishPreparedWorkspaceHtml = async ({plan: ReadyWorkspaceHtmlPublishPlan;publish: WorkspaceHtmlArtifactPublisher['publish'];signal?: AbortSignal;+ successMessage?: string;topicId: string;}): Promise<WorkspaceHtmlArtifactPublishResult | undefined> => {try {@@ -166,7 +190,7 @@ export const publishPreparedWorkspaceHtml = async ({topicId,});- toast.success(t('workingPanel.localFile.publish.success', { ns: 'chat' }));+ toast.success(successMessage ?? t('workingPanel.localFile.publish.success', { ns: 'chat' }));return result;} catch (error) {if (!onError?.(error)) toast.error(workspaceHtmlPublishErrorMessage(error));diff --git a/src/features/Portal/LocalFile/readExternalAssetForPublish.ts b/src/features/Portal/LocalFile/readExternalAssetForPublish.tsnew file mode 100644index 00000000000..35ba6bd44ef--- /dev/null+++ b/src/features/Portal/LocalFile/readExternalAssetForPublish.ts@@ -0,0 +1 @@+export { readExternalAssetForPublish } from './readWorkspaceAsset';diff --git a/src/features/Portal/LocalFile/readWorkspaceAsset.test.ts b/src/features/Portal/LocalFile/readWorkspaceAsset.test.tsindex 4a4c7979822..b1b611087c0 100644--- a/src/features/Portal/LocalFile/readWorkspaceAsset.test.ts+++ b/src/features/Portal/LocalFile/readWorkspaceAsset.test.ts@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';const callTool = vi.hoisted(() => vi.fn());const getLocalFilePreview = vi.hoisted(() => vi.fn());const readProjectFileBytes = vi.hoisted(() => vi.fn());+const readExternalAssetForPublishBytes = vi.hoisted(() => vi.fn());vi.mock('@/services/cloudSandbox', () => ({cloudSandboxService: {@@ -13,12 +14,14 @@ vi.mock('@/services/cloudSandbox', () => ({vi.mock('@/services/projectFile', () => ({projectFileService: {getLocalFilePreview,+ readExternalAssetForPublish: readExternalAssetForPublishBytes,readProjectFileBytes,},}));const { readWorkspaceAsset, resolveWorkspaceAssetContentType } =await import('./readWorkspaceAsset');+const { readExternalAssetForPublish } = await import('./readExternalAssetForPublish');describe('resolveWorkspaceAssetContentType', () => {it('prefers the svg image type over a generic text/plain preview', () => {@@ -37,6 +40,7 @@ describe('readWorkspaceAsset', () => {callTool.mockReset();getLocalFilePreview.mockReset();readProjectFileBytes.mockReset();+ readExternalAssetForPublishBytes.mockReset();});it('reads sandbox text files through readLocalFile', async () => {@@ -133,4 +137,32 @@ describe('readWorkspaceAsset', () => {readWorkspaceAsset({ path: '/tmp/runtime.js', workingDirectory: '/tmp' }),).resolves.toEqual({ ok: false, reason: 'oversized', sizeBytes: bytes.byteLength });});++ it('refuses a path outside the workspace before touching any normal transport', async () => {+ await expect(+ readWorkspaceAsset({ path: '/private/secret.txt', workingDirectory: '/repo' }),+ ).resolves.toEqual({ ok: false, reason: 'missing' });++ expect(getLocalFilePreview).not.toHaveBeenCalled();+ expect(readProjectFileBytes).not.toHaveBeenCalled();+ });++ it('reads an external path only through the publish-scoped transport', async () => {+ readExternalAssetForPublishBytes.mockResolvedValue({+ bytes: new TextEncoder().encode('body{}'),+ contentType: 'text/css',+ });++ await expect(+ readExternalAssetForPublish({ path: '/private/app.css', workingDirectory: '/repo' }),+ ).resolves.toMatchObject({ contentType: 'text/css', ok: true, text: 'body{}' });++ expect(readExternalAssetForPublishBytes).toHaveBeenCalledWith({+ deviceId: undefined,+ path: '/private/app.css',+ workingDirectory: '/repo',+ });+ expect(getLocalFilePreview).not.toHaveBeenCalled();+ expect(readProjectFileBytes).not.toHaveBeenCalled();+ });});diff --git a/src/features/Portal/LocalFile/readWorkspaceAsset.ts b/src/features/Portal/LocalFile/readWorkspaceAsset.tsindex c936e613ff2..b031c906169 100644--- a/src/features/Portal/LocalFile/readWorkspaceAsset.ts+++ b/src/features/Portal/LocalFile/readWorkspaceAsset.ts@@ -1,7 +1,9 @@import {+ isPathInsideWorkspace,isTextContentType,type ReadWorkspaceAssetResult,resolveWorkspaceAssetContentType,+ toWorkspaceAbsolutePath,WORKSPACE_HTML_ARTIFACT_MAX_FILE_BYTES,} from '@lobechat/html-artifact';import { base64ToBytes, getMimeType } from '@lobechat/utils';@@ -98,17 +100,17 @@ const previewToBytes = async (return;};-export const readWorkspaceAsset = async ({- deviceId,- path,- sandboxTopicId,- workingDirectory,-}: {+interface ReadAssetInput {deviceId?: string;path: string;sandboxTopicId?: string;workingDirectory: string;-}): Promise<ReadWorkspaceAssetResult> => {+}++const readAsset = async (+ { deviceId, path, sandboxTopicId, workingDirectory }: ReadAssetInput,+ externalForPublish: boolean,+): Promise<ReadWorkspaceAssetResult> => {try {if (sandboxTopicId) {const contentType = getMimeType(path);@@ -145,25 +147,25 @@ export const readWorkspaceAsset = async ({return { bytes, contentType, ok: true };}- const preview = await projectFileService.getLocalFilePreview({- deviceId,- path,- workingDirectory,- });- const fromPreview = await previewToBytes(preview);- if (fromPreview) {- if (!fromPreview.ok) return fromPreview;- return {- ...fromPreview,- contentType: resolveWorkspaceAssetContentType(path, fromPreview.contentType),- };+ if (!externalForPublish) {+ const preview = await projectFileService.getLocalFilePreview({+ deviceId,+ path,+ workingDirectory,+ });+ const fromPreview = await previewToBytes(preview);+ if (fromPreview) {+ if (!fromPreview.ok) return fromPreview;+ return {+ ...fromPreview,+ contentType: resolveWorkspaceAssetContentType(path, fromPreview.contentType),+ };+ }}- const bytesResult = await projectFileService.readProjectFileBytes({- deviceId,- path,- workingDirectory,- });+ const bytesResult = externalForPublish+ ? await projectFileService.readExternalAssetForPublish({ deviceId, path, workingDirectory })+ : await projectFileService.readProjectFileBytes({ deviceId, path, workingDirectory });if (!bytesResult) return { ok: false, reason: 'unreadable' };if (bytesResult.bytes.byteLength > WORKSPACE_HTML_ARTIFACT_MAX_FILE_BYTES) {return { ok: false, reason: 'oversized', sizeBytes: bytesResult.bytes.byteLength };@@ -178,3 +180,19 @@ export const readWorkspaceAsset = async ({return { ok: false, reason: 'missing' };}};++export const readWorkspaceAsset = async (+ input: ReadAssetInput,+): Promise<ReadWorkspaceAssetResult> => {+ const absolutePath = toWorkspaceAbsolutePath(input.path, input.workingDirectory);+ if (!isPathInsideWorkspace(absolutePath, input.workingDirectory)) {+ return { ok: false, reason: 'missing' };+ }++ return readAsset({ ...input, path: absolutePath }, false);+};++/** The explicit-consent publish flow is the only caller allowed to reach this reader. */+export const readExternalAssetForPublish = (+ input: ReadAssetInput,+): Promise<ReadWorkspaceAssetResult> => readAsset(input, true);diff --git a/src/features/Portal/LocalFile/useBlockedWorkspaceHtmlPublish.test.ts b/src/features/Portal/LocalFile/useBlockedWorkspaceHtmlPublish.test.tsnew file mode 100644index 00000000000..2aeab4a9f00--- /dev/null+++ b/src/features/Portal/LocalFile/useBlockedWorkspaceHtmlPublish.test.ts@@ -0,0 +1,242 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useBlockedWorkspaceHtmlPublish } from './useBlockedWorkspaceHtmlPublish';++const mocks = vi.hoisted(() => ({+ copy: vi.fn(),+ confirmModal: vi.fn(),+ debugLog: vi.fn(),+ notifyBlocked: vi.fn(),+ openConfirm: vi.fn(),+ prepare: vi.fn(),+ publishPrepared: vi.fn(),+ toastError: vi.fn(),+ translate: vi.fn((key: string, _options?: Record<string, unknown>) => key),+}));++vi.mock('debug', () => ({ default: () => mocks.debugLog }));++vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ confirmModal: (...args: unknown[]) => mocks.confirmModal(...args),+ toast: { error: (...args: unknown[]) => mocks.toastError(...args) },+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, options?: Record<string, unknown>) => mocks.translate(key, options),+ }),+}));+vi.mock('./copyWorkspaceHtmlArtifactIntoWorkspace', () => ({+ copyWorkspaceHtmlArtifactIntoWorkspace: (...args: unknown[]) => mocks.copy(...args),+}));+vi.mock('./prepareWorkspaceHtmlPublish', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ notifyWorkspaceHtmlPublishBlocked: (...args: unknown[]) => mocks.notifyBlocked(...args),+ prepareWorkspaceHtmlPublish: (...args: unknown[]) => mocks.prepare(...args),+ publishPreparedWorkspaceHtml: (...args: unknown[]) => mocks.publishPrepared(...args),+}));+vi.mock('./PublishHtmlArtifactConfirm', () => ({+ openWorkspaceHtmlPublishConfirm: (...args: unknown[]) => mocks.openConfirm(...args),+}));++const externalResource = {+ absolutePath: '/tmp/site/logo.png',+ contentType: 'image/png',+ hrefs: ['logo.png'],+};++const readyPlan = (resources = [externalResource], missing: string[] = []) =>+ ({+ gathered: {+ entryPath: 'index.html',+ files: [+ {+ content: '<html><img src="logo.png"></html>',+ contentType: 'text/html',+ encoding: 'utf8',+ path: 'index.html',+ },+ ],+ identifier: 'copied',+ missing,+ resources,+ title: 'Demo',+ },+ packed: { html: '<html></html>', inlinedPaths: [], sidecars: [], unresolvedHrefs: [] },+ }) as never;++const ready = readyPlan();++const input = {+ close: vi.fn(),+ copyFile: vi.fn(),+ filePath: '/tmp/site/index.html',+ hasExisting: false,+ plan: {+ blocked: 'outside-workspace' as const,+ escaped: [{ absolutePath: '/tmp/site/logo.png', hrefs: ['logo.png'] }],+ gathered: {+ entryPath: 'index.html',+ files: [+ {+ content: '<html><img src="logo.png"></html>',+ contentType: 'text/html',+ encoding: 'utf8' as const,+ path: 'index.html',+ },+ ],+ } as never,+ },+ publish: vi.fn(),+ topicId: 'topic-1',+ workingDirectory: '/project',+ writeFile: vi.fn(),+};++const copied = {+ entryPath: '/project/.lobe-artifacts/copied/index.html',+ failed: [],+ htmlContent: '<html><img src="logo.png"></html>',+ targetDirectory: '/project/.lobe-artifacts/copied',+};++describe('useBlockedWorkspaceHtmlPublish', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.publishPrepared.mockResolvedValue({ id: 'published' });+ });++ it('copies immediately when closure discovery adds no files, then safely prepares', async () => {+ mocks.prepare.mockResolvedValueOnce(ready).mockResolvedValueOnce(ready);+ mocks.copy.mockResolvedValue(copied);+ const { result } = renderHook(() => useBlockedWorkspaceHtmlPublish(input));++ await act(() => result.current.handleContinue());++ expect(mocks.prepare.mock.calls[0][0]).toEqual(+ expect.objectContaining({ allowExternalReads: true, filePath: '/tmp/site/index.html' }),+ );+ expect(mocks.copy).toHaveBeenCalledWith(+ expect.objectContaining({+ htmlFilePath: '/tmp/site/index.html',+ resources: [externalResource],+ writeFile: input.writeFile,+ }),+ );+ expect(mocks.prepare.mock.calls[1][0]).toEqual({+ deviceId: undefined,+ filePath: copied.entryPath,+ sandboxTopicId: undefined,+ workingDirectory: '/project',+ });+ expect(mocks.openConfirm).toHaveBeenCalledOnce();+ });++ it('shows newly discovered closure files and requires a second click before copying', async () => {+ const localResource = {+ absolutePath: '/project/assets/app.css',+ contentType: 'text/css',+ hrefs: ['/assets/app.css'],+ text: 'body{}',+ };+ const closure = readyPlan([externalResource, localResource]);+ mocks.prepare+ .mockResolvedValueOnce(closure)+ .mockResolvedValueOnce(closure)+ .mockResolvedValueOnce(ready);+ mocks.copy.mockResolvedValue(copied);+ const { result } = renderHook(() => useBlockedWorkspaceHtmlPublish(input));++ await act(() => result.current.handleContinue());++ expect(mocks.copy).not.toHaveBeenCalled();+ expect(result.current.resources).toEqual([+ externalResource,+ expect.objectContaining({ ...localResource, source: 'workspace' }),+ ]);++ await act(() => result.current.handleContinue());++ expect(mocks.copy).toHaveBeenCalledWith(+ expect.objectContaining({ resources: [externalResource, localResource] }),+ );+ expect(mocks.openConfirm).toHaveBeenCalledOnce();+ });++ it('hard-blocks when the safe prepare still has missing files', async () => {+ mocks.prepare+ .mockResolvedValueOnce(ready)+ .mockResolvedValueOnce(readyPlan([externalResource], ['gone.png']));+ mocks.copy.mockResolvedValue(copied);+ const { result } = renderHook(() => useBlockedWorkspaceHtmlPublish(input));++ await act(() => result.current.handleContinue());++ expect(mocks.openConfirm).not.toHaveBeenCalled();+ expect(mocks.toastError).toHaveBeenCalledWith(+ 'workingPanel.localFile.publish.outsideWorkspace.stillBlocked',+ );+ expect(mocks.debugLog).toHaveBeenCalledWith(expect.any(String), ['gone.png']);+ });++ it('does not reopen a confirm after the user cancels a pending closure read', async () => {+ let resolvePrepare: (value: typeof ready) => void = () => {};+ mocks.prepare.mockReturnValueOnce(+ new Promise((resolve) => {+ resolvePrepare = resolve;+ }),+ );+ const { result } = renderHook(() => useBlockedWorkspaceHtmlPublish(input));++ let pending: Promise<void>;+ act(() => {+ pending = result.current.handleContinue();+ });+ act(() => result.current.cancel());+ await act(async () => {+ resolvePrepare(ready);+ await pending!;+ });++ expect(input.close).toHaveBeenCalledOnce();+ expect(mocks.copy).not.toHaveBeenCalled();+ expect(mocks.openConfirm).not.toHaveBeenCalled();+ });++ it('clears resource-copy failures so a second attempt can succeed', async () => {+ mocks.prepare+ .mockResolvedValueOnce(ready)+ .mockResolvedValueOnce(ready)+ .mockResolvedValueOnce(ready);+ mocks.copy.mockResolvedValueOnce({ failed: [externalResource] }).mockResolvedValueOnce(copied);+ const { result } = renderHook(() => useBlockedWorkspaceHtmlPublish(input));++ await act(() => result.current.handleContinue());+ expect(result.current.failed).toEqual([externalResource]);++ await act(() => result.current.handleContinue());+ expect(result.current.failed).toEqual([]);+ expect(mocks.copy).toHaveBeenCalledTimes(2);+ expect(mocks.openConfirm).toHaveBeenCalledOnce();+ });++ it('requires warning confirmation before using the external publish reader', async () => {+ mocks.prepare.mockResolvedValue(ready);+ const { result } = renderHook(() => useBlockedWorkspaceHtmlPublish(input));++ act(() => result.current.handleForceChange(true));+ expect(result.current.force).toBe(false);+ act(() => mocks.confirmModal.mock.calls[0][0].onOk());+ expect(result.current.force).toBe(true);++ await act(() => result.current.handleContinue());++ expect(mocks.copy).not.toHaveBeenCalled();+ expect(mocks.prepare).toHaveBeenCalledWith(+ expect.objectContaining({ allowExternalReads: true, filePath: '/tmp/site/index.html' }),+ );+ expect(mocks.openConfirm).toHaveBeenCalledOnce();+ });+});diff --git a/src/features/Portal/LocalFile/useBlockedWorkspaceHtmlPublish.ts b/src/features/Portal/LocalFile/useBlockedWorkspaceHtmlPublish.tsnew file mode 100644index 00000000000..974f2bc6a71--- /dev/null+++ b/src/features/Portal/LocalFile/useBlockedWorkspaceHtmlPublish.ts@@ -0,0 +1,244 @@+import type { GatheredWorkspaceHtmlResource } from '@lobechat/html-artifact';+import { confirmModal, toast } from '@lobehub/ui/base-ui';+import debug from 'debug';+import { useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { copyWorkspaceHtmlArtifactIntoWorkspace } from './copyWorkspaceHtmlArtifactIntoWorkspace';+import {+ notifyWorkspaceHtmlPublishBlocked,+ prepareWorkspaceHtmlPublish,+ publishPreparedWorkspaceHtml,+ type ReadyWorkspaceHtmlPublishPlan,+ type WorkspaceHtmlPublishPlan,+} from './prepareWorkspaceHtmlPublish';+import { openWorkspaceHtmlPublishConfirm } from './PublishHtmlArtifactConfirm';+import type {+ WorkspaceHtmlArtifactPublisher,+ WorkspaceHtmlArtifactPublishResult,+} from './workspaceHtmlArtifact';+import { isPathInsideWorkspace } from './workspaceHtmlPath';++type OutsideWorkspacePlan = Extract<WorkspaceHtmlPublishPlan, { blocked: 'outside-workspace' }>;+type ResourceSource = 'nested' | 'workspace';+export type DisplayedWorkspaceHtmlResource = GatheredWorkspaceHtmlResource & {+ source?: ResourceSource;+};++const log = debug('lobe-client:workspace-html-publish');++export interface BlockedWorkspaceHtmlPublishInput {+ agentId?: string | null;+ close: () => void;+ copyFile: (from: string, to: string) => Promise<void>;+ deviceId?: string;+ filePath: string;+ hasExisting: boolean;+ onError?: (error: unknown) => boolean;+ onPublished?: (+ result: WorkspaceHtmlArtifactPublishResult,+ plan: ReadyWorkspaceHtmlPublishPlan,+ ) => void;+ plan: OutsideWorkspacePlan;+ publish: WorkspaceHtmlArtifactPublisher['publish'];+ sandboxTopicId?: string;+ topicId: string;+ workingDirectory: string;+ writeFile: (path: string, content: string) => Promise<void>;+}++export const useBlockedWorkspaceHtmlPublish = ({+ agentId,+ close,+ copyFile,+ deviceId,+ filePath,+ hasExisting,+ onError,+ onPublished,+ plan,+ publish,+ sandboxTopicId,+ topicId,+ workingDirectory,+ writeFile,+}: BlockedWorkspaceHtmlPublishInput) => {+ const { t } = useTranslation(['chat', 'common']);+ const [force, setForce] = useState(false);+ const [busy, setBusy] = useState(false);+ const [failed, setFailed] = useState<GatheredWorkspaceHtmlResource[]>([]);+ const [resources, setResources] = useState<DisplayedWorkspaceHtmlResource[]>(plan.escaped);+ const cancelled = useRef(false);+ const busyRef = useRef(false);+ const htmlEntry = plan.gathered.files.find((file) => file.path === plan.gathered.entryPath);+ const htmlContent = htmlEntry?.encoding === 'utf8' ? htmlEntry.content : undefined;++ useEffect(() => () => void (cancelled.current = true), []);++ const cancel = () => {+ cancelled.current = true;+ close();+ };++ const handleForceChange = (checked: boolean) => {+ if (!checked) {+ setForce(false);+ return;+ }++ confirmModal({+ cancelText: t('cancel', { ns: 'common' }),+ content: t('workingPanel.localFile.publish.outsideWorkspace.forceHint', { ns: 'chat' }),+ okButtonProps: { danger: true },+ okText: t('confirm', { ns: 'common' }),+ onOk: () => setForce(true),+ title: t('workingPanel.localFile.publish.outsideWorkspace.forceLabel', { ns: 'chat' }),+ });+ };++ const openConfirm = (ready: ReadyWorkspaceHtmlPublishPlan, copiedDirectory?: string) => {+ close();+ openWorkspaceHtmlPublishConfirm({+ hasExisting,+ plan: ready,+ onOk: () => {+ void publishPreparedWorkspaceHtml({+ agentId,+ onError,+ plan: ready,+ publish,+ successMessage: copiedDirectory+ ? t('workingPanel.localFile.publish.outsideWorkspace.copiedToast', {+ dir: copiedDirectory,+ })+ : undefined,+ topicId,+ }).then((result) => {+ if (result) onPublished?.(result, ready);+ });+ },+ });+ };++ const stillBlocked = (paths: string[]) => {+ log('Prepared workspace copy still has unresolved paths: %O', paths);+ toast.error(t('workingPanel.localFile.publish.outsideWorkspace.stillBlocked', { ns: 'chat' }));+ };++ const prepareNext = async (+ input: Parameters<typeof prepareWorkspaceHtmlPublish>[0],+ requireClean = false,+ ) => {+ const next = await prepareWorkspaceHtmlPublish(input);+ if ('blocked' in next) {+ if (next.blocked === 'outside-workspace') {+ stillBlocked(next.escaped.map((item) => item.absolutePath));+ } else {+ notifyWorkspaceHtmlPublishBlocked(next);+ }+ return;+ }+ if (requireClean && next.gathered.missing.length > 0) {+ stillBlocked(next.gathered.missing);+ return;+ }+ return next;+ };++ const handleContinue = async () => {+ if (busyRef.current) return;+ busyRef.current = true;+ cancelled.current = false;+ setFailed([]);+ setBusy(true);++ try {+ if (force) {+ const ready = await prepareNext({+ allowExternalReads: true,+ content: htmlContent,+ deviceId,+ filePath,+ sandboxTopicId,+ workingDirectory,+ });+ if (!cancelled.current && ready) openConfirm(ready);+ return;+ }++ const closure = await prepareNext({+ allowExternalReads: true,+ content: htmlContent,+ deviceId,+ filePath,+ sandboxTopicId,+ workingDirectory,+ });+ if (cancelled.current || !closure) return;++ const displayedPaths = new Set(resources.map((resource) => resource.absolutePath));+ if (+ closure.gathered.resources.some((resource) => !displayedPaths.has(resource.absolutePath))+ ) {+ const initiallyDisplayed = new Set(plan.escaped.map((resource) => resource.absolutePath));+ setResources(+ closure.gathered.resources.map((resource) =>+ initiallyDisplayed.has(resource.absolutePath)+ ? resource+ : {+ ...resource,+ source: isPathInsideWorkspace(resource.absolutePath, workingDirectory)+ ? 'workspace'+ : 'nested',+ },+ ),+ );+ return;+ }++ const entry = closure.gathered.files.find(+ (file) => file.path === closure.gathered.entryPath && file.encoding === 'utf8',+ );+ if (!entry) {+ notifyWorkspaceHtmlPublishBlocked({ blocked: 'unreadable' });+ return;+ }++ const copied = await copyWorkspaceHtmlArtifactIntoWorkspace({+ copyFile,+ htmlContent: entry.content,+ htmlFilePath: filePath,+ resources: closure.gathered.resources,+ workingDirectory,+ writeFile,+ });+ if (cancelled.current) return;+ if (copied.failed.length > 0) {+ setFailed(copied.failed);+ return;+ }++ const ready = await prepareNext(+ {+ deviceId,+ filePath: copied.entryPath,+ sandboxTopicId,+ workingDirectory,+ },+ true,+ );+ if (!cancelled.current && ready) openConfirm(ready, copied.targetDirectory);+ } catch (error) {+ if (cancelled.current) return;+ log('Failed to copy workspace HTML entry %s: %O', filePath, error);+ toast.error(+ t('workingPanel.localFile.publish.outsideWorkspace.copyFailedEntry', { ns: 'chat' }),+ );+ } finally {+ busyRef.current = false;+ if (!cancelled.current) setBusy(false);+ }+ };++ return { busy, cancel, failed, force, handleContinue, handleForceChange, resources };+};diff --git a/src/services/electron/localFileService.test.ts b/src/services/electron/localFileService.test.tsindex fb126edb87e..1ff161636ee 100644--- a/src/services/electron/localFileService.test.ts+++ b/src/services/electron/localFileService.test.ts@@ -1,6 +1,7 @@import { afterEach, describe, expect, it, vi } from 'vitest';const mockLocalSystem = vi.hoisted(() => ({+ getExternalAssetForPublishUrl: vi.fn(),getLocalFilePreviewUrl: vi.fn(),}));@@ -192,4 +193,36 @@ describe('localFileService', () => {contentType: 'font/woff2',});});++ it('uses the dedicated publish IPC channel for external bytes', async () => {+ const { localFileService } = await import('./localFileService');+ mockLocalSystem.getExternalAssetForPublishUrl.mockResolvedValue({+ success: true,+ url: 'localfile://publish/font.woff2',+ });+ vi.stubGlobal(+ 'fetch',+ vi.fn(+ async () =>+ ({+ arrayBuffer: vi.fn(async () => new Uint8Array([10, 20]).buffer),+ headers: { get: vi.fn(() => 'font/woff2') },+ ok: true,+ }) as unknown as Response,+ ),+ );++ await expect(+ localFileService.readExternalAssetForPublish({+ path: '/outside/font.woff2',+ workingDirectory: '/repo',+ }),+ ).resolves.toEqual({ bytes: new Uint8Array([10, 20]), contentType: 'font/woff2' });++ expect(mockLocalSystem.getExternalAssetForPublishUrl).toHaveBeenCalledWith({+ path: '/outside/font.woff2',+ workingDirectory: '/repo',+ });+ expect(mockLocalSystem.getLocalFilePreviewUrl).not.toHaveBeenCalled();+ });});diff --git a/src/services/electron/localFileService.ts b/src/services/electron/localFileService.tsindex 485c9511d08..792c66009d6 100644--- a/src/services/electron/localFileService.ts+++ b/src/services/electron/localFileService.ts@@ -178,6 +178,19 @@ const fetchLocalFilePreview = async (return { contentType, type: 'binary' };};+const fetchLocalFileBytes = async (+ url: string,+): Promise<{ bytes: Uint8Array; contentType: string } | undefined> => {+ const response = await fetch(url);+ if (!response.ok) return;++ return {+ bytes: new Uint8Array(await response.arrayBuffer()),+ contentType:+ normalizeContentType(response.headers.get('content-type')) || 'application/octet-stream',+ };+};+class LocalFileService {// File Operationsasync listLocalFiles(params: ListLocalFileParams): Promise<ListLocalFilesResult> {@@ -256,14 +269,17 @@ class LocalFileService {if (!result.success || !result.url) return;- const response = await fetch(result.url);- if (!response.ok) return;+ return fetchLocalFileBytes(result.url);+ }- return {- bytes: new Uint8Array(await response.arrayBuffer()),- contentType:- normalizeContentType(response.headers.get('content-type')) || 'application/octet-stream',- };+ async readExternalAssetForPublish(params: {+ path: string;+ workingDirectory: string;+ }): Promise<{ bytes: Uint8Array; contentType: string } | undefined> {+ const result = await ensureElectronIpc().localSystem.getExternalAssetForPublishUrl(params);+ if (!result.success || !result.url) return;++ return fetchLocalFileBytes(result.url);}async prepareSkillDirectory(diff --git a/src/services/projectFile.test.ts b/src/services/projectFile.test.tsindex 9829c56f341..653c0853bb4 100644--- a/src/services/projectFile.test.ts+++ b/src/services/projectFile.test.ts@@ -3,12 +3,14 @@ import { afterEach, describe, expect, it, vi } from 'vitest';const mockDeviceClient = vi.hoisted(() => ({getLocalFilePreview: { query: vi.fn() },getProjectFileIndex: { query: vi.fn() },+ readExternalAssetForPublish: { query: vi.fn() },searchProjectFiles: { query: vi.fn() },}));const mockLocalFileService = vi.hoisted(() => ({getLocalFilePreview: vi.fn(),getProjectFileIndex: vi.fn(),+ readExternalAssetForPublish: vi.fn(),searchProjectFiles: vi.fn(),}));@@ -141,6 +143,49 @@ describe('projectFileService', () => {});});+ it('reads an external publish asset through the dedicated remote RPC', async () => {+ const { projectFileService } = await import('./projectFile');+ mockDeviceClient.readExternalAssetForPublish.query.mockResolvedValue({+ base64: 'AQID',+ contentType: 'image/png',+ success: true,+ });++ await expect(+ projectFileService.readExternalAssetForPublish({+ deviceId: 'device-1',+ path: '/outside/image.png',+ workingDirectory: '/repo',+ }),+ ).resolves.toEqual({ bytes: new Uint8Array([1, 2, 3]), contentType: 'image/png' });++ expect(mockDeviceClient.readExternalAssetForPublish.query).toHaveBeenCalledWith({+ deviceId: 'device-1',+ path: '/outside/image.png',+ workingDirectory: '/repo',+ });+ expect(mockDeviceClient.getLocalFilePreview.query).not.toHaveBeenCalled();+ });++ it('reads an external publish asset through the dedicated desktop service', async () => {+ const { projectFileService } = await import('./projectFile');+ const result = { bytes: new Uint8Array([4]), contentType: 'font/woff2' };+ mockLocalFileService.readExternalAssetForPublish.mockResolvedValue(result);++ await expect(+ projectFileService.readExternalAssetForPublish({+ path: '/outside/font.woff2',+ workingDirectory: '/repo',+ }),+ ).resolves.toBe(result);++ expect(mockLocalFileService.readExternalAssetForPublish).toHaveBeenCalledWith({+ path: '/outside/font.woff2',+ workingDirectory: '/repo',+ });+ expect(mockLocalFileService.getLocalFilePreview).not.toHaveBeenCalled();+ });+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.tsindex 9964cf9580a..e2c8aa9a615 100644--- a/src/services/projectFile.ts+++ b/src/services/projectFile.ts@@ -144,6 +144,32 @@ class ProjectFileService {return localFileService.readLocalFileBytes({ path, workingDirectory });}+ async readExternalAssetForPublish({+ deviceId,+ path,+ workingDirectory,+ }: {+ deviceId?: string;+ path: string;+ workingDirectory: string;+ }): Promise<{ bytes: Uint8Array; contentType: string } | undefined> {+ if (!deviceId) {+ return localFileService.readExternalAssetForPublish({ path, workingDirectory });+ }++ const result = await lambdaClient.device.readExternalAssetForPublish.query({+ deviceId,+ path,+ workingDirectory,+ });+ if (!result.success || result.base64 === undefined || !result.contentType) return;++ return {+ bytes: Uint8Array.from(globalThis.atob(result.base64), (char) => char.charCodeAt(0)),+ contentType: result.contentType,+ };+ }+/*** Move one or more files/folders within a project working directory. Batched:* each item succeeds or fails independently.