接入桌面壳文本文件导出能力

新增 HostBridge file.exportText 契约、文件名清洗和 H5 导出入口

Tauri 桌面壳通过受控 host_bridge_request 打开保存对话框并写入文本文件

Expo 移动壳对未接入的文件导出能力明确返回 unsupported

更新宿主壳方案、统一协议和项目共享决策记录
This commit is contained in:
2026-06-17 23:02:01 +08:00
parent 6f19e1c3ba
commit d67f9d5725
14 changed files with 540 additions and 12 deletions

View File

@@ -34,7 +34,7 @@ const requiredUrlParts = [
'hostShell=tauri_desktop',
'hostPlatform=unknown',
'bridgeVersion=1',
'hostCapabilities=host.getRuntime,share.open,share.setTarget,app.openExternalUrl,app.setTitle,clipboard.writeText',
'hostCapabilities=host.getRuntime,share.open,share.setTarget,app.openExternalUrl,app.setTitle,clipboard.writeText,file.exportText',
];
for (const part of requiredUrlParts) {
@@ -57,7 +57,10 @@ const requiredMainSnippets = [
'"share.setTarget"',
'"app.setTitle"',
'"clipboard.writeText"',
'"file.exportText"',
'tauri_plugin_dialog::init()',
'"copied_to_clipboard"',
'"file export cancelled"',
'set_title',
];

View File

@@ -1282,6 +1282,7 @@ dependencies = [
"tauri",
"tauri-build",
"tauri-plugin-clipboard-manager",
"tauri-plugin-dialog",
"tauri-plugin-opener",
]
@@ -2349,6 +2350,7 @@ checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
dependencies = [
"bitflags 2.13.0",
"block2",
"libc",
"objc2",
"objc2-core-foundation",
]
@@ -2915,6 +2917,30 @@ dependencies = [
"web-sys",
]
[[package]]
name = "rfd"
version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a15ad77d9e70a92437d8f74c35d99b4e4691128df018833e99f90bcd36152672"
dependencies = [
"block2",
"dispatch2",
"glib-sys",
"gobject-sys",
"gtk-sys",
"js-sys",
"log",
"objc2",
"objc2-app-kit",
"objc2-core-foundation",
"objc2-foundation",
"raw-window-handle",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"windows-sys 0.60.2",
]
[[package]]
name = "rustc-hash"
version = "2.1.2"
@@ -3613,6 +3639,48 @@ dependencies = [
"thiserror 2.0.18",
]
[[package]]
name = "tauri-plugin-dialog"
version = "2.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65981abb771e74e571a38196c3baa11c459379164791eba0e67abc1a5fac9884"
dependencies = [
"log",
"raw-window-handle",
"rfd",
"serde",
"serde_json",
"tauri",
"tauri-plugin",
"tauri-plugin-fs",
"thiserror 2.0.18",
"url",
]
[[package]]
name = "tauri-plugin-fs"
version = "2.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7ecc274121aca0c036a2b42d1cbe83d368d348f54e0bb8a735c2b1548e8f371"
dependencies = [
"anyhow",
"dunce",
"glob",
"log",
"objc2-foundation",
"percent-encoding",
"schemars 0.8.22",
"serde",
"serde_json",
"serde_repr",
"tauri",
"tauri-plugin",
"tauri-utils",
"thiserror 2.0.18",
"toml 1.1.2+spec-1.1.0",
"url",
]
[[package]]
name = "tauri-plugin-opener"
version = "2.5.4"
@@ -4818,6 +4886,15 @@ dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-sys"
version = "0.60.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
dependencies = [
"windows-targets 0.53.5",
]
[[package]]
name = "windows-sys"
version = "0.61.2"
@@ -4851,13 +4928,30 @@ dependencies = [
"windows_aarch64_gnullvm 0.52.6",
"windows_aarch64_msvc 0.52.6",
"windows_i686_gnu 0.52.6",
"windows_i686_gnullvm",
"windows_i686_gnullvm 0.52.6",
"windows_i686_msvc 0.52.6",
"windows_x86_64_gnu 0.52.6",
"windows_x86_64_gnullvm 0.52.6",
"windows_x86_64_msvc 0.52.6",
]
[[package]]
name = "windows-targets"
version = "0.53.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
dependencies = [
"windows-link 0.2.1",
"windows_aarch64_gnullvm 0.53.1",
"windows_aarch64_msvc 0.53.1",
"windows_i686_gnu 0.53.1",
"windows_i686_gnullvm 0.53.1",
"windows_i686_msvc 0.53.1",
"windows_x86_64_gnu 0.53.1",
"windows_x86_64_gnullvm 0.53.1",
"windows_x86_64_msvc 0.53.1",
]
[[package]]
name = "windows-threading"
version = "0.1.0"
@@ -4888,6 +4982,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
[[package]]
name = "windows_aarch64_msvc"
version = "0.42.2"
@@ -4900,6 +5000,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_aarch64_msvc"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
[[package]]
name = "windows_i686_gnu"
version = "0.42.2"
@@ -4912,12 +5018,24 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnu"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_gnullvm"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
[[package]]
name = "windows_i686_msvc"
version = "0.42.2"
@@ -4930,6 +5048,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_i686_msvc"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
[[package]]
name = "windows_x86_64_gnu"
version = "0.42.2"
@@ -4942,6 +5066,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnu"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.42.2"
@@ -4954,6 +5084,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
[[package]]
name = "windows_x86_64_msvc"
version = "0.42.2"
@@ -4966,6 +5102,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "windows_x86_64_msvc"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
[[package]]
name = "winnow"
version = "0.5.40"

View File

@@ -12,4 +12,5 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1"
tauri = { version = "2.11.2", features = [] }
tauri-plugin-clipboard-manager = "2.3.2"
tauri-plugin-dialog = "2.7.1"
tauri-plugin-opener = "2.5.4"

View File

@@ -1,14 +1,20 @@
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::fs;
use std::path::PathBuf;
use std::sync::Mutex;
use tauri::Manager;
use tauri_plugin_clipboard_manager::ClipboardExt;
use tauri_plugin_dialog::DialogExt;
use tauri_plugin_opener::OpenerExt;
const HOST_BRIDGE_PROTOCOL: &str = "GenarrativeHostBridge";
const HOST_BRIDGE_VERSION: u8 = 1;
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_FILE_NAME_FALLBACK: &str = "genarrative-export.txt";
const EXPORT_FILE_NAME_MAX_LENGTH: usize = 120;
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -74,6 +80,7 @@ fn capabilities() -> Vec<&'static str> {
"app.openExternalUrl",
"app.setTitle",
"clipboard.writeText",
"file.exportText",
]
}
@@ -168,6 +175,81 @@ fn normalize_window_title(raw_title: &str) -> Option<String> {
Some(title.chars().take(80).collect())
}
fn normalize_export_file_name(raw_file_name: &str) -> String {
let mut file_name = String::new();
let mut last_was_space = false;
for character in raw_file_name.trim().chars().take(EXPORT_FILE_NAME_MAX_LENGTH) {
if character.is_control()
|| matches!(
character,
'<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*'
)
{
file_name.push('-');
last_was_space = false;
continue;
}
if character.is_whitespace() {
if !last_was_space {
file_name.push(' ');
last_was_space = true;
}
continue;
}
file_name.push(character);
last_was_space = false;
}
let file_name = file_name
.trim()
.trim_start_matches(|character| matches!(character, '.' | '-') || character.is_whitespace())
.trim();
if file_name.is_empty() {
EXPORT_FILE_NAME_FALLBACK.to_string()
} else {
file_name.to_string()
}
}
fn export_text_payload(
request: &HostBridgeRequest,
) -> Result<(String, String), HostBridgeResponse> {
let payload = request.payload.as_ref().ok_or_else(|| {
failed(
request.id.clone(),
"invalid_request",
"fileName and content are required",
)
})?;
let file_name = payload
.get("fileName")
.and_then(Value::as_str)
.map(normalize_export_file_name)
.unwrap_or_else(|| EXPORT_FILE_NAME_FALLBACK.to_string());
let content = payload
.get("content")
.and_then(Value::as_str)
.ok_or_else(|| failed(request.id.clone(), "invalid_request", "content is required"))?;
if content.len() > EXPORT_TEXT_MAX_BYTES {
return Err(failed(
request.id.clone(),
"invalid_request",
"content exceeds file export size limit",
));
}
Ok((file_name, content.to_string()))
}
fn write_export_text_file(path: PathBuf, content: String) -> Result<usize, String> {
fs::write(path, content.as_bytes()).map_err(|error| error.to_string())?;
Ok(content.len())
}
fn payload_string<'a>(value: &'a Value, field: &str) -> Option<&'a str> {
value
.get(field)
@@ -266,9 +348,8 @@ fn resolve_host_bridge_request(request: HostBridgeRequest) -> HostBridgeResponse
}
#[tauri::command]
fn host_bridge_request(
async fn host_bridge_request(
app: tauri::AppHandle,
share_state: tauri::State<'_, DesktopShareState>,
request: HostBridgeRequest,
) -> HostBridgeResponse {
if let Some(response) = validate_request(&request) {
@@ -307,6 +388,42 @@ fn host_bridge_request(
Err(error) => failed(request.id, "host_error", error.to_string()),
}
}
"file.exportText" => {
let (file_name, content) = match export_text_payload(&request) {
Ok(payload) => payload,
Err(response) => return response,
};
let file_path = app
.dialog()
.file()
.add_filter("Text", &["txt", "json", "md", "csv"])
.set_file_name(file_name.clone())
.blocking_save_file();
let Some(file_path) = file_path else {
return failed(request.id, "cancelled", "file export cancelled");
};
let path = match file_path.into_path() {
Ok(path) => path,
Err(error) => return failed(request.id, "host_error", error.to_string()),
};
let export_result =
tauri::async_runtime::spawn_blocking(move || write_export_text_file(path, content))
.await;
let bytes = match export_result {
Ok(Ok(bytes)) => bytes,
Ok(Err(error)) => return failed(request.id, "host_error", error),
Err(error) => return failed(request.id, "host_error", error.to_string()),
};
ok(
request.id,
json!({
"action": "saved",
"fileName": file_name,
"bytes": bytes,
}),
)
}
"app.setTitle" => {
let title = match required_string_payload(&request, "title")
.ok()
@@ -332,16 +449,19 @@ fn host_bridge_request(
let Some(target) = target else {
return failed(request.id, "invalid_request", "target is required");
};
let share_state = app.state::<DesktopShareState>();
match share_state.target.lock() {
let response = match share_state.target.lock() {
Ok(mut current_target) => {
*current_target = Some(target.clone());
ok(request.id, json!(true))
}
Err(_) => failed(request.id, "host_error", "share target lock poisoned"),
}
};
response
}
"share.open" => {
let share_state = app.state::<DesktopShareState>();
let share_text = match share_text_from_request(&request, &share_state) {
Ok(text) => text,
Err(response) => return response,
@@ -365,6 +485,7 @@ fn main() {
tauri::Builder::default()
.manage(DesktopShareState::default())
.plugin(tauri_plugin_clipboard_manager::init())
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_opener::init())
.setup(|app| {
let window_config = app.config().app.windows.get(0).cloned();
@@ -413,6 +534,10 @@ mod tests {
.as_array()
.unwrap()
.contains(&json!("app.setTitle")));
assert!(result["capabilities"]
.as_array()
.unwrap()
.contains(&json!("file.exportText")));
}
#[test]
@@ -484,6 +609,72 @@ mod tests {
);
}
#[test]
fn export_file_name_normalization_rejects_path_like_characters() {
assert_eq!(
normalize_export_file_name(" 作品:记录?.txt "),
"作品-记录-.txt"
);
assert_eq!(normalize_export_file_name("../secret.txt"), "secret.txt");
assert_eq!(normalize_export_file_name(""), EXPORT_FILE_NAME_FALLBACK);
let long_file_name = "".repeat(140);
assert_eq!(
normalize_export_file_name(&long_file_name).chars().count(),
EXPORT_FILE_NAME_MAX_LENGTH
);
}
#[test]
fn export_text_payload_requires_text_content() {
let mut invalid = request("file.exportText");
invalid.payload = Some(json!({
"fileName": "作品记录.txt",
"content": 123
}));
let response = export_text_payload(&invalid).expect_err("invalid content");
assert!(!response.ok);
let error = response.error.expect("error");
assert_eq!(error.code, "invalid_request");
assert_eq!(error.message, "content is required");
}
#[test]
fn export_text_payload_rejects_oversized_content() {
let mut invalid = request("file.exportText");
invalid.payload = Some(json!({
"fileName": "作品记录.txt",
"content": "a".repeat(EXPORT_TEXT_MAX_BYTES + 1)
}));
let response = export_text_payload(&invalid).expect_err("oversized content");
assert!(!response.ok);
let error = response.error.expect("error");
assert_eq!(error.code, "invalid_request");
assert_eq!(error.message, "content exceeds file export size limit");
}
#[test]
fn write_export_text_file_persists_utf8_content() {
let path = std::env::temp_dir().join(format!(
"genarrative-host-bridge-export-{}.txt",
std::process::id()
));
let bytes = write_export_text_file(path.clone(), "暖灯猫街".to_string())
.expect("write export file");
assert_eq!(bytes, "暖灯猫街".len());
assert_eq!(
fs::read_to_string(&path).expect("read export file"),
"暖灯猫街"
);
fs::remove_file(path).expect("remove export file");
}
#[test]
fn share_text_uses_direct_share_payload() {
let state = DesktopShareState::default();

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,app.openExternalUrl,app.setTitle,clipboard.writeText",
"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,app.openExternalUrl,app.setTitle,clipboard.writeText,file.exportText",
"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,app.openExternalUrl,app.setTitle,clipboard.writeText",
"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,app.openExternalUrl,app.setTitle,clipboard.writeText,file.exportText",
"title": "Genarrative",
"width": 1280,
"height": 820,