Skip to content

Commit e3b456c

Browse files
matt2eclaude
andcommitted
fix(desktop): apply the review of the in-app installer download
Applies the review findings on d5bd8fe, which made the deprecation banner download the new app's installer inside the app. Leftover partial files - The signal-handler exit path now aborts the download and removes its partial file. That path ends in exit(), so the download never cleaned up after itself. - The running download's partial path is recorded in the app data directory. The next launch removes exactly that path, and only while it is still a regular file named like one of this module's partials. No folder is searched. A normal finish, cancel or exit clears the record. Failure reasons and actions - A redirect the policy refuses is "redirect-blocked". It no longer asks the user to check their internet connection. - A write the system refuses is "permission-denied". It no longer shows the free-space message. On macOS the wording says where to allow access to the Downloads folder, for a user who declined the system prompt. - Linux falls back to ~/Downloads when no XDG download directory is configured. - Failures a retry cannot fix (redirect blocked, protection mark not written, permission denied, too large) lead with "Download in browser", which opens the validated installer URL as 78d9bcd did. A rejected URL leads with buzz.xyz and is never opened. "Try again" leads only for transient failures. - The release tag is restricted to letters, digits and ._+-/ in both the Rust validator and resolveInstallerUrl, so no percent escape reaches GitHub. Window and remount - Hiding the main window no longer cancels the download. It is cancelled when the window is destroyed or the app exits. - The banner's owner remounts on a community switch, an identity change and a signer change. The download state moved out of the component into an app-level store, so the download and its dialog survive that. This was smaller than a visible "cancelled" state, which needs the same store to outlive the remount and new wording on top. Dialog - Focus moves to Cancel when a download starts or restarts. A repeated Enter keydown inside the dialog is ignored, so holding Enter on the banner button or on "Try again" cannot cancel the download it started. - A failed reveal says the folder could not be opened and points at the path shown. It no longer claims the file was moved or deleted. - An AppImage's finished message gives the make-it-executable step. - The saved file's mode follows the user's umask instead of a fixed 0644: tempfile creates the partial with mode 0666 under the umask. Tests - The mock bridge gained "finish on next cancel" and "fail next reveal". The smoke journeys assert the rendered result of each, plus held Enter, focus after retry, each failure's actions, and a community switch mid-download. - A jsdom test drives the real hook: the attempt fence, the mount-time cancel, and survival across unmount and remount. Where this differs from the review decisions - The hook's unmount cancel is removed, not tested. Surviving a remount requires that unmounting does not cancel, so the test asserts the opposite: unmount sends no cancel and the next mount shows the same download. The mount-time cancel now runs only when this page has no download of its own, and the hook's doc comment states the single-window assumption. - permission-denied keeps "Try again" as its secondary action. The message tells the user how to grant access, after which the same download works. Windows: no behaviour changed. CI does run this crate's tests on Windows. The required "Windows Rust (x86_64-pc-windows-msvc)" job in _ci-rust.yml runs cargo test for desktop/src-tauri on windows-latest when desktop/src-tauri changes, so mark_of_the_web_write_is_verified_by_reading_it_back writes and reads a real alternate data stream there. Not covered anywhere: the stream surviving the final rename inside download_installer, and SmartScreen. macOS CI only builds this crate, so the quarantine test runs locally only. d5bd8fe is not pushed yet, so no Windows or Linux CI result exists for this code. Verified on macOS arm64 - Desktop: biome check, tsc, file-size check, unit tests (6970 node, 187 jsdom), production build. - Tauri crate: fmt, clippy with and without mesh-llm, cargo test --workspace (3470 lib tests), cargo test --features mesh-llm --lib (3576 tests). - Smoke: deprecation-banner.spec.ts, 6 journeys, on an e2e build. - Falsified: 13 Rust, 15 unit and hook, and 7 smoke mutations. Each fails the test that guards it. One gap found this way is closed: the recovery test did not notice a followed symlink. - Native debug build: the download was saved with the umask's mode and com.apple.quarantine set, and Finder revealed it. Cancel removed the partial. With the window hidden the partial kept growing, and the dialog reopened from the tray read 29% then 35%. SIGTERM and a menu quit mid-download removed the partial. After SIGKILL the next launch removed the recorded partial and left a lookalike .part file beside it. Mid-download steps ran through a local throttling proxy. Not verified - The macOS consent prompt and the permission-denied path in a real app: a binary started from a terminal inherits the terminal's access. - The new Rust tests on Windows and Linux. They run in CI after a push. - The full desktop smoke suite. Only the banner spec ran. The rebase of this branch onto origin/main was aborted before this commit and still needs doing. Co-Authored-By: Claude Fable 5.2 <[email protected]> Signed-off-by: Matt Toohey <[email protected]>
1 parent d5bd8fe commit e3b456c

