Skip to content

Commit cf97237

Browse files
wpfleger96npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
andauthored
feat(desktop): add Sign Out to Settings to reset and relaunch (#1842)
Signed-off-by: Will Pfleger <[email protected]> Co-authored-by: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@sprout-oss.stage.blox.sqprod.co>
1 parent 2d7ed32 commit cf97237

19 files changed

Lines changed: 1445 additions & 41 deletions

‎desktop/playwright.config.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ export default defineConfig({
9090
"**/project-pr-review.spec.ts",
9191
"**/persona-model-combobox-screenshots.spec.ts",
9292
"**/drafts-screenshots.spec.ts",
93+
"**/signout-screenshots.spec.ts",
9394
"**/buzz-theme-screenshots.spec.ts",
9495
"**/channel-sort.spec.ts",
9596
"**/identity-lost.spec.ts",

‎desktop/scripts/check-file-sizes.mjs‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,8 @@ const overrides = new Map([
207207
// mcp-readonly-view rebase: PR2 MCP config surface FE-type fields force +1 over the grandfathered ceiling.
208208
// Git Bash prerequisite payload adds four fields to the shared Tauri API
209209
// contract. This is the canonical type location; split remains queued.
210-
["src/shared/api/types.ts", 1038],
210+
// signout-wipe: resetFailed field added to Identity type (+6 lines).
211+
["src/shared/api/types.ts", 1044],
211212
// readiness-gate: PersonaDialog.tsx threads computeLocalModeGate +
212213
// requiredCredentialEnvKeys + RequiredFieldLabel so the "New agent" dialog
213214
// shows required markers and credential amber rows (parity with
@@ -307,7 +308,7 @@ const overrides = new Map([
307308
// am review fix: also clear stale V1 model field on provider rewrite +
308309
// new model-clear test. Load-bearing chimera fix.
309310
// keyring-dev-isolation: run_boot_migrations wires agent-key migration.
310-
["src-tauri/src/migration.rs", 1415],
311+
["src-tauri/src/migration.rs", 1436],
311312
// onMarkRead + isUnread prop threading (mirrors the onMarkUnread prop
312313
// already here) for the single-toggle mark-read/unread menu item — a small
313314
// overage from load-bearing per-message plumbing, not generic debt growth.
@@ -331,7 +332,22 @@ const overrides = new Map([
331332
// security fix for the lost-update race that stranded agent keys.
332333
// identity-import-keyring: KeyringLockedScreen, RecoveryScreen,
333334
// load_readonly + load_all_readonly + store_all for safe cross-service reads.
334-
["src-tauri/src/secret_store.rs", 1140],
335+
// sign-out wipe: delete_all() method removes the entire keychain blob under
336+
// the interprocess advisory lock; +8 lines. Load-bearing; queued to split.
337+
// signout-wipe phase 2: delete_all_with_legacy_cleanup replaces delete_all;
338+
// reads blob keys + deletes per-key legacy entries to prevent resurrection.
339+
// + regression test for per-key resurrection via real OS keychain.
340+
// Net growth ~36+32 lines over prior cap. Load-bearing correctness fix.
341+
// signout-wipe pass-2 (F2): delete_all_with_legacy_cleanup DPK deletes now
342+
// observable (propagate real errors); verify_fully_wiped checks all three
343+
// keychain shapes (main blob, DPK blob, per-key "identity"). +73 lines.
344+
["src-tauri/src/secret_store.rs", 1307],
345+
// sign-out wipe: Sign Out section (AlertDialog + controlled state) added
346+
// at the bottom of the Profile settings page. Load-bearing UX feature;
347+
// queued to split when ProfileSettingsCard is broken into sub-components.
348+
// +20 lines: scroll-position save/restore across avatar editor open/close
349+
// to prevent layout shift from the Sign Out section causing a viewport jump.
350+
["src/features/settings/ui/ProfileSettingsCard.tsx", 1033],
335351
// keyring-dev-isolation: keyring_service() fn (7 lines) replaces the const
336352
// to return "buzz-desktop-dev" in debug builds. Load-bearing isolation fix.
337353
["src-tauri/src/app_state.rs", 1042],

‎desktop/scripts/check-px-text.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ const rules = [
2323
// glyphs are fixed display sizes sized to their avatar box (not readable
2424
// message text), so they are exempted from the readable-text px rule.
2525
const overrides = new Set([
26-
"src/features/settings/ui/ProfileSettingsCard.tsx:672",
26+
"src/features/settings/ui/ProfileSettingsCard.tsx:712",
2727
"src/features/onboarding/ui/AvatarStep.tsx:95",
2828
"src/features/agents/ui/AgentCreationPreview.tsx:666",
2929
"src/features/agents/ui/AgentCreationPreview.tsx:747",

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,14 @@ pub struct AppState {
7777
/// `keys` so readers (signing, get_identity, etc.) are not blocked during
7878
/// keyring I/O.
7979
pub identity_mutation: Mutex<()>,
80+
/// Set when the boot-time Phase 2 reset attempted a wipe but verification
81+
/// failed. The sentinel is preserved so the next relaunch retries. All
82+
/// identity-dependent setup is skipped; the frontend shows a reset-failed
83+
/// recovery screen via `get_identity`.
84+
///
85+
/// Ordering: written once in `setup()` with `Ordering::Release`; read in
86+
/// `get_identity` with `Ordering::Acquire`.
87+
pub reset_failed: AtomicBool,
8088
/// Cached ACP session config from running agents, keyed by agent pubkey.
8189
/// Populated when the harness emits `session_config_captured` observer events.
8290
pub session_config_cache: Mutex<HashMap<String, SessionConfigCache>>,
@@ -169,6 +177,7 @@ pub fn build_app_state() -> AppState {
169177
)),
170178
keyring_locked: AtomicBool::new(false),
171179
identity_lost: AtomicBool::new(false),
180+
reset_failed: AtomicBool::new(false),
172181
#[cfg(feature = "mesh-llm")]
173182
mesh_llm_runtime: AsyncMutex::new(None),
174183
#[cfg(feature = "mesh-llm")]

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

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,12 +36,16 @@ pub fn get_identity(state: State<'_, AppState>) -> Result<IdentityInfo, String>
3636
let locked = state
3737
.keyring_locked
3838
.load(std::sync::atomic::Ordering::Acquire);
39+
let reset_failed = state
40+
.reset_failed
41+
.load(std::sync::atomic::Ordering::Acquire);
3942

4043
Ok(IdentityInfo {
4144
pubkey: pubkey_hex,
4245
display_name,
4346
lost,
4447
locked,
48+
reset_failed,
4549
})
4650
}
4751

@@ -220,6 +224,7 @@ pub async fn import_identity(
220224
display_name,
221225
lost: false,
222226
locked: false,
227+
reset_failed: false,
223228
})
224229
})
225230
.await
@@ -287,12 +292,53 @@ pub async fn persist_current_identity(
287292
display_name,
288293
lost: false,
289294
locked: false,
295+
reset_failed: false,
290296
})
291297
})
292298
.await
293299
.map_err(|e| format!("spawn_blocking failed: {e}"))?
294300
}
295301

302+
/// Write a reset-intent sentinel and request a graceful restart into Phase 2
303+
/// (boot-time wipe).
304+
///
305+
/// The actual data destruction is deferred to the next boot: `setup()` in
306+
/// `lib.rs` checks for the sentinel and performs the wipe before any migration
307+
/// or identity resolution. This two-phase design means a crash before the
308+
/// restart is safe — the sentinel persists and the wipe completes on the next
309+
/// open.
310+
///
311+
/// Not available in shared-identity mode (`BUZZ_SHARE_IDENTITY=1`): the key
312+
/// comes from an env var, not the keychain, so wiping would have no effect and
313+
/// would be confusing.
314+
#[tauri::command]
315+
pub async fn sign_out(app: tauri::AppHandle) -> Result<(), String> {
316+
if is_shared_identity() {
317+
return Err(
318+
"Sign out isn't available while BUZZ_SHARE_IDENTITY provides your identity. Unset BUZZ_SHARE_IDENTITY and BUZZ_PRIVATE_KEY, then relaunch to sign out."
319+
.to_string(),
320+
);
321+
}
322+
323+
// Stop all managed agents before restart so they don't race the wipe.
324+
if let Err(e) = crate::shutdown::shutdown_managed_agents(&app) {
325+
eprintln!("buzz-desktop sign-out: agent shutdown: {e}");
326+
}
327+
328+
// Write the reset sentinel — destruction happens on next boot.
329+
let data_dir = app
330+
.path()
331+
.app_data_dir()
332+
.map_err(|e| format!("app data dir: {e}"))?;
333+
crate::reset::write_sentinel(&data_dir)?;
334+
335+
// Tauri restarts only after normal shutdown, avoiding a single-instance
336+
// race. If restarting does not complete, the sentinel makes a manual open
337+
// finish the reset.
338+
app.request_restart();
339+
Ok(())
340+
}
341+
296342
fn nostr_bind_tag(name: &str, value: &str) -> Result<Tag, String> {
297343
Tag::parse(vec![name, value]).map_err(|error| format!("{name} tag failed: {error}"))
298344
}

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

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ pub mod nostr_convert;
1818
mod prevent_sleep;
1919
mod ptt_shortcut;
2020
mod relay;
21+
mod reset;
2122
mod secret_store;
2223
mod shutdown;
2324
mod templates;
@@ -415,8 +416,41 @@ pub fn run() {
415416
.setup(move |app| {
416417
let app_handle = app.handle().clone();
417418

419+
// ── Phase 2: boot-time sentinel wipe ──────────────────────────────
420+
// Must run before migrations and identity resolution so the wipe
421+
// completes atomically on crash recovery.
422+
//
423+
// init_nest_dir is called early here (normally it runs inside
424+
// run_boot_migrations) so reset::run_boot_reset can call nest_dir().
425+
let reset_outcome = if let Ok(data_dir) = app_handle.path().app_data_dir() {
426+
let is_dev_for_reset = data_dir
427+
.file_name()
428+
.and_then(|n| n.to_str())
429+
.map(crate::migration::is_dev_data_dir_name)
430+
.unwrap_or(false);
431+
crate::managed_agents::init_nest_dir(is_dev_for_reset);
432+
crate::reset::run_boot_reset(&data_dir)
433+
} else {
434+
crate::reset::ResetOutcome::default()
435+
};
436+
437+
if reset_outcome.failed {
438+
// Surface reset-failed state — skip identity resolution and
439+
// all side-effecting setup. The webview still loads so the
440+
// frontend can show the recovery screen via get_identity.
441+
let state = app_handle.state::<AppState>();
442+
state
443+
.reset_failed
444+
.store(true, std::sync::atomic::Ordering::Release);
445+
return Ok(());
446+
}
447+
418448
// Run all pre-identity data migrations before state loads from disk.
419-
migration::run_boot_migrations(&app_handle);
449+
if reset_outcome.completed {
450+
migration::run_boot_migrations_after_reset(&app_handle);
451+
} else {
452+
migration::run_boot_migrations(&app_handle);
453+
}
420454

421455
// Resolve persisted identity key (env var → file → generate+save).
422456
// This is fatal — the app should not start with an ephemeral identity
@@ -517,18 +551,22 @@ pub fn run() {
517551
// destination is present. Non-fatal.
518552
// On a real migration, emit a one-time hint so the user can delete
519553
// the now-inert ~/.sprout; the frontend dedupes the toast.
520-
if migration::migrate_legacy_nest() {
554+
// Suppressed when a reset completed this boot: the nest was wiped and
555+
// a fresh ~/.sprout-less state is exactly what we want.
556+
if !reset_outcome.completed && migration::migrate_legacy_nest() {
521557
let _ = app_handle.emit("legacy-nest-migrated", ());
522558
}
523559

524560
// One-time migration for dev builds: copy accumulated knowledge
525561
// from the shared ~/.buzz nest into the new dedicated ~/.buzz-dev
526562
// nest so no work is lost when the nest is first namespaced.
527563
// Runs only when nest_dir() resolved to ~/.buzz-dev (dev instance).
564+
// Suppressed after a reset so re-importing ~/.buzz into ~/.buzz-dev
565+
// doesn't re-populate what was just wiped.
528566
let is_dev_nest = managed_agents::nest_dir()
529567
.and_then(|p| p.file_name().map(|n| n.to_os_string()))
530568
.is_some_and(|n| n == ".buzz-dev");
531-
if is_dev_nest {
569+
if !reset_outcome.completed && is_dev_nest {
532570
migration::migrate_dev_nest();
533571
}
534572

@@ -691,6 +729,7 @@ pub fn run() {
691729
discover_managed_agent_prereqs,
692730
sign_event,
693731
sign_nostr_identity_binding,
732+
sign_out,
694733
decrypt_observer_event,
695734
build_observer_control_event,
696735
create_auth_event,

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

Lines changed: 42 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ const SHARED_AGENT_DIRS: &[&str] = &["agents/teams"];
4444
/// `xyz.block.buzz.app.developer`. This is the authoritative dev/prod
4545
/// discriminator shared by `run_boot_migrations`, `sync_shared_agent_data`,
4646
/// and `reconcile_target_dir`.
47-
fn is_dev_data_dir_name(name: &str) -> bool {
47+
pub(crate) fn is_dev_data_dir_name(name: &str) -> bool {
4848
name == CANONICAL_DEV_IDENTIFIER
4949
|| name
5050
.strip_prefix(CANONICAL_DEV_IDENTIFIER)
@@ -55,7 +55,7 @@ fn canonical_dev_data_dir(current: &Path) -> Option<PathBuf> {
5555
current.parent().map(|p| p.join(CANONICAL_DEV_IDENTIFIER))
5656
}
5757

58-
fn legacy_app_data_dir(current: &Path) -> Option<PathBuf> {
58+
pub(crate) fn legacy_app_data_dir(current: &Path) -> Option<PathBuf> {
5959
let name = current.file_name()?.to_str()?;
6060
let legacy_name = if name.starts_with(CANONICAL_DEV_IDENTIFIER) {
6161
name.replacen(CANONICAL_DEV_IDENTIFIER, LEGACY_CANONICAL_DEV_IDENTIFIER, 1)
@@ -119,6 +119,15 @@ fn copy_dir_all(src: &Path, dst: &Path) -> std::io::Result<()> {
119119
/// readers — reader-first loses a launch (stale harness/`mcp_command` until
120120
/// the next boot).
121121
pub fn run_boot_migrations(app: &tauri::AppHandle) {
122+
run_boot_migrations_inner(app, false);
123+
}
124+
125+
/// Entry point when a completed reset must suppress dev-nest re-import.
126+
pub fn run_boot_migrations_after_reset(app: &tauri::AppHandle) {
127+
run_boot_migrations_inner(app, true);
128+
}
129+
130+
fn run_boot_migrations_inner(app: &tauri::AppHandle, reset_completed: bool) {
122131
// Initialize the process-lifetime nest directory before any filesystem
123132
// operation that calls nest_dir(). The discriminator matches the existing
124133
// pattern used by reconcile_target_dir: dev instances have an app-data-dir
@@ -139,8 +148,10 @@ pub fn run_boot_migrations(app: &tauri::AppHandle) {
139148
// ensures the dev nest boots with the correct workspace on its first launch,
140149
// matching what the prod nest had configured. Skip-if-dest-exists so it is
141150
// idempotent and never clobbers a value the dev nest already set explicitly.
142-
if is_dev {
143-
migrate_dev_repos_dir();
151+
// Uses the composed helper so the gate + migration run through the same
152+
// code path that the behavioral test exercises.
153+
if let (Some(home), Some(dev_nest)) = (dirs::home_dir(), crate::managed_agents::nest_dir()) {
154+
maybe_migrate_dev_repos_dir(is_dev, reset_completed, &home, &dev_nest);
144155
}
145156

146157
migrate_legacy_app_data_dir(app);
@@ -318,31 +329,29 @@ fn migrate_legacy_nest_at(legacy: &Path, current: &Path) -> bool {
318329
/// also copies into `~/.buzz-dev` and could otherwise set the sentinel early.
319330
const DEV_NEST_MIGRATED_SENTINEL: &str = ".dev-nest-migrated";
320331

321-
/// Copy the `.repos-dir` dotfile from `~/.buzz` → `~/.buzz-dev`, non-destructively.
322-
///
323-
/// Must be called on dev builds BEFORE `resolve_repos_at_boot()` reads the
324-
/// dotfile, so the dev nest boots with the correct workspace configuration on
325-
/// its first launch. Skip-if-dest-exists so it is idempotent and never
326-
/// overwrites a value set directly by the dev nest.
327-
fn migrate_dev_repos_dir() {
328-
let Some(home) = dirs::home_dir() else {
329-
return;
330-
};
332+
/// Returns true when `migrate_dev_repos_dir` should run: dev build AND no
333+
/// completed reset this boot (a completed reset means the dev nest was just
334+
/// wiped — re-importing from prod would undo the sign-out).
335+
pub(crate) fn should_migrate_dev_repos_dir(is_dev: bool, reset_completed: bool) -> bool {
336+
is_dev && !reset_completed
337+
}
338+
339+
/// Injectable core: copy `.repos-dir` from `<home>/.buzz/` into `dev_nest`,
340+
/// non-destructively. Extracted so tests can inject temp paths without
341+
/// touching `dirs::home_dir()` or the global `nest_dir()` OnceLock.
342+
pub(crate) fn migrate_dev_repos_dir_at(home: &Path, dev_nest: &Path) {
331343
let src = home.join(".buzz").join(".repos-dir");
332344
if !src.exists() {
333345
return;
334346
}
335-
let Some(dev_nest) = crate::managed_agents::nest_dir() else {
336-
return;
337-
};
338347
let dst = dev_nest.join(".repos-dir");
339348
// Skip if the dev nest already has its own .repos-dir.
340349
if dst.exists() {
341350
return;
342351
}
343352
// Ensure the dev nest directory itself exists — this migration runs before
344353
// ensure_nest() in the boot sequence, so the directory may not yet exist.
345-
if let Err(e) = std::fs::create_dir_all(&dev_nest) {
354+
if let Err(e) = std::fs::create_dir_all(dev_nest) {
346355
eprintln!(
347356
"buzz-desktop: dev-nest-migration: failed to create dev nest {}: {e}",
348357
dev_nest.display()
@@ -358,6 +367,21 @@ fn migrate_dev_repos_dir() {
358367
}
359368
}
360369

370+
/// Composed gate + migration: applies `should_migrate_dev_repos_dir` and, if
371+
/// the gate passes, runs the injectable migration core. This is the seam that
372+
/// `run_boot_migrations_inner` calls with real paths — a future mis-wired flag
373+
/// or inverted gate breaks tests at this level, not just the predicate.
374+
pub(crate) fn maybe_migrate_dev_repos_dir(
375+
is_dev: bool,
376+
reset_completed: bool,
377+
home: &Path,
378+
dev_nest: &Path,
379+
) {
380+
if should_migrate_dev_repos_dir(is_dev, reset_completed) {
381+
migrate_dev_repos_dir_at(home, dev_nest);
382+
}
383+
}
384+
361385
/// One-time migration of dev-build nest contents from `~/.buzz` → `~/.buzz-dev`.
362386
///
363387
/// When a dev build first boots after this change ships, it switches from the

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,11 @@ pub struct IdentityInfo {
1717
/// shows a "unlock the keyring and relaunch" screen. Mutually exclusive
1818
/// with `lost`.
1919
pub locked: bool,
20+
/// True when the boot-time Phase 2 reset attempted a wipe but verification
21+
/// failed. Identity resolution was skipped; the frontend shows a
22+
/// reset-failed recovery screen. The sentinel is preserved so the next
23+
/// relaunch retries the wipe automatically.
24+
pub reset_failed: bool,
2025
}
2126

2227
#[derive(Serialize, Deserialize)]

0 commit comments

Comments
 (0)