接入原生壳应用角标能力

新增 HostBridge app.setBadgeCount 契约和 H5 能力门控

Expo 壳按平台声明能力并在 iOS 调用系统角标 API

Tauri 壳通过主窗口设置任务栏角标并校验 payload

补齐角标能力测试、漂移检查和架构文档
This commit is contained in:
2026-06-18 01:50:15 +08:00
parent 910625d5e1
commit 6b39bdbe19
15 changed files with 336 additions and 19 deletions

View File

@@ -137,6 +137,7 @@ const requiredMainSnippets = [
'"share.setTarget"',
'"navigation.openNativePage"',
'"app.setTitle"',
'"app.setBadgeCount"',
'"clipboard.writeText"',
'"file.exportText"',
'"file.exportImage"',
@@ -145,6 +146,7 @@ const requiredMainSnippets = [
'"file export cancelled"',
'BASE64_STANDARD.decode',
'set_title',
'set_badge_count',
];
for (const permission of requiredPermissions) {

View File

@@ -18,6 +18,7 @@ const EXPORT_TEXT_MAX_BYTES: usize = 5 * 1024 * 1024;
const EXPORT_IMAGE_MAX_BYTES: usize = 5 * 1024 * 1024;
const EXPORT_FILE_NAME_FALLBACK: &str = "genarrative-export.txt";
const EXPORT_FILE_NAME_MAX_LENGTH: usize = 120;
const BADGE_COUNT_MAX: i64 = 99999;
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -83,6 +84,7 @@ fn capabilities() -> Vec<&'static str> {
"navigation.openNativePage",
"app.openExternalUrl",
"app.setTitle",
"app.setBadgeCount",
"clipboard.writeText",
"file.exportText",
"file.exportImage",
@@ -195,6 +197,31 @@ fn normalize_window_title(raw_title: &str) -> Option<String> {
Some(title.chars().take(80).collect())
}
fn badge_count_payload(request: &HostBridgeRequest) -> Result<Option<i64>, HostBridgeResponse> {
let count = request
.payload
.as_ref()
.and_then(|value| value.get("count"))
.and_then(Value::as_i64)
.ok_or_else(|| {
failed(
request.id.clone(),
"invalid_request",
"count must be an integer between 0 and 99999",
)
})?;
if !(0..=BADGE_COUNT_MAX).contains(&count) {
return Err(failed(
request.id.clone(),
"invalid_request",
"count must be an integer between 0 and 99999",
));
}
Ok(if count == 0 { None } else { Some(count) })
}
fn normalize_export_file_name(raw_file_name: &str) -> String {
let mut file_name = String::new();
let mut last_was_space = false;
@@ -286,7 +313,10 @@ fn export_image_extension(mime_type: &str) -> Option<&'static str> {
fn normalize_export_image_file_name(raw_file_name: &str, mime_type: &str) -> String {
let mut file_name = normalize_export_file_name(raw_file_name);
let extension = export_image_extension(mime_type).unwrap_or("png");
if !file_name.to_ascii_lowercase().ends_with(&format!(".{}", extension)) {
if !file_name
.to_ascii_lowercase()
.ends_with(&format!(".{}", extension))
{
file_name.push('.');
file_name.push_str(extension);
}
@@ -306,7 +336,13 @@ fn export_image_payload(
let mime_type = payload
.get("mimeType")
.and_then(Value::as_str)
.ok_or_else(|| failed(request.id.clone(), "invalid_request", "mimeType is required"))?;
.ok_or_else(|| {
failed(
request.id.clone(),
"invalid_request",
"mimeType is required",
)
})?;
if export_image_extension(mime_type).is_none() {
return Err(failed(
request.id.clone(),
@@ -320,7 +356,13 @@ fn export_image_payload(
.and_then(Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.ok_or_else(|| failed(request.id.clone(), "invalid_request", "base64Data is required"))?;
.ok_or_else(|| {
failed(
request.id.clone(),
"invalid_request",
"base64Data is required",
)
})?;
let bytes = BASE64_STANDARD.decode(base64_data).map_err(|_| {
failed(
request.id.clone(),
@@ -600,6 +642,20 @@ async fn host_bridge_request(
None => failed(request.id, "host_error", "main window not found"),
}
}
"app.setBadgeCount" => {
let count = match badge_count_payload(&request) {
Ok(count) => count,
Err(response) => return response,
};
match app.get_webview_window("main") {
Some(window) => match window.set_badge_count(count) {
Ok(()) => ok(request.id, json!(true)),
Err(error) => failed(request.id, "host_error", error.to_string()),
},
None => failed(request.id, "host_error", "main window not found"),
}
}
"share.setTarget" => {
let target = request
.payload
@@ -697,6 +753,10 @@ mod tests {
.as_array()
.unwrap()
.contains(&json!("app.setTitle")));
assert!(result["capabilities"]
.as_array()
.unwrap()
.contains(&json!("app.setBadgeCount")));
assert!(result["capabilities"]
.as_array()
.unwrap()
@@ -809,6 +869,33 @@ mod tests {
);
}
#[test]
fn badge_count_payload_accepts_clear_and_positive_counts() {
let mut clear = request("app.setBadgeCount");
clear.payload = Some(json!({ "count": 0 }));
assert_eq!(badge_count_payload(&clear).expect("clear badge"), None);
let mut count = request("app.setBadgeCount");
count.payload = Some(json!({ "count": 12 }));
assert_eq!(badge_count_payload(&count).expect("badge count"), Some(12));
}
#[test]
fn badge_count_payload_rejects_invalid_counts() {
for count in [json!(-1), json!(1.5), json!(100000), json!("1")] {
let mut invalid = request("app.setBadgeCount");
invalid.payload = Some(json!({ "count": count }));
let response = badge_count_payload(&invalid).expect_err("invalid count");
let error = response.error.expect("error");
assert_eq!(error.code, "invalid_request");
assert_eq!(
error.message,
"count must be an integer between 0 and 99999"
);
}
}
#[test]
fn export_file_name_normalization_rejects_path_like_characters() {
assert_eq!(
@@ -908,7 +995,10 @@ mod tests {
"mimeType": "image/png"
}));
let response = export_image_payload(&invalid_base64).expect_err("invalid base64");
assert_eq!(response.error.expect("error").message, "base64Data is invalid");
assert_eq!(
response.error.expect("error").message,
"base64Data is invalid"
);
}
#[test]
@@ -922,7 +1012,10 @@ mod tests {
let response = export_image_payload(&invalid).expect_err("oversized image");
assert_eq!(response.error.expect("error").message, "image exceeds file export size limit");
assert_eq!(
response.error.expect("error").message,
"image exceeds file export size limit"
);
}
#[test]
@@ -936,7 +1029,10 @@ mod tests {
.expect("write image file");
assert_eq!(bytes, 4);
assert_eq!(fs::read(&path).expect("read image file"), vec![0x89, b'P', b'N', b'G']);
assert_eq!(
fs::read(&path).expect("read image file"),
vec![0x89, b'P', b'N', b'G']
);
fs::remove_file(path).expect("remove image file");
}

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,share.open,share.setTarget,navigation.openNativePage,app.openExternalUrl,app.setTitle,clipboard.writeText,file.exportText,file.exportImage",
"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,share.open,share.setTarget,navigation.openNativePage,app.openExternalUrl,app.setTitle,app.setBadgeCount,clipboard.writeText,file.exportText,file.exportImage",
"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,share.open,share.setTarget,navigation.openNativePage,app.openExternalUrl,app.setTitle,clipboard.writeText,file.exportText,file.exportImage",
"url": "index.html?clientRuntime=native_app&clientType=native_app&hostShell=tauri_desktop&hostPlatform=unknown&hostVersion=0.1.0&bridgeVersion=1&hostCapabilities=host.getRuntime,share.open,share.setTarget,navigation.openNativePage,app.openExternalUrl,app.setTitle,app.setBadgeCount,clipboard.writeText,file.exportText,file.exportImage",
"title": "Genarrative",
"width": 1280,
"height": 820,

View File

@@ -7,7 +7,7 @@ import { WebView } from 'react-native-webview';
import {
configureMobileHostBridgeNavigation,
handleMobileHostBridgeMessage,
MOBILE_HOST_CAPABILITIES,
resolveMobileHostCapabilities,
} from './src/mobileHostBridge';
import { buildMobileShellUrlFromDeepLink } from './src/mobileShellDeepLink';
import {
@@ -33,7 +33,7 @@ export default function App() {
() => ({
platform: Platform.OS === 'ios' ? 'ios' as const : 'android' as const,
hostVersion,
capabilities: MOBILE_HOST_CAPABILITIES,
capabilities: resolveMobileHostCapabilities(),
}),
[],
);

View File

@@ -47,7 +47,12 @@ const mobileCapabilities = extractStringArrayExport(
bridgeSource,
'MOBILE_HOST_CAPABILITIES',
);
const iosMobileCapabilities = extractStringArrayExport(
bridgeSource,
'IOS_MOBILE_HOST_CAPABILITIES',
);
const mobileCapabilitySet = new Set(mobileCapabilities);
const iosMobileCapabilitySet = new Set(iosMobileCapabilities);
const unknownMobileCapabilities = mobileCapabilities.filter(
(capability) => !sharedCapabilities.includes(capability),
);
@@ -57,7 +62,16 @@ if (unknownMobileCapabilities.length > 0) {
);
}
for (const capability of mobileCapabilities) {
const unknownIosMobileCapabilities = iosMobileCapabilities.filter(
(capability) => !sharedCapabilities.includes(capability),
);
if (unknownIosMobileCapabilities.length > 0) {
throw new Error(
`iOS mobile shell declares unknown HostBridge capabilities: ${unknownIosMobileCapabilities.join(', ')}`,
);
}
for (const capability of iosMobileCapabilities) {
const switchCase = `case '${capability}':`;
if (
capability !== 'host.events' &&
@@ -129,8 +143,12 @@ for (const snippet of [
}
const capabilityQuerySnippet = "capabilities: MOBILE_HOST_CAPABILITIES";
if (!appSource.includes(capabilityQuerySnippet)) {
throw new Error('mobile shell URL must use MOBILE_HOST_CAPABILITIES');
if (appSource.includes(capabilityQuerySnippet)) {
throw new Error('mobile shell URL must resolve platform-aware capabilities');
}
if (!appSource.includes('capabilities: resolveMobileHostCapabilities()')) {
throw new Error('mobile shell URL must use resolveMobileHostCapabilities()');
}
for (const capability of [
@@ -149,3 +167,11 @@ for (const capability of [
throw new Error(`mobile shell capabilities missing ${capability}`);
}
}
if (!iosMobileCapabilitySet.has('app.setBadgeCount')) {
throw new Error('iOS mobile shell capabilities missing app.setBadgeCount');
}
if (mobileCapabilitySet.has('app.setBadgeCount')) {
throw new Error('Android mobile shell base capabilities must not include app.setBadgeCount');
}

View File

@@ -1,7 +1,7 @@
import * as Haptics from 'expo-haptics';
import * as Linking from 'expo-linking';
import * as Sharing from 'expo-sharing';
import { Share } from 'react-native';
import { Platform, PushNotificationIOS, Share } from 'react-native';
import { afterEach, describe, expect, test, vi } from 'vitest';
import {
@@ -73,6 +73,9 @@ vi.mock('react-native', () => ({
Platform: {
OS: 'ios',
},
PushNotificationIOS: {
setApplicationIconBadgeNumber: vi.fn(),
},
Share: {
share: vi.fn(),
},
@@ -122,9 +125,15 @@ function expectFailed(response: HostBridgeResponse) {
return response;
}
function setPlatformOS(os: 'ios' | 'android') {
(Platform as { OS: 'ios' | 'android' }).OS = os;
}
afterEach(() => {
vi.mocked(Haptics.impactAsync).mockReset();
vi.mocked(Linking.openURL).mockReset();
vi.mocked(PushNotificationIOS.setApplicationIconBadgeNumber).mockReset();
setPlatformOS('ios');
vi.mocked(Sharing.isAvailableAsync).mockReset();
vi.mocked(Sharing.isAvailableAsync).mockResolvedValue(true);
vi.mocked(Sharing.shareAsync).mockReset();
@@ -152,10 +161,29 @@ describe('handleMobileHostBridgeMessage', () => {
expect(
(okResponse.result as { capabilities: string[] }).capabilities,
).toEqual(
expect.arrayContaining(['host.events', 'navigation.canGoBack']),
expect.arrayContaining([
'host.events',
'navigation.canGoBack',
'app.setBadgeCount',
]),
);
});
test('Android runtime 不声明 iOS 角标能力', async () => {
setPlatformOS('android');
const response = await send(request('host.getRuntime'));
const okResponse = expectOk(response);
expect(okResponse.result).toMatchObject({
shell: 'expo_mobile',
platform: 'android',
});
expect(
(okResponse.result as { capabilities: string[] }).capabilities,
).not.toContain('app.setBadgeCount');
});
test('navigation.openNativePage 把同源路径切到移动壳 WebView', async () => {
const openWebViewUrl = vi.fn();
configureMobileHostBridgeNavigation({
@@ -241,6 +269,40 @@ describe('handleMobileHostBridgeMessage', () => {
);
});
test('app.setBadgeCount 在 iOS 调起系统角标能力', async () => {
const response = await send(
request('app.setBadgeCount', {
count: 12,
}),
);
expectOk(response);
expect(
PushNotificationIOS.setApplicationIconBadgeNumber,
).toHaveBeenCalledWith(12);
});
test('app.setBadgeCount 拒绝非法数量并在 Android 返回 unsupported', async () => {
const invalid = await send(
request('app.setBadgeCount', {
count: 1.5,
}),
);
expect(expectFailed(invalid).error.code).toBe('invalid_request');
expect(PushNotificationIOS.setApplicationIconBadgeNumber).not.toHaveBeenCalled();
setPlatformOS('android');
const unsupported = await send(
request('app.setBadgeCount', {
count: 1,
}),
);
expect(expectFailed(unsupported).error.code).toBe('unsupported_capability');
expect(PushNotificationIOS.setApplicationIconBadgeNumber).not.toHaveBeenCalled();
});
test('share.open 使用直接分享 payload 调起系统分享', async () => {
const response = await send(
request('share.open', {

View File

@@ -3,7 +3,7 @@ import { File, Paths } from 'expo-file-system';
import * as Haptics from 'expo-haptics';
import * as Linking from 'expo-linking';
import * as Sharing from 'expo-sharing';
import { Platform, Share } from 'react-native';
import { Platform, PushNotificationIOS, Share } from 'react-native';
import {
type ClipboardWriteTextPayload,
@@ -20,9 +20,11 @@ import {
type HostBridgeRequest,
type HostBridgeResponse,
type NavigateNativePagePayload,
normalizeHostBridgeBadgeCount,
normalizeHostBridgeExportFileName,
normalizeHostBridgeExternalUrl,
type OpenExternalUrlPayload,
type SetBadgeCountPayload,
type ShareOpenPayload,
} from '../../../packages/shared/src/contracts/hostBridge';
import { resolveMobileShellWebViewUrl } from './mobileShellNavigation';
@@ -50,6 +52,17 @@ export const MOBILE_HOST_CAPABILITIES: HostBridgeCapability[] = [
'haptics.impact',
];
export const IOS_MOBILE_HOST_CAPABILITIES: HostBridgeCapability[] = [
...MOBILE_HOST_CAPABILITIES,
'app.setBadgeCount',
];
export function resolveMobileHostCapabilities(platform = Platform.OS) {
return platform === 'ios'
? IOS_MOBILE_HOST_CAPABILITIES
: MOBILE_HOST_CAPABILITIES;
}
export type MobileHostBridgeNavigation = {
allowedOrigin: string;
openWebViewUrl: (url: string) => void;
@@ -277,6 +290,25 @@ async function runHaptics(payload: unknown) {
return true;
}
function setBadgeCount(payload: unknown) {
if (Platform.OS !== 'ios') {
throw {
code: 'unsupported_capability',
message: 'app badge count is only supported on iOS mobile shell',
} satisfies HostBridgeError;
}
const count = normalizeHostBridgeBadgeCount(
(payload as SetBadgeCountPayload | undefined)?.count,
);
if (count === null) {
throw invalidRequest('count must be an integer between 0 and 99999');
}
PushNotificationIOS.setApplicationIconBadgeNumber(count);
return true;
}
function stringField(value: unknown, field: string) {
if (!value || typeof value !== 'object') {
return undefined;
@@ -385,7 +417,7 @@ async function handleRequest(request: HostBridgeRequest) {
platform: Platform.OS === 'ios' ? 'ios' : 'android',
hostVersion: '0.1.0',
bridgeVersion: HOST_BRIDGE_VERSION,
capabilities: MOBILE_HOST_CAPABILITIES,
capabilities: resolveMobileHostCapabilities(),
});
case 'app.openExternalUrl':
return ok(request, await openExternalUrl(request.payload));
@@ -397,6 +429,8 @@ async function handleRequest(request: HostBridgeRequest) {
return ok(request, await exportImageFile(request.payload));
case 'haptics.impact':
return ok(request, await runHaptics(request.payload));
case 'app.setBadgeCount':
return ok(request, setBadgeCount(request.payload));
case 'share.open':
return ok(request, await openShare(request.payload));
case 'share.setTarget':

View File

@@ -23,4 +23,28 @@ describe('buildMobileShellUrl', () => {
);
expect(url.searchParams.get('work')).toBe('PZ-1');
});
test('支持按平台注入不同能力清单', () => {
const iosUrl = new URL(
buildMobileShellUrl('https://app.test/', {
platform: 'ios',
hostVersion: '0.1.0',
capabilities: ['host.getRuntime', 'app.setBadgeCount'],
}),
);
const androidUrl = new URL(
buildMobileShellUrl('https://app.test/', {
platform: 'android',
hostVersion: '0.1.0',
capabilities: ['host.getRuntime'],
}),
);
expect(iosUrl.searchParams.get('hostCapabilities')).toBe(
'host.getRuntime,app.setBadgeCount',
);
expect(androidUrl.searchParams.get('hostCapabilities')).toBe(
'host.getRuntime',
);
});
});

View File

@@ -28,6 +28,7 @@
- 2026-06-18 壳能力防漂移:`npm run mobile-shell:typecheck``npm run desktop-shell:typecheck` 会校验 Expo / Tauri 壳声明的 capability 均来自共享 HostBridge 白名单,并校验壳 runtime 回包、H5 URL `hostCapabilities` 和实现分支保持一致;新增能力必须先更新契约和真实壳实现,再通过这些检查。
- 2026-06-18 原生壳统一验收门禁:根级 `npm run check:native-shells` 统一执行 H5 HostBridge 关键测试、Expo 壳 typecheck / test 和 Tauri 壳 typecheck / cargo test根级 `npm run check` 会在 lint、主站测试、构建和内容检查后继续执行该门禁避免 HostBridge 与两端壳验收散落成容易漏跑的单项命令。
- 2026-06-18 分享卡图片导出:新增 `file.exportImage` HostBridge capabilityH5 分享卡下载在 native app 中优先把 canvas 生成的 base64 图片交给宿主导出Expo 壳写缓存图片后交给系统分享 / 保存面板Tauri 壳通过系统保存对话框写入图片字节。该能力只接受 `image/png` / `image/jpeg` / `image/webp`、单次 5 MiB 内图片数据,成功只返回文件名和字节数,不暴露本机绝对路径;宿主未声明时保留浏览器下载。
- 2026-06-18 应用角标能力:新增 `app.setBadgeCount` HostBridge capabilityH5 只传 `0-99999` 整数并在宿主未声明时静默 fallbackExpo 壳只在 iOS 声明并通过 React Native `PushNotificationIOS` 设置应用图标角标Android 不声明、不伪造成功Tauri 壳通过主窗口 `set_badge_count` 设置任务栏角标,底层平台不支持时返回真实错误。
- 影响范围:`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

@@ -119,6 +119,7 @@ type HostBridgeEvent = {
| `navigation.canGoBack` | 通知 H5 宿主返回栈状态 | 支持事件 | 不声明 |
| `app.openExternalUrl` | 用系统浏览器打开外链 | 支持白名单协议 | 支持白名单协议 |
| `app.setTitle` | 同步宿主窗口标题 | 不声明 | 支持 |
| `app.setBadgeCount` | 设置应用 / 任务栏角标 | 仅 iOS 支持Android 不声明 | 支持;平台底层不支持时返回错误 |
| `clipboard.writeText` | 写剪贴板 | 支持 | 支持 |
| `file.exportText` | 导出文本到用户选择的本地文件 | 支持系统分享 / 保存面板 | 支持系统保存对话框 |
| `haptics.impact` | 轻量触感反馈 | 支持 | 不声明 |
@@ -242,7 +243,7 @@ GameBridge 禁止:
- iOS / Android 深链打开作品详情、创作页和邀请码。
- 登录和支付先 fallback 到 H5只把能力边界跑通。
当前状态:已新增 `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``host.events``share.open``share.setTarget``navigation.openNativePage``navigation.canGoBack``app.openExternalUrl``clipboard.writeText``file.exportText``file.exportImage``haptics.impact` 和 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 复制服务优先调用并写入系统剪贴板;`file.exportText` 通过 Expo 文件系统写入缓存文本文件,再交给系统分享 / 保存面板,文件名必须清洗,单次文本不超过 5 MiB成功只返回文件名和字节数`file.exportImage` 通过 Expo 文件系统写入缓存图片,再交给系统分享 / 保存面板H5 只传允许 MIME 的 base64 图片数据,单次不超过 5 MiB分享卡下载会优先走该能力`haptics.impact` 通过 Expo Haptics 承接运行时轻触反馈H5 在宿主不支持时回退到浏览器 vibration。登录和支付尚未接入渠道 SDK / 原生页面时明确返回 unsupported让 H5 fallback 承接。
当前状态:已新增 `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``host.events``share.open``share.setTarget``navigation.openNativePage``navigation.canGoBack``app.openExternalUrl``clipboard.writeText``file.exportText``file.exportImage``haptics.impact` 和 Android 返回键回退;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 复制服务优先调用并写入系统剪贴板;`file.exportText` 通过 Expo 文件系统写入缓存文本文件,再交给系统分享 / 保存面板,文件名必须清洗,单次文本不超过 5 MiB成功只返回文件名和字节数`file.exportImage` 通过 Expo 文件系统写入缓存图片,再交给系统分享 / 保存面板H5 只传允许 MIME 的 base64 图片数据,单次不超过 5 MiB分享卡下载会优先走该能力`haptics.impact` 通过 Expo Haptics 承接运行时轻触反馈H5 在宿主不支持时回退到浏览器 vibration。登录和支付尚未接入渠道 SDK / 原生页面时明确返回 unsupported让 H5 fallback 承接。
### Phase 3Tauri 桌面壳 MVP
@@ -253,7 +254,7 @@ GameBridge 禁止:
- 实现 runtime、openExternalUrl、clipboard、share fallback、窗口标题同步。
- 验证 macOS / Windows / Linux 至少一条本地 smoke。
当前状态:已新增 `apps/desktop-shell/`Tauri dev 直接加载本地主站 Viterelease 打包根 `dist` 主站资产。Rust 侧只把 `host_bridge_request` command 授给主窗口,`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 复制服务优先调用,`app.setTitle` 通过 Tauri 主窗口 API 同步窗口标题并拒绝空标题 / 控制字符H5 主站会按当前平台阶段先更新 `document.title`,再通过 `app.setTitle` 把同一标题同步给 Tauri 窗口Expo 移动壳不声明该能力时静默忽略;不把 opener、clipboard 或 dialog 插件命令直接暴露给前端。当前真实能力为 `host.getRuntime``share.setTarget``share.open``navigation.openNativePage``app.openExternalUrl``app.setTitle``clipboard.writeText``file.exportText``file.exportImage`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`。原生系统分享面板、登录和支付未接入真实插件 / 渠道前不声明支持,不返回 mock 成功。
当前状态:已新增 `apps/desktop-shell/`Tauri dev 直接加载本地主站 Viterelease 打包根 `dist` 主站资产。Rust 侧只把 `host_bridge_request` command 授给主窗口,`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 复制服务优先调用,`app.setTitle` 通过 Tauri 主窗口 API 同步窗口标题并拒绝空标题 / 控制字符`app.setBadgeCount` 通过主窗口 `set_badge_count` 设置任务栏角标,数量只接受 `0-99999` 整数且 `0` 表示清除H5 主站会按当前平台阶段先更新 `document.title`,再通过 `app.setTitle` 把同一标题同步给 Tauri 窗口Expo 移动壳不声明该能力时静默忽略;不把 opener、clipboard 或 dialog 插件命令直接暴露给前端。当前真实能力为 `host.getRuntime``share.setTarget``share.open``navigation.openNativePage``app.openExternalUrl``app.setTitle``app.setBadgeCount``clipboard.writeText``file.exportText``file.exportImage`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`。原生系统分享面板、登录和支付未接入真实插件 / 渠道前不声明支持,不返回 mock 成功。
### Phase 4宿主能力扩展

View File

@@ -48,6 +48,7 @@ AI H5 sandbox
- `writeHostClipboardText()`:原生 App 宿主的受控剪贴板入口。H5 复制服务在 `native_app` 中优先通过 `clipboard.writeText` 写入 Expo / Tauri 系统剪贴板;宿主不可用、拒绝或返回 unsupported 时继续回退到浏览器 Clipboard API 和 legacy selection copy。
- `requestHostHapticsImpact()`:原生 App 宿主的受控触觉反馈入口。Expo 移动壳通过 `haptics.impact` 调用 Expo HapticsH5 运行时点击反馈在 `native_app` 中优先请求宿主触觉,宿主不可用、拒绝或返回 unsupported 时继续回退到浏览器 `navigator.vibrate`
- `setHostAppTitle()`:原生 App 宿主的受控窗口标题入口。H5 主站会按当前平台阶段先同步 `document.title`,再通过 `app.setTitle` 请求宿主窗口标题同步Tauri 桌面壳支持该能力Expo 移动壳不声明时静默忽略。
- `setHostAppBadgeCount()`:原生 App 宿主的受控应用角标入口。H5 只传 `0-99999` 的整数,`0` 表示清除角标Expo 移动壳只在 iOS 声明 `app.setBadgeCount` 并通过 React Native `PushNotificationIOS` 设置应用图标角标Android 不声明该能力Tauri 桌面壳通过主窗口 `set_badge_count` 设置任务栏角标,底层平台不支持时返回明确错误,由 H5 视作失败并继续主流程。
- `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 承接。

View File

@@ -2,6 +2,7 @@ import { describe, expect, test } from 'vitest';
import {
isHostBridgeCapability,
normalizeHostBridgeBadgeCount,
normalizeHostBridgeExportFileName,
normalizeHostBridgeExternalUrl,
} from './hostBridge';
@@ -46,8 +47,19 @@ describe('HostBridge shared contract helpers', () => {
test('识别 HostBridge 能力白名单', () => {
expect(isHostBridgeCapability('share.open')).toBe(true);
expect(isHostBridgeCapability('app.setBadgeCount')).toBe(true);
expect(isHostBridgeCapability('navigation.canGoBack')).toBe(true);
expect(isHostBridgeCapability('unknown.capability')).toBe(false);
expect(isHostBridgeCapability(null)).toBe(false);
});
test('归一化宿主角标数量', () => {
expect(normalizeHostBridgeBadgeCount(0)).toBe(0);
expect(normalizeHostBridgeBadgeCount(12)).toBe(12);
expect(normalizeHostBridgeBadgeCount(99999)).toBe(99999);
expect(normalizeHostBridgeBadgeCount(-1)).toBeNull();
expect(normalizeHostBridgeBadgeCount(1.5)).toBeNull();
expect(normalizeHostBridgeBadgeCount(100000)).toBeNull();
expect(normalizeHostBridgeBadgeCount('1')).toBeNull();
});
});

View File

@@ -22,6 +22,7 @@ export const HOST_BRIDGE_METHODS = [
'navigation.openNativePage',
'app.openExternalUrl',
'app.setTitle',
'app.setBadgeCount',
'clipboard.writeText',
'file.exportText',
'file.exportImage',
@@ -113,6 +114,25 @@ export type SetTitlePayload = {
title: string;
};
export type SetBadgeCountPayload = {
count: number;
};
export const HOST_BRIDGE_BADGE_COUNT_MAX = 99999;
export function normalizeHostBridgeBadgeCount(rawCount: unknown) {
if (
typeof rawCount !== 'number' ||
!Number.isInteger(rawCount) ||
rawCount < 0 ||
rawCount > HOST_BRIDGE_BADGE_COUNT_MAX
) {
return null;
}
return rawCount;
}
export const HOST_BRIDGE_EXTERNAL_URL_PROTOCOLS = [
'http:',
'https:',

View File

@@ -25,6 +25,7 @@ import {
requestWechatMiniProgramPhoneLogin,
resetHostRuntimeCacheForTest,
resolveHostRuntime,
setHostAppBadgeCount,
setHostAppTitle,
setHostShareTarget,
subscribeHostRuntimeChange,
@@ -443,6 +444,7 @@ describe('hostBridge', () => {
'haptics.impact',
'app.openExternalUrl',
'app.setTitle',
'app.setBadgeCount',
'share.open',
'file.exportImage',
]),
@@ -477,6 +479,7 @@ describe('hostBridge', () => {
await expect(setHostAppTitle({ title: ' 拼图 - 陶泥儿 ' })).resolves.toBe(
true,
);
await expect(setHostAppBadgeCount({ count: 7 })).resolves.toBe(true);
await expect(
openHostShare({
title: '暖灯猫街',
@@ -544,6 +547,14 @@ describe('hostBridge', () => {
},
}),
});
expect(invoke).toHaveBeenCalledWith('host_bridge_request', {
request: expect.objectContaining({
method: 'app.setBadgeCount',
payload: {
count: 7,
},
}),
});
expect(invoke).toHaveBeenCalledWith('host_bridge_request', {
request: expect.objectContaining({
method: 'share.open',
@@ -611,6 +622,9 @@ describe('hostBridge', () => {
false,
);
await expect(setHostAppTitle({ title: ' ' })).resolves.toBe(false);
await expect(setHostAppBadgeCount({ count: 1 })).resolves.toBe(false);
await expect(setHostAppBadgeCount({ count: -1 })).resolves.toBe(false);
await expect(setHostAppBadgeCount({ count: 1.5 })).resolves.toBe(false);
await expect(
openHostShare({
title: '暖灯猫街',

View File

@@ -8,10 +8,12 @@ import type {
HostBridgeMethod,
HostBridgeRuntimeResult,
OpenExternalUrlPayload,
SetBadgeCountPayload,
ShareOpenPayload,
} from '../../../packages/shared/src/contracts/hostBridge';
import {
isHostBridgeCapability,
normalizeHostBridgeBadgeCount,
normalizeHostBridgeExternalUrl,
} from '../../../packages/shared/src/contracts/hostBridge';
import type {
@@ -87,6 +89,8 @@ export type HostAppTitleRequest = {
title: string;
};
export type HostAppBadgeCountRequest = SetBadgeCountPayload;
export type HostShareOpenRequest = ShareOpenPayload;
export type HostExternalUrlRequest = OpenExternalUrlPayload;
@@ -740,3 +744,23 @@ export async function setHostAppTitle({ title }: HostAppTitleRequest) {
return false;
}
}
export async function setHostAppBadgeCount({
count,
}: HostAppBadgeCountRequest) {
const normalizedCount = normalizeHostBridgeBadgeCount(count);
if (
normalizedCount === null ||
!canUseNativeHostCapability('app.setBadgeCount')
) {
return false;
}
try {
return await requestNativeHostBoolean('app.setBadgeCount', {
count: normalizedCount,
});
} catch {
return false;
}
}