Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(web): add native mobile image sharing (#767)

Generc20ced67f437
diff --git a/scripts/ci/mobile-share-image.test.ts b/scripts/ci/mobile-share-image.test.ts
new file mode 100644
index 000000000..8c94c7508
--- /dev/null
+++ b/scripts/ci/mobile-share-image.test.ts
@@ -0,0 +1,202 @@
+import { readFileSync, readdirSync } from "node:fs"
+import { resolve } from "node:path"
+import { describe, expect, it } from "vitest"
+
+const root = resolve(import.meta.dirname, "../..")
+const tauriRoot = resolve(root, "src/desktop/src-tauri")
+const pluginRoot = resolve(tauriRoot, "plugins/mobile-share-image")
+const readRoot = (file: string) => readFileSync(resolve(root, file), "utf8")
+const readTauri = (file: string) => readFileSync(resolve(tauriRoot, file), "utf8")
+const readPlugin = (file: string) => readFileSync(resolve(pluginRoot, file), "utf8")
+
+type Capability = {
+ identifier: string
+ windows: string[]
+ platforms: string[]
+ local: boolean
+ remote: { urls: string[] }
+ permissions: string[]
+}
+
+const production = JSON.parse(readTauri("tauri.conf.json")) as {
+ app: { security: { capabilities: string[] } }
+}
+const development = JSON.parse(readTauri("tauri.dev.conf.json")) as {
+ app: { security: { capabilities: Array<string | Capability> } }
+}
+const mobileCapability = JSON.parse(
+ readTauri("capabilities/mobile-share-image-mobile.json"),
+) as Capability
+const build = readTauri("build.rs")
+const rustEntry = readTauri("src/lib.rs")
+const imageRuntime = readTauri("src/mobile_share_image_runtime.rs")
+const oauthRuntime = readTauri("src/native_oauth_runtime.rs")
+const guard = readTauri("src/native_command_guard.rs")
+const appManifest = readTauri("gen/android/app/src/main/AndroidManifest.xml")
+const pluginManifest = readPlugin("android/src/main/AndroidManifest.xml")
+const providerPaths = readPlugin("android/src/main/res/xml/mobile_share_image_file_paths.xml")
+const androidImage = readPlugin(
+ "android/src/main/java/ai/alook/plugin/mobileshareimage/MobileShareImage.kt",
+)
+const androidDocumentOwner = readPlugin(
+ "android/src/main/java/ai/alook/plugin/mobileshareimage/MobileShareImageDocumentOwner.kt",
+)
+const androidDocumentCore = readPlugin(
+ "android/src/main/java/ai/alook/plugin/mobileshareimage/MobileShareImageDocumentCoordinatorCore.kt",
+)
+const androidDocumentResultAdapter = readPlugin(
+ "android/src/main/java/ai/alook/plugin/mobileshareimage/MobileShareImageDocumentResultAdapter.kt",
+)
+const androidClipboardTransaction = readPlugin(
+ "android/src/main/java/ai/alook/plugin/mobileshareimage/MobileShareImageClipboardTransaction.kt",
+)
+const androidPlugin = readPlugin(
+ "android/src/main/java/ai/alook/plugin/mobileshareimage/MobileShareImagePlugin.kt",
+)
+const iosProject = readTauri("gen/apple/project.yml")
+const iosPlugin = readPlugin("ios/Sources/MobileShareImagePlugin.swift")
+
+describe("native mobile share-image contract", () => {
+ it("grants only both generated commands to the exact mobile production and dev callers", () => {
+ const expected = {
+ windows: ["main"],
+ platforms: ["android", "iOS"],
+ remote: { urls: ["https://alook.ai"] },
+ local: false,
+ permissions: [
+ "allow-mobile-share-image-copy",
+ "allow-mobile-share-image-save",
+ ],
+ }
+ expect(production.app.security.capabilities).toContain("mobile-share-image-mobile")
+ expect(mobileCapability).toMatchObject(expected)
+
+ const dev = development.app.security.capabilities.find(
+ capability => typeof capability !== "string"
+ && capability.identifier === "mobile-share-image-dev",
+ )
+ expect(dev).toMatchObject({
+ ...expected,
+ identifier: "mobile-share-image-dev",
+ local: true,
+ remote: { urls: ["http://localhost:3000"] },
+ })
+ for (const capability of [mobileCapability, dev as Capability]) {
+ expect(capability.permissions).not.toEqual(expect.arrayContaining([
+ expect.stringMatching(/^(?:core:default$|core:event:|fs:|store:|deep-link:)/),
+ ]))
+ }
+ })
+
+ it("uses one shared exact-origin guard before either native image lease", () => {
+ expect(imageRuntime).toContain("use crate::native_command_guard::guard;")
+ expect(oauthRuntime).toContain("use crate::native_command_guard::guard;")
+ expect(imageRuntime.indexOf("guard(&window)")).toBeLessThan(
+ imageRuntime.indexOf("state.acquire()"),
+ )
+ expect(guard).toContain('label == "main"')
+ expect(guard).toContain('"http://localhost:3000"')
+ expect(guard).toContain('"https://alook.ai"')
+ expect(guard).toContain("url.username().is_empty()")
+ expect(guard).toContain("url.password().is_none()")
+ expect(guard).toContain("https://alook.ai.evil.example/c")
+ })
+
+ it("generates command ACLs from AppManifest and registers the plugin only on mobile", () => {
+ for (const command of ["mobile_share_image_copy", "mobile_share_image_save"]) {
+ expect(build).toContain(`"${command}"`)
+ expect(rustEntry).toContain(`mobile_share_image_runtime::${command}`)
+ }
+ expect(rustEntry).toContain("fn run_mobile(")
+ expect(rustEntry).toContain("tauri_plugin_mobile_share_image::init()")
+ expect(readTauri("Cargo.toml")).toContain(
+ 'tauri-plugin-mobile-share-image = { path = "plugins/mobile-share-image" }',
+ )
+ const handwritten = readdirSync(resolve(tauriRoot, "permissions"))
+ .filter(name => name.endsWith(".toml"))
+ .map(name => readTauri(`permissions/${name}`))
+ .join("\n")
+ expect(handwritten).not.toContain("allow-mobile-share-image-copy")
+ expect(handwritten).not.toContain("allow-mobile-share-image-save")
+ })
+
+ it("keeps Android clipboard exposure narrow and storage permissions absent", () => {
+ expect(appManifest).not.toContain("FileProvider")
+ expect(pluginManifest).toContain(
+ 'android:name="ai.alook.plugin.mobileshareimage.MobileShareImageFileProvider"',
+ )
+ expect(pluginManifest).toContain(
+ 'android:authorities="${applicationId}.mobile_share_image.fileprovider"',
+ )
+ expect(pluginManifest).toContain('android:exported="false"')
+ expect(pluginManifest).toContain('android:grantUriPermissions="true"')
+ expect(providerPaths.match(/<cache-path/g)).toHaveLength(1)
+ expect(providerPaths).toContain('path="mobile-share-image/clipboard/"')
+ expect(providerPaths).not.toMatch(/<(?:external-path|external-files-path|root-path|files-path)\b/)
+ expect(`${appManifest}\n${pluginManifest}`).not.toMatch(
+ /READ_MEDIA_IMAGES|READ_EXTERNAL_STORAGE|WRITE_EXTERNAL_STORAGE/,
+ )
+ })
+
+ it("locks the Android API split, exact journal, and dedicated SAF launcher", () => {
+ expect(androidPlugin).toContain("Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q")
+ expect(androidImage).toContain('private const val RELATIVE_PATH = "Pictures/Alook/"')
+ expect(androidImage).toContain("MediaStore.Images.Media.IS_PENDING")
+ expect(androidImage).toContain("MediaStore.Images.Media.OWNER_PACKAGE_NAME")
+ expect(androidImage).toContain("MediaStore.QUERY_ARG_MATCH_PENDING")
+ expect(androidDocumentOwner).toContain("Intent.ACTION_CREATE_DOCUMENT")
+ expect(androidDocumentOwner).toContain("ActivityResultContracts.StartActivityForResult()")
+ expect(androidDocumentOwner).toContain("activity.activityResultRegistry.register(")
+ expect(androidDocumentOwner).toContain("deliver = { token, result ->")
+ expect(androidDocumentResultAdapter).toContain(
+ 'private fun resultKey(token: String): String = "alook.mobileShareImage.document.$token"',
+ )
+ expect(androidDocumentResultAdapter).toContain("deliver(token, result)")
+ expect(androidDocumentCore).toContain("class MobileShareImageDocumentCoordinatorCore")
+ expect(androidDocumentCore).toContain("fun begin(")
+ expect(androidDocumentCore).toContain("fun deliver(")
+ expect(androidDocumentCore).toContain("MobileShareImageDocumentPhase.WRITING")
+ const documentSources = [
+ androidDocumentOwner,
+ androidDocumentResultAdapter,
+ androidDocumentCore,
+ ].join("\n")
+ expect(documentSources).not.toContain("startActivityForResult")
+ expect(documentSources).not.toContain("@ActivityCallback")
+ expect(documentSources).not.toContain("contentResolver.delete")
+ expect(androidPlugin).toContain("commitMobileShareImageClipboard(")
+ expect(androidClipboardTransaction.indexOf("publish()"))
+ .toBeLessThan(androidClipboardTransaction.indexOf("runCatching(cleanupAfterPublish)"))
+ expect(androidClipboardTransaction).not.toContain("deleteUnpublished()")
+ })
+
+ it("uses add-only PhotoKit and the iOS 14-compatible PNG resource property", () => {
+ expect(iosProject).toContain(
+ "NSPhotoLibraryAddUsageDescription: Allow Alook to save shared message images to Photos.",
+ )
+ expect(iosProject).not.toContain("NSPhotoLibraryUsageDescription")
+ expect(iosPlugin).toContain("authorizationStatus(for: .addOnly)")
+ expect(iosPlugin).toContain("requestAuthorization(for: .addOnly)")
+ expect(iosPlugin).toContain("options.uniformTypeIdentifier = UTType.png.identifier")
+ expect(iosPlugin).not.toContain("options.contentType")
+ expect(iosPlugin).not.toContain("fetchAssets")
+ expect(readPlugin("ios/Package.swift")).toContain("platforms: [.iOS(.v14)]")
+ })
+
+ it("preserves Web and desktop routes while mobile uses only its typed adapter", () => {
+ const dialog = readRoot(
+ "src/web/src/components/community/messages/message-share-dialog.tsx",
+ )
+ const adapter = readRoot("src/web/src/lib/community/mobile-share-image.ts")
+ expect(dialog).toContain("const mobileNative = isTauri() && isMobile()")
+ expect(dialog).toContain("if (isTauri() && isDesktop())")
+ expect(dialog).toContain("navigator.clipboard.write")
+ expect(dialog).toContain("anchor.download = filename")
+ expect(dialog).toContain('await import("@/lib/community/mobile-share-image")')
+ expect(dialog).not.toMatch(/^import .*mobile-share-image/m)
+ expect(adapter).toContain('"mobile_share_image_copy"')
+ expect(adapter).toContain('"mobile_share_image_save"')
+ expect(adapter).not.toContain("setInterval")
+ expect(adapter).not.toContain("heartbeat")
+ })
+})
diff --git a/scripts/ci/native-oauth-desktop.test.ts b/scripts/ci/native-oauth-desktop.test.ts
index 7c25ef019..8b6fb1014 100644
--- a/scripts/ci/native-oauth-desktop.test.ts
+++ b/scripts/ci/native-oauth-desktop.test.ts
@@ -54,10 +54,13 @@ describe("desktop native OAuth security configuration", () => {
expect(source).toContain("WindowEvent::Destroyed")
expect(source).toContain("tauri::WindowEvent::Focused(true)")
expect(source).not.toContain("tauri::RunEvent::Resumed")
- expect(runtime).toContain('label == "main"')
- expect(runtime).toContain("url.origin().ascii_serialization() == expected")
- expect(runtime).toContain("url.username().is_empty()")
- expect(runtime).toContain("url.password().is_none()")
- expect(runtime).toContain("commands_require_main_and_exact_build_origin")
+ expect(runtime).toContain("use crate::native_command_guard::guard;")
+ expect(runtime).not.toContain('label == "main"')
+ const guard = read("src/native_command_guard.rs")
+ expect(guard).toContain('label == "main"')
+ expect(guard).toContain("url.origin().ascii_serialization() == expected")
+ expect(guard).toContain("url.username().is_empty()")
+ expect(guard).toContain("url.password().is_none()")
+ expect(guard).toContain("accepts_only_the_main_window_and_exact_origin")
})
})
diff --git a/scripts/ci/native-oauth-mobile.test.ts b/scripts/ci/native-oauth-mobile.test.ts
index 9de66dd89..345664ff2 100644
--- a/scripts/ci/native-oauth-mobile.test.ts
+++ b/scripts/ci/native-oauth-mobile.test.ts
@@ -51,6 +51,8 @@ const iosEntitlements = readTauri(
const iosProject = readTauri("gen/apple/project.yml")
const cargo = readTauri("Cargo.toml")
const rustEntry = readTauri("src/lib.rs")
+const oauthRuntime = readTauri("src/native_oauth_runtime.rs")
+const nativeCommandGuard = readTauri("src/native_command_guard.rs")
const mobileRelease = readRoot(".github/workflows/mobile-release.yml")
const desktopPackage = JSON.parse(readRoot("src/desktop/package.json")) as {
scripts: Record<string, string>
@@ -134,6 +136,10 @@ describe("native OAuth mobile activation", () => {
expect(rustEntry).toContain("fn run_mobile(")
expect(rustEntry).toContain("native_oauth_runtime::native_oauth_prepare")
expect(rustEntry).toContain("native_oauth_runtime::setup(app.handle())")
+ expect(oauthRuntime).toContain("use crate::native_command_guard::guard;")
+ expect(nativeCommandGuard).toContain('label == "main"')
+ expect(nativeCommandGuard).toContain('"http://localhost:3000"')
+ expect(nativeCommandGuard).toContain('"https://alook.ai"')
expect(rustEntry.indexOf("tauri_plugin_single_instance::init")).toBeLessThan(
rustEntry.indexOf("tauri_plugin_deep_link::init"),
)
diff --git a/scripts/ci/workflow-contract.test.ts b/scripts/ci/workflow-contract.test.ts
index 230504352..0d3c53867 100644
--- a/scripts/ci/workflow-contract.test.ts
+++ b/scripts/ci/workflow-contract.test.ts
@@ -1128,6 +1128,13 @@ describe("Desktop image clipboard", () => {
"desktop-capability",
"external-links",
expect.objectContaining({ identifier: "native-oauth-dev", local: true, remote: { urls: ["http://localhost:3000"] }, permissions: ["native-oauth"] }),
+ expect.objectContaining({
+ identifier: "mobile-share-image-dev",
+ local: true,
+ platforms: ["android", "iOS"],
+ remote: { urls: ["http://localhost:3000"] },
+ permissions: ["allow-mobile-share-image-copy", "allow-mobile-share-image-save"],
+ }),
])
})
})
diff --git a/src/desktop/src-tauri/Cargo.lock b/src/desktop/src-tauri/Cargo.lock
index 2701349a3..f6e2aed6e 100644
--- a/src/desktop/src-tauri/Cargo.lock
+++ b/src/desktop/src-tauri/Cargo.lock
@@ -43,6 +43,7 @@ dependencies = [
"objc2-app-kit",
"objc2-foundation",
"objc2-web-kit",
+ "png 0.18.1",
"serde",
"serde_json",
"sha2",
@@ -52,12 +53,14 @@ dependencies = [
"tauri-plugin-clipboard-manager",
"tauri-plugin-deep-link",
"tauri-plugin-dialog",
+ "tauri-plugin-mobile-share-image",
"tauri-plugin-notification",
"tauri-plugin-opener",
"tauri-plugin-single-instance",
"tauri-plugin-store",
"tauri-plugin-updater",
"tokio",
+ "unicode-normalization",
"url",
"webkit2gtk",
"webview2-com",
@@ -4166,6 +4169,16 @@ dependencies = [
"url",
]
+[[package]]
+name = "tauri-plugin-mobile-share-image"
+version = "0.1.0"
+dependencies = [
+ "serde",
+ "tauri",
+ "tauri-plugin",
+ "thiserror 2.0.18",
+]
+
[[package]]
name = "tauri-plugin-notification"
version = "2.3.3"
@@ -4881,6 +4894,15 @@ version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+[[package]]
+name = "unicode-normalization"
+version = "0.1.25"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"
+dependencies = [
+ "tinyvec",
+]
+
[[package]]
name = "unicode-segmentation"
version = "1.13.3"
diff --git a/src/desktop/src-tauri/Cargo.toml b/src/desktop/src-tauri/Cargo.toml
index 6b23c4315..3dff632dd 100644
--- a/src/desktop/src-tauri/Cargo.toml
+++ b/src/desktop/src-tauri/Cargo.toml
@@ -20,10 +20,15 @@ tauri-plugin-deep-link = "2"
tauri-plugin-store = "2"
base64 = "0.22"
getrandom = "0.3"
+png = "0.18"
sha2 = "0.10"
subtle = "2"
+unicode-normalization = "0.1"
url = "2"
+[target."cfg(any(target_os = \"android\", target_os = \"ios\"))".dependencies]
+tauri-plugin-mobile-share-image = { path = "plugins/mobile-share-image" }
+
[target."cfg(not(any(target_os = \"android\", target_os = \"ios\")))".dependencies]
tauri-plugin-notification = "2"
tauri-plugin-updater = "2"
diff --git a/src/desktop/src-tauri/build.rs b/src/desktop/src-tauri/build.rs
index 505217d0f..7fa4393ea 100644
--- a/src/desktop/src-tauri/build.rs
+++ b/src/desktop/src-tauri/build.rs
@@ -6,6 +6,8 @@ fn main() {
"set_window_theme",
"close_splashscreen",
"desktop_zoom_shortcut",
+ "mobile_share_image_copy",
+ "mobile_share_image_save",
"native_oauth_snapshot",
"native_oauth_listen",
"native_oauth_unlisten",
diff --git a/src/desktop/src-tauri/capabilities/mobile-share-image-mobile.json b/src/desktop/src-tauri/capabilities/mobile-share-image-mobile.json
new file mode 100644
index 000000000..ca044e727
--- /dev/null
+++ b/src/desktop/src-tauri/capabilities/mobile-share-image-mobile.json
@@ -0,0 +1,22 @@
+{
+ "$schema": "../gen/schemas/mobile-schema.json",
+ "identifier": "mobile-share-image-mobile",
+ "description": "Native mobile image copy and save for the trusted main WebView",
+ "windows": [
+ "main"
+ ],
+ "platforms": [
+ "android",
+ "iOS"
+ ],
+ "local": false,
+ "remote": {
+ "urls": [
+ "https://alook.ai"
+ ]
+ },
+ "permissions": [
+ "allow-mobile-share-image-copy",
+ "allow-mobile-share-image-save"
+ ]
+}
diff --git a/src/desktop/src-tauri/gen/android/app/src/main/AndroidManifest.xml b/src/desktop/src-tauri/gen/android/app/src/main/AndroidManifest.xml
index f064576bf..92f110be3 100644
--- a/src/desktop/src-tauri/gen/android/app/src/main/AndroidManifest.xml
+++ b/src/desktop/src-tauri/gen/android/app/src/main/AndroidManifest.xml
@@ -48,14 +48,5 @@
<!-- DEEP LINK PLUGIN. AUTO-GENERATED. DO NOT REMOVE. -->
</activity>
- <provider
- android:name="androidx.core.content.FileProvider"
- android:authorities="${applicationId}.fileprovider"
- android:exported="false"
- android:grantUriPermissions="true">
- <meta-data
- android:name="android.support.FILE_PROVIDER_PATHS"
- android:resource="@xml/file_paths" />
- </provider>
</application>
</manifest>
diff --git a/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/MainActivity.kt b/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/MainActivity.kt
index abff9ae5b..7f9a799d1 100644
--- a/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/MainActivity.kt
+++ b/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/MainActivity.kt
@@ -16,9 +16,11 @@ import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.webkit.WebViewCompat
import androidx.webkit.WebViewFeature
+import ai.alook.plugin.mobileshareimage.MobileShareImageDocumentOwner
class MainActivity : TauriActivity() {
private var isReady = false
+ private val mobileShareImageDocumentOwner = MobileShareImageDocumentOwner(this)
companion object {
const val COLOR_LIGHT = "#FFFFFF"
@@ -46,6 +48,7 @@ class MainActivity : TauriActivity() {
val splashScreen = installSplashScreen()
enableEdgeToEdge()
super.onCreate(savedInstanceState)
+ mobileShareImageDocumentOwner.attach(savedInstanceState)
splashScreen.setKeepOnScreenCondition { !isReady }
@@ -72,6 +75,16 @@ class MainActivity : TauriActivity() {
}
}
+ override fun onSaveInstanceState(outState: Bundle) {
+ mobileShareImageDocumentOwner.saveState(outState)
+ super.onSaveInstanceState(outState)
+ }
+
+ override fun onDestroy() {
+ mobileShareImageDocumentOwner.detach()
+ super.onDestroy()
+ }
+
override fun onWebViewCreate(webView: WebView) {
super.onWebViewCreate(webView)
webView.addJavascriptInterface(ThemeBridge(this), "AlookNative")
diff --git a/src/desktop/src-tauri/gen/apple/project.yml b/src/desktop/src-tauri/gen/apple/project.yml
index b241f119e..72972fe43 100644
--- a/src/desktop/src-tauri/gen/apple/project.yml
+++ b/src/desktop/src-tauri/gen/apple/project.yml
@@ -53,6 +53,7 @@ targets:
- UIInterfaceOrientationLandscapeRight
CFBundleShortVersionString: 0.1.36
CFBundleVersion: "1"
+ NSPhotoLibraryAddUsageDescription: Allow Alook to save shared message images to Photos.
CFBundleURLTypes:
- CFBundleURLName: ai.alook
CFBundleURLSchemes: [ai.alook]
diff --git a/src/desktop/src-tauri/plugins/mobile-share-image/.gitignore b/src/desktop/src-tauri/plugins/mobile-share-image/.gitignore
new file mode 100644
index 000000000..282bca8b9
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/mobile-share-image/.gitignore
@@ -0,0 +1,6 @@
+/.tauri
+/android/.tauri
+/android/build
+/ios/.build
+/ios/.swiftpm
+/ios/Package.resolved
diff --git a/src/desktop/src-tauri/plugins/mobile-share-image/Cargo.toml b/src/desktop/src-tauri/plugins/mobile-share-image/Cargo.toml
new file mode 100644
index 000000000..e7cc362bb
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/mobile-share-image/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "tauri-plugin-mobile-share-image"
+version = "0.1.0"
+edition = "2021"
+links = "tauri-plugin-mobile-share-image"
+
+[build-dependencies]
+tauri-plugin = { version = "2", features = ["build"] }
+
+[dependencies]
+serde = { version = "1", features = ["derive"] }
+tauri = { version = "=2.11.2", default-features = false }
+thiserror = "2"
+
+[target.'cfg(target_os = "ios")'.dependencies]
+tauri = { version = "=2.11.2", features = ["wry"], default-features = false }
diff --git a/src/desktop/src-tauri/plugins/mobile-share-image/android/build.gradle.kts b/src/desktop/src-tauri/plugins/mobile-share-image/android/build.gradle.kts
new file mode 100644
index 000000000..26b5a5f85
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/mobile-share-image/android/build.gradle.kts
@@ -0,0 +1,35 @@
+plugins {
+ id("com.android.library")
+ id("org.jetbrains.kotlin.android")
+}
+
+android {
+ namespace = "ai.alook.plugin.mobileshareimage"
+ compileSdk = 36
+
+ defaultConfig {
+ minSdk = 24
+ testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
+ consumerProguardFiles("proguard-rules.pro")
+ }
+
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_1_8
+ targetCompatibility = JavaVersion.VERSION_1_8
+ }
+ kotlinOptions {
+ jvmTarget = "1.8"
+ }
+}
+
+dependencies {
+ implementation("androidx.core:core-ktx:1.9.0")
+ implementation("androidx.appcompat:appcompat:1.7.1")
+ implementation("androidx.activity:activity-ktx:1.10.1")
+ implementation("com.fasterxml.jackson.core:jackson-databind:2.15.3")
+ implementation(project(":tauri-android"))
+ testImplementation("junit:junit:4.13.2")
+ androidTestImplementation("androidx.test:core:1.5.0")
+ androidTestImplementation("androidx.test:runner:1.5.2")
+ androidTestImplementation("androidx.test.ext:junit:1.1.4")
+}
diff --git a/src/desktop/src-tauri/plugins/mobile-share-image/android/proguard-rules.pro b/src/desktop/src-tauri/plugins/mobile-share-image/android/proguard-rules.pro
new file mode 100644
index 000000000..9434aa9dd
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/mobile-share-image/android/proguard-rules.pro
@@ -0,0 +1 @@
+-keep class ai.alook.plugin.mobileshareimage.** { *; }
diff --git a/src/desktop/src-tauri/plugins/mobile-share-image/android/settings.gradle b/src/desktop/src-tauri/plugins/mobile-share-image/android/settings.gradle
new file mode 100644
index 000000000..14a752e43
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/mobile-share-image/android/settings.gradle
@@ -0,0 +1,2 @@
+include ':tauri-android'
+project(':tauri-android').projectDir = new File('./.tauri/tauri-api')
diff --git a/src/desktop/src-tauri/plugins/mobile-share-image/android/src/androidTest/java/ai/alook/plugin/mobileshareimage/MobileShareImageIntegrationTest.kt b/src/desktop/src-tauri/plugins/mobile-share-image/android/src/androidTest/java/ai/alook/plugin/mobileshareimage/MobileShareImageIntegrationTest.kt
new file mode 100644
index 000000000..1b1113e5c
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/mobile-share-image/android/src/androidTest/java/ai/alook/plugin/mobileshareimage/MobileShareImageIntegrationTest.kt
@@ -0,0 +1,168 @@
+package ai.alook.plugin.mobileshareimage
+
+import android.content.ContentValues
+import android.content.Context
+import android.net.Uri
+import android.os.Build
+import android.provider.MediaStore
+import androidx.core.content.FileProvider
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import java.io.File
+import java.util.UUID
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@RunWith(AndroidJUnit4::class)
+class MobileShareImageIntegrationTest {
+ private val context = ApplicationProvider.getApplicationContext<Context>()
+ private val insertedUris = mutableListOf<Uri>()
+
+ @After
+ fun cleanUp() {
+ insertedUris.forEach { uri -> runCatching { context.contentResolver.delete(uri, null, null) } }
+ context.getSharedPreferences("mobile-share-image-journal", Context.MODE_PRIVATE)
+ .edit()
+ .clear()
+ .commit()
+ File(context.cacheDir, "mobile-share-image").deleteRecursively()
+ }
+
+ @Test
+ fun fileProviderExposesOnlyClipboardStagingDirectory() {
+ val authority = "${context.packageName}.mobile_share_image.fileprovider"
+ val allowed = File(context.cacheDir, "mobile-share-image/clipboard/allowed.png")
+ assertTrue(allowed.parentFile!!.mkdirs() || allowed.parentFile!!.isDirectory)
+ allowed.writeBytes(byteArrayOf(1))
+
+ val allowedUri = FileProvider.getUriForFile(context, authority, allowed)
+ assertEquals(authority, allowedUri.authority)
+
+ val outside = File(context.cacheDir, "outside.png").apply { writeBytes(byteArrayOf(1)) }
+ assertProviderRejects(authority, outside)
+ val traversal = File(allowed.parentFile, "../outside.png")
+ assertProviderRejects(authority, traversal)
+ context.getExternalFilesDir(null)?.let { external ->
+ assertProviderRejects(
+ authority,
+ File(external, "external.png").apply { writeBytes(byteArrayOf(1)) },
+ )
+ }
+ }
+
+ @Test
+ fun repairDeletesOnlyTheExactOwnedPendingMediaStoreRow() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return
+ val row = insertPendingRow()
+ val prefs = writeJournal(row, includeUri = true)
+
+ assertTrue(MobileShareImage.repairJournal(context))
+ assertFalse(prefs.contains("token"))
+ assertFalse(rowExists(row.uri))
+ insertedUris.remove(row.uri)
+ }
+
+ @Test
+ fun repairFindsTheExactPendingRowWhenProcessDiesBeforeUriCommit() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return
+ val row = insertPendingRow()
+ val prefs = writeJournal(row, includeUri = false)
+
+ assertTrue(MobileShareImage.repairJournal(context))
+ assertFalse(prefs.contains("token"))
+ assertFalse(rowExists(row.uri))
+ insertedUris.remove(row.uri)
+ }
+
+ @Test
+ fun repairClearsPublishedJournalWithoutDeletingTheImage() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return
+ val row = insertPendingRow()
+ assertEquals(
+ 1,
+ context.contentResolver.update(
+ row.uri,
+ ContentValues().apply { put(MediaStore.Images.Media.IS_PENDING, 0) },
+ null,
+ null,
+ ),
+ )
+ val prefs = writeJournal(row, includeUri = true)
+
+ assertTrue(MobileShareImage.repairJournal(context))
+ assertFalse(prefs.contains("token"))
+ assertTrue(rowExists(row.uri))
+ }
+
+ @Test
+ fun preparedJournalNeverDeletesAnUnrelatedPendingRow() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return
+ val unrelated = insertPendingRow()
+ val missing = JournalRow(
+ token = UUID.randomUUID().toString().replace("-", ""),
+ name = "",
+ createdAt = System.currentTimeMillis(),
+ uri = unrelated.uri,
+ ).let { it.copy(name = "alook-message-share-${it.token}.png") }
+ val prefs = writeJournal(missing, includeUri = false)
+
+ assertTrue(MobileShareImage.repairJournal(context))
+ assertFalse(prefs.contains("token"))
+ assertTrue(rowExists(unrelated.uri))
+ }
+
+ private data class JournalRow(
+ val token: String,
+ val name: String,
+ val createdAt: Long,
+ val uri: Uri,
+ )
+
+ private fun insertPendingRow(): JournalRow {
+ val token = UUID.randomUUID().toString().replace("-", "")
+ val name = "alook-message-share-$token.png"
+ val createdAt = System.currentTimeMillis()
+ val uri = context.contentResolver.insert(
+ MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY),
+ ContentValues().apply {
+ put(MediaStore.Images.Media.DISPLAY_NAME, name)
+ put(MediaStore.Images.Media.MIME_TYPE, "image/png")
+ put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/Alook/")
+ put(MediaStore.Images.Media.IS_PENDING, 1)
+ },
+ ) ?: error("MediaStore did not create the pending test row")
+ insertedUris += uri
+ context.contentResolver.openOutputStream(uri, "w")!!.use { it.write(byteArrayOf(1, 2, 3)) }
+ return JournalRow(token, name, createdAt, uri)
+ }
+
+ private fun writeJournal(row: JournalRow, includeUri: Boolean) =
+ context.getSharedPreferences("mobile-share-image-journal", Context.MODE_PRIVATE).also { prefs ->
+ val editor = prefs.edit()
+ .putString("token", row.token)
+ .putString("displayName", row.name)
+ .putString("relativePath", "Pictures/Alook/")
+ .putLong("createdAt", row.createdAt)
+ if (includeUri) editor.putString("uri", row.uri.toString()) else editor.remove("uri")
+ assertTrue(editor.commit())
+ }
+
+ private fun assertProviderRejects(authority: String, file: File) {
+ var rejected = false
+ try {
+ FileProvider.getUriForFile(context, authority, file)
+ } catch (_: IllegalArgumentException) {
+ rejected = true
+ }
+ assertTrue("FileProvider must reject ${file.path}", rejected)
+ }
+
+ private fun rowExists(uri: Uri): Boolean =
+ context.contentResolver.query(uri, arrayOf(MediaStore.Images.Media._ID), null, null, null)
+ ?.use { it.moveToFirst() }
+ ?: false
+}
diff --git a/src/desktop/src-tauri/plugins/mobile-share-image/android/src/main/AndroidManifest.xml b/src/desktop/src-tauri/plugins/mobile-share-image/android/src/main/AndroidManifest.xml
new file mode 100644
index 000000000..429505a7c
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/mobile-share-image/android/src/main/AndroidManifest.xml
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+ <application>
+ <provider
+ android:name="ai.alook.plugin.mobileshareimage.MobileShareImageFileProvider"
+ android:authorities="${applicationId}.mobile_share_image.fileprovider"
+ android:exported="false"
+ android:grantUriPermissions="true">
+ <meta-data
+ android:name="android.support.FILE_PROVIDER_PATHS"
+ android:resource="@xml/mobile_share_image_file_paths" />
+ </provider>
+ </application>
+</manifest>
diff --git a/src/desktop/src-tauri/plugins/mobile-share-image/android/src/main/java/ai/alook/plugin/mobileshareimage/MobileShareImage.kt b/src/desktop/src-tauri/plugins/mobile-share-image/android/src/main/java/ai/alook/plugin/mobileshareimage/MobileShareImage.kt
new file mode 100644
index 000000000..19ac37718
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/mobile-share-image/android/src/main/java/ai/alook/plugin/mobileshareimage/MobileShareImage.kt
@@ -0,0 +1,522 @@
+package ai.alook.plugin.mobileshareimage
+
+import android.content.ContentResolver
+import android.content.ContentUris
+import android.content.ContentValues
+import android.content.Context
+import android.content.SharedPreferences
+import android.database.Cursor
+import android.graphics.BitmapFactory
+import android.net.Uri
+import android.os.Build
+import android.os.Bundle
+import android.provider.MediaStore
+import android.util.Base64
+import app.tauri.plugin.Invoke
+import app.tauri.plugin.JSObject
+import java.io.File
+import java.io.FileOutputStream
+import java.nio.ByteBuffer
+import java.nio.ByteOrder
+import java.text.Normalizer
+import java.util.UUID
+import java.util.concurrent.atomic.AtomicBoolean
+import java.util.zip.CRC32
+
+internal object MobileShareImage {
+ const val MAX_PNG_BYTES = 10 * 1024 * 1024
+ private const val MAX_DIMENSION = 16_384
+ private const val MAX_PIXELS = 16_777_216L
+ private const val MAX_OUTPUT_BYTES = 64L * 1024L * 1024L
+ private const val JOURNAL = "mobile-share-image-journal"
+ private const val RELATIVE_PATH = "Pictures/Alook/"
+ private const val MEDIA_NAME_PREFIX = "alook-message-share-"
+
+ fun validateAttemptId(value: String) {
+ val canonical = runCatching { UUID.fromString(value).toString() }.getOrNull()
+ if (canonical != value || value[14] != '4' || value[19] !in setOf('8', '9', 'a', 'b')) {
+ throw MobileShareImageFailure("invalid_png", "Invalid attempt identifier")
+ }
+ }
+
+ fun validateBase64(value: String): ByteArray {
+ val maxEncoded = ((MAX_PNG_BYTES + 2) / 3) * 4
+ if (value.isEmpty() || value.length % 4 != 0 || value.length > maxEncoded) {
+ throw MobileShareImageFailure(
+ if (value.length > maxEncoded) "image_too_large" else "invalid_png",
+ "Image payload is invalid",
+ )
+ }
+ if (value.any { it !in 'A'..'Z' && it !in 'a'..'z' && it !in '0'..'9' && it != '+' && it != '/' && it != '=' }) {
+ throw MobileShareImageFailure("invalid_png", "Image payload is not valid base64")
+ }
+ val decoded = try {
+ Base64.decode(value, Base64.NO_WRAP)
+ } catch (_: IllegalArgumentException) {
+ throw MobileShareImageFailure("invalid_png", "Image payload is not valid base64")
+ }
+ if (decoded.isEmpty()) throw MobileShareImageFailure("invalid_png", "Image payload is empty")
+ if (decoded.size > MAX_PNG_BYTES) {
+ throw MobileShareImageFailure("image_too_large", "Image exceeds the mobile limit")
+ }
+ if (Base64.encodeToString(decoded, Base64.NO_WRAP) != value) {
+ throw MobileShareImageFailure("invalid_png", "Image payload is not canonical base64")
+ }
+ validatePng(decoded)
+ return decoded
+ }
+
+ fun sanitizeFilename(value: String): String {
+ val normalized = Normalizer.normalize(value, Normalizer.Form.NFC)
+ val basename = normalized.split('/', '\\').lastOrNull().orEmpty()
+ .dropWhile { it == '.' || it.isWhitespace() }
+ var stem = basename.filter { !it.isISOControl() && it != '/' && it != '\\' }.trim()
+ while (stem.lowercase().endsWith(".png")) stem = stem.dropLast(4)
+ if (stem.isBlank()) stem = "alook-message-share"
+ while ((stem + ".png").toByteArray(Charsets.UTF_8).size > 180) {
+ stem = stem.substring(0, stem.offsetByCodePoints(stem.length, -1))
+ }
+ return if (stem.isBlank()) "alook-message-share.png" else "$stem.png"
+ }
+
+ fun save(context: Context, bytes: ByteArray, attemptId: String): String {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
+ throw MobileShareImageFailure("unavailable", "MediaStore requires Android 10")
+ }
+ if (!repairJournal(context)) {
+ throw MobileShareImageFailure("write_failed", "A previous image save could not be repaired")
+ }
+
+ val resolver = context.contentResolver
+ val token = UUID.randomUUID().toString().replace("-", "")
+ val displayName = "$MEDIA_NAME_PREFIX$token.png"
+ val createdAt = System.currentTimeMillis()
+ val prefs = context.getSharedPreferences(JOURNAL, Context.MODE_PRIVATE)
+ if (!prefs.edit()
+ .putString("token", token)
+ .putString("displayName", displayName)
+ .putString("relativePath", RELATIVE_PATH)
+ .putLong("createdAt", createdAt)
+ .remove("uri")
+ .commit()
+ ) {
+ throw MobileShareImageFailure("write_failed", "Could not prepare image save")
+ }
+
+ val values = ContentValues().apply {
+ put(MediaStore.Images.Media.DISPLAY_NAME, displayName)
+ put(MediaStore.Images.Media.MIME_TYPE, "image/png")
+ put(MediaStore.Images.Media.RELATIVE_PATH, RELATIVE_PATH)
+ put(MediaStore.Images.Media.IS_PENDING, 1)
+ }
+ val collection = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
+ val uri = try {
+ resolver.insert(collection, values)
+ } catch (error: Exception) {
+ throw MobileShareImageFailure("write_failed", error.message ?: "Could not create image row")
+ } ?: throw MobileShareImageFailure("write_failed", "Could not create image row")
+
+ if (!prefs.edit().putString("uri", uri.toString()).commit()) {
+ cleanupInsertedRow(context, uri, prefs)
+ throw MobileShareImageFailure("write_failed", "Could not record image row")
+ }
+
+ try {
+ resolver.openOutputStream(uri, "w")?.use { stream ->
+ stream.write(bytes)
+ stream.flush()
+ } ?: throw MobileShareImageFailure("write_failed", "Could not open image destination")
+ val published = resolver.update(
+ uri,
+ ContentValues().apply { put(MediaStore.Images.Media.IS_PENDING, 0) },
+ null,
+ null,
+ )
+ if (published != 1) throw MobileShareImageFailure("write_failed", "Could not publish image")
+ } catch (error: Exception) {
+ cleanupInsertedRow(context, uri, prefs)
+ if (error is MobileShareImageFailure) throw error
+ throw MobileShareImageFailure("write_failed", error.message ?: "Could not save image")
+ }
+
+ // The row is already durably public. If this clear fails, the next exact repair
+ // recognizes that fact and clears the journal without deleting the image.
+ prefs.edit().clear().commit()
+ logNativeSettle(attemptId)
+ return "pictures"
+ }
+
+ fun stageClipboard(context: Context, bytes: ByteArray, token: String): File {
+ return stageClipboard(
+ File(context.cacheDir, "mobile-share-image/clipboard"),
+ bytes,
+ token,
+ )
+ }
+
+ internal fun stageClipboard(directory: File, bytes: ByteArray, token: String): File {
+ if (!directory.mkdirs() && !directory.isDirectory) {
+ throw MobileShareImageFailure("write_failed", "Could not prepare clipboard image")
+ }
+ cleanupClipboardTemporaries(directory)
+ val temporary = File(directory, "$token.tmp")
+ val final = File(directory, "$token.png")
+ try {
+ FileOutputStream(temporary).use { stream ->
+ stream.write(bytes)
+ stream.flush()
+ stream.fd.sync()
+ }
+ if (!temporary.renameTo(final)) {
+ throw MobileShareImageFailure("write_failed", "Could not publish clipboard image")
+ }
+ return final
+ } catch (error: Exception) {
+ temporary.delete()
+ final.delete()
+ if (error is MobileShareImageFailure) throw error
+ throw MobileShareImageFailure("write_failed", error.message ?: "Could not stage clipboard image")
+ }
+ }
+
+ fun cleanupClipboardAfterPublish(context: Context, published: File) {
+ cleanupClipboardAfterPublish(
+ File(context.cacheDir, "mobile-share-image/clipboard"),
+ published,
+ )
+ }
+
+ internal fun cleanupClipboardTemporaries(directory: File) {
+ directory.listFiles()?.forEach { candidate ->
+ if (candidate.isFile && candidate.extension == "tmp") candidate.delete()
+ }
+ }
+
+ internal fun cleanupClipboardAfterPublish(directory: File, published: File) {
+ directory.listFiles()?.forEach { candidate ->
+ if (candidate.isFile && candidate.extension == "png" && candidate != published) {
+ candidate.delete()
+ }
+ }
+ }
+
+ fun stageDocument(context: Context, bytes: ByteArray, token: String): File {
+ val directory = File(context.cacheDir, "mobile-share-image/document")
+ if (!directory.mkdirs() && !directory.isDirectory) {
+ throw MobileShareImageFailure("write_failed", "Could not prepare private image staging")
+ }
+ val temporary = File(directory, "$token.tmp")
+ val final = File(directory, "$token.png")
+ try {
+ FileOutputStream(temporary).use { stream ->
+ stream.write(bytes)
+ stream.flush()
+ stream.fd.sync()
+ }
+ if (!temporary.renameTo(final)) {
+ throw MobileShareImageFailure("write_failed", "Could not publish private image staging")
+ }
+ return final
+ } catch (error: Exception) {
+ temporary.delete()
+ final.delete()
+ if (error is MobileShareImageFailure) throw error
+ throw MobileShareImageFailure("write_failed", error.message ?: "Could not stage document image")
+ }
+ }
+
+ fun cleanupDocumentOrphans(context: Context) {
+ cleanupMobileShareImageDocumentOrphans(
+ File(context.cacheDir, "mobile-share-image/document"),
+ MobileShareImageCoordinator.liveToken(),
+ )
+ }
+
+ fun resolveSaved(invoke: Invoke, attemptId: String, destination: String) {
+ invoke.resolve(JSObject().apply {
+ put("attemptId", attemptId)
+ put("status", "saved")
+ put("destination", destination)
+ })
+ }
+
+ fun resolveCopied(invoke: Invoke, attemptId: String) {
+ invoke.resolve(JSObject().apply {
+ put("attemptId", attemptId)
+ put("status", "copied")
+ put("destination", "clipboard")
+ })
+ }
+
+ fun reject(invoke: Invoke, failure: MobileShareImageFailure) {
+ invoke.reject(failure.message, failure.code)
+ }
+
+ fun logNativeSettle(attemptId: String) {
+ android.util.Log.d(
+ "AlookMobileShareImage",
+ "native-settle attempt=$attemptId t=${android.os.SystemClock.elapsedRealtimeNanos()}",
+ )
+ }
+
+ private fun validatePng(bytes: ByteArray) {
+ val dimensions = validatePngStructure(bytes)
+ if (dimensions.width.toLong() * dimensions.height.toLong() * 4L > MAX_OUTPUT_BYTES) invalidPng()
+ val options = BitmapFactory.Options().apply { inJustDecodeBounds = true }
+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
+ if (options.outWidth != dimensions.width || options.outHeight != dimensions.height) invalidPng()
+ val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) ?: invalidPng()
+ bitmap.recycle()
+ }
+
+ internal data class PngDimensions(val width: Int, val height: Int)
+
+ internal fun validatePngStructure(bytes: ByteArray): PngDimensions {
+ val signature = byteArrayOf(-119, 80, 78, 71, 13, 10, 26, 10)
+ if (bytes.size < 8 || !bytes.copyOfRange(0, 8).contentEquals(signature)) invalidPng()
+ var offset = 8
+ var dimensions: PngDimensions? = null
+ var sawData = false
+ var sawEnd = false
+ while (offset < bytes.size) {
+ if (offset > bytes.size - 12) invalidPng()
+ val length = ByteBuffer.wrap(bytes, offset, 4).order(ByteOrder.BIG_ENDIAN).int
+ if (length < 0) invalidPng()
+ val dataStart = offset + 8
+ val dataEnd = dataStart.toLong() + length.toLong()
+ val chunkEnd = dataEnd + 4L
+ if (chunkEnd > bytes.size || sawEnd) invalidPng()
+ val type = bytes.copyOfRange(offset + 4, offset + 8).toString(Charsets.US_ASCII)
+ val crc = CRC32().apply { update(bytes, offset + 4, 4 + length) }.value
+ val stored = ByteBuffer.wrap(bytes, dataEnd.toInt(), 4)
+ .order(ByteOrder.BIG_ENDIAN).int.toLong() and 0xffffffffL
+ if (crc != stored) invalidPng()
+ when (type) {
+ "IHDR" -> {
+ if (dimensions != null || offset != 8 || length != 13) invalidPng()
+ val width = ByteBuffer.wrap(bytes, dataStart, 4).order(ByteOrder.BIG_ENDIAN).int
+ val height = ByteBuffer.wrap(bytes, dataStart + 4, 4).order(ByteOrder.BIG_ENDIAN).int
+ val pixels = width.toLong() * height.toLong()
+ if (width <= 0 || height <= 0 || width > MAX_DIMENSION || height > MAX_DIMENSION || pixels > MAX_PIXELS) invalidPng()
+ val bitDepth = bytes[dataStart + 8].toInt() and 0xff
+ val colorType = bytes[dataStart + 9].toInt() and 0xff
+ val legal = when (colorType) {
+ 0 -> bitDepth in setOf(1, 2, 4, 8, 16)
+ 2, 4, 6 -> bitDepth in setOf(8, 16)
+ 3 -> bitDepth in setOf(1, 2, 4, 8)
+ else -> false
+ }
+ if (!legal || bytes[dataStart + 10].toInt() != 0 || bytes[dataStart + 11].toInt() != 0 || (bytes[dataStart + 12].toInt() and 0xff) > 1) invalidPng()
+ dimensions = PngDimensions(width, height)
+ }
+ "IDAT" -> {
+ if (dimensions == null || sawEnd) invalidPng()
+ sawData = true
+ }
+ "IEND" -> {
+ if (dimensions == null || !sawData || length != 0 || chunkEnd.toInt() != bytes.size) invalidPng()
+ sawEnd = true
+ }
+ "acTL", "fcTL", "fdAT" -> invalidPng()
+ }
+ offset = chunkEnd.toInt()
+ }
+ if (!sawEnd) invalidPng()
+ return dimensions ?: invalidPng()
+ }
+
+ private fun invalidPng(): Nothing {
+ throw MobileShareImageFailure("invalid_png", "Image payload is not a valid PNG")
+ }
+
+ internal fun repairJournal(context: Context): Boolean {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return true
+ val prefs = context.getSharedPreferences(JOURNAL, Context.MODE_PRIVATE)
+ val token = prefs.getString("token", null) ?: return true
+ val expectedName = "$MEDIA_NAME_PREFIX$token.png"
+ val name = prefs.getString("displayName", null) ?: return false
+ val path = prefs.getString("relativePath", null) ?: return false
+ val createdAt = prefs.getLong("createdAt", 0)
+ if (!token.matches(Regex("[0-9a-f]{32}")) || name != expectedName || path != RELATIVE_PATH || createdAt <= 0) {
+ return false
+ }
+
+ val storedUri = prefs.getString("uri", null)?.let { runCatching { Uri.parse(it) }.getOrNull() }
+ val queried = if (storedUri != null) {
+ queryRows(context, pendingAwareUri(storedUri), null, null) { storedUri }
+ } else {
+ findPreparedRows(context, name, path, createdAt)
+ }
+ val rows = when (queried) {
+ QueryResult.Failed -> return false
+ is QueryResult.Rows -> queried.value
+ }
+ if (rows.size > 1) return false
+ if (rows.isEmpty()) return prefs.edit().clear().commit()
+
+ val row = rows.single()
+ if (!journalOwnsRow(context, row, token, name, path, createdAt)) return false
+ if (!row.pending) return prefs.edit().clear().commit()
+ val deleted = try {
+ context.contentResolver.delete(row.uri, null, null)
+ } catch (_: Exception) {
+ return false
+ }
+ return (deleted == 1 || (deleted == 0 && rowConfirmedMissing(context, row.uri))) &&
+ prefs.edit().clear().commit()
+ }
+
+ private fun journalOwnsRow(
+ context: Context,
+ row: JournalRow,
+ token: String,
+ name: String,
+ path: String,
+ createdAt: Long,
+ ): Boolean {
+ val createdFloor = createdAt / 1000L - 5L
+ val nowSeconds = System.currentTimeMillis() / 1000L
+ return row.owner == context.packageName &&
+ row.name == name &&
+ row.name == "$MEDIA_NAME_PREFIX$token.png" &&
+ row.path == path &&
+ row.path == RELATIVE_PATH &&
+ row.createdSeconds in createdFloor..nowSeconds
+ }
+
+ private fun cleanupInsertedRow(context: Context, uri: Uri, prefs: SharedPreferences) {
+ val deleted = try {
+ context.contentResolver.delete(uri, null, null)
+ } catch (_: Exception) {
+ return
+ }
+ if (deleted == 1 || (deleted == 0 && rowConfirmedMissing(context, uri))) {
+ prefs.edit().clear().commit()
+ }
+ }
+
+ private sealed interface QueryResult {
+ data object Failed : QueryResult
+ data class Rows(val value: List<JournalRow>) : QueryResult
+ }
+
+ private data class JournalRow(
+ val uri: Uri,
+ val owner: String,
+ val pending: Boolean,
+ val path: String,
+ val name: String,
+ val createdSeconds: Long,
+ )
+
+ private fun findPreparedRows(
+ context: Context,
+ name: String,
+ path: String,
+ createdAt: Long,
+ ): QueryResult {
+ val base = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
+ val uri = if (Build.VERSION.SDK_INT == Build.VERSION_CODES.Q) MediaStore.setIncludePending(base) else base
+ val selection = "${MediaStore.Images.Media.OWNER_PACKAGE_NAME} = ? AND " +
+ "${MediaStore.Images.Media.IS_PENDING} = ? AND " +
+ "${MediaStore.Images.Media.RELATIVE_PATH} = ? AND " +
+ "${MediaStore.Images.Media.DISPLAY_NAME} = ? AND " +
+ "${MediaStore.Images.Media.DATE_ADDED} BETWEEN ? AND ?"
+ val args = arrayOf(
+ context.packageName,
+ "1",
+ path,
+ name,
+ (createdAt / 1000L - 5L).toString(),
+ (System.currentTimeMillis() / 1000L).toString(),
+ )
+ return queryRows(context, uri, selection, args) { id -> ContentUris.withAppendedId(base, id) }
+ }
+
+ private fun queryRows(
+ context: Context,
+ uri: Uri,
+ selection: String?,
+ selectionArgs: Array<String>?,
+ rowUri: (Long) -> Uri,
+ ): QueryResult {
+ val columns = arrayOf(
+ MediaStore.Images.Media._ID,
+ MediaStore.Images.Media.OWNER_PACKAGE_NAME,
+ MediaStore.Images.Media.IS_PENDING,
+ MediaStore.Images.Media.RELATIVE_PATH,
+ MediaStore.Images.Media.DISPLAY_NAME,
+ MediaStore.Images.Media.DATE_ADDED,
+ )
+ val cursor = try {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ context.contentResolver.query(
+ uri,
+ columns,
+ Bundle().apply {
+ putInt(MediaStore.QUERY_ARG_MATCH_PENDING, MediaStore.MATCH_INCLUDE)
+ selection?.let { putString(ContentResolver.QUERY_ARG_SQL_SELECTION, it) }
+ selectionArgs?.let { putStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS, it) }
+ },
+ null,
+ )
+ } else {
+ context.contentResolver.query(uri, columns, selection, selectionArgs, null)
+ }
+ } catch (_: Exception) {
+ return QueryResult.Failed
+ } ?: return QueryResult.Failed
+
+ return try {
+ cursor.use { value ->
+ val rows = mutableListOf<JournalRow>()
+ while (value.moveToNext()) {
+ rows += value.toJournalRow(rowUri(value.getLong(0)))
+ if (rows.size > 1) break
+ }
+ QueryResult.Rows(rows)
+ }
+ } catch (_: Exception) {
+ QueryResult.Failed
+ }
+ }
+
+ private fun Cursor.toJournalRow(uri: Uri) = JournalRow(
+ uri = uri,
+ owner = getString(1),
+ pending = getInt(2) == 1,
+ path = getString(3),
+ name = getString(4),
+ createdSeconds = getLong(5),
+ )
+
+ private fun pendingAwareUri(uri: Uri): Uri =
+ if (Build.VERSION.SDK_INT == Build.VERSION_CODES.Q) MediaStore.setIncludePending(uri) else uri
+
+ private fun rowConfirmedMissing(context: Context, uri: Uri): Boolean =
+ when (val result = queryRows(context, pendingAwareUri(uri), null, null) { uri }) {
+ QueryResult.Failed -> false
+ is QueryResult.Rows -> result.value.isEmpty()
+ }
+}
+
+internal class MobileShareImageFailure(val code: String, override val message: String) : Exception(message)
+
+internal object MobileShareImageNativeFlight {
+ private val busy = AtomicBoolean(false)
+
+ fun acquire(): MobileShareImageNativeLease {
+ if (!busy.compareAndSet(false, true)) {
+ throw MobileShareImageFailure("busy", "Another image action is active")
+ }
+ return MobileShareImageNativeLease(busy)
+ }
+}
+
+internal class MobileShareImageNativeLease(private val busy: AtomicBoolean) {
+ private val closed = AtomicBoolean(false)
+
+ fun close() {
+ if (closed.compareAndSet(false, true)) busy.set(false)
+ }
+}
diff --git a/src/desktop/src-tauri/plugins/mobile-share-image/android/src/main/java/ai/alook/plugin/mobileshareimage/MobileShareImageClipboardTransaction.kt b/src/desktop/src-tauri/plugins/mobile-share-image/android/src/main/java/ai/alook/plugin/mobileshareimage/MobileShareImageClipboardTransaction.kt
new file mode 100644
index 000000000..c699ddc4e
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/mobile-share-image/android/src/main/java/ai/alook/plugin/mobileshareimage/MobileShareImageClipboardTransaction.kt
@@ -0,0 +1,62 @@
+package ai.alook.plugin.mobileshareimage
+
+internal fun commitMobileShareImageClipboard(
+ publish: () -> Unit,
+ cleanupAfterPublish: () -> Unit,
+ resolve: () -> Unit,
+ reject: (MobileShareImageFailure) -> Unit,
+ deleteUnpublished: () -> Unit,
+ release: () -> Unit,
+ reportFailure: (Exception) -> Unit = {},
+) {
+ try {
+ publish()
+ } catch (error: Exception) {
+ runCatching(deleteUnpublished).onFailure { failure ->
+ reportClipboardFailure(failure, reportFailure)
+ }
+ try {
+ reject(
+ if (error is MobileShareImageFailure) error
+ else MobileShareImageFailure(
+ "write_failed",
+ error.message ?: "Could not copy image",
+ ),
+ )
+ } catch (failure: Exception) {
+ reportClipboardFailure(failure, reportFailure)
+ } finally {
+ releaseClipboardLease(release, reportFailure)
+ }
+ return
+ }
+
+ runCatching(cleanupAfterPublish).onFailure { failure ->
+ reportClipboardFailure(failure, reportFailure)
+ }
+ try {
+ resolve()
+ } catch (failure: Exception) {
+ reportClipboardFailure(failure, reportFailure)
+ } finally {
+ releaseClipboardLease(release, reportFailure)
+ }
+}
+
+private fun releaseClipboardLease(
+ release: () -> Unit,
+ reportFailure: (Exception) -> Unit,
+) {
+ try {
+ release()
+ } catch (failure: Exception) {
+ reportClipboardFailure(failure, reportFailure)
+ }
+}
+
+private fun reportClipboardFailure(
+ failure: Throwable,
+ reportFailure: (Exception) -> Unit,
+) {
+ if (failure is Exception) runCatching { reportFailure(failure) }
+}
diff --git a/src/desktop/src-tauri/plugins/mobile-share-image/android/src/main/java/ai/alook/plugin/mobileshareimage/MobileShareImageDocumentCoordinatorCore.kt b/src/desktop/src-tauri/plugins/mobile-share-image/android/src/main/java/ai/alook/plugin/mobileshareimage/MobileShareImageDocumentCoordinatorCore.kt
new file mode 100644
index 000000000..982646227
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/mobile-share-image/android/src/main/java/ai/alook/plugin/mobileshareimage/MobileShareImageDocumentCoordinatorCore.kt
@@ -0,0 +1,350 @@
+package ai.alook.plugin.mobileshareimage
+
+import java.io.File
+
+internal enum class MobileShareImageDocumentPhase {
+ LAUNCHING,
+ WAITING,
+ WRITING,
+ TERMINAL,
+}
+
+internal enum class MobileShareImageDocumentDelivery {
+ ORPHAN,
+ STALE,
+ CANCEL,
+ WRITE,
+}
+
+internal fun classifyMobileShareImageDocumentDelivery(
+ currentToken: String?,
+ currentOwnerGeneration: String?,
+ currentPhase: MobileShareImageDocumentPhase?,
+ attachedOwnerGeneration: String?,
+ hasOwner: Boolean,
+ callbackToken: String,
+ callbackOwnerGeneration: String,
+ successfulSelection: Boolean,
+): MobileShareImageDocumentDelivery {
+ if (currentToken == null || currentToken != callbackToken) {
+ return MobileShareImageDocumentDelivery.ORPHAN
+ }
+ if (
+ currentOwnerGeneration != callbackOwnerGeneration ||
+ attachedOwnerGeneration != callbackOwnerGeneration ||
+ !hasOwner ||
+ currentPhase != MobileShareImageDocumentPhase.WAITING
+ ) {
+ return MobileShareImageDocumentDelivery.STALE
+ }
+ return if (successfulSelection) {
+ MobileShareImageDocumentDelivery.WRITE
+ } else {
+ MobileShareImageDocumentDelivery.CANCEL
+ }
+}
+
+internal fun interface MobileShareImageDocumentLauncher {
+ fun launch(token: String, filename: String)
+}
+
+internal interface MobileShareImageDocumentOutput {
+ fun writeFrom(staging: File)
+ fun flush()
+ fun close()
+}
+
+internal fun interface MobileShareImageDocumentDestination {
+ fun open(): MobileShareImageDocumentOutput
+}
+
+internal interface MobileShareImageDocumentTerminal {
+ fun resolve()
+ fun reject(failure: MobileShareImageFailure)
+}
+
+internal data class MobileShareImageDocumentRequest(
+ val attemptId: String,
+ val token: String,
+ val staging: File,
+ val filename: String,
+ val terminal: MobileShareImageDocumentTerminal,
+ val release: () -> Unit,
+)
+
+internal class MobileShareImageDocumentCoordinatorCore(
+ private val execute: ((() -> Unit) -> Unit),
+ private val deleteStaging: (File) -> Unit = { it.delete() },
+ private val reportFailure: (Exception) -> Unit = {},
+) {
+ private data class Owner(
+ val generation: String,
+ val launcher: MobileShareImageDocumentLauncher,
+ )
+
+ private data class PendingDocument(
+ val request: MobileShareImageDocumentRequest,
+ var phase: MobileShareImageDocumentPhase,
+ var ownerGeneration: String,
+ )
+
+ private val lock = Any()
+ private var owner: Owner? = null
+ private var pending: PendingDocument? = null
+
+ fun attach(
+ generation: String,
+ restoredToken: String?,
+ launcher: MobileShareImageDocumentLauncher,
+ ) {
+ synchronized(lock) {
+ owner = Owner(generation, launcher)
+ val active = pending
+ if (
+ active != null &&
+ restoredToken == active.request.token &&
+ active.phase != MobileShareImageDocumentPhase.TERMINAL
+ ) {
+ active.ownerGeneration = generation
+ }
+ }
+ }
+
+ fun detach(generation: String) {
+ synchronized(lock) {
+ if (owner?.generation == generation) owner = null
+ }
+ }
+
+ fun liveToken(): String? = synchronized(lock) { pending?.request?.token }
+
+ fun tokenForOwner(generation: String): String? = synchronized(lock) {
+ val active = pending ?: return@synchronized null
+ if (active.ownerGeneration == generation) active.request.token else null
+ }
+
+ fun begin(request: MobileShareImageDocumentRequest) {
+ val launchOwner = synchronized(lock) {
+ if (pending != null) {
+ throw MobileShareImageFailure("busy", "Another document save is active")
+ }
+ val attached = owner
+ ?: throw MobileShareImageFailure("unavailable", "Document picker is unavailable")
+ pending = PendingDocument(
+ request = request,
+ phase = MobileShareImageDocumentPhase.LAUNCHING,
+ ownerGeneration = attached.generation,
+ )
+ attached
+ }
+
+ try {
+ launchOwner.launcher.launch(request.token, request.filename)
+ } catch (error: Exception) {
+ val failed = synchronized(lock) {
+ val active = pending
+ if (
+ active?.request?.token == request.token &&
+ active.phase == MobileShareImageDocumentPhase.LAUNCHING
+ ) {
+ active.phase = MobileShareImageDocumentPhase.TERMINAL
+ pending = null
+ if (owner?.generation == active.ownerGeneration) owner = null
+ active
+ } else {
+ null
+ }
+ }
+ failed?.let {
+ settleFailure(
+ it,
+ MobileShareImageFailure(
+ "unavailable",
+ error.message ?: "Could not open document picker",
+ ),
+ )
+ }
+ return
+ }
+
+ synchronized(lock) {
+ val active = pending
+ if (
+ active?.request?.token == request.token &&
+ active.phase == MobileShareImageDocumentPhase.LAUNCHING
+ ) {
+ active.phase = MobileShareImageDocumentPhase.WAITING
+ }
+ }
+ }
+
+ fun deliver(
+ generation: String,
+ token: String?,
+ destination: MobileShareImageDocumentDestination?,
+ cleanupOrphan: (String) -> Unit,
+ ) {
+ if (token == null) return
+ val claim = synchronized(lock) {
+ val current = pending
+ when (
+ classifyMobileShareImageDocumentDelivery(
+ currentToken = current?.request?.token,
+ currentOwnerGeneration = current?.ownerGeneration,
+ currentPhase = current?.phase,
+ attachedOwnerGeneration = owner?.generation,
+ hasOwner = owner != null,
+ callbackToken = token,
+ callbackOwnerGeneration = generation,
+ successfulSelection = destination != null,
+ )
+ ) {
+ MobileShareImageDocumentDelivery.ORPHAN -> DeliveryClaim.Orphan
+ MobileShareImageDocumentDelivery.STALE -> DeliveryClaim.Stale
+ MobileShareImageDocumentDelivery.CANCEL -> {
+ current!!.phase = MobileShareImageDocumentPhase.TERMINAL
+ pending = null
+ DeliveryClaim.Active(current)
+ }
+ MobileShareImageDocumentDelivery.WRITE -> {
+ current!!.phase = MobileShareImageDocumentPhase.WRITING
+ DeliveryClaim.Active(current)
+ }
+ }
+ }
+
+ when (claim) {
+ DeliveryClaim.Orphan -> {
+ if (isValidNativeToken(token)) runCatching { cleanupOrphan(token) }
+ .onFailure(::report)
+ }
+ DeliveryClaim.Stale -> Unit
+ is DeliveryClaim.Active -> {
+ if (destination == null) {
+ settleFailure(
+ claim.pending,
+ MobileShareImageFailure("cancelled", "Document save was cancelled"),
+ )
+ } else {
+ try {
+ execute { writeAndSettle(claim.pending, destination) }
+ } catch (error: Exception) {
+ finishWrite(claim.pending, writeFailure(error, "Could not write selected document"))
+ }
+ }
+ }
+ }
+ }
+
+ private fun writeAndSettle(
+ active: PendingDocument,
+ destination: MobileShareImageDocumentDestination,
+ ) {
+ var output: MobileShareImageDocumentOutput? = null
+ var failure: MobileShareImageFailure? = null
+ try {
+ output = destination.open()
+ } catch (error: Exception) {
+ failure = writeFailure(error, "Could not open selected document")
+ }
+ if (failure == null) {
+ try {
+ output!!.writeFrom(active.request.staging)
+ } catch (error: Exception) {
+ failure = writeFailure(error, "Could not write selected document")
+ }
+ }
+ if (failure == null) {
+ try {
+ output!!.flush()
+ } catch (error: Exception) {
+ failure = writeFailure(error, "Could not flush selected document")
+ }
+ }
+ if (output != null) {
+ try {
+ output.close()
+ } catch (error: Exception) {
+ if (failure == null) {
+ failure = writeFailure(error, "Could not close selected document")
+ } else {
+ report(error)
+ }
+ }
+ }
+ finishWrite(active, failure)
+ }
+
+ private fun finishWrite(active: PendingDocument, failure: MobileShareImageFailure?) {
+ val terminal = synchronized(lock) {
+ val current = pending
+ if (current === active && current.phase == MobileShareImageDocumentPhase.WRITING) {
+ current.phase = MobileShareImageDocumentPhase.TERMINAL
+ pending = null
+ current
+ } else {
+ null
+ }
+ } ?: return
+
+ delete(terminal.request.staging)
+ try {
+ if (failure == null) terminal.request.terminal.resolve()
+ else terminal.request.terminal.reject(failure)
+ } catch (error: Exception) {
+ report(error)
+ } finally {
+ release(terminal.request)
+ }
+ }
+
+ private fun settleFailure(active: PendingDocument, failure: MobileShareImageFailure) {
+ delete(active.request.staging)
+ try {
+ active.request.terminal.reject(failure)
+ } catch (error: Exception) {
+ report(error)
+ } finally {
+ release(active.request)
+ }
+ }
+
+ private fun delete(file: File) {
+ try {
+ deleteStaging(file)
+ } catch (error: Exception) {
+ report(error)
+ }
+ }
+
+ private fun release(request: MobileShareImageDocumentRequest) {
+ try {
+ request.release()
+ } catch (error: Exception) {
+ report(error)
+ }
+ }
+
+ private fun report(error: Throwable) {
+ if (error is Exception) runCatching { reportFailure(error) }
+ }
+
+ private fun writeFailure(error: Exception, fallback: String): MobileShareImageFailure =
+ if (error is MobileShareImageFailure) error
+ else MobileShareImageFailure("write_failed", error.message ?: fallback)
+
+ private sealed interface DeliveryClaim {
+ data object Orphan : DeliveryClaim
+ data object Stale : DeliveryClaim
+ data class Active(val pending: PendingDocument) : DeliveryClaim
+ }
+}
+
+internal fun cleanupMobileShareImageDocumentOrphans(directory: File, liveToken: String?) {
+ directory.listFiles()?.forEach { file ->
+ if (liveToken == null || file.name != "$liveToken.png") file.delete()
+ }
+}
+
+private fun isValidNativeToken(token: String): Boolean =
+ token.length == 32 && token.all { it in '0'..'9' || it in 'a'..'f' }
diff --git a/src/desktop/src-tauri/plugins/mobile-share-image/android/src/main/java/ai/alook/plugin/mobileshareimage/MobileShareImageDocumentOwner.kt b/src/desktop/src-tauri/plugins/mobile-share-image/android/src/main/java/ai/alook/plugin/mobileshareimage/MobileShareImageDocumentOwner.kt
new file mode 100644
index 000000000..a2f3a2821
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/mobile-share-image/android/src/main/java/ai/alook/plugin/mobileshareimage/MobileShareImageDocumentOwner.kt
@@ -0,0 +1,181 @@
+package ai.alook.plugin.mobileshareimage
+
+import android.app.Activity
+import android.content.Intent
+import android.net.Uri
+import android.os.Bundle
+import androidx.activity.ComponentActivity
+import androidx.activity.result.ActivityResult
+import androidx.activity.result.contract.ActivityResultContracts
+import app.tauri.plugin.Invoke
+import java.io.File
+import java.io.FileInputStream
+import java.io.OutputStream
+import java.util.UUID
+import java.util.concurrent.Executors
+
+class MobileShareImageDocumentOwner(private val activity: ComponentActivity) {
+ private val generation = UUID.randomUUID().toString()
+ private var restoredToken: String? = null
+ private val resultAdapter = MobileShareImageDocumentResultAdapter<Intent, ActivityResult>(
+ register = { key, callback ->
+ val launcher = activity.activityResultRegistry.register(
+ key,
+ ActivityResultContracts.StartActivityForResult(),
+ callback,
+ )
+ object : MobileShareImageDocumentResultRegistration<Intent> {
+ override fun launch(input: Intent) {
+ launcher.launch(input)
+ }
+
+ override fun unregister() {
+ launcher.unregister()
+ }
+ }
+ },
+ createInput = { _, filename ->
+ Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
+ addCategory(Intent.CATEGORY_OPENABLE)
+ type = "image/png"
+ putExtra(Intent.EXTRA_TITLE, filename)
+ }
+ },
+ deliver = { token, result ->
+ MobileShareImageCoordinator.deliver(generation, token, result, activity)
+ if (restoredToken == token) restoredToken = null
+ },
+ )
+
+ fun attach(savedInstanceState: Bundle?) {
+ restoredToken = savedInstanceState?.getString(STATE_TOKEN)
+ MobileShareImageCoordinator.attach(this, generation, restoredToken)
+ resultAdapter.restore(restoredToken)
+ }
+
+ fun saveState(outState: Bundle) {
+ val token = MobileShareImageCoordinator.tokenForOwner(generation) ?: restoredToken
+ if (token != null) outState.putString(STATE_TOKEN, token)
+ }
+
+ fun detach() {
+ MobileShareImageCoordinator.detach(generation)
+ resultAdapter.detach()
+ }
+
+ internal fun launch(token: String, filename: String) {
+ restoredToken = token
+ try {
+ resultAdapter.launch(token, filename)
+ } catch (error: Exception) {
+ if (restoredToken == token) restoredToken = null
+ throw error
+ }
+ }
+
+ companion object {
+ private const val STATE_TOKEN = "alook.mobileShareImage.documentToken"
+ }
+}
+
+internal object MobileShareImageCoordinator {
+ private val executor = Executors.newSingleThreadExecutor()
+ private val core = MobileShareImageDocumentCoordinatorCore(
+ execute = { task -> executor.execute { task() } },
+ reportFailure = {
+ android.util.Log.w(
+ "AlookMobileShareImage",
+ "document coordinator post-terminal failure",
+ )
+ },
+ )
+
+ fun attach(nextOwner: MobileShareImageDocumentOwner, generation: String, restoredToken: String?) {
+ core.attach(generation, restoredToken) { token, filename ->
+ nextOwner.launch(token, filename)
+ }
+ }
+
+ fun detach(generation: String) {
+ core.detach(generation)
+ }
+
+ fun liveToken(): String? = core.liveToken()
+
+ fun tokenForOwner(generation: String): String? = core.tokenForOwner(generation)
+
+ fun begin(
+ attemptId: String,
+ token: String,
+ staging: File,
+ filename: String,
+ invoke: Invoke,
+ nativeLease: MobileShareImageNativeLease,
+ ) {
+ core.begin(
+ MobileShareImageDocumentRequest(
+ attemptId = attemptId,
+ token = token,
+ staging = staging,
+ filename = filename,
+ terminal = object : MobileShareImageDocumentTerminal {
+ override fun resolve() {
+ MobileShareImage.logNativeSettle(attemptId)
+ MobileShareImage.resolveSaved(invoke, attemptId, "document")
+ }
+
+ override fun reject(failure: MobileShareImageFailure) {
+ MobileShareImage.reject(invoke, failure)
+ }
+ },
+ release = nativeLease::close,
+ ),
+ )
+ }
+
+ fun deliver(generation: String, token: String?, result: ActivityResult, activity: Activity) {
+ val uri = result.data?.data
+ ?.takeIf { result.resultCode == Activity.RESULT_OK }
+ core.deliver(
+ generation = generation,
+ token = token,
+ destination = uri?.let { AndroidDocumentDestination(activity, it) },
+ cleanupOrphan = { orphanToken ->
+ File(
+ activity.cacheDir,
+ "mobile-share-image/document/$orphanToken.png",
+ ).delete()
+ },
+ )
+ }
+
+ private class AndroidDocumentDestination(
+ private val activity: Activity,
+ private val uri: Uri,
+ ) : MobileShareImageDocumentDestination {
+ override fun open(): MobileShareImageDocumentOutput {
+ val output = activity.contentResolver.openOutputStream(uri, "w")
+ ?: throw MobileShareImageFailure(
+ "write_failed",
+ "Could not open selected document",
+ )
+ return AndroidDocumentOutput(output)
+ }
+ }
+
+ private class AndroidDocumentOutput(
+ private val output: OutputStream,
+ ) : MobileShareImageDocumentOutput {
+ override fun writeFrom(staging: File) {
+ FileInputStream(staging).use { input -> input.copyTo(output) }
+ }
+
+ override fun flush() {
+ output.flush()
+ }
+
+ override fun close() {
+ output.close()
+ }
+ }
+}
diff --git a/src/desktop/src-tauri/plugins/mobile-share-image/android/src/main/java/ai/alook/plugin/mobileshareimage/MobileShareImageDocumentResultAdapter.kt b/src/desktop/src-tauri/plugins/mobile-share-image/android/src/main/java/ai/alook/plugin/mobileshareimage/MobileShareImageDocumentResultAdapter.kt
new file mode 100644
index 000000000..4c3ba46f0
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/mobile-share-image/android/src/main/java/ai/alook/plugin/mobileshareimage/MobileShareImageDocumentResultAdapter.kt
@@ -0,0 +1,88 @@
+package ai.alook.plugin.mobileshareimage
+
+internal interface MobileShareImageDocumentResultRegistration<Input> {
+ fun launch(input: Input)
+ fun unregister()
+}
+
+/**
+ * Binds every Activity Result callback to the native token that created its
+ * registry key. A callback must never recover identity from the coordinator's
+ * current pending request: a late result from request A could otherwise be
+ * mistaken for a later request B.
+ */
+internal class MobileShareImageDocumentResultAdapter<Input, Result>(
+ private val register: (
+ key: String,
+ callback: (Result) -> Unit,
+ ) -> MobileShareImageDocumentResultRegistration<Input>,
+ private val createInput: (token: String, filename: String) -> Input,
+ private val deliver: (token: String, result: Result) -> Unit,
+) {
+ private data class Binding<Input>(
+ var registration: MobileShareImageDocumentResultRegistration<Input>? = null,
+ var deliveredDuringRegistration: Boolean = false,
+ )
+
+ private val bindings = mutableMapOf<String, Binding<Input>>()
+
+ fun restore(token: String?) {
+ if (token != null) ensureRegistered(token)
+ }
+
+ fun launch(token: String, filename: String) {
+ val registration = ensureRegistered(token)
+ try {
+ registration.launch(createInput(token, filename))
+ } catch (error: Exception) {
+ remove(token, registration)
+ throw error
+ }
+ }
+
+ fun detach() {
+ val registrations = bindings.values.mapNotNull { it.registration }
+ bindings.clear()
+ registrations.forEach { registration -> runCatching { registration.unregister() } }
+ }
+
+ private fun ensureRegistered(token: String): MobileShareImageDocumentResultRegistration<Input> {
+ bindings[token]?.registration?.let { return it }
+ val binding = Binding<Input>()
+ bindings[token] = binding
+ val registration = try {
+ register(resultKey(token)) { result ->
+ try {
+ deliver(token, result)
+ } finally {
+ val current = bindings[token]
+ if (current === binding) {
+ bindings.remove(token)
+ val registered = binding.registration
+ if (registered == null) binding.deliveredDuringRegistration = true
+ else runCatching { registered.unregister() }
+ }
+ }
+ }
+ } catch (error: Exception) {
+ if (bindings[token] === binding) bindings.remove(token)
+ throw error
+ }
+ binding.registration = registration
+ if (binding.deliveredDuringRegistration) {
+ runCatching { registration.unregister() }
+ }
+ return registration
+ }
+
+ private fun remove(
+ token: String,
+ registration: MobileShareImageDocumentResultRegistration<Input>,
+ ) {
+ val current = bindings[token]
+ if (current?.registration === registration) bindings.remove(token)
+ runCatching { registration.unregister() }
+ }
+
+ private fun resultKey(token: String): String = "alook.mobileShareImage.document.$token"
+}
diff --git a/src/desktop/src-tauri/plugins/mobile-share-image/android/src/main/java/ai/alook/plugin/mobileshareimage/MobileShareImageFileProvider.kt b/src/desktop/src-tauri/plugins/mobile-share-image/android/src/main/java/ai/alook/plugin/mobileshareimage/MobileShareImageFileProvider.kt
new file mode 100644
index 000000000..dc09ea4ae
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/mobile-share-image/android/src/main/java/ai/alook/plugin/mobileshareimage/MobileShareImageFileProvider.kt
@@ -0,0 +1,5 @@
+package ai.alook.plugin.mobileshareimage
+
+import androidx.core.content.FileProvider
+
+class MobileShareImageFileProvider : FileProvider()
diff --git a/src/desktop/src-tauri/plugins/mobile-share-image/android/src/main/java/ai/alook/plugin/mobileshareimage/MobileShareImagePlugin.kt b/src/desktop/src-tauri/plugins/mobile-share-image/android/src/main/java/ai/alook/plugin/mobileshareimage/MobileShareImagePlugin.kt
new file mode 100644
index 000000000..d399542a8
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/mobile-share-image/android/src/main/java/ai/alook/plugin/mobileshareimage/MobileShareImagePlugin.kt
@@ -0,0 +1,173 @@
+package ai.alook.plugin.mobileshareimage
+
+import android.app.Activity
+import android.content.ClipData
+import android.content.ClipboardManager
+import android.content.Context
+import android.os.Build
+import androidx.core.content.FileProvider
+import app.tauri.annotation.Command
+import app.tauri.annotation.InvokeArg
+import app.tauri.annotation.TauriPlugin
+import app.tauri.plugin.Invoke
+import app.tauri.plugin.Plugin
+import java.io.File
+import java.util.UUID
+import java.util.concurrent.Executors
+
+@InvokeArg
+class SaveImageArgs {
+ lateinit var attemptId: String
+ lateinit var pngBase64: String
+ lateinit var filename: String
+}
+
+@InvokeArg
+class CopyImageArgs {
+ lateinit var attemptId: String
+ lateinit var pngBase64: String
+}
+
+@TauriPlugin
+class MobileShareImagePlugin(private val activity: Activity) : Plugin(activity) {
+ private val executor = Executors.newSingleThreadExecutor()
+ private val context = activity.applicationContext
+
+ init {
+ MobileShareImage.cleanupDocumentOrphans(context)
+ executor.execute {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ MobileShareImage.repairJournal(context)
+ }
+ }
+ }
+
+ @Command
+ fun copyImage(invoke: Invoke) {
+ val args = parse(invoke, CopyImageArgs::class.java) ?: return
+ val lease = acquire(invoke, args.attemptId) ?: return
+ logNativeReceive(args.attemptId)
+ executor.execute {
+ var staged: File? = null
+ try {
+ val bytes = MobileShareImage.validateBase64(args.pngBase64)
+ val token = UUID.randomUUID().toString().replace("-", "")
+ staged = MobileShareImage.stageClipboard(context, bytes, token)
+ val published = staged
+ val uri = FileProvider.getUriForFile(
+ context,
+ "${context.packageName}.mobile_share_image.fileprovider",
+ published,
+ )
+ val clip = ClipData.newUri(context.contentResolver, "Alook image", uri)
+ activity.runOnUiThread {
+ commitMobileShareImageClipboard(
+ publish = {
+ val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE)
+ as? ClipboardManager
+ ?: throw MobileShareImageFailure(
+ "unavailable",
+ "Clipboard is unavailable",
+ )
+ clipboard.setPrimaryClip(clip)
+ },
+ cleanupAfterPublish = {
+ MobileShareImage.cleanupClipboardAfterPublish(context, published)
+ },
+ resolve = {
+ MobileShareImage.logNativeSettle(args.attemptId)
+ MobileShareImage.resolveCopied(invoke, args.attemptId)
+ },
+ reject = { failure -> MobileShareImage.reject(invoke, failure) },
+ deleteUnpublished = { published.delete() },
+ release = lease::close,
+ reportFailure = {
+ android.util.Log.w(
+ "AlookMobileShareImage",
+ "clipboard post-commit cleanup or response failed",
+ )
+ },
+ )
+ }
+ } catch (error: Exception) {
+ staged?.delete()
+ reject(invoke, lease, asFailure(error, "Could not copy image"))
+ }
+ }
+ }
+
+ @Command
+ fun saveImage(invoke: Invoke) {
+ val args = parse(invoke, SaveImageArgs::class.java) ?: return
+ val lease = acquire(invoke, args.attemptId) ?: return
+ logNativeReceive(args.attemptId)
+ executor.execute {
+ try {
+ val bytes = MobileShareImage.validateBase64(args.pngBase64)
+ val filename = MobileShareImage.sanitizeFilename(args.filename)
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ val destination = MobileShareImage.save(context, bytes, args.attemptId)
+ try {
+ MobileShareImage.resolveSaved(invoke, args.attemptId, destination)
+ } finally {
+ lease.close()
+ }
+ } else {
+ val token = UUID.randomUUID().toString().replace("-", "")
+ val staging = MobileShareImage.stageDocument(context, bytes, token)
+ activity.runOnUiThread {
+ try {
+ MobileShareImageCoordinator.begin(
+ args.attemptId,
+ token,
+ staging,
+ filename,
+ invoke,
+ lease,
+ )
+ } catch (error: Exception) {
+ staging.delete()
+ reject(invoke, lease, asFailure(error, "Could not open document picker"))
+ }
+ }
+ }
+ } catch (error: Exception) {
+ reject(invoke, lease, asFailure(error, "Could not save image"))
+ }
+ }
+ }
+
+ private fun <T> parse(invoke: Invoke, type: Class<T>): T? = try {
+ invoke.parseArgs(type)
+ } catch (_: Exception) {
+ MobileShareImage.reject(invoke, MobileShareImageFailure("invalid_png", "Image request is invalid"))
+ null
+ }
+
+ private fun acquire(invoke: Invoke, attemptId: String): MobileShareImageNativeLease? = try {
+ MobileShareImage.validateAttemptId(attemptId)
+ MobileShareImageNativeFlight.acquire()
+ } catch (failure: MobileShareImageFailure) {
+ MobileShareImage.reject(invoke, failure)
+ null
+ }
+
+ private fun reject(invoke: Invoke, lease: MobileShareImageNativeLease, failure: MobileShareImageFailure) {
+ try {
+ MobileShareImage.reject(invoke, failure)
+ } finally {
+ lease.close()
+ }
+ }
+
+ private fun asFailure(error: Exception, fallback: String): MobileShareImageFailure =
+ if (error is MobileShareImageFailure) error
+ else MobileShareImageFailure("write_failed", error.message ?: fallback)
+
+ private fun logNativeReceive(attemptId: String) {
+ android.util.Log.d(
+ "AlookMobileShareImage",
+ "native-receive attempt=$attemptId t=${android.os.SystemClock.elapsedRealtimeNanos()}",
+ )
+ }
+}
diff --git a/src/desktop/src-tauri/gen/android/app/src/main/res/xml/file_paths.xml b/src/desktop/src-tauri/plugins/mobile-share-image/android/src/main/res/xml/mobile_share_image_file_paths.xml
similarity index 51%
rename from src/desktop/src-tauri/gen/android/app/src/main/res/xml/file_paths.xml
rename to src/desktop/src-tauri/plugins/mobile-share-image/android/src/main/res/xml/mobile_share_image_file_paths.xml
index 782d63b99..be13688b1 100644
--- a/src/desktop/src-tauri/gen/android/app/src/main/res/xml/file_paths.xml
+++ b/src/desktop/src-tauri/plugins/mobile-share-image/android/src/main/res/xml/mobile_share_image_file_paths.xml
@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
- <external-path name="my_images" path="." />
- <cache-path name="my_cache_images" path="." />
+ <cache-path
+ name="mobile_share_image_clipboard"
+ path="mobile-share-image/clipboard/" />
</paths>
diff --git a/src/desktop/src-tauri/plugins/mobile-share-image/android/src/test/java/ai/alook/plugin/mobileshareimage/MobileShareImageDocumentStateTest.kt b/src/desktop/src-tauri/plugins/mobile-share-image/android/src/test/java/ai/alook/plugin/mobileshareimage/MobileShareImageDocumentStateTest.kt
new file mode 100644
index 000000000..ab2a34afb
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/mobile-share-image/android/src/test/java/ai/alook/plugin/mobileshareimage/MobileShareImageDocumentStateTest.kt
@@ -0,0 +1,425 @@
+package ai.alook.plugin.mobileshareimage
+
+import java.io.File
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertThrows
+import org.junit.Assert.assertTrue
+import org.junit.Rule
+import org.junit.Test
+import org.junit.rules.TemporaryFolder
+
+class MobileShareImageDocumentStateTest {
+ @get:Rule
+ val temporaryFolder = TemporaryFolder()
+
+ private val ownerOne = "owner-one"
+ private val ownerTwo = "owner-two"
+ private val tokenOne = "0123456789abcdef0123456789abcdef"
+ private val tokenTwo = "fedcba9876543210fedcba9876543210"
+
+ @Test
+ fun launchFailureAndCancellationSettleOnceAndPermitImmediateRetry() {
+ val deleted = mutableListOf<File>()
+ val launches = mutableListOf<String>()
+ val core = core(deleted = deleted)
+ core.attach(ownerOne, null) { _, _ -> throw IllegalStateException("launch failed") }
+
+ val failedLaunch = probe(tokenOne, throwOnReject = true)
+ core.begin(failedLaunch.request)
+
+ assertEquals(listOf(failedLaunch.staging), deleted)
+ assertEquals(listOf("unavailable"), failedLaunch.terminal.rejectionCodes)
+ assertEquals(1, failedLaunch.terminal.rejectAttempts)
+ assertEquals(1, failedLaunch.releases)
+ assertNull(core.liveToken())
+
+ core.attach(ownerTwo, null) { token, filename -> launches += "$token:$filename" }
+ val cancelled = probe(tokenTwo)
+ core.begin(cancelled.request)
+ assertEquals(tokenTwo, core.liveToken())
+ core.deliver(ownerTwo, tokenTwo, null) { error("cancel must not clean an orphan") }
+
+ assertEquals(listOf("$tokenTwo:share.png"), launches)
+ assertEquals(listOf("cancelled"), cancelled.terminal.rejectionCodes)
+ assertEquals(1, cancelled.terminal.rejectAttempts)
+ assertEquals(1, cancelled.releases)
+ assertNull(core.liveToken())
+
+ val retry = probe(tokenOne)
+ core.begin(retry.request)
+ core.deliver(ownerTwo, tokenOne, null) { error("retry must not clean an orphan") }
+ assertEquals(1, retry.terminal.rejectAttempts)
+ assertEquals(1, retry.releases)
+ }
+
+ @Test
+ fun selectedDocumentRunsOpenWriteFlushCloseAndIgnoresDuplicateWhileWriting() {
+ val tasks = mutableListOf<() -> Unit>()
+ val deleted = mutableListOf<File>()
+ val events = mutableListOf<String>()
+ val orphanTokens = mutableListOf<String>()
+ val core = core(execute = { tasks += it }, deleted = deleted)
+ core.attach(ownerOne, null) { token, _ -> events += "launch:$token" }
+ val probe = probe(tokenOne, events = events)
+ val destination = RecordingDestination(events = events)
+
+ core.begin(probe.request)
+ core.deliver(ownerOne, tokenOne, destination, orphanTokens::add)
+ core.deliver(ownerOne, tokenOne, destination, orphanTokens::add)
+ val overlap = probe(tokenTwo)
+ val busy = assertThrows(MobileShareImageFailure::class.java) {
+ core.begin(overlap.request)
+ }
+
+ assertEquals(1, tasks.size)
+ assertEquals("busy", busy.code)
+ assertEquals(tokenOne, core.liveToken())
+ assertEquals(0, overlap.terminal.resolveAttempts)
+ assertEquals(0, overlap.terminal.rejectAttempts)
+ assertEquals(0, overlap.releases)
+ assertEquals(0, destination.opens)
+ assertTrue(orphanTokens.isEmpty())
+ tasks.single().invoke()
+
+ assertEquals(
+ listOf("launch:$tokenOne", "open", "write", "flush", "close", "resolve", "release"),
+ events,
+ )
+ assertEquals(1, destination.opens)
+ assertEquals(0, destination.returnedUriDeletes)
+ assertEquals(listOf(probe.staging), deleted)
+ assertEquals(1, probe.terminal.resolveAttempts)
+ assertEquals(0, probe.terminal.rejectAttempts)
+ assertEquals(1, probe.releases)
+
+ core.deliver(ownerOne, tokenOne, destination, orphanTokens::add)
+ assertEquals(listOf(tokenOne), orphanTokens)
+ assertEquals(1, destination.opens)
+ assertEquals(1, probe.terminal.resolveAttempts)
+ assertEquals(1, probe.releases)
+ }
+
+ @Test
+ fun openWriteFlushAndCloseFailuresRejectOnceWithoutDeletingTheSafUri() {
+ for (failurePoint in listOf("open", "write", "flush", "close")) {
+ val deleted = mutableListOf<File>()
+ val core = core(deleted = deleted)
+ core.attach(ownerOne, null) { _, _ -> }
+ val failed = probe(tokenOne)
+ val destination = RecordingDestination(failurePoint = failurePoint)
+
+ core.begin(failed.request)
+ core.deliver(ownerOne, tokenOne, destination) { error("active failure is not orphaned") }
+
+ assertEquals("failure at $failurePoint", listOf("write_failed"), failed.terminal.rejectionCodes)
+ assertEquals("failure at $failurePoint", 1, failed.terminal.rejectAttempts)
+ assertEquals("failure at $failurePoint", 0, failed.terminal.resolveAttempts)
+ assertEquals("failure at $failurePoint", 1, failed.releases)
+ assertEquals("failure at $failurePoint", 0, destination.returnedUriDeletes)
+ assertEquals("failure at $failurePoint", listOf(failed.staging), deleted)
+ assertNull(core.liveToken())
+
+ val retry = probe(tokenTwo)
+ core.begin(retry.request)
+ core.deliver(ownerOne, tokenTwo, null) { error("retry cancel is not orphaned") }
+ assertEquals("retry after $failurePoint", 1, retry.terminal.rejectAttempts)
+ assertEquals("retry after $failurePoint", 1, retry.releases)
+ }
+ }
+
+ @Test
+ fun detachAndReattachFenceStaleOwnersAndPreserveThePendingRequest() {
+ val events = mutableListOf<String>()
+ val orphanTokens = mutableListOf<String>()
+ val core = core()
+ core.attach(ownerOne, null) { _, _ -> }
+ val probe = probe(tokenOne, events = events)
+ val destination = RecordingDestination(events = events)
+ core.begin(probe.request)
+
+ core.detach(ownerOne)
+ core.deliver(ownerOne, tokenOne, destination, orphanTokens::add)
+ assertEquals(tokenOne, core.liveToken())
+ assertEquals(0, destination.opens)
+
+ core.attach(ownerTwo, tokenOne) { _, _ -> }
+ assertEquals(tokenOne, core.tokenForOwner(ownerTwo))
+ core.deliver(ownerOne, tokenOne, destination, orphanTokens::add)
+ assertEquals(0, destination.opens)
+ core.deliver(ownerTwo, tokenOne, destination, orphanTokens::add)
+
+ assertEquals(1, destination.opens)
+ assertEquals(1, probe.terminal.resolveAttempts)
+ assertEquals(1, probe.releases)
+ assertTrue(orphanTokens.isEmpty())
+ }
+
+ @Test
+ fun mismatchedAndRestoredOrphanCallbacksCannotSettleTheActiveRequest() {
+ val orphanTokens = mutableListOf<String>()
+ val core = core()
+ core.attach(ownerOne, null) { _, _ -> }
+ val active = probe(tokenOne)
+ core.begin(active.request)
+
+ core.deliver(ownerOne, tokenTwo, RecordingDestination(), orphanTokens::add)
+ assertEquals(listOf(tokenTwo), orphanTokens)
+ assertEquals(0, active.terminal.resolveAttempts)
+ assertEquals(0, active.terminal.rejectAttempts)
+ assertEquals(0, active.releases)
+ assertEquals(tokenOne, core.liveToken())
+
+ core.deliver(ownerOne, tokenOne, null, orphanTokens::add)
+ assertEquals(1, active.terminal.rejectAttempts)
+ assertEquals(1, active.releases)
+ }
+
+ @Test
+ fun activityResultAdapterKeepsLateCallbackBoundToItsOwnLaunchToken() {
+ data class Result(val destination: MobileShareImageDocumentDestination?)
+
+ val callbacks = mutableMapOf<String, (Result) -> Unit>()
+ val launches = mutableListOf<String>()
+ val unregistered = mutableListOf<String>()
+ val orphanTokens = mutableListOf<String>()
+ val core = core()
+ val adapter = MobileShareImageDocumentResultAdapter<String, Result>(
+ register = { key, callback ->
+ val token = key.substringAfterLast('.')
+ callbacks[token] = callback
+ object : MobileShareImageDocumentResultRegistration<String> {
+ override fun launch(input: String) {
+ launches += input
+ }
+
+ override fun unregister() {
+ unregistered += token
+ }
+ }
+ },
+ createInput = { token, filename -> "$token:$filename" },
+ deliver = { token, result ->
+ core.deliver(ownerOne, token, result.destination, orphanTokens::add)
+ },
+ )
+ core.attach(ownerOne, null, adapter::launch)
+
+ val first = probe(tokenOne)
+ core.begin(first.request)
+ val lateFirstCallback = callbacks.getValue(tokenOne)
+ lateFirstCallback(Result(null))
+ assertEquals(1, first.terminal.rejectAttempts)
+ assertEquals(1, first.releases)
+
+ val second = probe(tokenTwo)
+ val secondDestination = RecordingDestination()
+ core.begin(second.request)
+ val secondCallback = callbacks.getValue(tokenTwo)
+ val lateDestination = RecordingDestination()
+
+ lateFirstCallback(Result(lateDestination))
+ assertEquals(tokenTwo, core.liveToken())
+ assertEquals(0, lateDestination.opens)
+ assertEquals(0, second.terminal.resolveAttempts)
+ assertEquals(0, second.terminal.rejectAttempts)
+ assertEquals(0, second.releases)
+ assertEquals(listOf(tokenOne), orphanTokens)
+
+ secondCallback(Result(secondDestination))
+ secondCallback(Result(secondDestination))
+ assertEquals(1, secondDestination.opens)
+ assertEquals(1, second.terminal.resolveAttempts)
+ assertEquals(0, second.terminal.rejectAttempts)
+ assertEquals(1, second.releases)
+ assertNull(core.liveToken())
+ assertEquals(listOf(tokenOne, tokenTwo), orphanTokens)
+ assertEquals(
+ listOf("$tokenOne:share.png", "$tokenTwo:share.png"),
+ launches,
+ )
+ assertEquals(listOf(tokenOne, tokenTwo), unregistered)
+ }
+
+ @Test
+ fun responseFailureDoesNotCreateASecondTerminalAndStillReleasesTheLease() {
+ val failures = mutableListOf<String>()
+ val core = core(reportFailure = { failures += it.message.orEmpty() })
+ core.attach(ownerOne, null) { _, _ -> }
+ val probe = probe(tokenOne, throwOnResolve = true)
+
+ core.begin(probe.request)
+ core.deliver(ownerOne, tokenOne, RecordingDestination()) {
+ error("successful write is not orphaned")
+ }
+
+ assertEquals(1, probe.terminal.resolveAttempts)
+ assertEquals(0, probe.terminal.rejectAttempts)
+ assertEquals(1, probe.releases)
+ assertEquals(listOf("resolve failed"), failures)
+ assertNull(core.liveToken())
+
+ val retry = probe(tokenTwo)
+ core.begin(retry.request)
+ core.deliver(ownerOne, tokenTwo, null) { error("retry cancel is not orphaned") }
+ assertEquals(1, retry.terminal.rejectAttempts)
+ assertEquals(1, retry.releases)
+ }
+
+ @Test
+ fun processDeathCleanupDeletesOnlyOrphansUntilNoLiveCoordinatorExists() {
+ val directory = temporaryFolder.newFolder("document")
+ val active = File(directory, "$tokenOne.png").apply { writeText("active") }
+ val orphan = File(directory, "$tokenTwo.png").apply { writeText("orphan") }
+ val temporary = File(directory, "$tokenTwo.tmp").apply { writeText("partial") }
+ val activeTemporary = File(directory, "$tokenOne.tmp").apply { writeText("partial") }
+ val liveCore = core()
+ liveCore.attach(ownerOne, null) { _, _ -> }
+ val live = probe(tokenOne, staging = active)
+ liveCore.begin(live.request)
+
+ cleanupMobileShareImageDocumentOrphans(directory, liveCore.liveToken())
+ assertTrue(active.exists())
+ assertFalse(orphan.exists())
+ assertFalse(temporary.exists())
+ assertFalse(activeTemporary.exists())
+
+ val afterProcessDeath = core()
+ val restoredDestination = RecordingDestination()
+ val restoredCallbackCleanups = mutableListOf<String>()
+ afterProcessDeath.attach(ownerTwo, tokenOne) { _, _ -> }
+ afterProcessDeath.deliver(
+ ownerTwo,
+ tokenOne,
+ restoredDestination,
+ restoredCallbackCleanups::add,
+ )
+ assertEquals(listOf(tokenOne), restoredCallbackCleanups)
+ assertEquals(0, restoredDestination.opens)
+
+ cleanupMobileShareImageDocumentOrphans(directory, afterProcessDeath.liveToken())
+ assertFalse(active.exists())
+ }
+
+ @Test
+ fun executorRejectionTerminatesTheWriteAndAllowsRetry() {
+ val core = core(execute = { throw IllegalStateException("executor stopped") })
+ core.attach(ownerOne, null) { _, _ -> }
+ val failed = probe(tokenOne)
+
+ core.begin(failed.request)
+ core.deliver(ownerOne, tokenOne, RecordingDestination()) {
+ error("executor rejection is not orphaned")
+ }
+
+ assertEquals(listOf("write_failed"), failed.terminal.rejectionCodes)
+ assertEquals(1, failed.terminal.rejectAttempts)
+ assertEquals(1, failed.releases)
+ assertNull(core.liveToken())
+ }
+
+ private fun core(
+ execute: ((() -> Unit) -> Unit) = { it() },
+ deleted: MutableList<File> = mutableListOf(),
+ reportFailure: (Exception) -> Unit = {},
+ ) = MobileShareImageDocumentCoordinatorCore(
+ execute = execute,
+ deleteStaging = { deleted += it; it.delete() },
+ reportFailure = reportFailure,
+ )
+
+ private fun probe(
+ token: String,
+ staging: File = temporaryFolder.newFile("$token.png").apply { writeText("png") },
+ events: MutableList<String> = mutableListOf(),
+ throwOnResolve: Boolean = false,
+ throwOnReject: Boolean = false,
+ ): RequestProbe {
+ val terminal = RecordingTerminal(events, throwOnResolve, throwOnReject)
+ var releases = 0
+ return RequestProbe(
+ staging = staging,
+ terminal = terminal,
+ releasesValue = { releases },
+ request = MobileShareImageDocumentRequest(
+ attemptId = "123e4567-e89b-42d3-a456-426614174000",
+ token = token,
+ staging = staging,
+ filename = "share.png",
+ terminal = terminal,
+ release = {
+ releases += 1
+ events += "release"
+ },
+ ),
+ )
+ }
+
+ private data class RequestProbe(
+ val staging: File,
+ val terminal: RecordingTerminal,
+ val releasesValue: () -> Int,
+ val request: MobileShareImageDocumentRequest,
+ ) {
+ val releases: Int get() = releasesValue()
+ }
+
+ private class RecordingTerminal(
+ private val events: MutableList<String>,
+ private val throwOnResolve: Boolean,
+ private val throwOnReject: Boolean,
+ ) : MobileShareImageDocumentTerminal {
+ var resolveAttempts = 0
+ var rejectAttempts = 0
+ val rejectionCodes = mutableListOf<String>()
+
+ override fun resolve() {
+ resolveAttempts += 1
+ events += "resolve"
+ if (throwOnResolve) throw IllegalStateException("resolve failed")
+ }
+
+ override fun reject(failure: MobileShareImageFailure) {
+ rejectAttempts += 1
+ rejectionCodes += failure.code
+ events += "reject:${failure.code}"
+ if (throwOnReject) throw IllegalStateException("reject failed")
+ }
+ }
+
+ private class RecordingDestination(
+ private val events: MutableList<String> = mutableListOf(),
+ private val failurePoint: String? = null,
+ ) : MobileShareImageDocumentDestination {
+ var opens = 0
+ var returnedUriDeletes = 0
+
+ override fun open(): MobileShareImageDocumentOutput {
+ opens += 1
+ events += "open"
+ failAt("open")
+ return object : MobileShareImageDocumentOutput {
+ override fun writeFrom(staging: File) {
+ events += "write"
+ assertTrue(staging.exists())
+ failAt("write")
+ }
+
+ override fun flush() {
+ events += "flush"
+ failAt("flush")
+ }
+
+ override fun close() {
+ events += "close"
+ failAt("close")
+ }
+ }
+ }
+
+ private fun failAt(point: String) {
+ if (failurePoint == point) throw IllegalStateException("$point failed")
+ }
+ }
+}
diff --git a/src/desktop/src-tauri/plugins/mobile-share-image/android/src/test/java/ai/alook/plugin/mobileshareimage/MobileShareImageTest.kt b/src/desktop/src-tauri/plugins/mobile-share-image/android/src/test/java/ai/alook/plugin/mobileshareimage/MobileShareImageTest.kt
new file mode 100644
index 000000000..5c775ccc3
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/mobile-share-image/android/src/test/java/ai/alook/plugin/mobileshareimage/MobileShareImageTest.kt
@@ -0,0 +1,248 @@
+package ai.alook.plugin.mobileshareimage
+
+import java.io.ByteArrayOutputStream
+import java.io.File
+import java.nio.ByteBuffer
+import java.nio.ByteOrder
+import java.util.zip.CRC32
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertThrows
+import org.junit.Assert.assertTrue
+import org.junit.Rule
+import org.junit.Test
+import org.junit.rules.TemporaryFolder
+
+class MobileShareImageTest {
+ @get:Rule
+ val temporaryFolder = TemporaryFolder()
+
+ @Test
+ fun validatesCanonicalPngStructureAndRejectsCrcCorruption() {
+ val png = png(width = 2, height = 3)
+ assertEquals(MobileShareImage.PngDimensions(2, 3), MobileShareImage.validatePngStructure(png))
+
+ png[png.lastIndex - 4] = (png[png.lastIndex - 4].toInt() xor 1).toByte()
+ assertFailure("invalid_png") { MobileShareImage.validatePngStructure(png) }
+ }
+
+ @Test
+ fun rejectsAnimatedTrailingAndDimensionBombPngs() {
+ assertFailure("invalid_png") {
+ MobileShareImage.validatePngStructure(
+ png(extraChunks = listOf(chunk("acTL", ByteArray(8)))),
+ )
+ }
+ assertFailure("invalid_png") {
+ MobileShareImage.validatePngStructure(png() + byteArrayOf(0))
+ }
+ assertFailure("invalid_png") {
+ MobileShareImage.validatePngStructure(png(width = 16_384, height = 16_384))
+ }
+ }
+
+ @Test
+ fun sanitizesFilenameToNfcPngWithinUtf8Limit() {
+ assertEquals("Café.png", MobileShareImage.sanitizeFilename("../Cafe\u0301\u0000.png"))
+ assertEquals("alook-message-share.png", MobileShareImage.sanitizeFilename("../...\u0000"))
+
+ val bounded = MobileShareImage.sanitizeFilename("🚀".repeat(100) + ".PNG")
+ assertTrue(bounded.endsWith(".png"))
+ assertTrue(bounded.toByteArray(Charsets.UTF_8).size <= 180)
+
+ val mixed = MobileShareImage.sanitizeFilename("a" + "🚀".repeat(100) + ".PNG")
+ assertTrue(mixed.endsWith(".png"))
+ assertTrue(mixed.toByteArray(Charsets.UTF_8).size <= 180)
+ assertEquals(mixed, mixed.toByteArray(Charsets.UTF_8).toString(Charsets.UTF_8))
+ assertEquals(179, MobileShareImage.sanitizeFilename("a".repeat(175)).toByteArray().size)
+ assertEquals(180, MobileShareImage.sanitizeFilename("a".repeat(176)).toByteArray().size)
+ assertEquals(180, MobileShareImage.sanitizeFilename("a".repeat(177)).toByteArray().size)
+ }
+
+ @Test
+ fun acceptsOnlyCanonicalLowercaseUuidV4AttemptIds() {
+ MobileShareImage.validateAttemptId("123e4567-e89b-42d3-a456-426614174000")
+ assertFailure("invalid_png") {
+ MobileShareImage.validateAttemptId("123E4567-E89B-42D3-A456-426614174000")
+ }
+ assertFailure("invalid_png") {
+ MobileShareImage.validateAttemptId("123e4567-e89b-12d3-a456-426614174000")
+ }
+ assertFailure("invalid_png") { MobileShareImage.validateAttemptId("not-a-uuid") }
+ }
+
+ @Test
+ fun nativeFlightRejectsOverlapAndLeaseCloseIsIdempotent() {
+ val first = MobileShareImageNativeFlight.acquire()
+ try {
+ assertFailure("busy") { MobileShareImageNativeFlight.acquire() }
+ } finally {
+ first.close()
+ first.close()
+ }
+ MobileShareImageNativeFlight.acquire().close()
+ }
+
+ @Test
+ fun clipboardCleanupKeepsPublishedFileUntilReplacementIsReady() {
+ val directory = temporaryFolder.newFolder("clipboard")
+ val old = File(directory, "old.png").apply {
+ writeText("old")
+ setLastModified(0)
+ }
+ val temporary = File(directory, "next.tmp").apply { writeText("partial") }
+ val unrelated = File(directory, "keep.txt").apply { writeText("keep") }
+
+ MobileShareImage.cleanupClipboardTemporaries(directory)
+ assertTrue(old.exists())
+ assertFalse(temporary.exists())
+
+ val published = File(directory, "next.png").apply { writeText("new") }
+ MobileShareImage.cleanupClipboardAfterPublish(directory, published)
+ MobileShareImage.cleanupClipboardAfterPublish(directory, published)
+ assertFalse(old.exists())
+ assertTrue(published.exists())
+ assertTrue(unrelated.exists())
+ }
+
+ @Test
+ fun clipboardStagingFailurePreservesThePreviousBackingFile() {
+ val directory = temporaryFolder.newFolder("clipboard-failure")
+ val old = File(directory, "old.png").apply {
+ writeText("old")
+ setLastModified(0)
+ }
+ assertTrue(File(directory, "blocked.png").mkdir())
+
+ assertFailure("write_failed") {
+ MobileShareImage.stageClipboard(directory, byteArrayOf(1, 2, 3), "blocked")
+ }
+
+ assertTrue(old.exists())
+ assertEquals("old", old.readText())
+ assertFalse(File(directory, "blocked.tmp").exists())
+ }
+
+ @Test
+ fun clipboardPublicationFailureDeletesOnlyTheNewBackingAndRejectsOnce() {
+ val directory = temporaryFolder.newFolder("clipboard-publication-failure")
+ val old = File(directory, "old.png").apply { writeText("old") }
+ val published = File(directory, "new.png").apply { writeText("new") }
+ var cleanupAttempts = 0
+ var deleteAttempts = 0
+ var resolveAttempts = 0
+ var rejectAttempts = 0
+ var releases = 0
+
+ commitMobileShareImageClipboard(
+ publish = { throw IllegalStateException("clipboard unavailable") },
+ cleanupAfterPublish = {
+ cleanupAttempts += 1
+ old.delete()
+ },
+ resolve = { resolveAttempts += 1 },
+ reject = {
+ rejectAttempts += 1
+ assertEquals("write_failed", it.code)
+ },
+ deleteUnpublished = {
+ deleteAttempts += 1
+ published.delete()
+ },
+ release = { releases += 1 },
+ )
+
+ assertTrue(old.exists())
+ assertFalse(published.exists())
+ assertEquals(0, cleanupAttempts)
+ assertEquals(1, deleteAttempts)
+ assertEquals(0, resolveAttempts)
+ assertEquals(1, rejectAttempts)
+ assertEquals(1, releases)
+ }
+
+ @Test
+ fun clipboardCommitCannotBeRolledBackByCleanupOrResponseFailure() {
+ for (failurePoint in listOf("cleanup", "resolve")) {
+ val directory = temporaryFolder.newFolder("clipboard-committed-$failurePoint")
+ val old = File(directory, "old.png").apply { writeText("old") }
+ val published = File(directory, "new.png").apply { writeText("new") }
+ val reported = mutableListOf<String>()
+ var clipboardPointsAtPublished = false
+ var deleteAttempts = 0
+ var resolveAttempts = 0
+ var rejectAttempts = 0
+ var releases = 0
+
+ commitMobileShareImageClipboard(
+ publish = { clipboardPointsAtPublished = true },
+ cleanupAfterPublish = {
+ if (failurePoint == "cleanup") throw IllegalStateException("cleanup failed")
+ old.delete()
+ },
+ resolve = {
+ resolveAttempts += 1
+ if (failurePoint == "resolve") throw IllegalStateException("resolve failed")
+ },
+ reject = { rejectAttempts += 1 },
+ deleteUnpublished = {
+ deleteAttempts += 1
+ published.delete()
+ },
+ release = { releases += 1 },
+ reportFailure = { reported += it.message.orEmpty() },
+ )
+
+ assertTrue("failure at $failurePoint", clipboardPointsAtPublished)
+ assertTrue("failure at $failurePoint", published.exists())
+ assertEquals("failure at $failurePoint", 0, deleteAttempts)
+ assertEquals("failure at $failurePoint", 1, resolveAttempts)
+ assertEquals("failure at $failurePoint", 0, rejectAttempts)
+ assertEquals("failure at $failurePoint", 1, releases)
+ assertEquals("failure at $failurePoint", listOf("$failurePoint failed"), reported)
+ assertEquals("failure at $failurePoint", failurePoint == "cleanup", old.exists())
+ }
+ }
+
+ private fun assertFailure(code: String, block: () -> Unit) {
+ val failure = assertThrows(MobileShareImageFailure::class.java, block)
+ assertEquals(code, failure.code)
+ }
+
+ private fun png(
+ width: Int = 1,
+ height: Int = 1,
+ extraChunks: List<ByteArray> = emptyList(),
+ ): ByteArray {
+ val header = ByteBuffer.allocate(13).order(ByteOrder.BIG_ENDIAN)
+ .putInt(width)
+ .putInt(height)
+ .put(8)
+ .put(6)
+ .put(0)
+ .put(0)
+ .put(0)
+ .array()
+ return ByteArrayOutputStream().apply {
+ write(byteArrayOf(-119, 80, 78, 71, 13, 10, 26, 10))
+ write(chunk("IHDR", header))
+ extraChunks.forEach(::write)
+ write(chunk("IDAT", byteArrayOf(0)))
+ write(chunk("IEND", byteArrayOf()))
+ }.toByteArray()
+ }
+
+ private fun chunk(type: String, data: ByteArray): ByteArray {
+ val typeBytes = type.toByteArray(Charsets.US_ASCII)
+ val crc = CRC32().apply {
+ update(typeBytes)
+ update(data)
+ }.value
+ return ByteBuffer.allocate(12 + data.size).order(ByteOrder.BIG_ENDIAN)
+ .putInt(data.size)
+ .put(typeBytes)
+ .put(data)
+ .putInt(crc.toInt())
+ .array()
+ }
+}
diff --git a/src/desktop/src-tauri/plugins/mobile-share-image/build.rs b/src/desktop/src-tauri/plugins/mobile-share-image/build.rs
new file mode 100644
index 000000000..697fb8c97
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/mobile-share-image/build.rs
@@ -0,0 +1,7 @@
+fn main() {
+ tauri_plugin::Builder::new(&[])
+ .android_path("android")
+ .ios_path("ios")
+ .try_build()
+ .expect("failed to build mobile share image plugin");
+}
diff --git a/src/desktop/src-tauri/plugins/mobile-share-image/ios/Package.swift b/src/desktop/src-tauri/plugins/mobile-share-image/ios/Package.swift
new file mode 100644
index 000000000..2b3a55853
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/mobile-share-image/ios/Package.swift
@@ -0,0 +1,33 @@
+// swift-tools-version:5.3
+
+import PackageDescription
+
+let package = Package(
+ name: "tauri-plugin-mobile-share-image",
+ platforms: [.iOS(.v14)],
+ products: [
+ .library(
+ name: "tauri-plugin-mobile-share-image",
+ type: .static,
+ targets: ["tauri-plugin-mobile-share-image"])
+ ],
+ dependencies: [
+ .package(name: "Tauri", path: "../.tauri/tauri-api")
+ ],
+ targets: [
+ .target(
+ name: "tauri-plugin-mobile-share-image",
+ dependencies: [.byName(name: "Tauri")],
+ path: "Sources",
+ linkerSettings: [
+ .linkedFramework("ImageIO"),
+ .linkedFramework("Photos"),
+ .linkedFramework("UIKit"),
+ .linkedFramework("UniformTypeIdentifiers"),
+ ]),
+ .testTarget(
+ name: "MobileShareImagePluginTests",
+ dependencies: [.byName(name: "tauri-plugin-mobile-share-image")],
+ path: "Tests/MobileShareImagePluginTests")
+ ]
+)
diff --git a/src/desktop/src-tauri/plugins/mobile-share-image/ios/Sources/MobileShareImagePlugin.swift b/src/desktop/src-tauri/plugins/mobile-share-image/ios/Sources/MobileShareImagePlugin.swift
new file mode 100644
index 000000000..1d27b2d83
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/mobile-share-image/ios/Sources/MobileShareImagePlugin.swift
@@ -0,0 +1,509 @@
+import CoreGraphics
+import Foundation
+import ImageIO
+import Photos
+import SwiftRs
+import Tauri
+import UIKit
+import UniformTypeIdentifiers
+
+struct CopyImageArgs: Decodable {
+ let attemptId: String
+ let pngBase64: String
+}
+
+struct SaveImageArgs: Decodable {
+ let attemptId: String
+ let pngBase64: String
+ let filename: String
+}
+
+struct MobileShareImageResult: Encodable, Equatable {
+ let attemptId: String
+ let status: String
+ let destination: String
+}
+
+struct MobileShareImageFailure: Error, Equatable {
+ let code: String
+ let message: String
+}
+
+private let mobileShareImageMaxBytes = 10 * 1024 * 1024
+private let mobileShareImageMaxDimension = 16_384
+private let mobileShareImageMaxPixels = 16_777_216
+private let mobileShareImageMaxOutputBytes = 64 * 1024 * 1024
+
+enum MobileShareImageValidator {
+ struct Dimensions: Equatable {
+ let width: Int
+ let height: Int
+ }
+
+ private static let signature: [UInt8] = [137, 80, 78, 71, 13, 10, 26, 10]
+ private static let crcTable: [UInt32] = (0..<256).map { value in
+ var result = UInt32(value)
+ for _ in 0..<8 {
+ result = (result & 1) == 1 ? 0xedb88320 ^ (result >> 1) : result >> 1
+ }
+ return result
+ }
+
+ static func validateAttemptId(_ value: String) throws {
+ let utf8 = Array(value.utf8)
+ let canonical = UUID(uuidString: value)?.uuidString.lowercased()
+ guard canonical == value,
+ utf8.count == 36,
+ utf8[14] == 52,
+ [56, 57, 97, 98].contains(utf8[19])
+ else {
+ throw MobileShareImageFailure(code: "invalid_png", message: "Invalid attempt identifier")
+ }
+ }
+
+ static func decode(_ value: String) throws -> Data {
+ let maxEncoded = ((mobileShareImageMaxBytes + 2) / 3) * 4
+ guard !value.isEmpty, value.utf8.count % 4 == 0 else {
+ throw MobileShareImageFailure(code: "invalid_png", message: "Image payload is invalid")
+ }
+ guard value.utf8.count <= maxEncoded else {
+ throw MobileShareImageFailure(code: "image_too_large", message: "Image exceeds the mobile limit")
+ }
+ guard let data = Data(base64Encoded: value, options: []), data.base64EncodedString() == value else {
+ throw MobileShareImageFailure(code: "invalid_png", message: "Image payload is not canonical base64")
+ }
+ guard !data.isEmpty else {
+ throw MobileShareImageFailure(code: "invalid_png", message: "Image payload is empty")
+ }
+ guard data.count <= mobileShareImageMaxBytes else {
+ throw MobileShareImageFailure(code: "image_too_large", message: "Image exceeds the mobile limit")
+ }
+ let dimensions = try validateStructure(data)
+ try forceDecode(data, dimensions: dimensions)
+ return data
+ }
+
+ static func sanitizeFilename(_ value: String) -> String {
+ let normalized = value.precomposedStringWithCanonicalMapping
+ let basename = normalized.components(separatedBy: CharacterSet(charactersIn: "/\\")).last ?? ""
+ var scalars = Array(basename.unicodeScalars)
+ while let first = scalars.first,
+ first == "." || CharacterSet.whitespacesAndNewlines.contains(first) {
+ scalars.removeFirst()
+ }
+ scalars.removeAll {
+ CharacterSet.controlCharacters.contains($0) || $0 == "/" || $0 == "\\"
+ }
+ var stem = String(String.UnicodeScalarView(scalars))
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ while stem.lowercased().hasSuffix(".png") {
+ stem.removeLast(4)
+ }
+ if stem.isEmpty { stem = "alook-message-share" }
+ while (stem + ".png").utf8.count > 180, !stem.isEmpty {
+ stem.removeLast()
+ }
+ return stem.isEmpty ? "alook-message-share.png" : stem + ".png"
+ }
+
+ static func validateStructure(_ data: Data) throws -> Dimensions {
+ let bytes = [UInt8](data)
+ guard bytes.count >= signature.count, Array(bytes[0..<8]) == signature else {
+ throw invalidPNG()
+ }
+ var offset = 8
+ var dimensions: Dimensions?
+ var sawData = false
+ var sawEnd = false
+ while offset < bytes.count {
+ guard offset <= bytes.count - 12 else { throw invalidPNG() }
+ let lengthValue = readUInt32(bytes, at: offset)
+ let dataStart = offset + 8
+ let dataEndValue = UInt64(dataStart) + UInt64(lengthValue)
+ let chunkEndValue = dataEndValue + 4
+ guard chunkEndValue <= UInt64(bytes.count), !sawEnd else { throw invalidPNG() }
+ let dataEnd = Int(dataEndValue)
+ let chunkEnd = Int(chunkEndValue)
+ let type = Array(bytes[(offset + 4)..<(offset + 8)])
+ let storedCRC = readUInt32(bytes, at: dataEnd)
+ guard crc32(bytes, range: (offset + 4)..<dataEnd) == storedCRC else { throw invalidPNG() }
+
+ if type == [73, 72, 68, 82] { // IHDR
+ guard dimensions == nil, offset == 8, lengthValue == 13 else { throw invalidPNG() }
+ let width = Int(readUInt32(bytes, at: dataStart))
+ let height = Int(readUInt32(bytes, at: dataStart + 4))
+ let pixels = UInt64(width) * UInt64(height)
+ guard width > 0, height > 0,
+ width <= mobileShareImageMaxDimension,
+ height <= mobileShareImageMaxDimension,
+ pixels <= UInt64(mobileShareImageMaxPixels)
+ else { throw invalidPNG() }
+ let bitDepth = Int(bytes[dataStart + 8])
+ let colorType = Int(bytes[dataStart + 9])
+ let legal: Bool
+ switch colorType {
+ case 0: legal = [1, 2, 4, 8, 16].contains(bitDepth)
+ case 2, 4, 6: legal = [8, 16].contains(bitDepth)
+ case 3: legal = [1, 2, 4, 8].contains(bitDepth)
+ default: legal = false
+ }
+ guard legal,
+ bytes[dataStart + 10] == 0,
+ bytes[dataStart + 11] == 0,
+ bytes[dataStart + 12] <= 1
+ else { throw invalidPNG() }
+ dimensions = Dimensions(width: width, height: height)
+ } else if type == [73, 68, 65, 84] { // IDAT
+ guard dimensions != nil, !sawEnd else { throw invalidPNG() }
+ sawData = true
+ } else if type == [73, 69, 78, 68] { // IEND
+ guard dimensions != nil, sawData, lengthValue == 0, chunkEnd == bytes.count else {
+ throw invalidPNG()
+ }
+ sawEnd = true
+ } else if type == [97, 99, 84, 76] || // acTL
+ type == [102, 99, 84, 76] || // fcTL
+ type == [102, 100, 65, 84] { // fdAT
+ throw invalidPNG()
+ }
+ offset = chunkEnd
+ }
+ guard sawEnd, let dimensions = dimensions else { throw invalidPNG() }
+ return dimensions
+ }
+
+ private static func forceDecode(_ data: Data, dimensions: Dimensions) throws {
+ guard let source = CGImageSourceCreateWithData(data as CFData, nil),
+ CGImageSourceGetStatus(source) == .statusComplete,
+ CGImageSourceGetStatusAtIndex(source, 0) == .statusComplete,
+ CGImageSourceGetCount(source) == 1,
+ let image = CGImageSourceCreateImageAtIndex(source, 0, nil),
+ image.width == dimensions.width,
+ image.height == dimensions.height
+ else { throw invalidPNG() }
+ let byteCount = dimensions.width * dimensions.height * 4
+ guard byteCount <= mobileShareImageMaxOutputBytes else { throw invalidPNG() }
+ var pixels = [UInt8](repeating: 0, count: byteCount)
+ let decoded = pixels.withUnsafeMutableBytes { buffer -> Bool in
+ guard let context = CGContext(
+ data: buffer.baseAddress,
+ width: dimensions.width,
+ height: dimensions.height,
+ bitsPerComponent: 8,
+ bytesPerRow: dimensions.width * 4,
+ space: CGColorSpaceCreateDeviceRGB(),
+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
+ ) else { return false }
+ context.draw(image, in: CGRect(x: 0, y: 0, width: dimensions.width, height: dimensions.height))
+ return true
+ }
+ guard decoded else { throw invalidPNG() }
+ }
+
+ private static func readUInt32(_ bytes: [UInt8], at offset: Int) -> UInt32 {
+ UInt32(bytes[offset]) << 24 |
+ UInt32(bytes[offset + 1]) << 16 |
+ UInt32(bytes[offset + 2]) << 8 |
+ UInt32(bytes[offset + 3])
+ }
+
+ private static func crc32(_ bytes: [UInt8], range: Range<Int>) -> UInt32 {
+ var crc = UInt32.max
+ for index in range {
+ crc = crcTable[Int((crc ^ UInt32(bytes[index])) & 0xff)] ^ (crc >> 8)
+ }
+ return crc ^ UInt32.max
+ }
+
+ private static func invalidPNG() -> MobileShareImageFailure {
+ MobileShareImageFailure(code: "invalid_png", message: "Image payload is not a valid PNG")
+ }
+}
+
+protocol MobileShareImagePasteboardWriting {
+ func setPNG(_ data: Data) throws
+}
+
+final class SystemMobileShareImagePasteboard: MobileShareImagePasteboardWriting {
+ func setPNG(_ data: Data) throws {
+ UIPasteboard.general.setData(data, forPasteboardType: UTType.png.identifier)
+ }
+}
+
+enum MobileShareImagePhotoAuthorization {
+ case notDetermined
+ case authorized
+ case limited
+ case denied
+ case restricted
+ case unavailable
+}
+
+protocol MobileShareImagePhotoLibraryAdding {
+ func authorizationStatus() -> MobileShareImagePhotoAuthorization
+ func requestAuthorization(_ completion: @escaping (MobileShareImagePhotoAuthorization) -> Void)
+ func addPNG(_ data: Data, filename: String, completion: @escaping (Result<Void, Error>) -> Void)
+}
+
+final class SystemMobileShareImagePhotoLibrary: MobileShareImagePhotoLibraryAdding {
+ func authorizationStatus() -> MobileShareImagePhotoAuthorization {
+ map(PHPhotoLibrary.authorizationStatus(for: .addOnly))
+ }
+
+ func requestAuthorization(_ completion: @escaping (MobileShareImagePhotoAuthorization) -> Void) {
+ PHPhotoLibrary.requestAuthorization(for: .addOnly) { status in completion(self.map(status)) }
+ }
+
+ func addPNG(_ data: Data, filename: String, completion: @escaping (Result<Void, Error>) -> Void) {
+ PHPhotoLibrary.shared().performChanges({
+ let options = PHAssetResourceCreationOptions()
+ options.originalFilename = filename
+ options.uniformTypeIdentifier = UTType.png.identifier
+ PHAssetCreationRequest.forAsset().addResource(with: .photo, data: data, options: options)
+ }) { success, error in
+ if success {
+ completion(.success(()))
+ } else {
+ completion(.failure(error ?? MobileShareImageFailure(
+ code: "write_failed",
+ message: "Could not save image to Photos"
+ )))
+ }
+ }
+ }
+
+ private func map(_ status: PHAuthorizationStatus) -> MobileShareImagePhotoAuthorization {
+ switch status {
+ case .notDetermined: return .notDetermined
+ case .authorized: return .authorized
+ case .limited: return .limited
+ case .denied: return .denied
+ case .restricted: return .restricted
+ @unknown default: return .unavailable
+ }
+ }
+}
+
+final class MobileShareImageOperations {
+ typealias Completion = (Result<MobileShareImageResult, MobileShareImageFailure>) -> Void
+
+ private let worker: DispatchQueue
+ private let main: (@escaping () -> Void) -> Void
+ private let pasteboard: MobileShareImagePasteboardWriting
+ private let photos: MobileShareImagePhotoLibraryAdding
+ private let state = DispatchQueue(label: "ai.alook.mobile-share-image.state")
+ private var activeAttemptId: String?
+
+ init(
+ worker: DispatchQueue = DispatchQueue(label: "ai.alook.mobile-share-image.worker"),
+ main: @escaping (@escaping () -> Void) -> Void = { DispatchQueue.main.async(execute: $0) },
+ pasteboard: MobileShareImagePasteboardWriting = SystemMobileShareImagePasteboard(),
+ photos: MobileShareImagePhotoLibraryAdding = SystemMobileShareImagePhotoLibrary()
+ ) {
+ self.worker = worker
+ self.main = main
+ self.pasteboard = pasteboard
+ self.photos = photos
+ }
+
+ func copy(_ args: CopyImageArgs, completion: @escaping Completion) {
+ guard acquire(args.attemptId) else {
+ completion(.failure(MobileShareImageFailure(code: "busy", message: "Another image action is active")))
+ return
+ }
+ worker.async {
+ do {
+ let data = try MobileShareImageValidator.decode(args.pngBase64)
+ self.main {
+ do {
+ try self.pasteboard.setPNG(data)
+ self.finish(args.attemptId, completion: completion, result: .success(MobileShareImageResult(
+ attemptId: args.attemptId,
+ status: "copied",
+ destination: "clipboard"
+ )))
+ } catch {
+ self.finish(args.attemptId, completion: completion, result: .failure(self.failure(
+ error,
+ fallback: "Could not copy image"
+ )))
+ }
+ }
+ } catch {
+ self.finish(args.attemptId, completion: completion, result: .failure(self.failure(
+ error,
+ fallback: "Could not copy image"
+ )))
+ }
+ }
+ }
+
+ func save(_ args: SaveImageArgs, completion: @escaping Completion) {
+ guard acquire(args.attemptId) else {
+ completion(.failure(MobileShareImageFailure(code: "busy", message: "Another image action is active")))
+ return
+ }
+ worker.async {
+ do {
+ let data = try MobileShareImageValidator.decode(args.pngBase64)
+ let filename = MobileShareImageValidator.sanitizeFilename(args.filename)
+ self.authorizeAndSave(data, filename: filename, attemptId: args.attemptId, completion: completion)
+ } catch {
+ self.finish(args.attemptId, completion: completion, result: .failure(self.failure(
+ error,
+ fallback: "Could not save image"
+ )))
+ }
+ }
+ }
+
+ private func authorizeAndSave(
+ _ data: Data,
+ filename: String,
+ attemptId: String,
+ completion: @escaping Completion
+ ) {
+ switch photos.authorizationStatus() {
+ case .authorized, .limited:
+ addToPhotos(data, filename: filename, attemptId: attemptId, completion: completion)
+ case .notDetermined:
+ photos.requestAuthorization { status in
+ switch status {
+ case .authorized, .limited:
+ self.addToPhotos(data, filename: filename, attemptId: attemptId, completion: completion)
+ case .denied, .restricted:
+ self.finish(attemptId, completion: completion, result: .failure(MobileShareImageFailure(
+ code: "permission_denied",
+ message: "Photos add access was denied"
+ )))
+ case .notDetermined, .unavailable:
+ self.finish(attemptId, completion: completion, result: .failure(MobileShareImageFailure(
+ code: "unavailable",
+ message: "Photos add access is unavailable"
+ )))
+ }
+ }
+ case .denied, .restricted:
+ finish(attemptId, completion: completion, result: .failure(MobileShareImageFailure(
+ code: "permission_denied",
+ message: "Photos add access was denied"
+ )))
+ case .unavailable:
+ finish(attemptId, completion: completion, result: .failure(MobileShareImageFailure(
+ code: "unavailable",
+ message: "Photos add access is unavailable"
+ )))
+ }
+ }
+
+ private func addToPhotos(
+ _ data: Data,
+ filename: String,
+ attemptId: String,
+ completion: @escaping Completion
+ ) {
+ photos.addPNG(data, filename: filename) { result in
+ switch result {
+ case .success:
+ self.finish(attemptId, completion: completion, result: .success(MobileShareImageResult(
+ attemptId: attemptId,
+ status: "saved",
+ destination: "photos"
+ )))
+ case .failure(let error):
+ self.finish(attemptId, completion: completion, result: .failure(self.failure(
+ error,
+ fallback: "Could not save image to Photos"
+ )))
+ }
+ }
+ }
+
+ private func acquire(_ attemptId: String) -> Bool {
+ state.sync {
+ guard activeAttemptId == nil else { return false }
+ activeAttemptId = attemptId
+ return true
+ }
+ }
+
+ private func finish(
+ _ attemptId: String,
+ completion: @escaping Completion,
+ result: Result<MobileShareImageResult, MobileShareImageFailure>
+ ) {
+ state.async {
+ guard self.activeAttemptId == attemptId else { return }
+ self.activeAttemptId = nil
+ completion(result)
+ }
+ }
+
+ private func failure(_ error: Error, fallback: String) -> MobileShareImageFailure {
+ if let failure = error as? MobileShareImageFailure { return failure }
+ return MobileShareImageFailure(code: "write_failed", message: error.localizedDescription.isEmpty
+ ? fallback
+ : error.localizedDescription)
+ }
+}
+
+final class MobileShareImagePlugin: Plugin {
+ private let operations = MobileShareImageOperations()
+
+ @objc public func copyImage(_ invoke: Invoke) {
+ do {
+ let args = try invoke.parseArgs(CopyImageArgs.self)
+ try MobileShareImageValidator.validateAttemptId(args.attemptId)
+ logReceive(args.attemptId)
+ operations.copy(args) { result in self.settle(invoke, result: result) }
+ } catch {
+ reject(invoke, failure: failure(error, fallback: "Image request is invalid"))
+ }
+ }
+
+ @objc public func saveImage(_ invoke: Invoke) {
+ do {
+ let args = try invoke.parseArgs(SaveImageArgs.self)
+ try MobileShareImageValidator.validateAttemptId(args.attemptId)
+ logReceive(args.attemptId)
+ operations.save(args) { result in self.settle(invoke, result: result) }
+ } catch {
+ reject(invoke, failure: failure(error, fallback: "Image request is invalid"))
+ }
+ }
+
+ private func settle(
+ _ invoke: Invoke,
+ result: Result<MobileShareImageResult, MobileShareImageFailure>
+ ) {
+ switch result {
+ case .success(let value):
+ #if DEBUG
+ print("mobile-share-image native-settle attempt=\(value.attemptId) t=\(ProcessInfo.processInfo.systemUptime)")
+ #endif
+ invoke.resolve(value)
+ case .failure(let failure):
+ reject(invoke, failure: failure)
+ }
+ }
+
+ private func reject(_ invoke: Invoke, failure: MobileShareImageFailure) {
+ invoke.reject(failure.message, code: failure.code)
+ }
+
+ private func failure(_ error: Error, fallback: String) -> MobileShareImageFailure {
+ if let failure = error as? MobileShareImageFailure { return failure }
+ return MobileShareImageFailure(code: "invalid_png", message: fallback)
+ }
+
+ private func logReceive(_ attemptId: String) {
+ #if DEBUG
+ print("mobile-share-image native-receive attempt=\(attemptId) t=\(ProcessInfo.processInfo.systemUptime)")
+ #endif
+ }
+}
+
+@_cdecl("init_plugin_mobile_share_image")
+func initPlugin() -> Plugin {
+ MobileShareImagePlugin()
+}
diff --git a/src/desktop/src-tauri/plugins/mobile-share-image/ios/Tests/MobileShareImagePluginTests/MobileShareImagePluginTests.swift b/src/desktop/src-tauri/plugins/mobile-share-image/ios/Tests/MobileShareImagePluginTests/MobileShareImagePluginTests.swift
new file mode 100644
index 000000000..211d19f62
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/mobile-share-image/ios/Tests/MobileShareImagePluginTests/MobileShareImagePluginTests.swift
@@ -0,0 +1,245 @@
+import XCTest
+@testable import tauri_plugin_mobile_share_image
+
+final class MobileShareImagePluginTests: XCTestCase {
+ private let attempt = "123e4567-e89b-42d3-a456-426614174000"
+ private let pngBase64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
+
+ func testValidatorAcceptsCompletePNGAndRejectsCorruption() throws {
+ try MobileShareImageValidator.validateAttemptId(attempt)
+ let data = try MobileShareImageValidator.decode(pngBase64)
+ XCTAssertEqual(try MobileShareImageValidator.validateStructure(data), .init(width: 1, height: 1))
+
+ var corrupted = data
+ corrupted[corrupted.index(corrupted.startIndex, offsetBy: 32)] ^= 1
+ XCTAssertThrowsError(try MobileShareImageValidator.validateStructure(corrupted)) { error in
+ XCTAssertEqual(error as? MobileShareImageFailure, .init(
+ code: "invalid_png",
+ message: "Image payload is not a valid PNG"
+ ))
+ }
+ }
+
+ func testValidatorRejectsNonCanonicalBase64NonPNGAndTrailingBytes() throws {
+ for invalid in ["", "AA", "A===", "****", "aGVsbG8="] {
+ XCTAssertThrowsError(try MobileShareImageValidator.decode(invalid))
+ }
+
+ var trailing = Data(base64Encoded: pngBase64)!
+ trailing.append(0)
+ XCTAssertThrowsError(try MobileShareImageValidator.validateStructure(trailing))
+ }
+
+ func testAttemptIdMustBeCanonicalVersionFourUUID() {
+ for invalid in [
+ "123e4567-e89b-12d3-a456-426614174000",
+ "123E4567-E89B-42D3-A456-426614174000",
+ "bad\nlog",
+ ] {
+ XCTAssertThrowsError(try MobileShareImageValidator.validateAttemptId(invalid))
+ }
+ }
+
+ func testFilenameNormalizationAndUTF8Boundary() {
+ XCTAssertEqual(
+ MobileShareImageValidator.sanitizeFilename(" ../a/b/..re\u{301}sume\u{301}.PNG.png"),
+ "r\u{e9}sum\u{e9}.png"
+ )
+ XCTAssertEqual(MobileShareImageValidator.sanitizeFilename("..."), "alook-message-share.png")
+ XCTAssertEqual(MobileShareImageValidator.sanitizeFilename("x\u{0}/name.png"), "name.png")
+ XCTAssertLessThanOrEqual(
+ MobileShareImageValidator.sanitizeFilename(String(repeating: "界", count: 100)).utf8.count,
+ 180
+ )
+ XCTAssertEqual(MobileShareImageValidator.sanitizeFilename(String(repeating: "a", count: 175)).utf8.count, 179)
+ XCTAssertEqual(MobileShareImageValidator.sanitizeFilename(String(repeating: "a", count: 176)).utf8.count, 180)
+ XCTAssertEqual(MobileShareImageValidator.sanitizeFilename(String(repeating: "a", count: 177)).utf8.count, 180)
+ }
+
+ func testCopySettlesOnlyAfterMainThreadPasteboardPublicationAndReleasesBusy() {
+ let pasteboard = FakePasteboard()
+ let photos = FakePhotos(status: .denied)
+ let queued = expectation(description: "main publication queued")
+ var publication: (() -> Void)?
+ let operations = MobileShareImageOperations(
+ worker: DispatchQueue(label: "test.copy.worker"),
+ main: { block in publication = block; queued.fulfill() },
+ pasteboard: pasteboard,
+ photos: photos
+ )
+ let success = expectation(description: "copy success")
+ var result: Result<MobileShareImageResult, MobileShareImageFailure>?
+ operations.copy(.init(attemptId: attempt, pngBase64: pngBase64)) {
+ result = $0
+ success.fulfill()
+ }
+ wait(for: [queued], timeout: 2)
+ XCTAssertEqual(pasteboard.writes, 0)
+ XCTAssertNil(result)
+
+ let busy = expectation(description: "second call busy")
+ operations.copy(.init(attemptId: "223e4567-e89b-42d3-a456-426614174000", pngBase64: pngBase64)) {
+ XCTAssertEqual(try? $0.get(), nil)
+ if case .failure(let failure) = $0 { XCTAssertEqual(failure.code, "busy") }
+ busy.fulfill()
+ }
+ wait(for: [busy], timeout: 1)
+ publication?()
+ wait(for: [success], timeout: 2)
+ XCTAssertEqual(pasteboard.writes, 1)
+ XCTAssertEqual(try? result?.get().destination, "clipboard")
+ }
+
+ func testPhotosDenialRejectsWithoutAdding() {
+ let photos = FakePhotos(status: .denied)
+ let operations = MobileShareImageOperations(
+ worker: DispatchQueue(label: "test.photos.denied"),
+ main: { $0() },
+ pasteboard: FakePasteboard(),
+ photos: photos
+ )
+ let settled = expectation(description: "denied")
+ operations.save(.init(attemptId: attempt, pngBase64: pngBase64, filename: "card.png")) { result in
+ if case .failure(let failure) = result { XCTAssertEqual(failure.code, "permission_denied") }
+ settled.fulfill()
+ }
+ wait(for: [settled], timeout: 2)
+ XCTAssertEqual(photos.addCalls, 0)
+ }
+
+ func testPhotosSuccessWaitsForAuthorizationAndWriteCompletion() {
+ let photos = FakePhotos(status: .notDetermined)
+ let operations = MobileShareImageOperations(
+ worker: DispatchQueue(label: "test.photos.success"),
+ main: { $0() },
+ pasteboard: FakePasteboard(),
+ photos: photos
+ )
+ let authorizationRequested = expectation(description: "authorization requested")
+ photos.onRequest = { authorizationRequested.fulfill() }
+ let settled = expectation(description: "saved")
+ var result: Result<MobileShareImageResult, MobileShareImageFailure>?
+ operations.save(.init(attemptId: attempt, pngBase64: pngBase64, filename: "..card.PNG.png")) {
+ result = $0
+ settled.fulfill()
+ }
+ wait(for: [authorizationRequested], timeout: 2)
+ XCTAssertNil(result)
+ photos.completeAuthorization(.authorized)
+ XCTAssertNil(result)
+ XCTAssertEqual(photos.filename, "card.png")
+ photos.completeAdd(.success(()))
+ wait(for: [settled], timeout: 2)
+ XCTAssertEqual(try? result?.get().destination, "photos")
+ }
+
+ func testPasteboardFailureReleasesBusyForImmediateRetry() {
+ let pasteboard = FakePasteboard()
+ pasteboard.failuresRemaining = 1
+ let operations = MobileShareImageOperations(
+ worker: DispatchQueue(label: "test.copy.retry"),
+ main: { $0() },
+ pasteboard: pasteboard,
+ photos: FakePhotos(status: .denied)
+ )
+ let first = expectation(description: "copy failure")
+ operations.copy(.init(attemptId: attempt, pngBase64: pngBase64)) { result in
+ if case .failure(let failure) = result { XCTAssertEqual(failure.code, "write_failed") }
+ first.fulfill()
+ }
+ wait(for: [first], timeout: 2)
+
+ let second = expectation(description: "copy retry")
+ operations.copy(.init(attemptId: attempt, pngBase64: pngBase64)) { result in
+ XCTAssertEqual(try? result.get().destination, "clipboard")
+ second.fulfill()
+ }
+ wait(for: [second], timeout: 2)
+ XCTAssertEqual(pasteboard.writes, 1)
+ }
+
+ func testDuplicatePhotoCompletionSettlesOnceAndReleasesForRetry() {
+ let photos = FakePhotos(status: .authorized)
+ let operations = MobileShareImageOperations(
+ worker: DispatchQueue(label: "test.photos.duplicate"),
+ main: { $0() },
+ pasteboard: FakePasteboard(),
+ photos: photos
+ )
+ let firstAdd = expectation(description: "first add")
+ photos.onAdd = { firstAdd.fulfill() }
+ let firstSettle = expectation(description: "first settle")
+ var settleCount = 0
+ operations.save(.init(attemptId: attempt, pngBase64: pngBase64, filename: "card.png")) { _ in
+ settleCount += 1
+ firstSettle.fulfill()
+ }
+ wait(for: [firstAdd], timeout: 2)
+ photos.completeAdd(.success(()))
+ photos.completeAdd(.success(()))
+ wait(for: [firstSettle], timeout: 2)
+
+ let secondAdd = expectation(description: "retry add")
+ photos.onAdd = { secondAdd.fulfill() }
+ let secondSettle = expectation(description: "retry settle")
+ operations.save(.init(attemptId: attempt, pngBase64: pngBase64, filename: "card.png")) { result in
+ XCTAssertEqual(try? result.get().destination, "photos")
+ secondSettle.fulfill()
+ }
+ wait(for: [secondAdd], timeout: 2)
+ photos.completeAdd(.success(()))
+ wait(for: [secondSettle], timeout: 2)
+ XCTAssertEqual(settleCount, 1)
+ }
+}
+
+private final class FakePasteboard: MobileShareImagePasteboardWriting {
+ var writes = 0
+ var failuresRemaining = 0
+ func setPNG(_ data: Data) throws {
+ XCTAssertFalse(data.isEmpty)
+ if failuresRemaining > 0 {
+ failuresRemaining -= 1
+ throw NSError(domain: "MobileShareImageTests", code: 1)
+ }
+ writes += 1
+ }
+}
+
+private final class FakePhotos: MobileShareImagePhotoLibraryAdding {
+ var status: MobileShareImagePhotoAuthorization
+ var addCalls = 0
+ var filename: String?
+ var onRequest: (() -> Void)?
+ var onAdd: (() -> Void)?
+ private var authorizationCompletion: ((MobileShareImagePhotoAuthorization) -> Void)?
+ private var addCompletion: ((Result<Void, Error>) -> Void)?
+
+ init(status: MobileShareImagePhotoAuthorization) {
+ self.status = status
+ }
+
+ func authorizationStatus() -> MobileShareImagePhotoAuthorization { status }
+
+ func requestAuthorization(_ completion: @escaping (MobileShareImagePhotoAuthorization) -> Void) {
+ authorizationCompletion = completion
+ onRequest?()
+ }
+
+ func addPNG(_ data: Data, filename: String, completion: @escaping (Result<Void, Error>) -> Void) {
+ XCTAssertFalse(data.isEmpty)
+ addCalls += 1
+ self.filename = filename
+ addCompletion = completion
+ onAdd?()
+ }
+
+ func completeAuthorization(_ status: MobileShareImagePhotoAuthorization) {
+ self.status = status
+ authorizationCompletion?(status)
+ }
+
+ func completeAdd(_ result: Result<Void, Error>) {
+ addCompletion?(result)
+ }
+}
diff --git a/src/desktop/src-tauri/plugins/mobile-share-image/src/desktop.rs b/src/desktop/src-tauri/plugins/mobile-share-image/src/desktop.rs
new file mode 100644
index 000000000..c5f1ebda2
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/mobile-share-image/src/desktop.rs
@@ -0,0 +1,22 @@
+use crate::{CopyRequest, Error, ImageResult, SaveRequest};
+use serde::de::DeserializeOwned;
+use tauri::{plugin::PluginApi, AppHandle, Runtime};
+
+pub fn init<R: Runtime, C: DeserializeOwned>(
+ _app: &AppHandle<R>,
+ _api: PluginApi<R, C>,
+) -> Result<MobileShareImage<R>, Error> {
+ Ok(MobileShareImage(std::marker::PhantomData))
+}
+
+pub struct MobileShareImage<R: Runtime>(std::marker::PhantomData<R>);
+
+impl<R: Runtime> MobileShareImage<R> {
+ pub async fn copy(&self, _request: CopyRequest) -> Result<ImageResult, Error> {
+ Err(Error::unavailable("Mobile image actions are unavailable"))
+ }
+
+ pub async fn save(&self, _request: SaveRequest) -> Result<ImageResult, Error> {
+ Err(Error::unavailable("Mobile image actions are unavailable"))
+ }
+}
diff --git a/src/desktop/src-tauri/plugins/mobile-share-image/src/error.rs b/src/desktop/src-tauri/plugins/mobile-share-image/src/error.rs
new file mode 100644
index 000000000..029ca5dc2
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/mobile-share-image/src/error.rs
@@ -0,0 +1,30 @@
+#[derive(Clone, Debug, thiserror::Error)]
+#[error("[{code}] {message}")]
+pub struct Error {
+ pub code: String,
+ pub message: String,
+}
+
+impl Error {
+ pub fn unavailable(message: impl Into<String>) -> Self {
+ Self {
+ code: "unavailable".to_string(),
+ message: message.into(),
+ }
+ }
+}
+
+#[cfg(mobile)]
+impl From<tauri::plugin::mobile::PluginInvokeError> for Error {
+ fn from(error: tauri::plugin::mobile::PluginInvokeError) -> Self {
+ match error {
+ tauri::plugin::mobile::PluginInvokeError::InvokeRejected(response) => Self {
+ code: response.code.unwrap_or_else(|| "write_failed".to_string()),
+ message: response
+ .message
+ .unwrap_or_else(|| "Native image operation failed".to_string()),
+ },
+ other => Self::unavailable(other.to_string()),
+ }
+ }
+}
diff --git a/src/desktop/src-tauri/plugins/mobile-share-image/src/lib.rs b/src/desktop/src-tauri/plugins/mobile-share-image/src/lib.rs
new file mode 100644
index 000000000..634368a41
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/mobile-share-image/src/lib.rs
@@ -0,0 +1,41 @@
+use tauri::{
+ plugin::{Builder, TauriPlugin},
+ Manager, Runtime,
+};
+
+#[cfg(desktop)]
+mod desktop;
+mod error;
+#[cfg(mobile)]
+mod mobile;
+mod models;
+
+#[cfg(desktop)]
+use desktop::MobileShareImage;
+pub use error::Error;
+#[cfg(mobile)]
+use mobile::MobileShareImage;
+pub use models::{CopyRequest, ImageResult, SaveRequest};
+
+pub trait MobileShareImageExt<R: Runtime> {
+ fn mobile_share_image(&self) -> &MobileShareImage<R>;
+}
+
+impl<R: Runtime, T: Manager<R>> MobileShareImageExt<R> for T {
+ fn mobile_share_image(&self) -> &MobileShareImage<R> {
+ self.state::<MobileShareImage<R>>().inner()
+ }
+}
+
+pub fn init<R: Runtime>() -> TauriPlugin<R> {
+ Builder::<R, ()>::new("mobile-share-image")
+ .setup(|app, api| {
+ #[cfg(mobile)]
+ let plugin = mobile::init(app, api)?;
+ #[cfg(desktop)]
+ let plugin = desktop::init(app, api)?;
+ app.manage(plugin);
+ Ok(())
+ })
+ .build()
+}
diff --git a/src/desktop/src-tauri/plugins/mobile-share-image/src/mobile.rs b/src/desktop/src-tauri/plugins/mobile-share-image/src/mobile.rs
new file mode 100644
index 000000000..590feda64
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/mobile-share-image/src/mobile.rs
@@ -0,0 +1,69 @@
+use crate::{CopyRequest, Error, ImageResult, SaveRequest};
+use serde::de::DeserializeOwned;
+use std::sync::OnceLock;
+use std::time::Instant;
+use tauri::{
+ plugin::{PluginApi, PluginHandle},
+ AppHandle, Runtime,
+};
+
+#[cfg(target_os = "android")]
+const PLUGIN_IDENTIFIER: &str = "ai.alook.plugin.mobileshareimage";
+
+#[cfg(target_os = "ios")]
+tauri::ios_plugin_binding!(init_plugin_mobile_share_image);
+
+fn monotonic_micros() -> u128 {
+ static START: OnceLock<Instant> = OnceLock::new();
+ START.get_or_init(Instant::now).elapsed().as_micros()
+}
+
+pub fn init<R: Runtime, C: DeserializeOwned>(
+ _app: &AppHandle<R>,
+ api: PluginApi<R, C>,
+) -> Result<MobileShareImage<R>, Error> {
+ #[cfg(target_os = "android")]
+ let handle = api.register_android_plugin(PLUGIN_IDENTIFIER, "MobileShareImagePlugin")?;
+ #[cfg(target_os = "ios")]
+ let handle = api.register_ios_plugin(init_plugin_mobile_share_image)?;
+ Ok(MobileShareImage(handle))
+}
+
+pub struct MobileShareImage<R: Runtime>(PluginHandle<R>);
+
+impl<R: Runtime> MobileShareImage<R> {
+ pub async fn copy(&self, request: CopyRequest) -> Result<ImageResult, Error> {
+ self.run("copyImage", request.attempt_id.clone(), request)
+ .await
+ }
+
+ pub async fn save(&self, request: SaveRequest) -> Result<ImageResult, Error> {
+ self.run("saveImage", request.attempt_id.clone(), request)
+ .await
+ }
+
+ async fn run<T: serde::Serialize>(
+ &self,
+ command: &str,
+ attempt_id: String,
+ request: T,
+ ) -> Result<ImageResult, Error> {
+ if cfg!(debug_assertions) {
+ eprintln!(
+ "mobile-share-image plugin-rust dispatch attempt={} t={}",
+ attempt_id,
+ monotonic_micros()
+ );
+ }
+ let result = self.0.run_mobile_plugin_async(command, request).await;
+ if cfg!(debug_assertions) {
+ eprintln!(
+ "mobile-share-image plugin-rust return attempt={} ok={} t={}",
+ attempt_id,
+ result.is_ok(),
+ monotonic_micros()
+ );
+ }
+ result.map_err(Into::into)
+ }
+}
diff --git a/src/desktop/src-tauri/plugins/mobile-share-image/src/models.rs b/src/desktop/src-tauri/plugins/mobile-share-image/src/models.rs
new file mode 100644
index 000000000..ae16c4385
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/mobile-share-image/src/models.rs
@@ -0,0 +1,24 @@
+use serde::{Deserialize, Serialize};
+
+#[derive(Clone, Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SaveRequest {
+ pub attempt_id: String,
+ pub png_base64: String,
+ pub filename: String,
+}
+
+#[derive(Clone, Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CopyRequest {
+ pub attempt_id: String,
+ pub png_base64: String,
+}
+
+#[derive(Clone, Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ImageResult {
+ pub attempt_id: String,
+ pub status: String,
+ pub destination: String,
+}
diff --git a/src/desktop/src-tauri/src/lib.rs b/src/desktop/src-tauri/src/lib.rs
index bd9b02350..f0fe45dba 100644
--- a/src/desktop/src-tauri/src/lib.rs
+++ b/src/desktop/src-tauri/src/lib.rs
@@ -2,6 +2,11 @@ mod commands;
use tauri::Manager;
+#[cfg(any(mobile, test))]
+mod mobile_share_image;
+#[cfg(mobile)]
+mod mobile_share_image_runtime;
+mod native_command_guard;
mod native_oauth;
mod native_oauth_runtime;
mod webview_recovery;
@@ -61,7 +66,12 @@ pub fn run() {
#[cfg(not(desktop))]
fn run_mobile(mut builder: tauri::Builder<tauri::Wry>) {
+ builder = builder
+ .manage(mobile_share_image::MobileShareImageState::default())
+ .plugin(tauri_plugin_mobile_share_image::init());
builder = builder.invoke_handler(tauri::generate_handler![
+ mobile_share_image_runtime::mobile_share_image_copy,
+ mobile_share_image_runtime::mobile_share_image_save,
native_oauth_runtime::native_oauth_snapshot,
native_oauth_runtime::native_oauth_listen,
native_oauth_runtime::native_oauth_unlisten,
diff --git a/src/desktop/src-tauri/src/mobile_share_image.rs b/src/desktop/src-tauri/src/mobile_share_image.rs
new file mode 100644
index 000000000..f3535a231
--- /dev/null
+++ b/src/desktop/src-tauri/src/mobile_share_image.rs
@@ -0,0 +1,501 @@
+use base64::{engine::general_purpose::STANDARD, Engine as _};
+use serde::{Deserialize, Serialize};
+use std::io::Cursor;
+use std::sync::atomic::{AtomicBool, Ordering};
+use unicode_normalization::UnicodeNormalization;
+
+pub const MAX_PNG_BYTES: usize = 10 * 1024 * 1024;
+const MAX_DIMENSION: u32 = 16_384;
+const MAX_PIXELS: u64 = 16_777_216;
+const MAX_OUTPUT_BYTES: usize = 64 * 1024 * 1024;
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MobileShareImagePayload {
+ pub attempt_id: String,
+ pub png_base64: String,
+ pub filename: Option<String>,
+}
+
+#[derive(Debug)]
+pub struct ValidatedMobileShareImage {
+ pub attempt_id: String,
+ pub png_base64: String,
+ pub filename: String,
+}
+
+#[derive(Debug, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MobileShareImageResult {
+ pub attempt_id: String,
+ pub status: String,
+ pub destination: String,
+}
+
+#[derive(Clone, Debug, Serialize)]
+pub struct MobileShareImageError {
+ pub code: String,
+ pub message: String,
+}
+
+impl MobileShareImageError {
+ pub fn new(code: &str, message: impl Into<String>) -> Self {
+ Self {
+ code: code.to_string(),
+ message: message.into(),
+ }
+ }
+}
+
+#[derive(Default)]
+pub struct MobileShareImageState {
+ busy: AtomicBool,
+}
+
+#[derive(Debug)]
+pub struct MobileShareImageLease<'a>(&'a AtomicBool);
+
+impl MobileShareImageState {
+ pub fn acquire(&self) -> Result<MobileShareImageLease<'_>, MobileShareImageError> {
+ self.busy
+ .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
+ .map_err(|_| MobileShareImageError::new("busy", "Another image action is active"))?;
+ Ok(MobileShareImageLease(&self.busy))
+ }
+}
+
+impl Drop for MobileShareImageLease<'_> {
+ fn drop(&mut self) {
+ self.0.store(false, Ordering::Release);
+ }
+}
+
+pub fn validate_payload(
+ payload: MobileShareImagePayload,
+) -> Result<ValidatedMobileShareImage, MobileShareImageError> {
+ if !valid_attempt_id(&payload.attempt_id) {
+ return Err(MobileShareImageError::new(
+ "invalid_png",
+ "Invalid attempt identifier",
+ ));
+ }
+ let max_encoded = MAX_PNG_BYTES.div_ceil(3) * 4;
+ if payload.png_base64.is_empty() || payload.png_base64.len() % 4 != 0 {
+ return Err(MobileShareImageError::new(
+ "invalid_png",
+ "Image payload is not valid base64",
+ ));
+ }
+ if payload.png_base64.len() > max_encoded {
+ return Err(MobileShareImageError::new(
+ "image_too_large",
+ "Image exceeds the mobile limit",
+ ));
+ }
+ let bytes = STANDARD
+ .decode(payload.png_base64.as_bytes())
+ .map_err(|_| {
+ MobileShareImageError::new("invalid_png", "Image payload is not valid base64")
+ })?;
+ if bytes.is_empty() {
+ return Err(MobileShareImageError::new(
+ "invalid_png",
+ "Image payload is empty",
+ ));
+ }
+ if bytes.len() > MAX_PNG_BYTES {
+ return Err(MobileShareImageError::new(
+ "image_too_large",
+ "Image exceeds the mobile limit",
+ ));
+ }
+ validate_png(&bytes)?;
+ Ok(ValidatedMobileShareImage {
+ attempt_id: payload.attempt_id,
+ png_base64: payload.png_base64,
+ filename: sanitize_filename(payload.filename.as_deref().unwrap_or_default()),
+ })
+}
+
+fn valid_attempt_id(value: &str) -> bool {
+ let bytes = value.as_bytes();
+ bytes.len() == 36
+ && [8, 13, 18, 23]
+ .into_iter()
+ .all(|index| bytes[index] == b'-')
+ && bytes.iter().enumerate().all(|(index, byte)| {
+ [8, 13, 18, 23].contains(&index)
+ || byte.is_ascii_digit()
+ || (b'a'..=b'f').contains(byte)
+ })
+ && bytes[14] == b'4'
+ && matches!(bytes[19], b'8' | b'9' | b'a' | b'b')
+}
+
+fn validate_png(bytes: &[u8]) -> Result<(), MobileShareImageError> {
+ const SIGNATURE: &[u8; 8] = b"\x89PNG\r\n\x1a\n";
+ if bytes.get(..8) != Some(SIGNATURE) {
+ return Err(invalid_png());
+ }
+ let mut offset = 8usize;
+ let mut ihdr = false;
+ let mut idat = false;
+ let mut iend = false;
+ while offset < bytes.len() {
+ let header_end = offset.checked_add(8).ok_or_else(invalid_png)?;
+ let header = bytes.get(offset..header_end).ok_or_else(invalid_png)?;
+ let length =
+ u32::from_be_bytes(header[..4].try_into().map_err(|_| invalid_png())?) as usize;
+ let chunk_type: [u8; 4] = header[4..8].try_into().map_err(|_| invalid_png())?;
+ let data_end = header_end.checked_add(length).ok_or_else(invalid_png)?;
+ let chunk_end = data_end.checked_add(4).ok_or_else(invalid_png)?;
+ let data = bytes.get(header_end..data_end).ok_or_else(invalid_png)?;
+ if chunk_end > bytes.len() || iend {
+ return Err(invalid_png());
+ }
+ match &chunk_type {
+ b"IHDR" => {
+ if ihdr || offset != 8 || length != 13 {
+ return Err(invalid_png());
+ }
+ ihdr = true;
+ let width = u32::from_be_bytes(data[..4].try_into().map_err(|_| invalid_png())?);
+ let height = u32::from_be_bytes(data[4..8].try_into().map_err(|_| invalid_png())?);
+ let pixels = u64::from(width)
+ .checked_mul(u64::from(height))
+ .ok_or_else(invalid_png)?;
+ if width == 0
+ || height == 0
+ || width > MAX_DIMENSION
+ || height > MAX_DIMENSION
+ || pixels > MAX_PIXELS
+ {
+ return Err(invalid_png());
+ }
+ let bit_depth = data[8];
+ let color_type = data[9];
+ let legal = matches!(
+ (color_type, bit_depth),
+ (0, 1 | 2 | 4 | 8 | 16)
+ | (2, 8 | 16)
+ | (3, 1 | 2 | 4 | 8)
+ | (4, 8 | 16)
+ | (6, 8 | 16)
+ );
+ if !legal || data[10] != 0 || data[11] != 0 || data[12] > 1 {
+ return Err(invalid_png());
+ }
+ }
+ b"IDAT" => {
+ if !ihdr || iend {
+ return Err(invalid_png());
+ }
+ idat = true;
+ }
+ b"IEND" => {
+ if !ihdr || !idat || length != 0 {
+ return Err(invalid_png());
+ }
+ iend = true;
+ if chunk_end != bytes.len() {
+ return Err(invalid_png());
+ }
+ }
+ b"acTL" | b"fcTL" | b"fdAT" => return Err(invalid_png()),
+ _ => {}
+ }
+ offset = chunk_end;
+ }
+ if !iend {
+ return Err(invalid_png());
+ }
+ let mut decoder = png::Decoder::new(Cursor::new(bytes));
+ decoder.ignore_checksums(false);
+ decoder.set_limits(png::Limits {
+ bytes: 80 * 1024 * 1024,
+ });
+ let mut reader = decoder.read_info().map_err(|_| invalid_png())?;
+ let output_size = reader.output_buffer_size().ok_or_else(invalid_png)?;
+ if output_size > MAX_OUTPUT_BYTES {
+ return Err(invalid_png());
+ }
+ let mut output = vec![0; output_size];
+ reader.next_frame(&mut output).map_err(|_| invalid_png())?;
+ reader.finish().map_err(|_| invalid_png())?;
+ Ok(())
+}
+
+fn invalid_png() -> MobileShareImageError {
+ MobileShareImageError::new("invalid_png", "Image payload is not a valid PNG")
+}
+
+pub fn sanitize_filename(value: &str) -> String {
+ let normalized: String = value.nfc().collect();
+ let basename = normalized
+ .rsplit(['/', '\\'])
+ .next()
+ .unwrap_or_default()
+ .trim_start_matches(|character: char| character == '.' || character.is_whitespace());
+ let mut stem = basename
+ .chars()
+ .filter(|character| !character.is_control() && *character != '/' && *character != '\\')
+ .collect::<String>();
+ while stem.to_ascii_lowercase().ends_with(".png") {
+ stem.truncate(stem.len() - 4);
+ }
+ stem = stem.trim().to_string();
+ if stem.is_empty() {
+ stem = "alook-message-share".to_string();
+ }
+ while format!("{stem}.png").len() > 180 {
+ stem.pop();
+ }
+ if stem.is_empty() {
+ "alook-message-share.png".to_string()
+ } else {
+ format!("{stem}.png")
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const ATTEMPT_ID: &str = "123e4567-e89b-42d3-a456-426614174000";
+
+ fn encode_png(width: u32, height: u32) -> Vec<u8> {
+ let mut bytes = Vec::new();
+ {
+ let mut encoder = png::Encoder::new(&mut bytes, width, height);
+ encoder.set_color(png::ColorType::Rgba);
+ encoder.set_depth(png::BitDepth::Eight);
+ let mut writer = encoder.write_header().unwrap();
+ writer
+ .write_image_data(&vec![0; width as usize * height as usize * 4])
+ .unwrap();
+ }
+ bytes
+ }
+
+ fn payload(bytes: Vec<u8>, filename: Option<&str>) -> MobileShareImagePayload {
+ MobileShareImagePayload {
+ attempt_id: ATTEMPT_ID.to_string(),
+ png_base64: STANDARD.encode(bytes),
+ filename: filename.map(str::to_string),
+ }
+ }
+
+ fn crc32(bytes: &[u8]) -> u32 {
+ let mut crc = u32::MAX;
+ for byte in bytes {
+ crc ^= u32::from(*byte);
+ for _ in 0..8 {
+ crc = if crc & 1 == 1 {
+ 0xedb8_8320 ^ (crc >> 1)
+ } else {
+ crc >> 1
+ };
+ }
+ }
+ crc ^ u32::MAX
+ }
+
+ fn rewrite_ihdr(mut bytes: Vec<u8>, change: impl FnOnce(&mut [u8])) -> Vec<u8> {
+ change(&mut bytes[16..29]);
+ let checksum = crc32(&bytes[12..29]).to_be_bytes();
+ bytes[29..33].copy_from_slice(&checksum);
+ bytes
+ }
+
+ fn insert_chunk(mut bytes: Vec<u8>, chunk_type: &[u8; 4], data: &[u8]) -> Vec<u8> {
+ let iend = bytes.len() - 12;
+ let mut chunk = Vec::with_capacity(data.len() + 12);
+ chunk.extend_from_slice(&(data.len() as u32).to_be_bytes());
+ chunk.extend_from_slice(chunk_type);
+ chunk.extend_from_slice(data);
+ chunk.extend_from_slice(&crc32(&chunk[4..]).to_be_bytes());
+ bytes.splice(iend..iend, chunk);
+ bytes
+ }
+
+ fn error_code(payload: MobileShareImagePayload) -> String {
+ validate_payload(payload).unwrap_err().code
+ }
+
+ #[test]
+ fn lease_is_app_wide_and_released() {
+ let state = MobileShareImageState::default();
+ let first = state.acquire().unwrap();
+ assert_eq!(state.acquire().unwrap_err().code, "busy");
+ drop(first);
+ assert!(state.acquire().is_ok());
+ }
+
+ #[test]
+ fn filename_is_normalized_and_bounded_by_utf8_bytes() {
+ assert_eq!(
+ sanitize_filename(" ../a/b/..re\u{301}sume\u{301}.PNG.png"),
+ "résumé.png"
+ );
+ assert_eq!(sanitize_filename("bad\0/name.png"), "name.png");
+ assert_eq!(sanitize_filename("..."), "alook-message-share.png");
+ let value = format!("{}。png", "界".repeat(100));
+ let filename = sanitize_filename(&value);
+ assert!(filename.len() <= 180);
+ assert!(filename.ends_with(".png"));
+ assert_eq!(sanitize_filename(&"a".repeat(175)).len(), 179);
+ assert_eq!(sanitize_filename(&"a".repeat(176)).len(), 180);
+ assert_eq!(sanitize_filename(&"a".repeat(177)).len(), 180);
+ }
+
+ #[test]
+ fn attempt_id_must_be_a_canonical_v4_uuid() {
+ assert!(valid_attempt_id(ATTEMPT_ID));
+ for value in [
+ "123e4567-e89b-12d3-a456-426614174000",
+ "123E4567-E89B-42D3-A456-426614174000",
+ "123e4567-e89b-42d3-c456-426614174000",
+ "bad\nlog",
+ ] {
+ assert!(!valid_attempt_id(value));
+ }
+ }
+
+ #[test]
+ fn accepts_a_complete_png_and_exact_transport_limit() {
+ let valid = encode_png(1, 1);
+ assert!(validate_payload(payload(valid.clone(), Some("card.png"))).is_ok());
+
+ let filler = MAX_PNG_BYTES - valid.len() - 12;
+ let exact = insert_chunk(valid, b"ruSt", &vec![0; filler]);
+ assert_eq!(exact.len(), MAX_PNG_BYTES);
+ assert!(validate_payload(payload(exact, None)).is_ok());
+ }
+
+ #[test]
+ fn validated_payload_retains_every_native_dispatch_field() {
+ let encoded = STANDARD.encode(encode_png(1, 1));
+ let validated = validate_payload(MobileShareImagePayload {
+ attempt_id: ATTEMPT_ID.to_string(),
+ png_base64: encoded.clone(),
+ filename: Some("card".to_string()),
+ })
+ .unwrap();
+
+ assert_eq!(validated.attempt_id, ATTEMPT_ID);
+ assert_eq!(validated.png_base64, encoded);
+ assert_eq!(validated.filename, "card.png");
+ }
+
+ #[test]
+ fn native_result_retains_every_response_field() {
+ let result = MobileShareImageResult {
+ attempt_id: ATTEMPT_ID.to_string(),
+ status: "saved".to_string(),
+ destination: "photos".to_string(),
+ };
+
+ assert_eq!(result.attempt_id, ATTEMPT_ID);
+ assert_eq!(result.status, "saved");
+ assert_eq!(result.destination, "photos");
+ }
+
+ #[test]
+ fn rejects_oversize_invalid_and_noncanonical_base64_before_native_dispatch() {
+ let oversized = STANDARD.encode(vec![0; MAX_PNG_BYTES + 1]);
+ assert_eq!(
+ error_code(MobileShareImagePayload {
+ attempt_id: ATTEMPT_ID.to_string(),
+ png_base64: oversized,
+ filename: None,
+ }),
+ "image_too_large"
+ );
+ for invalid in ["", "AA", "A===", "****", "aGVsbG8="] {
+ assert_eq!(
+ error_code(MobileShareImagePayload {
+ attempt_id: ATTEMPT_ID.to_string(),
+ png_base64: invalid.to_string(),
+ filename: None,
+ }),
+ "invalid_png"
+ );
+ }
+ }
+
+ #[test]
+ fn rejects_malformed_png_structure_and_bounds() {
+ let valid = encode_png(1, 1);
+ let invalid_header_length = {
+ let mut bytes = valid.clone();
+ bytes[11] = 12;
+ bytes
+ };
+ let zero_width = rewrite_ihdr(valid.clone(), |ihdr| ihdr[..4].fill(0));
+ let extreme_width = rewrite_ihdr(valid.clone(), |ihdr| {
+ ihdr[..4].copy_from_slice(&16_385u32.to_be_bytes())
+ });
+ let excessive_pixels = rewrite_ihdr(valid.clone(), |ihdr| {
+ ihdr[..4].copy_from_slice(&4_097u32.to_be_bytes());
+ ihdr[4..8].copy_from_slice(&4_097u32.to_be_bytes());
+ });
+ let invalid_color_depth = rewrite_ihdr(valid.clone(), |ihdr| {
+ ihdr[8] = 1;
+ ihdr[9] = 6;
+ });
+ let invalid_interlace = rewrite_ihdr(valid.clone(), |ihdr| ihdr[12] = 2);
+ let oversized_output = rewrite_ihdr(valid.clone(), |ihdr| {
+ ihdr[..4].copy_from_slice(&4_096u32.to_be_bytes());
+ ihdr[4..8].copy_from_slice(&4_096u32.to_be_bytes());
+ ihdr[8] = 16;
+ ihdr[9] = 6;
+ });
+ for bytes in [
+ invalid_header_length,
+ zero_width,
+ extreme_width,
+ excessive_pixels,
+ invalid_color_depth,
+ invalid_interlace,
+ oversized_output,
+ ] {
+ assert_eq!(error_code(payload(bytes, None)), "invalid_png");
+ }
+ }
+
+ #[test]
+ fn rejects_corruption_animation_truncation_duplicate_end_and_trailing_data() {
+ let valid = encode_png(1, 1);
+ let mut bad_crc = valid.clone();
+ bad_crc[29] ^= 1;
+
+ let mut bad_adler = valid.clone();
+ let idat = bad_adler
+ .windows(4)
+ .position(|window| window == b"IDAT")
+ .unwrap();
+ let idat_length =
+ u32::from_be_bytes(bad_adler[idat - 4..idat].try_into().unwrap()) as usize;
+ bad_adler[idat + 4 + idat_length - 1] ^= 1;
+ let idat_crc = crc32(&bad_adler[idat..idat + 4 + idat_length]).to_be_bytes();
+ bad_adler[idat + 4 + idat_length..idat + 8 + idat_length].copy_from_slice(&idat_crc);
+
+ let animated = insert_chunk(valid.clone(), b"acTL", &[0; 8]);
+ let truncated = valid[..valid.len() - 1].to_vec();
+ let missing_end = valid[..valid.len() - 12].to_vec();
+ let duplicate_end = insert_chunk(valid.clone(), b"IEND", &[]);
+ let mut trailing = valid;
+ trailing.push(0);
+ for bytes in [
+ bad_crc,
+ bad_adler,
+ animated,
+ truncated,
+ missing_end,
+ duplicate_end,
+ trailing,
+ ] {
+ assert_eq!(error_code(payload(bytes, None)), "invalid_png");
+ }
+ }
+}
diff --git a/src/desktop/src-tauri/src/mobile_share_image_runtime.rs b/src/desktop/src-tauri/src/mobile_share_image_runtime.rs
new file mode 100644
index 000000000..4d8cf7649
--- /dev/null
+++ b/src/desktop/src-tauri/src/mobile_share_image_runtime.rs
@@ -0,0 +1,114 @@
+use crate::mobile_share_image::{
+ validate_payload, MobileShareImageError, MobileShareImagePayload, MobileShareImageResult,
+ MobileShareImageState,
+};
+use crate::native_command_guard::guard;
+use std::sync::OnceLock;
+use std::time::Instant;
+use tauri::{Manager, WebviewWindow};
+use tauri_plugin_mobile_share_image::{CopyRequest, MobileShareImageExt, SaveRequest};
+
+fn monotonic_micros() -> u128 {
+ static START: OnceLock<Instant> = OnceLock::new();
+ START.get_or_init(Instant::now).elapsed().as_micros()
+}
+
+#[tauri::command]
+pub async fn mobile_share_image_save(
+ window: WebviewWindow,
+ state: tauri::State<'_, MobileShareImageState>,
+ payload: MobileShareImagePayload,
+) -> Result<MobileShareImageResult, MobileShareImageError> {
+ guard(&window).map_err(|code| MobileShareImageError::new(code, "Caller is not trusted"))?;
+ let _lease = state.acquire()?;
+ let payload = validate_payload(payload)?;
+ if cfg!(debug_assertions) {
+ eprintln!(
+ "mobile-share-image app-rust dispatch attempt={} t={}",
+ payload.attempt_id,
+ monotonic_micros()
+ );
+ }
+ let result = window
+ .app_handle()
+ .mobile_share_image()
+ .save(SaveRequest {
+ attempt_id: payload.attempt_id.clone(),
+ png_base64: payload.png_base64,
+ filename: payload.filename,
+ })
+ .await
+ .map_err(|error| MobileShareImageError::new(&error.code, error.message))?;
+ if result.attempt_id != payload.attempt_id
+ || result.status != "saved"
+ || !matches!(
+ result.destination.as_str(),
+ "pictures" | "document" | "photos"
+ )
+ {
+ return Err(MobileShareImageError::new(
+ "write_failed",
+ "Native image result did not match the request",
+ ));
+ }
+ if cfg!(debug_assertions) {
+ eprintln!(
+ "mobile-share-image app-rust settle attempt={} t={}",
+ result.attempt_id,
+ monotonic_micros()
+ );
+ }
+ Ok(MobileShareImageResult {
+ attempt_id: result.attempt_id,
+ status: result.status,
+ destination: result.destination,
+ })
+}
+
+#[tauri::command]
+pub async fn mobile_share_image_copy(
+ window: WebviewWindow,
+ state: tauri::State<'_, MobileShareImageState>,
+ payload: MobileShareImagePayload,
+) -> Result<MobileShareImageResult, MobileShareImageError> {
+ guard(&window).map_err(|code| MobileShareImageError::new(code, "Caller is not trusted"))?;
+ let _lease = state.acquire()?;
+ let payload = validate_payload(payload)?;
+ if cfg!(debug_assertions) {
+ eprintln!(
+ "mobile-share-image app-rust dispatch attempt={} t={}",
+ payload.attempt_id,
+ monotonic_micros()
+ );
+ }
+ let result = window
+ .app_handle()
+ .mobile_share_image()
+ .copy(CopyRequest {
+ attempt_id: payload.attempt_id.clone(),
+ png_base64: payload.png_base64,
+ })
+ .await
+ .map_err(|error| MobileShareImageError::new(&error.code, error.message))?;
+ if result.attempt_id != payload.attempt_id
+ || result.status != "copied"
+ || result.destination != "clipboard"
+ {
+ return Err(MobileShareImageError::new(
+ "write_failed",
+ "Native image result did not match the request",
+ ));
+ }
+ if cfg!(debug_assertions) {
+ eprintln!(
+ "mobile-share-image app-rust settle attempt={} t={}",
+ result.attempt_id,
+ monotonic_micros()
+ );
+ }
+ Ok(MobileShareImageResult {
+ attempt_id: result.attempt_id,
+ status: result.status,
+ destination: result.destination,
+ })
+}
diff --git a/src/desktop/src-tauri/src/native_command_guard.rs b/src/desktop/src-tauri/src/native_command_guard.rs
new file mode 100644
index 000000000..df4a8590e
--- /dev/null
+++ b/src/desktop/src-tauri/src/native_command_guard.rs
@@ -0,0 +1,56 @@
+use tauri::WebviewWindow;
+
+pub fn caller_allowed(label: &str, url: &url::Url, debug: bool) -> bool {
+ let expected = if debug {
+ "http://localhost:3000"
+ } else {
+ "https://alook.ai"
+ };
+ label == "main"
+ && url.origin().ascii_serialization() == expected
+ && url.username().is_empty()
+ && url.password().is_none()
+}
+
+pub fn guard(window: &WebviewWindow) -> Result<(), &'static str> {
+ let url = window.url().map_err(|_| "untrusted_caller")?;
+ if caller_allowed(window.label(), &url, cfg!(debug_assertions)) {
+ Ok(())
+ } else {
+ Err("untrusted_caller")
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::caller_allowed;
+
+ #[test]
+ fn accepts_only_the_main_window_and_exact_origin() {
+ assert!(caller_allowed(
+ "main",
+ &url::Url::parse("https://alook.ai/c").unwrap(),
+ false,
+ ));
+ assert!(caller_allowed(
+ "main",
+ &url::Url::parse("http://localhost:3000/c").unwrap(),
+ true,
+ ));
+ assert!(!caller_allowed(
+ "other",
+ &url::Url::parse("https://alook.ai/c").unwrap(),
+ false,
+ ));
+ assert!(!caller_allowed(
+ "main",
+ &url::Url::parse("https://alook.ai.evil.example/c").unwrap(),
+ false,
+ ));
+ assert!(!caller_allowed(
+ "main",
+ &url::Url::parse("https://[email protected]/c").unwrap(),
+ false,
+ ));
+ }
+}
diff --git a/src/desktop/src-tauri/src/native_oauth_runtime.rs b/src/desktop/src-tauri/src/native_oauth_runtime.rs
index 23a883de3..4d0ac427f 100644
--- a/src/desktop/src-tauri/src/native_oauth_runtime.rs
+++ b/src/desktop/src-tauri/src/native_oauth_runtime.rs
@@ -1,3 +1,4 @@
+use crate::native_command_guard::guard;
use crate::native_oauth::{Exchange, Proof, Record, Registration, Snapshot};
use std::sync::{Arc, Mutex};
use tauri::{ipc::Channel, AppHandle, Manager, WebviewWindow};
@@ -50,27 +51,6 @@ fn now() -> u64 {
.as_millis() as u64
}
-fn caller_allowed(label: &str, url: &url::Url, debug: bool) -> bool {
- let expected = if debug {
- "http://localhost:3000"
- } else {
- "https://alook.ai"
- };
- label == "main"
- && url.origin().ascii_serialization() == expected
- && url.username().is_empty()
- && url.password().is_none()
-}
-
-fn guard(window: &WebviewWindow) -> Result<(), &'static str> {
- let url = window.url().map_err(|_| "untrusted_caller")?;
- if caller_allowed(window.label(), &url, cfg!(debug_assertions)) {
- Ok(())
- } else {
- Err("untrusted_caller")
- }
-}
-
fn commit_record<T>(
current: &mut Record,
time: u64,
@@ -311,6 +291,7 @@ pub fn native_oauth_cancel(
#[cfg(test)]
mod tests {
use super::*;
+ use crate::native_command_guard::caller_allowed;
#[test]
fn durable_commit_precedes_proof_release_and_notification() {
let time = 1_000_000;
diff --git a/src/desktop/src-tauri/tauri.conf.json b/src/desktop/src-tauri/tauri.conf.json
index 2df30be84..dd7cb9aaa 100644
--- a/src/desktop/src-tauri/tauri.conf.json
+++ b/src/desktop/src-tauri/tauri.conf.json
@@ -48,7 +48,8 @@
"desktop-capability",
"external-links",
"native-oauth",
- "native-oauth-mobile"
+ "native-oauth-mobile",
+ "mobile-share-image-mobile"
]
}
},
diff --git a/src/desktop/src-tauri/tauri.dev.conf.json b/src/desktop/src-tauri/tauri.dev.conf.json
index 6fd00aeb0..1c6fd2074 100644
--- a/src/desktop/src-tauri/tauri.dev.conf.json
+++ b/src/desktop/src-tauri/tauri.dev.conf.json
@@ -28,6 +28,28 @@
"permissions": [
"native-oauth"
]
+ },
+ {
+ "$schema": "../gen/schemas/desktop-schema.json",
+ "identifier": "mobile-share-image-dev",
+ "description": "Native mobile image copy and save for the trusted development WebView",
+ "windows": [
+ "main"
+ ],
+ "platforms": [
+ "android",
+ "iOS"
+ ],
+ "local": true,
+ "remote": {
+ "urls": [
+ "http://localhost:3000"
+ ]
+ },
+ "permissions": [
+ "allow-mobile-share-image-copy",
+ "allow-mobile-share-image-save"
+ ]
}
]
}
diff --git a/src/web/src/components/community/messages/message-share-dialog.dom.test.ts b/src/web/src/components/community/messages/message-share-dialog.dom.test.ts
index 85b082eaf..a7e5ed519 100644
--- a/src/web/src/components/community/messages/message-share-dialog.dom.test.ts
+++ b/src/web/src/components/community/messages/message-share-dialog.dom.test.ts
@@ -1252,7 +1252,31 @@ describe("MessageShareDialog action feedback", () => {
}
}
+ function setupMobileActionEnvironment(invoke: ReturnType<typeof vi.fn>) {
+ Object.defineProperty(window, "__TAURI__", {
+ configurable: true,
+ value: { core: { invoke } },
+ })
+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue("iPhone")
+ Object.defineProperty(document, "fonts", {
+ configurable: true,
+ value: { ready: Promise.resolve() },
+ })
+ vi.stubGlobal("getComputedStyle", vi.fn(() => ({
+ getPropertyValue: vi.fn(() => ""),
+ })))
+ const renderer = renderMessage(message())
+ const copyButton = actionButton(tid.messageShareCopy)
+ const saveButton = actionButton(tid.messageShareSave)
+ const dialog = capturedNode(
+ componentMocks.dialogProps,
+ (props) => typeof props.onOpenChange === "function",
+ )
+ return { copyButton, dialog, renderer, saveButton }
+ }
+
afterEach(() => {
+ Reflect.deleteProperty(window, "__TAURI__")
vi.mocked(toBlob).mockReset()
vi.mocked(toast.success).mockReset()
vi.mocked(toast.error).mockReset()
@@ -1260,6 +1284,147 @@ describe("MessageShareDialog action feedback", () => {
vi.unstubAllGlobals()
})
+ it("routes mobile copy and shows success only after the native terminal receipt", async () => {
+ const native = deferred<Record<string, unknown>>()
+ const invoke = vi.fn(() => native.promise)
+ vi.mocked(toBlob).mockResolvedValue(new Blob(["png"], { type: "image/png" }))
+ const harness = setupMobileActionEnvironment(invoke)
+ let copy!: Promise<void>
+
+ act(() => { copy = harness.copyButton.props.onClick() })
+ await vi.waitFor(() => expect(invoke).toHaveBeenCalledOnce())
+ expect(invoke.mock.calls[0]![0]).toBe("mobile_share_image_copy")
+ expect(harness.copyButton.props.disabled).toBe(true)
+ expect(harness.saveButton.props.disabled).toBe(true)
+ expect(toast.success).not.toHaveBeenCalled()
+ const attemptId = (invoke.mock.calls[0]![1] as {
+ payload: { attemptId: string }
+ }).payload.attemptId
+
+ await act(async () => {
+ native.resolve({ attemptId, status: "copied", destination: "clipboard" })
+ await copy
+ })
+
+ expect(toast.success).toHaveBeenCalledWith("Image copied to clipboard")
+ expect(toast.error).not.toHaveBeenCalled()
+ expect(harness.copyButton.children).toContain("Copied")
+ })
+
+ it.each([
+ ["photos", "Saved to Photos"],
+ ["pictures", "Saved to Pictures/Alook"],
+ ["document", "Image saved"],
+ ] as const)("maps mobile %s receipt to exact save feedback", async (destination, feedback) => {
+ const invoke = vi.fn(async (_command: string, args: {
+ payload: { attemptId: string; filename: string }
+ }) => ({
+ attemptId: args.payload.attemptId,
+ status: "saved",
+ destination,
+ }))
+ vi.mocked(toBlob).mockResolvedValue(new Blob(["png"], { type: "image/png" }))
+ const harness = setupMobileActionEnvironment(invoke)
+
+ await act(async () => { await harness.saveButton.props.onClick() })
+
+ expect(invoke).toHaveBeenCalledOnce()
+ expect(invoke.mock.calls[0]![0]).toBe("mobile_share_image_save")
+ expect((invoke.mock.calls[0]![1] as {
+ payload: { filename: string }
+ }).payload.filename).toBe("alook-message-Alice.png")
+ expect(toast.success).toHaveBeenCalledWith(feedback)
+ expect(toast.error).not.toHaveBeenCalled()
+ })
+
+ it("keeps mobile cancellation silent and re-enables both actions", async () => {
+ const invoke = vi.fn().mockRejectedValue({ code: "cancelled", message: "cancelled" })
+ vi.mocked(toBlob).mockResolvedValue(new Blob(["png"], { type: "image/png" }))
+ const harness = setupMobileActionEnvironment(invoke)
+
+ await act(async () => { await harness.saveButton.props.onClick() })
+
+ expect(toast.success).not.toHaveBeenCalled()
+ expect(toast.error).not.toHaveBeenCalled()
+ expect(harness.copyButton.props.disabled).toBe(false)
+ expect(harness.saveButton.props.disabled).toBe(false)
+ })
+
+ it("shows mobile Photos denial and oversize failures without success", async () => {
+ const invoke = vi.fn().mockRejectedValue({
+ code: "permission_denied",
+ message: "denied",
+ })
+ vi.mocked(toBlob).mockResolvedValue(new Blob(["png"], { type: "image/png" }))
+ let harness = setupMobileActionEnvironment(invoke)
+
+ await act(async () => { await harness.saveButton.props.onClick() })
+ expect(toast.error).toHaveBeenCalledWith(
+ "Couldn't save image — allow Photos access in Settings",
+ )
+ expect(toast.success).not.toHaveBeenCalled()
+
+ act(() => harness.renderer.unmount())
+ vi.mocked(toast.error).mockReset()
+ vi.mocked(toBlob).mockResolvedValue({
+ type: "image/png",
+ size: 10 * 1024 * 1024 + 1,
+ } as Blob)
+ harness = setupMobileActionEnvironment(vi.fn())
+ await act(async () => { await harness.copyButton.props.onClick() })
+ expect(toast.error).toHaveBeenCalledWith("Image is too large — select fewer messages")
+ expect(toast.success).not.toHaveBeenCalled()
+ })
+
+ it("keeps the first mobile action as sole native owner during overlap", async () => {
+ const native = deferred<Record<string, unknown>>()
+ const invoke = vi.fn(() => native.promise)
+ vi.mocked(toBlob).mockResolvedValue(new Blob(["png"], { type: "image/png" }))
+ const harness = setupMobileActionEnvironment(invoke)
+ let copy!: Promise<void>
+ let save!: Promise<void>
+
+ act(() => {
+ copy = harness.copyButton.props.onClick()
+ save = harness.saveButton.props.onClick()
+ })
+
+ expect(save).toBe(copy)
+ await vi.waitFor(() => expect(invoke).toHaveBeenCalledOnce())
+ expect(invoke.mock.calls[0]![0]).toBe("mobile_share_image_copy")
+ const attemptId = (invoke.mock.calls[0]![1] as {
+ payload: { attemptId: string }
+ }).payload.attemptId
+ await act(async () => {
+ native.resolve({ attemptId, status: "copied", destination: "clipboard" })
+ await copy
+ })
+ expect(toast.success).toHaveBeenCalledOnce()
+ })
+
+ it("suppresses late mobile feedback when closed after native invocation", async () => {
+ const native = deferred<Record<string, unknown>>()
+ const invoke = vi.fn(() => native.promise)
+ vi.mocked(toBlob).mockResolvedValue(new Blob(["png"], { type: "image/png" }))
+ const harness = setupMobileActionEnvironment(invoke)
+ let save!: Promise<void>
+
+ act(() => { save = harness.saveButton.props.onClick() })
+ await vi.waitFor(() => expect(invoke).toHaveBeenCalledOnce())
+ act(() => harness.dialog.props.onOpenChange(false))
+ const attemptId = (invoke.mock.calls[0]![1] as {
+ payload: { attemptId: string }
+ }).payload.attemptId
+ await act(async () => {
+ native.resolve({ attemptId, status: "saved", destination: "photos" })
+ await save
+ })
+
+ expect(toast.success).not.toHaveBeenCalled()
+ expect(toast.error).not.toHaveBeenCalled()
+ expect(harness.copyButton.props.disabled).toBe(false)
+ })
+
it("confirms a completed image download", async () => {
const blob = new Blob(["png"], { type: "image/png" })
const click = vi.fn()
diff --git a/src/web/src/components/community/messages/message-share-dialog.tsx b/src/web/src/components/community/messages/message-share-dialog.tsx
index ca89332c8..bc01a8021 100644
--- a/src/web/src/components/community/messages/message-share-dialog.tsx
+++ b/src/web/src/components/community/messages/message-share-dialog.tsx
@@ -6,7 +6,7 @@ import { toBlob } from "html-to-image"
import { toast } from "sonner"
import { Check, Copy, Download, Highlighter, Loader2 } from "lucide-react"
import { writeImage } from "@tauri-apps/plugin-clipboard-manager"
-import { isDesktop, isTauri, stripInlineMarkup } from "@alook/shared"
+import { isDesktop, isMobile, isTauri, stripInlineMarkup } from "@alook/shared"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Avatar } from "../avatar"
@@ -458,6 +458,14 @@ export async function renderShareCard(
type ShareCardRenderer = () => Promise<Blob | null>
type ShareCardBlobWriter = (blob: Blob) => Promise<void> | void
+function mobileShareImageErrorCode(error: unknown): string | null {
+ if (typeof error !== "object" || error === null) return null
+ const value = error as { name?: unknown; code?: unknown }
+ return value.name === "MobileShareImageError" && typeof value.code === "string"
+ ? value.code
+ : null
+}
+
export async function writeShareCardToClipboard(blob: Blob): Promise<void> {
if (isTauri() && isDesktop()) {
await writeImage(await blob.arrayBuffer())
@@ -543,6 +551,7 @@ export function MessageShareDialog({ m, open, onClose }: {
onClose: () => void
}) {
const messages = useMemo(() => (Array.isArray(m) ? m : [m]), [m])
+ const mobileNative = isTauri() && isMobile()
const profilesByUserId = useProfilesByUserId()
const cardRef = useRef<HTMLDivElement>(null)
// One body wrapper per message — highlight operations are scoped to the body
@@ -643,8 +652,18 @@ export function MessageShareDialog({ m, open, onClose }: {
})
if (!isCurrent()) return
- if (action === "copy") await writeShareCardToClipboard(blob)
- else await saveShareCardDownload(blob, filename)
+ let mobileDestination: "photos" | "pictures" | "document" | null = null
+ if (action === "copy") {
+ if (mobileNative) {
+ const { copyMobileShareImage } = await import("@/lib/community/mobile-share-image")
+ if (!isCurrent()) return
+ await copyMobileShareImage(blob)
+ } else await writeShareCardToClipboard(blob)
+ } else if (mobileNative) {
+ const { saveMobileShareImage } = await import("@/lib/community/mobile-share-image")
+ if (!isCurrent()) return
+ mobileDestination = (await saveMobileShareImage(blob, filename)).destination
+ } else await saveShareCardDownload(blob, filename)
if (!isCurrent()) return
if (action === "copy") {
@@ -655,14 +674,37 @@ export function MessageShareDialog({ m, open, onClose }: {
copiedTimerRef.current = null
setCopied(false)
}, 1600)
+ } else if (mobileDestination === "photos") {
+ toast.success("Saved to Photos")
+ } else if (mobileDestination === "pictures") {
+ toast.success("Saved to Pictures/Alook")
+ } else if (mobileDestination === "document") {
+ toast.success("Image saved")
} else {
toast.success("Image downloaded")
}
} catch (error) {
if (!isCurrent()) return
+ const mobileErrorCode = mobileShareImageErrorCode(error)
+ if (mobileErrorCode === "cancelled") return
+ if (mobileErrorCode === "image_too_large") {
+ toast.error("Image is too large — select fewer messages")
+ return
+ }
+ if (
+ action === "download"
+ && mobileErrorCode === "permission_denied"
+ ) {
+ toast.error("Couldn't save image — allow Photos access in Settings")
+ return
+ }
toast.error(
shareCardRenderErrorMessage(error)
- ?? (action === "copy" ? "Couldn't copy image — try Download instead" : "Couldn't generate image"),
+ ?? (action === "copy"
+ ? mobileNative
+ ? "Couldn't copy image — try Save image instead"
+ : "Couldn't copy image — try Download instead"
+ : mobileNative ? "Couldn't save image" : "Couldn't generate image"),
)
} finally {
if (exportOwnerRef.current.active?.id !== id) return
@@ -672,7 +714,7 @@ export function MessageShareDialog({ m, open, onClose }: {
})()
return flight.promise
- }, [messages, profilesByUserId])
+ }, [messages, mobileNative, profilesByUserId])
const close = useCallback(() => {
invalidateExport()
@@ -875,19 +917,25 @@ export function MessageShareDialog({ m, open, onClose }: {
)}
</div>
<div className="flex gap-2">
- <Button variant="ghost" size="sm" onClick={download} disabled={busy !== null}>
- {busy === "download" ? <Loader2 className="animate-spin" /> : <Download />}
- Download
- </Button>
- <Button
- size="sm"
- data-testid={tid.messageShareCopy}
- onClick={copy}
- disabled={busy !== null}
- >
- {busy === "copy" ? <Loader2 className="animate-spin" /> : copied ? <Check /> : <Copy />}
- {copied ? "Copied" : "Copy image"}
- </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ data-testid={mobileNative ? tid.messageShareSave : undefined}
+ onClick={download}
+ disabled={busy !== null}
+ >
+ {busy === "download" ? <Loader2 className="animate-spin" /> : <Download />}
+ {mobileNative ? "Save image" : "Download"}
+ </Button>
+ <Button
+ size="sm"
+ data-testid={tid.messageShareCopy}
+ onClick={copy}
+ disabled={busy !== null}
+ >
+ {busy === "copy" ? <Loader2 className="animate-spin" /> : copied ? <Check /> : <Copy />}
+ {copied ? "Copied" : "Copy image"}
+ </Button>
</div>
</div>
</DialogContent>
diff --git a/src/web/src/lib/community/mobile-share-image.test.ts b/src/web/src/lib/community/mobile-share-image.test.ts
new file mode 100644
index 000000000..f30286231
--- /dev/null
+++ b/src/web/src/lib/community/mobile-share-image.test.ts
@@ -0,0 +1,183 @@
+import { afterEach, describe, expect, it, vi } from "vitest"
+import { tauriInvoke } from "@alook/shared"
+import {
+ MOBILE_SHARE_IMAGE_CHUNK_BYTES,
+ MOBILE_SHARE_IMAGE_MAX_BYTES,
+ MobileShareImageError,
+ copyMobileShareImage,
+ encodeMobileShareImageBytes,
+ saveMobileShareImage,
+} from "./mobile-share-image"
+
+vi.mock("@alook/shared", () => ({ tauriInvoke: vi.fn() }))
+
+function bytes(length: number): Uint8Array {
+ return Uint8Array.from({ length }, (_, index) => index % 251)
+}
+
+function decode(value: string): Uint8Array {
+ return Uint8Array.from(atob(value), character => character.charCodeAt(0))
+}
+
+describe("mobile share image transport", () => {
+ afterEach(() => {
+ vi.mocked(tauriInvoke).mockReset()
+ vi.restoreAllMocks()
+ })
+
+ it.each([
+ 1,
+ 2,
+ 3,
+ MOBILE_SHARE_IMAGE_CHUNK_BYTES - 1,
+ MOBILE_SHARE_IMAGE_CHUNK_BYTES,
+ MOBILE_SHARE_IMAGE_CHUNK_BYTES + 1,
+ MOBILE_SHARE_IMAGE_CHUNK_BYTES * 2 - 1,
+ MOBILE_SHARE_IMAGE_CHUNK_BYTES * 2,
+ MOBILE_SHARE_IMAGE_CHUNK_BYTES * 2 + 1,
+ ])("round trips %i bytes with final-chunk-only padding", (length) => {
+ const source = bytes(length)
+ const encoded = encodeMobileShareImageBytes(source)
+ expect(decode(encoded)).toEqual(source)
+ expect(encoded.slice(0, -4)).not.toContain("=")
+ })
+
+ it("routes copy through the mobile command with one canonical request", async () => {
+ vi.mocked(tauriInvoke).mockImplementation(async (command, args) => {
+ const payload = (args as { payload: { attemptId: string; pngBase64: string } }).payload
+ expect(command).toBe("mobile_share_image_copy")
+ expect(payload.attemptId).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/)
+ expect(decode(payload.pngBase64)).toEqual(bytes(7))
+ return {
+ attemptId: payload.attemptId,
+ status: "copied",
+ destination: "clipboard",
+ }
+ })
+
+ await expect(
+ copyMobileShareImage(new Blob([bytes(7)], { type: "image/png" })),
+ ).resolves.toMatchObject({ status: "copied", destination: "clipboard" })
+ expect(tauriInvoke).toHaveBeenCalledOnce()
+ })
+
+ it("routes save with the exact filename and accepts the 10 MiB boundary", async () => {
+ const arrayBuffer = vi.fn(async () => bytes(3).buffer)
+ const blob = {
+ type: "image/png",
+ size: MOBILE_SHARE_IMAGE_MAX_BYTES,
+ arrayBuffer,
+ } as Blob
+ vi.mocked(tauriInvoke).mockImplementation(async (command, args) => {
+ const payload = (args as {
+ payload: { attemptId: string; filename: string; pngBase64: string }
+ }).payload
+ expect(command).toBe("mobile_share_image_save")
+ expect(payload.filename).toBe("card.png")
+ expect(decode(payload.pngBase64)).toEqual(bytes(3))
+ return {
+ attemptId: payload.attemptId,
+ status: "saved",
+ destination: "photos",
+ }
+ })
+
+ await expect(saveMobileShareImage(blob, "card.png")).resolves.toMatchObject({
+ status: "saved",
+ destination: "photos",
+ })
+ expect(arrayBuffer).toHaveBeenCalledOnce()
+ expect(tauriInvoke).toHaveBeenCalledOnce()
+ })
+
+ it("waits for the matching native terminal result", async () => {
+ let resolve!: (value: unknown) => void
+ vi.mocked(tauriInvoke).mockReturnValue(new Promise(resolvePromise => {
+ resolve = resolvePromise
+ }))
+ vi.spyOn(crypto, "getRandomValues").mockImplementation((value) => {
+ const output = value as Uint8Array
+ output.fill(7)
+ return value
+ })
+ const pending = saveMobileShareImage(new Blob([bytes(32)], { type: "image/png" }), "card.png")
+ let settled = false
+ void pending.finally(() => { settled = true })
+ await vi.waitFor(() => expect(tauriInvoke).toHaveBeenCalledOnce())
+ expect(settled).toBe(false)
+ const call = vi.mocked(tauriInvoke).mock.calls[0]!
+ const id = (call[1] as { payload: { attemptId: string } }).payload.attemptId
+ resolve({ attemptId: id, status: "saved", destination: "pictures" })
+ await expect(pending).resolves.toEqual({ attemptId: id, status: "saved", destination: "pictures" })
+ })
+
+ it.each([
+ ["empty PNG", { type: "image/png", size: 0 }, "invalid_png"],
+ ["wrong MIME", { type: "image/jpeg", size: 1 }, "invalid_png"],
+ [
+ "oversize PNG",
+ { type: "image/png", size: MOBILE_SHARE_IMAGE_MAX_BYTES + 1 },
+ "image_too_large",
+ ],
+ ])("rejects %s before reading bytes or invoking IPC", async (_label, fields, code) => {
+ const arrayBuffer = vi.fn(async () => bytes(1).buffer)
+ const blob = { ...fields, arrayBuffer } as Blob
+
+ await expect(saveMobileShareImage(blob, "card.png")).rejects.toMatchObject({ code })
+ expect(arrayBuffer).not.toHaveBeenCalled()
+ expect(tauriInvoke).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ [{ attemptId: "wrong", status: "saved", destination: "pictures" }],
+ [{ attemptId: null, status: "saved", destination: "pictures" }],
+ [{ status: "copied", destination: "clipboard" }],
+ [{ attemptId: "wrong", status: "copied", destination: "clipboard" }],
+ ])("rejects a mismatched native terminal result %#", async (result) => {
+ vi.mocked(tauriInvoke).mockResolvedValue(result)
+ const operation = result.status === "copied"
+ ? copyMobileShareImage(new Blob([bytes(4)], { type: "image/png" }))
+ : saveMobileShareImage(new Blob([bytes(4)], { type: "image/png" }), "card.png")
+
+ await expect(operation).rejects.toEqual(
+ new MobileShareImageError("write_failed", "Native image result did not match the request"),
+ )
+ expect(tauriInvoke).toHaveBeenCalledOnce()
+ })
+
+ it("preserves a stable native rejection code and never retries", async () => {
+ vi.mocked(tauriInvoke).mockRejectedValue({ code: "cancelled", message: "cancelled" })
+ await expect(
+ saveMobileShareImage(new Blob([bytes(4)], { type: "image/png" }), "card.png"),
+ ).rejects.toEqual(new MobileShareImageError("cancelled", "cancelled"))
+ expect(tauriInvoke).toHaveBeenCalledOnce()
+ })
+
+ it.each([
+ "untrusted_caller",
+ "invalid_png",
+ "image_too_large",
+ "busy",
+ "permission_denied",
+ "cancelled",
+ "write_failed",
+ "unavailable",
+ ] as const)("preserves native %s failures", async (code) => {
+ vi.mocked(tauriInvoke).mockRejectedValue({ code })
+
+ await expect(
+ copyMobileShareImage(new Blob([bytes(4)], { type: "image/png" })),
+ ).rejects.toEqual(new MobileShareImageError(code, "Native image operation failed"))
+ expect(tauriInvoke).toHaveBeenCalledOnce()
+ })
+
+ it("maps unknown bridge failures to unavailable", async () => {
+ vi.mocked(tauriInvoke).mockRejectedValue(new Error("bridge exploded"))
+
+ await expect(
+ copyMobileShareImage(new Blob([bytes(4)], { type: "image/png" })),
+ ).rejects.toEqual(
+ new MobileShareImageError("unavailable", "Native image operation is unavailable"),
+ )
+ })
+})
diff --git a/src/web/src/lib/community/mobile-share-image.ts b/src/web/src/lib/community/mobile-share-image.ts
new file mode 100644
index 000000000..ffce776a2
--- /dev/null
+++ b/src/web/src/lib/community/mobile-share-image.ts
@@ -0,0 +1,139 @@
+import { tauriInvoke } from "@alook/shared"
+
+export const MOBILE_SHARE_IMAGE_MAX_BYTES = 10 * 1024 * 1024
+export const MOBILE_SHARE_IMAGE_CHUNK_BYTES = 49_152
+
+export type MobileShareImageErrorCode =
+ | "untrusted_caller"
+ | "invalid_png"
+ | "image_too_large"
+ | "busy"
+ | "permission_denied"
+ | "cancelled"
+ | "write_failed"
+ | "unavailable"
+
+export class MobileShareImageError extends Error {
+ constructor(readonly code: MobileShareImageErrorCode, message: string) {
+ super(message)
+ this.name = "MobileShareImageError"
+ }
+}
+
+export type MobileShareImageCopyResult = {
+ attemptId: string
+ status: "copied"
+ destination: "clipboard"
+}
+
+export type MobileShareImageSaveResult = {
+ attemptId: string
+ status: "saved"
+ destination: "photos" | "pictures" | "document"
+}
+
+function attemptId(): string {
+ const bytes = new Uint8Array(16)
+ crypto.getRandomValues(bytes)
+ bytes[6] = (bytes[6]! & 0x0f) | 0x40
+ bytes[8] = (bytes[8]! & 0x3f) | 0x80
+ const value = Array.from(bytes, byte => byte.toString(16).padStart(2, "0")).join("")
+ return `${value.slice(0, 8)}-${value.slice(8, 12)}-${value.slice(12, 16)}-${value.slice(16, 20)}-${value.slice(20)}`
+}
+
+export function encodeMobileShareImageBytes(bytes: Uint8Array): string {
+ const encoded: string[] = []
+ for (let offset = 0; offset < bytes.length; offset += MOBILE_SHARE_IMAGE_CHUNK_BYTES) {
+ const chunk = bytes.subarray(offset, offset + MOBILE_SHARE_IMAGE_CHUNK_BYTES)
+ let binary = ""
+ for (let index = 0; index < chunk.length; index += 1) {
+ binary += String.fromCharCode(chunk[index]!)
+ }
+ encoded.push(btoa(binary))
+ }
+ return encoded.join("")
+}
+
+function normalizeError(error: unknown): MobileShareImageError {
+ if (error instanceof MobileShareImageError) return error
+ if (typeof error === "object" && error !== null) {
+ const value = error as { code?: unknown; message?: unknown }
+ const allowed = new Set<MobileShareImageErrorCode>([
+ "untrusted_caller",
+ "invalid_png",
+ "image_too_large",
+ "busy",
+ "permission_denied",
+ "cancelled",
+ "write_failed",
+ "unavailable",
+ ])
+ if (typeof value.code === "string" && allowed.has(value.code as MobileShareImageErrorCode)) {
+ return new MobileShareImageError(
+ value.code as MobileShareImageErrorCode,
+ typeof value.message === "string" ? value.message : "Native image operation failed",
+ )
+ }
+ }
+ return new MobileShareImageError("unavailable", "Native image operation is unavailable")
+}
+
+export async function saveMobileShareImage(
+ blob: Blob,
+ filename: string,
+): Promise<MobileShareImageSaveResult> {
+ return invokeMobileShareImage("mobile_share_image_save", blob, { filename }, (result, id) => (
+ result?.attemptId === id
+ && result.status === "saved"
+ && ["photos", "pictures", "document"].includes(result.destination)
+ ))
+}
+
+export async function copyMobileShareImage(blob: Blob): Promise<MobileShareImageCopyResult> {
+ return invokeMobileShareImage("mobile_share_image_copy", blob, {}, (result, id) => (
+ result?.attemptId === id
+ && result.status === "copied"
+ && result.destination === "clipboard"
+ ))
+}
+
+async function invokeMobileShareImage<T extends MobileShareImageCopyResult | MobileShareImageSaveResult>(
+ command: "mobile_share_image_copy" | "mobile_share_image_save",
+ blob: Blob,
+ extra: { filename?: string },
+ accepts: (result: T, attemptId: string) => boolean,
+): Promise<T> {
+ if (blob.type !== "image/png") {
+ throw new MobileShareImageError("invalid_png", "Image must be a PNG")
+ }
+ if (blob.size === 0) {
+ throw new MobileShareImageError("invalid_png", "Image is empty")
+ }
+ if (blob.size > MOBILE_SHARE_IMAGE_MAX_BYTES) {
+ throw new MobileShareImageError("image_too_large", "Image exceeds the mobile limit")
+ }
+ const id = attemptId()
+ const start = performance.now()
+ if (process.env.NODE_ENV !== "production") {
+ console.debug(`mobile-share-image web dispatch attempt=${id} t=${start}`)
+ }
+ try {
+ const result = await tauriInvoke<T>(command, {
+ payload: {
+ attemptId: id,
+ pngBase64: encodeMobileShareImageBytes(new Uint8Array(await blob.arrayBuffer())),
+ ...extra,
+ },
+ })
+ if (!accepts(result, id)) {
+ throw new MobileShareImageError("write_failed", "Native image result did not match the request")
+ }
+ return result
+ } catch (error) {
+ throw normalizeError(error)
+ } finally {
+ if (process.env.NODE_ENV !== "production") {
+ console.debug(`mobile-share-image web settle attempt=${id} t=${performance.now()}`)
+ }
+ }
+}
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index 01396a62b..7bc612bf4 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -178,6 +178,7 @@ export const tid = {
messageShareImage: (msgId: string, index: number) =>
`message-share-image-${msgId}-${index}`,
messageShareCopy: `community-message-share-copy`,
+ messageShareSave: `community-message-share-save`,
threadIndicator: (msgId: string) => `community-thread-indicator-${msgId}`,
get threadSplit() {
return "community-thread-split" as const
diff --git a/src/web/src/test/e2e-ui/51-share-image-assets.spec.ts b/src/web/src/test/e2e-ui/51-share-image-assets.spec.ts
index 0d6ef56a4..a07483beb 100644
--- a/src/web/src/test/e2e-ui/51-share-image-assets.spec.ts
+++ b/src/web/src/test/e2e-ui/51-share-image-assets.spec.ts
@@ -6,6 +6,10 @@ import { tid } from "./_fixtures/testids"
type SamplePoint = { x: number; y: number }
type CaptureKind = "clipboard" | "download"
+type MobileShareTestState = {
+ calls: Array<{ command: string; attemptId: string; filename?: string }>
+ finish: (index: number, destination: "clipboard" | "pictures") => void
+}
async function uploadPhoto(page: Page): Promise<void> {
const status = await page.evaluate(async () => {
@@ -206,6 +210,68 @@ async function holdNextAvatarRequest(page: Page) {
}
}
+async function installMobileShareNativeStub(page: Page): Promise<void> {
+ await page.evaluate(() => {
+ const completions: Array<(value: Record<string, unknown>) => void> = []
+ const state: MobileShareTestState = {
+ calls: [],
+ finish(index, destination) {
+ const call = this.calls[index]
+ if (!call) throw new Error(`Missing mobile share call ${index}`)
+ completions[index]?.({
+ attemptId: call.attemptId,
+ status: destination === "clipboard" ? "copied" : "saved",
+ destination,
+ })
+ },
+ }
+ Object.defineProperty(navigator, "userAgent", {
+ configurable: true,
+ get: () => "iPhone",
+ })
+ Object.defineProperty(window, "__mobileShareTestState", {
+ configurable: true,
+ value: state,
+ })
+ Object.defineProperty(window, "__TAURI__", {
+ configurable: true,
+ value: {
+ core: {
+ invoke: (command: string, args: {
+ payload: { attemptId: string; filename?: string }
+ }) => new Promise((resolve) => {
+ state.calls.push({
+ command,
+ attemptId: args.payload.attemptId,
+ filename: args.payload.filename,
+ })
+ completions.push(resolve)
+ }),
+ },
+ },
+ })
+ })
+}
+
+async function mobileShareCalls(page: Page) {
+ return page.evaluate(() => (
+ window as typeof window & { __mobileShareTestState: MobileShareTestState }
+ ).__mobileShareTestState.calls)
+}
+
+async function finishMobileShareCall(
+ page: Page,
+ index: number,
+ destination: "clipboard" | "pictures",
+): Promise<void> {
+ await page.evaluate(({ callIndex, resultDestination }) => {
+ const state = (
+ window as typeof window & { __mobileShareTestState: MobileShareTestState }
+ ).__mobileShareTestState
+ state.finish(callIndex, resultDestination)
+ }, { callIndex: index, resultDestination: destination })
+}
+
test("share image timestamp matches the live row and survives both exports", async ({ asUser }) => {
test.setTimeout(120_000)
const serverId = await seedServer("alice", `Share timestamp ${Date.now()}`)
@@ -261,6 +327,58 @@ test("share image timestamp matches the live row and survives both exports", asy
await expect(card.locator("[data-share-timestamp]")).toHaveText(expectedTimestamp)
})
+test("mobile routing waits for native copy and save receipts", async ({ asUser }) => {
+ test.setTimeout(120_000)
+ const serverId = await seedServer("alice", `Mobile share receipt ${Date.now()}`)
+ const channelId = await seedChannel("alice", serverId, "mobile-share-receipt")
+ const { page } = await asUser("alice")
+ await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelId}`)
+ const seeded = await page.evaluate(async (targetId) => {
+ const response = await fetch(`/api/community/channels/${targetId}/messages`, {
+ method: "POST",
+ credentials: "include",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ content: "Native receipt controls success",
+ attachments: [],
+ nonce: `e2e:${crypto.randomUUID()}`,
+ }),
+ })
+ const payload = await response.json() as { message: { id: string } }
+ return { status: response.status, messageId: payload.message.id }
+ }, channelId)
+ expect(seeded.status).toBe(201)
+ await installMobileShareNativeStub(page)
+
+ const dialog = await openShareDialog(page, seeded.messageId)
+ const copy = dialog.getByRole("button", { name: "Copy image" })
+ const save = dialog.getByRole("button", { name: "Save image" })
+ await expect(dialog.getByRole("button", { name: "Download" })).toHaveCount(0)
+
+ await copy.click()
+ await expect.poll(() => mobileShareCalls(page)).toHaveLength(1)
+ await expect(copy).toBeDisabled()
+ await expect(save).toBeDisabled()
+ await expect(page.getByText("Image copied to clipboard", { exact: true })).toHaveCount(0)
+ await finishMobileShareCall(page, 0, "clipboard")
+ await expect(dialog.getByRole("button", { name: "Copied" })).toBeVisible()
+ await expect(copy).toBeVisible({ timeout: 5_000 })
+
+ await save.click()
+ await expect.poll(() => mobileShareCalls(page)).toHaveLength(2)
+ await expect(page.getByText("Saved to Pictures/Alook", { exact: true })).toHaveCount(0)
+ await finishMobileShareCall(page, 1, "pictures")
+ await expect(page.getByText("Saved to Pictures/Alook", { exact: true })).toBeVisible()
+
+ expect(await mobileShareCalls(page)).toEqual([
+ expect.objectContaining({ command: "mobile_share_image_copy" }),
+ expect.objectContaining({
+ command: "mobile_share_image_save",
+ filename: expect.stringMatching(/^alook-message-.+\.png$/),
+ }),
+ ])
+})
+
test("consecutive share-image exports reuse rendered avatar, attachment, and invite icon pixels", async ({ asUser }) => {
test.setTimeout(120_000)
const serverId = await seedServer("alice", `Share assets ${Date.now()}`)