Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(portal): publish workspace HTML as a public Artifact (#18424)

Inneieff0740fb441
diff --git a/.agents/acceptance/common-mistakes.md b/.agents/acceptance/common-mistakes.md
index 34e3183ddc2..885c814b2a7 100644
--- a/.agents/acceptance/common-mistakes.md
+++ b/.agents/acceptance/common-mistakes.md
@@ -614,6 +614,53 @@ input timing confirmed in a foreground tab — the user's window, or a screensho
check that tolerates a frozen transition. A negative result from a hidden tab is not
evidence of a defect.
+### L-S11 — Long `confirmModal` bodies overlay the footer
+
+**Wrong approach:** put a long list into `confirmModal({ content })` and assume the
+library pins Cancel / OK below a scroll area.
+
+**Why it fails:** `confirmModal` renders `ConfirmBody` (content + footer) inside
+`ModalContent`, which is itself `overflow: auto`. A tall list makes the dialog
+scroll as one column, or the footer paints over the last rows. Callers cannot pass
+content styles to change that.
+
+**Correct approach:** for any confirm body that can exceed a few lines, use
+`createModal` with a height-capped `ScrollArea` as `content` and put the actions in
+the modal `footer` slot. Assert `footer.top === scroller.bottom` at both ends of the
+list, not just that the dialog opened.
+
+### L-S12 — Bundled SPA HTML is not the whole site
+
+**Wrong approach:** collect only tags and CSS `url()` from `index.html`, then treat
+a Vite/webpack `dist` as publishable.
+
+**Why it fails:** hashed images and public sprites live in the JS bundle
+(`new URL('hero-….png', import.meta.url)`, `href: '/icons.svg#…'`). HTML-only
+collection ships CSS/JS and drops the files the app actually paints. Those JS
+references also cannot be inlined as data URIs: `import.meta.url` and SVG
+`<use href="/icons.svg#id">` need real sibling/root files.
+
+**Correct approach:** walk collected JS the same way as CSS. Keep
+`import.meta.url` targets and root-absolute sprites as sidecars even when they
+are under the inline size limit. Judge a Vite publish by the running page
+(images, icons, counter), not by whether `index.html` listed three tags.
+
+### L-S13 — macOS `/tmp` and `/private/tmp` are the same workspace
+
+**Wrong approach:** treat a Files-tree path and the topic working directory as
+outside each other when one string starts with `/tmp` and the other with
+`/private/tmp`.
+
+**Why it fails:** Darwin's `/tmp` is a symlink to `/private/tmp`. Electron's
+project index reports the real path; topic cwd is often the public alias. A
+prefix check then marks `./app.css` as an escape, HTML-only publish keeps the
+relative hrefs, and the live host 404s those files.
+
+**Correct approach:** canonicalize those Darwin private aliases before workspace
+containment. Prove a publish by fetching the public HTML (data URIs or 200
+sidecars) and opening the live page — in-app preview of the local file does not
+prove the hosted assets.
+
## Historical source
Detailed incident narratives and retired pixel- or component-specific directions
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.md
index e611af96c5f..76863101493 100644
--- a/.agents/acceptance/probe-mock-patterns.md
+++ b/.agents/acceptance/probe-mock-patterns.md
@@ -1243,6 +1243,24 @@ which runs on the golden profile in place and decrypts normally. It boots on the
loading shell once, so reload once before probing (see L-S8). Gate on
`app-probe.sh auth` AND `server-auth`, never on the helper's "Ready" line.
+### Workspace HTML publish: prove the hosted page, not the local preview
+
+**Situation:** after publishing workspace HTML, checking whether CSS/SVG/images
+actually load on the public Artifact URL.
+
+**Doesn't work:** grepping the in-app HTML preview, or treating `app.css` /
+`dot.svg` HTTP 404 on the host as failure after a successful inline publish.
+Those paths are not uploaded when files are inlined. Opening a relative
+`index.html` tab (instead of the Files-tree absolute path) also fails to load
+and hides the publish control.
+
+**Works:** click the Files-tree row so `openLocalFiles[].filePath` is the
+Electron absolute path (on macOS often `/private/tmp/...`). After publish,
+`curl` the public URL and assert the HTML no longer contains `./app.css`. Then
+open that URL and assert computed CSS plus `img.naturalWidth > 0`. If the hosted
+`<img>` is a data URI with `text/plain`, the image is broken even though it is
+not a 404.
+
## Detailed references
- [Probe field notes](./references/probe-field-notes.md) — all historical
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index d4cea50d281..bc06d410236 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -2039,6 +2039,31 @@
"workingPanel.localFile.preview.reload": "Reload preview",
"workingPanel.localFile.preview.render": "Preview",
"workingPanel.localFile.preview.source": "Source",
+ "workingPanel.localFile.publish.action": "Publish",
+ "workingPanel.localFile.publish.confirmTitle": "Before you publish this page",
+ "workingPanel.localFile.publish.details": "What will be published",
+ "workingPanel.localFile.publish.dynamic": "Files loaded later by scripts will not be included.",
+ "workingPanel.localFile.publish.failed": "Couldn't publish this page",
+ "workingPanel.localFile.publish.files_one": "This page includes {{count}} local file. It will be published together with the HTML.",
+ "workingPanel.localFile.publish.files_other": "This page includes {{count}} local files. They will be published together with the HTML.",
+ "workingPanel.localFile.publish.inline_one": "1 small file (under {{limit}}) is inlined into the HTML.",
+ "workingPanel.localFile.publish.inline_other": "{{count}} small files (under {{limit}}) are inlined into the HTML.",
+ "workingPanel.localFile.publish.live": "Live",
+ "workingPanel.localFile.publish.missing": "Missing files will not be included: {{list}}",
+ "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.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.",
+ "workingPanel.localFile.publish.scanning": "Preparing this page…",
+ "workingPanel.localFile.publish.success": "Published",
+ "workingPanel.localFile.publish.tooLarge": "This page is too large to publish ({{size}} bytes).",
+ "workingPanel.localFile.publish.tooMany": "This page references too many local files to publish.",
+ "workingPanel.localFile.publish.unresolvedLocals": "This page still points at local files that were not packed, so those assets would break after publish.",
+ "workingPanel.localFile.publish.upload_one": "1 larger file will be uploaded with the page.",
+ "workingPanel.localFile.publish.upload_other": "{{count}} larger files will be uploaded with the page.",
+ "workingPanel.localFile.publish.version": "Publish this version",
"workingPanel.localFile.sandboxUnavailable": "This file is no longer available — its sandbox environment has been recycled",
"workingPanel.localFile.truncated": "File preview truncated to {{limit}} characters",
"workingPanel.openMenu.configuration": "Configuration",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 1bcfb6531c5..2a0d58523c4 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -2039,6 +2039,31 @@
"workingPanel.localFile.preview.reload": "刷新预览",
"workingPanel.localFile.preview.render": "预览",
"workingPanel.localFile.preview.source": "源码",
+ "workingPanel.localFile.publish.action": "发布",
+ "workingPanel.localFile.publish.confirmTitle": "发布此页面前",
+ "workingPanel.localFile.publish.details": "将发布的内容",
+ "workingPanel.localFile.publish.dynamic": "脚本运行时再加载的本地文件不会带上。",
+ "workingPanel.localFile.publish.failed": "无法发布此页面",
+ "workingPanel.localFile.publish.files_one": "此页面包含 {{count}} 个本地文件,将与 HTML 一并发布。",
+ "workingPanel.localFile.publish.files_other": "此页面包含 {{count}} 个本地文件,将与 HTML 一并发布。",
+ "workingPanel.localFile.publish.inline_one": "1 个小于 {{limit}} 的文件会内联进 HTML。",
+ "workingPanel.localFile.publish.inline_other": "{{count}} 个小于 {{limit}} 的文件会内联进 HTML。",
+ "workingPanel.localFile.publish.live": "已上线",
+ "workingPanel.localFile.publish.missing": "缺失的文件不会包含在内:{{list}}",
+ "workingPanel.localFile.publish.noLocalFiles": "此页面除 HTML 外没有本地文件。",
+ "workingPanel.localFile.publish.noTopic": "打开一个话题后再发布此页面",
+ "workingPanel.localFile.publish.note": "你可以随时取消发布。",
+ "workingPanel.localFile.publish.oversized": "这些文件过大,无法发布:{{list}}",
+ "workingPanel.localFile.publish.privacy": "任何拥有链接的人都可以打开此页面。发布前请确认其中不含你希望保密的内容,例如凭证、API 密钥、个人信息、上传的文件或图片。",
+ "workingPanel.localFile.publish.remotes": "这些外部地址会保持原样,发布后仍从原站点加载。",
+ "workingPanel.localFile.publish.scanning": "正在准备此页面…",
+ "workingPanel.localFile.publish.success": "已发布",
+ "workingPanel.localFile.publish.tooLarge": "此页面过大,无法发布({{size}} 字节)。",
+ "workingPanel.localFile.publish.tooMany": "此页面引用的本地文件过多,无法发布。",
+ "workingPanel.localFile.publish.unresolvedLocals": "此页面仍引用未打包的本地文件,发布后这些资源会失效。",
+ "workingPanel.localFile.publish.upload_one": "1 个较大的文件会与页面一起上传。",
+ "workingPanel.localFile.publish.upload_other": "{{count}} 个较大的文件会与页面一起上传。",
+ "workingPanel.localFile.publish.version": "发布此版本",
"workingPanel.localFile.sandboxUnavailable": "此文件已不可用——所在的沙盒环境已被回收",
"workingPanel.localFile.truncated": "文件预览被截断至 {{limit}} 个字符",
"workingPanel.openMenu.configuration": "配置",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 38cf98ab3a5..f365b5b4bad 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -2279,6 +2279,39 @@ export default {
'workingPanel.localFile.preview.reload': 'Reload preview',
'workingPanel.localFile.preview.render': 'Preview',
'workingPanel.localFile.preview.source': 'Source',
+ 'workingPanel.localFile.publish.action': 'Publish',
+ 'workingPanel.localFile.publish.confirmTitle': 'Before you publish this page',
+ 'workingPanel.localFile.publish.details': 'What will be published',
+ 'workingPanel.localFile.publish.dynamic': 'Files loaded later by scripts will not be included.',
+ 'workingPanel.localFile.publish.failed': "Couldn't publish this page",
+ 'workingPanel.localFile.publish.files_one':
+ 'This page includes {{count}} local file. It will be published together with the HTML.',
+ 'workingPanel.localFile.publish.files_other':
+ 'This page includes {{count}} local files. They will be published together with the HTML.',
+ 'workingPanel.localFile.publish.inline_one':
+ '1 small file (under {{limit}}) is inlined into the HTML.',
+ 'workingPanel.localFile.publish.inline_other':
+ '{{count}} small files (under {{limit}}) are inlined into the HTML.',
+ 'workingPanel.localFile.publish.live': 'Live',
+ 'workingPanel.localFile.publish.upload_one': '1 larger file will be uploaded with the page.',
+ 'workingPanel.localFile.publish.upload_other':
+ '{{count}} larger files will be uploaded with the page.',
+ 'workingPanel.localFile.publish.missing': 'Missing files will not be included: {{list}}',
+ '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.oversized': 'These files are too large to publish: {{list}}',
+ '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…',
+ '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.success': 'Published',
+ 'workingPanel.localFile.publish.tooLarge': 'This page is too large to publish ({{size}} bytes).',
+ 'workingPanel.localFile.publish.tooMany': 'This page references too many local files to publish.',
+ 'workingPanel.localFile.publish.unresolvedLocals':
+ 'This page still points at local files that were not packed, so those assets would break after publish.',
+ 'workingPanel.localFile.publish.version': 'Publish this version',
'workingPanel.localFile.truncated': 'File preview truncated to {{limit}} characters',
'workingPanel.skills.actions.comingSoon': 'Coming soon',
'workingPanel.skills.actions.delete': 'Delete',
diff --git a/packages/utils/src/base64.ts b/packages/utils/src/base64.ts
index 0448982ec87..a26d32a55be 100644
--- a/packages/utils/src/base64.ts
+++ b/packages/utils/src/base64.ts
@@ -6,41 +6,59 @@
import { Buffer } from 'buffer.js';
/**
- * Encode a string to base64
- * @param input - The string to encode
+ * Encode raw bytes to base64
+ * @param bytes - The bytes to encode
* @returns Base64 encoded string
*/
-export const encodeToBase64 = (input: string): string => {
+export const bytesToBase64 = (bytes: Uint8Array): string => {
if (typeof btoa === 'function') {
- // Browser environment: `btoa` only accepts Latin1 and throws on any code
- // point > U+00FF, so UTF-8-encode first and map each byte to a Latin1 char.
- const bytes = new TextEncoder().encode(input);
- const binary = Array.from(bytes, (byte) => String.fromCodePoint(byte)).join('');
+ // Browser environment: `btoa` wants a Latin1 binary string; build it in
+ // chunks because `String.fromCharCode(...bytes)` overflows the argument
+ // limit on large payloads.
+ let binary = '';
+ const chunkSize = 8192;
+ for (let index = 0; index < bytes.byteLength; index += chunkSize) {
+ binary += String.fromCharCode(...bytes.subarray(index, index + chunkSize));
+ }
return btoa(binary);
} else {
// Node.js environment
- return Buffer.from(input, 'utf8').toString('base64');
+ return Buffer.from(bytes).toString('base64');
}
};
/**
- * Decode a base64 string
+ * Decode a base64 string to raw bytes
* @param input - The base64 string to decode
- * @returns Decoded string
+ * @returns Decoded bytes
*/
-export const decodeFromBase64 = (input: string): string => {
+export const base64ToBytes = (input: string): Uint8Array => {
if (typeof atob === 'function') {
- // Browser environment: `atob` yields a Latin1 binary string, so read the
- // bytes back out and decode them as UTF-8.
+ // Browser environment: `atob` yields a Latin1 binary string, one char per byte.
const binary = atob(input);
- const bytes = Uint8Array.from(binary, (char) => char.codePointAt(0) ?? 0);
- return new TextDecoder().decode(bytes);
+ return Uint8Array.from(binary, (char) => char.charCodeAt(0));
} else {
// Node.js environment
- return Buffer.from(input, 'base64').toString('utf8');
+ return new Uint8Array(Buffer.from(input, 'base64'));
}
};
+/**
+ * Encode a string to base64
+ * @param input - The string to encode
+ * @returns Base64 encoded string
+ */
+export const encodeToBase64 = (input: string): string =>
+ bytesToBase64(new TextEncoder().encode(input));
+
+/**
+ * Decode a base64 string
+ * @param input - The base64 string to decode
+ * @returns Decoded string
+ */
+export const decodeFromBase64 = (input: string): string =>
+ new TextDecoder().decode(base64ToBytes(input));
+
/**
* Create Basic Authentication header value
* @param username - Username for authentication
diff --git a/src/business/client/features/WorkspaceHtmlArtifactPublish.ts b/src/business/client/features/WorkspaceHtmlArtifactPublish.ts
new file mode 100644
index 00000000000..71f21450359
--- /dev/null
+++ b/src/business/client/features/WorkspaceHtmlArtifactPublish.ts
@@ -0,0 +1,57 @@
+export interface WorkspaceHtmlArtifactFile {
+ content: string;
+ contentType: string;
+ encoding: 'base64' | 'utf8';
+ path: string;
+}
+
+export interface WorkspaceHtmlArtifactPublishInput {
+ agentId?: string;
+ entryPath: string;
+ files: WorkspaceHtmlArtifactFile[];
+ identifier: string;
+ packed?: { html: string; sidecars: WorkspaceHtmlArtifactFile[] };
+ title: string;
+ topicId: string;
+}
+
+export interface WorkspaceHtmlArtifactExisting {
+ identifier: string;
+ publicUrl?: string;
+ revision?: number;
+ status?: string;
+}
+
+export interface WorkspaceHtmlArtifactPublishResult {
+ publicUrl?: string;
+ revision?: number;
+}
+
+export interface WorkspaceHtmlArtifactPublisher {
+ available: boolean;
+ getExisting: (input: {
+ identifier: string;
+ topicId: string;
+ }) => Promise<WorkspaceHtmlArtifactExisting | null>;
+ publish: (
+ input: WorkspaceHtmlArtifactPublishInput,
+ ) => Promise<WorkspaceHtmlArtifactPublishResult>;
+}
+
+/**
+ * The open-source build has no market deployment backend, so this slot reports
+ * the publisher as unavailable; downstream builds override the module via their
+ * own `@/business/...` mapping. Keep the returned object referentially stable —
+ * consumers put `getExisting` in effect dependencies.
+ */
+const unavailablePublisher: WorkspaceHtmlArtifactPublisher = {
+ available: false,
+ getExisting: async () => null,
+ publish: async () => {
+ throw new Error('unavailable');
+ },
+};
+
+export function useWorkspaceHtmlArtifactPublish(): WorkspaceHtmlArtifactPublisher {
+ return unavailablePublisher;
+}
diff --git a/src/business/client/features/__tests__/WorkspaceHtmlArtifactPublish.test.ts b/src/business/client/features/__tests__/WorkspaceHtmlArtifactPublish.test.ts
new file mode 100644
index 00000000000..e7d23c789d4
--- /dev/null
+++ b/src/business/client/features/__tests__/WorkspaceHtmlArtifactPublish.test.ts
@@ -0,0 +1,33 @@
+import { renderHook } from '@testing-library/react';
+import { describe, expect, it } from 'vitest';
+
+import { useWorkspaceHtmlArtifactPublish } from '../WorkspaceHtmlArtifactPublish';
+
+describe('useWorkspaceHtmlArtifactPublish (oss stub)', () => {
+ it('reports the publisher as unavailable', async () => {
+ const { result } = renderHook(() => useWorkspaceHtmlArtifactPublish());
+
+ expect(result.current.available).toBe(false);
+ await expect(
+ result.current.getExisting({ identifier: 'workspace-html-index-html', topicId: 'tpc_1' }),
+ ).resolves.toBeNull();
+ await expect(
+ result.current.publish({
+ entryPath: 'index.html',
+ files: [],
+ identifier: 'workspace-html-index-html',
+ title: 'Demo',
+ topicId: 'tpc_1',
+ }),
+ ).rejects.toThrow('unavailable');
+ });
+
+ it('keeps the publisher referentially stable across renders', () => {
+ const { rerender, result } = renderHook(() => useWorkspaceHtmlArtifactPublish());
+ const first = result.current;
+ rerender();
+
+ expect(result.current).toBe(first);
+ expect(result.current.getExisting).toBe(first.getExisting);
+ });
+});
diff --git a/src/components/HtmlPreview/PreviewDrawer.tsx b/src/components/HtmlPreview/PreviewDrawer.tsx
index 76cce0001d3..ac0fa0183c4 100644
--- a/src/components/HtmlPreview/PreviewDrawer.tsx
+++ b/src/components/HtmlPreview/PreviewDrawer.tsx
@@ -9,6 +9,8 @@ import { useTranslation } from 'react-i18next';
import { isDesktop } from '@/const/version';
+import { extractHtmlTitle } from './htmlTagScanner';
+
const styles = createStaticStyles(({ css }) => ({
container: css`
height: 100%;
@@ -27,13 +29,6 @@ const HtmlPreviewDrawer = memo<HtmlPreviewDrawerProps>(({ content, open, onClose
const { t } = useTranslation('components');
const [mode, setMode] = useState<'preview' | 'code'>('preview');
- const htmlContent = content;
-
- const extractTitle = useCallback(() => {
- const m = htmlContent.match(/<title>([\S\s]*?)<\/title>/i);
- return m ? m[1].trim() : undefined;
- }, [htmlContent]);
-
const sanitizeFileName = useCallback((name: string) => {
return name
.replaceAll(/["*/:<>?\\|]/g, '-')
@@ -43,10 +38,10 @@ const HtmlPreviewDrawer = memo<HtmlPreviewDrawerProps>(({ content, open, onClose
}, []);
const onDownload = useCallback(() => {
- const title = extractTitle();
+ const title = extractHtmlTitle(content);
const base = title ? sanitizeFileName(title) : `chat-html-preview-${Date.now()}`;
exportFile(content, `${base}.html`);
- }, [content, extractTitle, sanitizeFileName]);
+ }, [content, sanitizeFileName]);
const extra = (
<Flexbox horizontal align={'center'} gap={8}>
@@ -115,7 +110,7 @@ const HtmlPreviewDrawer = memo<HtmlPreviewDrawerProps>(({ content, open, onClose
showLanguage={false}
style={{ height: '100%', overflow: 'auto' }}
>
- {htmlContent}
+ {content}
</Highlighter>
</Block>
)}
diff --git a/src/components/HtmlPreview/applyBaseUrl.ts b/src/components/HtmlPreview/applyBaseUrl.ts
index f288c136675..f24dbcf6930 100644
--- a/src/components/HtmlPreview/applyBaseUrl.ts
+++ b/src/components/HtmlPreview/applyBaseUrl.ts
@@ -1,104 +1,8 @@
+import { findAttribute, findOpeningTag } from './htmlTagScanner';
+
const escapeHtmlAttribute = (value: string): string =>
value.replaceAll('&', '&amp;').replaceAll('"', '&quot;');
-const isTagNameBoundary = (value: string | undefined): boolean =>
- !value || value === '>' || value === '/' || /\s/.test(value);
-
-const findTagEnd = (content: string, start: number): number => {
- let quote: '"' | "'" | undefined;
-
- for (let index = start + 1; index < content.length; index += 1) {
- const char = content[index];
-
- if (quote) {
- if (char === quote) quote = undefined;
- continue;
- }
-
- if (char === '"' || char === "'") {
- quote = char;
- continue;
- }
-
- if (char === '>') return index + 1;
- }
-
- return -1;
-};
-
-const findOpeningTag = (
- content: string,
- tagName: string,
-): { end: number; start: number; text: string } | undefined => {
- const lowerContent = content.toLowerCase();
- const tagPrefix = `<${tagName}`;
- let searchFrom = 0;
-
- while (searchFrom < content.length) {
- const start = lowerContent.indexOf(tagPrefix, searchFrom);
- if (start === -1) return;
-
- if (!isTagNameBoundary(content[start + tagPrefix.length])) {
- searchFrom = start + tagPrefix.length;
- continue;
- }
-
- const end = findTagEnd(content, start);
- if (end === -1) return;
-
- return { end, start, text: content.slice(start, end) };
- }
-};
-
-const findAttribute = (
- tagText: string,
- attributeName: string,
-): { end: number; start: number; value: string } | undefined => {
- const lowerAttributeName = attributeName.toLowerCase();
- let index = 1;
-
- while (index < tagText.length - 1) {
- while (index < tagText.length && /\s/.test(tagText[index])) index += 1;
-
- const nameStart = index;
- while (index < tagText.length && /[^\s=/>]/.test(tagText[index])) index += 1;
-
- if (nameStart === index) {
- index += 1;
- continue;
- }
-
- const name = tagText.slice(nameStart, index).toLowerCase();
- while (index < tagText.length && /\s/.test(tagText[index])) index += 1;
-
- if (tagText[index] !== '=') continue;
- index += 1;
-
- while (index < tagText.length && /\s/.test(tagText[index])) index += 1;
-
- const valueStart = index;
- const quote = tagText[index] === '"' || tagText[index] === "'" ? tagText[index] : undefined;
-
- if (quote) {
- index += 1;
- const quotedValueStart = index;
- while (index < tagText.length && tagText[index] !== quote) index += 1;
-
- const value = tagText.slice(quotedValueStart, index);
- if (index < tagText.length) index += 1;
-
- if (name === lowerAttributeName) return { end: index, start: nameStart, value };
- continue;
- }
-
- while (index < tagText.length && !/[\s"'=<>`]/.test(tagText[index])) index += 1;
-
- if (name === lowerAttributeName) {
- return { end: index, start: nameStart, value: tagText.slice(valueStart, index) };
- }
- }
-};
-
export const applyHtmlPreviewBaseUrl = (content: string, baseUrl?: string): string => {
if (!baseUrl) return content;
diff --git a/src/components/HtmlPreview/htmlTagScanner.ts b/src/components/HtmlPreview/htmlTagScanner.ts
new file mode 100644
index 00000000000..1e5d4f785b8
--- /dev/null
+++ b/src/components/HtmlPreview/htmlTagScanner.ts
@@ -0,0 +1,103 @@
+const isTagNameBoundary = (value: string | undefined): boolean =>
+ !value || value === '>' || value === '/' || /\s/.test(value);
+
+export const findTagEnd = (content: string, start: number): number => {
+ let quote: '"' | "'" | undefined;
+
+ for (let index = start + 1; index < content.length; index += 1) {
+ const char = content[index];
+
+ if (quote) {
+ if (char === quote) quote = undefined;
+ continue;
+ }
+
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+
+ if (char === '>') return index + 1;
+ }
+
+ return -1;
+};
+
+export const findOpeningTag = (
+ content: string,
+ tagName: string,
+): { end: number; start: number; text: string } | undefined => {
+ const lowerContent = content.toLowerCase();
+ const tagPrefix = `<${tagName}`;
+ let searchFrom = 0;
+
+ while (searchFrom < content.length) {
+ const start = lowerContent.indexOf(tagPrefix, searchFrom);
+ if (start === -1) return;
+
+ if (!isTagNameBoundary(content[start + tagPrefix.length])) {
+ searchFrom = start + tagPrefix.length;
+ continue;
+ }
+
+ const end = findTagEnd(content, start);
+ if (end === -1) return;
+
+ return { end, start, text: content.slice(start, end) };
+ }
+};
+
+export const findAttribute = (
+ tagText: string,
+ attributeName: string,
+): { end: number; start: number; value: string } | undefined => {
+ const lowerAttributeName = attributeName.toLowerCase();
+ let index = 1;
+
+ while (index < tagText.length - 1) {
+ while (index < tagText.length && /\s/.test(tagText[index])) index += 1;
+
+ const nameStart = index;
+ while (index < tagText.length && /[^\s=/>]/.test(tagText[index])) index += 1;
+
+ if (nameStart === index) {
+ index += 1;
+ continue;
+ }
+
+ const name = tagText.slice(nameStart, index).toLowerCase();
+ while (index < tagText.length && /\s/.test(tagText[index])) index += 1;
+
+ if (tagText[index] !== '=') continue;
+ index += 1;
+
+ while (index < tagText.length && /\s/.test(tagText[index])) index += 1;
+
+ const valueStart = index;
+ const quote = tagText[index] === '"' || tagText[index] === "'" ? tagText[index] : undefined;
+
+ if (quote) {
+ index += 1;
+ const quotedValueStart = index;
+ while (index < tagText.length && tagText[index] !== quote) index += 1;
+
+ const value = tagText.slice(quotedValueStart, index);
+ if (index < tagText.length) index += 1;
+
+ if (name === lowerAttributeName) return { end: index, start: nameStart, value };
+ continue;
+ }
+
+ while (index < tagText.length && !/[\s"'=<>`]/.test(tagText[index])) index += 1;
+
+ if (name === lowerAttributeName) {
+ return { end: index, start: nameStart, value: tagText.slice(valueStart, index) };
+ }
+ }
+};
+
+export const extractHtmlTitle = (html: string): string | undefined => {
+ const match = html.match(/<title>([\S\s]*?)<\/title>/i);
+ const title = match?.[1]?.replaceAll(/\s+/g, ' ').trim();
+ return title || undefined;
+};
diff --git a/src/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx b/src/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx
index b614417fab3..9b22c15e44f 100644
--- a/src/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx
+++ b/src/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx
@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { useGlobalStore } from '@/store/global';
import { initialState } from '@/store/global/initialState';
+import { useUserStore } from '@/store/user';
import Files from '../index';
@@ -173,9 +174,21 @@ vi.mock('@/services/projectFile', () => ({
},
}));
+vi.mock('@/business/client/features/WorkspaceHtmlArtifactPublish', () => ({
+ useWorkspaceHtmlArtifactPublish: () => ({
+ available: true,
+ getExisting: async () => null,
+ publish: async () => ({}),
+ }),
+}));
+
vi.mock('@/store/chat', () => ({
useChatStore: (selector: (s: Record<string, unknown>) => unknown) =>
- selector({ openLocalFile: openLocalFileMock }),
+ selector({
+ activeAgentId: 'agt_1',
+ activeTopicId: 'tpc_1',
+ openLocalFile: openLocalFileMock,
+ }),
}));
const messageSpy = vi.hoisted(() => ({ warning: vi.fn() }));
@@ -324,6 +337,78 @@ describe('Files — reveal request integration', () => {
);
});
+ it('adds a publish action only for HTML files when artifact deployment is enabled', () => {
+ const previousLab = useUserStore.getState().preference.lab;
+ useUserStore.setState({
+ preference: {
+ ...useUserStore.getState().preference,
+ lab: { ...previousLab, enableArtifactDeployment: true },
+ },
+ });
+
+ try {
+ render(<Files workingDirectory="/repo" />);
+
+ const getContextMenuItems = explorerTreeProps.current?.getContextMenuItems as (
+ node: unknown,
+ ) => { key: string }[];
+
+ expect(
+ getContextMenuItems({
+ data: {
+ isDirectory: false,
+ name: 'index.html',
+ path: '/repo/index.html',
+ relativePath: 'index.html',
+ },
+ id: 'index.html',
+ isFolder: false,
+ }).map((item) => item.key),
+ ).toEqual([
+ 'open',
+ 'publish',
+ 'divider-reveal',
+ 'show-in-system',
+ 'divider-copy',
+ 'copy-absolute-path',
+ 'copy-relative-path',
+ ]);
+
+ expect(
+ getContextMenuItems({
+ data: {
+ isDirectory: false,
+ name: 'root.ts',
+ path: '/repo/root.ts',
+ relativePath: 'root.ts',
+ },
+ id: 'root.ts',
+ isFolder: false,
+ }).map((item) => item.key),
+ ).not.toContain('publish');
+
+ expect(
+ getContextMenuItems({
+ data: {
+ isDirectory: true,
+ name: 'site.html',
+ path: '/repo/site.html',
+ relativePath: 'site.html/',
+ },
+ id: 'site.html/',
+ isFolder: true,
+ }).map((item) => item.key),
+ ).not.toContain('publish');
+ } finally {
+ useUserStore.setState({
+ preference: {
+ ...useUserStore.getState().preference,
+ lab: previousLab,
+ },
+ });
+ }
+ });
+
it('opens file previews with the indexed project root as the approved workspace root', () => {
render(<Files workingDirectory="/repo/packages/app" />);
diff --git a/src/features/Conversation/WorkingSidebar/Files/index.tsx b/src/features/Conversation/WorkingSidebar/Files/index.tsx
index 7616855d564..6a722c31966 100644
--- a/src/features/Conversation/WorkingSidebar/Files/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/Files/index.tsx
@@ -28,6 +28,7 @@ import {
HIDE_POINTER_FOCUS_RING_CSS,
} from '@/features/ExplorerTree';
import type { ExplorerTreeHandle } from '@/features/ExplorerTree/types';
+import { usePublishWorkspaceHtmlFromFile } from '@/features/Portal/LocalFile/usePublishWorkspaceHtmlFromFile';
import type { NativeContextMenuItem } from '@/libs/contextMenu/types';
import { localFileService } from '@/services/electron/localFileService';
import { projectFileService } from '@/services/projectFile';
@@ -290,6 +291,10 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
}, [revealRequest?.nonce, nodes]);
const openLocalFile = useChatStore((s) => s.openLocalFile);
+ const { canOfferFile, publishFile } = usePublishWorkspaceHtmlFromFile({
+ deviceId,
+ workingDirectory: projectRoot,
+ });
const openNode = useCallback(
(node: ExplorerTreeNode<ProjectFileIndexEntry>) => {
@@ -336,40 +341,51 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
const { path, relativePath } = node.data;
const isDirty = dirtyFilePaths.has(relativePath);
+ const items: NativeContextMenuItem[] = [];
+
+ if (!isRemote) {
+ items.push({
+ key: 'open',
+ label: t('workingPanel.files.open'),
+ onClick: () => openNode(node),
+ });
+ }
+
+ if (canOfferFile(path, !!node.isFolder)) {
+ items.push({
+ key: 'publish',
+ label: t('workingPanel.localFile.publish.action'),
+ sfSymbol: 'square.and.arrow.up',
+ onClick: () => {
+ void publishFile(path);
+ },
+ });
+ }
+
+ if (!isRemote) {
+ items.push(
+ { key: 'divider-reveal', type: 'divider' as const },
+ {
+ key: 'show-in-system',
+ label: t('workingPanel.files.showInSystem'),
+ onClick: () => void localFileService.openFileFolder(path),
+ },
+ );
+ }
+
+ if (isDirty) {
+ items.push({
+ key: 'show-in-review',
+ label: t('workingPanel.files.showInReview'),
+ onClick: () => setWorkingSidebarTab('review'),
+ });
+ }
- // OS-level actions (open in app / reveal in Finder) only work on the local
- // machine — omit them for a remote device.
- const localActions: NativeContextMenuItem[] = isRemote
- ? []
- : [
- {
- key: 'open',
- label: t('workingPanel.files.open'),
- onClick: () => openNode(node),
- },
- { key: 'divider-reveal', type: 'divider' as const },
- {
- key: 'show-in-system',
- label: t('workingPanel.files.showInSystem'),
- onClick: () => void localFileService.openFileFolder(path),
- },
- ];
-
- const reviewActions: NativeContextMenuItem[] = isDirty
- ? [
- {
- key: 'show-in-review',
- label: t('workingPanel.files.showInReview'),
- onClick: () => setWorkingSidebarTab('review'),
- },
- ]
- : [];
-
- const before = [...localActions, ...reviewActions];
-
- return [
- ...before,
- ...(before.length > 0 ? [{ key: 'divider-copy', type: 'divider' as const }] : []),
+ if (items.length > 0) {
+ items.push({ key: 'divider-copy', type: 'divider' as const });
+ }
+
+ items.push(
{
key: 'copy-absolute-path',
label: t('workingPanel.files.copyAbsolutePath'),
@@ -388,9 +404,11 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
},
sfSymbol: 'doc.on.doc',
},
- ];
+ );
+
+ return items;
},
- [dirtyFilePaths, isRemote, openNode, setWorkingSidebarTab, t],
+ [canOfferFile, dirtyFilePaths, isRemote, openNode, publishFile, setWorkingSidebarTab, t],
);
const isEmpty = nodes.length === 0;
diff --git a/src/features/Portal/LocalFile/Body.test.tsx b/src/features/Portal/LocalFile/Body.test.tsx
index 86b34f69173..591e6c56ae6 100644
--- a/src/features/Portal/LocalFile/Body.test.tsx
+++ b/src/features/Portal/LocalFile/Body.test.tsx
@@ -88,6 +88,12 @@ vi.mock('./MarkdownImage', () => ({
default: () => null,
}));
+vi.mock('./PublishHtmlArtifactButton', () => ({
+ PublishHtmlArtifactLiveBar: () => null,
+ PublishHtmlArtifactProvider: ({ children }: { children: ReactNode }) => children,
+ PublishHtmlArtifactTrigger: () => null,
+}));
+
const mockClearPortalStack = vi.hoisted(() => vi.fn());
const mockChatState = vi.hoisted(() => ({
current: {} as Record<PropertyKey, unknown>,
diff --git a/src/features/Portal/LocalFile/Body.tsx b/src/features/Portal/LocalFile/Body.tsx
index ed8dc24aacd..69685d06481 100644
--- a/src/features/Portal/LocalFile/Body.tsx
+++ b/src/features/Portal/LocalFile/Body.tsx
@@ -25,6 +25,11 @@ import {
import { extensionToLanguage, getFileExtension } from './Body.helpers';
import MarkdownImage from './MarkdownImage';
+import {
+ PublishHtmlArtifactLiveBar,
+ PublishHtmlArtifactProvider,
+ PublishHtmlArtifactTrigger,
+} from './PublishHtmlArtifactButton';
// Deferred: pulls in react-pdf, only needed once a binary document is opened.
const DocumentPreview = lazy(() => import('./DocumentPreview'));
@@ -162,6 +167,7 @@ interface TextPreviewPaneProps {
readOnly?: boolean;
reloading?: boolean;
resourceBaseUrl?: string;
+ sandboxTopicId?: string;
workingDirectory: string;
}
@@ -178,6 +184,7 @@ const TextPreviewPane = memo<TextPreviewPaneProps>(
readOnly = false,
reloading = false,
resourceBaseUrl,
+ sandboxTopicId,
workingDirectory,
}) => {
const { t } = useTranslation('chat');
@@ -277,75 +284,93 @@ const TextPreviewPane = memo<TextPreviewPaneProps>(
}, [onReload]);
return (
- <Flexbox
- flex={1}
- height={'100%'}
- style={{ minHeight: 0, overflow: 'hidden', position: 'relative' }}
+ <PublishHtmlArtifactProvider
+ content={editingValue}
+ deviceId={deviceId}
+ filePath={filePath}
+ sandboxTopicId={sandboxTopicId}
+ topicId={activeTopicId}
+ workingDirectory={workingDirectory}
>
- {canRender && (
- <Flexbox horizontal align={'center'} className={floatingControlsStyles.container} gap={4}>
- {isHtml && (
- <ActionIcon
- icon={RefreshCwIcon}
- loading={reloading}
- size={'small'}
- title={t('workingPanel.localFile.preview.reload')}
- onClick={handleReloadPreview}
- />
+ <Flexbox flex={1} height={'100%'} style={{ minHeight: 0, overflow: 'hidden' }}>
+ <PublishHtmlArtifactLiveBar />
+ <Flexbox
+ flex={1}
+ height={'100%'}
+ style={{ minHeight: 0, overflow: 'hidden', position: 'relative' }}
+ >
+ {canRender && (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={floatingControlsStyles.container}
+ gap={4}
+ >
+ {isHtml && (
+ <ActionIcon
+ icon={RefreshCwIcon}
+ loading={reloading}
+ size={'small'}
+ title={t('workingPanel.localFile.preview.reload')}
+ onClick={handleReloadPreview}
+ />
+ )}
+
+ <Tabs
+ activeKey={mode}
+ size={'small'}
+ items={[
+ {
+ icon: <Icon icon={EyeIcon} />,
+ key: 'render',
+ label: t('workingPanel.localFile.preview.render'),
+ },
+ {
+ icon: <Icon icon={CodeIcon} />,
+ key: 'raw',
+ label: t(
+ isHtml
+ ? 'workingPanel.localFile.preview.source'
+ : 'workingPanel.localFile.preview.raw',
+ ),
+ },
+ ]}
+ onChange={(key) => setMode(key as TextPreviewMode)}
+ />
+ <PublishHtmlArtifactTrigger />
+ </Flexbox>
)}
-
- <Tabs
- activeKey={mode}
- size={'small'}
- items={[
- {
- icon: <Icon icon={EyeIcon} />,
- key: 'render',
- label: t('workingPanel.localFile.preview.render'),
- },
- {
- icon: <Icon icon={CodeIcon} />,
- key: 'raw',
- label: t(
- isHtml
- ? 'workingPanel.localFile.preview.source'
- : 'workingPanel.localFile.preview.raw',
- ),
- },
- ]}
- onChange={(key) => setMode(key as TextPreviewMode)}
- />
+ <div style={{ flex: 1, minHeight: 0, overflow: showHtmlPreview ? 'hidden' : 'auto' }}>
+ {isMarkdown && mode === 'render' ? (
+ <>
+ <SkillFrontmatterPreviewCard metadata={frontmatterMetadata} />
+ <Markdown
+ components={markdownComponents}
+ style={{ paddingBlock: 8, paddingInline: 12 }}
+ >
+ {body}
+ </Markdown>
+ </>
+ ) : showHtmlPreview ? (
+ <InlineHtmlPreview
+ baseUrl={resourceBaseUrl}
+ content={editingValue}
+ key={`${filePath}:${htmlPreviewRevision}`}
+ />
+ ) : (
+ <CodeEditorPane
+ language={extensionToLanguage(ext)}
+ readOnly={readOnly}
+ style={{ fontSize: 12, minHeight: '100%' }}
+ value={editingValue}
+ onChange={readOnly ? undefined : handleCodeChange}
+ onSave={readOnly ? undefined : handleSave}
+ />
+ )}
+ </div>
</Flexbox>
- )}
- <div style={{ flex: 1, minHeight: 0, overflow: showHtmlPreview ? 'hidden' : 'auto' }}>
- {isMarkdown && mode === 'render' ? (
- <>
- <SkillFrontmatterPreviewCard metadata={frontmatterMetadata} />
- <Markdown
- components={markdownComponents}
- style={{ paddingBlock: 8, paddingInline: 12 }}
- >
- {body}
- </Markdown>
- </>
- ) : showHtmlPreview ? (
- <InlineHtmlPreview
- baseUrl={resourceBaseUrl}
- content={editingValue}
- key={`${filePath}:${htmlPreviewRevision}`}
- />
- ) : (
- <CodeEditorPane
- language={extensionToLanguage(ext)}
- readOnly={readOnly}
- style={{ fontSize: 12, minHeight: '100%' }}
- value={editingValue}
- onChange={readOnly ? undefined : handleCodeChange}
- onSave={readOnly ? undefined : handleSave}
- />
- )}
- </div>
- </Flexbox>
+ </Flexbox>
+ </PublishHtmlArtifactProvider>
);
},
);
@@ -503,6 +528,7 @@ const ActiveFileView = memo<ActiveFileViewProps>(
readOnly={!!sandboxTopicId}
reloading={isValidating}
resourceBaseUrl={preview.resourceBaseUrl}
+ sandboxTopicId={sandboxTopicId}
workingDirectory={workingDirectory}
onReload={handleReload}
onSaved={handleSavedContent}
diff --git a/src/features/Portal/LocalFile/PublishHtmlArtifactButton.test.ts b/src/features/Portal/LocalFile/PublishHtmlArtifactButton.test.ts
new file mode 100644
index 00000000000..dee0953a56b
--- /dev/null
+++ b/src/features/Portal/LocalFile/PublishHtmlArtifactButton.test.ts
@@ -0,0 +1,177 @@
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { usePublishHtmlArtifactModel } from './PublishHtmlArtifactButton';
+import { createWorkspaceHtmlArtifactIdentifier } from './workspaceHtmlPath';
+
+vi.mock('antd-style', () => ({
+ createStaticStyles: () => ({ bar: 'bar', url: 'url' }),
+ cssVar: {
+ colorBgContainer: 'var(--color-bg-container)',
+ colorBorderSecondary: 'var(--color-border-secondary)',
+ fontFamilyCode: 'monospace',
+ fontSizeSM: 12,
+ },
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ ActionIcon: () => null,
+ CopyButton: () => null,
+ Flexbox: () => null,
+ Tag: () => null,
+ Text: () => null,
+}));
+
+vi.mock('@lobehub/ui/base-ui', () => ({
+ Button: () => null,
+ toast: { error: vi.fn(), success: vi.fn() },
+}));
+
+vi.mock('@/components/HtmlPreview', () => ({
+ isHtmlFile: ({ path }: { path: string }) => path.endsWith('.html'),
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (state: { activeAgentId: string }) => unknown) =>
+ selector({ activeAgentId: 'agt_1' }),
+}));
+
+vi.mock('@/store/user', () => ({
+ useUserStore: (selector: (state: unknown) => unknown) => selector({}),
+}));
+
+vi.mock('@/store/user/selectors', () => ({
+ labPreferSelectors: { enableArtifactDeployment: () => true },
+}));
+
+const getExisting = vi.hoisted(() => vi.fn());
+const publish = vi.hoisted(() => vi.fn());
+
+vi.mock('@/business/client/features/WorkspaceHtmlArtifactPublish', () => ({
+ useWorkspaceHtmlArtifactPublish: () => ({ available: true, getExisting, publish }),
+}));
+
+const prepareWorkspaceHtmlPublish = vi.hoisted(() => vi.fn());
+
+vi.mock('./prepareWorkspaceHtmlPublish', () => ({
+ notifyWorkspaceHtmlPublishBlocked: vi.fn(),
+ prepareWorkspaceHtmlPublish,
+ publishPreparedWorkspaceHtml: async ({
+ plan,
+ publish: run,
+ topicId,
+ }: {
+ plan: { gathered: { identifier: string } };
+ publish: (input: { identifier: string; topicId: string }) => Promise<unknown>;
+ topicId: string;
+ }) => {
+ try {
+ return await run({ identifier: plan.gathered.identifier, topicId });
+ } catch {
+ return undefined;
+ }
+ },
+}));
+
+vi.mock('./PublishHtmlArtifactConfirm', () => ({
+ openWorkspaceHtmlPublishConfirm: ({ onOk }: { onOk: () => void }) => onOk(),
+}));
+
+const modelProps = (filePath: string, workingDirectory: string) => ({
+ content: '<html></html>',
+ filePath,
+ topicId: 'tpc_1',
+ workingDirectory,
+});
+
+const gatheredFor = (relativePath: string) => ({
+ entryPath: relativePath,
+ files: [],
+ identifier: createWorkspaceHtmlArtifactIdentifier(relativePath),
+ missing: [],
+ oversized: [],
+ remotes: [],
+ title: 'Demo',
+ totalBytes: 0,
+});
+
+describe('usePublishHtmlArtifactModel', () => {
+ beforeEach(() => {
+ getExisting.mockReset().mockResolvedValue(null);
+ publish.mockReset();
+ prepareWorkspaceHtmlPublish.mockReset();
+ });
+
+ it('looks up deployments with the same canonical identifier gathering publishes', async () => {
+ renderHook(() =>
+ usePublishHtmlArtifactModel(modelProps('/private/tmp/ws/pages/index.html', '/tmp/ws')),
+ );
+
+ await waitFor(() => {
+ expect(getExisting).toHaveBeenCalledWith({
+ identifier: createWorkspaceHtmlArtifactIdentifier('pages/index.html'),
+ topicId: 'tpc_1',
+ });
+ });
+ });
+
+ it('marks the current file live once its publish completes', async () => {
+ prepareWorkspaceHtmlPublish.mockResolvedValue({
+ gathered: gatheredFor('a.html'),
+ packed: { html: '', sidecars: [] },
+ });
+ publish.mockResolvedValue({ publicUrl: 'https://pub.example.com/a' });
+
+ const { result } = renderHook(() =>
+ usePublishHtmlArtifactModel(modelProps('/ws/a.html', '/ws')),
+ );
+ act(() => {
+ result.current.handlePublish();
+ });
+
+ await waitFor(() => {
+ expect(result.current.publicUrl).toBe('https://pub.example.com/a');
+ });
+ expect(result.current.showLiveBar).toBe(true);
+ });
+
+ it('discards a publish result that finishes after switching to another file', async () => {
+ prepareWorkspaceHtmlPublish.mockResolvedValue({
+ gathered: gatheredFor('a.html'),
+ packed: { html: '', sidecars: [] },
+ });
+
+ let resolvePublish: (value: { publicUrl: string }) => void = () => {};
+ publish.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolvePublish = resolve;
+ }),
+ );
+
+ const { rerender, result } = renderHook((props) => usePublishHtmlArtifactModel(props), {
+ initialProps: modelProps('/ws/a.html', '/ws'),
+ });
+ act(() => {
+ result.current.handlePublish();
+ });
+ await waitFor(() => {
+ expect(publish).toHaveBeenCalled();
+ });
+
+ rerender(modelProps('/ws/b.html', '/ws'));
+
+ act(() => {
+ resolvePublish({ publicUrl: 'https://pub.example.com/a' });
+ });
+ await waitFor(() => {
+ expect(getExisting).toHaveBeenCalledTimes(2);
+ });
+
+ expect(result.current.publicUrl).toBeUndefined();
+ });
+});
diff --git a/src/features/Portal/LocalFile/PublishHtmlArtifactButton.tsx b/src/features/Portal/LocalFile/PublishHtmlArtifactButton.tsx
new file mode 100644
index 00000000000..caf4044b863
--- /dev/null
+++ b/src/features/Portal/LocalFile/PublishHtmlArtifactButton.tsx
@@ -0,0 +1,256 @@
+import { ActionIcon, CopyButton, Flexbox, Tag, Text } from '@lobehub/ui';
+import { Button, toast } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { ExternalLinkIcon } from 'lucide-react';
+import type { ReactNode } from 'react';
+import { createContext, use, useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { WorkspaceHtmlArtifactExisting } from '@/business/client/features/WorkspaceHtmlArtifactPublish';
+import { useWorkspaceHtmlArtifactPublish } from '@/business/client/features/WorkspaceHtmlArtifactPublish';
+import { isHtmlFile } from '@/components/HtmlPreview';
+import { useChatStore } from '@/store/chat';
+import { useUserStore } from '@/store/user';
+import { labPreferSelectors } from '@/store/user/selectors';
+
+import {
+ notifyWorkspaceHtmlPublishBlocked,
+ prepareWorkspaceHtmlPublish,
+ publishPreparedWorkspaceHtml,
+ type ReadyWorkspaceHtmlPublishPlan,
+} from './prepareWorkspaceHtmlPublish';
+import { openWorkspaceHtmlPublishConfirm } from './PublishHtmlArtifactConfirm';
+import { workspaceHtmlArtifactIdentifierForFile } from './workspaceHtmlPath';
+
+interface PublishHtmlArtifactButtonProps {
+ children?: ReactNode;
+ content: string;
+ deviceId?: string;
+ filePath: string;
+ sandboxTopicId?: string;
+ topicId?: string | null;
+ workingDirectory: string;
+}
+
+interface PublishHtmlArtifactModel {
+ busy: 'publishing' | 'scanning' | null;
+ handlePublish: () => void;
+ publicUrl?: string;
+ showLiveBar: boolean;
+ showOverlayTrigger: boolean;
+ topicId?: string | null;
+}
+
+const liveBarStyles = createStaticStyles(({ css }) => ({
+ bar: css`
+ flex-shrink: 0;
+
+ min-width: 0;
+ padding-block: 8px;
+ padding-inline: 12px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+
+ background: ${cssVar.colorBgContainer};
+ `,
+ url: css`
+ min-width: 0;
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: ${cssVar.fontSizeSM}px;
+ `,
+}));
+
+const PublishHtmlArtifactContext = createContext<PublishHtmlArtifactModel | null>(null);
+
+export const usePublishHtmlArtifactModel = ({
+ content,
+ deviceId,
+ filePath,
+ sandboxTopicId,
+ topicId,
+ workingDirectory,
+}: Omit<PublishHtmlArtifactButtonProps, 'children'>): PublishHtmlArtifactModel => {
+ const { t } = useTranslation(['chat', 'portal', 'common']);
+ const enabled = useUserStore(labPreferSelectors.enableArtifactDeployment);
+ const agentId = useChatStore((s) => s.activeAgentId);
+ const { available, getExisting, publish } = useWorkspaceHtmlArtifactPublish();
+ const [busy, setBusy] = useState<'publishing' | 'scanning' | null>(null);
+ const [existing, setExisting] = useState<WorkspaceHtmlArtifactExisting | null>(null);
+
+ const isHtml = isHtmlFile({ path: filePath });
+ const identifier = useMemo(
+ () => workspaceHtmlArtifactIdentifierForFile(filePath, workingDirectory),
+ [filePath, workingDirectory],
+ );
+
+ const scopeKey = `${topicId ?? ''}:${identifier}`;
+ const scopeRef = useRef(scopeKey);
+ useEffect(() => {
+ scopeRef.current = scopeKey;
+ }, [scopeKey]);
+
+ useEffect(() => {
+ setExisting(null);
+ if (!available || !enabled || !isHtml || !topicId) return;
+
+ let cancelled = false;
+ void getExisting({ identifier, topicId }).then((result) => {
+ if (!cancelled) setExisting(result);
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [available, enabled, getExisting, identifier, isHtml, topicId]);
+
+ const runPublish = useCallback(
+ async (plan: ReadyWorkspaceHtmlPublishPlan) => {
+ if (!topicId) return;
+
+ const requestScope = scopeRef.current;
+ setBusy('publishing');
+ try {
+ const result = await publishPreparedWorkspaceHtml({ agentId, plan, publish, topicId });
+ // Publishing may outlive a file/topic switch under the same provider;
+ // a completion for a previous scope must not label the current file.
+ if (!result || scopeRef.current !== requestScope) return;
+ setExisting((previous) => ({
+ identifier: plan.gathered.identifier,
+ publicUrl: result.publicUrl ?? previous?.publicUrl,
+ }));
+ } finally {
+ setBusy(null);
+ }
+ },
+ [agentId, publish, topicId],
+ );
+
+ const handlePublish = useCallback(async () => {
+ if (!topicId || busy) return;
+
+ setBusy('scanning');
+ try {
+ const plan = await prepareWorkspaceHtmlPublish({
+ content,
+ deviceId,
+ filePath,
+ sandboxTopicId,
+ workingDirectory,
+ });
+
+ if ('blocked' in plan) {
+ notifyWorkspaceHtmlPublishBlocked(plan);
+ return;
+ }
+
+ openWorkspaceHtmlPublishConfirm({
+ hasExisting: !!existing,
+ plan,
+ onOk: () => {
+ void runPublish(plan);
+ },
+ });
+ } catch {
+ toast.error(t('workingPanel.localFile.publish.failed'));
+ } finally {
+ setBusy((current) => (current === 'scanning' ? null : current));
+ }
+ }, [
+ busy,
+ content,
+ deviceId,
+ existing,
+ filePath,
+ runPublish,
+ sandboxTopicId,
+ t,
+ topicId,
+ workingDirectory,
+ ]);
+
+ const publicUrl = existing?.publicUrl;
+ const visible = available && enabled && isHtml;
+
+ return {
+ busy,
+ handlePublish,
+ publicUrl,
+ showLiveBar: visible && !!publicUrl,
+ showOverlayTrigger: visible && !publicUrl,
+ topicId,
+ };
+};
+
+export const PublishHtmlArtifactProvider = ({
+ children,
+ ...input
+}: PublishHtmlArtifactButtonProps) => {
+ const model = usePublishHtmlArtifactModel(input);
+
+ return <PublishHtmlArtifactContext value={model}>{children}</PublishHtmlArtifactContext>;
+};
+
+const PublishAction = () => {
+ const { t } = useTranslation('chat');
+ const model = use(PublishHtmlArtifactContext);
+ if (!model) return null;
+
+ return (
+ <Button
+ disabled={!model.topicId}
+ loading={!!model.busy}
+ size={'small'}
+ title={model.topicId ? undefined : t('workingPanel.localFile.publish.noTopic')}
+ onClick={() => {
+ void model.handlePublish();
+ }}
+ >
+ {t(
+ model.publicUrl
+ ? 'workingPanel.localFile.publish.version'
+ : 'workingPanel.localFile.publish.action',
+ )}
+ </Button>
+ );
+};
+
+export const PublishHtmlArtifactLiveBar = () => {
+ const { t } = useTranslation(['chat', 'portal']);
+ const model = use(PublishHtmlArtifactContext);
+ if (!model?.showLiveBar || !model.publicUrl) return null;
+
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={liveBarStyles.bar}
+ gap={8}
+ justify={'space-between'}
+ >
+ <Flexbox horizontal align={'center'} flex={1} gap={8} style={{ minWidth: 0 }}>
+ <Tag color={'success'} style={{ marginInlineEnd: 0 }}>
+ {t('workingPanel.localFile.publish.live')}
+ </Tag>
+ <Text ellipsis className={liveBarStyles.url}>
+ {model.publicUrl}
+ </Text>
+ <CopyButton content={model.publicUrl} size={'small'} />
+ <ActionIcon
+ icon={ExternalLinkIcon}
+ size={'small'}
+ title={t('artifacts.deploy.open', { ns: 'portal' })}
+ onClick={() => window.open(model.publicUrl, '_blank', 'noopener,noreferrer')}
+ />
+ </Flexbox>
+ <Flexbox flex={'none'}>
+ <PublishAction />
+ </Flexbox>
+ </Flexbox>
+ );
+};
+
+export const PublishHtmlArtifactTrigger = () => {
+ const model = use(PublishHtmlArtifactContext);
+ if (!model?.showOverlayTrigger) return null;
+
+ return <PublishAction />;
+};
diff --git a/src/features/Portal/LocalFile/PublishHtmlArtifactConfirm.tsx b/src/features/Portal/LocalFile/PublishHtmlArtifactConfirm.tsx
new file mode 100644
index 00000000000..1d7fe5a0710
--- /dev/null
+++ b/src/features/Portal/LocalFile/PublishHtmlArtifactConfirm.tsx
@@ -0,0 +1,184 @@
+import { Accordion, AccordionItem, Flexbox, Text } from '@lobehub/ui';
+import { Button, createModal, ScrollArea, useModalContext } from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
+import { useTranslation } from 'react-i18next';
+
+import type { ReadyWorkspaceHtmlPublishPlan } from './prepareWorkspaceHtmlPublish';
+import { WORKSPACE_HTML_ARTIFACT_INLINE_MAX_BYTES } from './readWorkspaceAsset';
+
+const CONFIRM_BODY_MAX_HEIGHT = 'min(52vh, 360px)';
+
+const PathList = ({ items }: { items: string[] }) => (
+ <Flexbox gap={4}>
+ {items.map((item) => (
+ <Text key={item} style={{ wordBreak: 'break-all' }} type={'secondary'}>
+ {item}
+ </Text>
+ ))}
+ </Flexbox>
+);
+
+interface PublishHtmlArtifactConfirmContentProps {
+ inlinedPaths: string[];
+ inlineLimit: string;
+ missing: string[];
+ oversized: string[];
+ remotes: string[];
+ uploadedPaths: string[];
+}
+
+const PublishHtmlArtifactConfirmContent = ({
+ inlineLimit,
+ inlinedPaths,
+ missing,
+ oversized,
+ remotes,
+ uploadedPaths,
+}: PublishHtmlArtifactConfirmContentProps) => {
+ const { t } = useTranslation('chat');
+ const showDetails = [inlinedPaths, uploadedPaths, missing, oversized, remotes].some(
+ (list) => list.length > 0,
+ );
+
+ return (
+ <ScrollArea
+ disableContentFit
+ scrollFade
+ style={{ maxHeight: CONFIRM_BODY_MAX_HEIGHT, overflow: 'hidden' }}
+ viewportProps={{ style: { height: 'auto', maxHeight: CONFIRM_BODY_MAX_HEIGHT } }}
+ >
+ <Flexbox gap={8} style={{ paddingBlock: 12, paddingInline: 16 }}>
+ <Text>{t('workingPanel.localFile.publish.privacy')}</Text>
+ {showDetails && (
+ <Accordion defaultExpandedKeys={[]} gap={0} variant={'borderless'}>
+ <AccordionItem
+ defaultExpand={false}
+ indicatorPlacement={'start'}
+ itemKey={'details'}
+ paddingBlock={4}
+ paddingInline={0}
+ title={
+ <Text fontSize={12} type={'secondary'} weight={500}>
+ {t('workingPanel.localFile.publish.details')}
+ </Text>
+ }
+ >
+ <Flexbox gap={8} paddingBlock={'4px 0'}>
+ {inlinedPaths.length > 0 && (
+ <>
+ <Text>
+ {t('workingPanel.localFile.publish.inline', {
+ count: inlinedPaths.length,
+ limit: inlineLimit,
+ })}
+ </Text>
+ <PathList items={inlinedPaths} />
+ </>
+ )}
+ {uploadedPaths.length > 0 && (
+ <>
+ <Text>
+ {t('workingPanel.localFile.publish.upload', { count: uploadedPaths.length })}
+ </Text>
+ <PathList items={uploadedPaths} />
+ </>
+ )}
+ {missing.length > 0 && (
+ <Text type={'secondary'}>
+ {t('workingPanel.localFile.publish.missing', { list: missing.join(', ') })}
+ </Text>
+ )}
+ {oversized.length > 0 && (
+ <Text type={'secondary'}>
+ {t('workingPanel.localFile.publish.oversized', { list: oversized.join(', ') })}
+ </Text>
+ )}
+ {remotes.length > 0 && (
+ <>
+ <Text>{t('workingPanel.localFile.publish.remotes')}</Text>
+ <PathList items={remotes} />
+ </>
+ )}
+ <Text type={'secondary'}>{t('workingPanel.localFile.publish.dynamic')}</Text>
+ </Flexbox>
+ </AccordionItem>
+ </Accordion>
+ )}
+ <Text type={'secondary'}>{t('workingPanel.localFile.publish.note')}</Text>
+ </Flexbox>
+ </ScrollArea>
+ );
+};
+
+const PublishHtmlArtifactConfirmFooter = ({
+ okText,
+ onOk,
+}: {
+ okText: string;
+ onOk: () => void;
+}) => {
+ const { t } = useTranslation('common');
+ const { close } = useModalContext();
+
+ return (
+ <Flexbox
+ horizontal
+ gap={8}
+ justify={'flex-end'}
+ style={{ paddingBlock: 12, paddingInline: 16 }}
+ >
+ <Button
+ onClick={() => {
+ close();
+ }}
+ >
+ {t('cancel')}
+ </Button>
+ <Button
+ type={'primary'}
+ onClick={() => {
+ close();
+ onOk();
+ }}
+ >
+ {okText}
+ </Button>
+ </Flexbox>
+ );
+};
+
+export const openWorkspaceHtmlPublishConfirm = ({
+ hasExisting,
+ onOk,
+ plan,
+}: {
+ hasExisting: boolean;
+ onOk: () => void;
+ plan: ReadyWorkspaceHtmlPublishPlan;
+}) => {
+ const okText = t(
+ hasExisting
+ ? 'workingPanel.localFile.publish.version'
+ : 'workingPanel.localFile.publish.action',
+ { ns: 'chat' },
+ );
+
+ createModal({
+ content: (
+ <PublishHtmlArtifactConfirmContent
+ inlineLimit={`${WORKSPACE_HTML_ARTIFACT_INLINE_MAX_BYTES / 1024} KB`}
+ inlinedPaths={plan.packed.inlinedPaths}
+ missing={plan.gathered.missing}
+ oversized={plan.gathered.oversized}
+ remotes={plan.gathered.remotes}
+ uploadedPaths={plan.packed.sidecars.map((file) => file.path)}
+ />
+ ),
+ footer: <PublishHtmlArtifactConfirmFooter okText={okText} onOk={onOk} />,
+ styles: {
+ content: { minHeight: 0, overflow: 'hidden', padding: 0 },
+ },
+ title: t('workingPanel.localFile.publish.confirmTitle', { ns: 'chat' }),
+ width: 420,
+ });
+};
diff --git a/src/features/Portal/LocalFile/collectHtmlLocalResources.test.ts b/src/features/Portal/LocalFile/collectHtmlLocalResources.test.ts
new file mode 100644
index 00000000000..d7bef1217d2
--- /dev/null
+++ b/src/features/Portal/LocalFile/collectHtmlLocalResources.test.ts
@@ -0,0 +1,314 @@
+import { describe, expect, it } from 'vitest';
+
+import { extractHtmlTitle } from '@/components/HtmlPreview/htmlTagScanner';
+
+import { collectJsResourceHrefs, collectLocalResourceRefs } from './collectHtmlLocalResources';
+import {
+ createWorkspaceHtmlArtifactIdentifier,
+ isPathInsideWorkspace,
+ lowestCommonAncestorDirectory,
+ resolveLocalResourceHref,
+ toWorkspaceAbsolutePath,
+ toWorkspaceRelativePath,
+} from './workspaceHtmlPath';
+
+describe('collectLocalResourceRefs', () => {
+ const workingDirectory = '/project';
+ const htmlFilePath = '/project/pages/index.html';
+
+ it('collects static local stylesheet, script, and image refs', () => {
+ const result = collectLocalResourceRefs({
+ content: `
+ <link rel="stylesheet" href="../assets/app.css">
+ <script src="./main.js"></script>
+ <img src="images/logo.png">
+ `,
+ sourceKind: 'html',
+ sourcePath: htmlFilePath,
+ workingDirectory,
+ });
+
+ expect(result.refs.map((ref) => ref.absolutePath).sort()).toEqual([
+ '/project/assets/app.css',
+ '/project/pages/images/logo.png',
+ '/project/pages/main.js',
+ ]);
+ });
+
+ it('collects srcset candidates and inline style urls', () => {
+ const result = collectLocalResourceRefs({
+ content: `
+ <img srcset="img-1x.png 1x, img-2x.png 2x">
+ <div style="background: url('bg.webp')"></div>
+ <style>.hero { background-image: url("../shared/hero.jpg"); }</style>
+ `,
+ sourceKind: 'html',
+ sourcePath: htmlFilePath,
+ workingDirectory,
+ });
+
+ expect(result.refs.map((ref) => ref.absolutePath).sort()).toEqual(
+ [
+ '/project/pages/img-1x.png',
+ '/project/pages/img-2x.png',
+ '/project/pages/bg.webp',
+ '/project/shared/hero.jpg',
+ ].sort(),
+ );
+ });
+
+ it('does not follow navigation links or remote urls', () => {
+ const result = collectLocalResourceRefs({
+ content: `
+ <a href="about.html">About</a>
+ <script src="https://cdn.example.com/app.js"></script>
+ <img src="data:image/png;base64,abc">
+ <img src="#logo">
+ <link rel="stylesheet" href="//cdn.example.com/app.css">
+ `,
+ sourceKind: 'html',
+ sourcePath: htmlFilePath,
+ workingDirectory,
+ });
+
+ expect(result.refs).toEqual([]);
+ expect(result.skipped.map((item) => item.reason).sort()).toEqual([
+ 'empty',
+ 'remote',
+ 'remote',
+ 'remote',
+ ]);
+ });
+
+ it('rejects escaped paths and disallowed extensions', () => {
+ const result = collectLocalResourceRefs({
+ content: `
+ <img src="../../.env">
+ <img src="../secrets/key.pem">
+ `,
+ sourceKind: 'html',
+ sourcePath: htmlFilePath,
+ workingDirectory,
+ });
+
+ expect(result.refs).toEqual([]);
+ expect(result.skipped.map((item) => item.reason).sort()).toEqual(['escape', 'extension']);
+ });
+
+ it('resolves root-relative paths against the working directory', () => {
+ const result = collectLocalResourceRefs({
+ content: '<link rel="stylesheet" href="/assets/app.css">',
+ sourceKind: 'html',
+ sourcePath: htmlFilePath,
+ workingDirectory,
+ });
+
+ expect(result.refs).toEqual([
+ { absolutePath: '/project/assets/app.css', href: '/assets/app.css' },
+ ]);
+ });
+
+ it('treats every ref as remote when html has an absolute base', () => {
+ const result = collectLocalResourceRefs({
+ content: `
+ <base href="https://cdn.example.com/app/">
+ <link rel="stylesheet" href="app.css">
+ <link rel="stylesheet" href="/assets/local.css">
+ `,
+ sourceKind: 'html',
+ sourcePath: htmlFilePath,
+ workingDirectory,
+ });
+
+ expect(result.refs).toEqual([]);
+ expect(result.skipped).toContainEqual({ href: 'app.css', reason: 'remote' });
+ expect(result.skipped).toContainEqual({ href: '/assets/local.css', reason: 'remote' });
+ });
+
+ it('resolves a relative base against the html file', () => {
+ const result = collectLocalResourceRefs({
+ content: `
+ <base href="../shared/">
+ <img src="logo.png">
+ `,
+ sourceKind: 'html',
+ sourcePath: htmlFilePath,
+ workingDirectory,
+ });
+
+ expect(result.refs).toEqual([{ absolutePath: '/project/shared/logo.png', href: 'logo.png' }]);
+ });
+
+ it('collects css url and import refs from the stylesheet directory', () => {
+ const result = collectLocalResourceRefs({
+ content: `
+ @import "./theme.css";
+ body { background: url("../images/bg.png"); }
+ `,
+ sourceKind: 'css',
+ sourcePath: '/project/pages/css/app.css',
+ workingDirectory,
+ });
+
+ expect(result.refs.map((ref) => ref.absolutePath).sort()).toEqual([
+ '/project/pages/css/theme.css',
+ '/project/pages/images/bg.png',
+ ]);
+ });
+
+ it('collects vite-style import.meta.url and root-absolute assets from js', () => {
+ const result = collectLocalResourceRefs({
+ content: `
+ const hero = new URL(\`hero-CLDdwZDr.png\`, import.meta.url);
+ const logo = new URL("react.svg",import.meta.url);
+ const icon = "/icons.svg#documentation-icon";
+ const skip = "https://cdn.example.com/app.js";
+ `,
+ rootDirectory: '/project/dist',
+ sourceKind: 'js',
+ sourcePath: '/project/dist/assets/index.js',
+ workingDirectory,
+ });
+
+ expect(result.refs.map((ref) => ref.absolutePath).sort()).toEqual([
+ '/project/dist/assets/hero-CLDdwZDr.png',
+ '/project/dist/assets/react.svg',
+ '/project/dist/icons.svg',
+ ]);
+ expect(result.skipped).toEqual([]);
+ });
+
+ it('dedupes identical refs but keeps every spelling of the same file', () => {
+ const result = collectLocalResourceRefs({
+ content: '<img src="logo.png"><img src="logo.png"><img src="./logo.png">',
+ sourceKind: 'html',
+ sourcePath: htmlFilePath,
+ workingDirectory,
+ });
+
+ expect(result.refs).toEqual([
+ { absolutePath: '/project/pages/logo.png', href: 'logo.png' },
+ { absolutePath: '/project/pages/logo.png', href: './logo.png' },
+ ]);
+ });
+});
+
+describe('collectJsResourceHrefs', () => {
+ it('reads backtick new URL and strips svg sprite hashes', () => {
+ expect(
+ collectJsResourceHrefs(
+ 'd=``+new URL(`hero-CLDdwZDr.png`,import.meta.url).href;use.href=`/icons.svg#documentation-icon`',
+ ),
+ ).toEqual(['hero-CLDdwZDr.png', '/icons.svg']);
+ });
+});
+
+describe('path helpers', () => {
+ it('keeps workspace containment strict', () => {
+ expect(isPathInsideWorkspace('/project/pages/a.html', '/project')).toBe(true);
+ expect(isPathInsideWorkspace('/project-other/a.html', '/project')).toBe(false);
+ });
+
+ it('treats macOS /private/tmp and /tmp as the same workspace', () => {
+ expect(
+ isPathInsideWorkspace(
+ '/private/tmp/lobe-html-publish-fixture/app.css',
+ '/tmp/lobe-html-publish-fixture',
+ ),
+ ).toBe(true);
+ expect(
+ isPathInsideWorkspace(
+ '/tmp/lobe-html-publish-fixture/app.css',
+ '/private/tmp/lobe-html-publish-fixture',
+ ),
+ ).toBe(true);
+ expect(isPathInsideWorkspace('/private/tmp-other/app.css', '/tmp')).toBe(false);
+
+ expect(
+ resolveLocalResourceHref({
+ href: './app.css',
+ sourcePath: '/private/tmp/lobe-html-publish-fixture/index.html',
+ workingDirectory: '/tmp/lobe-html-publish-fixture',
+ }),
+ ).toEqual({
+ absolutePath: '/private/tmp/lobe-html-publish-fixture/app.css',
+ href: './app.css',
+ kind: 'resolved',
+ });
+
+ expect(
+ toWorkspaceRelativePath(
+ '/private/tmp/lobe-html-publish-fixture/index.html',
+ '/tmp/lobe-html-publish-fixture',
+ ),
+ ).toBe('index.html');
+ expect(
+ toWorkspaceAbsolutePath(
+ '/private/tmp/lobe-html-publish-fixture/index.html',
+ '/tmp/lobe-html-publish-fixture',
+ ),
+ ).toBe('/private/tmp/lobe-html-publish-fixture/index.html');
+ });
+
+ it('computes the lowest common ancestor inside the workspace', () => {
+ expect(
+ lowestCommonAncestorDirectory(
+ ['/project/pages/index.html', '/project/pages/css/app.css'],
+ '/project',
+ ),
+ ).toBe('/project/pages');
+ expect(
+ lowestCommonAncestorDirectory(
+ ['/project/pages/index.html', '/project/shared/logo.png'],
+ '/project',
+ ),
+ ).toBe('/project');
+ });
+
+ it('builds a stable artifact identifier from the html relative path', () => {
+ expect(createWorkspaceHtmlArtifactIdentifier('pages/index.html')).toBe(
+ 'workspace-html-pages-index-html-6afd7f0435',
+ );
+ expect(createWorkspaceHtmlArtifactIdentifier('pages/index.html')).toBe(
+ createWorkspaceHtmlArtifactIdentifier('pages/index.html'),
+ );
+ expect(createWorkspaceHtmlArtifactIdentifier('页面.html')).not.toBe(
+ createWorkspaceHtmlArtifactIdentifier('报告.html'),
+ );
+ expect(createWorkspaceHtmlArtifactIdentifier('a/b.html')).not.toBe(
+ createWorkspaceHtmlArtifactIdentifier('a-b.html'),
+ );
+ });
+
+ it('extracts a title and returns undefined when missing', () => {
+ expect(extractHtmlTitle('<html><title> Demo Page </title></html>')).toBe('Demo Page');
+ expect(extractHtmlTitle('<html></html>')).toBeUndefined();
+ });
+
+ it('resolves windows-style relative hrefs', () => {
+ expect(
+ resolveLocalResourceHref({
+ href: 'assets\\logo.png',
+ sourcePath: 'C:\\repo\\pages\\index.html',
+ workingDirectory: 'C:\\repo',
+ }),
+ ).toEqual({
+ absolutePath: 'C:\\repo\\pages\\assets\\logo.png',
+ href: 'assets\\logo.png',
+ kind: 'resolved',
+ });
+ });
+
+ it('returns the workspace-relative path', () => {
+ expect(toWorkspaceRelativePath('/project/pages/index.html', '/project')).toBe(
+ 'pages/index.html',
+ );
+ });
+
+ it('joins a workspace-relative html path onto the working directory', () => {
+ expect(toWorkspaceAbsolutePath('index.html', '/tmp/site')).toBe('/tmp/site/index.html');
+ expect(toWorkspaceAbsolutePath('/tmp/site/index.html', '/tmp/site')).toBe(
+ '/tmp/site/index.html',
+ );
+ });
+});
diff --git a/src/features/Portal/LocalFile/collectHtmlLocalResources.ts b/src/features/Portal/LocalFile/collectHtmlLocalResources.ts
new file mode 100644
index 00000000000..eb280c240e7
--- /dev/null
+++ b/src/features/Portal/LocalFile/collectHtmlLocalResources.ts
@@ -0,0 +1,376 @@
+import { findAttribute, findOpeningTag, findTagEnd } from '@/components/HtmlPreview/htmlTagScanner';
+
+import { getFileExtension } from './Body.helpers';
+import { parentDirectory, resolveLocalResourceHref } from './workspaceHtmlPath';
+
+const ALLOWED_ASSET_EXTENSIONS = new Set([
+ 'avif',
+ 'bmp',
+ 'cjs',
+ 'css',
+ 'eot',
+ 'gif',
+ 'ico',
+ 'jpeg',
+ 'jpg',
+ 'js',
+ 'json',
+ 'mjs',
+ 'mp3',
+ 'mp4',
+ 'ogg',
+ 'otf',
+ 'png',
+ 'svg',
+ 'ttf',
+ 'wasm',
+ 'wav',
+ 'webm',
+ 'webp',
+ 'woff',
+ 'woff2',
+]);
+
+const HTML_RESOURCE_TAGS = new Set([
+ 'audio',
+ 'embed',
+ 'img',
+ 'link',
+ 'object',
+ 'script',
+ 'source',
+ 'video',
+]);
+
+export type LocalResourceSkipReason = 'empty' | 'escape' | 'extension' | 'remote';
+
+export interface CollectedLocalResourceRef {
+ absolutePath: string;
+ href: string;
+}
+
+export interface SkippedLocalResourceRef {
+ href: string;
+ reason: LocalResourceSkipReason;
+}
+
+export interface CollectLocalResourceResult {
+ refs: CollectedLocalResourceRef[];
+ skipped: SkippedLocalResourceRef[];
+}
+
+const isAllowedAssetPath = (absolutePath: string): boolean => {
+ const extension = getFileExtension(absolutePath).toLowerCase();
+ return ALLOWED_ASSET_EXTENSIONS.has(extension);
+};
+
+export const isCssAssetPath = (path: string): boolean =>
+ getFileExtension(path).toLowerCase() === 'css';
+
+const JS_ASSET_EXTENSIONS = new Set(['cjs', 'js', 'mjs']);
+
+export const isJsAssetPath = (path: string): boolean =>
+ JS_ASSET_EXTENSIONS.has(getFileExtension(path).toLowerCase());
+
+const pushRef = (
+ result: CollectLocalResourceResult,
+ seenRefs: Set<string>,
+ resolved: ReturnType<typeof resolveLocalResourceHref>,
+) => {
+ if (resolved.kind === 'empty') {
+ result.skipped.push({ href: resolved.href, reason: 'empty' });
+ return;
+ }
+
+ if (resolved.kind === 'remote') {
+ result.skipped.push({ href: resolved.href, reason: 'remote' });
+ return;
+ }
+
+ if (resolved.kind === 'escape' || !resolved.absolutePath) {
+ result.skipped.push({ href: resolved.href, reason: 'escape' });
+ return;
+ }
+
+ if (!isAllowedAssetPath(resolved.absolutePath)) {
+ result.skipped.push({ href: resolved.href, reason: 'extension' });
+ return;
+ }
+
+ // Dedupe by (path, href) pair: every distinct spelling of the same file must
+ // survive so packing can rewrite each token, not just the first one.
+ const refKey = `${resolved.absolutePath}\u0000${resolved.href}`;
+ if (seenRefs.has(refKey)) return;
+ seenRefs.add(refKey);
+
+ result.refs.push({ absolutePath: resolved.absolutePath, href: resolved.href });
+};
+
+const splitSrcset = (value: string): string[] =>
+ value
+ .split(',')
+ .map((part) => part.trim().split(/\s+/, 1)[0])
+ .filter(Boolean);
+
+const readQuotedValue = (
+ source: string,
+ start: number,
+): { end: number; value: string } | undefined => {
+ const quote = source[start];
+ if (quote !== '"' && quote !== "'" && quote !== '`') return;
+
+ let index = start + 1;
+ while (index < source.length && source[index] !== quote) {
+ if (quote === '`' && source[index] === '$' && source[index + 1] === '{') return;
+ index += 1;
+ }
+ if (index >= source.length) return;
+
+ return { end: index + 1, value: source.slice(start + 1, index) };
+};
+
+const collectTagAttributeHrefs = (tagText: string): string[] => {
+ const hrefs: string[] = [];
+ for (const attributeName of ['src', 'href', 'poster', 'data']) {
+ const value = findAttribute(tagText, attributeName)?.value;
+ if (value) hrefs.push(value);
+ }
+
+ const srcset = findAttribute(tagText, 'srcset')?.value;
+ if (srcset) hrefs.push(...splitSrcset(srcset));
+
+ return hrefs;
+};
+
+const stripCssComments = (css: string): string => css.replaceAll(/\/\*[\s\S]*?\*\//g, '');
+
+const readCssUrlArgument = (source: string, openParenIndex: number): string | undefined => {
+ let index = openParenIndex + 1;
+ while (index < source.length && /\s/.test(source[index])) index += 1;
+
+ const quoted = readQuotedValue(source, index);
+ if (quoted) return quoted.value.trim();
+
+ const start = index;
+ while (index < source.length && source[index] !== ')' && !/\s/.test(source[index])) index += 1;
+ return source.slice(start, index).trim() || undefined;
+};
+
+export const collectJsResourceHrefs = (js: string): string[] => {
+ const hrefs: string[] = [];
+ const lower = js.toLowerCase();
+ let index = 0;
+
+ while (index < js.length) {
+ const urlIndex = lower.indexOf('new url(', index);
+ if (urlIndex === -1) break;
+
+ let cursor = urlIndex + 8;
+ while (cursor < js.length && /\s/.test(js[cursor])) cursor += 1;
+
+ const quoted = readQuotedValue(js, cursor);
+ if (!quoted) {
+ index = urlIndex + 8;
+ continue;
+ }
+
+ cursor = quoted.end;
+ while (cursor < js.length && /\s/.test(js[cursor])) cursor += 1;
+ if (js[cursor] !== ',') {
+ index = quoted.end;
+ continue;
+ }
+
+ cursor += 1;
+ while (cursor < js.length && /\s/.test(js[cursor])) cursor += 1;
+ if (!lower.startsWith('import.meta.url', cursor)) {
+ index = quoted.end;
+ continue;
+ }
+
+ if (quoted.value) hrefs.push(quoted.value);
+ index = cursor + 15;
+ }
+
+ let quoteIndex = 0;
+ while (quoteIndex < js.length) {
+ const quote = js[quoteIndex];
+ if (quote !== '"' && quote !== "'" && quote !== '`') {
+ quoteIndex += 1;
+ continue;
+ }
+
+ const quoted = readQuotedValue(js, quoteIndex);
+ if (!quoted) {
+ quoteIndex += 1;
+ continue;
+ }
+
+ const href = quoted.value.trim().split(/[?#]/, 1)[0] ?? '';
+ quoteIndex = quoted.end;
+ if (!href.startsWith('/') || href.startsWith('//')) continue;
+ if (!isAllowedAssetPath(href)) continue;
+ hrefs.push(href);
+ }
+
+ return hrefs;
+};
+
+export const collectCssResourceHrefs = (css: string): string[] => {
+ const hrefs: string[] = [];
+ const source = stripCssComments(css);
+ const lower = source.toLowerCase();
+ let index = 0;
+
+ while (index < source.length) {
+ const urlIndex = lower.indexOf('url(', index);
+ const importIndex = lower.indexOf('@import', index);
+ if (urlIndex === -1 && importIndex === -1) break;
+
+ if (urlIndex !== -1 && (importIndex === -1 || urlIndex < importIndex)) {
+ const href = readCssUrlArgument(source, urlIndex + 3);
+ if (href) hrefs.push(href);
+ index = urlIndex + 4;
+ continue;
+ }
+
+ let cursor = importIndex + 7;
+ while (cursor < source.length && /\s/.test(source[cursor])) cursor += 1;
+
+ if (lower.startsWith('url(', cursor)) {
+ const href = readCssUrlArgument(source, cursor + 3);
+ if (href) hrefs.push(href);
+ index = cursor + 4;
+ continue;
+ }
+
+ const quoted = readQuotedValue(source, cursor);
+ if (quoted?.value.trim()) hrefs.push(quoted.value.trim());
+ index = cursor + 1;
+ }
+
+ return hrefs;
+};
+
+const collectInlineStyleHrefs = (html: string): string[] => {
+ const hrefs: string[] = [];
+ const styleTagPattern = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
+ const styleAttrPattern = /\sstyle\s*=\s*(?:"([^"]*)"|'([^']*)')/gi;
+
+ for (const match of html.matchAll(styleTagPattern)) {
+ hrefs.push(...collectCssResourceHrefs(match[1] ?? ''));
+ }
+
+ for (const match of html.matchAll(styleAttrPattern)) {
+ hrefs.push(...collectCssResourceHrefs(match[1] ?? match[2] ?? ''));
+ }
+
+ return hrefs;
+};
+
+const resolveHtmlResourceBasePath = (
+ html: string,
+ htmlFilePath: string,
+ workingDirectory: string,
+): { remote: boolean; sourcePath: string } => {
+ const baseTag = findOpeningTag(html, 'base');
+ const baseHref = baseTag ? findAttribute(baseTag.text, 'href')?.value : undefined;
+ if (!baseHref) return { remote: false, sourcePath: htmlFilePath };
+
+ const resolved = resolveLocalResourceHref({
+ href: baseHref,
+ sourcePath: htmlFilePath,
+ workingDirectory,
+ });
+
+ if (resolved.kind === 'remote') return { remote: true, sourcePath: htmlFilePath };
+ if (resolved.kind !== 'resolved' || !resolved.absolutePath) {
+ return { remote: false, sourcePath: htmlFilePath };
+ }
+
+ const extension = getFileExtension(resolved.absolutePath);
+ const directory = extension ? parentDirectory(resolved.absolutePath) : resolved.absolutePath;
+ return { remote: false, sourcePath: `${directory}/index.html` };
+};
+
+const walkHtmlTags = (html: string, onTag: (tagName: string, tagText: string) => void) => {
+ const lower = html.toLowerCase();
+ let index = 0;
+
+ while (index < html.length) {
+ const start = lower.indexOf('<', index);
+ if (start === -1) return;
+
+ let nameEnd = start + 1;
+ while (nameEnd < html.length && /[a-z0-9-]/i.test(html[nameEnd])) nameEnd += 1;
+ const tagName = lower.slice(start + 1, nameEnd);
+ const end = findTagEnd(html, start);
+ if (end === -1) return;
+
+ onTag(tagName, html.slice(start, end));
+ index = end;
+ }
+};
+
+export const collectLocalResourceRefs = ({
+ content,
+ rootDirectory,
+ sourceKind,
+ sourcePath,
+ workingDirectory,
+}: {
+ content: string;
+ rootDirectory?: string;
+ sourceKind: 'css' | 'html' | 'js';
+ sourcePath: string;
+ workingDirectory: string;
+}): CollectLocalResourceResult => {
+ const result: CollectLocalResourceResult = { refs: [], skipped: [] };
+ const seenRefs = new Set<string>();
+
+ if (sourceKind === 'css' || sourceKind === 'js') {
+ const hrefs =
+ sourceKind === 'css' ? collectCssResourceHrefs(content) : collectJsResourceHrefs(content);
+ for (const href of hrefs) {
+ pushRef(
+ result,
+ seenRefs,
+ resolveLocalResourceHref({
+ href,
+ rootDirectory,
+ sourcePath,
+ workingDirectory,
+ }),
+ );
+ }
+ return result;
+ }
+
+ const resourceBase = resolveHtmlResourceBasePath(content, sourcePath, workingDirectory);
+
+ const pushHtmlRef = (href: string) => {
+ const resolved = resolveLocalResourceHref({
+ href,
+ sourcePath: resourceBase.sourcePath,
+ workingDirectory,
+ });
+
+ // An absolute <base href> makes every non-fragment URL resolve against the
+ // remote origin — including root-relative ones like /assets/app.css.
+ if (resourceBase.remote && resolved.kind !== 'empty') {
+ result.skipped.push({ href, reason: 'remote' });
+ return;
+ }
+
+ pushRef(result, seenRefs, resolved);
+ };
+
+ walkHtmlTags(content, (tagName, tagText) => {
+ if (!HTML_RESOURCE_TAGS.has(tagName)) return;
+ for (const href of collectTagAttributeHrefs(tagText)) pushHtmlRef(href);
+ });
+
+ for (const href of collectInlineStyleHrefs(content)) pushHtmlRef(href);
+
+ return result;
+};
diff --git a/src/features/Portal/LocalFile/gatherWorkspaceHtmlArtifact.test.ts b/src/features/Portal/LocalFile/gatherWorkspaceHtmlArtifact.test.ts
new file mode 100644
index 00000000000..cb3ab24a70b
--- /dev/null
+++ b/src/features/Portal/LocalFile/gatherWorkspaceHtmlArtifact.test.ts
@@ -0,0 +1,264 @@
+import { describe, expect, it } from 'vitest';
+
+import { gatherWorkspaceHtmlArtifact } from './gatherWorkspaceHtmlArtifact';
+import type { ReadWorkspaceAssetResult } from './readWorkspaceAsset';
+
+const textAsset = (text: string, contentType = 'text/plain'): ReadWorkspaceAssetResult => ({
+ bytes: new TextEncoder().encode(text),
+ contentType,
+ ok: true,
+ text,
+});
+
+describe('gatherWorkspaceHtmlArtifact', () => {
+ it('publishes html plus collected local assets under the shared site root', async () => {
+ const css = 'body { background: url("../images/bg.png"); }';
+ const files = new Map<string, ReadWorkspaceAssetResult>([
+ ['/project/pages/app.css', textAsset(css, 'text/css')],
+ [
+ '/project/images/bg.png',
+ {
+ bytes: new Uint8Array([1, 2, 3]),
+ contentType: 'image/png',
+ ok: true,
+ },
+ ],
+ ]);
+
+ const result = await gatherWorkspaceHtmlArtifact({
+ htmlContent: '<html><title>Demo</title><link rel="stylesheet" href="app.css"></html>',
+ htmlFilePath: '/project/pages/index.html',
+ readAsset: async (absolutePath) =>
+ files.get(absolutePath) ?? { ok: false, reason: 'missing' },
+ workingDirectory: '/project',
+ });
+
+ expect(result.identifier).toBe('workspace-html-pages-index-html-6afd7f0435');
+ expect(result.title).toBe('Demo');
+ expect(result.entryPath).toBe('pages/index.html');
+ expect(result.files.map((file) => file.path).sort()).toEqual([
+ 'images/bg.png',
+ 'pages/app.css',
+ 'pages/index.html',
+ ]);
+ expect(result.files.find((file) => file.path === 'images/bg.png')).toMatchObject({
+ encoding: 'base64',
+ content: globalThis.btoa(String.fromCharCode(1, 2, 3)),
+ });
+ expect(result.blocked).toBeUndefined();
+ });
+
+ it('lists missing and oversized refs without blocking the rest', async () => {
+ const result = await gatherWorkspaceHtmlArtifact({
+ htmlContent:
+ '<html><link rel="stylesheet" href="app.css"><img src="gone.png"><img src="huge.png"></html>',
+ htmlFilePath: '/project/index.html',
+ readAsset: async (absolutePath) => {
+ if (absolutePath.endsWith('app.css')) return textAsset('body{}', 'text/css');
+ if (absolutePath.endsWith('huge.png')) return { ok: false, reason: 'oversized' };
+ return { ok: false, reason: 'missing' };
+ },
+ workingDirectory: '/project',
+ });
+
+ expect(result.files.map((file) => file.path).sort()).toEqual(['app.css', 'index.html']);
+ expect(result.missing).toEqual(['gone.png']);
+ expect(result.oversized).toEqual(['huge.png']);
+ });
+
+ it('uses the same identifier when the same html path is gathered again', async () => {
+ const first = await gatherWorkspaceHtmlArtifact({
+ htmlContent: '<html></html>',
+ htmlFilePath: '/project/pages/index.html',
+ readAsset: async () => ({ ok: false, reason: 'missing' }),
+ workingDirectory: '/project',
+ });
+ const second = await gatherWorkspaceHtmlArtifact({
+ htmlContent: '<html><img src="logo.png"></html>',
+ htmlFilePath: '/project/pages/index.html',
+ readAsset: async () => ({
+ bytes: new Uint8Array([9]),
+ contentType: 'image/png',
+ ok: true,
+ }),
+ workingDirectory: '/project',
+ });
+
+ expect(first.identifier).toBe(second.identifier);
+ });
+
+ it('resolves sibling assets when the html path is workspace-relative', async () => {
+ const readPaths: string[] = [];
+ const result = await gatherWorkspaceHtmlArtifact({
+ htmlContent: '<html><link rel="stylesheet" href="./app.css"><img src="./dot.svg"></html>',
+ htmlFilePath: 'index.html',
+ readAsset: async (absolutePath) => {
+ readPaths.push(absolutePath);
+ if (absolutePath === '/tmp/site/app.css') return textAsset('body{}', 'text/css');
+ if (absolutePath === '/tmp/site/dot.svg') return textAsset('<svg></svg>', 'image/svg+xml');
+ return { ok: false, reason: 'missing' };
+ },
+ workingDirectory: '/tmp/site',
+ });
+
+ expect(readPaths.sort()).toEqual(['/tmp/site/app.css', '/tmp/site/dot.svg']);
+ expect(result.files.map((file) => file.path).sort()).toEqual([
+ 'app.css',
+ 'dot.svg',
+ 'index.html',
+ ]);
+ expect(result.missing).toEqual([]);
+ });
+
+ it('collects sibling assets when Electron reports /private/tmp and the topic cwd is /tmp', async () => {
+ const readPaths: string[] = [];
+ const result = await gatherWorkspaceHtmlArtifact({
+ htmlContent: '<html><link rel="stylesheet" href="./app.css"><img src="./dot.svg"></html>',
+ htmlFilePath: '/private/tmp/lobe-html-publish-fixture/index.html',
+ readAsset: async (absolutePath) => {
+ readPaths.push(absolutePath);
+ if (absolutePath === '/private/tmp/lobe-html-publish-fixture/app.css') {
+ return textAsset('body{}', 'text/css');
+ }
+ if (absolutePath === '/private/tmp/lobe-html-publish-fixture/dot.svg') {
+ return textAsset('<svg></svg>', 'image/svg+xml');
+ }
+ return { ok: false, reason: 'missing' };
+ },
+ workingDirectory: '/tmp/lobe-html-publish-fixture',
+ });
+
+ expect(readPaths.sort()).toEqual([
+ '/private/tmp/lobe-html-publish-fixture/app.css',
+ '/private/tmp/lobe-html-publish-fixture/dot.svg',
+ ]);
+ expect(result.files.map((file) => file.path).sort()).toEqual([
+ 'app.css',
+ 'dot.svg',
+ 'index.html',
+ ]);
+ expect(result.missing).toEqual([]);
+ });
+
+ it('publishes a standalone html file with no local or remote refs', async () => {
+ const result = await gatherWorkspaceHtmlArtifact({
+ htmlContent: '<html><title>Solo</title><body><p>Hello</p></body></html>',
+ htmlFilePath: '/project/solo.html',
+ readAsset: async () => ({ ok: false, reason: 'missing' }),
+ workingDirectory: '/project',
+ });
+
+ expect(result.files.map((file) => file.path)).toEqual(['solo.html']);
+ expect(result.remotes).toEqual([]);
+ expect(result.missing).toEqual([]);
+ });
+
+ it('follows a vite script into hashed import.meta.url assets and public icons', async () => {
+ const js = `
+ const hero = new URL("hero-CLDdwZDr.png", import.meta.url);
+ const icon = "/icons.svg#documentation-icon";
+ `;
+ const files = new Map<string, ReadWorkspaceAssetResult>([
+ ['/project/dist/assets/index.js', textAsset(js, 'text/javascript')],
+ [
+ '/project/dist/assets/hero-CLDdwZDr.png',
+ { bytes: new Uint8Array([1, 2, 3]), contentType: 'image/png', ok: true },
+ ],
+ ['/project/dist/icons.svg', textAsset('<svg></svg>', 'image/svg+xml')],
+ ]);
+
+ const result = await gatherWorkspaceHtmlArtifact({
+ htmlContent:
+ '<html><title>Vite React Dist Probe</title><script type="module" src="./assets/index.js"></script></html>',
+ htmlFilePath: '/project/dist/index.html',
+ readAsset: async (absolutePath) =>
+ files.get(absolutePath) ?? { ok: false, reason: 'missing' },
+ workingDirectory: '/project',
+ });
+
+ expect(result.files.map((file) => file.path).sort()).toEqual([
+ 'assets/hero-CLDdwZDr.png',
+ 'assets/index.js',
+ 'icons.svg',
+ 'index.html',
+ ]);
+ });
+
+ it('stops reading as soon as the file count limit is exceeded', async () => {
+ const refs = Array.from({ length: 80 }, (_, index) => `<img src="a${index}.png">`).join('');
+ let reads = 0;
+
+ const result = await gatherWorkspaceHtmlArtifact({
+ htmlContent: `<html>${refs}</html>`,
+ htmlFilePath: '/project/index.html',
+ readAsset: async () => {
+ reads += 1;
+ return { bytes: new Uint8Array([1]), contentType: 'image/png', ok: true };
+ },
+ workingDirectory: '/project',
+ });
+
+ expect(result.blocked).toBe('too-many');
+ expect(reads).toBeLessThan(80);
+ });
+
+ it('stops reading as soon as the total byte limit is exceeded', async () => {
+ const refs = Array.from({ length: 12 }, (_, index) => `<img src="b${index}.png">`).join('');
+ let reads = 0;
+
+ const result = await gatherWorkspaceHtmlArtifact({
+ htmlContent: `<html>${refs}</html>`,
+ htmlFilePath: '/project/index.html',
+ readAsset: async () => {
+ reads += 1;
+ return { bytes: new Uint8Array(9 * 1024 * 1024), contentType: 'image/png', ok: true };
+ },
+ workingDirectory: '/project',
+ });
+
+ expect(result.blocked).toBe('too-large');
+ expect(reads).toBe(5);
+ });
+
+ it('reads a file once when it is referenced through several spellings', async () => {
+ const readPaths: string[] = [];
+
+ const result = await gatherWorkspaceHtmlArtifact({
+ htmlContent: '<html><img src="logo.png"><img src="./logo.png"></html>',
+ htmlFilePath: '/project/index.html',
+ readAsset: async (absolutePath) => {
+ readPaths.push(absolutePath);
+ return { bytes: new Uint8Array([1]), contentType: 'image/png', ok: true };
+ },
+ workingDirectory: '/project',
+ });
+
+ expect(readPaths).toEqual(['/project/logo.png']);
+ expect(result.files.map((file) => file.path).sort()).toEqual(['index.html', 'logo.png']);
+ });
+
+ it('keeps remote urls out of the file set and lists them separately', async () => {
+ const result = await gatherWorkspaceHtmlArtifact({
+ htmlContent: `
+ <html>
+ <link rel="stylesheet" href="app.css">
+ <script src="https://cdn.example.com/app.js"></script>
+ <img src="//cdn.example.com/hero.png">
+ </html>
+ `,
+ htmlFilePath: '/project/index.html',
+ readAsset: async (absolutePath) =>
+ absolutePath.endsWith('app.css')
+ ? textAsset('body { background: url("https://cdn.example.com/bg.png"); }', 'text/css')
+ : { ok: false, reason: 'missing' },
+ workingDirectory: '/project',
+ });
+
+ expect(result.files.map((file) => file.path).sort()).toEqual(['app.css', 'index.html']);
+ expect(result.remotes).toEqual([
+ 'https://cdn.example.com/app.js',
+ '//cdn.example.com/hero.png',
+ 'https://cdn.example.com/bg.png',
+ ]);
+ });
+});
diff --git a/src/features/Portal/LocalFile/gatherWorkspaceHtmlArtifact.ts b/src/features/Portal/LocalFile/gatherWorkspaceHtmlArtifact.ts
new file mode 100644
index 00000000000..b9bc2a055b9
--- /dev/null
+++ b/src/features/Portal/LocalFile/gatherWorkspaceHtmlArtifact.ts
@@ -0,0 +1,229 @@
+import { bytesToBase64 } from '@lobechat/utils';
+
+import type { WorkspaceHtmlArtifactFile } from '@/business/client/features/WorkspaceHtmlArtifactPublish';
+import { extractHtmlTitle } from '@/components/HtmlPreview/htmlTagScanner';
+
+import {
+ type CollectedLocalResourceRef,
+ collectLocalResourceRefs,
+ isCssAssetPath,
+ isJsAssetPath,
+} from './collectHtmlLocalResources';
+import {
+ type ReadWorkspaceAssetResult,
+ WORKSPACE_HTML_ARTIFACT_MAX_FILES,
+ WORKSPACE_HTML_ARTIFACT_MAX_TOTAL_BYTES,
+} from './readWorkspaceAsset';
+import {
+ lowestCommonAncestorDirectory,
+ parentDirectory,
+ toWorkspaceAbsolutePath,
+ toWorkspaceRelativePath,
+ workspaceHtmlArtifactIdentifierForFile,
+} from './workspaceHtmlPath';
+
+export interface GatheredWorkspaceHtmlArtifact {
+ blocked?: 'too-large' | 'too-many';
+ entryPath: string;
+ files: WorkspaceHtmlArtifactFile[];
+ identifier: string;
+ missing: string[];
+ oversized: string[];
+ remotes: string[];
+ title: string;
+ totalBytes: number;
+}
+
+const READ_CONCURRENCY = 5;
+
+const isWalkableAssetPath = (absolutePath: string): boolean =>
+ isCssAssetPath(absolutePath) || isJsAssetPath(absolutePath);
+
+const toArtifactFile = (
+ relativePath: string,
+ contentType: string,
+ bytes: Uint8Array,
+ text?: string,
+): WorkspaceHtmlArtifactFile => {
+ if (text !== undefined) {
+ return {
+ content: text,
+ contentType,
+ encoding: 'utf8',
+ path: relativePath,
+ };
+ }
+
+ return {
+ content: bytesToBase64(bytes),
+ contentType,
+ encoding: 'base64',
+ path: relativePath,
+ };
+};
+
+export const gatherWorkspaceHtmlArtifact = async ({
+ htmlContent,
+ htmlFilePath,
+ readAsset,
+ workingDirectory,
+}: {
+ htmlContent: string;
+ htmlFilePath: string;
+ readAsset: (absolutePath: string) => Promise<ReadWorkspaceAssetResult>;
+ workingDirectory: string;
+}): Promise<GatheredWorkspaceHtmlArtifact> => {
+ const absoluteHtmlPath = toWorkspaceAbsolutePath(htmlFilePath, workingDirectory);
+ const htmlRefs = collectLocalResourceRefs({
+ content: htmlContent,
+ sourceKind: 'html',
+ sourcePath: absoluteHtmlPath,
+ workingDirectory,
+ });
+
+ const pending = [...htmlRefs.refs];
+ const seen = new Set(pending.map((ref) => ref.absolutePath));
+ const handled = new Set<string>();
+ const walkQueue = pending.filter((ref) => isWalkableAssetPath(ref.absolutePath));
+ const missing: string[] = [];
+ const oversized: string[] = [];
+ const remotes: string[] = [];
+ const htmlDirectory = parentDirectory(absoluteHtmlPath);
+
+ const addRemotes = (skipped: typeof htmlRefs.skipped) => {
+ for (const item of skipped) {
+ if (item.reason !== 'remote') continue;
+ if (!remotes.includes(item.href)) remotes.push(item.href);
+ }
+ };
+
+ addRemotes(htmlRefs.skipped);
+ for (const item of htmlRefs.skipped) {
+ if (item.reason !== 'escape') continue;
+ if (!missing.includes(item.href)) missing.push(item.href);
+ }
+ const resolvedAssets: Array<{
+ absolutePath: string;
+ bytes: Uint8Array;
+ contentType: string;
+ 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);
+ 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';
+ };
+
+ const readLeafAsset = async (ref: CollectedLocalResourceRef) => {
+ const asset = await readAsset(ref.absolutePath);
+ if (!asset.ok) {
+ if (asset.reason === 'oversized') oversized.push(ref.href);
+ else missing.push(ref.href);
+ return;
+ }
+
+ registerAsset({
+ absolutePath: ref.absolutePath,
+ bytes: asset.bytes,
+ contentType: asset.contentType,
+ text: asset.text,
+ });
+ };
+
+ while (!blocked && walkQueue.length > 0) {
+ const walkRef = walkQueue.shift();
+ if (!walkRef) break;
+ if (handled.has(walkRef.absolutePath)) continue;
+ handled.add(walkRef.absolutePath);
+
+ const asset = await readAsset(walkRef.absolutePath);
+ if (!asset.ok) {
+ if (asset.reason === 'oversized') oversized.push(walkRef.href);
+ else missing.push(walkRef.href);
+ continue;
+ }
+
+ const text =
+ asset.text ??
+ (isWalkableAssetPath(walkRef.absolutePath)
+ ? new TextDecoder().decode(asset.bytes)
+ : undefined);
+
+ registerAsset({
+ absolutePath: walkRef.absolutePath,
+ bytes: asset.bytes,
+ contentType: asset.contentType,
+ text,
+ });
+
+ if (!text) continue;
+
+ const nested = collectLocalResourceRefs({
+ content: text,
+ rootDirectory: isJsAssetPath(walkRef.absolutePath) ? htmlDirectory : undefined,
+ sourceKind: isJsAssetPath(walkRef.absolutePath) ? 'js' : 'css',
+ sourcePath: walkRef.absolutePath,
+ workingDirectory,
+ });
+ addRemotes(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);
+ }
+ }
+
+ // 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);
+ return true;
+ });
+
+ for (let index = 0; index < leaves.length && !blocked; index += READ_CONCURRENCY) {
+ await Promise.all(leaves.slice(index, index + READ_CONCURRENCY).map(readLeafAsset));
+ }
+
+ const siteRoot = lowestCommonAncestorDirectory(
+ [absoluteHtmlPath, ...resolvedAssets.map((asset) => asset.absolutePath)],
+ workingDirectory,
+ );
+ const entryPath = toWorkspaceRelativePath(absoluteHtmlPath, siteRoot) || 'index.html';
+ const filename = htmlFilePath.split(/[/\\]/).at(-1) || 'index.html';
+
+ const files: WorkspaceHtmlArtifactFile[] = blocked
+ ? []
+ : [
+ toArtifactFile(entryPath, 'text/html', htmlBytes, htmlContent),
+ ...resolvedAssets.map((asset) =>
+ toArtifactFile(
+ toWorkspaceRelativePath(asset.absolutePath, siteRoot),
+ asset.contentType,
+ asset.bytes,
+ asset.text,
+ ),
+ ),
+ ];
+
+ return {
+ blocked,
+ entryPath,
+ files,
+ identifier: workspaceHtmlArtifactIdentifierForFile(htmlFilePath, workingDirectory),
+ missing,
+ oversized,
+ remotes,
+ title: extractHtmlTitle(htmlContent) || filename,
+ totalBytes,
+ };
+};
diff --git a/src/features/Portal/LocalFile/packWorkspaceHtmlDocument.test.ts b/src/features/Portal/LocalFile/packWorkspaceHtmlDocument.test.ts
new file mode 100644
index 00000000000..2901b2dc338
--- /dev/null
+++ b/src/features/Portal/LocalFile/packWorkspaceHtmlDocument.test.ts
@@ -0,0 +1,276 @@
+import { describe, expect, it } from 'vitest';
+
+import { packWorkspaceHtmlDocument } from './packWorkspaceHtmlDocument';
+import { WORKSPACE_HTML_ARTIFACT_INLINE_MAX_BYTES } from './readWorkspaceAsset';
+
+describe('packWorkspaceHtmlDocument', () => {
+ it('inlines small local css and images as data uris and leaves remotes', () => {
+ const packed = packWorkspaceHtmlDocument({
+ entryPath: 'index.html',
+ files: [
+ {
+ content:
+ '<html><link rel="stylesheet" href="app.css"><img src="dot.png"><script src="https://cdn.example.com/app.js"></script></html>',
+ contentType: 'text/html',
+ encoding: 'utf8',
+ path: 'index.html',
+ },
+ {
+ content: 'body { background: url("./dot.png"); color: #123456; }',
+ contentType: 'text/css',
+ encoding: 'utf8',
+ path: 'app.css',
+ },
+ {
+ content: globalThis.btoa(String.fromCharCode(1, 2, 3)),
+ contentType: 'image/png',
+ encoding: 'base64',
+ path: 'dot.png',
+ },
+ ],
+ });
+
+ expect(packed.html).toContain('data:text/css;base64,');
+ expect(packed.html).toContain('data:image/png;base64,AQID');
+ expect(packed.html).toContain('https://cdn.example.com/app.js');
+ expect(packed.html).not.toContain('href="app.css"');
+ expect(packed.html).not.toContain('src="dot.png"');
+ expect(packed.inlinedPaths).toEqual(['app.css', 'dot.png']);
+ expect(packed.sidecars).toEqual([]);
+ expect(packed.unresolvedHrefs).toEqual([]);
+ });
+
+ it('inlines svg as image/svg+xml even when the gathered type is text/plain', () => {
+ const packed = packWorkspaceHtmlDocument({
+ entryPath: 'index.html',
+ files: [
+ {
+ content: '<html><img alt="dot" src="./dot.svg"></html>',
+ contentType: 'text/html',
+ encoding: 'utf8',
+ path: 'index.html',
+ },
+ {
+ content: '<svg xmlns="http://www.w3.org/2000/svg"></svg>',
+ contentType: 'text/plain',
+ encoding: 'utf8',
+ path: 'dot.svg',
+ },
+ ],
+ });
+
+ expect(packed.html).toContain('data:image/svg+xml;base64,');
+ expect(packed.html).not.toContain('data:text/plain');
+ expect(packed.unresolvedHrefs).toEqual([]);
+ });
+
+ it('reports leftover relative files that were not packed', () => {
+ const packed = packWorkspaceHtmlDocument({
+ entryPath: 'index.html',
+ files: [
+ {
+ content:
+ '<html><link rel="stylesheet" href="./app.css"><img alt="dot" src="./dot.svg"></html>',
+ contentType: 'text/html',
+ encoding: 'utf8',
+ path: 'index.html',
+ },
+ ],
+ });
+
+ expect(packed.html).toContain('href="./app.css"');
+ expect(packed.html).toContain('src="./dot.svg"');
+ expect(packed.unresolvedHrefs.sort()).toEqual(['./app.css', './dot.svg']);
+ });
+
+ it('rewrites unquoted html attributes so inlined files are not left behind', () => {
+ const packed = packWorkspaceHtmlDocument({
+ entryPath: 'index.html',
+ files: [
+ {
+ content: '<html><img src=dot.png alt=mark><link rel=stylesheet href=app.css></html>',
+ contentType: 'text/html',
+ encoding: 'utf8',
+ path: 'index.html',
+ },
+ {
+ content: 'body { color: #111; }',
+ contentType: 'text/css',
+ encoding: 'utf8',
+ path: 'app.css',
+ },
+ {
+ content: globalThis.btoa(String.fromCharCode(1, 2, 3)),
+ contentType: 'image/png',
+ encoding: 'base64',
+ path: 'dot.png',
+ },
+ ],
+ });
+
+ expect(packed.html).toContain('src=data:image/png;base64,AQID');
+ expect(packed.html).toContain('href=data:text/css;base64,');
+ expect(packed.html).not.toContain('src=dot.png');
+ expect(packed.html).not.toContain('href=app.css');
+ expect(packed.inlinedPaths).toEqual(['app.css', 'dot.png']);
+ expect(packed.sidecars).toEqual([]);
+ });
+
+ it('rewrites refs that resolve through a local base element', () => {
+ const packed = packWorkspaceHtmlDocument({
+ entryPath: 'pages/index.html',
+ files: [
+ {
+ content: '<html><base href="../shared/"><img src="logo.png"></html>',
+ contentType: 'text/html',
+ encoding: 'utf8',
+ path: 'pages/index.html',
+ },
+ {
+ content: globalThis.btoa(String.fromCharCode(1, 2, 3)),
+ contentType: 'image/png',
+ encoding: 'base64',
+ path: 'shared/logo.png',
+ },
+ ],
+ });
+
+ expect(packed.html).toContain('data:image/png;base64,AQID');
+ expect(packed.html).not.toContain('src="logo.png"');
+ expect(packed.unresolvedHrefs).toEqual([]);
+ expect(packed.inlinedPaths).toEqual(['shared/logo.png']);
+ });
+
+ it('rewrites every spelling of the same inlined file', () => {
+ const packed = packWorkspaceHtmlDocument({
+ entryPath: 'index.html',
+ files: [
+ {
+ content: '<html><img src="dot.png"><img src="./dot.png"></html>',
+ contentType: 'text/html',
+ encoding: 'utf8',
+ path: 'index.html',
+ },
+ {
+ content: globalThis.btoa(String.fromCharCode(1, 2, 3)),
+ contentType: 'image/png',
+ encoding: 'base64',
+ path: 'dot.png',
+ },
+ ],
+ });
+
+ expect(packed.html).not.toContain('src="dot.png"');
+ expect(packed.html).not.toContain('src="./dot.png"');
+ expect(packed.unresolvedHrefs).toEqual([]);
+ expect(packed.inlinedPaths).toEqual(['dot.png']);
+ });
+
+ it('keeps files over the inline limit as uploaded sidecars', () => {
+ const largePng = globalThis.btoa('x'.repeat(WORKSPACE_HTML_ARTIFACT_INLINE_MAX_BYTES + 8));
+ const packed = packWorkspaceHtmlDocument({
+ entryPath: 'pages/index.html',
+ files: [
+ {
+ content:
+ '<html><img src="../images/hero.png"><link rel="stylesheet" href="app.css"></html>',
+ contentType: 'text/html',
+ encoding: 'utf8',
+ path: 'pages/index.html',
+ },
+ {
+ content: 'body { color: #111; }',
+ contentType: 'text/css',
+ encoding: 'utf8',
+ path: 'pages/app.css',
+ },
+ {
+ content: largePng,
+ contentType: 'image/png',
+ encoding: 'base64',
+ path: 'images/hero.png',
+ },
+ ],
+ });
+
+ expect(packed.html).toContain('src="/images/hero.png"');
+ expect(packed.html).toContain('data:text/css;base64,');
+ expect(packed.inlinedPaths).toEqual(['pages/app.css']);
+ expect(packed.sidecars.map((file) => file.path)).toEqual(['images/hero.png']);
+ });
+
+ it('keeps js-referenced assets as sidecars so import.meta.url still resolves', () => {
+ const packed = packWorkspaceHtmlDocument({
+ entryPath: 'index.html',
+ files: [
+ {
+ content:
+ '<html><link rel="stylesheet" href="app.css"><script type="module" src="assets/index.js"></script></html>',
+ contentType: 'text/html',
+ encoding: 'utf8',
+ path: 'index.html',
+ },
+ {
+ content: 'body { color: #111; }',
+ contentType: 'text/css',
+ encoding: 'utf8',
+ path: 'app.css',
+ },
+ {
+ content:
+ 'const hero = new URL("hero.png", import.meta.url); const icon = "/icons.svg#x";',
+ contentType: 'text/javascript',
+ encoding: 'utf8',
+ path: 'assets/index.js',
+ },
+ {
+ content: globalThis.btoa(String.fromCharCode(1, 2, 3)),
+ contentType: 'image/png',
+ encoding: 'base64',
+ path: 'assets/hero.png',
+ },
+ {
+ content: '<svg></svg>',
+ contentType: 'image/svg+xml',
+ encoding: 'utf8',
+ path: 'icons.svg',
+ },
+ ],
+ });
+
+ expect(packed.html).toContain('data:text/css;base64,');
+ expect(packed.html).toContain('src="/assets/index.js"');
+ expect(packed.inlinedPaths).toEqual(['app.css']);
+ expect(packed.sidecars.map((file) => file.path).sort()).toEqual([
+ 'assets/hero.png',
+ 'assets/index.js',
+ 'icons.svg',
+ ]);
+ expect(packed.sidecars.find((file) => file.path === 'assets/index.js')?.content).toContain(
+ 'new URL("hero.png", import.meta.url)',
+ );
+ });
+
+ it('returns standalone html unchanged when there are no local assets', () => {
+ const html = '<html><title>Solo</title><body><p>Hello</p></body></html>';
+
+ expect(
+ packWorkspaceHtmlDocument({
+ entryPath: 'solo.html',
+ files: [
+ {
+ content: html,
+ contentType: 'text/html',
+ encoding: 'utf8',
+ path: 'solo.html',
+ },
+ ],
+ }),
+ ).toEqual({
+ html,
+ inlinedPaths: [],
+ sidecars: [],
+ unresolvedHrefs: [],
+ });
+ });
+});
diff --git a/src/features/Portal/LocalFile/packWorkspaceHtmlDocument.ts b/src/features/Portal/LocalFile/packWorkspaceHtmlDocument.ts
new file mode 100644
index 00000000000..9000d04e563
--- /dev/null
+++ b/src/features/Portal/LocalFile/packWorkspaceHtmlDocument.ts
@@ -0,0 +1,250 @@
+import { decodeFromBase64, encodeToBase64 } from '@lobechat/utils';
+import { escapeRegExp } from 'es-toolkit';
+
+import type { WorkspaceHtmlArtifactFile } from '@/business/client/features/WorkspaceHtmlArtifactPublish';
+
+import {
+ collectCssResourceHrefs,
+ collectJsResourceHrefs,
+ collectLocalResourceRefs,
+ isCssAssetPath,
+ isJsAssetPath,
+} from './collectHtmlLocalResources';
+import {
+ resolveWorkspaceAssetContentType,
+ WORKSPACE_HTML_ARTIFACT_INLINE_MAX_BYTES,
+} from './readWorkspaceAsset';
+import { resolveLocalResourceHref, toWorkspaceRelativePath } from './workspaceHtmlPath';
+
+const SITE_ROOT = '/__workspace_html_site__';
+
+export interface PackedWorkspaceHtmlSite {
+ html: string;
+ inlinedPaths: string[];
+ sidecars: WorkspaceHtmlArtifactFile[];
+ unresolvedHrefs: string[];
+}
+
+export const normalizePath = (path: string) => path.replaceAll('\\', '/').replace(/^\/+/u, '');
+
+export const hostedPath = (path: string) => `/${normalizePath(path)}`;
+
+const exceedsInlineLimit = (file: WorkspaceHtmlArtifactFile): boolean => {
+ if (file.encoding === 'utf8') {
+ // UTF-8 byte length is never below the UTF-16 unit count, so oversized
+ // content short-circuits without encoding multi-MB strings.
+ if (file.content.length > WORKSPACE_HTML_ARTIFACT_INLINE_MAX_BYTES) return true;
+ return (
+ new TextEncoder().encode(file.content).byteLength > WORKSPACE_HTML_ARTIFACT_INLINE_MAX_BYTES
+ );
+ }
+
+ const padding = file.content.endsWith('==') ? 2 : file.content.endsWith('=') ? 1 : 0;
+ return (
+ Math.max(0, Math.floor((file.content.length * 3) / 4) - padding) >
+ WORKSPACE_HTML_ARTIFACT_INLINE_MAX_BYTES
+ );
+};
+
+const resolveSitePath = (href: string, sourcePath: string): string | undefined => {
+ const resolved = resolveLocalResourceHref({
+ href,
+ sourcePath: `${SITE_ROOT}/${normalizePath(sourcePath)}`,
+ workingDirectory: SITE_ROOT,
+ });
+ if (resolved.kind !== 'resolved' || !resolved.absolutePath) return;
+
+ return toWorkspaceRelativePath(resolved.absolutePath, SITE_ROOT);
+};
+
+const isCssFile = (file: WorkspaceHtmlArtifactFile) =>
+ file.contentType.includes('css') || isCssAssetPath(file.path);
+
+const isJsFile = (file: WorkspaceHtmlArtifactFile) =>
+ file.contentType.includes('javascript') || isJsAssetPath(file.path);
+
+const replaceHrefToken = (source: string, href: string, replacement: string): string => {
+ const escaped = escapeRegExp(href);
+
+ return source
+ .replaceAll(new RegExp(`(["'])${escaped}\\1`, 'g'), `$1${replacement}$1`)
+ .replaceAll(new RegExp(`url\\((['"]?)${escaped}\\1\\)`, 'gi'), `url($1${replacement}$1)`)
+ .replaceAll(new RegExp(`(^|[,\\s])${escaped}(?=\\s+\\d+[wx]|\\s*,|$)`, 'g'), `$1${replacement}`)
+ .replaceAll(
+ new RegExp(`(\\s(?:src|href|poster|data)=)${escaped}(?=[\\s>]|$)`, 'gi'),
+ `$1${replacement}`,
+ );
+};
+
+export const packWorkspaceHtmlDocument = ({
+ entryPath,
+ files,
+}: {
+ entryPath: string;
+ files: WorkspaceHtmlArtifactFile[];
+}): PackedWorkspaceHtmlSite => {
+ const fileMap = new Map(files.map((file) => [normalizePath(file.path), file]));
+ const entry = fileMap.get(normalizePath(entryPath));
+ if (!entry) {
+ throw new Error('entry missing');
+ }
+
+ const visiting = new Set<string>();
+ const decodedText = new Map<string, string>();
+ const rewrittenCss = new Map<string, string>();
+ const inlinableCache = new Map<string, boolean>();
+ const jsPinnedPaths = new Set<string>();
+
+ const fileText = (file: WorkspaceHtmlArtifactFile): string => {
+ const key = normalizePath(file.path);
+ const cached = decodedText.get(key);
+ if (cached !== undefined) return cached;
+
+ const text = file.encoding === 'utf8' ? file.content : decodeFromBase64(file.content);
+ decodedText.set(key, text);
+ return text;
+ };
+
+ for (const file of files) {
+ if (!isJsFile(file)) continue;
+
+ const localTargets = collectJsResourceHrefs(fileText(file))
+ .map((href) => resolveSitePath(href, file.path))
+ .filter((target): target is string => Boolean(target && fileMap.has(normalizePath(target))))
+ .map((target) => normalizePath(target));
+
+ if (localTargets.length === 0) continue;
+
+ jsPinnedPaths.add(normalizePath(file.path));
+ for (const target of localTargets) jsPinnedPaths.add(target);
+ }
+
+ const isInlinable = (relativePath: string): boolean => {
+ const key = normalizePath(relativePath);
+ const cached = inlinableCache.get(key);
+ if (cached !== undefined) return cached;
+
+ const file = fileMap.get(key);
+ if (!file || key === normalizePath(entryPath) || jsPinnedPaths.has(key)) {
+ inlinableCache.set(key, false);
+ return false;
+ }
+
+ if (exceedsInlineLimit(file)) {
+ inlinableCache.set(key, false);
+ return false;
+ }
+
+ if (!isCssFile(file)) {
+ inlinableCache.set(key, true);
+ return true;
+ }
+
+ if (visiting.has(key)) {
+ inlinableCache.set(key, false);
+ return false;
+ }
+
+ visiting.add(key);
+ const nestedInlinable = collectCssResourceHrefs(fileText(file)).every((href) => {
+ const target = resolveSitePath(href, file.path);
+ return !target || !fileMap.has(normalizePath(target)) || isInlinable(target);
+ });
+ visiting.delete(key);
+ inlinableCache.set(key, nestedInlinable);
+ return nestedInlinable;
+ };
+
+ const fileToDataUri = (relativePath: string): string | undefined => {
+ const file = fileMap.get(normalizePath(relativePath));
+ if (!file || !isInlinable(relativePath)) return;
+
+ if (isCssFile(file)) {
+ const css = rewriteCss(fileText(file), file.path);
+ return `data:text/css;base64,${encodeToBase64(css)}`;
+ }
+
+ const contentType = resolveWorkspaceAssetContentType(file.path, file.contentType);
+
+ if (file.encoding === 'base64') {
+ return `data:${contentType};base64,${file.content}`;
+ }
+
+ return `data:${contentType};base64,${encodeToBase64(file.content)}`;
+ };
+
+ const rewriteHref = (href: string, sourcePath: string): string | undefined => {
+ const target = resolveSitePath(href, sourcePath);
+ if (!target || !fileMap.has(normalizePath(target))) return;
+ return fileToDataUri(target) ?? hostedPath(target);
+ };
+
+ const rewriteCss = (css: string, sourcePath: string): string => {
+ const key = normalizePath(sourcePath);
+ const cached = rewrittenCss.get(key);
+ if (cached !== undefined) return cached;
+ if (visiting.has(`rewrite:${key}`)) return css;
+
+ visiting.add(`rewrite:${key}`);
+ let next = css;
+ for (const href of collectCssResourceHrefs(css)) {
+ const replacement = rewriteHref(href, sourcePath);
+ if (!replacement) continue;
+ next = replaceHrefToken(next, href, replacement);
+ }
+ visiting.delete(`rewrite:${key}`);
+ rewrittenCss.set(key, next);
+ return next;
+ };
+
+ const html = fileText(entry);
+ const collected = collectLocalResourceRefs({
+ content: html,
+ sourceKind: 'html',
+ sourcePath: `${SITE_ROOT}/${normalizePath(entry.path)}`,
+ workingDirectory: SITE_ROOT,
+ });
+
+ let packed = html;
+ const unresolvedHrefs: string[] = [];
+ for (const ref of collected.refs) {
+ // Collection already resolved <base href>, so reuse its absolute path
+ // instead of re-resolving the href against the entry directory.
+ const target = normalizePath(toWorkspaceRelativePath(ref.absolutePath, SITE_ROOT));
+ const replacement = fileMap.has(target)
+ ? (fileToDataUri(target) ?? hostedPath(target))
+ : undefined;
+ if (!replacement) {
+ unresolvedHrefs.push(ref.href);
+ continue;
+ }
+ packed = replaceHrefToken(packed, ref.href, replacement);
+ }
+
+ const inlinedPaths = files
+ .map((file) => normalizePath(file.path))
+ .filter((path) => path !== normalizePath(entryPath) && isInlinable(path))
+ .sort();
+
+ const sidecars = files
+ .filter((file) => {
+ const path = normalizePath(file.path);
+ return path !== normalizePath(entryPath) && !isInlinable(path);
+ })
+ .map((file) =>
+ isCssFile(file)
+ ? {
+ ...file,
+ content: rewriteCss(fileText(file), file.path),
+ encoding: 'utf8' as const,
+ }
+ : file,
+ );
+
+ return {
+ html: packed,
+ inlinedPaths,
+ sidecars,
+ unresolvedHrefs,
+ };
+};
diff --git a/src/features/Portal/LocalFile/prepareWorkspaceHtmlPublish.test.ts b/src/features/Portal/LocalFile/prepareWorkspaceHtmlPublish.test.ts
new file mode 100644
index 00000000000..eabcd96c3ac
--- /dev/null
+++ b/src/features/Portal/LocalFile/prepareWorkspaceHtmlPublish.test.ts
@@ -0,0 +1,67 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { prepareWorkspaceHtmlPublish } from './prepareWorkspaceHtmlPublish';
+
+const readWorkspaceAsset = vi.hoisted(() => vi.fn());
+
+vi.mock('./readWorkspaceAsset', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...(actual as Record<string, unknown>),
+ readWorkspaceAsset: (...args: unknown[]) => readWorkspaceAsset(...args),
+ };
+});
+
+describe('prepareWorkspaceHtmlPublish', () => {
+ beforeEach(() => {
+ readWorkspaceAsset.mockReset();
+ });
+
+ it('packs provided HTML without reading the file', async () => {
+ const plan = await prepareWorkspaceHtmlPublish({
+ content: '<html><title>Demo</title></html>',
+ filePath: '/repo/index.html',
+ workingDirectory: '/repo',
+ });
+
+ expect('blocked' in plan).toBe(false);
+ if ('blocked' in plan) return;
+
+ expect(plan.gathered.title).toBe('Demo');
+ expect(plan.packed.html).toContain('Demo');
+ expect(readWorkspaceAsset).not.toHaveBeenCalled();
+ });
+
+ it('reads the file when content is not provided', async () => {
+ readWorkspaceAsset.mockResolvedValue({
+ ok: true,
+ text: '<html><title>From disk</title></html>',
+ });
+
+ const plan = await prepareWorkspaceHtmlPublish({
+ filePath: '/repo/pages/index.html',
+ workingDirectory: '/repo',
+ });
+
+ expect(readWorkspaceAsset).toHaveBeenCalledWith({
+ deviceId: undefined,
+ path: '/repo/pages/index.html',
+ sandboxTopicId: undefined,
+ workingDirectory: '/repo',
+ });
+ expect('blocked' in plan).toBe(false);
+ if ('blocked' in plan) return;
+ expect(plan.gathered.title).toBe('From disk');
+ });
+
+ it('returns unreadable when the HTML file cannot be loaded', async () => {
+ readWorkspaceAsset.mockResolvedValue({ ok: false, reason: 'missing' });
+
+ await expect(
+ prepareWorkspaceHtmlPublish({
+ filePath: '/repo/missing.html',
+ workingDirectory: '/repo',
+ }),
+ ).resolves.toEqual({ blocked: 'unreadable' });
+ });
+});
diff --git a/src/features/Portal/LocalFile/prepareWorkspaceHtmlPublish.ts b/src/features/Portal/LocalFile/prepareWorkspaceHtmlPublish.ts
new file mode 100644
index 00000000000..5454dfdbf9a
--- /dev/null
+++ b/src/features/Portal/LocalFile/prepareWorkspaceHtmlPublish.ts
@@ -0,0 +1,153 @@
+import { toast } from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
+
+import type {
+ WorkspaceHtmlArtifactPublisher,
+ WorkspaceHtmlArtifactPublishResult,
+} from '@/business/client/features/WorkspaceHtmlArtifactPublish';
+
+import {
+ type GatheredWorkspaceHtmlArtifact,
+ gatherWorkspaceHtmlArtifact,
+} from './gatherWorkspaceHtmlArtifact';
+import {
+ type PackedWorkspaceHtmlSite,
+ packWorkspaceHtmlDocument,
+} from './packWorkspaceHtmlDocument';
+import { readWorkspaceAsset } from './readWorkspaceAsset';
+
+export interface ReadyWorkspaceHtmlPublishPlan {
+ gathered: GatheredWorkspaceHtmlArtifact;
+ packed: PackedWorkspaceHtmlSite;
+}
+
+export type WorkspaceHtmlPublishPlan =
+ | {
+ blocked: 'too-large' | 'too-many';
+ totalBytes: number;
+ }
+ | {
+ blocked: 'unreadable';
+ }
+ | {
+ blocked: 'unresolved';
+ unresolvedHrefs: string[];
+ }
+ | ReadyWorkspaceHtmlPublishPlan;
+
+interface PrepareWorkspaceHtmlPublishInput {
+ content?: string;
+ deviceId?: string;
+ filePath: string;
+ sandboxTopicId?: string;
+ workingDirectory: string;
+}
+
+export const prepareWorkspaceHtmlPublish = async ({
+ content,
+ deviceId,
+ filePath,
+ sandboxTopicId,
+ workingDirectory,
+}: PrepareWorkspaceHtmlPublishInput): Promise<WorkspaceHtmlPublishPlan> => {
+ let htmlContent = content;
+ if (htmlContent === undefined) {
+ const asset = await readWorkspaceAsset({
+ deviceId,
+ path: filePath,
+ sandboxTopicId,
+ workingDirectory,
+ });
+ if (!asset.ok || !asset.text) return { blocked: 'unreadable' };
+ htmlContent = asset.text;
+ }
+
+ const gathered = await gatherWorkspaceHtmlArtifact({
+ htmlContent,
+ htmlFilePath: filePath,
+ readAsset: (absolutePath) =>
+ readWorkspaceAsset({
+ deviceId,
+ path: absolutePath,
+ sandboxTopicId,
+ workingDirectory,
+ }),
+ workingDirectory,
+ });
+
+ if (gathered.blocked) {
+ return { blocked: gathered.blocked, totalBytes: gathered.totalBytes };
+ }
+
+ const packed = packWorkspaceHtmlDocument({
+ entryPath: gathered.entryPath,
+ files: gathered.files,
+ });
+
+ if (packed.unresolvedHrefs.length > 0) {
+ return { blocked: 'unresolved', unresolvedHrefs: packed.unresolvedHrefs };
+ }
+
+ return { gathered, packed };
+};
+
+export const notifyWorkspaceHtmlPublishBlocked = (
+ plan: Extract<WorkspaceHtmlPublishPlan, { blocked: string }>,
+) => {
+ if (plan.blocked === 'unreadable') {
+ toast.error(t('workingPanel.localFile.publish.failed', { ns: 'chat' }));
+ return;
+ }
+
+ if (plan.blocked === 'unresolved') {
+ toast.error(t('workingPanel.localFile.publish.unresolvedLocals', { ns: 'chat' }));
+ return;
+ }
+
+ toast.error(
+ t(
+ plan.blocked === 'too-many'
+ ? 'workingPanel.localFile.publish.tooMany'
+ : 'workingPanel.localFile.publish.tooLarge',
+ { ns: 'chat', size: plan.totalBytes },
+ ),
+ );
+};
+
+const workspaceHtmlPublishErrorMessage = (error: unknown): string => {
+ if (error instanceof Error && error.message === 'unresolved-local-assets') {
+ return t('workingPanel.localFile.publish.unresolvedLocals', { ns: 'chat' });
+ }
+ if (error instanceof Error && error.message) return error.message;
+ return t('workingPanel.localFile.publish.failed', { ns: 'chat' });
+};
+
+export const publishPreparedWorkspaceHtml = async ({
+ agentId,
+ plan,
+ publish,
+ topicId,
+}: {
+ agentId?: string | null;
+ plan: ReadyWorkspaceHtmlPublishPlan;
+ publish: WorkspaceHtmlArtifactPublisher['publish'];
+ topicId: string;
+}): Promise<WorkspaceHtmlArtifactPublishResult | undefined> => {
+ try {
+ const result = await publish({
+ agentId: agentId ?? undefined,
+ entryPath: plan.gathered.entryPath,
+ files: plan.gathered.files,
+ identifier: plan.gathered.identifier,
+ packed: { html: plan.packed.html, sidecars: plan.packed.sidecars },
+ title: plan.gathered.title,
+ topicId,
+ });
+
+ toast.success(t('workingPanel.localFile.publish.success', { ns: 'chat' }));
+ return result;
+ } catch (error) {
+ toast.error(workspaceHtmlPublishErrorMessage(error));
+ return;
+ }
+};
diff --git a/src/features/Portal/LocalFile/publishWorkspaceHtmlArtifact.test.ts b/src/features/Portal/LocalFile/publishWorkspaceHtmlArtifact.test.ts
new file mode 100644
index 00000000000..b8762a82cd1
--- /dev/null
+++ b/src/features/Portal/LocalFile/publishWorkspaceHtmlArtifact.test.ts
@@ -0,0 +1,209 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ publishWorkspaceHtmlArtifact,
+ wrapWorkspaceHtmlArtifact,
+} from './publishWorkspaceHtmlArtifact';
+
+describe('publishWorkspaceHtmlArtifact', () => {
+ it('packs files, persists a closed html artifact, then publishes that message', async () => {
+ const createMessage = vi.fn(
+ async (_params: {
+ agentId: string;
+ content: string;
+ role: 'assistant';
+ topicId: string;
+ }) => ({
+ id: 'msg_1',
+ }),
+ );
+ const publishArtifact = vi.fn(async () => ({
+ latestRevisionNumber: 2,
+ publicUrl: 'https://example.lobehub.com/page',
+ }));
+
+ const result = await publishWorkspaceHtmlArtifact(
+ {
+ agentId: 'agt_1',
+ entryPath: 'index.html',
+ files: [
+ {
+ content: '<html><title>Demo</title><link rel="stylesheet" href="app.css"></html>',
+ contentType: 'text/html',
+ encoding: 'utf8',
+ path: 'index.html',
+ },
+ {
+ content: 'body { color: red; }',
+ contentType: 'text/css',
+ encoding: 'utf8',
+ path: 'app.css',
+ },
+ ],
+ identifier: 'workspace-html-index-html',
+ title: 'Demo',
+ topicId: 'tpc_1',
+ },
+ { createMessage, publishArtifact },
+ );
+
+ expect(result).toEqual({
+ publicUrl: 'https://example.lobehub.com/page',
+ revision: 2,
+ });
+ const content = createMessage.mock.calls[0]?.[0]?.content ?? '';
+ expect(createMessage).toHaveBeenCalledWith({
+ agentId: 'agt_1',
+ content,
+ role: 'assistant',
+ topicId: 'tpc_1',
+ });
+ expect(content).toContain('identifier="workspace-html-index-html"');
+ expect(content).toContain('data:text/css;base64,');
+ expect(content.startsWith('<lobeArtifact ')).toBe(true);
+ expect(content.endsWith('</lobeArtifact>')).toBe(true);
+ expect(content).toBe(
+ wrapWorkspaceHtmlArtifact({
+ html: content.replace(/^<lobeArtifact\b[^>]*>\n/u, '').replace(/\n<\/lobeArtifact>$/u, ''),
+ identifier: 'workspace-html-index-html',
+ title: 'Demo',
+ }),
+ );
+ expect(publishArtifact).toHaveBeenCalledWith({
+ artifactIdentifier: 'workspace-html-index-html',
+ messageId: 'msg_1',
+ requestedSlug: 'Demo',
+ topicId: 'tpc_1',
+ });
+ });
+
+ it('uploads files over the inline limit through publishSite', async () => {
+ const publishSite = vi.fn(async () => ({
+ latestRevisionNumber: 1,
+ publicUrl: 'https://example.lobehub.com/page',
+ }));
+ const large = 'y'.repeat(32 * 1024 + 4);
+
+ const result = await publishWorkspaceHtmlArtifact(
+ {
+ agentId: 'agt_1',
+ entryPath: 'index.html',
+ files: [
+ {
+ content: '<html><img src="hero.png"></html>',
+ contentType: 'text/html',
+ encoding: 'utf8',
+ path: 'index.html',
+ },
+ {
+ content: globalThis.btoa(large),
+ contentType: 'image/png',
+ encoding: 'base64',
+ path: 'hero.png',
+ },
+ ],
+ identifier: 'workspace-html-index-html',
+ title: 'Demo',
+ topicId: 'tpc_1',
+ },
+ {
+ createMessage: vi.fn(),
+ publishArtifact: vi.fn(),
+ publishSite,
+ },
+ );
+
+ expect(result.publicUrl).toBe('https://example.lobehub.com/page');
+ expect(publishSite).toHaveBeenCalledWith({
+ artifactIdentifier: 'workspace-html-index-html',
+ files: [
+ expect.objectContaining({
+ path: '/hero.png',
+ }),
+ ],
+ html: expect.stringContaining('src="/hero.png"'),
+ requestedSlug: 'Demo',
+ topicId: 'tpc_1',
+ });
+ });
+
+ it('publishes a prepacked plan without re-packing the file set', async () => {
+ const createMessage = vi.fn(
+ async (_params: {
+ agentId: string;
+ content: string;
+ role: 'assistant';
+ topicId: string;
+ }) => ({
+ id: 'msg_1',
+ }),
+ );
+ const publishArtifact = vi.fn(async () => ({ latestRevisionNumber: 1 }));
+
+ await publishWorkspaceHtmlArtifact(
+ {
+ agentId: 'agt_1',
+ entryPath: 'index.html',
+ files: [
+ {
+ content: '<html><link rel="stylesheet" href="./app.css"></html>',
+ contentType: 'text/html',
+ encoding: 'utf8',
+ path: 'index.html',
+ },
+ ],
+ identifier: 'workspace-html-index-html',
+ packed: { html: '<html>prepacked</html>', sidecars: [] },
+ title: 'Demo',
+ topicId: 'tpc_1',
+ },
+ { createMessage, publishArtifact },
+ );
+
+ expect(createMessage.mock.calls[0]?.[0]?.content).toContain('<html>prepacked</html>');
+ });
+
+ it('refuses to publish html that still points at unpacked local files', async () => {
+ await expect(
+ publishWorkspaceHtmlArtifact(
+ {
+ agentId: 'agt_1',
+ entryPath: 'index.html',
+ files: [
+ {
+ content: '<html><link rel="stylesheet" href="./app.css"></html>',
+ contentType: 'text/html',
+ encoding: 'utf8',
+ path: 'index.html',
+ },
+ ],
+ identifier: 'workspace-html-index-html',
+ title: 'Demo',
+ topicId: 'tpc_1',
+ },
+ {
+ createMessage: vi.fn(),
+ publishArtifact: vi.fn(),
+ },
+ ),
+ ).rejects.toThrow('unresolved-local-assets');
+ });
+
+ it('refuses to publish without an agent', async () => {
+ await expect(
+ publishWorkspaceHtmlArtifact(
+ {
+ entryPath: 'index.html',
+ files: [],
+ identifier: 'workspace-html-index-html',
+ title: 'Demo',
+ topicId: 'tpc_1',
+ },
+ {
+ createMessage: vi.fn(),
+ publishArtifact: vi.fn(),
+ },
+ ),
+ ).rejects.toThrow('unavailable');
+ });
+});
diff --git a/src/features/Portal/LocalFile/publishWorkspaceHtmlArtifact.ts b/src/features/Portal/LocalFile/publishWorkspaceHtmlArtifact.ts
new file mode 100644
index 00000000000..eecba3f2437
--- /dev/null
+++ b/src/features/Portal/LocalFile/publishWorkspaceHtmlArtifact.ts
@@ -0,0 +1,112 @@
+import { ARTIFACT_TAG } from '@lobechat/const';
+import { escapeXmlAttr } from '@lobechat/prompts';
+
+import type {
+ WorkspaceHtmlArtifactFile,
+ WorkspaceHtmlArtifactPublishInput,
+ WorkspaceHtmlArtifactPublishResult,
+} from '@/business/client/features/WorkspaceHtmlArtifactPublish';
+
+import { hostedPath, packWorkspaceHtmlDocument } from './packWorkspaceHtmlDocument';
+
+export const wrapWorkspaceHtmlArtifact = ({
+ html,
+ identifier,
+ title,
+}: {
+ html: string;
+ identifier: string;
+ title: string;
+}): string =>
+ `<${ARTIFACT_TAG} identifier="${escapeXmlAttr(identifier)}" type="text/html" title="${escapeXmlAttr(title)}">\n${html}\n</${ARTIFACT_TAG}>`;
+
+export interface PublishWorkspaceHtmlSiteParams {
+ artifactIdentifier: string;
+ files: WorkspaceHtmlArtifactFile[];
+ html: string;
+ requestedSlug?: string;
+ topicId: string;
+}
+
+export const publishWorkspaceHtmlArtifact = async (
+ input: WorkspaceHtmlArtifactPublishInput,
+ deps: {
+ createMessage: (params: {
+ agentId: string;
+ content: string;
+ role: 'assistant';
+ topicId: string;
+ }) => Promise<{ id: string }>;
+ publishArtifact: (params: {
+ artifactIdentifier: string;
+ messageId: string;
+ requestedSlug?: string;
+ topicId: string;
+ }) => Promise<{ latestRevisionNumber?: number; publicUrl?: string }>;
+ publishSite?: (
+ params: PublishWorkspaceHtmlSiteParams,
+ ) => Promise<{ latestRevisionNumber?: number; publicUrl?: string }>;
+ },
+): Promise<WorkspaceHtmlArtifactPublishResult> => {
+ if (!input.agentId) {
+ throw new Error('unavailable');
+ }
+
+ const packed =
+ input.packed ??
+ (() => {
+ const fresh = packWorkspaceHtmlDocument({
+ entryPath: input.entryPath,
+ files: input.files,
+ });
+ if (fresh.unresolvedHrefs.length > 0) {
+ throw new Error('unresolved-local-assets');
+ }
+ return fresh;
+ })();
+
+ if (packed.sidecars.length > 0) {
+ if (!deps.publishSite) {
+ throw new Error('unavailable');
+ }
+
+ const deployment = await deps.publishSite({
+ artifactIdentifier: input.identifier,
+ files: packed.sidecars.map((file) => ({
+ ...file,
+ path: hostedPath(file.path),
+ })),
+ html: packed.html,
+ requestedSlug: input.title,
+ topicId: input.topicId,
+ });
+
+ return {
+ publicUrl: deployment.publicUrl,
+ revision: deployment.latestRevisionNumber,
+ };
+ }
+
+ const message = await deps.createMessage({
+ agentId: input.agentId,
+ content: wrapWorkspaceHtmlArtifact({
+ html: packed.html,
+ identifier: input.identifier,
+ title: input.title,
+ }),
+ role: 'assistant',
+ topicId: input.topicId,
+ });
+
+ const deployment = await deps.publishArtifact({
+ artifactIdentifier: input.identifier,
+ messageId: message.id,
+ requestedSlug: input.title,
+ topicId: input.topicId,
+ });
+
+ return {
+ publicUrl: deployment.publicUrl,
+ revision: deployment.latestRevisionNumber,
+ };
+};
diff --git a/src/features/Portal/LocalFile/readWorkspaceAsset.test.ts b/src/features/Portal/LocalFile/readWorkspaceAsset.test.ts
new file mode 100644
index 00000000000..337b73ded4d
--- /dev/null
+++ b/src/features/Portal/LocalFile/readWorkspaceAsset.test.ts
@@ -0,0 +1,108 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const callTool = vi.fn();
+
+vi.mock('@/services/cloudSandbox', () => ({
+ cloudSandboxService: {
+ callTool,
+ },
+}));
+
+vi.mock('@/services/projectFile', () => ({
+ projectFileService: {
+ getLocalFilePreview: vi.fn(),
+ readProjectFileBytes: vi.fn(),
+ },
+}));
+
+const { readWorkspaceAsset, resolveWorkspaceAssetContentType } =
+ await import('./readWorkspaceAsset');
+
+describe('resolveWorkspaceAssetContentType', () => {
+ it('prefers the svg image type over a generic text/plain preview', () => {
+ expect(resolveWorkspaceAssetContentType('/tmp/site/dot.svg', 'text/plain')).toBe(
+ 'image/svg+xml',
+ );
+ expect(resolveWorkspaceAssetContentType('/tmp/site/app.css', 'text/plain')).toBe('text/css');
+ expect(resolveWorkspaceAssetContentType('/tmp/site/notes.bin', 'application/x-foo')).toBe(
+ 'application/x-foo',
+ );
+ });
+});
+
+describe('readWorkspaceAsset', () => {
+ beforeEach(() => {
+ callTool.mockReset();
+ });
+
+ it('reads sandbox text files through readLocalFile', async () => {
+ callTool.mockResolvedValueOnce({
+ result: { content: 'body { color: red; }', mimeType: 'text/css' },
+ success: true,
+ });
+
+ await expect(
+ readWorkspaceAsset({
+ path: '/sandbox/app.css',
+ sandboxTopicId: 'tpc_1',
+ workingDirectory: '/sandbox',
+ }),
+ ).resolves.toEqual({
+ bytes: new TextEncoder().encode('body { color: red; }'),
+ contentType: 'text/css',
+ ok: true,
+ text: 'body { color: red; }',
+ });
+
+ expect(callTool).toHaveBeenCalledWith(
+ 'readLocalFile',
+ { fullContent: true, path: '/sandbox/app.css' },
+ { topicId: 'tpc_1' },
+ );
+ });
+
+ it('reads sandbox binary files as bytes instead of text', async () => {
+ const png = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]);
+ callTool.mockResolvedValueOnce({
+ result: { stdout: globalThis.btoa(String.fromCharCode(...png)) },
+ success: true,
+ });
+
+ await expect(
+ readWorkspaceAsset({
+ path: '/sandbox/hero.png',
+ sandboxTopicId: 'tpc_1',
+ workingDirectory: '/sandbox',
+ }),
+ ).resolves.toEqual({
+ bytes: png,
+ contentType: 'image/png',
+ ok: true,
+ });
+
+ expect(callTool).toHaveBeenCalledWith(
+ 'runCommand',
+ expect.objectContaining({
+ command: expect.stringContaining('python3'),
+ }),
+ { topicId: 'tpc_1' },
+ );
+ expect(callTool).not.toHaveBeenCalledWith(
+ 'readLocalFile',
+ expect.anything(),
+ expect.anything(),
+ );
+ });
+
+ it('marks sandbox binary files unreadable when the byte export fails', async () => {
+ callTool.mockResolvedValue({ result: { stdout: '' }, success: false });
+
+ await expect(
+ readWorkspaceAsset({
+ path: '/sandbox/hero.png',
+ sandboxTopicId: 'tpc_1',
+ workingDirectory: '/sandbox',
+ }),
+ ).resolves.toEqual({ ok: false, reason: 'unreadable' });
+ });
+});
diff --git a/src/features/Portal/LocalFile/readWorkspaceAsset.ts b/src/features/Portal/LocalFile/readWorkspaceAsset.ts
new file mode 100644
index 00000000000..35fc5718dc6
--- /dev/null
+++ b/src/features/Portal/LocalFile/readWorkspaceAsset.ts
@@ -0,0 +1,206 @@
+import { base64ToBytes, getMimeType } from '@lobechat/utils';
+
+import { cloudSandboxService } from '@/services/cloudSandbox';
+import { type LocalFilePreview, projectFileService } from '@/services/projectFile';
+
+export const WORKSPACE_HTML_ARTIFACT_MAX_FILE_BYTES = 8 * 1024 * 1024;
+export const WORKSPACE_HTML_ARTIFACT_MAX_TOTAL_BYTES = 20 * 1024 * 1024;
+export const WORKSPACE_HTML_ARTIFACT_MAX_FILES = 64;
+export const WORKSPACE_HTML_ARTIFACT_INLINE_MAX_BYTES = 32 * 1024;
+
+export type ReadWorkspaceAssetFailure = 'missing' | 'oversized' | 'unreadable';
+
+export interface ReadWorkspaceAssetSuccess {
+ bytes: Uint8Array;
+ contentType: string;
+ ok: true;
+ text?: string;
+}
+
+export interface ReadWorkspaceAssetError {
+ ok: false;
+ reason: ReadWorkspaceAssetFailure;
+}
+
+export type ReadWorkspaceAssetResult = ReadWorkspaceAssetError | ReadWorkspaceAssetSuccess;
+
+const TEXT_CONTENT_TYPES = new Set([
+ 'application/javascript',
+ 'application/json',
+ 'application/xml',
+ 'image/svg+xml',
+ 'text/css',
+ 'text/html',
+ 'text/javascript',
+ 'text/plain',
+]);
+
+const isTextContentType = (contentType: string): boolean => {
+ const bare = contentType.split(';')[0].trim().toLowerCase();
+ return bare.startsWith('text/') || TEXT_CONTENT_TYPES.has(bare);
+};
+
+export const resolveWorkspaceAssetContentType = (path: string, reported?: string): string => {
+ const guessed = getMimeType(path);
+ if (guessed !== 'application/octet-stream') return guessed;
+
+ const reportedType = reported?.split(';')[0]?.trim();
+ return reportedType || guessed;
+};
+
+const quoteShellArg = (value: string): string => `'${value.replaceAll("'", `'\\''`)}'`;
+
+const decodeBase64Bytes = (value: string): Uint8Array | undefined => {
+ const compact = value.replaceAll(/\s+/g, '');
+ if (!compact) return;
+ try {
+ return base64ToBytes(compact);
+ } catch {
+ return;
+ }
+};
+
+const sandboxCommandOutput = (result: {
+ result?: unknown;
+ success: boolean;
+}): string | undefined => {
+ if (!result.success || !result.result || typeof result.result !== 'object') return;
+ const payload = result.result as { output?: unknown; stdout?: unknown };
+ if (typeof payload.stdout === 'string') return payload.stdout;
+ if (typeof payload.output === 'string') return payload.output;
+ return;
+};
+
+const readSandboxBytes = async (path: string, topicId: string): Promise<Uint8Array | undefined> => {
+ const python = await cloudSandboxService.callTool(
+ 'runCommand',
+ {
+ command: `python3 -c ${quoteShellArg(`import pathlib,base64; print(base64.b64encode(pathlib.Path(${JSON.stringify(path)}).read_bytes()).decode(), end="")`)}`,
+ description: 'Read workspace asset bytes',
+ },
+ { topicId },
+ );
+ const pythonBytes = decodeBase64Bytes(sandboxCommandOutput(python) ?? '');
+ if (pythonBytes) return pythonBytes;
+
+ const fallback = await cloudSandboxService.callTool(
+ 'runCommand',
+ {
+ command: `base64 ${quoteShellArg(path)}`,
+ description: 'Read workspace asset bytes',
+ },
+ { topicId },
+ );
+ return decodeBase64Bytes(sandboxCommandOutput(fallback) ?? '');
+};
+
+const previewToBytes = async (
+ preview: LocalFilePreview,
+): Promise<ReadWorkspaceAssetResult | undefined> => {
+ if (preview.type === 'text') {
+ const bytes = new TextEncoder().encode(preview.content);
+ if (bytes.byteLength > WORKSPACE_HTML_ARTIFACT_MAX_FILE_BYTES) {
+ return { ok: false, reason: 'oversized' };
+ }
+ return {
+ bytes,
+ contentType: preview.contentType,
+ ok: true,
+ text: preview.content,
+ };
+ }
+
+ if (preview.type === 'image' || preview.type === 'document') {
+ if (preview.blob.size > WORKSPACE_HTML_ARTIFACT_MAX_FILE_BYTES) {
+ return { ok: false, reason: 'oversized' };
+ }
+ const bytes = new Uint8Array(await preview.blob.arrayBuffer());
+ const text = isTextContentType(preview.contentType)
+ ? new TextDecoder().decode(bytes)
+ : undefined;
+ return { bytes, contentType: preview.contentType, ok: true, text };
+ }
+
+ return;
+};
+
+export const readWorkspaceAsset = async ({
+ deviceId,
+ path,
+ sandboxTopicId,
+ workingDirectory,
+}: {
+ deviceId?: string;
+ path: string;
+ sandboxTopicId?: string;
+ workingDirectory: string;
+}): Promise<ReadWorkspaceAssetResult> => {
+ try {
+ if (sandboxTopicId) {
+ const contentType = getMimeType(path);
+ if (isTextContentType(contentType)) {
+ const result = await cloudSandboxService.callTool(
+ 'readLocalFile',
+ { fullContent: true, path },
+ { topicId: sandboxTopicId },
+ );
+ if (!result.success || typeof result.result?.content !== 'string') {
+ return { ok: false, reason: 'missing' };
+ }
+
+ const text = result.result.content;
+ const bytes = new TextEncoder().encode(text);
+ if (bytes.byteLength > WORKSPACE_HTML_ARTIFACT_MAX_FILE_BYTES) {
+ return { ok: false, reason: 'oversized' };
+ }
+
+ return {
+ bytes,
+ contentType: resolveWorkspaceAssetContentType(path, result.result.mimeType),
+ ok: true,
+ text,
+ };
+ }
+
+ const bytes = await readSandboxBytes(path, sandboxTopicId);
+ if (!bytes) return { ok: false, reason: 'unreadable' };
+ if (bytes.byteLength > WORKSPACE_HTML_ARTIFACT_MAX_FILE_BYTES) {
+ return { ok: false, reason: 'oversized' };
+ }
+
+ 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),
+ };
+ }
+
+ const bytesResult = 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' };
+ }
+
+ const contentType = resolveWorkspaceAssetContentType(path, bytesResult.contentType);
+ const text = isTextContentType(contentType)
+ ? new TextDecoder().decode(bytesResult.bytes)
+ : undefined;
+ return { ...bytesResult, contentType, ok: true, text };
+ } catch {
+ return { ok: false, reason: 'missing' };
+ }
+};
diff --git a/src/features/Portal/LocalFile/usePublishWorkspaceHtmlFromFile.ts b/src/features/Portal/LocalFile/usePublishWorkspaceHtmlFromFile.ts
new file mode 100644
index 00000000000..ea309ab4ef2
--- /dev/null
+++ b/src/features/Portal/LocalFile/usePublishWorkspaceHtmlFromFile.ts
@@ -0,0 +1,83 @@
+import { toast } from '@lobehub/ui/base-ui';
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useWorkspaceHtmlArtifactPublish } from '@/business/client/features/WorkspaceHtmlArtifactPublish';
+import { isHtmlFile } from '@/components/HtmlPreview';
+import { useChatStore } from '@/store/chat';
+import { useUserStore } from '@/store/user';
+import { labPreferSelectors } from '@/store/user/selectors';
+
+import {
+ notifyWorkspaceHtmlPublishBlocked,
+ prepareWorkspaceHtmlPublish,
+ publishPreparedWorkspaceHtml,
+} from './prepareWorkspaceHtmlPublish';
+import { openWorkspaceHtmlPublishConfirm } from './PublishHtmlArtifactConfirm';
+
+interface UsePublishWorkspaceHtmlFromFileInput {
+ deviceId?: string;
+ workingDirectory: string;
+}
+
+export const usePublishWorkspaceHtmlFromFile = ({
+ deviceId,
+ workingDirectory,
+}: UsePublishWorkspaceHtmlFromFileInput) => {
+ const { t } = useTranslation('chat');
+ const enabled = useUserStore(labPreferSelectors.enableArtifactDeployment);
+ const { available, getExisting, publish } = useWorkspaceHtmlArtifactPublish();
+ const agentId = useChatStore((s) => s.activeAgentId);
+ const topicId = useChatStore((s) => s.activeTopicId);
+ const openLocalFile = useChatStore((s) => s.openLocalFile);
+
+ const canOfferFile = useCallback(
+ (path: string, isFolder: boolean) => enabled && available && !isFolder && isHtmlFile({ path }),
+ [available, enabled],
+ );
+
+ const publishFile = useCallback(
+ async (filePath: string) => {
+ if (!topicId) {
+ toast.error(t('workingPanel.localFile.publish.noTopic'));
+ return;
+ }
+
+ const loadingToast = toast.loading(t('workingPanel.localFile.publish.scanning'));
+ try {
+ const plan = await prepareWorkspaceHtmlPublish({
+ deviceId,
+ filePath,
+ workingDirectory,
+ });
+
+ loadingToast.close();
+
+ if ('blocked' in plan) {
+ notifyWorkspaceHtmlPublishBlocked(plan);
+ return;
+ }
+
+ const existing = await getExisting({ identifier: plan.gathered.identifier, topicId });
+
+ openWorkspaceHtmlPublishConfirm({
+ hasExisting: !!existing,
+ plan,
+ onOk: () => {
+ void publishPreparedWorkspaceHtml({ agentId, plan, publish, topicId }).then(
+ (result) => {
+ if (result) openLocalFile({ deviceId, filePath, workingDirectory });
+ },
+ );
+ },
+ });
+ } catch {
+ loadingToast.close();
+ toast.error(t('workingPanel.localFile.publish.failed'));
+ }
+ },
+ [agentId, deviceId, getExisting, openLocalFile, publish, t, topicId, workingDirectory],
+ );
+
+ return { canOfferFile, publishFile };
+};
diff --git a/src/features/Portal/LocalFile/workspaceHtmlPath.ts b/src/features/Portal/LocalFile/workspaceHtmlPath.ts
new file mode 100644
index 00000000000..1196a18c584
--- /dev/null
+++ b/src/features/Portal/LocalFile/workspaceHtmlPath.ts
@@ -0,0 +1,213 @@
+import { sha256 } from 'js-sha256';
+
+const toSlashPath = (filePath: string): string => filePath.replaceAll('\\', '/');
+
+const fromSlashPath = (filePath: string, sourcePath: string): string => {
+ const usesWindowsSeparator = sourcePath.includes('\\') && !sourcePath.includes('/');
+ return usesWindowsSeparator ? filePath.replaceAll('/', '\\') : filePath;
+};
+
+const stripTrailingSlash = (value: string) => (value.endsWith('/') ? value.slice(0, -1) : value);
+
+const DARWIN_PRIVATE_ROOTS = ['/tmp', '/var', '/etc'] as const;
+
+const canonicalizeWorkspacePath = (filePath: string): string => {
+ const slashPath = stripTrailingSlash(toSlashPath(filePath));
+
+ for (const root of DARWIN_PRIVATE_ROOTS) {
+ const privateRoot = `/private${root}`;
+ if (slashPath === privateRoot || slashPath.startsWith(`${privateRoot}/`)) {
+ return slashPath.slice('/private'.length);
+ }
+ }
+
+ return slashPath;
+};
+
+const decodePathSegment = (segment: string): string => {
+ try {
+ return decodeURIComponent(segment);
+ } catch {
+ return segment;
+ }
+};
+
+const splitResourceHref = (href: string): string => {
+ const queryIndex = href.indexOf('?');
+ const hashIndex = href.indexOf('#');
+ const suffixIndex = [queryIndex, hashIndex]
+ .filter((index) => index >= 0)
+ .sort((a, b) => a - b)[0];
+ return (suffixIndex === undefined ? href : href.slice(0, suffixIndex)).trim();
+};
+
+const normalizeSlashPath = (
+ filePath: string,
+ { preserveLeadingDoubleSlash = false }: { preserveLeadingDoubleSlash?: boolean } = {},
+): string => {
+ const leadingEmptySegmentLimit = preserveLeadingDoubleSlash && filePath.startsWith('//') ? 2 : 1;
+ const normalizedSegments: string[] = [];
+
+ for (const segment of filePath.split('/')) {
+ if (!segment || segment === '.') {
+ if (
+ segment === '' &&
+ normalizedSegments.length < leadingEmptySegmentLimit &&
+ normalizedSegments.every((item) => item === '')
+ ) {
+ normalizedSegments.push('');
+ }
+ continue;
+ }
+
+ if (segment === '..') {
+ if (normalizedSegments.length > 1) normalizedSegments.pop();
+ continue;
+ }
+
+ normalizedSegments.push(segment);
+ }
+
+ return normalizedSegments.join('/') || '/';
+};
+
+const parentDirectory = (filePath: string): string => {
+ const slashPath = toSlashPath(filePath);
+ const isUncPath = slashPath.startsWith('//');
+ const lastSeparatorIndex = slashPath.lastIndexOf('/');
+ if (lastSeparatorIndex < 0) return '';
+ if (slashPath.startsWith('/') && lastSeparatorIndex === 0) return '/';
+ const directory = slashPath.slice(0, lastSeparatorIndex);
+ return fromSlashPath(isUncPath && directory === '' ? '//' : directory, filePath);
+};
+
+export const isPathInsideWorkspace = (targetPath: string, workingDirectory: string): boolean => {
+ const target = canonicalizeWorkspacePath(targetPath);
+ const root = canonicalizeWorkspacePath(workingDirectory);
+ return target === root || target.startsWith(`${root}/`);
+};
+
+export const toWorkspaceAbsolutePath = (filePath: string, workingDirectory: string): string => {
+ const slashPath = toSlashPath(filePath);
+ if (isPathInsideWorkspace(filePath, workingDirectory)) {
+ return fromSlashPath(slashPath, workingDirectory);
+ }
+
+ const isAbsolute = slashPath.startsWith('/') || /^[a-zA-Z]:/u.test(filePath);
+ if (isAbsolute) return filePath;
+
+ const root = stripTrailingSlash(toSlashPath(workingDirectory));
+ return fromSlashPath(normalizeSlashPath(`${root}/${slashPath}`), workingDirectory);
+};
+
+export const toWorkspaceRelativePath = (absolutePath: string, workingDirectory: string): string => {
+ const target = canonicalizeWorkspacePath(absolutePath);
+ const root = canonicalizeWorkspacePath(workingDirectory);
+ if (target === root) return '';
+ if (target.startsWith(`${root}/`)) return target.slice(root.length + 1);
+ return stripTrailingSlash(toSlashPath(absolutePath)).split('/').at(-1) ?? absolutePath;
+};
+
+export const lowestCommonAncestorDirectory = (
+ absolutePaths: string[],
+ workingDirectory: string,
+): 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 [first, ...rest] = relativeDirs;
+ const common: string[] = [];
+
+ for (const [index, segment] of first.entries()) {
+ if (rest.every((dirs) => dirs[index] === segment)) {
+ common.push(segment);
+ continue;
+ }
+ break;
+ }
+
+ if (common.length === 0) return workingDirectory;
+
+ const slashRoot = `${stripTrailingSlash(toSlashPath(workingDirectory))}/${common.join('/')}`;
+ return fromSlashPath(slashRoot, workingDirectory);
+};
+
+const joinPath = (basePath: string, segments: string[], sourcePath: string): string => {
+ const slashBase = toSlashPath(basePath);
+ const isUncPath = slashBase.startsWith('//');
+ const resolved = normalizeSlashPath(
+ slashBase ? [slashBase, ...segments].join('/') : segments.join('/'),
+ {
+ preserveLeadingDoubleSlash: isUncPath,
+ },
+ );
+ return fromSlashPath(resolved, sourcePath);
+};
+
+const resolveAgainstDirectory = (directory: string, href: string, sourcePath: string): string => {
+ const segments = href.split(/[\\/]+/).map(decodePathSegment);
+ return joinPath(directory, segments, sourcePath);
+};
+
+export const resolveLocalResourceHref = ({
+ href,
+ rootDirectory,
+ sourcePath,
+ workingDirectory,
+}: {
+ href: string;
+ rootDirectory?: string;
+ sourcePath: string;
+ workingDirectory: string;
+}): { absolutePath?: string; href: string; kind: 'empty' | 'escape' | 'remote' | 'resolved' } => {
+ const assetPath = splitResourceHref(href);
+ if (!assetPath || assetPath === '#' || assetPath.startsWith('#')) {
+ return { href, kind: 'empty' };
+ }
+
+ if (/^[a-z][a-z\d+.-]*:/i.test(assetPath) || assetPath.startsWith('//')) {
+ return { href, kind: 'remote' };
+ }
+
+ const resolvedPath = assetPath.startsWith('/')
+ ? resolveAgainstDirectory(rootDirectory ?? workingDirectory, assetPath.slice(1), sourcePath)
+ : resolveAgainstDirectory(parentDirectory(sourcePath), assetPath, sourcePath);
+
+ if (!isPathInsideWorkspace(resolvedPath, workingDirectory)) {
+ return { absolutePath: resolvedPath, href, kind: 'escape' };
+ }
+
+ return { absolutePath: resolvedPath, href, kind: 'resolved' };
+};
+
+export const createWorkspaceHtmlArtifactIdentifier = (relativePath: string): 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);
+
+ return `workspace-html-${slug || 'page'}-${digest}`;
+};
+
+export const workspaceHtmlArtifactIdentifierForFile = (
+ filePath: string,
+ workingDirectory: string,
+): string => {
+ const relativePath =
+ toWorkspaceRelativePath(
+ toWorkspaceAbsolutePath(filePath, workingDirectory),
+ workingDirectory,
+ ) ||
+ (stripTrailingSlash(toSlashPath(filePath)).split('/').at(-1) ?? filePath);
+ return createWorkspaceHtmlArtifactIdentifier(relativePath);
+};
+
+export { parentDirectory };
diff --git a/src/services/electron/localFileService.test.ts b/src/services/electron/localFileService.test.ts
index 02589d1a94e..fb126edb87e 100644
--- a/src/services/electron/localFileService.test.ts
+++ b/src/services/electron/localFileService.test.ts
@@ -162,4 +162,34 @@ describe('localFileService', () => {
).rejects.toThrow('Unsupported local file preview type');
expect(textMock).not.toHaveBeenCalled();
});
+
+ it('reads local file bytes from the preview URL', async () => {
+ const { localFileService } = await import('./localFileService');
+
+ mockLocalSystem.getLocalFilePreviewUrl.mockResolvedValue({
+ success: true,
+ url: 'localfile://preview/font.woff2',
+ });
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(
+ async () =>
+ ({
+ arrayBuffer: vi.fn(async () => new Uint8Array([10, 20, 30]).buffer),
+ headers: { get: vi.fn(() => 'font/woff2') },
+ ok: true,
+ }) as unknown as Response,
+ ),
+ );
+
+ const result = await localFileService.readLocalFileBytes({
+ path: '/repo/font.woff2',
+ workingDirectory: '/repo',
+ });
+
+ expect(result).toEqual({
+ bytes: new Uint8Array([10, 20, 30]),
+ contentType: 'font/woff2',
+ });
+ });
});
diff --git a/src/services/electron/localFileService.ts b/src/services/electron/localFileService.ts
index da22bfbcbaf..8def3249eda 100644
--- a/src/services/electron/localFileService.ts
+++ b/src/services/electron/localFileService.ts
@@ -244,6 +244,23 @@ class LocalFileService {
return fetchLocalFilePreview(result.url, params.accept, params.resourceScope);
}
+ async readLocalFileBytes(
+ params: LocalFilePreviewUrlParams,
+ ): Promise<{ bytes: Uint8Array; contentType: string } | undefined> {
+ const result = await ensureElectronIpc().localSystem.getLocalFilePreviewUrl(params);
+
+ if (!result.success || !result.url) return;
+
+ const response = await fetch(result.url);
+ if (!response.ok) return;
+
+ return {
+ bytes: new Uint8Array(await response.arrayBuffer()),
+ contentType:
+ normalizeContentType(response.headers.get('content-type')) || 'application/octet-stream',
+ };
+ }
+
async prepareSkillDirectory(
params: PrepareSkillDirectoryParams,
): Promise<PrepareSkillDirectoryResult> {
diff --git a/src/services/projectFile.ts b/src/services/projectFile.ts
index fdaad502338..e1ac95d6893 100644
--- a/src/services/projectFile.ts
+++ b/src/services/projectFile.ts
@@ -1,3 +1,4 @@
+import { isDesktop } from '@lobechat/const';
import type {
LocalFilePreviewUrlParams,
LocalMoveFilesResultItem,
@@ -115,6 +116,24 @@ class ProjectFileService {
return localFileService.getLocalFilePreview(params);
}
+ /**
+ * Raw bytes for a file in a project working directory. Only the local desktop
+ * transport can serve bytes today — remote devices have no byte-read RPC yet,
+ * so device-backed calls resolve to `undefined`.
+ */
+ async readProjectFileBytes({
+ deviceId,
+ path,
+ workingDirectory,
+ }: {
+ deviceId?: string;
+ path: string;
+ workingDirectory: string;
+ }): Promise<{ bytes: Uint8Array; contentType: string } | undefined> {
+ if (deviceId || !isDesktop) return undefined;
+ return localFileService.readLocalFileBytes({ path, workingDirectory });
+ }
+
/**
* Move one or more files/folders within a project working directory. Batched:
* each item succeeds or fails independently.