Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix: open native share sheets after mobile downloads (#820)

Gustavo Ye0248ef9f1fb9
diff --git a/scripts/ci/file-save.test.ts b/scripts/ci/file-save.test.ts
index 979ccd61a..33a0f3466 100644
--- a/scripts/ci/file-save.test.ts
+++ b/scripts/ci/file-save.test.ts
@@ -35,8 +35,17 @@ describe("native file save boundary", () => {
expect(read("plugins/file-save/android/src/main/java/ai/alook/plugin/filesave/FileSavePlugin.kt")).toContain('source.name == args.attemptId + ".partial"')
expect(read("plugins/file-save/ios/Sources/FileSavePlugin.swift")).toContain('source.lastPathComponent == args.attemptId + ".partial"')
})
- it("hooks Android picker ownership into activity recreation", () => {
- const activity = read("gen/android/app/src/main/java/ai/alook/android/MainActivity.kt")
- for (const call of ["attach(savedInstanceState)", "saveState(outState)", "detach()"]) expect(activity).toContain(`fileSaveDocumentOwner.${call}`)
+ it("limits Android shared file access to the dedicated cache with temporary grants", () => {
+ const manifest = read("plugins/file-save/android/src/main/AndroidManifest.xml")
+ expect(manifest).toContain('android:exported="false"')
+ expect(manifest).toContain('android:grantUriPermissions="true"')
+ expect(manifest).toContain('android:authorities="${applicationId}.file-share"')
+ const paths = read("plugins/file-save/android/src/main/res/xml/alook_file_share_paths.xml")
+ expect(paths).toContain('<cache-path name="shared_files" path="alook-share/" />')
+ expect(paths).not.toMatch(/<(root|external|files)-path/)
+ const plugin = read("plugins/file-save/android/src/main/java/ai/alook/plugin/filesave/FileSavePlugin.kt")
+ expect(plugin).toContain("Intent.ACTION_SEND")
+ expect(plugin).toContain("Intent.FLAG_GRANT_READ_URI_PERMISSION")
+ expect(plugin).not.toContain("Intent.ACTION_CREATE_DOCUMENT")
})
})
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 73632c528..836efa438 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
@@ -18,7 +18,6 @@ import androidx.core.view.WindowInsetsCompat
import androidx.webkit.WebViewCompat
import androidx.webkit.WebViewFeature
import ai.alook.plugin.mobileshareimage.MobileShareImageDocumentOwner
-import ai.alook.plugin.filesave.FileSaveDocumentOwner
class MainActivity : TauriActivity() {
override val handleBackNavigation: Boolean = false
@@ -27,7 +26,6 @@ class MainActivity : TauriActivity() {
private var mainWebView: WebView? = null
private lateinit var nativeBackCallback: OnBackPressedCallback
private lateinit var nativeBackDispatcher: NativeBackDispatcher
- private val fileSaveDocumentOwner = FileSaveDocumentOwner(this)
private val mobileShareImageDocumentOwner = MobileShareImageDocumentOwner(this)
companion object {
@@ -71,7 +69,6 @@ class MainActivity : TauriActivity() {
nativeBackDispatcher = NativeBackDispatcher(::delegateBackToSystem)
onBackPressedDispatcher.addCallback(this, nativeBackCallback)
mobileShareImageDocumentOwner.attach(savedInstanceState)
- fileSaveDocumentOwner.attach(savedInstanceState)
splashScreen.setKeepOnScreenCondition { !isReady }
@@ -100,7 +97,6 @@ class MainActivity : TauriActivity() {
override fun onSaveInstanceState(outState: Bundle) {
mobileShareImageDocumentOwner.saveState(outState)
- fileSaveDocumentOwner.saveState(outState)
super.onSaveInstanceState(outState)
}
@@ -108,7 +104,6 @@ class MainActivity : TauriActivity() {
nativeBackDispatcher.close()
mainWebView = null
mobileShareImageDocumentOwner.detach()
- fileSaveDocumentOwner.detach()
super.onDestroy()
}
diff --git a/src/desktop/src-tauri/plugins/file-save/android/src/main/AndroidManifest.xml b/src/desktop/src-tauri/plugins/file-save/android/src/main/AndroidManifest.xml
index 94cbbcfc3..9b992bf89 100644
--- a/src/desktop/src-tauri/plugins/file-save/android/src/main/AndroidManifest.xml
+++ b/src/desktop/src-tauri/plugins/file-save/android/src/main/AndroidManifest.xml
@@ -1 +1,9 @@
-<manifest xmlns:android="http://schemas.android.com/apk/res/android" />
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+ <application>
+ <provider android:name="ai.alook.plugin.filesave.FileShareProvider"
+ android:authorities="${applicationId}.file-share"
+ android:exported="false" android:grantUriPermissions="true">
+ <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/alook_file_share_paths" />
+ </provider>
+ </application>
+</manifest>
diff --git a/src/desktop/src-tauri/plugins/file-save/android/src/main/java/ai/alook/plugin/filesave/FileSavePlugin.kt b/src/desktop/src-tauri/plugins/file-save/android/src/main/java/ai/alook/plugin/filesave/FileSavePlugin.kt
index 264841829..b960d6213 100644
--- a/src/desktop/src-tauri/plugins/file-save/android/src/main/java/ai/alook/plugin/filesave/FileSavePlugin.kt
+++ b/src/desktop/src-tauri/plugins/file-save/android/src/main/java/ai/alook/plugin/filesave/FileSavePlugin.kt
@@ -1,17 +1,14 @@
package ai.alook.plugin.filesave
import android.app.Activity
-import android.content.ContentValues
+import android.content.ClipData
+import androidx.core.content.FileProvider
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
-import android.os.Bundle
import android.provider.MediaStore
import android.provider.DocumentsContract
-import androidx.activity.ComponentActivity
-import androidx.activity.result.ActivityResultLauncher
-import androidx.activity.result.contract.ActivityResultContracts
import app.tauri.plugin.JSObject
import app.tauri.annotation.Command
import app.tauri.annotation.InvokeArg
@@ -37,57 +34,18 @@ class ExportArgs {
class CancelArgs { lateinit var attemptId: String }
private class ExportSession(val args: ExportArgs, val invoke: Invoke) {
- val token: String = UUID.randomUUID().toString()
val cancelled = AtomicBoolean(false)
var terminal = false
- var waitingPicker = false
-}
-
-class FileSaveDocumentOwner(private val activity: ComponentActivity) {
- private val launchers = mutableMapOf<String, ActivityResultLauncher<Intent>>()
- private val tokens = linkedSetOf<String>()
- fun attach(saved: Bundle?) {
- FileExporter.owner = this
- tokens.addAll(saved?.getStringArrayList("alook.fileSave.tokens") ?: emptyList())
- tokens.toList().forEach { register(it) }
- }
- private fun register(id: String): ActivityResultLauncher<Intent> {
- launchers[id]?.let { return it }
- var delivered = false
- val launcher = activity.activityResultRegistry.register("alook.file-save.$id", ActivityResultContracts.StartActivityForResult()) { result ->
- delivered = true
- val uri = result.data?.data?.takeIf { result.resultCode == Activity.RESULT_OK }
- FileExporter.deliver(activity.applicationContext, id, uri)
- launchers.remove(id)?.unregister()
- tokens.remove(id)
- }
- if (delivered) launcher.unregister() else launchers[id] = launcher
- return launcher
- }
- fun launch(args: ExportArgs, token: String) {
- tokens.add(token)
- register(token).launch(Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
- addCategory(Intent.CATEGORY_OPENABLE); type = args.mime; putExtra(Intent.EXTRA_TITLE, args.name)
- })
- }
- fun saveState(out: Bundle) { out.putStringArrayList("alook.fileSave.tokens", ArrayList(tokens)) }
- fun detach() {
- if (FileExporter.owner === this) { FileExporter.owner = null; FileExporter.cancelActive() }
- launchers.values.forEach { it.unregister() }; launchers.clear()
- }
}
private object FileExporter {
val executor = Executors.newSingleThreadExecutor()
- @Volatile var owner: FileSaveDocumentOwner? = null
private var session: ExportSession? = null
private val cancelled = mutableSetOf<String>()
- @Synchronized fun cancelActive() { session?.let { cancel(it.args.attemptId) } }
@Synchronized fun cancel(id: String) {
val active = session
if (active?.args?.attemptId == id) {
active.cancelled.set(true)
- if (active.waitingPicker) settle(active, "cancelled")
} else { if (cancelled.size > 128) cancelled.clear(); cancelled.add(id) }
}
@Synchronized fun acquire(args: ExportArgs, invoke: Invoke): ExportSession? {
@@ -112,16 +70,45 @@ private object FileExporter {
try {
validate(activity, args)
if (s.cancelled.get()) { settle(s, "cancelled"); return@execute }
- if (Build.VERSION.SDK_INT >= 29) saveDownloads(activity.applicationContext, s)
- else activity.runOnUiThread {
- try {
- if (s.cancelled.get()) settle(s, "cancelled")
- else synchronized(this) {
- check(!s.cancelled.get())
- s.waitingPicker = true
- (owner ?: throw IllegalStateException()).launch(args, s.token)
+ val root = File(activity.cacheDir, "alook-share")
+ root.mkdirs()
+ root.listFiles()?.filter { it.lastModified() < System.currentTimeMillis() - 86_400_000L }?.forEach { it.deleteRecursively() }
+ val directory = File(root, args.attemptId)
+ check(directory.mkdirs())
+ val destination = File(directory, args.name)
+ try {
+ FileInputStream(args.path).use { input ->
+ destination.outputStream().use { output ->
+ FileSaveCopy.write(input, output, args.bytes, args.sha256) { s.cancelled.get() }
+ }
+ }
+ activity.runOnUiThread {
+ synchronized(this) {
+ try {
+ if (s.cancelled.get()) {
+ directory.deleteRecursively()
+ settle(s, "cancelled")
+ } else {
+ val uri = FileProvider.getUriForFile(activity, "${activity.packageName}.file-share", destination)
+ val send = Intent(Intent.ACTION_SEND).apply {
+ type = args.mime
+ putExtra(Intent.EXTRA_STREAM, uri)
+ putExtra(Intent.EXTRA_TITLE, args.name)
+ clipData = ClipData.newRawUri(args.name, uri)
+ addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ }
+ activity.startActivity(Intent.createChooser(send, null))
+ settle(s, "started", "share")
+ }
+ } catch (_: Exception) {
+ directory.deleteRecursively()
+ settle(s, "error")
+ }
}
- } catch (_: Exception) { settle(s, "error") }
+ }
+ } catch (error: Exception) {
+ directory.deleteRecursively()
+ throw error
}
} catch (_: Exception) { settle(s, if (s.cancelled.get()) "cancelled" else "error") }
}
@@ -133,13 +120,6 @@ private object FileExporter {
require(source.path.startsWith(context.cacheDir.canonicalPath + "/") && source.parentFile?.name == "user-file-save" && source.name == args.attemptId + ".partial")
require(source.length() == args.bytes)
}
- private fun copy(context: Context, s: ExportSession, uri: Uri) {
- context.contentResolver.openOutputStream(uri, "w")?.use { output ->
- FileInputStream(s.args.path).use { input ->
- FileSaveCopy.write(input, output, s.args.bytes, s.args.sha256) { s.cancelled.get() }
- }
- } ?: throw IllegalStateException()
- }
private fun prefs(context: Context) = context.getSharedPreferences("alook-file-save", Context.MODE_PRIVATE)
fun repair(context: Context) {
val prefs = prefs(context)
@@ -169,53 +149,6 @@ private object FileExporter {
reportCleanup(documentCleanup(context).repair())
}
- private fun saveDownloads(context: Context, s: ExportSession) {
- val resolver = context.contentResolver
- val values = ContentValues().apply {
- put(MediaStore.MediaColumns.DISPLAY_NAME, ".alook-${s.args.attemptId}.partial")
- put(MediaStore.MediaColumns.MIME_TYPE, s.args.mime)
- put(MediaStore.MediaColumns.RELATIVE_PATH, "Download/Alook")
- put(MediaStore.MediaColumns.IS_PENDING, 1)
- }
- val uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values) ?: throw IllegalStateException()
- var published = false
- try {
- check(prefs(context).edit().putString(s.args.attemptId, uri.toString()).commit())
- copy(context, s, uri)
- synchronized(this) {
- check(!s.cancelled.get())
- check(resolver.update(uri, ContentValues().apply { put(MediaStore.MediaColumns.IS_PENDING, 0); put(MediaStore.MediaColumns.DISPLAY_NAME, s.args.name) }, null, null) == 1)
- published = true
- settle(s, "saved", "downloads")
- }
- } finally {
- if (published || resolver.delete(uri, null, null) > 0) prefs(context).edit().remove(s.args.attemptId).commit()
- }
- }
- fun deliver(context: Context, id: String, uri: Uri?) {
- val s = synchronized(this) { session?.takeIf { it.token == id && !it.terminal }?.also { it.waitingPicker = false } }
- executor.execute {
- if (s == null || s.cancelled.get()) {
- if (uri != null) reportCleanup(documentCleanup(context).discard(id, uri.toString()))
- if (s != null) settle(s, "cancelled")
- return@execute
- }
- if (uri == null) { settle(s, "cancelled"); return@execute }
- val cleanup = documentCleanup(context)
- try {
- cleanup.acquire(id, uri.toString())
- copy(context, s, uri)
- synchronized(this) {
- check(!s.cancelled.get())
- reportCleanup(cleanup.published(id, uri.toString()))
- settle(s, "saved", "document")
- }
- } catch (_: Exception) {
- reportCleanup(cleanup.discard(id, uri.toString()))
- settle(s, if (s.cancelled.get()) "cancelled" else "error")
- }
- }
- }
private fun reportCleanup(complete: Boolean) {
if (!complete) android.util.Log.w("AlookFileSave", "Document cleanup incomplete; recovery required")
}
diff --git a/src/desktop/src-tauri/plugins/file-save/android/src/main/java/ai/alook/plugin/filesave/FileShareProvider.kt b/src/desktop/src-tauri/plugins/file-save/android/src/main/java/ai/alook/plugin/filesave/FileShareProvider.kt
new file mode 100644
index 000000000..c36ae5085
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/file-save/android/src/main/java/ai/alook/plugin/filesave/FileShareProvider.kt
@@ -0,0 +1,5 @@
+package ai.alook.plugin.filesave
+
+import androidx.core.content.FileProvider
+
+class FileShareProvider : FileProvider()
diff --git a/src/desktop/src-tauri/plugins/file-save/android/src/main/res/xml/alook_file_share_paths.xml b/src/desktop/src-tauri/plugins/file-save/android/src/main/res/xml/alook_file_share_paths.xml
new file mode 100644
index 000000000..31ccddcfd
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/file-save/android/src/main/res/xml/alook_file_share_paths.xml
@@ -0,0 +1,3 @@
+<paths xmlns:android="http://schemas.android.com/apk/res/android">
+ <cache-path name="shared_files" path="alook-share/" />
+</paths>
diff --git a/src/desktop/src-tauri/plugins/file-save/ios/Sources/FileSavePlugin.swift b/src/desktop/src-tauri/plugins/file-save/ios/Sources/FileSavePlugin.swift
index d6a95a33a..2e8cddc98 100644
--- a/src/desktop/src-tauri/plugins/file-save/ios/Sources/FileSavePlugin.swift
+++ b/src/desktop/src-tauri/plugins/file-save/ios/Sources/FileSavePlugin.swift
@@ -14,11 +14,11 @@ struct ExportArgs: Decodable {
struct CancelArgs: Decodable { let attemptId: String }
struct ExportResult: Encodable { let attemptId: String; let status: String; let destination: String }
-final class ExportSession: NSObject, UIDocumentPickerDelegate, UIAdaptivePresentationControllerDelegate {
+final class ExportSession: NSObject, UIAdaptivePresentationControllerDelegate {
let args: ExportArgs
let invoke: Invoke
let directory: URL
- var picker: UIDocumentPickerViewController?
+ var picker: UIActivityViewController?
private let lock = NSLock()
private var stopped = false
var cancelled: Bool {
@@ -33,16 +33,12 @@ final class ExportSession: NSObject, UIDocumentPickerDelegate, UIAdaptivePresent
func finish(_ status: String) {
guard !finished else { return }
finished = true
- picker?.delegate = nil
+ picker?.completionWithItemsHandler = nil
if status == "error" { invoke.reject("File export failed", code: "write_failed") }
- else { invoke.resolve(ExportResult(attemptId: args.attemptId, status: status, destination: status == "saved" ? "files" : "")) }
+ else { invoke.resolve(ExportResult(attemptId: args.attemptId, status: status, destination: status == "started" ? "share" : "")) }
try? FileManager.default.removeItem(at: directory)
release?()
}
- func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
- finish(urls.isEmpty ? "error" : "saved")
- }
- func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) { finish("cancelled") }
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { finish("cancelled") }
func cancel() {
cancelled = true
@@ -97,8 +93,16 @@ final class FileSavePlugin: Plugin {
if session.cancelled { session.finish("cancelled"); return }
guard let presenter = self.manager.viewController, presenter.presentedViewController == nil,
presenter.view.window != nil else { session.finish("error"); return }
- let picker = UIDocumentPickerViewController(forExporting: [destination], asCopy: true)
- session.picker = picker; picker.delegate = session
+ let picker = UIActivityViewController(activityItems: [destination], applicationActivities: nil)
+ session.picker = picker
+ picker.completionWithItemsHandler = { [weak session] _, completed, _, error in
+ session?.finish(error != nil ? "error" : completed ? "started" : "cancelled")
+ }
+ if let popover = picker.popoverPresentationController {
+ popover.sourceView = presenter.view
+ popover.sourceRect = CGRect(x: presenter.view.bounds.midX, y: presenter.view.bounds.midY, width: 1, height: 1)
+ popover.permittedArrowDirections = []
+ }
presenter.present(picker, animated: true)
picker.presentationController?.delegate = session
}
diff --git a/src/desktop/src-tauri/src/file_save.rs b/src/desktop/src-tauri/src/file_save.rs
index e620b160c..5b1964bdc 100644
--- a/src/desktop/src-tauri/src/file_save.rs
+++ b/src/desktop/src-tauri/src/file_save.rs
@@ -221,7 +221,9 @@ impl Transfer {
pub fn receipt(&self, destination: Option<String>) -> Receipt {
Receipt {
attempt_id: self.metadata.attempt_id.clone(),
- status: if destination.is_some() {
+ status: if destination.as_deref() == Some("share") {
+ "started"
+ } else if destination.is_some() {
"saved"
} else {
"cancelled"
@@ -238,6 +240,13 @@ impl Transfer {
#[cfg(test)]
mod tests {
use super::*;
+ #[test]
+ fn share_receipt_reports_handoff_instead_of_saved() {
+ let t = transfer(Some(0));
+ let receipt = t.receipt(Some("share".into()));
+ assert_eq!(receipt.status, "started");
+ assert_eq!(receipt.destination, "share");
+ }
fn transfer(size: Option<u64>) -> Transfer {
let mut random = [0u8; 16];
getrandom::fill(&mut random).unwrap();
diff --git a/src/desktop/src-tauri/src/file_save_runtime.rs b/src/desktop/src-tauri/src/file_save_runtime.rs
index c739d5228..9cb56ef09 100644
--- a/src/desktop/src-tauri/src/file_save_runtime.rs
+++ b/src/desktop/src-tauri/src/file_save_runtime.rs
@@ -219,6 +219,7 @@ async fn export(app: &AppHandle, transfer: &Transfer) -> Result<Option<String>,
"saved" if ["downloads", "files", "document"].contains(&result.destination.as_str()) => {
Ok(Some(result.destination))
}
+ "started" if result.destination == "share" => Ok(Some(result.destination)),
"cancelled" => Ok(None),
_ => Err("File export failed".into()),
}
diff --git a/src/web/src/components/file-download-button.dom.test.tsx b/src/web/src/components/file-download-button.dom.test.tsx
index 0f146c01d..1a71a28ec 100644
--- a/src/web/src/components/file-download-button.dom.test.tsx
+++ b/src/web/src/components/file-download-button.dom.test.tsx
@@ -18,6 +18,16 @@ describe("file download control", () => {
else if (status !== "cancelled") expect(service.success).toHaveBeenCalledWith(text)
else { expect(service.error).not.toHaveBeenCalled(); expect(service.success).not.toHaveBeenCalled() }
})
+ it("announces the native share handoff and permits another download", async () => {
+ service.download.mockResolvedValue({ status: "started", destination: "share" })
+ const view = render(<FileDownloadButton url="/file" filename="a.pdf">Get file</FileDownloadButton>)
+ await act(async () => { view.getByRole("button").click() })
+ expect(view.getByRole("status")).toHaveTextContent("Share sheet opened")
+ expect(service.success).toHaveBeenCalledWith("Share sheet opened")
+ expect(service.success).not.toHaveBeenCalledWith("Saved")
+ await act(async () => { view.getByRole("button").click() })
+ expect(service.download).toHaveBeenCalledTimes(2)
+ })
it("keeps the busy action cancellable and allows retry", async () => {
service.download.mockImplementationOnce((_url, _name, { signal }) => new Promise(resolve => signal.addEventListener("abort", () => resolve({ status: "cancelled" }))))
.mockResolvedValueOnce({ status: "started" })
diff --git a/src/web/src/lib/file-save.test.ts b/src/web/src/lib/file-save.test.ts
index a47cd620b..6b0145cec 100644
--- a/src/web/src/lib/file-save.test.ts
+++ b/src/web/src/lib/file-save.test.ts
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
-import { downloadUrl, saveFile, fileSaveName, FILE_SAVE_CHUNK_BYTES } from "./file-save"
+import { downloadUrl, saveFile, fileSaveMessage, fileSaveName, FILE_SAVE_CHUNK_BYTES } from "./file-save"
const bridge = vi.hoisted(() => ({ native: false, invoke: vi.fn() }))
vi.mock("@alook/shared", () => ({ isTauri: () => bridge.native, tauriInvoke: bridge.invoke }))
const id = "00000000-0000-4000-8000-000000000001"
@@ -54,6 +54,32 @@ describe("product file save", () => {
expect(bridge.invoke).toHaveBeenCalledWith("file_save_cancel", { attemptId: id })
expect(URL.createObjectURL).not.toHaveBeenCalled()
})
+ it("reports native share handoff without claiming a save or cancelling the shared file", async () => {
+ native()
+ const original = bridge.invoke.getMockImplementation()!
+ bridge.invoke.mockImplementation(async (...args) => {
+ const result = await original(...args)
+ return args[0] === "file_save_commit" ? { ...result, status: "started", destination: "share" } : result
+ })
+ const result = await saveFile(new Blob(["attachment"]), "report.txt")
+ expect(result).toEqual({ status: "started", destination: "share" })
+ expect(fileSaveMessage(result)).toBe("Share sheet opened")
+ expect(bridge.invoke).not.toHaveBeenCalledWith("file_save_cancel", expect.anything())
+ })
+ it.each([
+ { status: "started", destination: "desktop" },
+ { status: "saved", destination: "share" },
+ { status: "started", destination: "share", bytes: 999 },
+ { status: "started", destination: "share", sha256: "bad" },
+ ])("rejects an inconsistent share receipt %j", async receipt => {
+ native()
+ const original = bridge.invoke.getMockImplementation()!
+ bridge.invoke.mockImplementation(async (...args) => {
+ const result = await original(...args)
+ return args[0] === "file_save_commit" ? { ...result, ...receipt } : result
+ })
+ expect((await saveFile(new Blob(["a"]), "a.txt")).status).toBe("error")
+ })
it("cleans up native staging on a wrong chunk ack", async () => {
native(); bridge.invoke.mockResolvedValue({ attemptId: id, bytes: 99, sequence: 1 })
expect((await saveFile(new Blob(["a"]), "a")).status).toBe("error")
diff --git a/src/web/src/lib/file-save.ts b/src/web/src/lib/file-save.ts
index 39162e0fa..f6d0e9cac 100644
--- a/src/web/src/lib/file-save.ts
+++ b/src/web/src/lib/file-save.ts
@@ -2,7 +2,7 @@ import { isTauri, tauriInvoke } from "@alook/shared"
export const FILE_SAVE_CHUNK_BYTES = 65_536
export type FileSaveResult =
- | { status: "started" }
+ | { status: "started"; destination?: "share" }
| { status: "saved"; name: string; mime: string; bytes: number; sha256: string; destination: string }
| { status: "cancelled" }
| { status: "error"; message: string }
@@ -12,7 +12,7 @@ type NativeReceipt = { attemptId: string; status: string; name: string; mime: st
export function fileSaveMessage(result: FileSaveResult): string | null {
if (result.status === "saved") return "Saved"
- if (result.status === "started") return "Download started"
+ if (result.status === "started") return result.destination === "share" ? "Share sheet opened" : "Download started"
if (result.status === "error") return "Couldn’t save — retry"
return null
}
@@ -128,12 +128,14 @@ async function nativeSave(source: FileSource, signal?: AbortSignal): Promise<Fil
const result = await tauriInvoke<NativeReceipt>("file_save_commit", { payload: { attemptId, bytes } })
if (result.attemptId !== attemptId) throw new Error("Mismatched save receipt")
if (result.status === "cancelled") return { status: "cancelled" }
- if (result.status !== "saved" || result.bytes !== bytes || result.name !== source.name
+ const sharing = result.status === "started" && result.destination === "share"
+ if ((!sharing && result.status !== "saved") || result.bytes !== bytes || result.name !== source.name
|| result.mime !== source.mime || !/^[a-f0-9]{64}$/.test(result.sha256)
- || !["downloads", "files", "document", "desktop"].includes(result.destination)) {
+ || (!sharing && !["downloads", "files", "document", "desktop"].includes(result.destination))) {
throw new Error("Invalid save receipt")
}
completed = true
+ if (sharing) return { status: "started", destination: "share" }
return { status: "saved", name: result.name, mime: result.mime, bytes, sha256: result.sha256, destination: result.destination }
} finally {
signal?.removeEventListener("abort", onAbort)