Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
import { interceptHtmlNavigation } from '@/session/htmlNavigationPolicy';
import { pathDisplayName } from '@/session/chatPathCandidate';
import { isHtmlFilePreviewCandidate } from '@/session/filePreview';
/**
* 源码契约用例的统一读法:**必须把 CRLF 归一成 LF**。
*
* Windows CI 的 checkout 走 `core.autocrlf=true`,而 .gitattributes 只给
* `.sh` / `.mjs` / `.githooks/**` / migration `.sql` 钉了 `eol=lf` —— `.tsx` 不在其中,
* 于是 runner 上读到的源码是 CRLF。任何跨行的字面量或含 `\n` 的正则断言不归一就只在
* Windows 上红(实捉:head c6527c24 的 `Windows unit tests (1/2)` 卡在一条 `visible ? (\n…`
* 断言上,Linux 全绿)。断言本意是代码结构,与行尾无关,所以在读入口一次性抹平。
*/
function readSource(rel: string): string {
return readFileSync(resolve(process.cwd(), rel), 'utf8').replace(/\r\n/g, '\n');
}
const source = readSource('app/files/preview/[sessionId].tsx');
describe('remote file preview pager wiring', () => {
it.each(['app/files/[sessionId].tsx', 'app/files/preview/[sessionId].tsx'])('cancels the in-flight export on blur and on Cancel, including the phone download and share sheet, in %s', (path) => {
const routeSource = readSource(path);
// 失焦即取消:点进下一层 / 跳会话页时本屏留在栈中不卸载。必须走与「取消」按钮同一个
// 会复位忙碌提示的出口,否则回到本屏时残留一个无事可取消的忙碌底栏。
expect(routeSource).toContain('useFocusEffect(useCallback(() => cancelExport, [cancelExport]));');
expect(routeSource).toMatch(/onCancel(Notice)?[=:] ?\{? ?cancelExport/);
// 动态加载分享模块期间可能已取消:shareAsync 前必须再查一次。
expect(routeSource).toMatch(/await import\('expo-sharing'\);\n\s*if \(run\.cancelled\) return;\n\s*await sharing\.shareAsync/);
expect(routeSource).toMatch(/run\.abort\.abort\(\);/);
expect(routeSource).toMatch(/downloadRemoteMediaShareTemp\(url, mime, item\.name, run\.abort\.signal\)/);
});
it.each(['app/files/[sessionId].tsx', 'app/files/preview/[sessionId].tsx'])('passes the route device ID into the source gate for %s', (path) => {
const routeSource = readSource(path).split('export default function ')[1]?.split('\n}\n')[0] ?? '';
expect(routeSource).toContain('const { sessionId, deviceId } = useLocalSearchParams<');
expect(routeSource).toContain('deviceId={readRouteString(deviceId) ?? undefined}');
});
it('exposes source readiness only on the visible loaded text page', () => {
const textPage = source.slice(source.indexOf('function TextPreviewPage('), source.indexOf('function ImagePreviewPage('));
const sourceList = textPage.match(/<FlatList\s[\s\S]*?data=\{state.lines\}[\s\S]*?testID=\{visible \? 'filePreview.sourceReady' : undefined\}/);
expect(sourceList).not.toBeNull();
// Guard protocol: Maestro file_browser.yaml / visual_files.yaml wait for sourceReady.
// Loading/error pages and prefetched neighbours must not satisfy that wait.
// Require both branches to exist: comparing a list offset with -1 silently passed.
const loadingBranch = textPage.indexOf("state.status === 'loading' ? (");
const unavailableBranch = textPage.indexOf("state.status === 'unavailable' ? (");
expect(loadingBranch).toBeGreaterThanOrEqual(0);
expect(unavailableBranch).toBeGreaterThan(loadingBranch);
expect(textPage.indexOf(sourceList![0])).toBeGreaterThan(unavailableBranch);
});
it('reserves horizontal gestures for the PDF WebView', () => {
expect(source).toContain("current.previewKind !== 'pdf'");
});
it('HTML 渲染态同样让出外层横滑,让内层 WebView 能横向平移', () => {
// 固定宽度布局 / 放大后需要横向平移,pager 抢走手势就永远看不到超出视口的内容。
expect(source).toContain("scrollEnabled={current.previewKind !== 'pdf' && htmlPanPageKey !== current.key && markdownPagerPageKey !== current.key}");
const markdownReader = readSource('src/session/MarkdownFileReader.tsx');
expect(markdownReader).toContain('injectedJavaScript={onPageSwipe ? MARKDOWN_FILE_PAGER_SCRIPT : undefined}');
expect(markdownReader).toContain('onMessage={onPageSwipe ? handleMessage : undefined}');
// 让路状态按页 key 存,不存布尔:翻页时新旧两页的上报先后顺序不能决定结果。
expect(source).toContain('setHtmlPanPageKey((prev) => (wants ? key : (prev === key ? null : prev)))');
// 只有真的挂着 WebView 的那种组合才要横滑(资源还在取 → 页面是 spinner → 不禁滑);
// cleanup 必须无条件归还。
expect(source).toContain("visible && richKind === 'html' && richView === 'rendered'");
expect(source).toContain("htmlSnapshot.foreground && (!!website || (!!htmlSnapshot.preview && !htmlError))");
expect(source).toContain("visible && richKind === 'html' && richView === 'rendered' && !website");
expect(source).toContain('return () => onHtmlPanChange?.(item.key, false)');
});
it('keeps ordinary PDF gestures out of WebView remount and reload triggers', () => {
expect(source).toContain("item.previewKind === 'pdf' ? item.key : `${item.key}:${recoveryEpoch}`");
expect(source).not.toContain('keyExtractor={(item) => `${item.key}:${pageIndex}');
expect(source).not.toContain('<WebView key=');
expect(source).toContain('const pdfSource = useMemo(() => (url ? { uri: url } : null), [url]);');
expect(source).toContain('<WebView source={pdfSource}');
});
it('retries a failed PDF after device recovery without remounting a loaded WebView', () => {
expect(source).toContain('requestedAtRecoveryEpochRef.current >= recoveryEpoch');
expect(source).toContain('setRequestEpoch((epoch) => epoch + 1)');
});
it('gives the audio/video player a definite height inside the preview page', () => {
// RemoteMediaPlayerWebView fills its wrapper with flex: 1. A width-only wrapper
// collapsed the player to 0 pt: media loaded, but no picture or controls to tap.
expect(source).toMatch(/avPlayer: \{[^}]*\bflex: 1\b[^}]*\}/);
expect(source).toContain('style={styles.avPlayer}');
});
it('pins every link of the player height chain, not just avPlayer (review P2)', () => {
// 上一条只看 avPlayer 自己的 flex: 1 —— 外层 avPage / 分页容器一旦失去高度约束,
// 用例照样绿,播放器又会塌成 0(review P2)。高度链每一环都要钉住:
// 1) 分页 cell 只定宽,高度靠横向 FlatList 的行向拉伸(默认 alignItems: stretch
// 把 cell 拉到 pager 高度)+ RN ScrollView 的隐式 flexGrow 填满 safeArea;
// cell 改成按内容收高即破。
expect(source).toContain('<View style={{ width: pageWidth }}>');
// 2) avPlayer 的父级 avPage 以 flex: 1 占满 cell。
expect(source).toMatch(/avPage: \{[^}]*\bflex: 1\b[^}]*\}/);
// 3) 预览屏根容器把高度传给 pager。
expect(source).toMatch(/safeArea: \{[^}]*\bflex: 1\b[^}]*\}/);
// 4) 链条最里层:WebView 以 flex: 1 填满 RemoteMediaPlayerWebView 的样式外层。
const playerSource = readSource('src/session/mediaPlayerWebView.tsx');
expect(playerSource).toContain("style={{ backgroundColor: 'transparent', flex: 1 }}");
});
it('pauses the audio/video player when its preview page becomes inactive', () => {
// pager 用 windowSize={3} 保留相邻页,相邻页的 active 仍为 true —— 可见性(visible
// = screenFocused && 当前页)必须一路传进播放器,翻页失活时暂停,否则上一页的
// 媒体在后台继续播(review P1)。
const filePage = source.slice(source.indexOf('function FilePreviewPage('), source.indexOf('function AvPreviewPage('));
expect(filePage).toMatch(/<AvPreviewPage[^>]*visible=\{visible\}[^>]*\/>/);
const avPage = source.slice(source.indexOf('function AvPreviewPage('), source.indexOf('function PdfPreviewPage('));
expect(avPage).toMatch(/<RemoteMediaPlayerWebView[^>]*visible=\{visible\}[^>]*\/>/);
expect(avPage).toMatch(/<NativeVideoPlayer[^>]*visible=\{visible\}[^>]*\/>/);
// 判定落在纯生命周期模块(行为级用例在 mediaPlayerWebView.test.ts),载体只发 pause。
const playerSource = readSource('src/session/mediaPlayerWebView.tsx');
expect(playerSource).toContain('if (lifecycleRef.current.onVisibilityChange(visible)) pausePlayback();');
const nativeSource = readSource('src/session/NativeVideoPlayer.tsx');
expect(nativeSource).toContain('if (lifecycleRef.current.onVisibilityChange(visible)) player.pause();');
});
it('plays video with the system player and keeps it filling the page', () => {
// 视频走系统原生播放器(控件、全屏、旋转都由系统负责);data: 地址与原生播放器
// 报错的格式(iOS 上的 WebM)退回 WebView 播放器,原来能播的文件不能退化。
const avPage = source.slice(source.indexOf('function AvPreviewPage('), source.indexOf('function PdfPreviewPage('));
expect(avPage).toContain("if (kind === 'video' && !nativeFailed && !url.startsWith('data:')) {");
expect(avPage).toContain('onError={handleNativePlaybackError}');
expect(avPage).toContain('setNativeFailed(true);');
const nativeSource = readSource('src/session/NativeVideoPlayer.tsx');
expect(nativeSource).toMatch(/stage: \{[^}]*\bflex: 1\b[^}]*\}/);
expect(nativeSource).toContain('nativeControls');
});
it('shows real upload progress while the computer stages audio/video', () => {
const avPage = source.slice(source.indexOf('function AvPreviewPage('), source.indexOf('function PdfPreviewPage('));
expect(avPage).toContain('if (!cancelled) setProgress(measure(uploaded, total));');
expect(avPage).toContain('formatTransferProgress(progress)');
});
});
const htmlReaderSource = readSource('src/session/HtmlFileReader.tsx');
const source_reader = htmlReaderSource;
const navPolicySource = readSource('src/session/htmlNavigationPolicy.ts');
describe('HTML 渲染态的 WebView 约束', () => {
it('显式给 baseUrl,不吃两端默认值不一致(Android 空串会吞掉页内锚点)', () => {
expect(htmlReaderSource).toContain("source={{ baseUrl: 'about:blank', html: guardedHtml }}");
});
it('回调是唯一导航决策点:originWhitelist 不得收窄', () => {
expect(htmlReaderSource).toContain('onShouldStartLoadWithRequest={interceptNavigation}');
// 载体只负责传闩,判定在纯策略模块里(便于行为级用例)。
expect(htmlReaderSource).toContain('interceptHtmlNavigation(request, documentSettledRef.current)');
// 收窄成 ['about:blank'] 会让 RNW 在回调**之前**拒掉非白名单 URL,并把它交给
// RN Linking 让系统处理 —— tel: / mailto: / 自定义 scheme 会拉起外部应用,
// 整段策略被绕过(review P2 实捉)。必须放到 '*' 让回调拿到全部请求。
expect(htmlReaderSource).toContain("originWhitelist={['*']}");
expect(htmlReaderSource).not.toContain("originWhitelist={['about:blank']}");
});
it('Android 多窗口必须关闭:window.open / target=_blank 不经过导航回调', () => {
// 留着默认支持时这两条路走 onCreateWindow,整个绕过 click 门与 scheme 拒绝(review P1)。
expect(htmlReaderSource).toContain('setSupportMultipleWindows={false}');
});
it('Android 关掉 file:// 读取能力(不可信页面不得探测 app 沙盒)', () => {
expect(htmlReaderSource).toContain('allowFileAccess={false}');
});
it('零出网信道:连用户点击的 http(s) 外链也不外送', () => {
// 导航回调**只管导航**,`new Image().src` / `fetch` 这类子资源请求完全不经过它 ——
// 出网必须由 CSP 在引擎层关掉(见 htmlPreviewCsp)。这里关的是另一半:顶层跳转。
// 连「用户点击的外链」也不放:页面里内联了被控电脑上的资源字节(data: URI)、脚本又是
// 开启的,作者脚本能把这些字节拼进一个真实 <a href="https://attacker/…"> 让用户去点,
// 而 CSP 管不到顶层导航(navigate-to 已从 CSP3 移除)(review P1)。
//
// 判据写成「模块既不 import 也不调用 Linking」:比检查某个分支更难绕过。
// (注意别写成 /Linking/ —— 头注里本来就在解释「为什么不用 Linking」,会自我命中。)
expect(htmlReaderSource).toContain("import { StyleSheet, View } from 'react-native';");
expect(htmlReaderSource).not.toMatch(/\bLinking\.\w/);
// 回调必须以无条件拒绝收尾(默认拒绝,不是默认放行)。
const decision = /export function interceptHtmlNavigation[\s\S]*?\n\}/.exec(navPolicySource);
expect(decision, '未找到导航决策函数').not.toBeNull();
expect(decision![0].trimEnd().endsWith('return false;\n}')).toBe(true);
// **不得**放行整个 about:* —— 那会让页面把自己导航到 about:blank、换掉加固过的文档。
// 注意别写成裸字符串 —— 头注里正在解释「为什么不再这么做」,会自我命中(第 5 次踩)。
// 只禁代码形态:整段 about: 前缀放行的 return。
expect(navPolicySource).not.toMatch(/if\s*\(.*startsWith\('about:'\).*\)\s*return true/);
// 策略模块必须保持无 RN 运行时依赖(否则契约用例又只能读源码字符串)。
expect(navPolicySource).not.toMatch(/^import \{[^}]*\} from 'react-native'/m);
// onMessage 缺席是刻意的:不给任意生成物一条通向 RN 的桥。
// 只匹配 JSX 属性形态 —— 头注里说明「不挂 onMessage」的那句话不算挂上。
expect(htmlReaderSource).not.toMatch(/onMessage\s*=/);
});
it('可执行 WebView 只为真正可见的当前页挂载', () => {
// 相邻预取页(active)不得提前挂 WebView:里面的脚本 / 计时器 / 网络请求会在
// 用户还没打开该文件时就跑起来,滑走后还继续跑(review P1)。
//
// 断言避开跨行字面量:意图是「不可见时走占位、可见时才是 HtmlFileReader」,
// 与缩进、行尾都无关(见 readSource 的 CRLF 说明)。
expect(source).toContain('!visible ? (');
expect(source).toContain('<HtmlSnapshotReader preview={htmlSnapshot.preview}');
expect(source).toContain('testID="filePreview.htmlOffscreen"');
// 挂载门必须是 visible 而不是 active。
expect(source).not.toMatch(/active\s*\?\s*\(\s*<HtmlFileReader/);
});
it('挂载门含屏级焦点,本屏被压栈后脚本不再跑', () => {
// 深链进预览 → 点「发送到会话」→ router.navigate 把会话页推到根 Stack:
// 预览路由默认仍挂载、pageIndex 也不变,只看 pageIndex 的话 WebView 会在用户
// 已经回到对话界面之后继续执行脚本 / 计时器 / 网络请求(review P1 第二轮)。
expect(source).toContain('visible={screenFocused && index === pageIndex}');
expect(source).toContain('const screenFocused = useIsFocused()');
// 用 expo-router 的再导出,不新增依赖 —— apps/mobile 的依赖是 runtime fingerprint
// 输入,加包会触发冷更门(见 docs/dev-rules/mobile-development.md)。
expect(source).toMatch(/import \{[^}]*useIsFocused[^}]*\} from 'expo-router'/);
});
});
describe('HTML 生成物的渲染态接线', () => {
it('rendered HTML uses a complete snapshot while source mode retains the text reader', () => {
expect(source).toContain('content: richKind ? content : undefined');
expect(source).toContain('useHtmlSnapshot(');
expect(source).toContain('<HtmlSnapshotReader preview={htmlSnapshot.preview}');
expect(source).not.toContain('useHtmlLocalResources(');
});
it('failed snapshots show recovery without publishing a partially fetched page', () => {
expect(source).toContain('testID="filePreview.htmlError"');
expect(source).toContain("t('files.preview.htmlSnapshotTooLarge')");
expect(source).toContain('onPress: htmlSnapshot.retry');
// The viewport now mounts during preparation; executable content remains gated
// inside the reader until a current, guarded snapshot exists.
expect(readSource('src/session/HtmlFileReader.tsx')).toContain('{preview ? <WebView');
expect(readSource('src/session/useHtmlSnapshot.ts')).toContain('const current = enabled && foreground');
});
it('downloads stop on source mode, invisibility, background, and source identity changes', () => {
const hook = readSource('src/session/useHtmlSnapshot.ts');
expect(hook).toContain('if (!enabled || !foreground) {');
expect(hook).toContain('controller.abort()');
expect(hook).toContain('preview?.close()');
expect(hook).toContain('[absPath, enabled, foreground, prepare, epoch]');
expect(source).toContain("visible && richKind === 'html' && richView === 'rendered'");
});
it('markdown 与 HTML 共用同一套双态机(不再是 markdown 专用)', () => {
expect(source).toContain("const richKind = richTextKindOf(item.relPath)");
expect(source).toContain("useState<'rendered' | 'source'>(richKind ? 'rendered' : 'source')");
// 双态切换只在这两类文本上出现,其余仍恒为源码态。
expect(source).toContain("const canRenderRich = richKind === 'html' || (richKind !== null && typeof ready?.content === 'string')");
});
it('进 WebView 的判定必须吃 relPath(真实路径),不得吃 name(展示名)', () => {
// review P1 第三轮,同一根因的**调用方**入口:`absPathItem` 的 name 走 pathDisplayName,
// 它 split(/[\\/]/).filter(Boolean) 会把 macOS/Linux 上合法的 `report.html\` 削成
// `report.html` —— 判定函数内部再严也拿不回上游丢掉的字符。relPath 两种模式下都是
// 未归一化的真实路径,所以判定一律以它为输入。
expect(source).toContain('richTextKindOf(item.relPath)');
expect(source).toContain('avKindFor(item.relPath)');
// 不许有任何一处判定回退到 name(这两个写法就是上一版的漏洞形态)。
expect(source).not.toContain('richTextKindOf(item.name)');
expect(source).not.toContain('avKindFor(item.name)');
// pathDisplayName 仍只用于展示(标题栏 / 合成 item 的 name),不得进判定。
expect(source).not.toMatch(/richTextKindOf\(\s*pathDisplayName/);
expect(source).not.toMatch(/isHtmlFilePreviewCandidate\(\s*pathDisplayName/);
});
it('行为级证据:pathDisplayName 会削掉尾随反斜杠,足以让非 HTML 文件冒充 HTML', () => {
// 上面那条是源码守卫(防写法回归),这条是**行为**证据 —— 证明这两个入参不等价、
// 且差异恰好落在「进不进可执行 WebView」上,而不是只在措辞上不同。
const posixTrailingBackslash = '/repo/report.html\\'; // macOS / Linux 上的合法文件名
// 归一化后 `\` 消失 → 冒充成 .html。
expect(pathDisplayName(posixTrailingBackslash)).toBe('report.html');
expect(isHtmlFilePreviewCandidate(pathDisplayName(posixTrailingBackslash))).toBe(true);
// 直接吃真实路径 → 最后一段为空 → fail-closed,不进渲染态。
expect(isHtmlFilePreviewCandidate(posixTrailingBackslash)).toBe(false);
// 正常路径两条路结论一致(修复没有把正常文件挡在外面)。
expect(isHtmlFilePreviewCandidate('/repo/report.html')).toBe(true);
expect(isHtmlFilePreviewCandidate(pathDisplayName('/repo/report.html'))).toBe(true);
// Windows 被控端的正常形态照旧可进(`\` 在那里是真分隔符)。
expect(isHtmlFilePreviewCandidate('C:\\proj\\report.html')).toBe(true);
});
it('HTML 判定取共享层口径,不在页面里另写一份扩展名表', () => {
expect(source).toContain('isHtmlFilePreviewCandidate');
expect(source).not.toMatch(/\/\\\.\(html\|htm/);
});
});
describe('导航门:只放行同文档锚点与首份文档加载(review P1)', () => {
it('同文档锚点放行 —— 不替换文档,CSP 与能力剥离都还在', () => {
for (const settled of [false, true]) {
expect(interceptHtmlNavigation({ url: 'about:blank#toc' } as never, settled)).toBe(true);
expect(interceptHtmlNavigation({ url: 'about:blank#a/b' } as never, settled)).toBe(true);
}
});
it('首份文档加载放行一次,上闩之后 about:blank 一律拒绝', () => {
// 早先 `startsWith('about:')` 一律放行 → 页面能把自己导航到 about:blank,新文档不再
// 经过 withHtmlPreviewCsp,iOS 侧原生 RTCPeerConnection 复活(review P1)。
expect(interceptHtmlNavigation({ url: 'about:blank' } as never, false)).toBe(true);
expect(interceptHtmlNavigation({ url: '' } as never, false)).toBe(true);
expect(interceptHtmlNavigation({ url: 'about:blank' } as never, true)).toBe(false);
expect(interceptHtmlNavigation({ url: '' } as never, true)).toBe(false);
});
it('其它 about: 形态一律拒绝(不再整段放行)', () => {
for (const settled of [false, true]) {
for (const url of ['about:srcdoc', 'about:config', 'about:blank?x=1', 'ABOUT:BLANK']) {
expect(interceptHtmlNavigation({ url } as never, settled)).toBe(false);
}
}
});
it('http(s) / 自定义 scheme / file 一律拒绝,与闩状态无关', () => {
for (const settled of [false, true]) {
for (const url of [
'https://evil.example/?d=x', 'http://x', 'file:///etc/passwd',
'tel:123', 'mailto:[email protected]', 'intent://x', 'javascript:alert(1)',
]) {
expect(interceptHtmlNavigation({ url } as never, settled)).toBe(false);
}
}
});
it('闩由 onLoadEnd 合上,换 html 时重置(渲染期比对,不用弱 key)', () => {
expect(source_reader).toContain('onLoadEnd={() => { documentSettledRef.current = true; }}');
expect(source_reader).toContain('lastHtmlRef.current !== guardedHtml');
expect(source_reader).toContain('documentSettledRef.current = false');
// 不得退回用长度当 key 的弱判据。
expect(source_reader).not.toContain('key={guardedHtml.length}');
});
it('opens HTML straight into the pending browser chrome instead of the classic header', () => {
const pending = source.slice(source.indexOf('if (!current || !siblings) {'), source.indexOf("const htmlBrowser = richTextKindOf(current.relPath) === 'html';"));
const shell = pending.slice(pending.indexOf("if (richTextKindOf(pendingPath) === 'html')"), pending.indexOf('<PreviewNav'));
expect(shell).toContain('<HtmlBrowserChrome');
expect(shell).toMatch(/\bpending\b\s*\n\s*loading=\{!error\}/);
for (const chrome of ['src/session/HtmlBrowserChrome.ios.tsx', 'src/session/HtmlBrowserChrome.tsx']) {
const text = readSource(chrome);
const edit = text.slice(text.lastIndexOf('<', text.indexOf('testID="filePreview.browser.editAddress"')), text.indexOf('testID="filePreview.browser.editAddress"') + 200);
expect(edit, chrome).toMatch(/disabled(\(p\.pending === true\)|=\{p\.pending\})/);
const more = text.slice(text.indexOf('"filePreview.browser.more"') - 200, text.indexOf('"filePreview.browser.more"') + 200);
expect(more, chrome).toMatch(/p\.pending/);
}
});
});