16 files changed

Lines changed: 1380 additions & 199 deletions

‎desktop/src-tauri/src/commands/new_app_installer.rs‎

Lines changed: 224 additions & 39 deletions
Large diffs are not rendered by default.

‎desktop/src-tauri/src/commands/new_app_installer_tests.rs‎

Lines changed: 224 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,32 @@ fn accepts_the_installer_for_each_shipped_target() {
154154
)
155155
.expect("nested tag");
156156
assert_eq!(nested.file_name, "Buzz.dmg");
157+
// Every character a tag may hold.
158+
assert!(validate_installer_url(
159+
"https://github.com/block/buzz-app/releases/download/desktop/v1.0.0-rc.1+build_2/Buzz.dmg",
160+
"macos-arm64",
161+
)
162+
.is_some());
163+
}
164+
165+
#[test]
166+
fn failure_reasons_reach_the_webview_under_their_kebab_names() {
167+
let cases = [
168+
(InstallerFailure::Busy, "busy"),
169+
(InstallerFailure::Rejected, "rejected"),
170+
(InstallerFailure::Network, "network"),
171+
(InstallerFailure::RedirectBlocked, "redirect-blocked"),
172+
(InstallerFailure::TooLarge, "too-large"),
173+
(InstallerFailure::Storage, "storage"),
174+
(InstallerFailure::PermissionDenied, "permission-denied"),
175+
(InstallerFailure::Protection, "protection"),
176+
];
177+
for (reason, name) in cases {
178+
assert_eq!(
179+
serde_json::to_value(reason).expect("serialize"),
180+
serde_json::Value::from(name)
181+
);
182+
}
157183
}
158184

159185
#[test]
@@ -202,6 +228,12 @@ fn rejects_every_url_that_is_not_this_machines_installer() {
202228
"macos-arm64",
203229
),
204230
("no tag segment", "https://github.com/block/buzz-app/releases/download/Buzz.dmg".into(), "macos-arm64"),
231+
("encoded separator in the tag", format!("{RELEASE}%2F..%2F..%2Fother/Buzz.dmg"), "macos-arm64"),
232+
("encoded backslash in the tag", format!("{RELEASE}%5Cother/Buzz.dmg"), "macos-arm64"),
233+
("encoded NUL in the tag", format!("{RELEASE}%00/Buzz.dmg"), "macos-arm64"),
234+
("semicolon in the tag", format!("{RELEASE};other/Buzz.dmg"), "macos-arm64"),
235+
("space in the tag", format!("{RELEASE}%20beta/Buzz.dmg"), "macos-arm64"),
236+
("at sign in the tag", format!("{RELEASE}@other/Buzz.dmg"), "macos-arm64"),
205237
(
206238
"wrong file type for the target",
207239
format!("{RELEASE}/Buzz_1.0.0_x64_unsigned.exe"),
@@ -359,14 +391,114 @@ async fn saves_the_whole_body_under_the_installers_name() {
359391
})
360392
);
361393

