Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): refresh local HTML preview after agent edits (#1074)

codeingforcoffee989043f9f465
diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/openInSidebarBrowser.test.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/openInSidebarBrowser.test.ts
index 4a11a2a810..d17ea5dd28 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/openInSidebarBrowser.test.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/openInSidebarBrowser.test.ts
@@ -23,7 +23,12 @@ vi.mock('../detachedSidebarRouting', () => ({
import { addTab, ensureHydrated } from '../../store';
import { requestRightSidebarVisibility } from '../sidebarCommands';
import { routeSidebarCommand } from '../detachedSidebarRouting';
-import { openUrlInSidebarBrowser, pathToFileUrl } from '../openInSidebarBrowser';
+import {
+ openUrlInSidebarBrowser,
+ pathToFileUrl,
+ fileUrlToAbsPath,
+ isLocalHtmlFileUrl,
+} from '../openInSidebarBrowser';
describe('pathToFileUrl', () => {
it('converts a Windows drive path with backslashes', () => {
@@ -40,6 +45,30 @@ describe('pathToFileUrl', () => {
});
});
+describe('fileUrlToAbsPath / isLocalHtmlFileUrl', () => {
+ it('round-trips POSIX paths including spaces', () => {
+ expect(fileUrlToAbsPath('file:///Users/a%20b/x.html')).toBe('/Users/a b/x.html');
+ expect(isLocalHtmlFileUrl('file:///Users/a%20b/x.html')).toBe(true);
+ });
+
+ it('round-trips Windows drive paths', () => {
+ expect(fileUrlToAbsPath('file:///E:/out/index.html')).toBe('E:\\out\\index.html');
+ expect(isLocalHtmlFileUrl('file:///E:/out/index.htm')).toBe(true);
+ });
+
+ it('rejects non-file and non-html URLs', () => {
+ expect(fileUrlToAbsPath('https://example.com/x.html')).toBeNull();
+ expect(fileUrlToAbsPath('file:///%E0%A4%A.html')).toBeNull();
+ expect(isLocalHtmlFileUrl('https://example.com/x.html')).toBe(false);
+ expect(isLocalHtmlFileUrl('file:///tmp/notes.md')).toBe(false);
+ expect(isLocalHtmlFileUrl('about:blank')).toBe(false);
+ });
+
+ it('ignores hash/query when recovering the path', () => {
+ expect(fileUrlToAbsPath('file:///tmp/x.html#section')).toBe('/tmp/x.html');
+ });
+});
+
describe('openUrlInSidebarBrowser', () => {
beforeEach(() => {
vi.clearAllMocks();
diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts
new file mode 100644
index 0000000000..99908e0b14
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts
@@ -0,0 +1,128 @@
+/**
+ * 从最近一轮消息里的文件编辑产物提取改动路径。
+ *
+ * 这是 renderer 已经拿到的会话产物,不需要额外扫描磁盘或给文件挂 watcher。
+ * Review 的「最近一轮」过滤与本地 HTML 预览刷新共用同一套口径。
+ */
+
+import type { ChatMessage } from '@/lib/makerChatStore';
+
+const EDIT_TOOL_NAMES = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit']);
+
+function slashPath(p: string): string {
+ return p.replace(/\\/g, '/').replace(/\/+/g, '/');
+}
+
+function normalizeForCompare(p: string, platform: string): string {
+ const normalized = slashPath(p);
+ return platform === 'win32' ? normalized.toLowerCase() : normalized;
+}
+
+function defaultPlatform(): string {
+ return typeof window === 'undefined' ? '' : (window.electronAPI?.platform ?? '');
+}
+
+function isAbsoluteLikePath(filePath: string): boolean {
+ return (
+ filePath.startsWith('/') || /^[a-zA-Z]:[\\/]/.test(filePath) || filePath.startsWith('\\\\')
+ );
+}
+
+function normalizeWorkdirRelativePath(filePath: string): string | null {
+ const rel = slashPath(filePath).replace(/^\.\//, '');
+ return rel && rel !== '.' ? rel : null;
+}
+
+export function absoluteToWorkdirRelative(
+ filePath: string,
+ workdir: string,
+ platform = defaultPlatform(),
+): string | null {
+ if (!filePath || !workdir) return null;
+ const file = normalizeForCompare(filePath, platform);
+ const root = normalizeForCompare(workdir, platform).replace(/\/$/, '');
+ if (file === root) return '';
+ if (!file.startsWith(`${root}/`)) return null;
+ return slashPath(filePath).slice(slashPath(workdir).replace(/\/$/, '').length + 1);
+}
+
+function addPathLike(paths: string[], value: unknown): void {
+ if (typeof value === 'string' && value.trim()) paths.push(value);
+}
+
+function collectCodexFileChangePaths(input: Record<string, unknown> | null): string[] {
+ const paths: string[] = [];
+ const changes = input?.changes;
+ if (!Array.isArray(changes)) return paths;
+ for (const change of changes) {
+ if (!change || typeof change !== 'object') continue;
+ const record = change as Record<string, unknown>;
+ addPathLike(paths, record.path);
+ const kind = record.kind;
+ if (kind && typeof kind === 'object') {
+ const kindRecord = kind as Record<string, unknown>;
+ addPathLike(paths, kindRecord.move_path);
+ addPathLike(paths, kindRecord.movePath);
+ }
+ addPathLike(paths, record.move_path);
+ addPathLike(paths, record.movePath);
+ }
+ return paths;
+}
+
+function extractToolFilePaths(msg: ChatMessage): string[] {
+ if (msg.role !== 'tool_use' || !msg.toolName) return [];
+ const input = (msg.toolInput as Record<string, unknown> | null) ?? null;
+ if (msg.toolName === 'file_change') return collectCodexFileChangePaths(input);
+ if (!EDIT_TOOL_NAMES.has(msg.toolName)) return [];
+ const filePath = input?.file_path;
+ return typeof filePath === 'string' && filePath ? [filePath] : [];
+}
+
+function toolPathToWorkdirRelative(
+ filePath: string,
+ workdir: string,
+ platform: string,
+): string | null {
+ if (isAbsoluteLikePath(filePath)) {
+ return absoluteToWorkdirRelative(filePath, workdir, platform);
+ }
+ return normalizeWorkdirRelativePath(filePath);
+}
+
+export function collectLastTurnPaths(
+ messages: readonly ChatMessage[],
+ workdir: string | null,
+ platform = defaultPlatform(),
+): Set<string> {
+ const paths = new Set<string>();
+ if (!workdir) return paths;
+ let start = 0;
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
+ if (messages[i].role === 'user') {
+ start = i;
+ break;
+ }
+ }
+ for (let i = start; i < messages.length; i += 1) {
+ for (const filePath of extractToolFilePaths(messages[i])) {
+ const rel = toolPathToWorkdirRelative(filePath, workdir, platform);
+ if (rel) paths.add(rel);
+ }
+ }
+ return paths;
+}
+
+export function wasFileChangedInLastTurn(
+ messages: readonly ChatMessage[],
+ workdir: string,
+ absoluteFilePath: string,
+ platform = defaultPlatform(),
+): boolean {
+ const target = absoluteToWorkdirRelative(absoluteFilePath, workdir, platform);
+ if (!target) return false;
+ const normalizedTarget = normalizeForCompare(target, platform);
+ return [...collectLastTurnPaths(messages, workdir, platform)].some(
+ (path) => normalizeForCompare(path, platform) === normalizedTarget,
+ );
+}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts
index d63a3b8e42..033049c100 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts
@@ -36,6 +36,43 @@ export function pathToFileUrl(absPath: string): string {
return `file://${encoded}`;
}
+/** 本地 HTML 预览自动刷新只认这些扩展名(与 browserOpenableExts / 文件树菜单对齐)。 */
+const LOCAL_HTML_EXT_RE = /\.(html?|xhtml)$/i;
+
+/**
+ * file:// URL → 本机绝对路径。与 pathToFileUrl 互逆:
+ * file:///Users/a%20b/x.html → /Users/a b/x.html
+ * file:///E:/out/index.html → E:\out\index.html (win32 风格分隔)
+ *
+ * 只取 pathname(忽略 hash / query);非 file: 或解析失败 → null。
+ */
+export function fileUrlToAbsPath(url: string): string | null {
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ return null;
+ }
+ if (parsed.protocol !== 'file:') return null;
+ let pathname: string;
+ try {
+ pathname = decodeURIComponent(parsed.pathname);
+ } catch {
+ return null;
+ }
+ // Windows: URL pathname 形如 `/E:/out/x.html`,剥掉前导 `/` 并还原 `\`。
+ if (/^\/[A-Za-z]:[\\/]/.test(pathname)) {
+ pathname = pathname.slice(1).replace(/\//g, '\\');
+ }
+ return pathname || null;
+}
+
+/** 当前页是否为本地 HTML 文件预览(file:// + html/htm/xhtml)。 */
+export function isLocalHtmlFileUrl(url: string): boolean {
+ const abs = fileUrlToAbsPath(url);
+ return abs !== null && LOCAL_HTML_EXT_RE.test(abs);
+}
+
export interface OpenUrlInSidebarBrowserOptions {
/**
* false = 不是用户当次手势(插件 preview 槽开页):标签照常开、内容照常加载,
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts
index 3b48eb9ee1..07b1e80af6 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts
@@ -8,98 +8,14 @@
import { useCallback, useMemo, useSyncExternalStore } from 'react';
import { makerChatStore, type ChatMessage } from '@/lib/makerChatStore';
+import { collectLastTurnPaths } from '../../lib/lastTurnChangedFiles';
-const EDIT_TOOL_NAMES = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit']);
const EMPTY_MESSAGES: readonly ChatMessage[] = Object.freeze([]);
-function slashPath(p: string): string {
- return p.replace(/\\/g, '/').replace(/\/+/g, '/');
-}
-
-function normalizeForCompare(p: string, platform: string): string {
- const normalized = slashPath(p);
- return platform === 'win32' ? normalized.toLowerCase() : normalized;
-}
-
-function defaultPlatform(): string {
- return typeof window === 'undefined' ? '' : window.electronAPI?.platform ?? '';
-}
-
-function isAbsoluteLikePath(filePath: string): boolean {
- return filePath.startsWith('/') || /^[a-zA-Z]:[\\/]/.test(filePath) || filePath.startsWith('\\\\');
-}
-
-function normalizeRepoRelativePath(filePath: string): string | null {
- const rel = slashPath(filePath).replace(/^\.\//, '');
- return rel && rel !== '.' ? rel : null;
-}
-
-export function absoluteToRepoRelative(filePath: string, repoRoot: string, platform = defaultPlatform()): string | null {
- if (!filePath || !repoRoot) return null;
- const file = normalizeForCompare(filePath, platform);
- const root = normalizeForCompare(repoRoot, platform).replace(/\/$/, '');
- if (file === root) return '';
- if (!file.startsWith(`${root}/`)) return null;
- return slashPath(filePath).slice(slashPath(repoRoot).replace(/\/$/, '').length + 1);
-}
-
-function addPathLike(paths: string[], value: unknown): void {
- if (typeof value === 'string' && value.trim()) paths.push(value);
-}
-
-function collectCodexFileChangePaths(input: Record<string, unknown> | null): string[] {
- const paths: string[] = [];
- const changes = input?.changes;
- if (!Array.isArray(changes)) return paths;
- for (const change of changes) {
- if (!change || typeof change !== 'object') continue;
- const record = change as Record<string, unknown>;
- addPathLike(paths, record.path);
- const kind = record.kind;
- if (kind && typeof kind === 'object') {
- const kindRecord = kind as Record<string, unknown>;
- addPathLike(paths, kindRecord.move_path);
- addPathLike(paths, kindRecord.movePath);
- }
- addPathLike(paths, record.move_path);
- addPathLike(paths, record.movePath);
- }
- return paths;
-}
-
-function extractToolFilePaths(msg: ChatMessage): string[] {
- if (msg.role !== 'tool_use') return [];
- if (!msg.toolName) return [];
- const input = (msg.toolInput as Record<string, unknown> | null) ?? null;
- if (msg.toolName === 'file_change') return collectCodexFileChangePaths(input);
- if (!EDIT_TOOL_NAMES.has(msg.toolName)) return [];
- const filePath = input?.file_path;
- return typeof filePath === 'string' && filePath ? [filePath] : [];
-}
-
-function toolPathToRepoRelative(filePath: string, repoRoot: string): string | null {
- if (isAbsoluteLikePath(filePath)) return absoluteToRepoRelative(filePath, repoRoot);
- return normalizeRepoRelativePath(filePath);
-}
-
-export function collectLastTurnPaths(messages: readonly ChatMessage[], repoRoot: string | null): Set<string> {
- const paths = new Set<string>();
- if (!repoRoot) return paths;
- let start = 0;
- for (let i = messages.length - 1; i >= 0; i -= 1) {
- if (messages[i].role === 'user') {
- start = i;
- break;
- }
- }
- for (let i = start; i < messages.length; i += 1) {
- for (const filePath of extractToolFilePaths(messages[i])) {
- const rel = toolPathToRepoRelative(filePath, repoRoot);
- if (rel) paths.add(rel);
- }
- }
- return paths;
-}
+export {
+ absoluteToWorkdirRelative as absoluteToRepoRelative,
+ collectLastTurnPaths,
+} from '../../lib/lastTurnChangedFiles';
export function useLastTurnFilter(sessionId: string | null, repoRoot: string | null): Set<string> {
const subscribe = useCallback(
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx
index 5d7d10549c..83973422c9 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx
@@ -49,6 +49,7 @@ import type { TabKindHostContext } from '../../types';
import { BrowserChrome, type BrowserChromeHandle } from './BrowserChrome';
import { BrowserCommentPopover } from './BrowserCommentPopover';
import { useBrowserComment } from './useBrowserComment';
+import { useLocalHtmlAutoReload } from './useLocalHtmlAutoReload';
import type { WebBrowserState } from './index';
const log = createLogger('rightSidebar.browserTabBody');
@@ -101,6 +102,16 @@ export function BrowserTabBody({ state, ctx, active, shellVisible }: BrowserTabB
browserUrlRef.current = browser.url;
navigateRef.current = browser.navigate;
+ // 当前会话一轮结束后,如果该轮产物修改了正在预览的本地 HTML,则刷新一次。
+ // 不监听磁盘;非激活 tab 与 SSH 远程会话不参与。
+ useLocalHtmlAutoReload({
+ sessionId,
+ workdir: ctx.workdir,
+ url: browser.url || state.url,
+ reload: browser.reload,
+ enabled: active === true && ctx.remoteHostId === null && !browser.crash,
+ });
+
// 把 pool 的 wrapper 挂进 slot —— useLayoutEffect(在 paint 前移 DOM,避免闪)。
// 卸载时把 wrapper 挪回 pool 的 off-screen container 保活 webContents。
// 切到不同 tabId 时:wrapper 引用变,effect 重跑,旧 wrapper 自动回 parking 区。
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/__tests__/BrowserTabBody.navigation.test.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/__tests__/BrowserTabBody.navigation.test.ts
index 6ca00fd7f3..9f3ec174a2 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/__tests__/BrowserTabBody.navigation.test.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/__tests__/BrowserTabBody.navigation.test.ts
@@ -26,6 +26,10 @@ vi.mock('../../../hooks/useBrowserWebview', () => ({
useBrowserWebview: () => browserState,
}));
+vi.mock('../useLocalHtmlAutoReload', () => ({
+ useLocalHtmlAutoReload: vi.fn(),
+}));
+
vi.mock('../../../lib/browserWebviewPool', () => ({
browserWebviewPool: {
release: vi.fn(),
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/__tests__/useLocalHtmlAutoReload.test.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/__tests__/useLocalHtmlAutoReload.test.ts
new file mode 100644
index 0000000000..45ca50bdcc
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/__tests__/useLocalHtmlAutoReload.test.ts
@@ -0,0 +1,226 @@
+// @vitest-environment jsdom
+
+import { act, cleanup, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const chat = vi.hoisted(() => {
+ const listeners = new Set<() => void>();
+ return {
+ listeners,
+ snapshot: {
+ messages: [] as Array<Record<string, unknown>>,
+ agentStatus: {
+ status: 'Idle',
+ tokenUsage: 0,
+ costUsd: 0,
+ contextTokens: 0,
+ contextWindow: 0,
+ isRunning: false,
+ startedAt: null,
+ },
+ } as {
+ messages: Array<Record<string, unknown>>;
+ agentStatus: {
+ status: string;
+ tokenUsage: number;
+ costUsd: number;
+ contextTokens: number;
+ contextWindow: number;
+ isRunning: boolean;
+ startedAt: number | null;
+ sideTaskRunning?: boolean;
+ };
+ },
+ };
+});
+
+vi.mock('@/lib/makerChatStore', () => ({
+ makerChatStore: {
+ getSnapshot: () => chat.snapshot,
+ subscribe: (_sessionId: string, listener: () => void) => {
+ chat.listeners.add(listener);
+ return () => chat.listeners.delete(listener);
+ },
+ },
+}));
+
+import { useLocalHtmlAutoReload } from '../useLocalHtmlAutoReload';
+
+function setTurnState(
+ isRunning: boolean,
+ messages: Array<Record<string, unknown>>,
+ sideTaskRunning = false,
+): void {
+ chat.snapshot = {
+ messages,
+ agentStatus: {
+ ...chat.snapshot.agentStatus,
+ status: isRunning ? 'Working' : 'Done',
+ isRunning,
+ startedAt: isRunning ? Date.now() : null,
+ ...(sideTaskRunning ? { sideTaskRunning: true } : {}),
+ },
+ };
+ act(() => {
+ for (const listener of chat.listeners) listener();
+ });
+}
+
+const userMessage = { clientId: 'u1', role: 'user', content: 'update preview' };
+
+describe('useLocalHtmlAutoReload', () => {
+ beforeEach(() => {
+ chat.listeners.clear();
+ chat.snapshot = {
+ messages: [],
+ agentStatus: {
+ status: 'Idle',
+ tokenUsage: 0,
+ costUsd: 0,
+ contextTokens: 0,
+ contextWindow: 0,
+ isRunning: false,
+ startedAt: null,
+ },
+ };
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ });
+
+ it('reloads once when the completed turn changed the active HTML preview', () => {
+ const reload = vi.fn();
+ renderHook(() =>
+ useLocalHtmlAutoReload({
+ sessionId: 's1',
+ workdir: '/repo',
+ url: 'file:///repo/dist/preview.html',
+ reload,
+ }),
+ );
+
+ setTurnState(true, [userMessage]);
+ const messages = [
+ userMessage,
+ {
+ clientId: 't1',
+ role: 'tool_use',
+ content: '',
+ toolName: 'Write',
+ toolInput: { file_path: '/repo/dist/preview.html' },
+ },
+ ];
+ setTurnState(true, messages);
+ expect(reload).not.toHaveBeenCalled();
+
+ setTurnState(false, messages);
+ expect(reload).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not reload when the completed turn changed another file', () => {
+ const reload = vi.fn();
+ renderHook(() =>
+ useLocalHtmlAutoReload({
+ sessionId: 's1',
+ workdir: '/repo',
+ url: 'file:///repo/dist/preview.html',
+ reload,
+ }),
+ );
+
+ const messages = [
+ userMessage,
+ {
+ clientId: 't1',
+ role: 'tool_use',
+ content: '',
+ toolName: 'file_change',
+ toolInput: { changes: [{ path: 'src/app.ts' }] },
+ },
+ ];
+ setTurnState(true, messages);
+ setTurnState(false, messages);
+
+ expect(reload).not.toHaveBeenCalled();
+ });
+
+ it('does not reuse a previous turn edit when a later turn changes nothing', () => {
+ const reload = vi.fn();
+ renderHook(() =>
+ useLocalHtmlAutoReload({
+ sessionId: 's1',
+ workdir: '/repo',
+ url: 'file:///repo/preview.html',
+ reload,
+ }),
+ );
+
+ const firstTurnMessages = [
+ userMessage,
+ {
+ clientId: 't1',
+ role: 'tool_use',
+ content: '',
+ toolName: 'Write',
+ toolInput: { file_path: '/repo/preview.html' },
+ },
+ ];
+ setTurnState(true, [userMessage]);
+ setTurnState(false, firstTurnMessages);
+ expect(reload).toHaveBeenCalledTimes(1);
+
+ setTurnState(true, firstTurnMessages);
+ setTurnState(false, [
+ ...firstTurnMessages,
+ { clientId: 'a2', role: 'assistant', content: 'No further changes.' },
+ ]);
+ expect(reload).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not subscribe for remote pages or inactive tabs', () => {
+ const { rerender } = renderHook(
+ ({ enabled }) =>
+ useLocalHtmlAutoReload({
+ sessionId: 's1',
+ workdir: '/repo',
+ url: 'https://example.com/preview.html',
+ reload: vi.fn(),
+ enabled,
+ }),
+ { initialProps: { enabled: true } },
+ );
+ expect(chat.listeners.size).toBe(0);
+
+ rerender({ enabled: false });
+ expect(chat.listeners.size).toBe(0);
+ });
+
+ it('ignores side-task running transitions', () => {
+ const reload = vi.fn();
+ renderHook(() =>
+ useLocalHtmlAutoReload({
+ sessionId: 's1',
+ workdir: '/repo',
+ url: 'file:///repo/preview.html',
+ reload,
+ }),
+ );
+
+ const messages = [
+ userMessage,
+ {
+ clientId: 't1',
+ role: 'tool_use',
+ content: '',
+ toolName: 'Write',
+ toolInput: { file_path: '/repo/preview.html' },
+ },
+ ];
+ setTurnState(true, messages, true);
+ setTurnState(false, messages);
+
+ expect(reload).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts
new file mode 100644
index 0000000000..736841a4b6
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts
@@ -0,0 +1,74 @@
+/**
+ * 一轮会话结束时,按该轮文件编辑产物刷新当前 HTML 预览。
+ *
+ * 不监听磁盘。只有当前会话从 running 变为 idle,且最近一轮确实修改了正在预览的
+ * 本地 HTML 文件时,才触发一次 webview.reload()。
+ */
+
+import { useEffect, useRef } from 'react';
+
+import { makerChatStore, type AgentStatus, type ChatMessage } from '@/lib/makerChatStore';
+
+import { wasFileChangedInLastTurn } from '../../lib/lastTurnChangedFiles';
+import { fileUrlToAbsPath, isLocalHtmlFileUrl } from '../../lib/openInSidebarBrowser';
+
+export interface UseLocalHtmlAutoReloadOptions {
+ sessionId: string;
+ workdir: string;
+ /** 当前 webview / plugin state 的 URL。 */
+ url: string;
+ /** 触发 webview.reload。 */
+ reload: () => void;
+ /** false 时不订阅(非激活 tab、远程会话或 guest 已崩溃)。 */
+ enabled?: boolean;
+}
+
+function isTurnRunning(status: AgentStatus): boolean {
+ return status.isRunning && status.sideTaskRunning !== true;
+}
+
+function latestUserMessageIndex(messages: readonly ChatMessage[]): number {
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
+ if (messages[i].role === 'user') return i;
+ }
+ return 0;
+}
+
+export function useLocalHtmlAutoReload({
+ sessionId,
+ workdir,
+ url,
+ reload,
+ enabled = true,
+}: UseLocalHtmlAutoReloadOptions): void {
+ const reloadRef = useRef(reload);
+ reloadRef.current = reload;
+
+ useEffect(() => {
+ if (!enabled || !isLocalHtmlFileUrl(url)) return;
+ const absPath = fileUrlToAbsPath(url);
+ if (!absPath) return;
+
+ const initialSnapshot = makerChatStore.getSnapshot(sessionId);
+ let wasRunning = isTurnRunning(initialSnapshot.agentStatus);
+ let turnStartMessageIndex = wasRunning
+ ? latestUserMessageIndex(initialSnapshot.messages)
+ : initialSnapshot.messages.length;
+ return makerChatStore.subscribe(sessionId, () => {
+ const snapshot = makerChatStore.getSnapshot(sessionId);
+ const running = isTurnRunning(snapshot.agentStatus);
+ if (!wasRunning && running) {
+ turnStartMessageIndex = snapshot.messages.length;
+ } else if (wasRunning && !running) {
+ const currentTurnMessages = snapshot.messages.slice(
+ Math.min(turnStartMessageIndex, snapshot.messages.length),
+ );
+ if (wasFileChangedInLastTurn(currentTurnMessages, workdir, absPath)) {
+ reloadRef.current();
+ }
+ turnStartMessageIndex = snapshot.messages.length;
+ }
+ wasRunning = running;
+ });
+ }, [enabled, sessionId, url, workdir]);
+}