接入原生壳文本文件导入能力

新增 file.importText HostBridge 契约和 H5 facade

移动端通过 Expo DocumentPicker 读取受控文本文件

桌面端通过 Tauri 文件选择框读取受控文本文件

更新壳能力检查、测试、方案文档和共享决策记录
This commit is contained in:
2026-06-18 04:51:56 +08:00
parent c7a24fba37
commit 1c6749b53e
16 changed files with 527 additions and 4 deletions

View File

@@ -145,6 +145,7 @@ const requiredMainSnippets = [
'"clipboard.writeText"',
'"clipboard.readText"',
'"file.exportText"',
'"file.importText"',
'"file.exportImage"',
'"file.importImage"',
'"file.imageDropped"',
@@ -157,6 +158,7 @@ const requiredMainSnippets = [
'"file import cancelled"',
'BASE64_STANDARD.decode',
'blocking_pick_file',
'import_text_file_payload',
'import_image_file_payload',
'set_title',
'set_badge_count',

View File

@@ -23,6 +23,7 @@ const WEB_APP_ORIGIN: &str = "https://app.genarrative.world";
const EXTERNAL_URL_PROTOCOLS: [&str; 4] = ["http:", "https:", "mailto:", "tel:"];
const EXPORT_TEXT_MAX_BYTES: usize = 5 * 1024 * 1024;
const EXPORT_IMAGE_MAX_BYTES: usize = 5 * 1024 * 1024;
const IMPORT_TEXT_MAX_BYTES: u64 = 5 * 1024 * 1024;
const IMPORT_IMAGE_MAX_BYTES: u64 = 10 * 1024 * 1024;
const EXPORT_FILE_NAME_FALLBACK: &str = "genarrative-export.txt";
const EXPORT_FILE_NAME_MAX_LENGTH: usize = 120;
@@ -104,6 +105,7 @@ fn capabilities() -> Vec<&'static str> {
"clipboard.writeText",
"clipboard.readText",
"file.exportText",
"file.importText",
"file.exportImage",
"file.importImage",
"file.imageDropped",
@@ -383,6 +385,54 @@ fn write_export_text_file(path: PathBuf, content: String) -> Result<usize, Strin
Ok(content.len())
}
fn import_text_mime_type(path: &Path) -> Option<&'static str> {
match path
.extension()
.and_then(|extension| extension.to_str())
.map(|extension| extension.to_ascii_lowercase())
.as_deref()
{
Some("txt") => Some("text/plain"),
Some("md") | Some("markdown") => Some("text/markdown"),
Some("csv") => Some("text/csv"),
Some("json") => Some("application/json"),
_ => None,
}
}
fn import_text_file_payload(path: PathBuf) -> Result<Value, String> {
if !path.is_file() {
return Err("text file is required".to_string());
}
let mime_type =
import_text_mime_type(&path).ok_or_else(|| "text MIME must be allowed".to_string())?;
let metadata = fs::metadata(&path).map_err(|error| error.to_string())?;
let byte_count = metadata.len();
if byte_count == 0 || byte_count > IMPORT_TEXT_MAX_BYTES {
return Err("text exceeds import size limit".to_string());
}
let content = fs::read_to_string(&path).map_err(|error| error.to_string())?;
let byte_count = content.len() as u64;
if byte_count == 0 || byte_count > IMPORT_TEXT_MAX_BYTES {
return Err("text exceeds import size limit".to_string());
}
let file_name = path
.file_name()
.and_then(|name| name.to_str())
.map(normalize_export_file_name)
.unwrap_or_else(|| "genarrative-import.txt".to_string());
Ok(json!({
"action": "selected",
"fileName": file_name,
"content": content,
"mimeType": mime_type,
"bytes": byte_count,
}))
}
fn export_image_extension(mime_type: &str) -> Option<&'static str> {
match mime_type {
"image/png" => Some("png"),
@@ -910,6 +960,27 @@ async fn host_bridge_request(
}),
)
}
"file.importText" => {
let file_path = app
.dialog()
.file()
.add_filter("Text", &["txt", "md", "markdown", "csv", "json"])
.blocking_pick_file();
let Some(file_path) = file_path else {
return failed(request.id, "cancelled", "file import cancelled");
};
let path = match file_path.into_path() {
Ok(path) => path,
Err(error) => return failed(request.id, "host_error", error.to_string()),
};
let import_result =
tauri::async_runtime::spawn_blocking(move || import_text_file_payload(path)).await;
match import_result {
Ok(Ok(payload)) => ok(request.id, payload),
Ok(Err(error)) => failed(request.id, "invalid_request", error),
Err(error) => failed(request.id, "host_error", error.to_string()),
}
}
"file.exportImage" => {
let (file_name, bytes) = match export_image_payload(&request) {
Ok(payload) => payload,
@@ -1153,6 +1224,10 @@ mod tests {
.as_array()
.unwrap()
.contains(&json!("file.exportText")));
assert!(result["capabilities"]
.as_array()
.unwrap()
.contains(&json!("file.importText")));
assert!(result["capabilities"]
.as_array()
.unwrap()
@@ -1457,6 +1532,57 @@ mod tests {
fs::remove_file(path).expect("remove export file");
}
#[test]
fn import_text_file_payload_reads_allowed_text_without_exposing_path() {
let path = std::env::temp_dir().join(format!(
"genarrative-host-bridge-import-text-{}.md",
std::process::id()
));
fs::write(&path, "暖灯猫街").expect("write import text");
let payload = import_text_file_payload(path.clone()).expect("payload");
assert_eq!(payload["action"], "selected");
assert_eq!(
payload["fileName"],
path.file_name().unwrap().to_str().unwrap()
);
assert_eq!(payload["content"], "暖灯猫街");
assert_eq!(payload["mimeType"], "text/markdown");
assert_eq!(payload["bytes"], "暖灯猫街".len() as u64);
assert!(!payload
.to_string()
.contains(path.to_string_lossy().as_ref()));
fs::remove_file(path).expect("remove import text");
}
#[test]
fn import_text_file_payload_rejects_invalid_or_oversized_text() {
let image_path = std::env::temp_dir().join(format!(
"genarrative-host-bridge-import-text-{}.png",
std::process::id()
));
fs::write(&image_path, "text").expect("write image-like text");
assert_eq!(
import_text_file_payload(image_path.clone()).unwrap_err(),
"text MIME must be allowed"
);
fs::remove_file(image_path).expect("remove image-like text");
let large_path = std::env::temp_dir().join(format!(
"genarrative-host-bridge-import-text-large-{}.txt",
std::process::id()
));
fs::write(&large_path, "a".repeat(IMPORT_TEXT_MAX_BYTES as usize + 1))
.expect("write large text");
assert_eq!(
import_text_file_payload(large_path.clone()).unwrap_err(),
"text exceeds import size limit"
);
fs::remove_file(large_path).expect("remove large text");
}
#[test]
fn export_image_payload_decodes_allowed_image_base64() {
let mut valid = request("file.exportImage");

View File

@@ -6,7 +6,7 @@
"build": {
"beforeDevCommand": "npm --prefix ../.. run dev:web",
"beforeBuildCommand": "npm --prefix ../.. run build:raw && npm run typecheck",
"devUrl": "http://127.0.0.1:3000/?clientRuntime=native_app&clientType=native_app&hostShell=tauri_desktop&hostPlatform=unknown&hostVersion=0.1.0&bridgeVersion=1&hostCapabilities=host.getRuntime,appearance.getColorScheme,app.lifecycle,share.open,share.setTarget,navigation.openNativePage,app.openExternalUrl,app.setTitle,app.setBadgeCount,network.status,network.statusChanged,clipboard.writeText,clipboard.readText,file.exportText,file.exportImage,file.importImage,file.imageDropped,notification.showLocal",
"devUrl": "http://127.0.0.1:3000/?clientRuntime=native_app&clientType=native_app&hostShell=tauri_desktop&hostPlatform=unknown&hostVersion=0.1.0&bridgeVersion=1&hostCapabilities=host.getRuntime,appearance.getColorScheme,app.lifecycle,share.open,share.setTarget,navigation.openNativePage,app.openExternalUrl,app.setTitle,app.setBadgeCount,network.status,network.statusChanged,clipboard.writeText,clipboard.readText,file.exportText,file.importText,file.exportImage,file.importImage,file.imageDropped,notification.showLocal",
"frontendDist": "../../../dist"
},
"app": {
@@ -14,7 +14,7 @@
{
"create": false,
"label": "main",
"url": "index.html?clientRuntime=native_app&clientType=native_app&hostShell=tauri_desktop&hostPlatform=unknown&hostVersion=0.1.0&bridgeVersion=1&hostCapabilities=host.getRuntime,appearance.getColorScheme,app.lifecycle,share.open,share.setTarget,navigation.openNativePage,app.openExternalUrl,app.setTitle,app.setBadgeCount,network.status,network.statusChanged,clipboard.writeText,clipboard.readText,file.exportText,file.exportImage,file.importImage,file.imageDropped,notification.showLocal",
"url": "index.html?clientRuntime=native_app&clientType=native_app&hostShell=tauri_desktop&hostPlatform=unknown&hostVersion=0.1.0&bridgeVersion=1&hostCapabilities=host.getRuntime,appearance.getColorScheme,app.lifecycle,share.open,share.setTarget,navigation.openNativePage,app.openExternalUrl,app.setTitle,app.setBadgeCount,network.status,network.statusChanged,clipboard.writeText,clipboard.readText,file.exportText,file.importText,file.exportImage,file.importImage,file.imageDropped,notification.showLocal",
"title": "Genarrative",
"width": 1280,
"height": 820,

View File

@@ -15,6 +15,7 @@
"@expo/metro-runtime": "^56.0.15",
"expo": "^56.0.12",
"expo-clipboard": "^56.0.4",
"expo-document-picker": "^56.0.4",
"expo-file-system": "^56.0.8",
"expo-haptics": "^56.0.3",
"expo-image-picker": "^56.0.18",

View File

@@ -131,6 +131,7 @@ for (const snippet of [
for (const dependency of [
'expo-file-system',
'expo-document-picker',
'expo-image-picker',
'expo-network',
'expo-notifications',
@@ -177,6 +178,7 @@ if (Array.isArray(notificationsPlugin)) {
for (const snippet of [
'file.exportText',
'file.importText',
'file.exportImage',
'file.importImage',
'clipboard.readText',
@@ -188,6 +190,7 @@ for (const snippet of [
'Notifications.getPermissionsAsync',
'Notifications.requestPermissionsAsync',
'Sharing.shareAsync',
'DocumentPicker.getDocumentAsync',
'Clipboard.getStringAsync',
'ImagePicker.launchImageLibraryAsync',
'ImagePicker.requestMediaLibraryPermissionsAsync',
@@ -223,6 +226,7 @@ for (const capability of [
'clipboard.writeText',
'clipboard.readText',
'file.exportText',
'file.importText',
'file.exportImage',
'file.importImage',
'haptics.impact',

View File

@@ -1,4 +1,5 @@
import * as Clipboard from 'expo-clipboard';
import * as DocumentPicker from 'expo-document-picker';
import * as Haptics from 'expo-haptics';
import * as ImagePicker from 'expo-image-picker';
import * as Linking from 'expo-linking';
@@ -48,6 +49,8 @@ vi.mock('expo-clipboard', () => ({
setStringAsync: vi.fn(),
}));
const fileTexts = vi.hoisted(() => new Map<string, string>());
const writtenFiles = vi.hoisted(
() =>
[] as {
@@ -64,8 +67,9 @@ vi.mock('expo-file-system', () => ({
File: class MockFile {
uri: string;
constructor(_base: string, fileName: string) {
this.uri = `file:///cache/${fileName}`;
constructor(base: string, fileName?: string) {
this.uri =
typeof fileName === 'string' ? `file:///cache/${fileName}` : base;
}
write(content: string, options?: { encoding?: 'utf8' | 'base64' }) {
@@ -75,9 +79,17 @@ vi.mock('expo-file-system', () => ({
options,
});
}
text() {
return Promise.resolve(fileTexts.get(this.uri) ?? '');
}
},
}));
vi.mock('expo-document-picker', () => ({
getDocumentAsync: vi.fn(),
}));
vi.mock('expo-haptics', () => ({
ImpactFeedbackStyle: {
Heavy: 'heavy',
@@ -203,6 +215,11 @@ afterEach(() => {
vi.mocked(Clipboard.getStringAsync).mockReset();
vi.mocked(Clipboard.getStringAsync).mockResolvedValue('作品号 PZ-1');
vi.mocked(Clipboard.setStringAsync).mockReset();
vi.mocked(DocumentPicker.getDocumentAsync).mockReset();
vi.mocked(DocumentPicker.getDocumentAsync).mockResolvedValue({
canceled: true,
assets: null,
});
vi.mocked(ImagePicker.launchImageLibraryAsync).mockReset();
vi.mocked(ImagePicker.launchImageLibraryAsync).mockResolvedValue({
canceled: true,
@@ -242,6 +259,7 @@ afterEach(() => {
vi.mocked(Sharing.isAvailableAsync).mockResolvedValue(true);
vi.mocked(Sharing.shareAsync).mockReset();
vi.mocked(Share.share).mockReset();
fileTexts.clear();
writtenFiles.length = 0;
resetMobileHostBridgeForTest();
});
@@ -262,6 +280,9 @@ describe('handleMobileHostBridgeMessage', () => {
expect(
(okResponse.result as { capabilities: string[] }).capabilities,
).toContain('file.exportText');
expect(
(okResponse.result as { capabilities: string[] }).capabilities,
).toContain('file.importText');
expect(
(okResponse.result as { capabilities: string[] }).capabilities,
).toContain('file.importImage');
@@ -667,6 +688,86 @@ describe('handleMobileHostBridgeMessage', () => {
expect(Sharing.shareAsync).not.toHaveBeenCalled();
});
test('file.importText 调起系统文档选择器并返回受控文本数据', async () => {
fileTexts.set('file:///private/mobile/story.md', '暖灯猫街');
vi.mocked(DocumentPicker.getDocumentAsync).mockResolvedValue({
canceled: false,
assets: [
{
uri: 'file:///private/mobile/story.md',
name: ' ../剧情:草稿?.md ',
mimeType: 'text/markdown',
size: 12,
lastModified: 1,
},
],
});
const response = await send(request('file.importText'));
expect(expectOk(response).result).toEqual({
action: 'selected',
fileName: '剧情-草稿-.md',
content: '暖灯猫街',
mimeType: 'text/markdown',
bytes: 12,
});
expect(DocumentPicker.getDocumentAsync).toHaveBeenCalledWith({
copyToCacheDirectory: true,
multiple: false,
type: ['text/*', 'application/json'],
});
});
test('file.importText 取消选择时返回 cancelled', async () => {
vi.mocked(DocumentPicker.getDocumentAsync).mockResolvedValue({
canceled: true,
assets: null,
});
const response = await send(request('file.importText'));
expect(expectFailed(response).error.code).toBe('cancelled');
});
test('file.importText 拒绝非法 MIME 与超限文本', async () => {
fileTexts.set('file:///private/mobile/story.png', '暖灯猫街');
vi.mocked(DocumentPicker.getDocumentAsync).mockResolvedValue({
canceled: false,
assets: [
{
uri: 'file:///private/mobile/story.png',
name: 'story.png',
mimeType: 'image/png',
size: 12,
lastModified: 1,
},
],
});
const unsupportedMime = await send(request('file.importText'));
expect(expectFailed(unsupportedMime).error.code).toBe('invalid_request');
fileTexts.set('file:///private/mobile/story.txt', 'a'.repeat(5 * 1024 * 1024 + 1));
vi.mocked(DocumentPicker.getDocumentAsync).mockResolvedValue({
canceled: false,
assets: [
{
uri: 'file:///private/mobile/story.txt',
name: 'story.txt',
mimeType: 'text/plain',
size: 5 * 1024 * 1024 + 1,
lastModified: 1,
},
],
});
const oversized = await send(request('file.importText'));
expect(expectFailed(oversized).error.code).toBe('invalid_request');
});
test('file.exportImage 写入缓存图片并调起系统分享', async () => {
const response = await send(
request('file.exportImage', {

View File

@@ -1,4 +1,5 @@
import * as Clipboard from 'expo-clipboard';
import * as DocumentPicker from 'expo-document-picker';
import { File, Paths } from 'expo-file-system';
import * as Haptics from 'expo-haptics';
import * as ImagePicker from 'expo-image-picker';
@@ -20,6 +21,7 @@ import {
type FileExportTextPayload,
type FileExportTextResult,
type FileImportImageResult,
type FileImportTextResult,
type HapticsImpactPayload,
HOST_BRIDGE_PROTOCOL,
HOST_BRIDGE_VERSION,
@@ -29,6 +31,7 @@ import {
type HostBridgeMethod,
type HostBridgeRequest,
type HostBridgeResponse,
type HostBridgeTextMimeType,
type NavigateNativePagePayload,
normalizeHostBridgeBadgeCount,
normalizeHostBridgeClipboardText,
@@ -46,8 +49,15 @@ import { getMobileNetworkStatus } from './mobileShellNetwork';
const WEB_APP_ORIGIN = 'https://app.genarrative.world';
const EXPORT_TEXT_MAX_BYTES = 5 * 1024 * 1024;
const EXPORT_IMAGE_MAX_BYTES = 5 * 1024 * 1024;
const IMPORT_TEXT_MAX_BYTES = 5 * 1024 * 1024;
const IMPORT_IMAGE_MAX_BYTES = 10 * 1024 * 1024;
const LOCAL_NOTIFICATION_CHANNEL_ID = 'genarrative-local';
const HOST_BRIDGE_TEXT_MIME_TYPES = new Set<HostBridgeTextMimeType>([
'text/plain',
'text/markdown',
'text/csv',
'application/json',
]);
const HOST_BRIDGE_IMAGE_MIME_TYPES = new Set<HostBridgeImageMimeType>([
'image/png',
'image/jpeg',
@@ -78,6 +88,7 @@ export const MOBILE_HOST_CAPABILITIES: HostBridgeCapability[] = [
'clipboard.writeText',
'clipboard.readText',
'file.exportText',
'file.importText',
'file.exportImage',
'file.importImage',
'haptics.impact',
@@ -283,6 +294,82 @@ async function exportTextFile(payload: unknown): Promise<FileExportTextResult> {
};
}
function normalizeImportedTextMimeType(
value: unknown,
fileName: string,
): HostBridgeTextMimeType | null {
if (typeof value === 'string') {
const mimeType = value.toLowerCase();
if (HOST_BRIDGE_TEXT_MIME_TYPES.has(mimeType as HostBridgeTextMimeType)) {
return mimeType as HostBridgeTextMimeType;
}
}
const normalizedName = fileName.toLowerCase();
if (normalizedName.endsWith('.json')) {
return 'application/json';
}
if (normalizedName.endsWith('.md') || normalizedName.endsWith('.markdown')) {
return 'text/markdown';
}
if (normalizedName.endsWith('.csv')) {
return 'text/csv';
}
if (normalizedName.endsWith('.txt')) {
return 'text/plain';
}
return null;
}
async function importTextFile(): Promise<FileImportTextResult> {
const result = await DocumentPicker.getDocumentAsync({
copyToCacheDirectory: true,
multiple: false,
type: ['text/*', 'application/json'],
});
if (result.canceled) {
throw {
code: 'cancelled',
message: 'file import cancelled',
} satisfies HostBridgeError;
}
const asset = result.assets[0];
if (!asset?.uri) {
throw invalidRequest('text file is required');
}
const fileName = normalizeHostBridgeExportFileName(
asset.name || 'genarrative-import.txt',
);
const mimeType = normalizeImportedTextMimeType(asset.mimeType, fileName);
if (!mimeType) {
throw invalidRequest('mimeType must be an allowed text type');
}
if (
typeof asset.size === 'number' &&
(asset.size <= 0 || asset.size > IMPORT_TEXT_MAX_BYTES)
) {
throw invalidRequest('text exceeds file import size limit');
}
const file = new File(asset.uri);
const content = await file.text();
const bytes = utf8ByteLength(content);
if (bytes <= 0 || bytes > IMPORT_TEXT_MAX_BYTES) {
throw invalidRequest('text exceeds file import size limit');
}
return {
action: 'selected',
fileName,
content,
mimeType,
bytes,
};
}
async function exportImageFile(payload: unknown): Promise<FileExportImageResult> {
const exportPayload = payload as FileExportImagePayload | undefined;
const mimeType = exportPayload?.mimeType;
@@ -627,6 +714,8 @@ async function handleRequest(request: HostBridgeRequest) {
return ok(request, await readClipboard());
case 'file.exportText':
return ok(request, await exportTextFile(request.payload));
case 'file.importText':
return ok(request, await importTextFile());
case 'file.exportImage':
return ok(request, await exportImageFile(request.payload));
case 'file.importImage':

View File

@@ -40,6 +40,7 @@
- 2026-06-18 固定玩法音频接入宿主生命周期:前端新增 `useHostLifecycleActive()` 统一消费 `subscribeHostAppLifecycle()``useBackgroundMusic`、拼图运行态和抓大鹅运行态都只依赖该归一状态判断音频可播放性;宿主 inactive、background 或窗口失焦时暂停 `<audio>` / WebAudio回到 `active + focused` 后仅在运行态仍在播放、音源存在且用户音乐音量大于 0 时恢复,不改变用户音量设置。
- 2026-06-18 本地通知能力:新增 `notification.showLocal` HostBridge capabilityH5 只能传必填 `title` 和可选 `body`共享契约负责修剪、折叠普通空白、限制长度并拒绝控制字符Expo 壳通过 `expo-notifications` 请求系统通知权限、创建 Android 本地 channel 并发送即时本地通知Tauri 壳通过 Rust 侧 `tauri-plugin-notification` 发送系统通知且不开放插件 JS guest API。该能力不包含远程推送、token 注册、定时提醒或后台远程通知,权限拒绝、系统失败或宿主未声明时由 H5 视作失败并继续主流程。
- 2026-06-18 剪贴板读取能力:新增 `clipboard.readText` HostBridge capabilityH5 只能读取纯文本结果,契约限制返回文本最多 100000 字符Expo 壳通过 `expo-clipboard` 读取系统剪贴板文本Tauri 壳通过 Rust 侧 `tauri-plugin-clipboard-manager` 读取文本且不开放插件 JS guest API。该能力不读取图片、HTML、文件列表或剪贴板监听事件宿主未声明或读取失败时由 H5 视作失败并保留原流程。
- 2026-06-18 文本文件导入能力:新增 `file.importText` HostBridge capabilityH5 统一通过 `importHostTextFile()` 读取宿主返回的纯文本内容Expo 壳通过 `expo-document-picker` 打开系统文档选择器Tauri 壳通过系统文件选择框读取真实文本文件。两端只接受 `text/plain``text/markdown``text/csv``application/json` 或对应扩展名,单次不超过 5 MiB成功只返回清洗后的文件名、MIME、UTF-8 文本内容和字节数,不暴露设备 URI / 本机绝对路径,也不开放通用文件系统。
- 影响范围:`src/services/host-bridge/`、未来 `apps/mobile-shell/`、未来 `apps/desktop-shell/`、移动端支付 / 分享 / 深链 / 推送、桌面端系统能力、AI H5 sandbox 的 GameBridge 边界。
- 验证方式普通浏览器、小程序、Expo 壳、Tauri 壳都能返回正确 `getHostRuntime()`;未支持能力能回退 H5固定玩法在各宿主中读取同一作品数据和运行态 snapshotAI sandbox 无法直接调用 HostBridgeTauri release 不允许任意远端页面调用桌面命令。
- 关联文档:`docs/【前端架构】ExpoReactNative与Tauri宿主壳方案-2026-06-17.md``docs/【前端架构】宿主壳能力统一协议-2026-06-17.md`

View File

@@ -127,6 +127,7 @@ type HostBridgeEvent = {
| `clipboard.writeText` | 写剪贴板 | 支持 | 支持 |
| `clipboard.readText` | 读取纯文本剪贴板 | 支持 | 支持 |
| `file.exportText` | 导出文本到用户选择的本地文件 | 支持系统分享 / 保存面板 | 支持系统保存对话框 |
| `file.importText` | 导入用户选择的文本文件 | 支持系统文档选择器 | 支持系统选择文本文件 |
| `file.importImage` | 导入用户选择的图片文件 | 支持系统相册选择图片 | 支持系统选择图片 |
| `file.imageDropped` | 通知 H5 桌面拖入图片 | 不声明 | 支持主窗口拖拽图片事件 |
| `haptics.impact` | 轻量触感反馈 | 支持 | 不声明 |
@@ -253,6 +254,8 @@ GameBridge 禁止:
当前状态:已新增 `apps/mobile-shell/`,通过 Expo development build 运行,`react-native-webview` 加载 H5 URL 并附加 `native_app` 宿主 query。移动壳使用真实品牌图标资产已接入 `genarrative://` scheme、iOS associated domain 和 Android app link filter启动和运行时 deep link 只会映射到同源 H5 路径并继续附加 HostBridge 上下文,外域和危险协议回退到默认主站入口。首轮真实能力包括 `host.getRuntime``appearance.getColorScheme``host.events``app.lifecycle``network.status``network.statusChanged``share.open``share.setTarget``navigation.openNativePage``navigation.canGoBack``app.openExternalUrl``clipboard.writeText``clipboard.readText``file.exportText``file.exportImage``file.importImage``haptics.impact``notification.showLocal` 和 Android 返回键回退;其中 `appearance.getColorScheme` 只读系统配色偏好,不强改 H5 或系统主题;`app.lifecycle` 通过 React Native `AppState` 注入 `active` / `inactive` / `background` 统一状态,供 H5 游戏循环、音频和轮询做真实暂停 / 恢复判断H5 的 `useHostLifecycleActive()` 会把该事件归一成运行态可播放状态WebAudio 背景音乐和拼图、抓大鹅等固定玩法 `<audio>` 背景音乐都按该状态在宿主进后台时暂停、回到前台且原播放条件仍满足时恢复;`network.status` / `network.statusChanged` 通过 `expo-network` 查询并订阅真实系统网络状态,供 H5 游戏运行态和生成页识别离线 / 弱网回退iOS 额外声明 `app.setBadgeCount`,通过 React Native `PushNotificationIOS` 设置应用图标角标Android 不声明该能力。H5 会解析并过滤 `hostCapabilities`,也会在主 App 启动时通过真实 `host.getRuntime` 回读并缓存能力,只对声明或回读到的能力展示入口或调用宿主能力;其中 `share.setTarget` / `share.open` 会解析统一分享目标里的 `title``message``url``work``path``targetPath` 并调用 React Native 系统分享面板;发布分享弹窗只有在宿主声明 `share.open` 时才提供“系统分享”动作,失败时保留复制链接回退路径;`navigation.openNativePage` 在 Expo 壳内只接受同源 H5 route 并切换 WebView URL不伪造尚未存在的登录、支付或其它原生页面`navigation.canGoBack` 由 WebView 导航状态变化实时注入 H5WebView 自身拦截到外域导航时只会把 `http:``https:``mailto:``tel:` 交给系统,危险协议直接阻断;`app.openExternalUrl` 也只允许同一协议白名单ICP备案号和资产调试原图等 H5 外链入口在 `native_app` 中优先通过该能力离开 WebView 并交给系统浏览器;`clipboard.writeText` 由 H5 复制服务优先调用并写入系统剪贴板;`clipboard.readText` 通过 Expo Clipboard 读取纯文本剪贴板并按 100000 字符上限返回不读取图片、HTML 或监听剪贴板变化;`file.exportText` 通过 Expo 文件系统写入缓存文本文件,再交给系统分享 / 保存面板,文件名必须清洗,单次文本不超过 5 MiB成功只返回文件名和字节数`file.exportImage` 通过 Expo 文件系统写入缓存图片,再交给系统分享 / 保存面板H5 只传允许 MIME 的 base64 图片数据,单次不超过 5 MiB分享卡下载会优先走该能力`file.importImage` 通过 Expo ImagePicker 请求相册权限并打开系统相册选择器,只接受 `image/png` / `image/jpeg` / `image/webp`、单次不超过 10 MiB成功只返回清洗后的文件名、MIME、base64 内容和字节数,不把设备本地 URI 暴露给 H5用户取消返回 `cancelled` 并由 H5 视作无选择;通用创作图片输入面板 `CreativeImageInputPanel` 在原生壳声明 `file.importImage` 时会优先调用该宿主能力,并把导入结果转换为现有 `File` 上传回调,拼图、拼消消、敲木鱼等复用该面板的主图和描述参考图选择无需新增玩法分叉;`haptics.impact` 通过 Expo Haptics 承接运行时轻触反馈H5 在宿主不支持时回退到浏览器 vibration`notification.showLocal` 通过 `expo-notifications` 请求系统通知权限并调度即时本地通知Android 只使用固定本地 channel不启用后台远程通知、远程推送 token 或定时提醒。登录和支付尚未接入渠道 SDK / 原生页面时明确返回 unsupported让 H5 fallback 承接。
2026-06-18 追加:移动壳声明并实现 `file.importText`,通过 Expo DocumentPicker 打开系统文档选择器,只接受 `text/plain``text/markdown``text/csv``application/json` 或对应扩展名,单次不超过 5 MiB成功只返回清洗后的文件名、MIME、UTF-8 文本内容和字节数,不暴露设备本地 URI也不开放通用文件系统。
### Phase 3Tauri 桌面壳 MVP
- 新增 `apps/desktop-shell/`
@@ -264,6 +267,8 @@ GameBridge 禁止:
当前状态:已新增 `apps/desktop-shell/`Tauri dev 直接加载本地主站 Viterelease 打包根 `dist` 主站资产。Rust 侧只把 `host_bridge_request` command 授给主窗口,`appearance.getColorScheme` 由 Rust 内部读取主窗口 `theme()` 并返回 `light` / `dark` / `unknown`,不设置或覆盖系统主题;`app.lifecycle` 由主窗口 focus / blur 事件注入 `active` / `inactive` 统一状态,不开放 Tauri event 插件给前端H5 通过 `useHostLifecycleActive()` 统一归一窗口焦点状态WebAudio 背景音乐和拼图、抓大鹅等固定玩法 `<audio>` 背景音乐都会在窗口失焦时暂停、恢复焦点且原播放条件仍满足时恢复;`network.status` 由 Rust 对 `app.genarrative.world:443` 做短超时 TCP 可达性查询,`network.statusChanged` 由主 WebView 的 `online` / `offline` 事件注入,不开放任意网络探测给 H5`app.openExternalUrl` 由 Rust 内部通过 opener 插件执行且只允许 `http:``https:``mailto:``tel:` 外链协议ICP备案号和资产调试原图等 H5 外链入口在 `native_app` 中优先通过该能力离开主窗口并交给系统浏览器;`navigation.openNativePage` 只接受 `https://app.genarrative.world` 同源 H5 route 并在主窗口内受控跳转,`clipboard.writeText` 由 Rust 内部通过 clipboard-manager 插件写入系统剪贴板并由 H5 复制服务优先调用,`clipboard.readText` 由 Rust 内部通过同一插件读取纯文本剪贴板并按 100000 字符上限返回,不开放剪贴板插件 JS guest API、图片读取、HTML 读取或监听事件,`app.setTitle` 通过 Tauri 主窗口 API 同步窗口标题并拒绝空标题 / 控制字符,`app.setBadgeCount` 通过主窗口 `set_badge_count` 设置任务栏角标,数量只接受 `0-99999` 整数且 `0` 表示清除H5 主站会按当前平台阶段先更新 `document.title`,再通过 `app.setTitle` 把同一标题同步给 Tauri 窗口Expo 移动壳不声明该能力时静默忽略;不把 opener、clipboard、dialog 或 notification 插件命令直接暴露给前端。当前真实能力为 `host.getRuntime``appearance.getColorScheme``app.lifecycle``network.status``network.statusChanged``share.setTarget``share.open``navigation.openNativePage``app.openExternalUrl``app.setTitle``app.setBadgeCount``clipboard.writeText``clipboard.readText``file.exportText``file.exportImage``file.importImage``file.imageDropped``notification.showLocal`H5 会在主 App 启动时通过真实 `host.getRuntime` 回读并缓存这些能力,即使入口 URL 缺少 `hostCapabilities`,也只按宿主真实回包开启能力入口;其中 `share.open` 会把直接传入的分享 payload 或 `share.setTarget` 缓存的作品目标整理成非空分享文本并写入系统剪贴板,返回 `copied_to_clipboard`,发布分享弹窗在桌面壳中也通过该能力提供“系统分享”动作;`file.exportText` 通过系统保存对话框让用户选择本地路径,清洗文件名、限制单次文本导出不超过 5 MiB写入成功后只返回文件名和字节数不把本机绝对路径暴露给 H5用户取消返回 `cancelled``file.exportImage` 同样通过系统保存对话框写入 H5 生成的图片字节,只接受 `image/png` / `image/jpeg` / `image/webp` base64 数据,单次不超过 5 MiB分享卡下载会优先走该能力用户取消返回 `cancelled``file.importImage` 通过系统选择框读取用户选择的图片,`file.imageDropped` 通过主窗口拖拽事件读取用户拖入的图片,二者都只接受 `image/png` / `image/jpeg` / `image/webp`、单次不超过 10 MiB成功只返回文件名、MIME、base64 内容和字节数,不把本机绝对路径暴露给 H5也不开放通用文件系统`notification.showLocal` 由 Rust 内部通过 `tauri-plugin-notification` 发送即时系统通知,只接受清洗后的标题和正文,不开放插件 JS guest API、远程推送、定时提醒或通知 token通用创作图片输入面板 `CreativeImageInputPanel` 在桌面壳声明 `file.importImage` 时会优先打开系统图片选择框,在同时声明 `file.imageDropped` 时会按宿主拖入坐标把图片交给命中的主图槽位,并把结果转换为现有 `File` 上传回调,普通浏览器、小程序和未声明能力的壳继续保留原文件输入路径。原生系统分享面板、登录和支付未接入真实插件 / 渠道前不声明支持,不返回 mock 成功。
2026-06-18 追加:桌面壳声明并实现 `file.importText`,通过系统文件选择框读取用户选择的文本文件,只接受 `text/plain``text/markdown``text/csv``application/json` 对应扩展名,单次不超过 5 MiB成功只返回清洗后的文件名、MIME、UTF-8 文本内容和字节数,不暴露本机绝对路径,也不开放通用文件系统。
### Phase 4宿主能力扩展
- 移动端接入系统分享、推送、原生登录和渠道支付。

View File

@@ -57,6 +57,7 @@ AI H5 sandbox
- `openHostExternalUrl()`:原生 App 宿主的受控外链入口。H5 中需要离开主站的外链在 `native_app` 下先通过 `app.openExternalUrl` 请求宿主系统浏览器打开;只允许 `http:``https:``mailto:``tel:`,相对路径会先归一化到当前站点绝对 URL。宿主不可用或拒绝时回退浏览器外链行为普通浏览器和小程序保持原有 `<a>` 语义。
- `navigateHostNativePage()`:受控跳转宿主页,供订阅授权、支付、登录等 adapter 复用。Expo 移动壳首版只接受同源 H5 route 并切换 WebView URLTauri 桌面壳同样只接受 `https://app.genarrative.world` 同源 H5 route 并在主窗口内跳转。真正原生页面、登录和支付能力必须等对应 SDK / 页面接入后再声明支持。
- `exportHostTextFile()`:原生 App 宿主的受控文本导出入口。Expo 移动壳通过 `file.exportText` 写入缓存文本文件并交给系统分享 / 保存面板Tauri 桌面壳通过 `file.exportText` 打开系统保存对话框并写入用户选择的文件。文件名必须清洗,单次文本不超过 5 MiB成功只返回文件名和字节数不把本机绝对路径暴露给 H5系统分享不可用或用户取消时返回明确错误由 H5 fallback 承接。
- `importHostTextFile()`:原生 App 宿主的受控文本导入入口。Expo 移动壳通过 Expo DocumentPicker 打开系统文档选择器Tauri 桌面壳通过系统文件选择框读取用户选择的文本文件;两端都只接受 `text/plain``text/markdown``text/csv``application/json` 或对应扩展名,单次不超过 5 MiB成功只返回清洗后的文件名、MIME、UTF-8 文本内容和字节数,不暴露设备本地 URI 或本机绝对路径,也不开放通用文件系统能力;用户取消时由 H5 facade 归为 `false`
- `exportHostImageFile()`:原生 App 宿主的受控图片导出入口。H5 只传自己生成的图片 `base64Data`、清洗后的文件名和允许的 `image/png` / `image/jpeg` / `image/webp` MIMEExpo 移动壳写入缓存图片后交给系统分享 / 保存面板Tauri 桌面壳打开系统保存对话框并写入图片字节。单次图片不超过 5 MiB成功只返回文件名和字节数不回传本机绝对路径。当前分享卡下载在 native app 中优先走 `file.exportImage`,宿主未声明时保留浏览器下载路径。
- `importHostImageFile()` / `subscribeHostImageDrop()`:原生 App 宿主的受控图片导入入口。Expo 移动壳通过 Expo ImagePicker 请求相册权限并打开系统相册选择器Tauri 壳通过系统文件选择框或主窗口拖拽事件读取用户选择 / 拖入的图片;两端都只接受 `image/png``image/jpeg``image/webp`,单次不超过 10 MiB成功只返回文件名、MIME、base64 内容、字节数和可选拖入坐标,不暴露设备本地 URI 或本机绝对路径也不开放通用文件系统能力。H5 的通用图片输入面板 `CreativeImageInputPanel``native_app` 且声明 `file.importImage` 时优先调用宿主导入,并把结果转换成现有 `File` 回调;在桌面壳同时声明 `file.imageDropped` 时,只有拖入坐标命中当前主图卡片且未被上层元素遮挡的面板会消费该事件。普通浏览器、小程序和未声明能力的裁剪壳继续使用浏览器文件输入。

16
package-lock.json generated
View File

@@ -17,6 +17,7 @@
"dotenv": "^17.2.3",
"expo": "^56.0.12",
"expo-clipboard": "^56.0.4",
"expo-document-picker": "^56.0.4",
"expo-file-system": "^56.0.8",
"expo-haptics": "^56.0.3",
"expo-image-picker": "^56.0.18",
@@ -6372,6 +6373,15 @@
"react-native": "*"
}
},
"node_modules/expo-document-picker": {
"version": "56.0.4",
"resolved": "https://registry.npmjs.org/expo-document-picker/-/expo-document-picker-56.0.4.tgz",
"integrity": "sha512-75Apf74XNkYYohObIH19VZw42xpe0gmEnPccuzGXKVAzlvTYCfibSgW17F+6vt4paOfZEnAoZ1QFZM6dmaujRA==",
"license": "MIT",
"peerDependencies": {
"expo": "*"
}
},
"node_modules/expo-file-system": {
"version": "56.0.8",
"resolved": "https://registry.npmjs.org/expo-file-system/-/expo-file-system-56.0.8.tgz",
@@ -17339,6 +17349,12 @@
"@expo/env": "~2.3.0"
}
},
"expo-document-picker": {
"version": "56.0.4",
"resolved": "https://registry.npmjs.org/expo-document-picker/-/expo-document-picker-56.0.4.tgz",
"integrity": "sha512-75Apf74XNkYYohObIH19VZw42xpe0gmEnPccuzGXKVAzlvTYCfibSgW17F+6vt4paOfZEnAoZ1QFZM6dmaujRA==",
"requires": {}
},
"expo-file-system": {
"version": "56.0.8",
"resolved": "https://registry.npmjs.org/expo-file-system/-/expo-file-system-56.0.8.tgz",

View File

@@ -87,6 +87,7 @@
"dotenv": "^17.2.3",
"expo": "^56.0.12",
"expo-clipboard": "^56.0.4",
"expo-document-picker": "^56.0.4",
"expo-file-system": "^56.0.8",
"expo-haptics": "^56.0.3",
"expo-image-picker": "^56.0.18",

View File

@@ -57,6 +57,7 @@ describe('HostBridge shared contract helpers', () => {
expect(isHostBridgeCapability('network.status')).toBe(true);
expect(isHostBridgeCapability('network.statusChanged')).toBe(true);
expect(isHostBridgeCapability('clipboard.readText')).toBe(true);
expect(isHostBridgeCapability('file.importText')).toBe(true);
expect(isHostBridgeCapability('file.importImage')).toBe(true);
expect(isHostBridgeCapability('file.imageDropped')).toBe(true);
expect(isHostBridgeCapability('app.setBadgeCount')).toBe(true);

View File

@@ -28,6 +28,7 @@ export const HOST_BRIDGE_METHODS = [
'clipboard.writeText',
'clipboard.readText',
'file.exportText',
'file.importText',
'file.exportImage',
'file.importImage',
'haptics.impact',
@@ -291,6 +292,20 @@ export type FileExportTextResult = {
bytes: number;
};
export type HostBridgeTextMimeType =
| 'text/plain'
| 'text/markdown'
| 'text/csv'
| 'application/json';
export type FileImportTextResult = {
action: 'selected';
fileName: string;
content: string;
mimeType: HostBridgeTextMimeType;
bytes: number;
};
export type FileExportImagePayload = {
fileName: string;
base64Data: string;

View File

@@ -13,6 +13,7 @@ import {
getHostRuntime,
getNativeAppHostRuntime,
importHostImageFile,
importHostTextFile,
isWechatMiniProgramWebViewRuntime,
navigateHostNativePage,
openHostExternalUrl,
@@ -607,6 +608,14 @@ describe('hostBridge', () => {
mimeType: 'image/png',
bytes: 5,
}
: request.method === 'file.importText'
? {
action: 'selected',
fileName: '剧情.md',
content: '暖灯猫街',
mimeType: 'text/markdown',
bytes: 12,
}
: true,
};
});
@@ -627,6 +636,7 @@ describe('hostBridge', () => {
'app.setBadgeCount',
'network.status',
'share.open',
'file.importText',
'file.exportImage',
'file.importImage',
'file.imageDropped',
@@ -697,6 +707,13 @@ describe('hostBridge', () => {
mimeType: 'image/png',
bytes: 5,
});
await expect(importHostTextFile()).resolves.toEqual({
action: 'selected',
fileName: '剧情.md',
content: '暖灯猫街',
mimeType: 'text/markdown',
bytes: 12,
});
await expect(
showHostLocalNotification({
title: ' 生成完成 ',
@@ -806,6 +823,12 @@ describe('hostBridge', () => {
timeoutMs: 30000,
}),
});
expect(invoke).toHaveBeenCalledWith('host_bridge_request', {
request: expect.objectContaining({
method: 'file.importText',
timeoutMs: 30000,
}),
});
expect(invoke).toHaveBeenCalledWith('host_bridge_request', {
request: expect.objectContaining({
method: 'notification.showLocal',
@@ -882,6 +905,7 @@ describe('hostBridge', () => {
}),
).resolves.toBe(false);
await expect(importHostImageFile()).resolves.toBe(false);
await expect(importHostTextFile()).resolves.toBe(false);
await expect(
showHostLocalNotification({
title: '生成完成',
@@ -906,6 +930,7 @@ describe('hostBridge', () => {
}),
).resolves.toBe(false);
await expect(importHostImageFile()).resolves.toBe(false);
await expect(importHostTextFile()).resolves.toBe(false);
await expect(
showHostLocalNotification({
title: '生成完成',
@@ -1155,6 +1180,82 @@ describe('hostBridge', () => {
});
});
test('原生 App 宿主通过 HostBridge 导入文本文件', async () => {
const invoke = vi.fn(
async (_command: string, args?: Record<string, unknown>) => {
const request = (args as { request: { id: string } }).request;
return {
bridge: 'GenarrativeHostBridge',
version: 1,
id: request.id,
ok: true,
result: {
action: 'selected',
fileName: ' 剧情.md ',
content: '暖灯猫街',
mimeType: 'text/markdown',
bytes: 12,
},
};
},
);
window.history.replaceState(
null,
'',
nativeAppPath(['file.importText']),
);
window.__TAURI__ = {
core: {
invoke: asTauriInvoke(invoke),
},
};
await expect(importHostTextFile()).resolves.toEqual({
action: 'selected',
fileName: '剧情.md',
content: '暖灯猫街',
mimeType: 'text/markdown',
bytes: 12,
});
expect(invoke).toHaveBeenCalledWith('host_bridge_request', {
request: expect.objectContaining({
method: 'file.importText',
timeoutMs: 30000,
}),
});
});
test('原生 App 宿主取消导入文本时回退为 false', async () => {
const invoke = vi.fn(
async (_command: string, args?: Record<string, unknown>) => {
const request = (args as { request: { id: string } }).request;
return {
bridge: 'GenarrativeHostBridge',
version: 1,
id: request.id,
ok: false,
error: {
code: 'cancelled',
message: 'file import cancelled',
},
};
},
);
window.history.replaceState(
null,
'',
nativeAppPath(['file.importText']),
);
window.__TAURI__ = {
core: {
invoke: asTauriInvoke(invoke),
},
};
await expect(importHostTextFile()).resolves.toBe(false);
});
test('原生 App 宿主取消导入图片时回退为 false', async () => {
const invoke = vi.fn(
async (_command: string, args?: Record<string, unknown>) => {

View File

@@ -7,11 +7,13 @@ import type {
FileExportTextPayload,
FileExportTextResult,
FileImportImageResult,
FileImportTextResult,
HapticsImpactPayload,
HostBridgeCapability,
HostBridgeImageMimeType,
HostBridgeMethod,
HostBridgeRuntimeResult,
HostBridgeTextMimeType,
LocalNotificationPayload,
NetworkStatusResult,
OpenExternalUrlPayload,
@@ -94,6 +96,8 @@ export type HostFileExportImageRequest = FileExportImagePayload;
export type HostFileImportImageResult = FileImportImageResult;
export type HostFileImportTextResult = FileImportTextResult;
export type HostClipboardWriteTextRequest = {
text: string;
};
@@ -830,6 +834,61 @@ export async function importHostImageFile() {
}
}
const HOST_BRIDGE_TEXT_MIME_TYPES = new Set<HostBridgeTextMimeType>([
'text/plain',
'text/markdown',
'text/csv',
'application/json',
]);
function normalizeHostTextImportResult(
payload: FileImportTextResult | null | undefined,
): FileImportTextResult | false {
if (
!payload ||
typeof payload !== 'object' ||
payload.action !== 'selected' ||
!HOST_BRIDGE_TEXT_MIME_TYPES.has(payload.mimeType) ||
typeof payload.fileName !== 'string' ||
!payload.fileName.trim() ||
typeof payload.content !== 'string' ||
typeof payload.bytes !== 'number' ||
!Number.isInteger(payload.bytes) ||
payload.bytes <= 0
) {
return false;
}
return {
action: 'selected',
fileName: payload.fileName.trim(),
content: payload.content,
mimeType: payload.mimeType,
bytes: payload.bytes,
};
}
export async function importHostTextFile() {
if (!canUseNativeHostCapability('file.importText')) {
return false;
}
try {
return normalizeHostTextImportResult(
await requestNativeAppHostBridge<FileImportTextResult>(
'file.importText',
undefined,
{ timeoutMs: 30000 },
),
);
} catch (error) {
if (isUnsupportedHostBridgeError(error)) {
return false;
}
throw error;
}
}
export async function requestHostHapticsImpact(
params: HostHapticsImpactRequest = {},
) {