接入原生壳应用角标能力

新增 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',
);
});
});