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(html-preview): 后台更新保留当前内页导航

Dash9c776524746f
diff --git a/apps/mobile/app/files/preview/[sessionId].tsx b/apps/mobile/app/files/preview/[sessionId].tsx
index 11dbbfbfb4..c380b7c1a5 100644
--- a/apps/mobile/app/files/preview/[sessionId].tsx
+++ b/apps/mobile/app/files/preview/[sessionId].tsx
@@ -1345,7 +1345,10 @@ function TextPreviewPage({
loading={<HtmlPreviewLoading progress={htmlSnapshot.progress} />}
webViewRef={browserRef}
viewportInsets={{ ...browserContentInset, left: insets.left, right: insets.right }}
- onNavigationStateChange={(preview, state) => setBrowserNavigation({ preview, state })}
+ onNavigationStateChange={(preview, state) => {
+ htmlSnapshot.onNavigationStateChange(preview, state);
+ setBrowserNavigation({ preview, state });
+ }}
/>
)
) : (
diff --git a/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx b/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx
index 56dd9ced94..f6d5118cfb 100644
--- a/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx
+++ b/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx
@@ -290,6 +290,39 @@ it('ignores late failure events from a replaced preview', () => {
expect(onError).toHaveBeenCalledOnce();
});
+// Unit regression for PR #6323: real hook + reader navigation followed by a delayed
+// update must preserve the current inner page. Existing update cases had no navigation.
+// Minimal input: cached entry -> sibling document -> background update resolves.
+it.each(['sibling', 'entry', 'returned'] as const)('applies background updates only at the entry document (%s)', async (destination) => {
+ root = createRoot(document.createElement('div'));
+ let finishCheck!: (preview: MobileHtmlPreview) => void;
+ const initial: MobileHtmlPreview = {
+ url: 'http://127.0.0.1:1234/__cindy/token', documents: ['/report%20one.html', '/detail.html'],
+ close: vi.fn().mockResolvedValue(undefined),
+ updated: new Promise(resolve => { finishCheck = resolve; }),
+ };
+ const next = { ...initial, url: 'http://127.0.0.1:4321/__cindy/fresh', updated: undefined };
+ const prepare = vi.fn().mockResolvedValue(initial);
+ let snapshot!: ReturnType<typeof useHtmlSnapshot>;
+ function Harness() {
+ snapshot = useHtmlSnapshot('/report one.html', true, prepare);
+ return createElement(HtmlSnapshotReader, {
+ preview: snapshot.preview, onError() {}, onNavigationStateChange: snapshot.onNavigationStateChange,
+ });
+ }
+ await act(async () => root!.render(createElement(Harness)));
+ const navigate = (path: string) => act(() => state.props.onNavigationStateChange({ url: `http://127.0.0.1:1234/${path}` }));
+ navigate(destination === 'entry' ? 'report%20one.html#details' : 'detail.html');
+ if (destination === 'returned') navigate('report%20one.html');
+ await act(async () => finishCheck(next));
+ expect(snapshot.preview).toBe(destination === 'sibling' ? initial : next);
+ expect(state.mounts).toBe(destination === 'sibling' ? 1 : 2);
+ expect(initial.close).not.toHaveBeenCalled();
+ expect(prepare).toHaveBeenCalledOnce();
+ await act(async () => root!.unmount()); root = undefined;
+ expect(initial.close).toHaveBeenCalledOnce();
+});
+
// Unit: the real hook must retain usable content during automatic replacement and
// ignore late work after leaving. These timings were absent from manual-retry coverage.
it.each(['changed', 'same', 'failed', 'left'] as const)('replaces a stale snapshot at most once and preserves its owner (%s)', async (outcome) => {
diff --git a/apps/mobile/src/session/useHtmlSnapshot.ts b/apps/mobile/src/session/useHtmlSnapshot.ts
index 8a29a4d756..88a32e9241 100644
--- a/apps/mobile/src/session/useHtmlSnapshot.ts
+++ b/apps/mobile/src/session/useHtmlSnapshot.ts
@@ -1,6 +1,8 @@
-import { useEffect, useState } from 'react';
+import { useEffect, useRef, useState } from 'react';
import { AppState } from 'react-native';
+import type { WebViewNavigation } from 'react-native-webview/lib/WebViewTypes';
import type { HtmlPreviewProgress, MobileHtmlPreview, PrepareMobileHtmlPreview } from './mobileHtmlPreview';
+import { htmlSnapshotLocation } from './htmlDirectorySnapshot';
import { errorText } from '@/debug/fileDiagnostics';
import { mobileDebugLog } from '@/debug/mobileDebugLog';
@@ -8,6 +10,7 @@ import { mobileDebugLog } from '@/debug/mobileDebugLog';
export function useHtmlSnapshot(absPath: string, enabled: boolean, prepare: PrepareMobileHtmlPreview) {
const [foreground, setForeground] = useState(AppState.currentState === 'active');
const [epoch, setEpoch] = useState(0);
+ const navigation = useRef<{ preview: MobileHtmlPreview; url: string } | null>(null);
const [result, setResult] = useState<{
preview?: MobileHtmlPreview; error?: unknown; path?: string; prepare?: PrepareMobileHtmlPreview; epoch?: number;
progress?: HtmlPreviewProgress;
@@ -37,13 +40,22 @@ export function useHtmlSnapshot(absPath: string, enabled: boolean, prepare: Prep
ms: Date.now() - startedAt, onDemand: value.onDemand === true, aborted: controller.signal.aborted,
});
if (controller.signal.aborted) { void value.close().catch(() => {}); return; }
+ navigation.current = { preview: value, url: value.url };
setResult((previous) => ({ ...previous, preview: value, path: absPath, prepare, epoch }));
const fresh = await value.updated;
if (fresh) {
// Reuse the completed background snapshot. No second remote download and
// no recursive refresh: this is one check for this opening only.
if (controller.signal.aborted) void fresh.close().catch(() => {});
- else setResult({ preview: fresh, path: absPath, prepare, epoch });
+ else {
+ const target = new URL(navigation.current?.url ?? value.url);
+ const bootstrap = new URL(value.url);
+ const atEntry = target.origin === bootstrap.origin && (target.pathname === bootstrap.pathname
+ || decodeURIComponent(target.pathname) === '/' + htmlSnapshotLocation(absPath).entry);
+ // A delayed update must not pull an inner page back to the entry. The
+ // visit still owns both copies and releases them together on exit.
+ if (atEntry) setResult({ preview: fresh, path: absPath, prepare, epoch });
+ }
}
}).catch((error: unknown) => {
mobileDebugLog(controller.signal.aborted ? 'debug' : 'warn', 'files', 'html preview prepare failed', {
@@ -53,6 +65,7 @@ export function useHtmlSnapshot(absPath: string, enabled: boolean, prepare: Prep
});
return () => {
controller.abort();
+ if (navigation.current?.preview === preview) navigation.current = null;
void preview?.close().catch(() => {});
};
}, [absPath, enabled, foreground, prepare, epoch]);
@@ -61,6 +74,9 @@ export function useHtmlSnapshot(absPath: string, enabled: boolean, prepare: Prep
preview: current ? result.preview : undefined,
error: current ? result.error : undefined,
progress: current ? result.progress : undefined,
+ onNavigationStateChange: (preview: MobileHtmlPreview, state: Pick<WebViewNavigation, 'url'>) => {
+ if (navigation.current?.preview === preview) navigation.current.url = state.url;
+ },
foreground, retry: () => setEpoch((value) => value + 1),
};
}
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index e01aa13360..c2b72223bc 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -925,6 +925,7 @@ Desktop 完整文件与远程 HTML 预览复用现有磁盘副本,后台检查
device 仍可复用主机确认版本的字节,SSH 重新读取;新版原子保存前保留旧副本。HTML 直接通过
现有磁盘索引定位副本,不再另维护进程内元数据索引和刷新集合。两端 HTML 先显示缓存,再在
本次打开的后台读取中比较入口 HTML 内容;不同且新版快照准备完成时自动切换,相同或失败不重载。
+更新仅在当前仍停留于入口文档时应用;已导航到内页则保留当前页面,新缓存供下次打开使用。
Mobile 直接复用后台准备好的快照;Desktop 缓存入口通过现有鉴权的本地预览服务读取一次更新结果,
确认变化后重载。没有持续监听或轮询,检查完成后的修改需从 Cindy 重新打开;手机也可手动刷新,
跳过旧副本并在成功后更新缓存。只改配套资源不触发入口重载。图片、PDF 保持后台更新供后续打开使用。