394+
// The saved file has the mode any new file gets under this user's umask,
395+
// not the private mode of a temporary file, and it is never executable.
396+
#[cfg(unix)]
397+
{
398+
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
399+
let mode_of = |path: &Path| {
400+
std::fs::metadata(path)
401+
.expect("metadata")
402+
.permissions()
403+
.mode()
404+
& 0o777
405+
};
406+
let ordinary = dir.path().join("ordinary-new-file");
407+
std::fs::OpenOptions::new()
408+
.write(true)
409+
.create_new(true)
410+
.mode(0o666)
411+
.open(&ordinary)
412+
.expect("ordinary file");
413+
assert_eq!(mode_of(&saved), mode_of(&ordinary));
414+
assert_eq!(mode_of(&saved) & 0o111, 0, "not executable");
415+
}
416+
}
417+
418+
#[tokio::test]
419+
async fn a_redirect_the_policy_refuses_is_its_own_failure() {
420+
let addr = serve().await;
421+
let dir = tempfile::tempdir().expect("download dir");
422+
423+
// 127.0.0.1 is not a release asset host, so the policy stops the redirect.
424+
let result = download_installer(
425+
&installer_client_builder().build().expect("client"),
426+
&source_at(addr, "/redirects"),
427+
dir.path(),
428+
test_limits(),
429+
&CancellationToken::new(),
430+
|_| {},
431+
|_, _| Ok(()),
432+
|_| {},
433+
)
434+
.await;
435+
436+
assert_eq!(
437+
result,
438+
Err(TransferError::Failed(InstallerFailure::RedirectBlocked))
439+
);
440+
assert_eq!(file_names(dir.path()), Vec::<String>::new());
441+
}
442+
443+
#[tokio::test]
444+
async fn a_folder_that_cannot_be_written_names_its_cause() {
445+
let addr = serve().await;
446+
let dir = tempfile::tempdir().expect("parent dir");
447+
448+
// Something that is not a folder sits where the folder should be.
449+
let not_a_folder = dir.path().join("Downloads");
450+
std::fs::write(&not_a_folder, b"a file").expect("file");
451+
let run_in = run(addr, "/ok", &not_a_folder, &CancellationToken::new()).await;
452+
assert_eq!(
453+
run_in.result,
454+
Err(TransferError::Failed(InstallerFailure::Storage))
455+
);
456+
457+
// The system refuses the write: the folder is read-only for this user.
362458
#[cfg(unix)]
363459
{
364460
use std::os::unix::fs::PermissionsExt;
365-
let mode = std::fs::metadata(&saved)
366-
.expect("metadata")
367-
.permissions()
368-
.mode();
369-
assert_eq!(mode & 0o777, 0o644, "readable, not executable");
461+
let locked = dir.path().join("locked");
462+
std::fs::create_dir(&locked).expect("locked dir");
463+
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o555))
464+
.expect("lock dir");
465+
// A superuser ignores the mode, and then there is nothing to observe.
466+
if std::fs::write(locked.join("probe"), b"").is_err() {
467+
let run_in = run(addr, "/ok", &locked, &CancellationToken::new()).await;
468+
assert_eq!(
469+
run_in.result,
470+
Err(TransferError::Failed(InstallerFailure::PermissionDenied))
471+
);
472+
assert_eq!(file_names(&locked), Vec::<String>::new());
473+
}
474+
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755))
475+
.expect("unlock dir");
476+
}
477+
}
478+
479+
#[test]
480+
fn the_download_folder_falls_back_to_home_downloads_on_linux_only() {
481+
let configured = Some(PathBuf::from("/home/sam/Transfers"));
482+
let home = Some(PathBuf::from("/home/sam"));
483+
// (configured, home, is_linux, expected)
484+
let cases = [
485+
(configured.clone(), home.clone(), true, configured.clone()),
486+
(configured.clone(), None, false, configured.clone()),
487+
(
488+
None,
489+
home.clone(),
490+
true,
491+
Some(PathBuf::from("/home/sam/Downloads")),
492+
),
493+
(None, home.clone(), false, None),
494+
(None, None, true, None),
495+
];
496+
for (configured, home, is_linux, expected) in cases {
497+
assert_eq!(
498+
resolve_download_dir(configured.clone(), home.clone(), is_linux),
499+
expected,
500+
"{configured:?} {home:?} {is_linux}"
501+
);
370502
}
371503
}
372504

