Skip to content

Commit a3117a4

Browse files
wesbillmanCarl
andauthored
fix(desktop): register macOS badges for new and existing installs (#7783)
## Summary - Request macOS badge authorization alongside alerts and sounds. - Repair existing bundled installations at startup only when native status is `Authorized` and `badgeSetting` is `NotSupported` (the omitted/unregistered interaction). Leave user-disabled badges, denied notifications, new users, and provisional/ephemeral authorization untouched. - Reuse the native query/request path in one background startup operation. No frontend changes, read-state resets, persisted migration flags, timers, or in-process retries. ## Validation - Full `just ci` passed at implementation head `e6c4bc640`, before the test-seam extraction and additional regression coverage. - Native patch head `8ab8cf6d6`: normal pre-commit/pre-push hooks passed, including macOS Tauri clippy (default and mesh-llm), complete Tauri test suite (3,208 passed, 19 ignored), and repository file-size gate. - Regression coverage: all five native authorization statuses × all three badge states; request exactly once only for Authorized + NotSupported; settings/request failure propagation; startup wiring; complete authorization options. - Mutation verification: removing the startup task and removing the Badge option each fail the corresponding regression. - Isolated bundled native app on macOS 26.6.2: requesting Alert | Sound produced Authorized + badge NotSupported; requesting Alert | Sound | Badge then produced badge Enabled with no error. A direct AppKit Dock label of 7 was visibly rendered in the isolated app. - Independent review found no remaining code blocker at final head. ## CI repair (`f9a6ff2b0`) - The original browser smoke failure was a 500ms startup assertion racing loaded-runner rendering. Hosted failure snapshots contained all 14 expected rows; the unchanged test also reproduced the failure locally with 6× CPU throttling. - Reuse the existing one-shot mock channel response gate in the affected test. Wait for startup settlement, defer a second real revalidation, mutate display state while pending, release, then assert after query settlement. No production changes in this follow-up. - All 10 sidebar snapshot E2Es pass at clean head `f9a6ff2b0`; the repaired case also passed 3/3 CPU-throttled runs before commit. Temporarily removing display preservation or persisting the display mutation each caused the corresponding assertion to fail; both mutants were restored. - Normal pre-commit/pre-push gates passed, including desktop checks/typechecking, all 6,508 desktop tests, and the file-size gate. Independent artifact/source review found no blocker in the repair. - New hosted CI is running: https://github.com/block/buzz/actions/runs/35633308957. This is not a claim that hosted CI is green. Exact-range security review still requires organization-member authorization. ## Runtime limitation This fixes a verified missing authorization registration and provides an automatic existing-install path. It is **not yet proof that the reported blank Dock badge in the released Buzz app is fully resolved**: patched bundled Buzz startup and unread-to-Dock recovery have not been exercised. The isolated app is native API evidence, not a replacement for that release smoke test. Installed Buzz and its read state were not modified. Before release, verify an existing Alert/Sound-only install gains the badge setting on launch and renders an unread Dock badge; verify a user-disabled badge remains disabled. --------- Signed-off-by: Carl <32a2e2c9d428ee08902cab75d956da2c1d235a22d4766b0dd4138bf6e2e5db1d@buzz.block.builderlab.xyz> Co-authored-by: Carl <32a2e2c9d428ee08902cab75d956da2c1d235a22d4766b0dd4138bf6e2e5db1d@buzz.block.builderlab.xyz>
1 parent a61239f commit a3117a4

2 files changed

Lines changed: 163 additions & 16 deletions

File tree

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

Lines changed: 127 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ use objc2_foundation::{NSBundle, NSDictionary, NSError, NSObject, NSObjectProtoc
2525
use objc2_user_notifications::{
2626
UNAuthorizationOptions, UNAuthorizationStatus, UNMutableNotificationContent,
2727
UNNotificationDefaultActionIdentifier, UNNotificationPresentationOptions,
28-
UNNotificationRequest, UNNotificationResponse, UNNotificationSettings,
28+
UNNotificationRequest, UNNotificationResponse, UNNotificationSetting, UNNotificationSettings,
2929
UNUserNotificationCenter, UNUserNotificationCenterDelegate,
3030
};
3131
use tauri::{AppHandle, Emitter};
@@ -144,6 +144,18 @@ pub(crate) fn init(app: &AppHandle) -> tauri::Result<()> {
144144
// process-lifetime state, matching the application-lifetime delegate Apple
145145
// documents and avoiding mutable global or per-notification registrations.
146146
std::mem::forget(delegate);
147+
148+
// Older releases registered alerts/sounds but omitted Badge. Repair only
149+
// that unregistered interaction, never an explicit user opt-out. This runs
150+
// once per bundled process without blocking startup or prompting new users.
151+
tauri::async_runtime::spawn_blocking(|| {
152+
let result =
153+
register_missing_badge(notification_settings_sync, request_notification_access_sync);
154+
if let Err(error) = result {
155+
// Leave the native setting unchanged; a later launch can retry.
156+
eprintln!("buzz-desktop: failed to register macOS badge authorization: {error}");
157+
}
158+
});
147159
Ok(())
148160
}
149161

@@ -158,15 +170,15 @@ fn ensure_bundled_application() -> Result<(), String> {
158170
}
159171
}
160172

161-
fn notification_permission_state_sync() -> Result<NotificationPermissionState, String> {
173+
fn notification_settings_sync() -> Result<(UNAuthorizationStatus, UNNotificationSetting), String> {
162174
ensure_bundled_application()?;
163175

164176
let (sender, receiver) = mpsc::sync_channel(1);
165177
let handler = RcBlock::new(move |settings: NonNull<UNNotificationSettings>| {
166178
// SAFETY: Apple guarantees a live UNNotificationSettings object for
167179
// the duration of this completion handler.
168-
let status = unsafe { settings.as_ref() }.authorizationStatus();
169-
let _ = sender.send(permission_state(status));
180+
let settings = unsafe { settings.as_ref() };
181+
let _ = sender.send((settings.authorizationStatus(), settings.badgeSetting()));
170182
});
171183
UNUserNotificationCenter::currentNotificationCenter()
172184
.getNotificationSettingsWithCompletionHandler(&handler);
@@ -176,13 +188,35 @@ fn notification_permission_state_sync() -> Result<NotificationPermissionState, S
176188
.map_err(|_| "macOS notification settings request timed out".to_string())
177189
}
178190

191+
fn notification_permission_state_sync() -> Result<NotificationPermissionState, String> {
192+
notification_settings_sync().map(|(status, _)| permission_state(status))
193+
}
194+
195+
fn register_missing_badge(
196+
settings: impl FnOnce() -> Result<(UNAuthorizationStatus, UNNotificationSetting), String>,
197+
request: impl FnOnce() -> Result<NotificationPermissionState, String>,
198+
) -> Result<(), String> {
199+
let (permission, badge) = settings()?;
200+
if permission == UNAuthorizationStatus::Authorized
201+
&& badge == UNNotificationSetting::NotSupported
202+
{
203+
request()?;
204+
}
205+
Ok(())
206+
}
207+
179208
#[tauri::command]
180209
pub(crate) async fn notification_permission_state() -> Result<NotificationPermissionState, String> {
181210
tokio::task::spawn_blocking(notification_permission_state_sync)
182211
.await
183212
.map_err(|error| format!("macOS notification settings task failed: {error}"))?
184213
}
185214

215+
fn notification_authorization_options() -> UNAuthorizationOptions {
216+
// Register every interaction Buzz uses, including its Dock badge.
217+
UNAuthorizationOptions::Alert | UNAuthorizationOptions::Sound | UNAuthorizationOptions::Badge
218+
}
219+
186220
fn request_notification_access_sync() -> Result<NotificationPermissionState, String> {
187221
ensure_bundled_application()?;
188222

@@ -196,7 +230,7 @@ fn request_notification_access_sync() -> Result<NotificationPermissionState, Str
196230
});
197231
UNUserNotificationCenter::currentNotificationCenter()
198232
.requestAuthorizationWithOptions_completionHandler(
199-
UNAuthorizationOptions::Alert | UNAuthorizationOptions::Sound,
233+
notification_authorization_options(),
200234
&handler,
201235
);
202236

@@ -335,13 +369,97 @@ fn parse_target(serialized: &str) -> Option<serde_json::Value> {
335369
#[cfg(test)]
336370
mod tests {
337371
use super::{
338-
is_application_bundle_layout, is_bundled_application, parse_target, permission_state,
339-
queue_activation, take_pending_activations, NotificationPermissionState,
340-
MAX_PENDING_ACTIVATIONS,
372+
is_application_bundle_layout, is_bundled_application, notification_authorization_options,
373+
parse_target, permission_state, queue_activation, register_missing_badge,
374+
take_pending_activations, NotificationPermissionState, MAX_PENDING_ACTIVATIONS,
375+
};
376+
use objc2_user_notifications::{
377+
UNAuthorizationOptions, UNAuthorizationStatus, UNNotificationSetting,
341378
};
342-
use objc2_user_notifications::UNAuthorizationStatus;
343379
use std::path::Path;
344380

381+
#[test]
382+
fn registers_only_unrequested_badges_for_already_authorized_installs() {
383+
for permission in [
384+
UNAuthorizationStatus::NotDetermined,
385+
UNAuthorizationStatus::Denied,
386+
UNAuthorizationStatus::Authorized,
387+
UNAuthorizationStatus::Provisional,
388+
UNAuthorizationStatus::Ephemeral,
389+
] {
390+
for badge in [
391+
UNNotificationSetting::NotSupported,
392+
UNNotificationSetting::Disabled,
393+
UNNotificationSetting::Enabled,
394+
] {
395+
let mut requests = 0;
396+
register_missing_badge(
397+
|| Ok((permission, badge)),
398+
|| {
399+
requests += 1;
400+
Ok(NotificationPermissionState::Granted)
401+
},
402+
)
403+
.expect("registration succeeds");
404+
assert_eq!(
405+
requests,
406+
usize::from(
407+
permission == UNAuthorizationStatus::Authorized
408+
&& badge == UNNotificationSetting::NotSupported
409+
),
410+
"permission={permission:?}, badge={badge:?}",
411+
);
412+
}
413+
}
414+
}
415+
416+
#[test]
417+
fn badge_registration_propagates_settings_and_request_failures() {
418+
let error = register_missing_badge(
419+
|| Err("settings unavailable".into()),
420+
|| panic!("must not request when settings failed"),
421+
)
422+
.expect_err("settings failure");
423+
assert_eq!(error, "settings unavailable");
424+
let error = register_missing_badge(
425+
|| {
426+
Ok((
427+
UNAuthorizationStatus::Authorized,
428+
UNNotificationSetting::NotSupported,
429+
))
430+
},
431+
|| Err("request failed".into()),
432+
)
433+
.expect_err("request failure");
434+
assert_eq!(error, "request failed");
435+
}
436+
437+
#[test]
438+
fn bundled_startup_wires_native_badge_registration() {
439+
// Complement behavioral tests with a wiring guard: removing the startup
440+
// task must not leave the isolated operation tests green.
441+
let source = include_str!("macos_notifications.rs");
442+
let init = source
443+
.split("pub(crate) fn init(")
444+
.nth(1)
445+
.expect("init")
446+
.split("fn ensure_bundled_application")
447+
.next()
448+
.expect("init body");
449+
assert!(init.contains("tauri::async_runtime::spawn_blocking"));
450+
assert!(init.contains("register_missing_badge("));
451+
assert!(init.contains("notification_settings_sync,"));
452+
assert!(init.contains("request_notification_access_sync"));
453+
}
454+
455+
#[test]
456+
fn requests_all_interactions_used_by_buzz() {
457+
let options = notification_authorization_options();
458+
assert!(options.contains(UNAuthorizationOptions::Alert));
459+
assert!(options.contains(UNAuthorizationOptions::Sound));
460+
assert!(options.contains(UNAuthorizationOptions::Badge));
461+
}
462+
345463
#[test]
346464
fn activation_queue_is_bounded_and_drained() {
347465
let _ = take_pending_activations();

‎desktop/tests/e2e/sidebar-snapshot.spec.ts‎

Lines changed: 36 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -294,24 +294,53 @@ test("matching not-modified preserves display mutations without persisting them"
294294
}) => {
295295
const optimisticName = "optimistic-local-channel";
296296
await seedSnapshot(page, { hash: MATCHING_HASH });
297-
await installMockBridge(page, {
298-
channelsReadDelayMs: READ_DELAY_MS,
299-
honorChannelsKnownHash: true,
300-
});
297+
await installMockBridge(page, { honorChannelsKnownHash: true });
301298
await page.goto("/");
302299

303300
await expect(page.locator('[data-channel-id^="snapshot-"]')).toHaveCount(
304301
FULL_SNAPSHOT.length,
305-
{ timeout: 500 },
306302
);
303+
await expect
304+
.poll(() =>
305+
page.evaluate(() =>
306+
window.__BUZZ_E2E_QUERY_CLIENT__?.getQueryState(["channels"]),
307+
),
308+
)
309+
.toMatchObject({ fetchStatus: "idle", status: "success" });
310+
311+
// Exercise the mutation during a real revalidation, not a race between boot
312+
// rendering and a fixed response delay. The cold-boot test covers first paint.
313+
await page.evaluate(() => {
314+
window.__BUZZ_E2E_DEFER_NEXT_CHANNELS_READ__?.();
315+
void window.__BUZZ_E2E_QUERY_CLIENT__?.invalidateQueries({
316+
queryKey: ["channels"],
317+
exact: true,
318+
});
319+
});
320+
await expect
321+
.poll(() => page.evaluate(() => window.__BUZZ_E2E_CHANNELS_READ_PENDING__))
322+
.toBe(1);
307323
await mutateDisplayedChannels(page, optimisticName);
308324
await expect(
309325
page.locator('[data-channel-id="optimistic-channel"]'),
310326
).toBeVisible();
311327

328+
expect(
329+
await page.evaluate(() => window.__BUZZ_E2E_RELEASE_CHANNELS_READ__?.()),
330+
).toBe(1);
331+
// Invocation logging only proves the request started. Wait for the query to
332+
// consume its response before checking either display state or persistence.
312333
await expect
313-
.poll(() => getChannelsPayloads(page))
314-
.toEqual([{ knownHash: MATCHING_HASH }]);
334+
.poll(() =>
335+
page.evaluate(() =>
336+
window.__BUZZ_E2E_QUERY_CLIENT__?.getQueryState(["channels"]),
337+
),
338+
)
339+
.toMatchObject({ fetchStatus: "idle", status: "success" });
340+
expect(await getChannelsPayloads(page)).toEqual([
341+
{ knownHash: MATCHING_HASH },
342+
{ knownHash: MATCHING_HASH },
343+
]);
315344
await expect
316345
.poll(() => readPersistedSnapshot(page))
317346
.toEqual({

0 commit comments

Comments
 (0)