Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(desktop): unify native and browser file saves (#789)

Gener363b378e297c
diff --git a/scripts/ci/file-save.test.ts b/scripts/ci/file-save.test.ts
new file mode 100644
index 000000000..979ccd61a
--- /dev/null
+++ b/scripts/ci/file-save.test.ts
@@ -0,0 +1,42 @@
+import { readFileSync } from "node:fs"
+import { resolve } from "node:path"
+import { describe, expect, it } from "vitest"
+const root = resolve(import.meta.dirname, "../../src/desktop/src-tauri")
+const read = (path: string) => readFileSync(resolve(root, path), "utf8")
+const commands = ["file_save_begin", "file_save_write_chunk", "file_save_commit", "file_save_cancel"]
+describe("native file save boundary", () => {
+ it("grants only the four guarded commands to the exact main production origin", () => {
+ const capability = JSON.parse(read("capabilities/file-save.json"))
+ expect(capability).toMatchObject({ identifier: "file-save", windows: ["main"], local: false, remote: { urls: ["https://alook.ai"] }, permissions: commands.map(c => `allow-${c.replaceAll("_", "-")}`) })
+ expect(Object.keys(capability).sort()).toEqual(["description", "identifier", "local", "permissions", "remote", "windows"])
+ expect(JSON.parse(read("tauri.conf.json")).app.security.capabilities).toContain("file-save")
+ for (const command of commands) {
+ expect(read("build.rs")).toContain(`"${command}"`)
+ expect(read("src/lib.rs").match(new RegExp(`file_save_runtime::${command}`, "g"))).toHaveLength(2)
+ }
+ expect(read("src/file_save_runtime.rs").match(/native_command_guard::guard\(&window\)/g)).toHaveLength(4)
+ })
+ it("allows Tauri devUrl local classification only in the main development capability", () => {
+ const capabilities = JSON.parse(read("tauri.dev.conf.json")).app.security.capabilities
+ const capability = capabilities.find((entry: { identifier?: string } | string) => typeof entry !== "string" && entry.identifier === "file-save-dev")
+ expect(capability).toEqual({
+ identifier: "file-save-dev", description: "User file save from the trusted main webview",
+ windows: ["main"], local: true, remote: { urls: ["http://localhost:3000"] },
+ permissions: commands.map(c => `allow-${c.replaceAll("_", "-")}`),
+ })
+ expect(JSON.parse(read("capabilities/file-save.json")).local).toBe(false)
+ expect(JSON.parse(read("tauri.conf.json")).app.security.capabilities).not.toContain("file-save-dev")
+ })
+ it("does not grant the private mobile exporter or let the web choose paths", () => {
+ expect(read("plugins/file-save/build.rs")).toContain("Builder::new(&[])")
+ const core = read("src/file_save.rs")
+ const begin = core.slice(core.indexOf("pub struct Begin"), core.indexOf("pub struct Chunk"))
+ expect(begin).not.toMatch(/pub (path|destination|url|token):/)
+ 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}`)
+ })
+})
diff --git a/scripts/ci/mobile-share-image.test.ts b/scripts/ci/mobile-share-image.test.ts
index 8c94c7508..bd0437278 100644
--- a/scripts/ci/mobile-share-image.test.ts
+++ b/scripts/ci/mobile-share-image.test.ts
@@ -191,7 +191,8 @@ describe("native mobile share-image contract", () => {
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("saveFile(blob, filename")
+ expect(dialog).not.toContain("anchor.download")
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"')
diff --git a/scripts/ci/system-notifications-desktop.test.ts b/scripts/ci/system-notifications-desktop.test.ts
index 5014f8ae7..bc36872dc 100644
--- a/scripts/ci/system-notifications-desktop.test.ts
+++ b/scripts/ci/system-notifications-desktop.test.ts
@@ -26,7 +26,8 @@ describe("desktop system notification contract", () => {
const manifestCommands = quotedValues(read("build.rs"))
.filter((command) => !command.startsWith("native_oauth_")
&& !command.startsWith("mobile_share_image_")
- && !command.startsWith("mobile_system_notification_"))
+ && !command.startsWith("mobile_system_notification_")
+ && !command.startsWith("file_save_"))
const permissionCommands = quotedValues(
read("permissions/desktop-commands.toml").match(/commands\.allow\s*=\s*\[[^\]]*\]/s)?.[0] ?? "",
)
diff --git a/scripts/ci/verify-coverage-plan.mjs b/scripts/ci/verify-coverage-plan.mjs
index 54704db7b..3f36b58c8 100644
--- a/scripts/ci/verify-coverage-plan.mjs
+++ b/scripts/ci/verify-coverage-plan.mjs
@@ -24,16 +24,31 @@ function statementCounts(file) {
}
}
-function isTypeOnlySource(path) {
- if (!/\.[cm]?tsx?$/.test(path)) return false
+function uninstrumentedSourceKind(path) {
+ if (!/\.[cm]?tsx?$/.test(path)) return null
const source = ts.createSourceFile(path, readFileSync(path, "utf8"), ts.ScriptTarget.Latest, true)
- if (source.parseDiagnostics.length > 0 || source.statements.length === 0) return false
- return source.statements.every((statement) => (
- ts.isTypeAliasDeclaration(statement)
- || ts.isInterfaceDeclaration(statement)
- || (ts.isImportDeclaration(statement) && statement.importClause?.isTypeOnly === true)
- || (ts.isExportDeclaration(statement) && statement.isTypeOnly)
- ))
+ if (source.parseDiagnostics.length > 0 || source.statements.length === 0) return null
+ let prologue = true
+ let hasTypes = false
+ let hasReExports = false
+ for (const statement of source.statements) {
+ if (prologue && ts.isExpressionStatement(statement) && ts.isStringLiteral(statement.expression)
+ && ["use client", "use server", "use strict"].includes(statement.expression.text)) continue
+ prologue = false
+ if (ts.isTypeAliasDeclaration(statement) || ts.isInterfaceDeclaration(statement)
+ || (ts.isImportDeclaration(statement) && statement.importClause?.isTypeOnly === true)
+ || (ts.isExportDeclaration(statement) && statement.isTypeOnly)) {
+ hasTypes = true
+ continue
+ }
+ if (ts.isExportDeclaration(statement) && statement.moduleSpecifier
+ && ts.isStringLiteral(statement.moduleSpecifier) && !statement.attributes) {
+ hasReExports = true
+ continue
+ }
+ return null
+ }
+ return hasReExports ? "re_export" : hasTypes ? "type_only" : null
}
export function verifyCoveragePlan(plan, report, options = {}) {
@@ -47,14 +62,17 @@ export function verifyCoveragePlan(plan, report, options = {}) {
}))
const reportPaths = new Set(files.map((entry) => entry.path))
const typeOnlyChangedFiles = []
+ const reExportChangedFiles = []
for (const path of plan.coverage.required_changed_files) {
if (!existsSync(resolve(root, path))) {
throw new Error(`required changed coverage file does not exist at head: ${path}`)
}
if (!reportPaths.has(path)) {
- if (isTypeOnlySource(resolve(root, path))) {
- typeOnlyChangedFiles.push(path)
+ const kind = uninstrumentedSourceKind(resolve(root, path))
+ if (kind) {
+ if (kind === "type_only") typeOnlyChangedFiles.push(path)
+ else reExportChangedFiles.push(path)
continue
}
throw new Error(`required changed coverage file is missing from merged report: ${path}`)
@@ -100,6 +118,7 @@ export function verifyCoveragePlan(plan, report, options = {}) {
include_roots: plan.coverage.include_roots,
required_changed_files: plan.coverage.required_changed_files,
type_only_changed_files: typeOnlyChangedFiles,
+ re_export_changed_files: reExportChangedFiles,
report_files: [...reportPaths].sort(),
targets,
}
diff --git a/scripts/ci/verify-coverage-plan.test.ts b/scripts/ci/verify-coverage-plan.test.ts
index 4412083cf..e41786142 100644
--- a/scripts/ci/verify-coverage-plan.test.ts
+++ b/scripts/ci/verify-coverage-plan.test.ts
@@ -46,7 +46,6 @@ describe("verifyCoveragePlan", () => {
["runtime value", "export type Foo = string; export const value = 1;", false],
["side-effect import", "import './setup'; export type Foo = string;", false],
["value import", "import { Foo } from './foo'; export type Bar = Foo;", false],
- ["value re-export", "export { Foo } from './foo';", false],
["enum", "export enum Foo { Bar }", false],
["namespace", "export namespace Foo { export const bar = 1 }", false],
["invalid syntax", "export type Foo = ;", false],
@@ -67,6 +66,49 @@ describe("verifyCoveragePlan", () => {
}
})
+ it.each([
+ ["named alias", '"use client"; export { start as download } from "./owner";', true],
+ ["star", 'export * from "./owner";', true],
+ ["namespace re-export", 'export * as owner from "./owner";', true],
+ ["types with forwarding", 'export interface Item { id: string } export { start } from "./owner";', true],
+ ["side-effect import", 'import "./setup"; export * from "./owner";', false],
+ ["local bindings", 'import { start } from "./owner"; export { start };', false],
+ ["executable initializer", 'export * from "./owner"; export const value = run();', false],
+ ["function body", 'export * from "./owner"; export function start() {}', false],
+ ["export expression", 'export default run();', false],
+ ["local export", 'export {};', false],
+ ["only directive", '"use client";', false],
+ ["late directive", 'export * from "./owner"; "use client";', false],
+ ["malformed", 'export { from "./owner";', false],
+ ])("audits forwarding modules: %s", (_name, source, forwardingOnly) => {
+ const root = mkdtempSync(join(tmpdir(), "alook-coverage-forwarding-"))
+ const changed = "src/web/src/barrel.ts"
+ const runtime = "src/web/src/owner.ts"
+ const plan = buildExecutionPlan([{ status: "M", path: changed }], { baseSha, headSha })
+ try {
+ mkdirSync(join(root, "src/web/src"), { recursive: true })
+ writeFileSync(join(root, changed), source)
+ const verify = () => verifyCoveragePlan(plan, { [runtime]: coveredFile(runtime) }, { root })
+ if (forwardingOnly) {
+ expect(verify()).toMatchObject({ re_export_changed_files: [changed], type_only_changed_files: [] })
+ expect(() => verifyCoveragePlan(plan, {}, { root })).toThrow("nonempty denominator")
+ } else expect(verify).toThrow(`required changed coverage file is missing from merged report: ${changed}`)
+ } finally { rmSync(root, { recursive: true, force: true }) }
+ })
+
+ it("does not let a forwarding barrel hide a missing changed implementation", () => {
+ const root = mkdtempSync(join(tmpdir(), "alook-coverage-owner-"))
+ const barrel = "src/web/src/barrel.ts", owner = "src/web/src/owner.ts"
+ const plan = buildExecutionPlan([{ status: "M", path: barrel }, { status: "M", path: owner }], { baseSha, headSha })
+ try {
+ mkdirSync(join(root, "src/web/src"), { recursive: true })
+ writeFileSync(join(root, barrel), '"use client"; export { run } from "./owner";')
+ writeFileSync(join(root, owner), 'export function run() { return 1 }')
+ expect(() => verifyCoveragePlan(plan, {}, { root })).toThrow(`missing from merged report: ${owner}`)
+ expect(verifyCoveragePlan(plan, { [owner]: coveredFile(owner) }, { root })).toMatchObject({ re_export_changed_files: [barrel] })
+ } finally { rmSync(root, { recursive: true, force: true }) }
+ })
+
it("permits an excluded E2E fixture without hiding missing product coverage", () => {
const fixture = "src/web/src/test/e2e-ui/_fixtures/community-notification-requests.ts"
const product = "src/web/src/lib/community/message-dispatcher.ts"
diff --git a/scripts/ci/workflow-contract.test.ts b/scripts/ci/workflow-contract.test.ts
index bd94ad8ba..e88ce35f5 100644
--- a/scripts/ci/workflow-contract.test.ts
+++ b/scripts/ci/workflow-contract.test.ts
@@ -1144,6 +1144,14 @@ describe("Desktop image clipboard", () => {
remote: { urls: ["http://localhost:3000"] },
permissions: ["mobile-system-notification"],
}),
+ "file-save",
+ expect.objectContaining({
+ identifier: "file-save-dev",
+ local: true,
+ windows: ["main"],
+ remote: { urls: ["http://localhost:3000"] },
+ permissions: ["allow-file-save-begin", "allow-file-save-write-chunk", "allow-file-save-commit", "allow-file-save-cancel"],
+ }),
])
})
})
diff --git a/src/desktop/src-tauri/Cargo.lock b/src/desktop/src-tauri/Cargo.lock
index 2064c1a81..0217956ed 100644
--- a/src/desktop/src-tauri/Cargo.lock
+++ b/src/desktop/src-tauri/Cargo.lock
@@ -56,6 +56,7 @@ dependencies = [
"tauri-plugin-clipboard-manager",
"tauri-plugin-deep-link",
"tauri-plugin-dialog",
+ "tauri-plugin-file-save",
"tauri-plugin-mobile-push",
"tauri-plugin-mobile-share-image",
"tauri-plugin-notification",
@@ -4151,6 +4152,16 @@ dependencies = [
"url",
]
+[[package]]
+name = "tauri-plugin-file-save"
+version = "0.1.0"
+dependencies = [
+ "serde",
+ "serde_json",
+ "tauri",
+ "tauri-plugin",
+]
+
[[package]]
name = "tauri-plugin-fs"
version = "2.5.1"
diff --git a/src/desktop/src-tauri/Cargo.toml b/src/desktop/src-tauri/Cargo.toml
index 6ecfd83d6..704ac3977 100644
--- a/src/desktop/src-tauri/Cargo.toml
+++ b/src/desktop/src-tauri/Cargo.toml
@@ -27,6 +27,7 @@ unicode-normalization = "0.1"
url = "2"
[target."cfg(any(target_os = \"android\", target_os = \"ios\"))".dependencies]
+tauri-plugin-file-save = { path = "plugins/file-save" }
tauri-plugin-mobile-share-image = { path = "plugins/mobile-share-image" }
tauri-plugin-mobile-push = { path = "plugins/mobile-push" }
diff --git a/src/desktop/src-tauri/build.rs b/src/desktop/src-tauri/build.rs
index 926e13af0..51ddd91f2 100644
--- a/src/desktop/src-tauri/build.rs
+++ b/src/desktop/src-tauri/build.rs
@@ -1,6 +1,10 @@
fn main() {
tauri_build::try_build(tauri_build::Attributes::new().app_manifest(
tauri_build::AppManifest::new().commands(&[
+ "file_save_begin",
+ "file_save_write_chunk",
+ "file_save_commit",
+ "file_save_cancel",
"daemon_runtime_capability",
"daemon_pair",
"set_window_theme",
diff --git a/src/desktop/src-tauri/capabilities/file-save.json b/src/desktop/src-tauri/capabilities/file-save.json
new file mode 100644
index 000000000..6f35a4576
--- /dev/null
+++ b/src/desktop/src-tauri/capabilities/file-save.json
@@ -0,0 +1,19 @@
+{
+ "identifier": "file-save",
+ "description": "User file save from the trusted main webview",
+ "windows": [
+ "main"
+ ],
+ "local": false,
+ "remote": {
+ "urls": [
+ "https://alook.ai"
+ ]
+ },
+ "permissions": [
+ "allow-file-save-begin",
+ "allow-file-save-write-chunk",
+ "allow-file-save-commit",
+ "allow-file-save-cancel"
+ ]
+}
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 7f9a799d1..1566c54ff 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
@@ -17,9 +17,11 @@ 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() {
private var isReady = false
+ private val fileSaveDocumentOwner = FileSaveDocumentOwner(this)
private val mobileShareImageDocumentOwner = MobileShareImageDocumentOwner(this)
companion object {
@@ -49,6 +51,7 @@ class MainActivity : TauriActivity() {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
mobileShareImageDocumentOwner.attach(savedInstanceState)
+ fileSaveDocumentOwner.attach(savedInstanceState)
splashScreen.setKeepOnScreenCondition { !isReady }
@@ -77,11 +80,13 @@ class MainActivity : TauriActivity() {
override fun onSaveInstanceState(outState: Bundle) {
mobileShareImageDocumentOwner.saveState(outState)
+ fileSaveDocumentOwner.saveState(outState)
super.onSaveInstanceState(outState)
}
override fun onDestroy() {
mobileShareImageDocumentOwner.detach()
+ fileSaveDocumentOwner.detach()
super.onDestroy()
}
diff --git a/src/desktop/src-tauri/plugins/file-save/.gitignore b/src/desktop/src-tauri/plugins/file-save/.gitignore
new file mode 100644
index 000000000..282bca8b9
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/file-save/.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/file-save/Cargo.toml b/src/desktop/src-tauri/plugins/file-save/Cargo.toml
new file mode 100644
index 000000000..f6a81f143
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/file-save/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "tauri-plugin-file-save"
+version = "0.1.0"
+edition = "2021"
+links = "tauri-plugin-file-save"
+
+[build-dependencies]
+tauri-plugin = { version = "2", features = ["build"] }
+
+[dependencies]
+serde = { version = "1", features = ["derive"] }
+tauri = { version = "=2.11.2", default-features = false }
+serde_json = "1"
+
+[target.'cfg(target_os = "ios")'.dependencies]
+tauri = { version = "=2.11.2", features = ["wry"], default-features = false }
diff --git a/src/desktop/src-tauri/plugins/file-save/android/build.gradle.kts b/src/desktop/src-tauri/plugins/file-save/android/build.gradle.kts
new file mode 100644
index 000000000..f53900b3a
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/file-save/android/build.gradle.kts
@@ -0,0 +1,35 @@
+plugins {
+ id("com.android.library")
+ id("org.jetbrains.kotlin.android")
+}
+
+android {
+ namespace = "ai.alook.plugin.filesave"
+ 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/file-save/android/proguard-rules.pro b/src/desktop/src-tauri/plugins/file-save/android/proguard-rules.pro
new file mode 100644
index 000000000..59aa982c6
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/file-save/android/proguard-rules.pro
@@ -0,0 +1 @@
+-keep class ai.alook.plugin.filesave.** { *; }
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
new file mode 100644
index 000000000..94cbbcfc3
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/file-save/android/src/main/AndroidManifest.xml
@@ -0,0 +1 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android" />
diff --git a/src/desktop/src-tauri/plugins/file-save/android/src/main/java/ai/alook/plugin/filesave/FileSaveCopy.kt b/src/desktop/src-tauri/plugins/file-save/android/src/main/java/ai/alook/plugin/filesave/FileSaveCopy.kt
new file mode 100644
index 000000000..616cc740a
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/file-save/android/src/main/java/ai/alook/plugin/filesave/FileSaveCopy.kt
@@ -0,0 +1,24 @@
+package ai.alook.plugin.filesave
+
+import java.io.InputStream
+import java.io.OutputStream
+import java.security.MessageDigest
+
+internal object FileSaveCopy {
+ fun write(input: InputStream, output: OutputStream, size: Long, sha256: String, cancelled: () -> Boolean) {
+ val hash = MessageDigest.getInstance("SHA-256")
+ var bytes = 0L
+ val buffer = ByteArray(65_536)
+ while (true) {
+ check(!cancelled())
+ val n = input.read(buffer)
+ if (n < 0) break
+ bytes += n
+ check(bytes <= size)
+ output.write(buffer, 0, n)
+ hash.update(buffer, 0, n)
+ }
+ output.flush()
+ check(!cancelled() && bytes == size && hash.digest().joinToString("") { "%02x".format(it) } == sha256)
+ }
+}
diff --git a/src/desktop/src-tauri/plugins/file-save/android/src/main/java/ai/alook/plugin/filesave/FileSaveDocumentCleanup.kt b/src/desktop/src-tauri/plugins/file-save/android/src/main/java/ai/alook/plugin/filesave/FileSaveDocumentCleanup.kt
new file mode 100644
index 000000000..1c0a3761d
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/file-save/android/src/main/java/ai/alook/plugin/filesave/FileSaveDocumentCleanup.kt
@@ -0,0 +1,54 @@
+package ai.alook.plugin.filesave
+
+internal data class DocumentCleanupRecord(val uri: String, val releaseOnly: Boolean = false)
+internal interface DocumentCleanupStore {
+ fun entries(): Map<String, DocumentCleanupRecord>
+ fun put(token: String, record: DocumentCleanupRecord)
+ fun remove(token: String)
+}
+internal interface DocumentCleanupProvider {
+ fun retain(uri: String)
+ fun delete(uri: String): Boolean
+ fun release(uri: String)
+}
+internal class FileSaveDocumentCleanup(private val store: DocumentCleanupStore, private val provider: DocumentCleanupProvider) {
+ fun acquire(token: String, uri: String) {
+ val existing = store.entries()[token]
+ check(existing == null || existing == DocumentCleanupRecord(uri))
+ store.put(token, DocumentCleanupRecord(uri))
+ provider.retain(uri)
+ }
+ fun discard(token: String, uri: String): Boolean {
+ var durable = true
+ val existing = try { store.entries()[token] } catch (_: Exception) { durable = false; null }
+ if (existing != null && existing.uri != uri) return false
+ if (existing?.releaseOnly == true) return release(token, existing)
+ try { store.put(token, DocumentCleanupRecord(uri)) } catch (_: Exception) { durable = false }
+ try { provider.retain(uri) } catch (_: Exception) { }
+ val deleted = try { provider.delete(uri) } catch (_: Exception) { false }
+ if (!deleted) return false
+ val record = DocumentCleanupRecord(uri, releaseOnly = true)
+ if (durable) {
+ try { store.put(token, record) } catch (_: Exception) { return false }
+ return release(token, record)
+ }
+ return try { provider.release(uri); false } catch (_: Exception) { false }
+ }
+ fun published(token: String, uri: String): Boolean {
+ val record = DocumentCleanupRecord(uri, releaseOnly = true)
+ store.put(token, record)
+ return release(token, record)
+ }
+ fun repair(): Boolean {
+ val entries = try { store.entries() } catch (_: Exception) { return false }
+ var complete = true
+ for ((token, record) in entries) {
+ val done = if (record.releaseOnly) release(token, record) else discard(token, record.uri)
+ if (!done) complete = false
+ }
+ return complete
+ }
+ private fun release(token: String, record: DocumentCleanupRecord): Boolean {
+ return try { provider.release(record.uri); store.remove(token); true } catch (_: Exception) { false }
+ }
+}
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
new file mode 100644
index 000000000..264841829
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/file-save/android/src/main/java/ai/alook/plugin/filesave/FileSavePlugin.kt
@@ -0,0 +1,275 @@
+package ai.alook.plugin.filesave
+
+import android.app.Activity
+import android.content.ContentValues
+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
+import app.tauri.annotation.TauriPlugin
+import app.tauri.plugin.Invoke
+import app.tauri.plugin.Plugin
+import java.io.File
+import java.io.FileInputStream
+import java.util.UUID
+import java.util.concurrent.Executors
+import java.util.concurrent.atomic.AtomicBoolean
+
+@InvokeArg
+class ExportArgs {
+ lateinit var attemptId: String
+ lateinit var path: String
+ lateinit var name: String
+ lateinit var mime: String
+ var bytes: Long = -1
+ lateinit var sha256: String
+}
+@InvokeArg
+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? {
+ if (session != null) { invoke.reject("Another file is being saved", "busy"); return null }
+ if (cancelled.remove(args.attemptId)) { resolve(invoke, args.attemptId, "cancelled", ""); return null }
+ cancelled.clear()
+ return ExportSession(args, invoke).also { session = it }
+ }
+ @Synchronized private fun settle(s: ExportSession, status: String, destination: String = "") {
+ if (s.terminal) return
+ s.terminal = true
+ if (session === s) session = null
+ if (status == "error") s.invoke.reject("File export failed", "write_failed")
+ else resolve(s.invoke, s.args.attemptId, status, destination)
+ }
+ private fun resolve(invoke: Invoke, id: String, status: String, destination: String) {
+ invoke.resolve(JSObject().apply { put("attemptId", id); put("status", status); put("destination", destination) })
+ }
+ fun start(activity: Activity, args: ExportArgs, invoke: Invoke) {
+ val s = acquire(args, invoke) ?: return
+ executor.execute {
+ 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)
+ }
+ } catch (_: Exception) { settle(s, "error") }
+ }
+ } catch (_: Exception) { settle(s, if (s.cancelled.get()) "cancelled" else "error") }
+ }
+ }
+ private fun validate(context: Context, args: ExportArgs) {
+ require(UUID.fromString(args.attemptId).toString() == args.attemptId)
+ require(args.bytes >= 0 && args.name.isNotEmpty() && File(args.name).name == args.name && args.name != "." && args.name != "..")
+ val source = File(args.path).canonicalFile
+ 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)
+ if (Build.VERSION.SDK_INT >= 29) try {
+ context.contentResolver.query(
+ MediaStore.Downloads.EXTERNAL_CONTENT_URI,
+ arrayOf(MediaStore.MediaColumns._ID),
+ "${MediaStore.MediaColumns.IS_PENDING}=1 AND ${MediaStore.MediaColumns.RELATIVE_PATH}=? AND ${MediaStore.MediaColumns.DISPLAY_NAME} LIKE ? AND ${MediaStore.MediaColumns.OWNER_PACKAGE_NAME}=?",
+ arrayOf("Download/Alook/", ".alook-%.partial", context.packageName), null,
+ )?.use { cursor ->
+ while (cursor.moveToNext()) context.contentResolver.delete(
+ android.content.ContentUris.withAppendedId(MediaStore.Downloads.EXTERNAL_CONTENT_URI, cursor.getLong(0)), null, null)
+ }
+ } catch (_: Exception) { }
+ for ((key, value) in prefs.all) {
+ if (key.startsWith("document:")) continue
+ val uri = Uri.parse(value as? String ?: continue)
+ try {
+ if (Build.VERSION.SDK_INT >= 29) {
+ context.contentResolver.query(uri, arrayOf(MediaStore.MediaColumns.IS_PENDING), null, null, null)?.use {
+ if (it.moveToFirst() && it.getInt(0) == 1) check(context.contentResolver.delete(uri, null, null) > 0)
+ }
+ }
+ check(prefs.edit().remove(key).commit())
+ } catch (_: Exception) { }
+ }
+ 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")
+ }
+ private fun documentCleanup(context: Context): FileSaveDocumentCleanup {
+ val preferences = prefs(context)
+ val store = object : DocumentCleanupStore {
+ override fun entries(): Map<String, DocumentCleanupRecord> = preferences.all.entries
+ .filter { it.key.startsWith("document:") }
+ .associate { (key, value) ->
+ val text = value as String
+ val record = if (text.startsWith("{")) {
+ val json = org.json.JSONObject(text)
+ DocumentCleanupRecord(json.getString("uri"), json.getBoolean("releaseOnly"))
+ } else DocumentCleanupRecord(text)
+ key.removePrefix("document:") to record
+ }
+ override fun put(token: String, record: DocumentCleanupRecord) {
+ val json = org.json.JSONObject().put("uri", record.uri).put("releaseOnly", record.releaseOnly)
+ check(preferences.edit().putString("document:$token", json.toString()).commit())
+ }
+ override fun remove(token: String) { check(preferences.edit().remove("document:$token").commit()) }
+ }
+ val provider = object : DocumentCleanupProvider {
+ override fun retain(uri: String) {
+ context.contentResolver.takePersistableUriPermission(Uri.parse(uri), Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
+ }
+ override fun delete(uri: String): Boolean {
+ val parsed = Uri.parse(uri)
+ return try {
+ if (DocumentsContract.deleteDocument(context.contentResolver, parsed)) true
+ else context.contentResolver.query(parsed, arrayOf(DocumentsContract.Document.COLUMN_DOCUMENT_ID), null, null, null)?.use { it.count == 0 } ?: false
+ } catch (_: java.io.FileNotFoundException) { true }
+ }
+ override fun release(uri: String) {
+ val parsed = Uri.parse(uri)
+ if (context.contentResolver.persistedUriPermissions.any { it.uri == parsed }) {
+ context.contentResolver.releasePersistableUriPermission(parsed, Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
+ }
+ }
+ }
+ return FileSaveDocumentCleanup(store, provider)
+ }
+
+}
+
+@TauriPlugin
+class FileSavePlugin(private val activity: Activity) : Plugin(activity) {
+ init { FileExporter.executor.execute { FileExporter.repair(activity.applicationContext) } }
+ @Command fun exportFile(invoke: Invoke) {
+ try { FileExporter.start(activity, invoke.parseArgs(ExportArgs::class.java), invoke) }
+ catch (_: Exception) { invoke.reject("Invalid file export", "invalid_request") }
+ }
+ @Command fun cancel(invoke: Invoke) {
+ try { FileExporter.cancel(invoke.parseArgs(CancelArgs::class.java).attemptId); invoke.resolve() }
+ catch (_: Exception) { invoke.reject("Invalid save cancellation", "invalid_request") }
+ }
+}
diff --git a/src/desktop/src-tauri/plugins/file-save/android/src/test/java/ai/alook/plugin/filesave/FileSaveCopyTest.kt b/src/desktop/src-tauri/plugins/file-save/android/src/test/java/ai/alook/plugin/filesave/FileSaveCopyTest.kt
new file mode 100644
index 000000000..f81b54382
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/file-save/android/src/test/java/ai/alook/plugin/filesave/FileSaveCopyTest.kt
@@ -0,0 +1,46 @@
+package ai.alook.plugin.filesave
+
+import org.junit.Assert.*
+import org.junit.Test
+import java.io.ByteArrayInputStream
+import java.io.ByteArrayOutputStream
+import java.io.IOException
+import java.io.OutputStream
+import java.security.MessageDigest
+
+class FileSaveCopyTest {
+ private fun hash(bytes: ByteArray) = MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) }
+ @Test fun exactStreamingBytesIncludingEmptyFile() {
+ for (size in listOf(0, 1, 65_537, 25 * 1024 * 1024)) {
+ val input = ByteArray(size) { (it % 251).toByte() }
+ val output = ByteArrayOutputStream()
+ FileSaveCopy.write(ByteArrayInputStream(input), output, size.toLong(), hash(input)) { false }
+ assertArrayEquals(input, output.toByteArray())
+ }
+ }
+ @Test fun rejectsShortLongAndCorruptSource() {
+ val bytes = "abc".toByteArray()
+ for ((size, sha) in listOf(2L to hash(bytes), 4L to hash(bytes), 3L to "bad")) {
+ assertThrows(IllegalStateException::class.java) {
+ FileSaveCopy.write(ByteArrayInputStream(bytes), ByteArrayOutputStream(), size, sha) { false }
+ }
+ }
+ }
+ @Test fun cancelsBetweenBoundedWrites() {
+ val bytes = ByteArray(131_072)
+ val output = ByteArrayOutputStream()
+ assertThrows(IllegalStateException::class.java) {
+ FileSaveCopy.write(ByteArrayInputStream(bytes), output, bytes.size.toLong(), hash(bytes)) { output.size() >= 65_536 }
+ }
+ assertEquals(65_536, output.size())
+ }
+ @Test fun propagatesDiskFullWithoutContinuing() {
+ val bytes = ByteArray(65_537)
+ var calls = 0
+ val output = object : OutputStream() {
+ override fun write(b: Int) { calls++; throw IOException("full") }
+ }
+ assertThrows(IOException::class.java) { FileSaveCopy.write(ByteArrayInputStream(bytes), output, bytes.size.toLong(), hash(bytes)) { false } }
+ assertEquals(1, calls)
+ }
+}
diff --git a/src/desktop/src-tauri/plugins/file-save/android/src/test/java/ai/alook/plugin/filesave/FileSaveDocumentCleanupTest.kt b/src/desktop/src-tauri/plugins/file-save/android/src/test/java/ai/alook/plugin/filesave/FileSaveDocumentCleanupTest.kt
new file mode 100644
index 000000000..28bd3c76c
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/file-save/android/src/test/java/ai/alook/plugin/filesave/FileSaveDocumentCleanupTest.kt
@@ -0,0 +1,105 @@
+package ai.alook.plugin.filesave
+
+import java.io.File
+import java.util.Properties
+import org.junit.Assert.*
+import org.junit.Test
+
+class FileSaveDocumentCleanupTest {
+ private class Store(val file: File) : DocumentCleanupStore {
+ var failRemove = false
+ var failPut = false
+ override fun entries(): Map<String, DocumentCleanupRecord> {
+ val props = Properties()
+ if (file.exists()) file.inputStream().use { props.load(it) }
+ return props.stringPropertyNames().associateWith {
+ val value = props.getProperty(it)
+ DocumentCleanupRecord(value.substring(1), value.startsWith("1"))
+ }
+ }
+ private fun write(records: Map<String, DocumentCleanupRecord>) {
+ val props = Properties()
+ records.forEach { (key, value) -> props[key] = (if (value.releaseOnly) "1" else "0") + value.uri }
+ file.outputStream().use { props.store(it, null) }
+ }
+ override fun put(token: String, record: DocumentCleanupRecord) {
+ check(!failPut)
+ write(entries() + (token to record))
+ }
+ override fun remove(token: String) {
+ check(!failRemove)
+ write(entries() - token)
+ }
+ }
+ private class Provider : DocumentCleanupProvider {
+ val documents = mutableSetOf("uri:A", "uri:B")
+ val grants = mutableSetOf<String>()
+ val failures = mutableSetOf<String>()
+ var throwDelete = false
+ var failRetain = false
+ override fun retain(uri: String) { check(!failRetain); grants.add(uri) }
+ override fun delete(uri: String): Boolean {
+ if (uri in failures) { if (throwDelete) error("provider failed"); return false }
+ documents.remove(uri)
+ return true
+ }
+ override fun release(uri: String) { grants.remove(uri) }
+ }
+ private fun fixture(test: (Store, Provider) -> Unit) {
+ val dir = kotlin.io.path.createTempDirectory("file-save-cleanup").toFile()
+ try { test(Store(File(dir, "journal")), Provider()) } finally { dir.deleteRecursively() }
+ }
+ @Test fun failedLateCleanupSurvivesRestartWithoutAffectingNextSave() = fixture { store, provider ->
+ provider.failures.add("uri:A")
+ assertFalse(FileSaveDocumentCleanup(store, provider).discard("A", "uri:A"))
+ assertTrue("uri:A" in provider.grants)
+ val next = FileSaveDocumentCleanup(Store(store.file), provider)
+ next.acquire("B", "uri:B")
+ assertTrue(next.published("B", "uri:B"))
+ assertFalse(next.repair())
+ assertEquals(setOf("A"), store.entries().keys)
+ provider.failures.clear()
+ assertTrue(FileSaveDocumentCleanup(Store(store.file), provider).repair())
+ assertEquals(setOf("uri:B"), provider.documents)
+ assertTrue(provider.grants.isEmpty())
+ assertTrue(store.entries().isEmpty())
+ }
+ @Test fun throwingProviderKeepsRecoveryRecord() = fixture { store, provider ->
+ provider.throwDelete = true
+ provider.failures.add("uri:A")
+ assertFalse(FileSaveDocumentCleanup(store, provider).discard("A", "uri:A"))
+ assertEquals(DocumentCleanupRecord("uri:A"), Store(store.file).entries()["A"])
+ provider.failures.clear()
+ assertTrue(FileSaveDocumentCleanup(Store(store.file), provider).repair())
+ }
+ @Test fun failedJournalRemovalRetriesReleaseWithoutDeletingPublishedFile() = fixture { store, provider ->
+ val cleanup = FileSaveDocumentCleanup(store, provider)
+ cleanup.acquire("A", "uri:A")
+ store.failRemove = true
+ assertFalse(cleanup.published("A", "uri:A"))
+ assertTrue(store.entries()["A"]!!.releaseOnly)
+ assertTrue(FileSaveDocumentCleanup(Store(store.file), provider).repair())
+ assertTrue("uri:A" in provider.documents)
+ }
+ @Test fun alreadyDeletedDocumentCanFinishAfterJournalRemovalFailure() = fixture { store, provider ->
+ store.failRemove = true
+ assertFalse(FileSaveDocumentCleanup(store, provider).discard("A", "uri:A"))
+ assertFalse("uri:A" in provider.documents)
+ assertTrue(FileSaveDocumentCleanup(Store(store.file), provider).repair())
+ assertTrue(store.entries().isEmpty())
+ }
+ @Test fun persistenceFailureIsReportedEvenIfImmediateDeletionSucceeds() = fixture { store, provider ->
+ store.failPut = true
+ assertFalse(FileSaveDocumentCleanup(store, provider).discard("A", "uri:A"))
+ assertFalse("uri:A" in provider.documents)
+ }
+ @Test fun permissionFailureKeepsFailedDeletionVisibleForRecovery() = fixture { store, provider ->
+ provider.failRetain = true
+ provider.failures.add("uri:A")
+ assertFalse(FileSaveDocumentCleanup(store, provider).discard("A", "uri:A"))
+ assertEquals(DocumentCleanupRecord("uri:A"), Store(store.file).entries()["A"])
+ provider.failRetain = false
+ provider.failures.clear()
+ assertTrue(FileSaveDocumentCleanup(Store(store.file), provider).repair())
+ }
+}
diff --git a/src/desktop/src-tauri/plugins/file-save/build.rs b/src/desktop/src-tauri/plugins/file-save/build.rs
new file mode 100644
index 000000000..250f8a216
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/file-save/build.rs
@@ -0,0 +1,7 @@
+fn main() {
+ tauri_plugin::Builder::new(&[])
+ .android_path("android")
+ .ios_path("ios")
+ .try_build()
+ .expect("failed to build file save plugin");
+}
diff --git a/src/desktop/src-tauri/plugins/file-save/ios/Package.swift b/src/desktop/src-tauri/plugins/file-save/ios/Package.swift
new file mode 100644
index 000000000..07a46cd6d
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/file-save/ios/Package.swift
@@ -0,0 +1,3 @@
+// swift-tools-version:5.3
+import PackageDescription
+let package = Package(name: "tauri-plugin-file-save", platforms: [.iOS(.v14)], products: [.library(name: "tauri-plugin-file-save", type: .static, targets: ["tauri-plugin-file-save"])], dependencies: [.package(name: "Tauri", path: "../.tauri/tauri-api")], targets: [.target(name: "tauri-plugin-file-save", dependencies: [.byName(name: "Tauri")], path: "Sources", linkerSettings: [.linkedFramework("UIKit"), .linkedFramework("CryptoKit")])])
diff --git a/src/desktop/src-tauri/plugins/file-save/ios/Sources/FileSaveCopy.swift b/src/desktop/src-tauri/plugins/file-save/ios/Sources/FileSaveCopy.swift
new file mode 100644
index 000000000..60d0b051f
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/file-save/ios/Sources/FileSaveCopy.swift
@@ -0,0 +1,26 @@
+import Foundation
+import CryptoKit
+
+enum FileSaveCopy {
+ static func write(source: URL, destination: URL, bytes expectedBytes: UInt64, sha256: String, cancelled: () -> Bool) throws {
+ guard FileManager.default.createFile(atPath: destination.path, contents: nil) else { throw CocoaError(.fileWriteUnknown) }
+ let input = try FileHandle(forReadingFrom: source)
+ let output = try FileHandle(forWritingTo: destination)
+ defer { try? input.close(); try? output.close() }
+ var bytes: UInt64 = 0
+ var hash = SHA256()
+ while true {
+ guard !cancelled() else { throw CocoaError(.userCancelled) }
+ guard let data = try input.read(upToCount: 65_536), !data.isEmpty else { break }
+ bytes += UInt64(data.count)
+ guard bytes <= expectedBytes else { throw CocoaError(.fileReadCorruptFile) }
+ try output.write(contentsOf: data)
+ hash.update(data: data)
+ }
+ guard !cancelled(), bytes == expectedBytes,
+ hash.finalize().map({ String(format: "%02x", $0) }).joined() == sha256 else { throw CocoaError(.fileReadCorruptFile) }
+ try output.synchronize()
+ try output.close()
+ try input.close()
+ }
+}
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
new file mode 100644
index 000000000..d6a95a33a
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/file-save/ios/Sources/FileSavePlugin.swift
@@ -0,0 +1,111 @@
+import Foundation
+import Tauri
+import UIKit
+import WebKit
+
+struct ExportArgs: Decodable {
+ let attemptId: String
+ let path: String
+ let name: String
+ let mime: String
+ let bytes: UInt64
+ let sha256: String
+}
+struct CancelArgs: Decodable { let attemptId: String }
+struct ExportResult: Encodable { let attemptId: String; let status: String; let destination: String }
+
+final class ExportSession: NSObject, UIDocumentPickerDelegate, UIAdaptivePresentationControllerDelegate {
+ let args: ExportArgs
+ let invoke: Invoke
+ let directory: URL
+ var picker: UIDocumentPickerViewController?
+ private let lock = NSLock()
+ private var stopped = false
+ var cancelled: Bool {
+ get { lock.lock(); defer { lock.unlock() }; return stopped }
+ set { lock.lock(); stopped = newValue; lock.unlock() }
+ }
+ var finished = false
+ var release: (() -> Void)?
+ init(_ args: ExportArgs, _ invoke: Invoke, _ directory: URL) {
+ self.args = args; self.invoke = invoke; self.directory = directory
+ }
+ func finish(_ status: String) {
+ guard !finished else { return }
+ finished = true
+ picker?.delegate = 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" : "")) }
+ 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
+ if let picker = picker { picker.dismiss(animated: true) { self.finish("cancelled") } }
+ }
+}
+
+final class FileSavePlugin: Plugin {
+ private var session: ExportSession?
+ private let queue = DispatchQueue(label: "ai.alook.file-save")
+ private var cancelledAttempts = Set<String>()
+ override func load(webview: WKWebView) {
+ guard session == nil else { return }
+ queue.async {
+ try? FileManager.default.removeItem(at: FileManager.default.temporaryDirectory.appendingPathComponent("alook-files", isDirectory: true))
+ }
+ }
+ @objc public func cancel(_ invoke: Invoke) throws {
+ let args = try invoke.parseArgs(CancelArgs.self)
+ DispatchQueue.main.async {
+ if self.session?.args.attemptId == args.attemptId { self.session?.cancel() }
+ else { if self.cancelledAttempts.count > 128 { self.cancelledAttempts.removeAll() }; self.cancelledAttempts.insert(args.attemptId) }
+ invoke.resolve()
+ }
+ }
+ @objc public func exportFile(_ invoke: Invoke) throws {
+ let args = try invoke.parseArgs(ExportArgs.self)
+ DispatchQueue.main.async {
+ guard self.session == nil else { invoke.reject("Another file is being saved", code: "busy"); return }
+ if self.cancelledAttempts.remove(args.attemptId) != nil {
+ invoke.resolve(ExportResult(attemptId: args.attemptId, status: "cancelled", destination: "")); return
+ }
+ self.cancelledAttempts.removeAll()
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent("alook-files", isDirectory: true)
+ let directory = root.appendingPathComponent(args.attemptId, isDirectory: true)
+ let session = ExportSession(args, invoke, directory)
+ session.release = { [weak self] in self?.session = nil }
+ self.session = session
+ self.queue.async {
+ do {
+ guard UUID(uuidString: args.attemptId) != nil, args.name == URL(fileURLWithPath: args.name).lastPathComponent,
+ !args.name.isEmpty, args.name != ".", args.name != ".." else { throw CocoaError(.fileReadInvalidFileName) }
+ let source = URL(fileURLWithPath: args.path).resolvingSymlinksInPath()
+ let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].resolvingSymlinksInPath().path + "/"
+ guard source.path.hasPrefix(caches), source.deletingLastPathComponent().lastPathComponent == "user-file-save",
+ source.lastPathComponent == args.attemptId + ".partial" else { throw CocoaError(.fileReadNoPermission) }
+ try? FileManager.default.removeItem(at: root)
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ let destination = directory.appendingPathComponent(args.name)
+ try FileSaveCopy.write(source: source, destination: destination, bytes: args.bytes, sha256: args.sha256) { session.cancelled }
+ DispatchQueue.main.async {
+ 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
+ presenter.present(picker, animated: true)
+ picker.presentationController?.delegate = session
+ }
+ } catch { DispatchQueue.main.async { session.finish(session.cancelled ? "cancelled" : "error") } }
+ }
+ }
+ }
+}
+@_cdecl("init_plugin_file_save")
+func initPlugin() -> Plugin { FileSavePlugin() }
diff --git a/src/desktop/src-tauri/plugins/file-save/ios/Tests/FileSaveCopyTests.swift b/src/desktop/src-tauri/plugins/file-save/ios/Tests/FileSaveCopyTests.swift
new file mode 100644
index 000000000..0f989e7c2
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/file-save/ios/Tests/FileSaveCopyTests.swift
@@ -0,0 +1,54 @@
+import Foundation
+import CryptoKit
+import XCTest
+@testable import FileSaveCopyCore
+
+final class FileSaveCopyTests: XCTestCase {
+ func fixture(_ action: (URL) throws -> Void) throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+ try action(root)
+ }
+ func hash(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() }
+ func testExactLargeAndEmptyFile() throws {
+ try fixture { root in
+ for size in [0, 1, 65_537, 25 * 1024 * 1024] {
+ let data = Data(repeating: 42, count: size)
+ let source = root.appendingPathComponent("source")
+ let target = root.appendingPathComponent("target")
+ try data.write(to: source)
+ try FileSaveCopy.write(source: source, destination: target, bytes: UInt64(size), sha256: hash(data)) { false }
+ XCTAssertEqual(try Data(contentsOf: target), data)
+ }
+ }
+ }
+ func testRejectsLengthAndHashMismatch() throws {
+ try fixture { root in
+ let data = Data("abc".utf8)
+ let source = root.appendingPathComponent("source")
+ try data.write(to: source)
+ for (size, sha) in [(UInt64(2), hash(data)), (4, hash(data)), (3, "bad")] {
+ XCTAssertThrowsError(try FileSaveCopy.write(source: source, destination: root.appendingPathComponent("target"), bytes: size, sha256: sha) { false })
+ }
+ }
+ }
+ func testCancellationStopsBetweenChunks() throws {
+ try fixture { root in
+ let data = Data(repeating: 1, count: 131_072)
+ let source = root.appendingPathComponent("source")
+ let target = root.appendingPathComponent("target")
+ try data.write(to: source)
+ var reads = 0
+ XCTAssertThrowsError(try FileSaveCopy.write(source: source, destination: target, bytes: UInt64(data.count), sha256: hash(data)) { reads += 1; return reads > 1 })
+ XCTAssertEqual(try Data(contentsOf: target).count, 65_536)
+ }
+ }
+ func testUnwritableDestinationFails() throws {
+ try fixture { root in
+ let source = root.appendingPathComponent("source")
+ try Data().write(to: source)
+ XCTAssertThrowsError(try FileSaveCopy.write(source: source, destination: root.appendingPathComponent("missing/target"), bytes: 0, sha256: hash(Data())) { false })
+ }
+ }
+}
diff --git a/src/desktop/src-tauri/plugins/file-save/scripts/test-swift-copy.sh b/src/desktop/src-tauri/plugins/file-save/scripts/test-swift-copy.sh
new file mode 100644
index 000000000..b4f37b92b
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/file-save/scripts/test-swift-copy.sh
@@ -0,0 +1,14 @@
+#!/bin/sh
+set -eu
+plugin_dir=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
+test_dir=$(mktemp -d "${TMPDIR:-/tmp}/alook-file-save-tests.XXXXXX")
+trap 'rm -rf "$test_dir"' EXIT HUP INT TERM
+mkdir -p "$test_dir/Sources/FileSaveCopyCore" "$test_dir/Tests/FileSaveCopyTests"
+cp "$plugin_dir/ios/Sources/FileSaveCopy.swift" "$test_dir/Sources/FileSaveCopyCore/"
+cp "$plugin_dir/ios/Tests/FileSaveCopyTests.swift" "$test_dir/Tests/FileSaveCopyTests/"
+cat > "$test_dir/Package.swift" <<'PACKAGE'
+// swift-tools-version:5.3
+import PackageDescription
+let package = Package(name: "FileSaveCopyCore", platforms: [.macOS(.v11)], targets: [.target(name: "FileSaveCopyCore"), .testTarget(name: "FileSaveCopyTests", dependencies: ["FileSaveCopyCore"])])
+PACKAGE
+swift test --package-path "$test_dir"
diff --git a/src/desktop/src-tauri/plugins/file-save/src/lib.rs b/src/desktop/src-tauri/plugins/file-save/src/lib.rs
new file mode 100644
index 000000000..6576ac310
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/file-save/src/lib.rs
@@ -0,0 +1,27 @@
+use serde::{Deserialize, Serialize};
+use tauri::{plugin::{Builder,TauriPlugin}, Manager, Runtime};
+#[cfg(mobile)] use tauri::plugin::PluginHandle;
+#[cfg(target_os="ios")] tauri::ios_plugin_binding!(init_plugin_file_save);
+#[derive(Serialize)]
+#[serde(rename_all="camelCase")]
+pub struct ExportRequest { pub attempt_id:String, pub path:String, pub name:String, pub mime:String, pub bytes:u64, pub sha256:String }
+#[derive(Deserialize)]
+#[serde(rename_all="camelCase")]
+pub struct ExportResult { pub attempt_id:String, pub status:String, pub destination:String }
+#[cfg(mobile)] pub struct FileSave<R:Runtime>(PluginHandle<R>);
+#[cfg(desktop)] pub struct FileSave<R:Runtime>(std::marker::PhantomData<R>);
+pub trait FileSaveExt<R:Runtime> { fn file_save(&self)->&FileSave<R>; }
+impl<R:Runtime,T:Manager<R>> FileSaveExt<R> for T { fn file_save(&self)->&FileSave<R> { self.state::<FileSave<R>>().inner() } }
+#[cfg(mobile)]
+impl<R:Runtime> FileSave<R> {
+ pub async fn export(&self,request:ExportRequest)->Result<ExportResult,tauri::plugin::mobile::PluginInvokeError> { self.0.run_mobile_plugin_async("exportFile",request).await }
+ pub async fn cancel(&self,attempt_id:String)->Result<(),tauri::plugin::mobile::PluginInvokeError> { self.0.run_mobile_plugin_async("cancel",serde_json::json!({"attemptId":attempt_id})).await }
+}
+pub fn init<R:Runtime>()->TauriPlugin<R> {
+ Builder::<R,()>::new("file-save").setup(|app,_api| {
+ #[cfg(target_os="android")] let plugin=FileSave(_api.register_android_plugin("ai.alook.plugin.filesave","FileSavePlugin")?);
+ #[cfg(target_os="ios")] let plugin=FileSave(_api.register_ios_plugin(init_plugin_file_save)?);
+ #[cfg(desktop)] let plugin=FileSave::<R>(std::marker::PhantomData);
+ app.manage(plugin); Ok(())
+ }).build()
+}
diff --git a/src/desktop/src-tauri/src/file_save.rs b/src/desktop/src-tauri/src/file_save.rs
new file mode 100644
index 000000000..e620b160c
--- /dev/null
+++ b/src/desktop/src-tauri/src/file_save.rs
@@ -0,0 +1,328 @@
+use base64::{engine::general_purpose::STANDARD, Engine};
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+use std::{
+ fs::{self, File, OpenOptions},
+ io::Write,
+ path::{Path, PathBuf},
+ sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc, Mutex,
+ },
+};
+use unicode_normalization::UnicodeNormalization;
+
+pub const CHUNK_BYTES: usize = 65_536;
+const MAX_BYTES: u64 = 9_007_199_254_740_991;
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct Begin {
+ pub attempt_id: String,
+ pub name: String,
+ pub mime: String,
+ pub size: Option<u64>,
+}
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct Chunk {
+ pub attempt_id: String,
+ pub sequence: u64,
+ pub offset: u64,
+ pub data: String,
+}
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct Commit {
+ pub attempt_id: String,
+ pub bytes: u64,
+}
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Ack {
+ pub attempt_id: String,
+ pub bytes: u64,
+ pub sequence: u64,
+}
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Receipt {
+ pub attempt_id: String,
+ pub status: &'static str,
+ pub name: String,
+ pub mime: String,
+ pub bytes: u64,
+ pub sha256: String,
+ pub destination: String,
+}
+
+pub fn safe_name(value: &str) -> String {
+ let base = value.rsplit(['/', '\\']).next().unwrap_or("");
+ let mut name: String = base
+ .nfc()
+ .filter(|c| !c.is_control())
+ .map(|c| if "<>:\"|?*".contains(c) { '_' } else { c })
+ .collect();
+ name = name
+ .trim_matches(|c: char| c == '.' || c.is_whitespace())
+ .to_owned();
+ if name.is_empty() {
+ name = "download".into();
+ }
+ let stem = name.split('.').next().unwrap_or("").to_ascii_uppercase();
+ if ["CON", "PRN", "AUX", "NUL"].contains(&stem.as_str())
+ || (stem.len() == 4
+ && (stem.starts_with("COM") || stem.starts_with("LPT"))
+ && matches!(stem.as_bytes()[3], b'1'..=b'9'))
+ {
+ name.insert(0, '_');
+ }
+ while name.len() > 180 {
+ name.pop();
+ }
+ name.trim_end_matches(|c: char| c == '.' || c.is_whitespace())
+ .to_owned()
+}
+fn valid_id(id: &str) -> bool {
+ id.len() == 36
+ && id.bytes().enumerate().all(|(i, b)| {
+ if [8, 13, 18, 23].contains(&i) {
+ b == b'-'
+ } else {
+ b.is_ascii_hexdigit()
+ }
+ })
+}
+fn valid_mime(mime: &str) -> bool {
+ mime.len() <= 127
+ && mime.split('/').count() == 2
+ && mime.split('/').all(|part| {
+ !part.is_empty()
+ && part
+ .bytes()
+ .all(|b| b.is_ascii_alphanumeric() || b"!#$&^_.+-".contains(&b))
+ })
+}
+
+pub struct Transfer {
+ pub metadata: Begin,
+ pub path: PathBuf,
+ file: Option<File>,
+ pub bytes: u64,
+ sequence: u64,
+ hash: Sha256,
+ pub cancelled: Arc<AtomicBool>,
+ pub publish_guard: Arc<Mutex<()>>,
+ sealed: bool,
+}
+impl Drop for Transfer {
+ fn drop(&mut self) {
+ self.file.take();
+ let _ = fs::remove_file(&self.path);
+ }
+}
+impl Transfer {
+ pub fn begin(root: &Path, metadata: Begin) -> Result<Self, String> {
+ if !valid_id(&metadata.attempt_id)
+ || safe_name(&metadata.name) != metadata.name
+ || !valid_mime(&metadata.mime)
+ || metadata.size.is_some_and(|n| n > MAX_BYTES)
+ {
+ return Err("Invalid file metadata".into());
+ }
+ fs::create_dir_all(root).map_err(|_| "Save storage unavailable")?;
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ fs::set_permissions(root, fs::Permissions::from_mode(0o700))
+ .map_err(|_| "Save storage unavailable")?;
+ }
+ let path = root.join(format!("{}.partial", metadata.attempt_id));
+ let mut options = OpenOptions::new();
+ options.write(true).create_new(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ options.mode(0o600);
+ }
+ let file = options
+ .open(&path)
+ .map_err(|_| "Save storage unavailable")?;
+ Ok(Self {
+ metadata,
+ path,
+ file: Some(file),
+ bytes: 0,
+ sequence: 0,
+ hash: Sha256::new(),
+ cancelled: Arc::new(AtomicBool::new(false)),
+ publish_guard: Arc::new(Mutex::new(())),
+ sealed: false,
+ })
+ }
+ pub fn ack(&self) -> Ack {
+ Ack {
+ attempt_id: self.metadata.attempt_id.clone(),
+ bytes: self.bytes,
+ sequence: self.sequence,
+ }
+ }
+ pub fn write(&mut self, chunk: Chunk) -> Result<Ack, String> {
+ if self.cancelled.load(Ordering::Acquire)
+ || self.sealed
+ || chunk.attempt_id != self.metadata.attempt_id
+ || chunk.sequence != self.sequence
+ || chunk.offset != self.bytes
+ || chunk.data.len() > CHUNK_BYTES.div_ceil(3) * 4
+ {
+ return Err("Invalid save chunk".into());
+ }
+ let data = STANDARD
+ .decode(chunk.data)
+ .map_err(|_| "Invalid save chunk")?;
+ if data.is_empty() || data.len() > CHUNK_BYTES {
+ return Err("Invalid save chunk".into());
+ }
+ let next = self
+ .bytes
+ .checked_add(data.len() as u64)
+ .filter(|n| *n <= MAX_BYTES)
+ .ok_or("File too large")?;
+ if self.metadata.size.is_some_and(|size| next > size) {
+ return Err("File length mismatch".into());
+ }
+ self.file
+ .as_mut()
+ .ok_or("Save already closed")?
+ .write_all(&data)
+ .map_err(|_| "File write failed")?;
+ self.hash.update(&data);
+ self.bytes = next;
+ self.sequence += 1;
+ Ok(self.ack())
+ }
+ pub fn seal(&mut self, commit: Commit) -> Result<(), String> {
+ if self.cancelled.load(Ordering::Acquire)
+ || self.sealed
+ || commit.attempt_id != self.metadata.attempt_id
+ || commit.bytes != self.bytes
+ || self.metadata.size.is_some_and(|size| size != self.bytes)
+ {
+ return Err("File length mismatch".into());
+ }
+ self.file
+ .take()
+ .ok_or("Save already closed")?
+ .sync_all()
+ .map_err(|_| "File write failed")?;
+ self.sealed = true;
+ Ok(())
+ }
+ pub fn receipt(&self, destination: Option<String>) -> Receipt {
+ Receipt {
+ attempt_id: self.metadata.attempt_id.clone(),
+ status: if destination.is_some() {
+ "saved"
+ } else {
+ "cancelled"
+ },
+ name: self.metadata.name.clone(),
+ mime: self.metadata.mime.clone(),
+ bytes: self.bytes,
+ sha256: format!("{:x}", self.hash.clone().finalize()),
+ destination: destination.unwrap_or_default(),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ fn transfer(size: Option<u64>) -> Transfer {
+ let mut random = [0u8; 16];
+ getrandom::fill(&mut random).unwrap();
+ let root = std::env::temp_dir().join(format!("alook-save-test-{:x?}", random));
+ Transfer::begin(
+ &root,
+ Begin {
+ attempt_id: "00000000-0000-0000-0000-000000000001".into(),
+ name: "file.bin".into(),
+ mime: "application/octet-stream".into(),
+ size,
+ },
+ )
+ .unwrap()
+ }
+ fn chunk(t: &Transfer, bytes: &[u8]) -> Chunk {
+ Chunk {
+ attempt_id: t.metadata.attempt_id.clone(),
+ sequence: t.sequence,
+ offset: t.bytes,
+ data: STANDARD.encode(bytes),
+ }
+ }
+ #[test]
+ fn bounded_stream_has_exact_hash_and_cleanup() {
+ let mut t = transfer(Some(3));
+ let path = t.path.clone();
+ let root = path.parent().unwrap().to_owned();
+ let c = chunk(&t, b"abc");
+ assert_eq!(t.write(c).unwrap().bytes, 3);
+ t.seal(Commit {
+ attempt_id: t.metadata.attempt_id.clone(),
+ bytes: 3,
+ })
+ .unwrap();
+ assert_eq!(
+ t.receipt(Some("desktop".into())).sha256,
+ "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
+ );
+ assert_eq!(fs::read(&path).unwrap(), b"abc");
+ drop(t);
+ assert!(!path.exists());
+ fs::remove_dir(root).unwrap();
+ }
+ #[test]
+ fn rejects_replay_offset_oversize_and_incomplete_commit() {
+ let mut t = transfer(Some(4));
+ let mut c = chunk(&t, b"a");
+ c.offset = 1;
+ assert!(t.write(c).is_err());
+ let c = chunk(&t, &vec![0; CHUNK_BYTES + 1]);
+ assert!(t.write(c).is_err());
+ let c = chunk(&t, b"a");
+ t.write(c).unwrap();
+ assert!(t
+ .seal(Commit {
+ attempt_id: t.metadata.attempt_id.clone(),
+ bytes: 1
+ })
+ .is_err());
+ let mut c = chunk(&t, b"a");
+ c.sequence = 0;
+ assert!(t.write(c).is_err());
+ t.cancelled.store(true, Ordering::Release);
+ let c = chunk(&t, b"a");
+ assert!(t.write(c).is_err());
+ let root = t.path.parent().unwrap().to_owned();
+ drop(t);
+ fs::remove_dir(root).unwrap();
+ }
+ #[test]
+ fn empty_file_and_names() {
+ assert_eq!(safe_name("../CON.txt"), "_CON.txt");
+ assert_eq!(safe_name("x\\a\0:b?.txt "), "a_b_.txt");
+ assert_eq!(safe_name("..."), "download");
+ assert!(safe_name(&"中".repeat(100)).len() <= 180);
+ let mut t = transfer(Some(0));
+ t.seal(Commit {
+ attempt_id: t.metadata.attempt_id.clone(),
+ bytes: 0,
+ })
+ .unwrap();
+ assert_eq!(t.receipt(None).status, "cancelled");
+ let root = t.path.parent().unwrap().to_owned();
+ drop(t);
+ fs::remove_dir(root).unwrap();
+ }
+}
diff --git a/src/desktop/src-tauri/src/file_save_journal.rs b/src/desktop/src-tauri/src/file_save_journal.rs
new file mode 100644
index 000000000..b21fb51d4
--- /dev/null
+++ b/src/desktop/src-tauri/src/file_save_journal.rs
@@ -0,0 +1,202 @@
+use std::{
+ fs::{self, File, OpenOptions},
+ io::{self, Write},
+ path::{Path, PathBuf},
+};
+
+pub trait JournalIo {
+ fn remove(&self, path: &Path) -> io::Result<()>;
+ fn write_record(&self, file: &mut File, bytes: &[u8]) -> io::Result<()>;
+}
+pub struct Disk;
+impl JournalIo for Disk {
+ fn remove(&self, path: &Path) -> io::Result<()> {
+ fs::remove_file(path)
+ }
+ fn write_record(&self, file: &mut File, bytes: &[u8]) -> io::Result<()> {
+ file.write_all(bytes)?;
+ file.sync_all()
+ }
+}
+fn remove_if_present(io: &impl JournalIo, path: &Path) -> Result<(), String> {
+ match io.remove(path) {
+ Ok(()) => Ok(()),
+ Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
+ Err(_) => Err("Save cleanup failed".into()),
+ }
+}
+fn record(root: &Path) -> PathBuf {
+ root.join("desktop-export.json")
+}
+fn pending(root: &Path) -> PathBuf {
+ root.join("desktop-export.json.pending")
+}
+
+pub fn repair(root: &Path, io: &impl JournalIo) -> Result<(), String> {
+ let journal = record(root);
+ match fs::read(&journal) {
+ Ok(bytes) => {
+ let partial: PathBuf =
+ serde_json::from_slice(&bytes).map_err(|_| "Save cleanup failed")?;
+ let name = partial
+ .file_name()
+ .and_then(|n| n.to_str())
+ .ok_or("Save cleanup failed")?;
+ if !partial.is_absolute()
+ || !name.starts_with(".alook-")
+ || !name.ends_with(".partial")
+ || name.len() != 51
+ {
+ return Err("Save cleanup failed".into());
+ }
+ remove_if_present(io, &partial)?;
+ remove_if_present(io, &journal)?;
+ }
+ Err(e) if e.kind() == io::ErrorKind::NotFound => {}
+ Err(_) => return Err("Save cleanup failed".into()),
+ }
+ remove_if_present(io, &pending(root))
+}
+
+pub fn prepare(root: &Path, partial: &Path, io: &impl JournalIo) -> Result<(), String> {
+ let journal = record(root);
+ if journal
+ .try_exists()
+ .map_err(|_| "Save journal unavailable")?
+ {
+ return Err("Save cleanup required".into());
+ }
+ let pending = pending(root);
+ let mut options = OpenOptions::new();
+ options.create_new(true).write(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ options.mode(0o600);
+ }
+ let mut file = options
+ .open(&pending)
+ .map_err(|_| "Save journal unavailable")?;
+ let result = (|| {
+ let bytes = serde_json::to_vec(partial).map_err(|_| "Save journal failed")?;
+ io.write_record(&mut file, &bytes)
+ .map_err(|_| "Save journal failed")?;
+ fs::hard_link(&pending, &journal).map_err(|_| "Save journal publish failed")?;
+ Ok(())
+ })();
+ drop(file);
+ let _ = remove_if_present(io, &pending);
+ result
+}
+
+pub fn finish(
+ root: &Path,
+ partial: &Path,
+ created: bool,
+ io: &impl JournalIo,
+) -> Result<(), String> {
+ if created {
+ remove_if_present(io, partial)?;
+ }
+ remove_if_present(io, &record(root))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::Mutex;
+ struct Faults {
+ blocked: Mutex<Option<PathBuf>>,
+ fail_write: bool,
+ }
+ impl JournalIo for Faults {
+ fn remove(&self, path: &Path) -> io::Result<()> {
+ if self.blocked.lock().unwrap().as_deref() == Some(path) {
+ Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected"))
+ } else {
+ fs::remove_file(path)
+ }
+ }
+ fn write_record(&self, file: &mut File, bytes: &[u8]) -> io::Result<()> {
+ if self.fail_write {
+ file.write_all(b"{")?;
+ Err(io::Error::other("injected sync failure"))
+ } else {
+ Disk.write_record(file, bytes)
+ }
+ }
+ }
+ fn root() -> PathBuf {
+ let mut bytes = [0; 16];
+ getrandom::fill(&mut bytes).unwrap();
+ let p = std::env::temp_dir().join(format!("alook-journal-{:x?}", bytes));
+ fs::create_dir_all(&p).unwrap();
+ p
+ }
+ const A: &str = ".alook-00000000-0000-4000-8000-000000000001.partial";
+ const B: &str = ".alook-00000000-0000-4000-8000-000000000002.partial";
+ #[test]
+ fn failed_cleanup_blocks_overwrite_then_restart_recovers() {
+ let root = root();
+ let a = root.join(A);
+ let b = root.join(B);
+ let target = root.join("complete-b");
+ fs::write(&a, b"partial-a").unwrap();
+ fs::write(&target, b"old").unwrap();
+ prepare(&root, &a, &Disk).unwrap();
+ let original = fs::read(record(&root)).unwrap();
+ let fault = Faults {
+ blocked: Mutex::new(Some(a.clone())),
+ fail_write: false,
+ };
+ assert!(finish(&root, &a, true, &fault).is_err());
+ assert!(repair(&root, &fault).is_err());
+ assert!(prepare(&root, &b, &Disk).is_err());
+ assert_eq!(fs::read(record(&root)).unwrap(), original);
+ assert_eq!(fs::read(&target).unwrap(), b"old");
+ assert!(!b.exists());
+ repair(&root, &Disk).unwrap();
+ assert!(!a.exists());
+ prepare(&root, &b, &Disk).unwrap();
+ fs::write(&b, b"complete-b").unwrap();
+ fs::rename(&b, &target).unwrap();
+ finish(&root, &b, true, &Disk).unwrap();
+ assert_eq!(fs::read(target).unwrap(), b"complete-b");
+ assert!(!record(&root).exists());
+ fs::remove_dir_all(root).unwrap();
+ }
+ #[test]
+ fn incomplete_record_never_becomes_a_cleanup_obligation() {
+ let root = root();
+ let partial = root.join(A);
+ let fault = Faults {
+ blocked: Mutex::new(None),
+ fail_write: true,
+ };
+ assert!(prepare(&root, &partial, &fault).is_err());
+ assert!(!partial.exists());
+ assert!(!record(&root).exists());
+ repair(&root, &Disk).unwrap();
+ prepare(&root, &partial, &Disk).unwrap();
+ repair(&root, &Disk).unwrap();
+ fs::remove_dir_all(root).unwrap();
+ }
+ #[test]
+ fn record_removal_failure_after_publish_never_removes_target() {
+ let root = root();
+ let partial = root.join(A);
+ let target = root.join("saved");
+ prepare(&root, &partial, &Disk).unwrap();
+ fs::write(&partial, b"exact").unwrap();
+ fs::rename(&partial, &target).unwrap();
+ let fault = Faults {
+ blocked: Mutex::new(Some(record(&root))),
+ fail_write: false,
+ };
+ assert!(finish(&root, &partial, true, &fault).is_err());
+ assert!(repair(&root, &fault).is_err());
+ repair(&root, &Disk).unwrap();
+ assert_eq!(fs::read(target).unwrap(), b"exact");
+ fs::remove_dir_all(root).unwrap();
+ }
+}
diff --git a/src/desktop/src-tauri/src/file_save_runtime.rs b/src/desktop/src-tauri/src/file_save_runtime.rs
new file mode 100644
index 000000000..c739d5228
--- /dev/null
+++ b/src/desktop/src-tauri/src/file_save_runtime.rs
@@ -0,0 +1,378 @@
+use crate::{
+ file_save::{Ack, Begin, Chunk, Commit, Receipt, Transfer},
+ native_command_guard,
+};
+use std::{
+ collections::VecDeque,
+ fs,
+ path::PathBuf,
+ sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc, Mutex,
+ },
+};
+use tauri::{AppHandle, Manager, State, WebviewWindow};
+
+#[derive(Default)]
+pub struct FileSaveState {
+ session: Mutex<Session>,
+ ready: AtomicBool,
+}
+#[derive(Default)]
+struct Session {
+ transfer: Option<Transfer>,
+ recent_attempts: VecDeque<String>,
+ exporting: Option<(String, Arc<AtomicBool>, Arc<Mutex<()>>)>,
+}
+fn root(app: &AppHandle) -> Result<PathBuf, String> {
+ Ok(app
+ .path()
+ .app_cache_dir()
+ .map_err(|_| "Save storage unavailable")?
+ .join("user-file-save"))
+}
+pub fn setup(app: &AppHandle) -> Result<(), String> {
+ let path = root(app)?;
+ #[cfg(desktop)]
+ repair_desktop(&path)?;
+ if path.exists() {
+ fs::remove_dir_all(&path).map_err(|_| "Save cleanup failed")?;
+ }
+ fs::create_dir_all(path).map_err(|_| "Save storage unavailable")?;
+ app.state::<FileSaveState>()
+ .ready
+ .store(true, Ordering::Release);
+ Ok(())
+}
+pub fn retire(app: &AppHandle) {
+ if let Ok(mut state) = app.state::<FileSaveState>().session.lock() {
+ state.transfer.take();
+ if let Some((id, cancelled, publish_guard)) = &state.exporting {
+ let _publication = publish_guard.lock().ok();
+ cancelled.store(true, Ordering::Release);
+ #[cfg(mobile)]
+ {
+ use tauri_plugin_file_save::FileSaveExt;
+ let app = app.clone();
+ let id = id.clone();
+ tauri::async_runtime::spawn(async move {
+ let _ = app.file_save().cancel(id).await;
+ });
+ }
+ #[cfg(desktop)]
+ let _ = id;
+ }
+ }
+}
+#[tauri::command]
+pub fn file_save_begin(
+ window: WebviewWindow,
+ state: State<'_, FileSaveState>,
+ payload: Begin,
+) -> Result<Ack, String> {
+ native_command_guard::guard(&window)?;
+ let mut state = state.session.lock().map_err(|_| "Save state unavailable")?;
+ if state.transfer.is_some() || state.exporting.is_some() {
+ return Err("Another file is being saved".into());
+ }
+ if !window
+ .app_handle()
+ .state::<FileSaveState>()
+ .ready
+ .load(Ordering::Acquire)
+ {
+ setup(window.app_handle())?;
+ }
+ #[cfg(desktop)]
+ repair_desktop(&root(window.app_handle())?)?;
+ if state.recent_attempts.contains(&payload.attempt_id) {
+ return Err("Save attempt already used".into());
+ }
+ let transfer = Transfer::begin(&root(window.app_handle())?, payload)?;
+ state
+ .recent_attempts
+ .push_back(transfer.metadata.attempt_id.clone());
+ if state.recent_attempts.len() > 256 {
+ state.recent_attempts.pop_front();
+ }
+ let ack = transfer.ack();
+ state.transfer = Some(transfer);
+ Ok(ack)
+}
+#[tauri::command]
+pub fn file_save_write_chunk(
+ window: WebviewWindow,
+ state: State<'_, FileSaveState>,
+ payload: Chunk,
+) -> Result<Ack, String> {
+ native_command_guard::guard(&window)?;
+ let mut state = state.session.lock().map_err(|_| "Save state unavailable")?;
+ let transfer = state.transfer.as_mut().ok_or("No active save")?;
+ if transfer.metadata.attempt_id != payload.attempt_id {
+ return Err("Unknown save attempt".into());
+ }
+ let result = transfer.write(payload);
+ if result.is_err() {
+ state.transfer.take();
+ }
+ result
+}
+#[tauri::command]
+pub async fn file_save_cancel(
+ window: WebviewWindow,
+ app: AppHandle,
+ attempt_id: String,
+) -> Result<(), String> {
+ native_command_guard::guard(&window)?;
+ let exporting = {
+ let state = app.state::<FileSaveState>();
+ let mut state = state.session.lock().map_err(|_| "Save state unavailable")?;
+ if state
+ .transfer
+ .as_ref()
+ .is_some_and(|t| t.metadata.attempt_id == attempt_id)
+ {
+ state.transfer.take();
+ }
+ if let Some((id, cancelled, publish_guard)) = &state.exporting {
+ if id == &attempt_id {
+ let _publication = publish_guard.lock().ok();
+ cancelled.store(true, Ordering::Release);
+ true
+ } else {
+ false
+ }
+ } else {
+ false
+ }
+ };
+ #[cfg(mobile)]
+ if exporting {
+ use tauri_plugin_file_save::FileSaveExt;
+ app.file_save()
+ .cancel(attempt_id)
+ .await
+ .map_err(|_| "Save cancellation failed")?;
+ }
+ #[cfg(desktop)]
+ let _ = exporting;
+ Ok(())
+}
+#[tauri::command]
+pub async fn file_save_commit(
+ window: WebviewWindow,
+ app: AppHandle,
+ payload: Commit,
+) -> Result<Receipt, String> {
+ native_command_guard::guard(&window)?;
+ let mut transfer = {
+ let state = app.state::<FileSaveState>();
+ let mut state = state.session.lock().map_err(|_| "Save state unavailable")?;
+ if state
+ .transfer
+ .as_ref()
+ .is_none_or(|t| t.metadata.attempt_id != payload.attempt_id)
+ {
+ return Err("Unknown save attempt".into());
+ }
+ let transfer = state.transfer.take().ok_or("No active save")?;
+ state.exporting = Some((
+ transfer.metadata.attempt_id.clone(),
+ transfer.cancelled.clone(),
+ transfer.publish_guard.clone(),
+ ));
+ transfer
+ };
+ let result = match transfer.seal(payload) {
+ Err(error) => Err(error),
+ Ok(()) => export(&app, &transfer)
+ .await
+ .map(|destination| transfer.receipt(destination)),
+ };
+ if let Ok(mut state) = app.state::<FileSaveState>().session.lock() {
+ state.exporting = None;
+ }
+ result
+}
+#[cfg(mobile)]
+async fn export(app: &AppHandle, transfer: &Transfer) -> Result<Option<String>, String> {
+ use tauri_plugin_file_save::{ExportRequest, FileSaveExt};
+ if transfer.cancelled.load(Ordering::Acquire) {
+ return Ok(None);
+ }
+ let result = app
+ .file_save()
+ .export(ExportRequest {
+ attempt_id: transfer.metadata.attempt_id.clone(),
+ path: transfer.path.to_string_lossy().into_owned(),
+ name: transfer.metadata.name.clone(),
+ mime: transfer.metadata.mime.clone(),
+ bytes: transfer.bytes,
+ sha256: transfer.receipt(None).sha256,
+ })
+ .await
+ .map_err(|_| "File export failed")?;
+ if result.attempt_id != transfer.metadata.attempt_id {
+ return Err("Invalid export receipt".into());
+ }
+ match result.status.as_str() {
+ "saved" if ["downloads", "files", "document"].contains(&result.destination.as_str()) => {
+ Ok(Some(result.destination))
+ }
+ "cancelled" => Ok(None),
+ _ => Err("File export failed".into()),
+ }
+}
+#[cfg(desktop)]
+async fn export(app: &AppHandle, transfer: &Transfer) -> Result<Option<String>, String> {
+ use tauri_plugin_dialog::DialogExt;
+ let journal = root(app)?;
+ let app = app.clone();
+ let name = transfer.metadata.name.clone();
+ let path = tauri::async_runtime::spawn_blocking(move || {
+ app.dialog().file().set_file_name(name).blocking_save_file()
+ })
+ .await
+ .map_err(|_| "Save dialog failed")?;
+ if transfer.cancelled.load(Ordering::Acquire) {
+ return Ok(None);
+ }
+ let Some(path) = path else {
+ return Ok(None);
+ };
+ let path = path.into_path().map_err(|_| "Invalid save destination")?;
+ let source = transfer.path.clone();
+ let id = transfer.metadata.attempt_id.clone();
+ let cancelled = transfer.cancelled.clone();
+ let publish_guard = transfer.publish_guard.clone();
+ tauri::async_runtime::spawn_blocking(move || {
+ copy_desktop(&source, &path, &id, &cancelled, &publish_guard, &journal)
+ })
+ .await
+ .map_err(|_| "File export failed")?
+}
+#[cfg(desktop)]
+fn copy_desktop(
+ source: &std::path::Path,
+ target: &std::path::Path,
+ id: &str,
+ cancelled: &AtomicBool,
+ publish_guard: &Mutex<()>,
+ journal: &std::path::Path,
+) -> Result<Option<String>, String> {
+ use std::io::{Read, Write};
+ let parent = target.parent().ok_or("Invalid save destination")?;
+ let partial = parent.join(format!(".alook-{id}.partial"));
+ crate::file_save_journal::repair(journal, &crate::file_save_journal::Disk)?;
+ crate::file_save_journal::prepare(journal, &partial, &crate::file_save_journal::Disk)?;
+ let mut created = false;
+ let result = (|| {
+ let mut input = fs::File::open(source).map_err(|_| "File read failed")?;
+ let mut options = fs::OpenOptions::new();
+ options.create_new(true).write(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ options.mode(0o600);
+ }
+ let mut output = options.open(&partial).map_err(|_| "File write failed")?;
+ created = true;
+ let mut buffer = [0u8; 65_536];
+ loop {
+ if cancelled.load(Ordering::Acquire) {
+ return Ok(None);
+ }
+ let n = input.read(&mut buffer).map_err(|_| "File read failed")?;
+ if n == 0 {
+ break;
+ }
+ output
+ .write_all(&buffer[..n])
+ .map_err(|_| "File write failed")?;
+ }
+ output.sync_all().map_err(|_| "File write failed")?;
+ drop(output);
+ let _publication = publish_guard.lock().map_err(|_| "Save state unavailable")?;
+ if cancelled.load(Ordering::Acquire) {
+ return Ok(None);
+ }
+ fs::rename(&partial, target).map_err(|_| "File publish failed")?;
+ Ok(Some("desktop".into()))
+ })();
+ let _ = crate::file_save_journal::finish(
+ journal,
+ &partial,
+ created,
+ &crate::file_save_journal::Disk,
+ );
+ result
+}
+#[cfg(desktop)]
+fn repair_desktop(root: &std::path::Path) -> Result<(), String> {
+ crate::file_save_journal::repair(root, &crate::file_save_journal::Disk)
+}
+#[cfg(all(test, desktop))]
+mod tests {
+ use super::*;
+ fn fixture() -> PathBuf {
+ let mut bytes = [0u8; 16];
+ getrandom::fill(&mut bytes).unwrap();
+ let root = std::env::temp_dir().join(format!("alook-export-test-{:x?}", bytes));
+ fs::create_dir_all(&root).unwrap();
+ root
+ }
+ const ID: &str = "00000000-0000-4000-8000-000000000001";
+ #[test]
+ fn atomic_export_replaces_only_after_complete_and_cleans_cancel() {
+ let root = fixture();
+ let source = root.join("source");
+ let target = root.join("target");
+ fs::write(&source, vec![42; 131_073]).unwrap();
+ fs::write(&target, b"old").unwrap();
+ assert_eq!(
+ copy_desktop(
+ &source,
+ &target,
+ ID,
+ &AtomicBool::new(true),
+ &Mutex::new(()),
+ &root
+ )
+ .unwrap(),
+ None
+ );
+ assert_eq!(fs::read(&target).unwrap(), b"old");
+ assert_eq!(
+ copy_desktop(
+ &source,
+ &target,
+ ID,
+ &AtomicBool::new(false),
+ &Mutex::new(()),
+ &root
+ )
+ .unwrap(),
+ Some("desktop".into())
+ );
+ assert_eq!(fs::read(&target).unwrap(), fs::read(source).unwrap());
+ assert!(!root.join("desktop-export.json").exists());
+ fs::remove_dir_all(root).unwrap();
+ }
+ #[test]
+ fn startup_reclaims_partial_and_keeps_existing_destination() {
+ let root = fixture();
+ let partial = root.join(format!(".alook-{ID}.partial"));
+ let target = root.join("target");
+ fs::write(&partial, b"incomplete").unwrap();
+ fs::write(&target, b"old").unwrap();
+ fs::write(
+ root.join("desktop-export.json"),
+ serde_json::to_vec(&partial).unwrap(),
+ )
+ .unwrap();
+ repair_desktop(&root).unwrap();
+ assert!(!partial.exists());
+ assert_eq!(fs::read(target).unwrap(), b"old");
+ fs::remove_dir_all(root).unwrap();
+ }
+}
diff --git a/src/desktop/src-tauri/src/lib.rs b/src/desktop/src-tauri/src/lib.rs
index 88a2ab81f..80d071ad9 100644
--- a/src/desktop/src-tauri/src/lib.rs
+++ b/src/desktop/src-tauri/src/lib.rs
@@ -1,4 +1,8 @@
mod commands;
+mod file_save;
+#[cfg(desktop)]
+mod file_save_journal;
+mod file_save_runtime;
use tauri::Manager;
@@ -35,6 +39,7 @@ pub fn run() {
commands::show_main_window(app);
}));
let builder = builder
+ .manage(file_save_runtime::FileSaveState::default())
.plugin(tauri_plugin_deep_link::init())
.plugin(tauri_plugin_store::Builder::default().build())
.plugin(tauri_plugin_opener::init());
@@ -76,8 +81,13 @@ fn run_mobile(mut builder: tauri::Builder<tauri::Wry>) {
builder = builder
.manage(mobile_share_image::MobileShareImageState::default())
.plugin(tauri_plugin_mobile_share_image::init())
+ .plugin(tauri_plugin_file_save::init())
.plugin(tauri_plugin_mobile_push::init());
builder = builder.invoke_handler(tauri::generate_handler![
+ file_save_runtime::file_save_begin,
+ file_save_runtime::file_save_write_chunk,
+ file_save_runtime::file_save_commit,
+ file_save_runtime::file_save_cancel,
mobile_share_image_runtime::mobile_share_image_copy,
mobile_share_image_runtime::mobile_share_image_save,
mobile_system_notification_runtime::mobile_system_notification_check_permission,
@@ -99,6 +109,9 @@ fn run_mobile(mut builder: tauri::Builder<tauri::Wry>) {
]);
builder = builder.setup(|app| {
+ if file_save_runtime::setup(app.handle()).is_err() {
+ eprintln!("file save storage unavailable");
+ }
if let Some(window) = app.get_webview_window("main") {
webview_recovery::attach(&window);
}
@@ -114,6 +127,7 @@ fn run_mobile(mut builder: tauri::Builder<tauri::Wry>) {
&& matches!(payload.event(), tauri::webview::PageLoadEvent::Started)
{
native_oauth_runtime::retire_listener(webview.app_handle());
+ file_save_runtime::retire(webview.app_handle());
}
});
@@ -133,6 +147,10 @@ fn run_desktop(mut builder: tauri::Builder<tauri::Wry>) {
// Register IPC commands (desktop only)
builder = builder.invoke_handler(tauri::generate_handler![
+ file_save_runtime::file_save_begin,
+ file_save_runtime::file_save_write_chunk,
+ file_save_runtime::file_save_commit,
+ file_save_runtime::file_save_cancel,
commands::daemon_runtime_capability,
commands::daemon_pair,
commands::set_window_theme,
@@ -155,6 +173,9 @@ fn run_desktop(mut builder: tauri::Builder<tauri::Wry>) {
// System tray + window setup (desktop only)
builder = builder.setup(|app| {
+ if file_save_runtime::setup(app.handle()).is_err() {
+ eprintln!("file save storage unavailable");
+ }
if let Some(window) = app.get_webview_window("main") {
webview_recovery::attach(&window);
}
@@ -202,6 +223,7 @@ fn run_desktop(mut builder: tauri::Builder<tauri::Wry>) {
&& matches!(payload.event(), tauri::webview::PageLoadEvent::Started)
{
native_oauth_runtime::retire_listener(webview.app_handle());
+ file_save_runtime::retire(webview.app_handle());
system_notifications::retire_listener(webview.app_handle());
}
});
@@ -209,6 +231,7 @@ fn run_desktop(mut builder: tauri::Builder<tauri::Wry>) {
builder = builder.on_window_event(|window, event| {
if window.label() == "main" && matches!(event, tauri::WindowEvent::Destroyed) {
native_oauth_runtime::retire_listener(window.app_handle());
+ file_save_runtime::retire(window.app_handle());
system_notifications::retire_listener(window.app_handle());
}
#[cfg(target_os = "macos")]
diff --git a/src/desktop/src-tauri/tauri.conf.json b/src/desktop/src-tauri/tauri.conf.json
index 853388f75..eed55caef 100644
--- a/src/desktop/src-tauri/tauri.conf.json
+++ b/src/desktop/src-tauri/tauri.conf.json
@@ -50,7 +50,8 @@
"native-oauth",
"native-oauth-mobile",
"mobile-share-image-mobile",
- "mobile-system-notification-mobile"
+ "mobile-system-notification-mobile",
+ "file-save"
]
}
},
diff --git a/src/desktop/src-tauri/tauri.dev.conf.json b/src/desktop/src-tauri/tauri.dev.conf.json
index c4981ea15..5bfa83e3d 100644
--- a/src/desktop/src-tauri/tauri.dev.conf.json
+++ b/src/desktop/src-tauri/tauri.dev.conf.json
@@ -71,6 +71,26 @@
"permissions": [
"mobile-system-notification"
]
+ },
+ "file-save",
+ {
+ "identifier": "file-save-dev",
+ "description": "User file save from the trusted main webview",
+ "windows": [
+ "main"
+ ],
+ "local": true,
+ "remote": {
+ "urls": [
+ "http://localhost:3000"
+ ]
+ },
+ "permissions": [
+ "allow-file-save-begin",
+ "allow-file-save-write-chunk",
+ "allow-file-save-commit",
+ "allow-file-save-cancel"
+ ]
}
]
}
diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx
index e47449af6..186f050bd 100644
--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx
+++ b/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx
@@ -1,5 +1,6 @@
"use client";
+import { FileDownloadButton } from "@/components/file-download-button"
import { useEffect, useState, useCallback, useMemo } from "react";
import { useParams } from "next/navigation";
import { useWorkspace } from "@/contexts/workspace-context";
@@ -670,12 +671,10 @@ export default function AgentEmailPage() {
</div>
<div className="flex flex-wrap gap-2">
{selected.attachments.map((att, i) => (
- <a
+ <FileDownloadButton
key={att.key}
- href={`/api/email/${selected.id}/attachment/${i}?workspace_id=${workspaceId}`}
- target="_blank"
- rel="noopener noreferrer"
- download={att.filename}
+ url={`/api/email/${selected.id}/attachment/${i}?workspace_id=${workspaceId}`}
+ filename={att.filename}
className="flex items-center gap-2 rounded-md border border-border/50 bg-muted/50 px-2 py-2 text-xs hover:bg-muted transition-colors cursor-pointer"
>
<FileIcon className="size-3 text-muted-foreground shrink-0" />
@@ -683,7 +682,7 @@ export default function AgentEmailPage() {
<span className="text-muted-foreground shrink-0">
{att.size < 1024 ? `${att.size} B` : att.size < 1024 * 1024 ? `${(att.size / 1024).toFixed(1)} KB` : `${(att.size / (1024 * 1024)).toFixed(1)} MB`}
</span>
- </a>
+ </FileDownloadButton>
))}
</div>
</div>
diff --git a/src/web/src/app/(app)/w/[slug]/issues/page.tsx b/src/web/src/app/(app)/w/[slug]/issues/page.tsx
index 1bf62b53f..b3b9dcf24 100644
--- a/src/web/src/app/(app)/w/[slug]/issues/page.tsx
+++ b/src/web/src/app/(app)/w/[slug]/issues/page.tsx
@@ -1,5 +1,6 @@
"use client";
+import { useArtifactClick } from "@/components/use-artifact-click";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useLocalStorage } from "@/hooks/use-local-storage";
import { CircleDot, Eye, EyeOff, Loader2, Plus, Trash2 } from "lucide-react";
@@ -21,7 +22,7 @@ import { DndContext, DragOverlay, PointerSensor, useSensor, useSensors, useDropp
import { IssueSheet } from "@/components/issues/issue-sheet";
import { trackIssueCreated, trackIssueStatusChanged } from "@/lib/analytics";
import { ArtifactSheet } from "@/components/agent-chat/artifact-sheet";
-import { isPreviewable, getArtifactUrl, computeArtifactVersions } from "@/components/artifact-content-renderer";
+import { computeArtifactVersions } from "@/components/artifact-content-renderer";
const COLUMNS = [
@@ -251,14 +252,11 @@ export default function IssuesPage() {
[issueArtifacts],
);
- const handleArtifactClick = useCallback((artifact: Artifact) => {
- if (isPreviewable(artifact)) {
- setSelectedArtifact(artifact);
- setArtifactSheetOpen(true);
- } else {
- window.open(getArtifactUrl(artifact.id, workspaceId, true), "_blank");
- }
- }, [workspaceId]);
+ const previewArtifact = useCallback((artifact: Artifact) => {
+ setSelectedArtifact(artifact);
+ setArtifactSheetOpen(true);
+ }, []);
+ const handleArtifactClick = useArtifactClick(workspaceId, previewArtifact);
async function reload() {
setLoading(true);
diff --git a/src/web/src/app/api/artifacts/[id]/content/route.ts b/src/web/src/app/api/artifacts/[id]/content/route.ts
index 707619897..fc6892da9 100644
--- a/src/web/src/app/api/artifacts/[id]/content/route.ts
+++ b/src/web/src/app/api/artifacts/[id]/content/route.ts
@@ -1,3 +1,4 @@
+import { contentDisposition } from "@/lib/content-disposition"
import { NextRequest } from "next/server";
import { queries } from "@alook/shared";
import { getDb } from "@/lib/db"
@@ -5,16 +6,6 @@ import { withAuth } from "@/lib/middleware/auth";
import { withWorkspaceMember } from "@/lib/middleware/workspace";
import { writeError } from "@/lib/middleware/helpers";
-function asciiFallbackFilename(filename: string): string {
- const fallback = filename.replace(/[^\x20-\x7E]/g, "_").replace(/["\\]/g, "_").trim();
- return fallback || "download";
-}
-
-function contentDisposition(disposition: "inline" | "attachment", filename: string): string {
- const fallback = asciiFallbackFilename(filename);
- return `${disposition}; filename="${fallback}"; filename*=UTF-8''${encodeURIComponent(filename)}`;
-}
-
export const GET = withAuth(async (req: NextRequest, ctx) => {
const ws = await withWorkspaceMember(req, ctx);
if (ws instanceof Response) return ws;
diff --git a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.test.ts b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.test.ts
index 39accdd57..e617c17ad 100644
--- a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.test.ts
@@ -220,7 +220,17 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {
mockR2Get.mockResolvedValue(r2Object({ httpMetadata: { contentType: "application/pdf" } }))
const res = await GET(req(), ctx())
expect(res.status).toBe(200)
- expect(res.headers.get("Content-Disposition")).toBe('attachment; filename="doc.pdf"')
+ expect(res.headers.get("Content-Disposition")).toBe("attachment; filename=\"doc.pdf\"; filename*=UTF-8''doc.pdf")
+ })
+
+ it.each(["small-报告.bin", "📎😀.bin", 'a"b\\c.bin', "a\r\nb.bin", "plain.bin"])("human: legal filename header and exact bytes for %j", async filename => {
+ const bytes = new Uint8Array([0, 1, 254, 255])
+ allowPersistedHuman(persistedRow({ filename, contentType: "application/octet-stream", size: bytes.length }))
+ mockR2Get.mockResolvedValue(r2Object({ size: bytes.length }, bytes))
+ const res = await GET(req(), ctx())
+ expect(res.status).toBe(200)
+ expect(decodeURIComponent(res.headers.get("Content-Disposition")!.split("filename*=UTF-8''")[1])).toBe(filename)
+ expect(new Uint8Array(await res.arrayBuffer())).toEqual(bytes)
})
it("human: full media GET is inline, byte-exact, and range-capable", async () => {
@@ -333,7 +343,7 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {
const res = await GET(req({ Range: "bytes=2-4" }), ctx())
expect(res.status).toBe(200)
- expect(res.headers.get("Content-Disposition")).toBe('attachment; filename="doc.pdf"')
+ expect(res.headers.get("Content-Disposition")).toBe("attachment; filename=\"doc.pdf\"; filename*=UTF-8''doc.pdf")
expect(res.headers.get("Accept-Ranges")).toBeNull()
expect(res.headers.get("Content-Range")).toBeNull()
expect(mockR2Get).toHaveBeenCalledWith("channel/c_row/uuid/a.png")
diff --git a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.ts b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.ts
index 3a9264ef4..d90556335 100644
--- a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.ts
@@ -1,3 +1,4 @@
+import { contentDisposition, encodeRfc5987 } from "@/lib/content-disposition"
import { NextResponse, type NextRequest } from "next/server"
import { createLogger } from "@alook/shared"
import { getDb } from "@/lib/db"
@@ -31,17 +32,6 @@ function parseByteRange(value: string, size: number): ParsedByteRange | null {
return { offset, length: end - offset + 1, end }
}
-/**
- * RFC 5987 filename encoding for `X-Alook-Filename`. Percent-encodes
- * everything outside the RFC 5987 attr-char set. The daemon-side client
- * decodes before writing to disk so non-ASCII filenames (`图表.png`) round
- * trip safely.
- */
-function encodeRfc5987(value: string): string {
- return encodeURIComponent(value)
- .replace(/['()]/g, escape)
- .replace(/\*/g, "%2A")
-}
/**
* GET /api/community/channels/[id]/attachments/[attachmentId] — the canonical
@@ -148,7 +138,7 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
"Content-Type": contentType,
"Content-Disposition": isImage || isMedia
? "inline"
- : `attachment; filename="${row.filename}"`,
+ : contentDisposition("attachment", row.filename),
"Cache-Control": ATTACHMENT_PRIVATE_IMMUTABLE_CACHE,
"Content-Length": String(parsedRange?.length ?? size),
}
diff --git a/src/web/src/app/api/email/[id]/attachment/[index]/route.test.ts b/src/web/src/app/api/email/[id]/attachment/[index]/route.test.ts
index 1abef0ac2..b2bc14c21 100644
--- a/src/web/src/app/api/email/[id]/attachment/[index]/route.test.ts
+++ b/src/web/src/app/api/email/[id]/attachment/[index]/route.test.ts
@@ -79,6 +79,19 @@ describe("GET /api/email/[id]/attachment/[index]", () => {
expect((await res.json()).error).toBe("attachment not found");
});
+ it.each(["small-报告.bin", "📎😀.bin", 'a"b\\c.bin', "a\r\nb.bin", "plain.bin"])("serves %j without invalid header bytes", async filename => {
+ mockGetById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "k" });
+ mockGetAgent.mockResolvedValue({ id: "a1" });
+ mockBucketGet.mockResolvedValue({ arrayBuffer: async () => new ArrayBuffer(4) });
+ mockParse.mockResolvedValue({ attachments: [{}] });
+ const bytes = new Uint8Array([0, 1, 254, 255]);
+ mockFilter.mockReturnValue([{ filename, mimeType: "application/octet-stream", content: bytes.buffer }]);
+ const res = await get({ id: "e1", index: "0" });
+ expect(res.status).toBe(200);
+ expect(decodeURIComponent(res.headers.get("Content-Disposition")!.split("filename*=UTF-8''")[1])).toBe(filename);
+ expect(new Uint8Array(await res.arrayBuffer())).toEqual(bytes);
+ });
+
it("streams the attachment with content headers", async () => {
mockGetById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "k" });
mockGetAgent.mockResolvedValue({ id: "a1" });
diff --git a/src/web/src/app/api/email/[id]/attachment/[index]/route.ts b/src/web/src/app/api/email/[id]/attachment/[index]/route.ts
index f5875e21a..9e666ffed 100644
--- a/src/web/src/app/api/email/[id]/attachment/[index]/route.ts
+++ b/src/web/src/app/api/email/[id]/attachment/[index]/route.ts
@@ -1,3 +1,4 @@
+import { contentDisposition } from "@/lib/content-disposition"
import PostalMime from "postal-mime";
import { queries, filterDownloadableAttachments } from "@alook/shared";
import { getDb } from "@/lib/db"
@@ -41,7 +42,7 @@ export const GET = withAuth(async (req, ctx) => {
return new Response(body as BodyInit, {
headers: {
"Content-Type": contentType,
- "Content-Disposition": `attachment; filename="${filename.replace(/"/g, '\\"')}"; filename*=UTF-8''${encodeURIComponent(filename)}`,
+ "Content-Disposition": contentDisposition("attachment", filename),
"Cache-Control": "private, max-age=3600",
},
});
diff --git a/src/web/src/components/agent-chat/agent-chat-view.tsx b/src/web/src/components/agent-chat/agent-chat-view.tsx
index 6e49975cf..1d2689a6a 100644
--- a/src/web/src/components/agent-chat/agent-chat-view.tsx
+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx
@@ -1,5 +1,6 @@
"use client";
+import { useArtifactClick } from "@/components/use-artifact-click";
import React, {
useEffect,
useLayoutEffect,
@@ -72,8 +73,6 @@ import { ImageLightbox } from "@/components/agent-chat/image-lightbox";
import { CalendarEventSheet } from "@/components/calendar/calendar-event-sheet";
import { IssueSheet } from "@/components/issues/issue-sheet";
import {
- isPreviewable,
- getArtifactUrl,
computeArtifactVersions,
} from "@/components/artifact-content-renderer";
import { ScrollToBottomButton } from "@/components/ui/scroll-to-bottom-button";
@@ -365,35 +364,12 @@ export function AgentChatView({
[],
);
- const handleArtifactClick = useCallback(
- (artifact: Artifact) => {
- if (artifact.content_type.startsWith("image/")) {
- setLightboxArtifact(artifact);
- } else if (isPreviewable(artifact)) {
- setSelectedArtifact(artifact);
- setArtifactSheetOpen(true);
- } else {
- window.open(getArtifactUrl(artifact.id, workspaceId, true), "_blank");
- }
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps -- setState fns are stable
- [workspaceId],
- );
-
- const handleIssueArtifactClick = useCallback(
- (artifact: Artifact) => {
- if (artifact.content_type.startsWith("image/")) {
- setLightboxArtifact(artifact);
- } else if (isPreviewable(artifact)) {
- setSelectedArtifact(artifact);
- setArtifactSheetOpen(true);
- } else {
- window.open(getArtifactUrl(artifact.id, workspaceId, true), "_blank");
- }
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps -- setState fns are stable
- [workspaceId],
- );
+ const previewArtifact = useCallback((artifact: Artifact) => {
+ setSelectedArtifact(artifact);
+ setArtifactSheetOpen(true);
+ }, [setSelectedArtifact, setArtifactSheetOpen]);
+ const handleArtifactClick = useArtifactClick(workspaceId, previewArtifact, setLightboxArtifact);
+ const handleIssueArtifactClick = useArtifactClick(workspaceId, previewArtifact, setLightboxArtifact);
// Editor plain text + caret, reported up from the composer, drive the
// slash-command popup (mentions are handled natively inside the composer).
diff --git a/src/web/src/components/agent-chat/artifact-sheet.tsx b/src/web/src/components/agent-chat/artifact-sheet.tsx
index e85f59b68..44dddbfab 100644
--- a/src/web/src/components/agent-chat/artifact-sheet.tsx
+++ b/src/web/src/components/agent-chat/artifact-sheet.tsx
@@ -1,5 +1,6 @@
"use client";
+import { FileDownloadButton } from "@/components/file-download-button"
import React, { useState, useEffect } from "react";
import { useSheetResize, SheetResizeHandle } from "@/components/ui/sheet-resize-handle";
import {
@@ -87,14 +88,13 @@ export function ArtifactSheet({ open, onOpenChange, artifacts, workspaceId, init
</span>
)}
</SheetTitle>
- <Button
- variant="ghost"
- size="icon-sm"
- className="shrink-0"
- onClick={() => window.open(getArtifactUrl(selectedArtifact.id, workspaceId, true), "_blank")}
+ <FileDownloadButton
+ className="shrink-0 inline-flex size-8 items-center justify-center rounded-md hover:bg-accent"
+ url={getArtifactUrl(selectedArtifact.id, workspaceId, true)}
+ filename={selectedArtifact.filename}
>
<Download className="size-4" />
- </Button>
+ </FileDownloadButton>
</div>
</SheetHeader>
<SheetBody className={cn(
diff --git a/src/web/src/components/agent-chat/email-event-sheet.tsx b/src/web/src/components/agent-chat/email-event-sheet.tsx
index f10e776c2..007916ae0 100644
--- a/src/web/src/components/agent-chat/email-event-sheet.tsx
+++ b/src/web/src/components/agent-chat/email-event-sheet.tsx
@@ -1,5 +1,6 @@
"use client";
+import { FileDownloadButton } from "@/components/file-download-button"
import React, { useState, useEffect, useRef } from "react";
import { useSheetResize, SheetResizeHandle } from "@/components/ui/sheet-resize-handle";
import {
@@ -128,12 +129,10 @@ export function EmailEventSheet({ open, onOpenChange, emailId, workspaceId }: Em
</div>
<div className="flex flex-wrap gap-2">
{email.attachments.map((att, i) => (
- <a
+ <FileDownloadButton
key={att.key}
- href={`/api/email/${email.id}/attachment/${i}?workspace_id=${workspaceId}`}
- target="_blank"
- rel="noopener noreferrer"
- download={att.filename}
+ url={`/api/email/${email.id}/attachment/${i}?workspace_id=${workspaceId}`}
+ filename={att.filename}
className="flex items-center gap-2 rounded-md border border-border/50 bg-muted/50 px-2 py-2 text-xs hover:bg-muted transition-colors cursor-pointer"
>
<FileIcon className="size-3 text-muted-foreground shrink-0" />
@@ -141,7 +140,7 @@ export function EmailEventSheet({ open, onOpenChange, emailId, workspaceId }: Em
<span className="text-muted-foreground shrink-0">
{att.size < 1024 ? `${att.size} B` : att.size < 1024 * 1024 ? `${(att.size / 1024).toFixed(1)} KB` : `${(att.size / (1024 * 1024)).toFixed(1)} MB`}
</span>
- </a>
+ </FileDownloadButton>
))}
</div>
</div>
diff --git a/src/web/src/components/agent-chat/image-lightbox.tsx b/src/web/src/components/agent-chat/image-lightbox.tsx
index b5a6c77b5..9b769f6c2 100644
--- a/src/web/src/components/agent-chat/image-lightbox.tsx
+++ b/src/web/src/components/agent-chat/image-lightbox.tsx
@@ -1,5 +1,6 @@
"use client";
+import { FileDownloadButton } from "@/components/file-download-button"
import React, { useEffect, useCallback } from "react";
import { createPortal } from "react-dom";
import type { Artifact } from "@alook/shared";
@@ -53,15 +54,15 @@ export function ImageLightbox(props: LightboxProps) {
>
<div className="absolute top-4 right-4 flex items-center gap-2">
{downloadUrl && (
- <a
- href={downloadUrl}
- download={alt}
+ <FileDownloadButton
+ url={downloadUrl}
+ filename={alt}
aria-label={`Download ${alt}`}
onClick={(e) => e.stopPropagation()}
className="rounded-full p-2 text-white/70 hover:text-white hover:bg-white/10 transition-colors"
>
<Download className="size-5" />
- </a>
+ </FileDownloadButton>
)}
<button
type="button"
diff --git a/src/web/src/components/artifact-content-renderer.tsx b/src/web/src/components/artifact-content-renderer.tsx
index 05ff3e05a..311ac8531 100644
--- a/src/web/src/components/artifact-content-renderer.tsx
+++ b/src/web/src/components/artifact-content-renderer.tsx
@@ -1,5 +1,6 @@
"use client";
+import { FileDownloadButton } from "@/components/file-download-button"
import React, { useEffect, useState } from "react";
import { getArtifactContent } from "@/lib/api";
import type { Artifact } from "@alook/shared";
@@ -137,14 +138,14 @@ export function ArtifactContentRenderer({ artifact, workspaceId }: ArtifactConte
<p className="text-sm text-muted-foreground">
This file type cannot be previewed.
</p>
- <a
- href={getArtifactUrl(artifact.id, workspaceId, true)}
- download={artifact.filename}
+ <FileDownloadButton
+ url={getArtifactUrl(artifact.id, workspaceId, true)}
+ filename={artifact.filename}
className="inline-flex items-center gap-2 rounded-md border border-input bg-background px-3 py-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-colors"
>
<Download className="size-3.5" />
Download
- </a>
+ </FileDownloadButton>
</div>
);
}
diff --git a/src/web/src/components/community/messages/attachment-card.dom.test.ts b/src/web/src/components/community/messages/attachment-card.dom.test.ts
index ba5f1580d..c66dc685b 100644
--- a/src/web/src/components/community/messages/attachment-card.dom.test.ts
+++ b/src/web/src/components/community/messages/attachment-card.dom.test.ts
@@ -51,6 +51,7 @@ describe("AttachmentCard", () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("bytes")))
vi.stubGlobal("document", {
createElement: vi.fn(() => anchor),
+ body: { appendChild: vi.fn() },
})
vi.stubGlobal("URL", { createObjectURL: vi.fn(() => "blob:file"), revokeObjectURL: vi.fn() })
const archive = attachment({ name: "报告.zip", contentType: "application/zip" })
@@ -69,7 +70,7 @@ describe("AttachmentCard", () => {
await Promise.resolve()
await Promise.resolve()
})
- expect(fetch).toHaveBeenCalledWith("/attachments/a1", { credentials: "same-origin" })
+ expect(fetch).toHaveBeenCalledWith("/attachments/a1", { credentials: "same-origin", signal: expect.any(AbortSignal) })
expect(anchor).toEqual(expect.objectContaining({ href: "blob:file", download: "报告.zip" }))
expect(anchor.click).toHaveBeenCalledOnce()
expect(onPreview).not.toHaveBeenCalled()
@@ -146,13 +147,14 @@ describe("AttachmentCard", () => {
})
it("shares one in-flight state and operation across two rendered surfaces", async () => {
- let resolveBlob!: (blob: Blob) => void
- const blob = vi.fn(() => new Promise<Blob>((resolve) => { resolveBlob = resolve }))
- const fetchMock = vi.fn().mockResolvedValue({ ok: true, status: 200, blob })
+ let streamController!: ReadableStreamDefaultController<Uint8Array>
+ const stream = new ReadableStream<Uint8Array>({ start(controller) { streamController = controller } })
+ const fetchMock = vi.fn().mockResolvedValue(new Response(stream))
const anchor = { href: "", download: "", hidden: false, click: vi.fn(), remove: vi.fn() }
vi.stubGlobal("fetch", fetchMock)
vi.stubGlobal("document", {
createElement: vi.fn(() => anchor),
+ body: { appendChild: vi.fn() },
})
vi.stubGlobal("URL", { createObjectURL: vi.fn(() => "blob:file"), revokeObjectURL: vi.fn() })
const pdf = attachment({ name: "report.pdf", contentType: "application/pdf" })
@@ -171,13 +173,13 @@ describe("AttachmentCard", () => {
})
expect(renderer!.getAllByRole("status").map((node) => node.textContent))
.toEqual(["Downloading…", "Downloading…"])
- expect(renderer!.getAllByRole("button").every((button) => (button as HTMLButtonElement).disabled))
+ expect(renderer!.getAllByRole("button").every((button) => !(button as HTMLButtonElement).disabled))
.toBe(true)
await Promise.resolve()
expect(fetchMock).toHaveBeenCalledOnce()
- await vi.waitFor(() => expect(blob).toHaveBeenCalledOnce())
- resolveBlob(new Blob(["complete"]))
+ streamController.enqueue(new TextEncoder().encode("complete"))
+ streamController.close()
await act(async () => {
await Promise.resolve()
await Promise.resolve()
diff --git a/src/web/src/components/community/messages/attachment-card.tsx b/src/web/src/components/community/messages/attachment-card.tsx
index cee241d55..f4c3f22f3 100644
--- a/src/web/src/components/community/messages/attachment-card.tsx
+++ b/src/web/src/components/community/messages/attachment-card.tsx
@@ -78,7 +78,7 @@ function FileAttachmentCard({
? Eye
: download.state.status === "downloading"
? LoaderCircle
- : download.state.status === "success"
+ : (download.state.status === "saved" || download.state.status === "started")
? CircleCheck
: download.state.status === "error"
? RefreshCw
@@ -86,7 +86,7 @@ function FileAttachmentCard({
const action = canPreview
? "Preview"
: download.state.status === "downloading"
- ? "Downloading"
+ ? "Cancel download"
: download.state.status === "error"
? "Retry download"
: "Download"
@@ -98,11 +98,10 @@ function FileAttachmentCard({
data-attachment-category={presentation.category}
onClick={() => canPreview
? onPreview(attachment)
- : void download.start()}
+ : download.state.status === "downloading" ? download.cancel() : void download.start()}
className="flex w-full max-w-[320px] items-center gap-3 rounded-lg border border-border bg-card p-2 text-left transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none disabled:cursor-not-allowed disabled:bg-muted disabled:text-muted-foreground"
aria-label={`${action} ${attachment.name}`}
aria-busy={!canPreview && download.state.status === "downloading"}
- disabled={!canPreview && download.state.status === "downloading"}
>
<Icon className="size-7 shrink-0 text-muted-foreground" />
<div className="min-w-0 flex-1">
diff --git a/src/web/src/components/community/messages/attachment-download-surfaces.contract.test.ts b/src/web/src/components/community/messages/attachment-download-surfaces.contract.test.ts
index e2325c7e7..85e8f7d66 100644
--- a/src/web/src/components/community/messages/attachment-download-surfaces.contract.test.ts
+++ b/src/web/src/components/community/messages/attachment-download-surfaces.contract.test.ts
@@ -34,6 +34,38 @@ describe("Community attachment download surface contract", () => {
}
})
+ it("routes Artifact, email, remote images and share images through the product owner", () => {
+ for (const path of [
+ "src/components/agent-chat/artifact-sheet.tsx",
+ "src/components/agent-chat/image-lightbox.tsx",
+ "src/components/agent-chat/email-event-sheet.tsx",
+ "src/components/artifact-content-renderer.tsx",
+ "src/components/issues/issue-attachment-list.tsx",
+ "src/app/(app)/w/[slug]/agents/[id]/email/page.tsx",
+ "src/components/remote-image/remote-markdown-image.tsx",
+ ]) {
+ const text = source(path)
+ expect(text, path).toContain("FileDownloadButton")
+ expect(text, path).not.toMatch(/<a\b[^>]*\bdownload=/)
+ expect(text, path).not.toMatch(/createElement\(["']a["']\)/)
+ expect(text, path).not.toContain("window.open")
+ }
+ const share = source("src/components/community/messages/message-share-dialog.tsx")
+ expect(share).toContain("saveFile(blob, filename")
+ expect(share).toContain("saveMobileShareImage")
+ expect(share).not.toMatch(/createElement\(["']a["']\)/)
+ })
+
+ it("keeps all artifact click controllers on the shared download routing", () => {
+ for (const path of ["src/components/agent-chat/agent-chat-view.tsx", "src/app/(app)/w/[slug]/issues/page.tsx"]) {
+ const text = source(path)
+ expect(text).toContain("useArtifactClick(workspaceId, previewArtifact")
+ expect(text).not.toMatch(/window\.open\(getArtifactUrl/)
+ }
+ expect(source("src/components/agent-chat/agent-chat-view.tsx")).toContain("const handleIssueArtifactClick = useArtifactClick")
+ expect(source("src/components/issues/issue-sheet.tsx")).toContain("<IssueAttachmentList")
+ })
+
it("renders representative message and thread attachments without a surface callback", () => {
for (const path of [
"src/components/community/messages/message.tsx",
diff --git a/src/web/src/components/community/messages/attachment-preview-sheet.dom.test.ts b/src/web/src/components/community/messages/attachment-preview-sheet.dom.test.ts
index fff170d1b..a596705d1 100644
--- a/src/web/src/components/community/messages/attachment-preview-sheet.dom.test.ts
+++ b/src/web/src/components/community/messages/attachment-preview-sheet.dom.test.ts
@@ -188,7 +188,7 @@ describe("AttachmentPreviewSheet", () => {
onOpenChange: vi.fn(),
}))
await flush()
- expect(fetchMock).toHaveBeenCalledWith("/attachments/a1", expect.objectContaining({ credentials: "same-origin" }))
+ expect(fetchMock).toHaveBeenCalledWith("/attachments/a1", expect.objectContaining({ credentials: "same-origin", signal: expect.any(AbortSignal) }))
expect(renderer.container.querySelector("[data-markdown]")?.textContent).toBe("# Hello")
const download = renderer.container.querySelector<HTMLButtonElement>(
'[data-testid="community-attachment-preview-download"]',
@@ -204,7 +204,7 @@ describe("AttachmentPreviewSheet", () => {
await Promise.resolve()
await Promise.resolve()
})
- expect(fetchMock).toHaveBeenNthCalledWith(2, "/attachments/a1", { credentials: "same-origin" })
+ expect(fetchMock).toHaveBeenNthCalledWith(2, "/attachments/a1", { credentials: "same-origin", signal: expect.any(AbortSignal) })
expect(anchor).toEqual(expect.objectContaining({ href: "blob:preview", download: "notes.md" }))
expect(click).toHaveBeenCalledOnce()
expect(renderer.container.querySelector(
diff --git a/src/web/src/components/community/messages/attachment-preview-sheet.tsx b/src/web/src/components/community/messages/attachment-preview-sheet.tsx
index af629d1e9..72c1c9cb4 100644
--- a/src/web/src/components/community/messages/attachment-preview-sheet.tsx
+++ b/src/web/src/components/community/messages/attachment-preview-sheet.tsx
@@ -67,7 +67,7 @@ function AttachmentPreviewDownload({ attachment }: { attachment: FileAttachment
const statusText = attachmentDownloadStatusText(download.state)
const Icon = download.state.status === "downloading"
? Loader2
- : download.state.status === "success"
+ : (download.state.status === "saved" || download.state.status === "started")
? CircleCheck
: download.state.status === "error"
? RefreshCw
@@ -77,8 +77,7 @@ function AttachmentPreviewDownload({ attachment }: { attachment: FileAttachment
<button
type="button"
data-testid={tid.attachmentPreviewDownload}
- onClick={() => void download.start()}
- disabled={download.state.status === "downloading"}
+ onClick={() => download.state.status === "downloading" ? download.cancel() : void download.start()}
aria-busy={download.state.status === "downloading"}
className={buttonVariants({
variant: "outline",
@@ -87,7 +86,7 @@ function AttachmentPreviewDownload({ attachment }: { attachment: FileAttachment
})}
>
<Icon className={`size-3.5 ${download.state.status === "downloading" ? "animate-spin motion-reduce:animate-none" : ""}`} />
- {statusText ?? "Download"}
+ {download.state.status === "downloading" ? "Cancel download" : statusText ?? "Download"}
</button>
)
}
diff --git a/src/web/src/components/community/messages/media-attachment-block.dom.test.ts b/src/web/src/components/community/messages/media-attachment-block.dom.test.ts
index a6c7def75..1d2f4c048 100644
--- a/src/web/src/components/community/messages/media-attachment-block.dom.test.ts
+++ b/src/web/src/components/community/messages/media-attachment-block.dom.test.ts
@@ -312,7 +312,7 @@ describe("MediaAttachmentBlock", () => {
await Promise.resolve()
})
expect(stopPropagation).toHaveBeenCalledOnce()
- expect(fetch).toHaveBeenCalledWith("/attachments/video-1", { credentials: "same-origin" })
+ expect(fetch).toHaveBeenCalledWith("/attachments/video-1", { credentials: "same-origin", signal: expect.any(AbortSignal) })
expect(anchor).toEqual(expect.objectContaining({ href: "blob:media", download: "clip.mp4" }))
expect(anchor.click).toHaveBeenCalledOnce()
expect(renderer.getByRole("status")).toHaveTextContent("Download started")
diff --git a/src/web/src/components/community/messages/media-attachment-block.tsx b/src/web/src/components/community/messages/media-attachment-block.tsx
index e44b10ea2..9b6ec8023 100644
--- a/src/web/src/components/community/messages/media-attachment-block.tsx
+++ b/src/web/src/components/community/messages/media-attachment-block.tsx
@@ -34,7 +34,7 @@ export function MediaAttachmentBlock({
const downloadStatusText = attachmentDownloadStatusText(attachmentDownload.state)
const DownloadIcon = attachmentDownload.state.status === "downloading"
? LoaderCircle
- : attachmentDownload.state.status === "success"
+ : (attachmentDownload.state.status === "saved" || attachmentDownload.state.status === "started")
? CircleCheck
: attachmentDownload.state.status === "error"
? RefreshCw
@@ -111,7 +111,8 @@ export function MediaAttachmentBlock({
function handleDownload(event: MouseEvent<HTMLButtonElement>): void {
event.stopPropagation()
- void attachmentDownload.start()
+ if (attachmentDownload.state.status === "downloading") attachmentDownload.cancel()
+ else void attachmentDownload.start()
}
const playerProps = {
@@ -290,12 +291,11 @@ export function MediaAttachmentBlock({
className="size-11 text-muted-foreground hover:text-foreground focus-visible:text-foreground sm:size-8"
onClick={handleDownload}
aria-label={`${attachmentDownload.state.status === "downloading"
- ? "Downloading"
+ ? "Cancel download"
: attachmentDownload.state.status === "error"
? "Retry download"
: "Download"} ${attachment.name}`}
aria-busy={attachmentDownload.state.status === "downloading"}
- disabled={attachmentDownload.state.status === "downloading"}
>
<DownloadIcon className={`size-4 ${attachmentDownload.state.status === "downloading" ? "animate-spin motion-reduce:animate-none" : ""}`} />
</Button>
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 a97873d6c..e939947b4 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
@@ -1,4 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { Blob as NodeBlob } from "node:buffer"
import React from "react"
import { act, render } from "@/test/react-dom-harness"
import { toBlob } from "html-to-image"
@@ -177,6 +178,7 @@ function installMobileNative(invoke: ReturnType<typeof vi.fn>) {
}
beforeEach(() => {
+ vi.stubGlobal("Blob", NodeBlob)
vi.clearAllMocks()
sessionMocks.prepare.mockImplementation(async (source: HTMLElement) => preparedFrom(source))
sessionMocks.capture.mockImplementation(async (
@@ -486,14 +488,14 @@ describe("MessageShareDialog exports", () => {
await act(async () => buttonWithText(renderer.container, "Copy image").click())
await vi.waitFor(() => expect(toast.success).toHaveBeenCalledWith("Image copied to clipboard"))
await act(async () => buttonWithText(renderer.container, "Download").click())
- await vi.waitFor(() => expect(toast.success).toHaveBeenCalledWith("Image downloaded"))
+ await vi.waitFor(() => expect(toast.success).toHaveBeenCalledWith("Download started"))
expect(sessionMocks.capture).toHaveBeenCalledTimes(1)
expect(toBlob).toHaveBeenCalledTimes(1)
expect(write).toHaveBeenCalledTimes(1)
expect(click).toHaveBeenCalledTimes(1)
expect(createObjectURL).toHaveBeenCalledTimes(1)
- await vi.waitFor(() => expect(revokeObjectURL).toHaveBeenCalledWith("blob:share-card"))
+ expect(revokeObjectURL).not.toHaveBeenCalled()
})
it("reports rasterization failure without invoking clipboard", async () => {
@@ -677,7 +679,7 @@ describe("MessageShareDialog exports", () => {
it.each([
["Copy", "Download", "Image copied to clipboard"],
- ["Download", "Copy image", "Image downloaded"],
+ ["Download", "Copy image", "Download started"],
] as const)("keeps %s as first winner when %s overlaps", async (first, second, feedback) => {
const rendered = deferred<Blob>()
sessionMocks.capture.mockReturnValueOnce(rendered.promise)
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 648bd4474..032d56a6d 100644
--- a/src/web/src/components/community/messages/message-share-dialog.tsx
+++ b/src/web/src/components/community/messages/message-share-dialog.tsx
@@ -1,5 +1,6 @@
"use client"
+import { saveFile, fileSaveMessage, type FileSaveResult } from "@/lib/file-save"
import { useCallback, useEffect, useMemo, useRef, useState, type MouseEvent as ReactMouseEvent } from "react"
import { toBlob } from "html-to-image"
import { toast } from "sonner"
@@ -68,29 +69,15 @@ export async function copyRenderedShareCard(
await write(blob)
}
-async function saveShareCardDownload(
- blob: Blob,
- filename: string,
- save: ShareCardBlobWriter = (value) => {
- const url = URL.createObjectURL(value)
- const anchor = document.createElement("a")
- anchor.href = url
- anchor.download = filename
- anchor.click()
- queueMicrotask(() => URL.revokeObjectURL(url))
- },
-): Promise<void> {
- await save(blob)
+async function saveShareCardDownload(blob: Blob, filename: string, save?: ShareCardBlobWriter, signal?: AbortSignal): Promise<FileSaveResult> {
+ if (save) { await save(blob); return { status: "started" } }
+ return saveFile(blob, filename, { signal })
}
-export async function downloadRenderedShareCard(
- render: ShareCardRenderer,
- filename: string,
- save?: ShareCardBlobWriter,
-): Promise<void> {
+export async function downloadRenderedShareCard(render: ShareCardRenderer, filename: string, save?: ShareCardBlobWriter): Promise<FileSaveResult> {
const blob = await render()
if (!blob) throw new ShareImageSessionError("rasterize")
- await saveShareCardDownload(blob, filename, save)
+ return saveShareCardDownload(blob, filename, save)
}
export function shareCardRenderErrorMessage(error: unknown): string | null {
@@ -295,7 +282,13 @@ export function MessageShareDialog({ m, open, onClose }: {
const { saveMobileShareImage } = await import("@/lib/community/mobile-share-image")
if (!isCurrent()) return
mobileDestination = (await saveMobileShareImage(blob, filename)).destination
- } else await saveShareCardDownload(blob, filename)
+ } else {
+ const result = await saveShareCardDownload(blob, filename, undefined, controller.signal)
+ if (!isCurrent()) return
+ if (result.status === "error") toast.error(fileSaveMessage(result))
+ else if (result.status !== "cancelled") toast.success(fileSaveMessage(result))
+ return
+ }
if (!isCurrent()) return
if (action === "copy") {
@@ -313,7 +306,7 @@ export function MessageShareDialog({ m, open, onClose }: {
} else if (mobileDestination === "document") {
toast.success("Image saved")
} else {
- toast.success("Image downloaded")
+ toast.success("Download started")
}
} catch (error) {
if (!isCurrent()) return
diff --git a/src/web/src/components/file-download-button.dom.test.tsx b/src/web/src/components/file-download-button.dom.test.tsx
new file mode 100644
index 000000000..0f146c01d
--- /dev/null
+++ b/src/web/src/components/file-download-button.dom.test.tsx
@@ -0,0 +1,32 @@
+import React from "react"
+import { afterEach, describe, expect, it, vi } from "vitest"
+import { act, render } from "@/test/react-dom-harness"
+import { FileDownloadButton } from "./file-download-button"
+import { resetFileDownloadsForTest } from "@/lib/file-download"
+const service = vi.hoisted(() => ({ download: vi.fn(), success: vi.fn(), error: vi.fn() }))
+vi.mock("@/lib/file-save", async importOriginal => ({ ...await importOriginal<object>(), downloadUrl: service.download }))
+vi.mock("sonner", () => ({ toast: { success: service.success, error: service.error } }))
+afterEach(() => { resetFileDownloadsForTest(); vi.clearAllMocks() })
+describe("file download control", () => {
+ it.each(["saved", "started", "error", "cancelled"] as const)("announces %s truthfully", async status => {
+ service.download.mockResolvedValue({ status })
+ const view = render(<FileDownloadButton url="/file" filename="a.pdf">Get file</FileDownloadButton>)
+ await act(async () => { view.getByRole("button").click() })
+ const text = status === "saved" ? "Saved" : status === "started" ? "Download started" : status === "error" ? "Couldn’t save — retry" : ""
+ expect(view.getByRole("status").textContent).toBe(text)
+ if (status === "error") expect(service.error).toHaveBeenCalledWith(text)
+ else if (status !== "cancelled") expect(service.success).toHaveBeenCalledWith(text)
+ else { expect(service.error).not.toHaveBeenCalled(); expect(service.success).not.toHaveBeenCalled() }
+ })
+ 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" })
+ const view = render(<FileDownloadButton url="/file" filename="a.pdf">Get file</FileDownloadButton>)
+ await act(async () => { view.getByRole("button").click() })
+ expect(view.getByRole("button", { name: "Cancel download a.pdf" })).toBeEnabled()
+ await act(async () => { view.getByRole("button").click() })
+ expect(view.getByRole("status").textContent).toBe("")
+ await act(async () => { view.getByRole("button").click() })
+ expect(view.getByRole("status")).toHaveTextContent("Download started")
+ })
+})
diff --git a/src/web/src/components/file-download-button.tsx b/src/web/src/components/file-download-button.tsx
new file mode 100644
index 000000000..24a35af5f
--- /dev/null
+++ b/src/web/src/components/file-download-button.tsx
@@ -0,0 +1,34 @@
+"use client"
+
+import { toast } from "sonner"
+import { readFileDownloadState, fileDownloadKey } from "@/lib/file-download"
+import type { ComponentProps } from "react"
+import { fileDownloadStatusText, useFileDownload } from "@/lib/file-download"
+
+export function FileDownloadButton({ url, filename, children, onClick, ...props }: Omit<ComponentProps<"button">, "type"> & { url: string; filename: string }) {
+ const download = useFileDownload({ url, name: filename })
+ const message = fileDownloadStatusText(download.state)
+ const busy = download.state.status === "downloading"
+ return (
+ <button
+ {...props}
+ type="button"
+ aria-label={busy ? `Cancel download ${filename}` : props["aria-label"] ?? `Download ${filename}`}
+ title={message ?? props.title}
+ onClick={event => {
+ onClick?.(event)
+ if (event.defaultPrevented) return
+ if (busy) download.cancel()
+ else void download.start().then(() => {
+ const result = readFileDownloadState(fileDownloadKey({ name: filename, url }))
+ const text = fileDownloadStatusText(result)
+ if (result.status === "error") toast.error(text)
+ else if (result.status === "saved" || result.status === "started") toast.success(text)
+ })
+ }}
+ >
+ {children}
+ <span role="status" className="sr-only">{message}</span>
+ </button>
+ )
+}
diff --git a/src/web/src/components/issues/issue-attachment-list.tsx b/src/web/src/components/issues/issue-attachment-list.tsx
new file mode 100644
index 000000000..c7fc47a3a
--- /dev/null
+++ b/src/web/src/components/issues/issue-attachment-list.tsx
@@ -0,0 +1,46 @@
+"use client"
+
+import type { Artifact } from "@alook/shared";
+import { File as FileIcon } from "lucide-react";
+import { FileDownloadButton } from "@/components/file-download-button";
+import { isPreviewable, getArtifactUrl } from "@/components/artifact-content-renderer";
+import { formatSize } from "@/components/agent-chat/artifact-sheet";
+import { cn } from "@/lib/utils";
+
+export function IssueAttachmentList({ artifacts, workspaceId, onArtifactClick }: { artifacts: Artifact[]; workspaceId: string; onArtifactClick?: (artifact: Artifact) => void }) {
+ if (artifacts.length === 0) return null;
+ const baseCls = "flex items-center gap-2 rounded-md px-2 py-2 text-sm transition-colors hover:bg-accent";
+ return (
+ <div className="space-y-1">
+ {artifacts.map((artifact) => {
+ const canPreview = onArtifactClick && isPreviewable(artifact);
+ const inner = (
+ <>
+ <FileIcon className="size-3.5 shrink-0 text-muted-foreground" />
+ <span className="min-w-0 flex-1 truncate">{artifact.filename}</span>
+ <span className="shrink-0 text-xs text-muted-foreground">{formatSize(artifact.size)}</span>
+ </>
+ );
+ return canPreview ? (
+ <button
+ key={artifact.id}
+ type="button"
+ onClick={() => onArtifactClick(artifact)}
+ className={cn(baseCls, "w-full text-left")}
+ >
+ {inner}
+ </button>
+ ) : (
+ <FileDownloadButton
+ key={artifact.id}
+ url={getArtifactUrl(artifact.id, workspaceId, true)}
+ filename={artifact.filename}
+ className={baseCls}
+ >
+ {inner}
+ </FileDownloadButton>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/src/web/src/components/issues/issue-sheet.tsx b/src/web/src/components/issues/issue-sheet.tsx
index 794682f4b..106f29cfa 100644
--- a/src/web/src/components/issues/issue-sheet.tsx
+++ b/src/web/src/components/issues/issue-sheet.tsx
@@ -1,5 +1,6 @@
"use client";
+import { IssueAttachmentList } from "./issue-attachment-list";
import { useCallback, useEffect, useRef, useState } from "react";
import {
Sheet,
@@ -25,7 +26,6 @@ import {
ArrowUp,
Check,
CircleDot,
- File as FileIcon,
GitBranch,
Loader2,
MessageSquare,
@@ -38,8 +38,6 @@ import { toast } from "sonner";
import { Streamdown } from "streamdown";
import { mermaid, cjk } from "@/lib/streamdown-plugins";
import type { Agent, Artifact, Issue, IssueComment, Message, TaskApi } from "@alook/shared";
-import { isPreviewable, getArtifactUrl } from "@/components/artifact-content-renderer";
-import { formatSize } from "@/components/agent-chat/artifact-sheet";
import { isTerminalIssueStatus, toAlookAddress } from "@alook/shared";
import type { TraceTask } from "@/lib/api";
import { updateIssue } from "@/lib/api";
@@ -133,45 +131,6 @@ function CommentRow({ comment, agents }: { comment: IssueComment; agents: Agent[
);
}
-function AttachmentList({ artifacts, workspaceId, onArtifactClick }: { artifacts: Artifact[]; workspaceId: string; onArtifactClick?: (artifact: Artifact) => void }) {
- if (artifacts.length === 0) return null;
- const baseCls = "flex items-center gap-2 rounded-md px-2 py-2 text-sm transition-colors hover:bg-accent";
- return (
- <div className="space-y-1">
- {artifacts.map((artifact) => {
- const canPreview = onArtifactClick && isPreviewable(artifact);
- const inner = (
- <>
- <FileIcon className="size-3.5 shrink-0 text-muted-foreground" />
- <span className="min-w-0 flex-1 truncate">{artifact.filename}</span>
- <span className="shrink-0 text-xs text-muted-foreground">{formatSize(artifact.size)}</span>
- </>
- );
- return canPreview ? (
- <button
- key={artifact.id}
- type="button"
- onClick={() => onArtifactClick(artifact)}
- className={cn(baseCls, "w-full text-left")}
- >
- {inner}
- </button>
- ) : (
- <a
- key={artifact.id}
- href={getArtifactUrl(artifact.id, workspaceId, true)}
- target="_blank"
- rel="noopener noreferrer"
- className={baseCls}
- >
- {inner}
- </a>
- );
- })}
- </div>
- );
-}
-
// --- Main component ---
export interface IssueSheetProps {
@@ -626,7 +585,7 @@ export function IssueSheet({
{/* Attachments (detail mode) */}
{mode === "detail" && detail?.artifacts && detail.artifacts.length > 0 && (
<div className="shrink-0 px-2 sm:px-3 py-2">
- <AttachmentList artifacts={detail.artifacts} workspaceId={workspaceId} onArtifactClick={onArtifactClick} />
+ <IssueAttachmentList artifacts={detail.artifacts} workspaceId={workspaceId} onArtifactClick={onArtifactClick} />
</div>
)}
</>
diff --git a/src/web/src/components/remote-image/remote-markdown-image.tsx b/src/web/src/components/remote-image/remote-markdown-image.tsx
index 85105ec27..194c36356 100644
--- a/src/web/src/components/remote-image/remote-markdown-image.tsx
+++ b/src/web/src/components/remote-image/remote-markdown-image.tsx
@@ -1,49 +1,15 @@
"use client"
import { Download } from "lucide-react"
-import { useCallback } from "react"
+import { FileDownloadButton } from "@/components/file-download-button"
import { cn } from "@/lib/utils"
import { useRemoteImageAttempt, useRemoteImageEligibility } from "./remote-image-attempt"
-const EXTENSION_RE = /\.[^/.]+$/
-
function dimension(value: unknown): number | undefined {
const parsed = typeof value === "number" ? value : Number.parseFloat(String(value ?? ""))
return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined
}
-async function downloadRemoteImage(src: string, alt: string) {
- try {
- const blob = await fetch(src).then((response) => response.blob())
- const pathName = new URL(src, window.location.origin).pathname.split("/").pop() || ""
- const pathExtension = pathName.split(".").pop()
- const hasExtension = pathName.includes(".") && pathExtension && pathExtension.length <= 4
- let filename = pathName
- if (!hasExtension) {
- const extension = blob.type.includes("jpeg") || blob.type.includes("jpg")
- ? "jpg"
- : blob.type.includes("svg")
- ? "svg"
- : blob.type.includes("gif")
- ? "gif"
- : blob.type.includes("webp")
- ? "webp"
- : "png"
- filename = `${(alt || pathName || "image").replace(EXTENSION_RE, "")}.${extension}`
- }
- const objectUrl = URL.createObjectURL(blob)
- const anchor = document.createElement("a")
- anchor.href = objectUrl
- anchor.download = filename
- document.body.appendChild(anchor)
- anchor.click()
- anchor.remove()
- URL.revokeObjectURL(objectUrl)
- } catch {
- window.open(src, "_blank")
- }
-}
-
type MarkdownImageProps = Record<string, unknown> & {
src?: string
alt?: string
@@ -72,9 +38,6 @@ function MarkdownImageAttempt({
const frameWidth = imageWidth && imageHeight
? Math.min(imageWidth, 300 * imageWidth / imageHeight)
: imageWidth ? Math.min(imageWidth, 300) : 300
- const download = useCallback(() => {
- if (src) void downloadRemoteImage(src, alt)
- }, [alt, src])
if (!src) return null
@@ -132,14 +95,14 @@ function MarkdownImageAttempt({
{status === "ready" && (
<>
<span className="pointer-events-none absolute inset-0 hidden rounded-lg bg-foreground/10 group-hover:block" />
- <button
- type="button"
+ <FileDownloadButton
title="Download image"
- onClick={download}
+ url={src}
+ filename={src.split(/[?#]/)[0].split("/").pop() || alt || "image"}
className="absolute right-2 bottom-2 flex size-8 cursor-pointer items-center justify-center rounded-md border border-border bg-background/90 opacity-0 shadow-sm backdrop-blur-sm transition-all duration-200 hover:bg-background group-hover:opacity-100 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<Download className="size-3.5" />
- </button>
+ </FileDownloadButton>
</>
)}
</div>
diff --git a/src/web/src/components/use-artifact-click.dom.test.tsx b/src/web/src/components/use-artifact-click.dom.test.tsx
new file mode 100644
index 000000000..11565e0b5
--- /dev/null
+++ b/src/web/src/components/use-artifact-click.dom.test.tsx
@@ -0,0 +1,98 @@
+import React from "react"
+import { afterEach, describe, expect, it, vi } from "vitest"
+import type { Artifact } from "@alook/shared"
+import { act, render } from "@/test/react-dom-harness"
+import { ArtifactCard } from "./agent-chat/chat-view-parts"
+import { IssueAttachmentList } from "./issues/issue-attachment-list"
+import { useArtifactClick } from "./use-artifact-click"
+import { resetFileDownloadsForTest } from "@/lib/file-download"
+
+const service = vi.hoisted(() => ({ download: vi.fn(), loading: vi.fn<(text: string, options: { action: { label: string; onClick: () => void } }) => number>(() => 1), dismiss: vi.fn(), success: vi.fn(), error: vi.fn() }))
+vi.mock("@/lib/file-save", async importOriginal => ({ ...await importOriginal<object>(), downloadUrl: service.download }))
+vi.mock("sonner", () => ({ toast: service }))
+const binary = { id: "binary", filename: "报告.bin", content_type: "application/octet-stream", size: 36, has_thumbnail: false } as Artifact
+function Card({ artifact = binary, preview = vi.fn(), image }: { artifact?: Artifact; preview?: (artifact: Artifact) => void; image?: (artifact: Artifact) => void }) {
+ const click = useArtifactClick("workspace", preview, image)
+ return <ArtifactCard artifact={artifact} workspaceId="workspace" version={1} hasDuplicates={false} onClick={click} />
+}
+afterEach(() => { resetFileDownloadsForTest(); vi.clearAllMocks() })
+describe("artifact card click controller", () => {
+ it("routes the actual binary card through authenticated file-save and exposes retry", async () => {
+ service.download.mockResolvedValueOnce({ status: "error", message: "network" }).mockResolvedValueOnce({ status: "started" })
+ const preview = vi.fn()
+ const view = render(<Card preview={preview} />)
+ await act(async () => { view.getByRole("button").click() })
+ expect(service.download).toHaveBeenCalledWith("/api/artifacts/binary/content?workspace_id=workspace&download=1", "报告.bin", { signal: expect.any(AbortSignal) })
+ expect(preview).not.toHaveBeenCalled()
+ expect(service.error).toHaveBeenCalledWith("Couldn’t save — retry", expect.objectContaining({ action: expect.objectContaining({ label: "Retry" }) }))
+ await act(async () => { service.error.mock.calls[0][1].action.onClick() })
+ expect(service.download).toHaveBeenCalledTimes(2)
+ expect(service.success).toHaveBeenCalledWith("Download started")
+ })
+ it("allows cancellation from the download notification and a fresh card retry", async () => {
+ service.download.mockImplementationOnce((_url, _name, { signal }) => new Promise(resolve => signal.addEventListener("abort", () => resolve({ status: "cancelled" })))).mockResolvedValueOnce({ status: "saved" })
+ const view = render(<Card />)
+ await act(async () => { view.getByRole("button").click() })
+ await act(async () => { service.loading.mock.calls[0][1].action.onClick() })
+ expect(service.error).not.toHaveBeenCalled()
+ expect(service.success).not.toHaveBeenCalled()
+ await act(async () => { view.getByRole("button").click() })
+ expect(service.success).toHaveBeenCalledWith("Saved")
+ })
+ it("a repeated card click cancels the active download without starting a duplicate", async () => {
+ let signal!: AbortSignal
+ service.download.mockImplementationOnce((_url, _name, options) => {
+ signal = options.signal
+ return new Promise(resolve => signal.addEventListener("abort", () => resolve({ status: "cancelled" })))
+ }).mockResolvedValueOnce({ status: "started" })
+ const view = render(<Card />)
+ await act(async () => { view.getByRole("button").click() })
+ expect(signal.aborted).toBe(false)
+ await act(async () => { view.getByRole("button").click() })
+ expect(signal.aborted).toBe(true)
+ expect(service.download).toHaveBeenCalledTimes(1)
+ expect(service.success).not.toHaveBeenCalled()
+ expect(service.error).not.toHaveBeenCalled()
+ await act(async () => { view.getByRole("button").click() })
+ expect(service.download).toHaveBeenCalledTimes(2)
+ expect(service.success).toHaveBeenCalledWith("Download started")
+ })
+ it.each([true, false])("preserves the image preview choice (lightbox=%s)", async lightbox => {
+ const preview = vi.fn(), image = vi.fn()
+ const artifact = { ...binary, content_type: "image/png", filename: "a.png" }
+ const view = render(<Card artifact={artifact} preview={preview} image={lightbox ? image : undefined} />)
+ await act(async () => { view.getByRole("button").click() })
+ expect(lightbox ? image : preview).toHaveBeenCalledWith(artifact)
+ expect(lightbox ? preview : image).not.toHaveBeenCalled()
+ expect(service.download).not.toHaveBeenCalled()
+ })
+ it("keeps text artifacts in the preview sheet", async () => {
+ const preview = vi.fn()
+ const artifact = { ...binary, content_type: "text/plain" }
+ const view = render(<Card artifact={artifact} preview={preview} />)
+ await act(async () => { view.getByRole("button").click() })
+ expect(preview).toHaveBeenCalledWith(artifact)
+ expect(service.download).not.toHaveBeenCalled()
+ })
+})
+
+describe("issue attachment list click", () => {
+ it("downloads a binary through the owner, even when a preview callback exists", async () => {
+ service.download.mockResolvedValue({ status: "started" })
+ const preview = vi.fn()
+ const view = render(<IssueAttachmentList artifacts={[binary]} workspaceId="workspace" onArtifactClick={preview} />)
+ await act(async () => { view.getByRole("button").click() })
+ expect(service.download).toHaveBeenCalledWith("/api/artifacts/binary/content?workspace_id=workspace&download=1", "报告.bin", { signal: expect.any(AbortSignal) })
+ expect(preview).not.toHaveBeenCalled()
+ expect(view.getByRole("status")).toHaveTextContent("Download started")
+ expect(view.queryByRole("link")).toBeNull()
+ })
+ it("preserves preview callbacks for text attachments", async () => {
+ const artifact = { ...binary, content_type: "text/plain" }
+ const preview = vi.fn()
+ const view = render(<IssueAttachmentList artifacts={[artifact]} workspaceId="workspace" onArtifactClick={preview} />)
+ await act(async () => { view.getByRole("button").click() })
+ expect(preview).toHaveBeenCalledWith(artifact)
+ expect(service.download).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/components/use-artifact-click.ts b/src/web/src/components/use-artifact-click.ts
new file mode 100644
index 000000000..28c5af502
--- /dev/null
+++ b/src/web/src/components/use-artifact-click.ts
@@ -0,0 +1,14 @@
+"use client"
+
+import { useCallback } from "react"
+import type { Artifact } from "@alook/shared"
+import { getArtifactUrl, isPreviewable } from "./artifact-content-renderer"
+import { downloadFileWithFeedback } from "@/lib/file-download-action"
+
+export function useArtifactClick(workspaceId: string, preview: (artifact: Artifact) => void, image?: (artifact: Artifact) => void) {
+ return useCallback((artifact: Artifact) => {
+ if (image && artifact.content_type.startsWith("image/")) image(artifact)
+ else if (isPreviewable(artifact)) preview(artifact)
+ else void downloadFileWithFeedback({ url: getArtifactUrl(artifact.id, workspaceId, true), name: artifact.filename })
+ }, [workspaceId, preview, image])
+}
diff --git a/src/web/src/lib/community/attachment-download.test.ts b/src/web/src/lib/community/attachment-download.test.ts
index 856b90558..104078527 100644
--- a/src/web/src/lib/community/attachment-download.test.ts
+++ b/src/web/src/lib/community/attachment-download.test.ts
@@ -1,141 +1,55 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
-import {
- attachmentDownloadKey,
- readAttachmentDownloadState,
- resetAttachmentDownloadsForTest,
- startAttachmentDownload,
-} from "./attachment-download"
-
-type AnchorMock = {
- href: string
- download: string
- hidden: boolean
- click: ReturnType<typeof vi.fn>
- remove: ReturnType<typeof vi.fn>
-}
-
-function installBrowserMocks() {
- const order: string[] = []
- const anchor: AnchorMock = {
- href: "",
- download: "",
- hidden: false,
- click: vi.fn(() => order.push("click")),
- remove: vi.fn(() => order.push("remove")),
- }
- const createObjectURL = vi.fn(() => {
- order.push("create-url")
- return "blob:attachment"
+import { afterEach, describe, expect, it, vi } from "vitest"
+import { attachmentDownloadKey, readAttachmentDownloadState, resetAttachmentDownloadsForTest, startAttachmentDownload } from "./attachment-download"
+import { cancelFileDownload } from "../file-download"
+const service = vi.hoisted(() => ({ download: vi.fn() }))
+vi.mock("../file-save", () => ({ downloadUrl: service.download, fileSaveMessage: (r: {status:string}) => r.status }))
+afterEach(() => { resetAttachmentDownloadsForTest(); service.download.mockReset() })
+describe("shared download owner", () => {
+ it("deduplicates by source URL and publishes the exact native or browser result", async () => {
+ let finish!: (value: {status:string}) => void
+ service.download.mockReturnValue(new Promise(resolve => { finish = resolve }))
+ const target = { name: "a.pdf", url: "/file/1" }
+ const first = startAttachmentDownload(target)
+ expect(startAttachmentDownload(target)).toBe(first)
+ expect(readAttachmentDownloadState(attachmentDownloadKey(target))).toEqual({status:"downloading"})
+ await Promise.resolve(); expect(service.download).toHaveBeenCalledOnce()
+ finish({status:"started"}); await first
+ expect(readAttachmentDownloadState(target.url)).toEqual({status:"started"})
})
- const revokeObjectURL = vi.fn(() => order.push("revoke-url"))
- vi.stubGlobal("document", {
- createElement: vi.fn(() => anchor),
+ it("separates same filenames on different URLs", async () => {
+ service.download.mockResolvedValue({status:"started"})
+ await Promise.all([startAttachmentDownload({name:"a",url:"/1"}),startAttachmentDownload({name:"a",url:"/2"})])
+ expect(service.download).toHaveBeenCalledTimes(2)
})
- vi.stubGlobal("URL", { createObjectURL, revokeObjectURL })
- return { anchor, createObjectURL, revokeObjectURL, order }
-}
-
-describe("attachment download owner", () => {
- beforeEach(() => resetAttachmentDownloadsForTest())
- afterEach(() => {
- resetAttachmentDownloadsForTest()
- vi.unstubAllGlobals()
+ it("cancels neutrally and retries after failure or cancellation", async () => {
+ service.download.mockImplementationOnce((_url, _name, {signal}) => new Promise(resolve => signal.addEventListener("abort", () => resolve({status:"cancelled"}))))
+ const target = {name:"a",url:"/1"}; const first = startAttachmentDownload(target)
+ await Promise.resolve(); cancelFileDownload(target.url); await first
+ expect(readAttachmentDownloadState(target.url)).toEqual({status:"cancelled"})
+ service.download.mockResolvedValueOnce({status:"error",message:"failed"}).mockResolvedValueOnce({status:"started"})
+ await startAttachmentDownload(target); expect(readAttachmentDownloadState(target.url).status).toBe("error")
+ await startAttachmentDownload(target); expect(readAttachmentDownloadState(target.url).status).toBe("started")
})
-
- it("deduplicates one in-flight attachment until Blob completion and one save trigger", async () => {
- const browser = installBrowserMocks()
- const bytes = new Blob(["complete"])
- let resolveBlob!: (blob: Blob) => void
- const blob = vi.fn(() => new Promise<Blob>((resolve) => { resolveBlob = resolve }))
- const fetchMock = vi.fn().mockResolvedValue({ ok: true, status: 200, blob })
- vi.stubGlobal("fetch", fetchMock)
- const target = {
- name: "报告.pdf",
- url: "/api/community/channels/channel-1/attachments/attachment-1",
- }
-
- const first = startAttachmentDownload(target)
- const second = startAttachmentDownload(target)
- expect(second).toBe(first)
- expect(readAttachmentDownloadState(attachmentDownloadKey(target))).toEqual({ status: "downloading" })
+ it("evicts old inactive results while preserving an in-flight download", async () => {
+ let finish!: (value: { status: string }) => void
+ service.download.mockReturnValueOnce(new Promise(resolve => { finish = resolve })).mockResolvedValue({ status: "started" })
+ const active = startAttachmentDownload({ name: "active", url: "/active" })
await Promise.resolve()
- expect(fetchMock).toHaveBeenCalledOnce()
- expect(fetchMock).toHaveBeenCalledWith(target.url, { credentials: "same-origin" })
- expect(browser.anchor.click).not.toHaveBeenCalled()
- expect(readAttachmentDownloadState(target.url)).toEqual({ status: "downloading" })
-
- await vi.waitFor(() => expect(blob).toHaveBeenCalledOnce())
- resolveBlob(bytes)
- await first
- expect(browser.createObjectURL).toHaveBeenCalledWith(bytes)
- expect(browser.anchor).toEqual(expect.objectContaining({
- href: "blob:attachment",
- download: "报告.pdf",
- hidden: true,
- }))
- expect(browser.anchor.click).toHaveBeenCalledOnce()
- expect(browser.anchor.remove).toHaveBeenCalledOnce()
- expect(browser.revokeObjectURL).toHaveBeenCalledOnce()
- expect(browser.order).toEqual(["create-url", "click", "remove", "revoke-url"])
- expect(readAttachmentDownloadState(target.url)).toEqual({ status: "success" })
- })
-
- it("does not key same-named attachments from different channel routes together", async () => {
- installBrowserMocks()
- const fetchMock = vi.fn().mockResolvedValue({
- ok: true,
- status: 200,
- blob: vi.fn().mockResolvedValue(new Blob(["bytes"])),
- })
- vi.stubGlobal("fetch", fetchMock)
- const first = { name: "report.pdf", url: "/api/community/channels/channel-1/attachments/a1" }
- const second = { name: "report.pdf", url: "/api/community/channels/channel-2/attachments/a1" }
-
- await Promise.all([startAttachmentDownload(first), startAttachmentDownload(second)])
- expect(fetchMock).toHaveBeenCalledTimes(2)
- expect(attachmentDownloadKey(first)).not.toBe(attachmentDownloadKey(second))
- })
-
- it.each([
- ["network", () => Promise.reject(new TypeError("network failed"))],
- ["abort", () => Promise.reject(new DOMException("Aborted", "AbortError"))],
- ["non-2xx", () => Promise.resolve({ ok: false, status: 403, blob: vi.fn() })],
- ["Blob", () => Promise.resolve({ ok: true, status: 200, blob: vi.fn().mockRejectedValue(new Error("Blob failed")) })],
- ])("makes %s failure visible and allows a later retry", async (_kind, failedFetch) => {
- const browser = installBrowserMocks()
- const fetchMock = vi.fn()
- .mockImplementationOnce(failedFetch)
- .mockResolvedValueOnce({
- ok: true,
- status: 200,
- blob: vi.fn().mockResolvedValue(new Blob(["retry"])),
- })
- vi.stubGlobal("fetch", fetchMock)
- const target = { name: "report.pdf", url: "/api/community/channels/c1/attachments/a1" }
-
- await startAttachmentDownload(target)
- expect(readAttachmentDownloadState(target.url).status).toBe("error")
- expect(browser.anchor.click).not.toHaveBeenCalled()
-
- await startAttachmentDownload(target)
- expect(fetchMock).toHaveBeenCalledTimes(2)
- expect(browser.anchor.click).toHaveBeenCalledOnce()
- expect(readAttachmentDownloadState(target.url)).toEqual({ status: "success" })
+ for (let index = 0; index < 130; index++) await startAttachmentDownload({ name: "file", url: `/file/${index}` })
+ expect(readAttachmentDownloadState("/file/0")).toEqual({ status: "idle" })
+ expect(readAttachmentDownloadState("/file/129")).toEqual({ status: "started" })
+ expect(readAttachmentDownloadState("/active")).toEqual({ status: "downloading" })
+ expect(startAttachmentDownload({ name: "active", url: "/active" })).toBe(active)
+ finish({ status: "cancelled" })
+ await active
+ expect(readAttachmentDownloadState("/active")).toEqual({ status: "cancelled" })
})
-
- it("cleans up a created anchor and object URL when the save trigger throws", async () => {
- const browser = installBrowserMocks()
- browser.anchor.click.mockImplementationOnce(() => { throw new Error("save blocked") })
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
- ok: true,
- status: 200,
- blob: vi.fn().mockResolvedValue(new Blob(["bytes"])),
- }))
- const target = { name: "report.pdf", url: "/api/community/channels/c1/attachments/a1" }
-
- await startAttachmentDownload(target)
- expect(readAttachmentDownloadState(target.url).status).toBe("error")
- expect(browser.anchor.remove).toHaveBeenCalledOnce()
- expect(browser.revokeObjectURL).toHaveBeenCalledWith("blob:attachment")
+ it("does not let an abandoned flight overwrite a new attempt", async () => {
+ let finish!: (value: {status:string}) => void
+ service.download.mockReturnValueOnce(new Promise(resolve => {finish=resolve})).mockResolvedValueOnce({status:"started"})
+ const target={name:"a",url:"/1"}; const old=startAttachmentDownload(target); await Promise.resolve()
+ resetAttachmentDownloadsForTest(); await startAttachmentDownload(target)
+ finish({status:"error"}); await old
+ expect(readAttachmentDownloadState(target.url)).toEqual({status:"started"})
})
})
diff --git a/src/web/src/lib/community/attachment-download.ts b/src/web/src/lib/community/attachment-download.ts
index 8f29af1c7..d2071101d 100644
--- a/src/web/src/lib/community/attachment-download.ts
+++ b/src/web/src/lib/community/attachment-download.ts
@@ -1,116 +1,10 @@
"use client"
-import { useCallback, useSyncExternalStore } from "react"
-
-export type AttachmentDownloadTarget = {
- name: string
- url: string
-}
-
-export type AttachmentDownloadState =
- | { status: "idle" }
- | { status: "downloading" }
- | { status: "success" }
- | { status: "error"; message: string }
-
-const IDLE_STATE: AttachmentDownloadState = { status: "idle" }
-const states = new Map<string, AttachmentDownloadState>()
-const listeners = new Map<string, Set<() => void>>()
-const inFlight = new Map<string, Promise<void>>()
-
-export function attachmentDownloadKey(attachment: AttachmentDownloadTarget): string {
- return attachment.url
-}
-
-export function readAttachmentDownloadState(key: string): AttachmentDownloadState {
- return states.get(key) ?? IDLE_STATE
-}
-
-export function attachmentDownloadStatusText(state: AttachmentDownloadState): string | null {
- if (state.status === "downloading") return "Downloading…"
- if (state.status === "success") return "Download started"
- if (state.status === "error") return "Couldn’t download — retry"
- return null
-}
-
-function publish(key: string, state: AttachmentDownloadState): void {
- states.set(key, state)
- for (const listener of listeners.get(key) ?? []) listener()
-}
-
-function subscribe(key: string, listener: () => void): () => void {
- const keyListeners = listeners.get(key) ?? new Set<() => void>()
- keyListeners.add(listener)
- listeners.set(key, keyListeners)
- return () => {
- keyListeners.delete(listener)
- if (keyListeners.size === 0) listeners.delete(key)
- }
-}
-
-async function acquireAndSave(attachment: AttachmentDownloadTarget): Promise<void> {
- let objectUrl: string | null = null
- let anchor: HTMLAnchorElement | null = null
- try {
- const response = await fetch(attachment.url, { credentials: "same-origin" })
- if (!response.ok) throw new Error(`Couldn’t download this attachment (${response.status})`)
- const blob = await response.blob()
- objectUrl = URL.createObjectURL(blob)
- anchor = document.createElement("a")
- anchor.href = objectUrl
- anchor.download = attachment.name
- anchor.hidden = true
- anchor.click()
- } finally {
- anchor?.remove()
- if (objectUrl) URL.revokeObjectURL(objectUrl)
- }
-}
-
-export function startAttachmentDownload(attachment: AttachmentDownloadTarget): Promise<void> {
- const key = attachmentDownloadKey(attachment)
- const active = inFlight.get(key)
- if (active) return active
-
- const target = { name: attachment.name, url: attachment.url }
- const task = Promise.resolve()
- .then(() => acquireAndSave(target))
- .then(() => publish(key, { status: "success" }))
- .catch((error: unknown) => {
- publish(key, {
- status: "error",
- message: error instanceof Error ? error.message : "Couldn’t download this attachment",
- })
- })
- .finally(() => {
- if (inFlight.get(key) === task) inFlight.delete(key)
- })
-
- inFlight.set(key, task)
- publish(key, { status: "downloading" })
- return task
-}
-
-export function useAttachmentDownload(attachment: AttachmentDownloadTarget): {
- state: AttachmentDownloadState
- start: () => Promise<void>
-} {
- const key = attachmentDownloadKey(attachment)
- const subscribeToKey = useCallback(
- (listener: () => void) => subscribe(key, listener),
- [key],
- )
- const getSnapshot = useCallback(() => readAttachmentDownloadState(key), [key])
- const state = useSyncExternalStore(subscribeToKey, getSnapshot, getSnapshot)
- const start = useCallback(
- () => startAttachmentDownload({ name: attachment.name, url: attachment.url }),
- [attachment.name, attachment.url],
- )
- return { state, start }
-}
-
-export function resetAttachmentDownloadsForTest(): void {
- states.clear()
- listeners.clear()
- inFlight.clear()
-}
+export {
+ fileDownloadKey as attachmentDownloadKey,
+ readFileDownloadState as readAttachmentDownloadState,
+ fileDownloadStatusText as attachmentDownloadStatusText,
+ startFileDownload as startAttachmentDownload,
+ useFileDownload as useAttachmentDownload,
+ resetFileDownloadsForTest as resetAttachmentDownloadsForTest,
+} from "../file-download"
diff --git a/src/web/src/lib/content-disposition.test.ts b/src/web/src/lib/content-disposition.test.ts
new file mode 100644
index 000000000..071c7ed58
--- /dev/null
+++ b/src/web/src/lib/content-disposition.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from "vitest"
+import { contentDisposition, encodeRfc5987 } from "./content-disposition"
+describe("download response filenames", () => {
+ it.each(["report.pdf", "small-报告.bin", "📎😀.txt", 'a"b\\c.txt', "a\r\nb.txt", "a'()*%;.txt", ""])("constructs a legal header preserving %j in filename*", name => {
+ const header = contentDisposition("attachment", name)
+ const response = new Response("exact bytes", { headers: { "Content-Disposition": header } })
+ expect(response.status).toBe(200)
+ expect(header).toMatch(/^[\x20-\x7e]+$/)
+ expect(decodeURIComponent(header.split("filename*=UTF-8''")[1])).toBe(name)
+ expect(header.split("; filename*=")[0]).not.toMatch(/[\r\n\\]/)
+ })
+ it("escapes extended attribute punctuation and keeps inline disposition", () => {
+ expect(encodeRfc5987("'()*")).toBe("%27%28%29%2A")
+ expect(contentDisposition("inline", "报告.pdf")).toBe('inline; filename="__.pdf"; filename*=UTF-8\'\'%E6%8A%A5%E5%91%8A.pdf')
+ })
+})
diff --git a/src/web/src/lib/content-disposition.ts b/src/web/src/lib/content-disposition.ts
new file mode 100644
index 000000000..3085e8914
--- /dev/null
+++ b/src/web/src/lib/content-disposition.ts
@@ -0,0 +1,8 @@
+export function encodeRfc5987(value: string): string {
+ return encodeURIComponent(value).replace(/['()*]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase()}`)
+}
+
+export function contentDisposition(disposition: "inline" | "attachment", filename: string): string {
+ const fallback = filename.replace(/[^\x20-\x7E]/g, "_").replace(/["\\]/g, "_").trim() || "download"
+ return `${disposition}; filename="${fallback}"; filename*=UTF-8''${encodeRfc5987(filename)}`
+}
diff --git a/src/web/src/lib/file-download-action.ts b/src/web/src/lib/file-download-action.ts
new file mode 100644
index 000000000..02183a20b
--- /dev/null
+++ b/src/web/src/lib/file-download-action.ts
@@ -0,0 +1,23 @@
+"use client"
+
+import { toast } from "sonner"
+import { cancelFileDownload, fileDownloadKey, fileDownloadStatusText, readFileDownloadState, startFileDownload } from "./file-download"
+
+export async function downloadFileWithFeedback(target: { url: string; name: string }): Promise<void> {
+ const key = fileDownloadKey(target)
+ if (readFileDownloadState(key).status === "downloading") {
+ cancelFileDownload(key)
+ return
+ }
+ const id = toast.loading("Downloading…", {
+ action: { label: "Cancel", onClick: () => cancelFileDownload(key) },
+ })
+ await startFileDownload(target)
+ toast.dismiss(id)
+ const result = readFileDownloadState(key)
+ const text = fileDownloadStatusText(result)
+ if (result.status === "error") toast.error(text, {
+ action: { label: "Retry", onClick: () => { void downloadFileWithFeedback(target) } },
+ })
+ else if (result.status === "saved" || result.status === "started") toast.success(text)
+}
diff --git a/src/web/src/lib/file-download.ts b/src/web/src/lib/file-download.ts
new file mode 100644
index 000000000..2a397ac28
--- /dev/null
+++ b/src/web/src/lib/file-download.ts
@@ -0,0 +1,60 @@
+"use client"
+
+import { useCallback, useSyncExternalStore } from "react"
+import { downloadUrl, fileSaveMessage, type FileSaveResult } from "./file-save"
+
+type FileDownloadTarget = { name: string; url: string }
+type FileDownloadState = { status: "idle" } | { status: "downloading" } | FileSaveResult
+const idle: FileDownloadState = { status: "idle" }
+const states = new Map<string, FileDownloadState>()
+const listeners = new Map<string, Set<() => void>>()
+const flights = new Map<string, { controller: AbortController; promise: Promise<void> }>()
+
+export function fileDownloadKey(target: FileDownloadTarget): string { return target.url }
+export function readFileDownloadState(key: string): FileDownloadState { return states.get(key) ?? idle }
+export function fileDownloadStatusText(state: FileDownloadState): string | null {
+ if (state.status === "downloading") return "Downloading…"
+ return state.status === "idle" ? null : fileSaveMessage(state)
+}
+function publish(key: string, state: FileDownloadState): void {
+ states.set(key, state)
+ if (states.size > 128) {
+ for (const stale of states.keys()) {
+ if (stale !== key && !flights.has(stale) && !listeners.has(stale)) states.delete(stale)
+ if (states.size <= 128) break
+ }
+ }
+ for (const listener of listeners.get(key) ?? []) listener()
+}
+export function cancelFileDownload(key: string): void { flights.get(key)?.controller.abort() }
+export function startFileDownload(target: FileDownloadTarget): Promise<void> {
+ const key = fileDownloadKey(target)
+ const existing = flights.get(key)
+ if (existing) return existing.promise
+ const controller = new AbortController()
+ const promise = Promise.resolve()
+ .then(() => downloadUrl(target.url, target.name, { signal: controller.signal }))
+ .then(result => { if (flights.get(key)?.controller === controller) publish(key, result) })
+ .finally(() => { if (flights.get(key)?.promise === promise) flights.delete(key) })
+ flights.set(key, { controller, promise })
+ publish(key, { status: "downloading" })
+ return promise
+}
+export function useFileDownload(target: FileDownloadTarget) {
+ const key = fileDownloadKey(target)
+ const subscribe = useCallback((listener: () => void) => {
+ const set = listeners.get(key) ?? new Set<() => void>()
+ set.add(listener)
+ listeners.set(key, set)
+ return () => { set.delete(listener); if (!set.size) listeners.delete(key) }
+ }, [key])
+ const snapshot = useCallback(() => readFileDownloadState(key), [key])
+ const state = useSyncExternalStore(subscribe, snapshot, snapshot)
+ const start = useCallback(() => startFileDownload({ url: target.url, name: target.name }), [target.url, target.name])
+ const cancel = useCallback(() => cancelFileDownload(key), [key])
+ return { state, start, cancel }
+}
+export function resetFileDownloadsForTest(): void {
+ for (const flight of flights.values()) flight.controller.abort()
+ flights.clear(); states.clear(); listeners.clear()
+}
diff --git a/src/web/src/lib/file-save.test.ts b/src/web/src/lib/file-save.test.ts
new file mode 100644
index 000000000..a47cd620b
--- /dev/null
+++ b/src/web/src/lib/file-save.test.ts
@@ -0,0 +1,121 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { downloadUrl, saveFile, 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"
+function browser() {
+ const anchor = { href: "", download: "", hidden: false, click: vi.fn(), remove: vi.fn() }
+ vi.stubGlobal("document", { createElement: vi.fn(() => anchor), body: { appendChild: vi.fn() } })
+ vi.stubGlobal("URL", { createObjectURL: vi.fn(() => "blob:save"), revokeObjectURL: vi.fn() })
+ return anchor
+}
+function native() {
+ bridge.native = true
+ let bytes = 0
+ let name = ""
+ let mime = ""
+ bridge.invoke.mockImplementation(async (command, { payload } = {}) => {
+ if (command === "file_save_begin") { name = payload.name; mime = payload.mime; return { attemptId: id } }
+ if (command === "file_save_write_chunk") { bytes += atob(payload.data).length; return { attemptId: id, bytes, sequence: payload.sequence + 1 } }
+ if (command === "file_save_commit") return { attemptId: id, bytes, name, mime, sha256: "a".repeat(64), destination: "desktop", status: "saved" }
+ })
+}
+beforeEach(() => { bridge.native = false; bridge.invoke.mockReset(); vi.stubGlobal("crypto", { randomUUID: () => id }); vi.useFakeTimers() })
+afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); vi.unstubAllGlobals() })
+
+describe("product file save", () => {
+ it("uses authenticated fetch and reports browser started, retaining the URL while download begins", async () => {
+ const anchor = browser()
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("abc", { headers: { "content-length": "3" } })))
+ expect(await downloadUrl("/private/file", "报告.txt")).toEqual({ status: "started" })
+ expect(fetch).toHaveBeenCalledWith("/private/file", { credentials: "same-origin", signal: undefined })
+ expect(anchor.download).toBe("报告.txt"); expect(anchor.click).toHaveBeenCalledOnce()
+ expect(anchor.remove).toHaveBeenCalledOnce(); expect(URL.revokeObjectURL).not.toHaveBeenCalled()
+ vi.advanceTimersByTime(60_000); expect(URL.revokeObjectURL).toHaveBeenCalledWith("blob:save")
+ })
+ it("streams sequential bounded native chunks and validates the final receipt", async () => {
+ native()
+ const data = new Uint8Array(FILE_SAVE_CHUNK_BYTES * 2 + 1).fill(127)
+ expect(await saveFile(new Blob([data]), "a.bin")).toEqual(expect.objectContaining({ status: "saved", bytes: data.length }))
+ const chunks = bridge.invoke.mock.calls.filter(([command]) => command === "file_save_write_chunk").map(([, args]) => args.payload)
+ expect(chunks.map(c => c.sequence)).toEqual([0, 1, 2])
+ expect(chunks.map(c => c.offset)).toEqual([0, FILE_SAVE_CHUNK_BYTES, FILE_SAVE_CHUNK_BYTES * 2])
+ expect(chunks.map(c => atob(c.data).length)).toEqual([FILE_SAVE_CHUNK_BYTES, FILE_SAVE_CHUNK_BYTES, 1])
+ expect(bridge.invoke).not.toHaveBeenCalledWith("file_save_cancel", expect.anything())
+ })
+ it.each(["name", "mime", "bytes", "sha256", "attemptId", "destination", "status"])("rejects invalid native %s without browser fallback", async field => {
+ browser(); native()
+ const original = bridge.invoke.getMockImplementation()!
+ bridge.invoke.mockImplementation(async (...args) => {
+ const result = await original(...args)
+ return args[0] === "file_save_commit" ? { ...result, [field]: "invalid" } : result
+ })
+ expect((await saveFile(new Blob(["a"]), "a.txt")).status).toBe("error")
+ expect(bridge.invoke).toHaveBeenCalledWith("file_save_cancel", { attemptId: id })
+ expect(URL.createObjectURL).not.toHaveBeenCalled()
+ })
+ 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")
+ expect(bridge.invoke).toHaveBeenCalledWith("file_save_cancel", { attemptId: id })
+ })
+ it("keeps picker cancellation neutral", async () => {
+ native(); const original = bridge.invoke.getMockImplementation()!
+ bridge.invoke.mockImplementation(async (...args) => args[0] === "file_save_commit" ? { attemptId: id, status: "cancelled" } : original(...args))
+ expect(await saveFile(new Blob([]), "empty")).toEqual({ status: "cancelled" })
+ })
+ it("cancels a reader and native attempt on abort during streaming", async () => {
+ native(); const controller = new AbortController()
+ const original = bridge.invoke.getMockImplementation()!
+ bridge.invoke.mockImplementation(async (...args) => { const value = await original(...args); if (args[0] === "file_save_write_chunk") controller.abort(); return value })
+ expect(await saveFile(new Blob(["a"]), "a", { signal: controller.signal })).toEqual({ status: "cancelled" })
+ expect(bridge.invoke).toHaveBeenCalledWith("file_save_cancel", { attemptId: id })
+ expect(bridge.invoke.mock.calls.some(([c]) => c === "file_save_commit")).toBe(false)
+ })
+ it.each(["http", "missing-body", "short-body", "stream-error"])("does not report success on %s", async kind => {
+ const anchor = browser()
+ const response = kind === "http" ? new Response("no", { status: 403 })
+ : kind === "missing-body" ? new Response(null)
+ : kind === "short-body" ? new Response("a", { headers: { "content-length": "2" } })
+ : new Response(new ReadableStream({ start(c) { c.error(new Error("read failed")) } }))
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response))
+ expect((await downloadUrl("/file", "a")).status).toBe("error"); expect(anchor.click).not.toHaveBeenCalled()
+ })
+ it("ignores compressed transfer length and accepts unknown length and empty files", async () => {
+ native(); vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("abc", { headers: { "content-length": "1", "content-encoding": "gzip" } })))
+ expect((await downloadUrl("/file", "a")).status).toBe("saved")
+ expect(bridge.invoke).toHaveBeenCalledWith("file_save_begin", { payload: expect.objectContaining({ size: null }) })
+ native(); expect((await saveFile(new Blob([]), "empty")).status).toBe("saved")
+ })
+ it("cleans browser resources when the click fails", async () => {
+ const anchor = browser(); anchor.click.mockImplementation(() => { throw new Error("blocked") })
+ expect((await saveFile(new Blob(["x"]), "a")).status).toBe("error")
+ expect(anchor.remove).toHaveBeenCalled(); vi.advanceTimersByTime(60_000); expect(URL.revokeObjectURL).toHaveBeenCalled()
+ })
+ it("normalizes a coded native cancellation and cleans the attempt without fallback", async () => {
+ const anchor = browser()
+ native()
+ const original = bridge.invoke.getMockImplementation()!
+ bridge.invoke.mockImplementation(async (...args) => {
+ if (args[0] === "file_save_commit") throw { code: "cancelled" }
+ return original(...args)
+ })
+ expect(await saveFile(new Blob(["a"]), "a.txt")).toEqual({ status: "cancelled" })
+ expect(bridge.invoke).toHaveBeenCalledWith("file_save_cancel", { attemptId: id })
+ expect(anchor.click).not.toHaveBeenCalled()
+ })
+ it("returns a retryable error when the source cannot construct its stream", async () => {
+ const anchor = browser()
+ const blob = new Blob(["a"])
+ vi.spyOn(blob, "stream").mockImplementation(() => { throw new Error("source unavailable") })
+ expect(await saveFile(blob, "a.txt")).toEqual({ status: "error", message: "Couldn’t save this file" })
+ expect(anchor.click).not.toHaveBeenCalled()
+ expect(bridge.invoke).not.toHaveBeenCalled()
+ })
+ it("sanitizes paths, controls, reserved names and UTF-8 length", () => {
+ expect(fileSaveName("../CON.txt")).toBe("_CON.txt")
+ expect(fileSaveName("a\\b\0:c?.txt ")).toBe("b_c_.txt")
+ expect(fileSaveName("...")).toBe("download")
+ expect(new TextEncoder().encode(fileSaveName("中".repeat(100))).length).toBeLessThanOrEqual(180)
+ })
+})
diff --git a/src/web/src/lib/file-save.ts b/src/web/src/lib/file-save.ts
new file mode 100644
index 000000000..39162e0fa
--- /dev/null
+++ b/src/web/src/lib/file-save.ts
@@ -0,0 +1,175 @@
+import { isTauri, tauriInvoke } from "@alook/shared"
+
+export const FILE_SAVE_CHUNK_BYTES = 65_536
+export type FileSaveResult =
+ | { status: "started" }
+ | { status: "saved"; name: string; mime: string; bytes: number; sha256: string; destination: string }
+ | { status: "cancelled" }
+ | { status: "error"; message: string }
+
+type FileSource = { name: string; mime: string; size: number | null; stream: ReadableStream<Uint8Array> }
+type NativeReceipt = { attemptId: string; status: string; name: string; mime: string; bytes: number; sha256: string; destination: string }
+
+export function fileSaveMessage(result: FileSaveResult): string | null {
+ if (result.status === "saved") return "Saved"
+ if (result.status === "started") return "Download started"
+ if (result.status === "error") return "Couldn’t save — retry"
+ return null
+}
+
+function normalizedError(error: unknown): FileSaveResult {
+ if (error instanceof DOMException && error.name === "AbortError") return { status: "cancelled" }
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "cancelled") {
+ return { status: "cancelled" }
+ }
+ return { status: "error", message: "Couldn’t save this file" }
+}
+
+export function fileSaveName(value: string): string {
+ const base = value.normalize("NFC").split(/[\\/]/).pop() ?? ""
+ let name = Array.from(base).filter(char => !/[\p{Cc}]/u.test(char))
+ .join("").replace(/[<>:"|?*]/g, "_").replace(/^[.\s]+|[.\s]+$/g, "")
+ if (!name) name = "download"
+ if (/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(name)) name = `_${name}`
+ while (new TextEncoder().encode(name).length > 180) name = Array.from(name).slice(0, -1).join("")
+ return name.replace(/[.\s]+$/g, "") || "download"
+}
+
+function fileSaveMime(value: string): string {
+ const mime = value.split(";")[0].trim().toLowerCase()
+ return mime.length <= 127 && /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/.test(mime) ? mime : "application/octet-stream"
+}
+
+function encodeChunk(bytes: Uint8Array): string {
+ let binary = ""
+ for (const byte of bytes) binary += String.fromCharCode(byte)
+ return btoa(binary)
+}
+
+function abortIfNeeded(signal?: AbortSignal): void {
+ if (signal?.aborted) throw new DOMException("Cancelled", "AbortError")
+}
+
+async function browserSave(source: FileSource, signal?: AbortSignal): Promise<FileSaveResult> {
+ const reader = source.stream.getReader()
+ const parts: Uint8Array<ArrayBuffer>[] = []
+ const onAbort = () => { void reader.cancel().catch(() => undefined) }
+ signal?.addEventListener("abort", onAbort, { once: true })
+ try {
+ for (;;) {
+ abortIfNeeded(signal)
+ const part = await reader.read()
+ abortIfNeeded(signal)
+ if (part.done) break
+ parts.push(new Uint8Array(part.value))
+ }
+ } finally {
+ signal?.removeEventListener("abort", onAbort)
+ await reader.cancel().catch(() => undefined)
+ reader.releaseLock()
+ }
+ const blob = new Blob(parts, { type: source.mime })
+ abortIfNeeded(signal)
+ if (source.size !== null && blob.size !== source.size) throw new Error("Length mismatch")
+ const url = URL.createObjectURL(blob)
+ const anchor = document.createElement("a")
+ try {
+ anchor.href = url
+ anchor.download = source.name
+ anchor.hidden = true
+ document.body.appendChild(anchor)
+ anchor.click()
+ return { status: "started" }
+ } finally {
+ anchor.remove()
+ setTimeout(() => URL.revokeObjectURL(url), 60_000)
+ }
+}
+
+async function nativeSave(source: FileSource, signal?: AbortSignal): Promise<FileSaveResult> {
+ const attemptId = crypto.randomUUID()
+ const reader = source.stream.getReader()
+ let begun = false
+ let completed = false
+ let bytes = 0
+ let sequence = 0
+ const cancelNative = () => tauriInvoke("file_save_cancel", { attemptId }).catch(() => undefined)
+ const onAbort = () => { void reader.cancel().catch(() => undefined); if (begun) void cancelNative() }
+ signal?.addEventListener("abort", onAbort, { once: true })
+ try {
+ abortIfNeeded(signal)
+ const begin = await tauriInvoke<{ attemptId: string }>("file_save_begin", {
+ payload: { attemptId, name: source.name, mime: source.mime, size: source.size },
+ })
+ begun = true
+ if (begin.attemptId !== attemptId) throw new Error("Mismatched save attempt")
+ abortIfNeeded(signal)
+ for (;;) {
+ const chunk = await reader.read()
+ abortIfNeeded(signal)
+ if (chunk.done) break
+ for (let offset = 0; offset < chunk.value.byteLength; offset += FILE_SAVE_CHUNK_BYTES) {
+ abortIfNeeded(signal)
+ const part = chunk.value.subarray(offset, offset + FILE_SAVE_CHUNK_BYTES)
+ const next = bytes + part.byteLength
+ if (!Number.isSafeInteger(next) || (source.size !== null && next > source.size)) throw new Error("Length mismatch")
+ const receipt = await tauriInvoke<{ attemptId: string; bytes: number; sequence: number }>("file_save_write_chunk", {
+ payload: { attemptId, sequence, offset: bytes, data: encodeChunk(part) },
+ })
+ if (receipt.attemptId !== attemptId || receipt.bytes !== next || receipt.sequence !== sequence + 1) {
+ throw new Error("Mismatched write receipt")
+ }
+ bytes = next
+ sequence += 1
+ }
+ }
+ if (source.size !== null && bytes !== source.size) throw new Error("Length mismatch")
+ abortIfNeeded(signal)
+ 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
+ || result.mime !== source.mime || !/^[a-f0-9]{64}$/.test(result.sha256)
+ || !["downloads", "files", "document", "desktop"].includes(result.destination)) {
+ throw new Error("Invalid save receipt")
+ }
+ completed = true
+ return { status: "saved", name: result.name, mime: result.mime, bytes, sha256: result.sha256, destination: result.destination }
+ } finally {
+ signal?.removeEventListener("abort", onAbort)
+ await reader.cancel().catch(() => undefined)
+ reader.releaseLock()
+ if (begun && !completed) await cancelNative()
+ }
+}
+
+async function saveSource(source: FileSource, signal?: AbortSignal): Promise<FileSaveResult> {
+ try {
+ abortIfNeeded(signal)
+ return await (isTauri() ? nativeSave(source, signal) : browserSave(source, signal))
+ } catch (error) {
+ return signal?.aborted ? { status: "cancelled" } : normalizedError(error)
+ }
+}
+
+export async function saveFile(blob: Blob, name: string, options: { signal?: AbortSignal } = {}): Promise<FileSaveResult> {
+ try {
+ return await saveSource({ name: fileSaveName(name), mime: fileSaveMime(blob.type), size: blob.size, stream: blob.stream() }, options.signal)
+ } catch (error) { return normalizedError(error) }
+}
+
+export async function downloadUrl(url: string, name: string, options: { signal?: AbortSignal } = {}): Promise<FileSaveResult> {
+ try {
+ abortIfNeeded(options.signal)
+ const response = await fetch(url, { credentials: "same-origin", signal: options.signal })
+ if (!response.ok) throw new Error("Download failed")
+ const mime = fileSaveMime(response.headers.get("content-type") ?? "")
+ const length = response.headers.get("content-length")
+ const size = length !== null && /^\d+$/.test(length) && !response.headers.get("content-encoding") ? Number(length) : null
+ if (size !== null && !Number.isSafeInteger(size)) throw new Error("Invalid length")
+ if (!response.body) throw new Error("Missing response body")
+ return await saveSource({ name: fileSaveName(name), mime, size, stream: response.body }, options.signal)
+ } catch (error) {
+ return options.signal?.aborted ? { status: "cancelled" } : normalizedError(error)
+ }
+}
diff --git a/src/web/src/test/e2e-ui/56-remote-image-state-contract.spec.ts b/src/web/src/test/e2e-ui/56-remote-image-state-contract.spec.ts
index 8288cc4f3..e2c590bf9 100644
--- a/src/web/src/test/e2e-ui/56-remote-image-state-contract.spec.ts
+++ b/src/web/src/test/e2e-ui/56-remote-image-state-contract.spec.ts
@@ -1,3 +1,4 @@
+import { readFile } from "node:fs/promises"
import type { Locator } from "@playwright/test"
import { test, expect } from "./_fixtures/community-fixture"
import { solidPngFixture, structuredJpegFixture } from "../fixtures/media"
@@ -12,7 +13,7 @@ async function expectStableFrame(frame: Locator, expected: { width: number; heig
}).toEqual(expected)
}
-test("Workspace artifact thumbnails and full images hold geometry through failure and exact-URL retry", async ({ asUser }) => {
+test("Workspace artifact thumbnails and full images hold geometry through failure and exact-URL retry", async ({ asUser }, testInfo) => {
test.setTimeout(180_000)
const { context, page } = await asUser("alice", { viewport: { width: 1280, height: 800 } })
const suffix = Date.now().toString(36)
@@ -130,7 +131,7 @@ test("Workspace artifact thumbnails and full images hold geometry through failur
await page.getByRole("button", { name: "Open artifact.png" }).first().click()
const fullImage = page.locator('img[alt="artifact.png"][src*="/content"]')
await expect(fullImage).toHaveAttribute("data-remote-image-state", "pending")
- await expect(page.getByRole("link", { name: "Download artifact.png" })).toBeVisible()
+ await expect(page.getByRole("button", { name: "Download artifact.png" })).toBeVisible()
const contentFrame = fullImage.locator("xpath=ancestor::*[@data-remote-image-frame][1]")
const contentPendingBox = await contentFrame.boundingBox()
expect(contentPendingBox).not.toBeNull()
@@ -148,6 +149,14 @@ test("Workspace artifact thumbnails and full images hold geometry through failur
await expect(fullImage).toHaveAttribute("src", contentUrl!)
await expect(fullImage).toHaveAttribute("data-remote-image-state", "ready")
await expectStableFrame(contentFrame, contentSize)
+ const downloadStarted = page.waitForEvent("download")
+ await page.getByRole("button", { name: "Download artifact.png" }).click()
+ const download = await downloadStarted
+ expect(download.suggestedFilename()).toBe("artifact.png")
+ const savedPath = testInfo.outputPath("artifact.png")
+ await download.saveAs(savedPath)
+ expect(await readFile(savedPath)).toEqual(ARTIFACT_IMAGE)
+ await expect(page.getByRole("button", { name: "Download artifact.png" }).getByRole("status")).toHaveText("Download started")
await page.getByRole("button", { name: "Close image" }).click()
await expect(fullImage).toHaveCount(0)
})