@@ -568,15 +700,102 @@ fn shutdown_cancels_and_removes_the_partial_file() {
568700
downloads.abort_for_shutdown();
569701
assert!(partial.exists());
570702

703+
let record = dir.path().join("app-data").join("partial-record.txt");
704+
downloads.recover(record.clone());
571705
let active = downloads.begin().expect("download");
572706
downloads.set_partial(&partial);
707+
assert!(record.exists());
573708
downloads.abort_for_shutdown();
574709
assert!(active.cancel.is_cancelled());
575710
assert!(!partial.exists());
711+
// Nothing is left for the next launch to remove.
712+
assert!(!record.exists());
576713
// The download task cleaning up afterwards finds nothing, and that is fine.
577714
downloads.abort_for_shutdown();
578715
}
579716

717+
#[test]
718+
fn the_next_launch_removes_exactly_the_partial_a_dead_run_recorded() {
719+
let dir = tempfile::tempdir().expect("download dir");
720+
let record = dir.path().join("app-data").join("partial-record.txt");
721+
let downloads_dir = dir.path().join("Downloads");
722+
std::fs::create_dir(&downloads_dir).expect("download dir");
723+
let partial = downloads_dir.join("Buzz_1.0.0_aarch64.dmg.aB3xYz.part");
724+
// Files the cleanup has no business touching, however similar they look.
725+
let bystanders = [
726+
"Buzz_1.0.0_aarch64.dmg",
727+
"Buzz_1.0.0_aarch64.dmg.zzzzzz.part",
728+
"film.mkv.part",
729+
];
730+
std::fs::write(&partial, b"half").expect("partial");
731+
for name in bystanders {
732+
std::fs::write(downloads_dir.join(name), b"mine").expect(name);
733+
}
734+
735+
// A download that ends normally leaves no record behind.
736+
let downloads = InstallerDownloads::default();
737+
downloads.recover(record.clone());
738+
let active = downloads.begin().expect("download");
739+
downloads.set_partial(&partial);
740+
assert_eq!(
741+
std::fs::read_to_string(&record).expect("record"),
742+
partial.to_str().expect("utf-8 path")
743+
);
744+
drop(active);
745+
assert!(!record.exists());
746+
747+
// A run that dies mid-download does: none of its cleanup runs.
748+
let active = downloads.begin().expect("download");
749+
downloads.set_partial(&partial);
750+
std::mem::forget(active);
751+
assert!(record.exists());
752+
753+
// The next launch removes that file, forgets it, and touches nothing else.
754+
InstallerDownloads::default().recover(record.clone());
755+
assert!(!record.exists());
756+
assert_eq!(file_names(&downloads_dir), bystanders);
757+
758+
// A record that names anything but a partial file of this module's shape
759+
// is dropped without removing what it names.
760+
#[cfg(unix)]
761+
std::os::unix::fs::symlink(
762+
downloads_dir.join("Buzz_1.0.0_aarch64.dmg"),
763+
downloads_dir.join("Buzz_1.0.0_aarch64.dmg.linked.part"),
764+
)
765+
.expect("symlink");
766+
let not_ours = [
767+
downloads_dir.join("Buzz_1.0.0_aarch64.dmg"),
768+
downloads_dir.join("film.mkv.part"),
769+
downloads_dir.join("Buzz_1.0.0_aarch64.dmg.linked.part"),
770+
PathBuf::from("Buzz_1.0.0_aarch64.dmg.zzzzzz.part"),
771+
downloads_dir.clone(),
772+
];
773+
for path in not_ours {
774+
// Asked of the path itself, so a removed symlink is noticed.
775+
let existed = path.symlink_metadata().is_ok();
776+
std::fs::write(&record, path.to_str().expect("utf-8 path")).expect("record");
777+
remove_recorded_partial(&record);
778+
assert!(!record.exists(), "{}", path.display());
779+
assert_eq!(
780+
path.symlink_metadata().is_ok(),
781+
existed,
782+
"{}",
783+
path.display()
784+
);
785+
for name in bystanders {
786+
assert!(
787+
downloads_dir.join(name).exists(),
788+
"{name} after {}",
789+
path.display()
790+
);
791+
}
792+
}
793+
// Neither is a record that is not text at all.
794+
std::fs::write(&record, [0xff, 0xfe, 0x00]).expect("record");
795+
remove_recorded_partial(&record);
796+
assert!(!record.exists());
797+
}
798+
580799
#[test]
581800
fn progress_is_reported_at_most_once_per_interval() {
582801
let start = Instant::now();

‎desktop/src-tauri/src/lib.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,7 @@ pub fn run() {
239239
.manage(channel_head_cache::ChannelHeadCacheStore::default())
240240
.setup(move |app| {
241241
let app_handle = app.handle().clone();
242+
recover_new_app_installer_downloads(&app_handle);
242243
#[cfg(target_os = "macos")]
243244
{
244245
tray_menu::init(&app_handle)?;
@@ -934,9 +935,8 @@ pub fn run() {
934935
..
935936
} if label == "main" => {
936937
// Keep the webview alive so Buzz can be reopened from its tray menu.
938+
// An installer download keeps running; its dialog is there on reopen.
937939
api.prevent_close();
938-
// A hidden window cannot show the installer download's dialog.
939-
app_handle.state::<InstallerDownloads>().cancel();
940940
if let Some(window) = app_handle.get_webview_window("main") {
941941
if let Err(error) = window.hide() {
942942
eprintln!("buzz-desktop: failed to hide main window: {error}");

‎desktop/src-tauri/src/shutdown.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,10 @@ pub(crate) fn install_signal_handler(
4747
.shutdown_started
4848
.store(true, Ordering::SeqCst);
4949
if !shutdown_done.swap(true, Ordering::SeqCst) {
50+
// This path ends in `exit`, so the download never cleans up itself.
51+
if let Some(downloads) = app.try_state::<crate::commands::InstallerDownloads>() {
52+
downloads.abort_for_shutdown();
53+
}
5054
app.state::<crate::terminal_runtime::TerminalSessions>()
5155
.shutdown_all();
5256
let _ = shutdown_managed_agents(&app);

‎desktop/src/app/NewAppDownloadButton.tsx‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,13 +55,23 @@ export function NewAppDownloadButton({
5555
<NewAppInstallerDialog
5656
onCancel={cancel}
5757
onDismiss={dismiss}
58+
onDownloadInBrowser={() => {
59+
// The URL the download was started with, which the resolver and
60+
// the backend both accepted. The browser downloads it its own way.
61+
if (state.status === "failed") {
62+
void openUrl(state.url);
63+
}
64+
dismiss();
65+
}}
5866
onOpenWebsite={() => {
5967
void openUrl(BUZZ_APP_WEBSITE_URL);
6068
dismiss();
6169
}}
6270
onRetry={() => {
63-
if (installerUrl) {
64-
start(installerUrl);
71+
// From the state, not the prop: after a remount the manifest is
72+
// fetched again and the prop is null until it arrives.
73+
if (state.status === "failed") {
74+
start(state.url);
6575
}
6676
}}
6777
onReveal={reveal}

0 commit comments

Comments
 (0)