The folder import code in my Tauri app registers a batch under its own task_id, then hands a future to a task manager under the name "import-phase2". Start a second import and it gets a fresh ID and exactly the same worker name.
That looks a little odd until you try to wire up the Stop button. The button needs to cancel one particular import. The application’s Quit handler has a different job. It needs to wake every background worker, including any imports still writing to SQLite, and give them time to finish. I ended up with both registrations while building LumenPod.
A worker that returns after five seconds
LumenPod runs a library sync loop for as long as the app is open. It also runs finite jobs, including folder imports. Both are Rust futures that return (). If a folder import returns after five seconds, it may have finished early enough for me to miss the progress dialog. If the sync loop returns after five seconds, the application can stay open all afternoon without syncing again.
At the call site, the distinction is one method name. The sync loop uses tasks.spawn("library-sync", ...). The import uses tasks.spawn_once("import-phase2", ...). Here, once means each invocation runs one pass to completion. Two imports can run concurrently under that name.
Both methods give the worker a child of the app’s root CancellationToken, wrap its future in a tracing span carrying the worker name, and register it with a TaskTracker. The difference shows up when worker.await returns. An early return from library-sync produces a warning while the app is still running. An ordinary return from import-phase2 is logged at debug level. A panic unwinds past that check and goes through the host’s panic hook.
There’s a Tauri-specific detail in the registration. Some workers start from the application setup callback, where we can’t assume there’s a current Tokio runtime context. The manager calls tracker.track_future(...), then passes that wrapped future to tauri::async_runtime::spawn(...). This lets us use the same tracker for shutdown while leaving the choice of runtime to Tauri.
The ID behind the Stop button
By the time the folder import command returns to the webview, its background pass can still have database writes ahead of it. This is the part of the Rust code that gives the webview a handle on that work, with the import arguments omitted:
let stop_token = CancellationToken::new(); import_task_service::start(&task_id, stop_token.clone(), requested_files); let guard = import_task_service::watch(&task_id); tasks.spawn_once("import-phase2", move |shutdown| async move { let _guard = guard; let token = stop_token; // Run the import with this batch's token. }); start puts the token and an initial progress snapshot in a map keyed by task_id. It runs before the future is spawned, so a status query can find the batch even if the runtime hasn’t polled the worker yet. The webview only needs the ID. The Rust JoinHandle never has to cross IPC.
Clicking Stop sends that ID back to Rust. For an active import, the backend sets stopping, increments the snapshot revision, and signals the batch token. A second import keeps running. The first can also keep running briefly if it’s finishing a chunk, which is why the dialog says Stopping while it waits for the worker’s result.
There’s a small race in the other direction, too. An import can finish just before the user clicks Stop, with its completion event still on the way to the webview. The backend checks done before signalling the token. A late click leaves the completed result intact.
The await after cancellation
The folder worker receives two cancellation tokens. shutdown comes from the application-wide manager. token belongs to the batch. The import code already knows how to stop at a chunk boundary when its batch token is signalled, so the shutdown branch uses that same path:
tokio::pin!(work); tokio::select! { _ = &mut work => {}, _ = shutdown.cancelled() => { token.cancel(); work.await; } } The line worth looking at is work.await. Suppose the user quits while an import is writing a chunk. If the shutdown branch returned immediately after token.cancel(), the enclosing future would drop work. The tracker could report that the worker had exited before the import got another poll to observe its token or finish its bookkeeping.
The first select! arm borrows the pinned future as &mut work. If shutdown wins, the second arm can continue polling that same future from where it left off. The current chunk has a chance to finish its transaction, and the import can record what committed before it stops.
The Quit handler puts a five-second bound on this. It signals the root token, closes the tracker, and waits for the workers to drain. If the deadline expires, it logs a warning and stops waiting. For a user trying to find out whether a particular file made it into the library, that warning alone tells them very little. The answer comes from the batch record.
What happened to the ten files?
One of the import registry tests starts with ten requested files. It records three imports, two skips, and one failure, then stops the batch. Six files have an outcome. Four are still unprocessed.
That last category earns its place in the UI. If the dialog counted the four untouched files as failures, the user would have five files to troubleshoot, even though the importer encountered an error on only one. And because the database-writing pass updates its result counts after the corresponding transaction commits, the three imported files are already part of the library. The current filename in a progress event makes a much weaker claim. It tells the UI what the worker is looking at.
Cancellation also has to survive the worker’s ordinary completion code. In the test, the worker sends a final update with stage: "complete". The registry sees that the token was cancelled and carries forward the last meaningful stage and its counters. The final snapshot can now say the batch stopped during import with six of ten files accounted for.
When the last progress event goes missing
The backend records each progress snapshot before sending its event. While the webview is following an import, it also asks Rust for the current snapshot every five seconds, with at most one query in flight. A missed completion event costs the dialog an extra wait until a successful query. If a query fails, the dialog can keep waiting. Silence alone can’t tell it whether a worker is stuck or busy.
The guard in the registration snippet covers a different failure. If the worker future drops while the batch is still active, the guard marks it done and records Import worker stopped before reporting a result. The next status query can surface that error. Both the guard and the snapshot live in the Rust process, so recovering across a hard process kill would require durable job state and a restart policy.
There’s a test for the uneventful case that I’d keep alongside the cancellation tests. An import finishes with four files imported and one skipped. The test reads the terminal snapshot, then calls stop on the finished batch. The token stays live and the result still says four imported, one skipped. By then the task manager can be finished with the future. Someone looking at the dialog still needs those numbers.