Make the logo panic gesture a three-way setting: confirm, instant, or off

The bitchat/ logo triple-tap performs a panic wipe. Since #1588 it always
raises a confirmation dialog, which closed the accidental-wipe hole but
removed the instant duress path for people who want it. Issue #152's
remaining ask was a preference for the gesture only. This adds one:

  confirm  - the shipped default; a triple-tap asks first (unchanged)
  instant  - the third tap wipes with no dialog (the seizure path)
  off      - the gesture does nothing; only the settings button wipes

Design follows the maintainer review of the competing PR #1575:

- The decision lives in AppChromeModel.requestPanicWipe(), the one choke
  point ContentHeaderView already calls. The gesture site is untouched
  and there is still exactly one gesture dialog, hosted on ContentView.
- Default is confirm, so an existing install keeps #1588's behaviour on
  update. An unreadable stored value also reads as confirm.
- Off is not silent: a triple-tap while disabled shows a "logo wipe is
  off - nothing was wiped" alert, and switching the gesture off asks
  first in settings. Silence would read as "it worked".
- A completed wipe sets the mode to instant (endorsed twice on #1575;
  that PR later dropped it). Because the install default is confirm,
  resetForPanicWipe() writes instant rather than clearing the key.
- The reset runs only after the panic transaction commits. The other
  preference resets in that block fail safe; this one fails armed, and a
  wipe that leaves data on disk must not also leave a deliberately
  disabled gesture one accidental tap from destroying it.

The preference store is injected into AppChromeModel so every branch is
tested through the real read path with an isolated suite; the one test
that must write UserDefaults.standard (ChatViewModel's store is fixed)
restores it. Copy is mode-aware: panic_note, the privacy-pane row, and
the danger-zone captions can no longer promise behaviour the gesture
does not have. Thirteen new catalog keys and one retranslation cover
all 30 locales. Also closes three unrelated gaps: the two panic modals
now count as root presentations (a Bluetooth alert could stack on a
pending wipe dialog), the settings-pane danger zone is finally rendered
by a smoke test (the pane picker defaults to Info), and README and the
in-source panic_note default no longer claim an "instant" wipe.

Verified: macOS Debug build; swift test (2029 tests, 220 suites);
iOS simulator suite on iPhone 17 (2262 tests); SwiftLint --strict via
the CI image (0 violations); Periphery --strict (no unused code);
catalog coverage 30 locales x 533 keys.

Refs #152. Relates to #1588 and #1575.
This commit is contained in:
Jozef Koval 2026-09-13 14:04:53 +02:00
parent 9b84b36122
commit d280684732
14 changed files with 2941 additions and 64 deletions

View File

@ -124,7 +124,7 @@ No cryptographic system can protect content after a recipient reads, copies, scr
## Your Controls
- **Panic wipe:** Triple-tap the logo to synchronously cancel in-flight media work and clear local keys, sessions, preferences, groups, queues, carried mail, public archives, board data, and media managed by the app.
- **Panic wipe:** Triple-tap the logo to synchronously cancel in-flight media work and clear local keys, sessions, preferences, groups, queues, carried mail, public archives, board data, and media managed by the app. The gesture asks to confirm by default; settings can make it wipe instantly or disable it. The panic button in settings always confirms and works in every mode. A completed wipe sets the gesture back to instant.
- **Notification previews:** Hidden by default, so lock-screen alerts do not show message text, sender names, or geohashes. Full previews can be turned on in settings.
- **Clearing a conversation:** Clearing the mesh timeline also deletes the recent public gossip this device had stored on disk.
- **Feature controls:** Location channels, mesh bridge, internet gateway, and related internet behaviors can be disabled in the app. Some already-published relay data cannot be recalled.

View File

@ -30,7 +30,7 @@ This project is released into the public domain. See the [LICENSE](LICENSE) file
- **Private Message End-to-End Encryption**: [Noise Protocol](https://noiseprotocol.org) for mesh, BitChat private envelopes for Nostr fallback
- **IRC-Style Commands**: Familiar `/slap`, `/msg`, `/who` style interface
- **Universal App**: Native support for iOS and macOS
- **Emergency Wipe**: Triple-tap to instantly clear all data
- **Emergency Wipe**: Triple-tap the logo to clear all data — asks to confirm by default; can be set to wipe instantly, or off, in settings
- **Performance Optimizations**: LZ4 message compression, adaptive battery modes, and optimized networking
## [Technical Architecture](https://deepwiki.com/permissionlesstech/bitchat)

View File

@ -21,8 +21,16 @@ final class AppChromeModel: ObservableObject {
/// connectivity banner. Mirrored from `ChatViewModel.torBlocked`.
@Published private(set) var torBlocked = false
@Published var showScreenshotPrivacyWarning = false
/// Triple-tapping the logo asks first; the dialog lives on the header.
/// Raised by the logo triple-tap when `PanicGestureSettings` says to ask
/// first. The dialog is hosted on ContentView so it survives whatever
/// happens to the header chrome. The settings-pane panic button is a
/// separate path: it keeps its own state and dialog inside its sheet and
/// calls `panicClearAllData()` directly, never through here.
@Published var showPanicConfirmation = false
/// The logo was triple-tapped while the gesture is switched off. Someone
/// who just tried to wipe under duress must be told nothing happened —
/// silence reads as "it worked", which is the dangerous failure here.
@Published var showPanicGestureDisabledAlert = false
/// Mirrors `ChatViewModel.panicRecoveryBlocked` for the chrome: a wipe
/// that did not commit must be visible, not just logged — the person who
/// triggered it needs to know data may remain on the device.
@ -30,6 +38,10 @@ final class AppChromeModel: ObservableObject {
private let chatViewModel: ChatViewModel
private let onPanicWipe: () -> Void
/// Where the logo-gesture preference is read from. Injectable so tests can
/// drive every branch of `requestPanicWipe()` through the real path with
/// an isolated suite, instead of writing to the shared defaults.
private let panicGestureDefaults: UserDefaults
private var cancellables = Set<AnyCancellable>()
/// The composer owns capture state above ChatViewModel. ContentView
/// installs this hook so both panic entry points synchronously stop it.
@ -41,10 +53,12 @@ final class AppChromeModel: ObservableObject {
init(
chatViewModel: ChatViewModel,
privateInboxModel: PrivateInboxModel,
onPanicWipe: @escaping () -> Void = {}
onPanicWipe: @escaping () -> Void = {},
panicGestureDefaults: UserDefaults = .standard
) {
self.chatViewModel = chatViewModel
self.onPanicWipe = onPanicWipe
self.panicGestureDefaults = panicGestureDefaults
self.nickname = chatViewModel.nickname
bind(privateInboxModel: privateInboxModel)
@ -120,11 +134,22 @@ final class AppChromeModel: ObservableObject {
prepareForPanic = preparation
}
/// Entry point for the header triple-tap: confirm before destroying.
/// The Settings-pane button has always confirmed; the gesture now goes
/// through the same dialog so a mis-tap can't wipe the device.
/// Entry point for the header triple-tap. Confirm-first by default: the
/// Settings-pane button has always confirmed, and the gesture now asks
/// the same question (same strings; its own dialog, on ContentView) so a
/// mis-tap can't wipe the device. `PanicGestureSettings` can trade that
/// safety for speed (`.instant`) or drop the gesture entirely (`.off`) —
/// the decision stays here, at the one choke point, rather than at the
/// gesture site.
func requestPanicWipe() {
showPanicConfirmation = true
switch PanicGestureSettings.mode(in: panicGestureDefaults) {
case .instant:
panicClearAllData()
case .confirm:
showPanicConfirmation = true
case .off:
showPanicGestureDisabledAlert = true
}
}
func panicClearAllData() {

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,77 @@
//
// PanicGestureSettings.swift
// bitchat
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Foundation
/// What a triple-tap on the `bitchat/` logo does.
///
/// The gesture sits on the same 18pt text whose single tap opens App Info, so
/// it is easy to fire by accident — and it destroys identity, keys, and every
/// message. It is also the fastest way to wipe a phone that is about to be
/// taken from you. Those two facts pull in opposite directions, and which one
/// dominates depends on the person holding the device, so it is theirs to set.
///
/// The settings-pane panic button is unaffected by this preference: it always
/// confirms, and it works in every mode.
enum PanicGestureMode: String, CaseIterable, Identifiable {
/// The third tap wipes, no questions asked.
case instant
/// The third tap raises the same confirmation the settings button shows.
case confirm
/// The gesture does nothing; only the settings button can wipe.
case off
var id: String { rawValue }
}
/// Persistence for `PanicGestureMode`.
enum PanicGestureSettings {
static let storageKey = "panic.gestureMode"
/// What a fresh install gets. Confirm-first, because that is the behavior
/// the app ships with today — a preference nobody has set must not quietly
/// re-arm an instant wipe on someone who never asked for one.
static let installDefault: PanicGestureMode = .confirm
/// What a panic wipe leaves behind. Deliberately *not* `installDefault`:
/// someone who just wiped under duress is on the seizure path, and the
/// next wipe should not cost them a dialog.
static let postWipeMode: PanicGestureMode = .instant
static var mode: PanicGestureMode {
get { mode(in: .standard) }
set { setMode(newValue, in: .standard) }
}
/// Store-injecting forms, so tests can assert every mode without touching
/// the shared preferences other tests read.
///
/// A missing or unrecognized value reads as `installDefault`: a preference
/// written by an older build, half-written, or edited by hand must not
/// silently disarm the confirmation.
static func mode(in defaults: UserDefaults) -> PanicGestureMode {
guard let raw = defaults.string(forKey: storageKey),
let mode = PanicGestureMode(rawValue: raw) else {
return installDefault
}
return mode
}
static func setMode(_ mode: PanicGestureMode, in defaults: UserDefaults) {
defaults.set(mode.rawValue, forKey: storageKey)
}
/// Panic-wipe hook. This *writes* `postWipeMode` rather than removing the
/// key: clearing it would fall back to `installDefault` (confirm), and a
/// device that was just wiped under duress should come back with the
/// gesture armed, not asking. Nothing about the pre-wipe choice survives —
/// the value written is a constant, not whatever was there before.
static func resetForPanicWipe(in defaults: UserDefaults = .standard) {
setMode(postWipeMode, in: defaults)
}
}

View File

@ -1752,6 +1752,16 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
guard panicCompleted else { return false }
// Only now, on the committed path — unlike the preference resets
// above, this one moves the device to a LESS safe state (the logo
// wipes on the next triple-tap, no dialog). A wipe that did not
// commit leaves the data on disk, and must not also leave it one
// accidental tap from destruction on a gesture the user may have
// deliberately switched off. Not a restore-to-default: a device wiped
// under duress comes back armed for the next one, and keeps no record
// of what it was set to before.
PanicGestureSettings.resetForPanicWipe()
if let panicTransport = meshService as? PanicResettingTransport {
// Startup recovery reopens admission but leaves actual service
// start to the bootstrapper immediately after this method.

View File

@ -30,6 +30,9 @@ struct AppInfoView: View {
/// introduction), and afterwards the sheet reopens wherever it was left.
@AppStorage("appInfo.selectedPane") private var selectedPane: Pane = .info
@State private var showPanicConfirmation = false
@AppStorage(PanicGestureSettings.storageKey) private var panicGestureRawValue = PanicGestureSettings.installDefault.rawValue
/// Turning the gesture off is itself a safety decision — confirm it.
@State private var showDisableGestureConfirm = false
@AppStorage(AppLanguageSettings.overrideKey) private var languageOverride = ""
/// The override changed this session; localization resolves at process
/// start, so surface the restart hint.
@ -44,6 +47,19 @@ struct AppInfoView: View {
AppTheme(rawValue: appThemeRawValue) ?? .matrix
}
private var panicGestureMode: PanicGestureMode {
PanicGestureMode(rawValue: panicGestureRawValue) ?? PanicGestureSettings.installDefault
}
/// Selecting `.off` asks first; every other mode applies immediately.
private func selectPanicGestureMode(_ mode: PanicGestureMode) {
guard mode == .off, panicGestureMode != .off else {
panicGestureRawValue = mode.rawValue
return
}
showDisableGestureConfirm = true
}
private var textColor: Color { palette.primary }
private var secondaryTextColor: Color { palette.secondary }
@ -120,7 +136,37 @@ struct AppInfoView: View {
static let dangerTitle = String(localized: "app_info.settings.danger.title", defaultValue: "DANGER ZONE", comment: "Section header (uppercase) for destructive actions in settings")
static let panicButton = String(localized: "app_info.settings.danger.panic_button", defaultValue: "panic wipe", comment: "Button in the settings danger zone that erases all local data after confirmation")
static let panicNote = String(localized: "app_info.settings.danger.panic_note", defaultValue: "erases all messages, keys, and identity. triple-tapping the bitchat/ logo does the same, instantly.", comment: "Caption under the panic wipe button explaining what it does and the triple-tap shortcut")
static let panicNote = String(localized: "app_info.settings.danger.panic_note", defaultValue: "erases all messages, keys, and identity. there is no undo.", comment: "Caption under the panic wipe button explaining what it does")
static let gestureTitle = String(localized: "app_info.settings.danger.gesture_title", defaultValue: "triple-tap the logo", comment: "Title of the setting controlling what a triple-tap on the bitchat/ logo does")
static let gestureSubtitle = String(localized: "app_info.settings.danger.gesture_subtitle", defaultValue: "the bitchat/ logo runs the same wipe when tapped three times. fast when seconds matter, and easy to set off by accident \u{2014} choose which it is. the button above always asks first.", comment: "Subtitle explaining the triple-tap wipe shortcut and why its behavior can be configured")
static let gestureResetNote = String(localized: "app_info.settings.danger.gesture_reset_note", defaultValue: "a wipe resets this to instant, so a device you just wiped is ready to wipe again.", comment: "Caption explaining that performing a panic wipe sets the triple-tap gesture back to instant")
static func gestureMode(_ mode: PanicGestureMode) -> String {
switch mode {
case .instant:
return String(localized: "app_info.settings.danger.gesture_instant", defaultValue: "instantly", comment: "Option: a triple-tap on the bitchat/ logo wipes all data immediately, with no confirmation")
case .confirm:
return String(localized: "app_info.settings.danger.gesture_confirm", defaultValue: "ask first", comment: "Option: a triple-tap on the bitchat/ logo asks for confirmation before wiping all data")
case .off:
return String(localized: "app_info.settings.danger.gesture_off", defaultValue: "off", comment: "Option: a triple-tap on the bitchat/ logo does nothing; only the settings button can wipe")
}
}
static let gestureDisableTitle = String(localized: "app_info.settings.danger.gesture_disable_title", defaultValue: "turn off the logo wipe?", comment: "Title of the dialog confirming that the triple-tap panic gesture should be disabled")
static let gestureDisableAction = String(localized: "app_info.settings.danger.gesture_disable_action", defaultValue: "turn it off", comment: "Confirmation button that disables the triple-tap panic gesture")
static let gestureDisableMessage = String(localized: "app_info.settings.danger.gesture_disable_message", defaultValue: "the logo will stop wiping entirely. the panic wipe button above still works.", comment: "Message of the dialog confirming that the triple-tap panic gesture should be disabled")
/// The privacy-pane one-liner has to track the mode too, or it
/// promises behavior the gesture no longer has.
static func privacyPanicDescription(_ mode: PanicGestureMode) -> String {
switch mode {
case .instant:
return String(localized: "app_info.privacy.panic.description_instant", defaultValue: "triple-tap logo to wipe all data instantly", comment: "Privacy-pane description of the panic gesture when a triple-tap wipes immediately")
case .confirm:
return String(localized: "app_info.privacy.panic.description", defaultValue: "triple-tap logo to wipe all data (asks to confirm)", comment: "Privacy-pane description of the panic gesture when a triple-tap asks for confirmation")
case .off:
return String(localized: "app_info.privacy.panic.description_off", defaultValue: "panic wipe available in settings; the logo shortcut is off", comment: "Privacy-pane description of the panic gesture when the triple-tap shortcut is disabled")
}
}
static let panicConfirmTitle = String(localized: "app_info.settings.danger.panic_confirm_title", defaultValue: "wipe all data?", comment: "Title of the confirmation dialog before a panic wipe")
static let panicConfirmAction = String(localized: "app_info.settings.danger.panic_confirm_action", defaultValue: "wipe everything", comment: "Destructive confirmation button that performs the panic wipe")
}
@ -221,11 +267,6 @@ struct AppInfoView: View {
title: "app_info.privacy.ephemeral.title",
description: "app_info.privacy.ephemeral.description"
)
static let panic = AppInfoFeatureInfo(
icon: "hand.raised.fill",
title: "app_info.privacy.panic.title",
description: "app_info.privacy.panic.description"
)
}
enum HowToUse {
@ -338,22 +379,9 @@ struct AppInfoView: View {
SectionHeader(Strings.appearanceTitle)
Spacer()
ForEach(AppTheme.allCases) { theme in
Button {
optionChip(Text(theme.displayNameKey), isSelected: selectedTheme == theme) {
appThemeRawValue = theme.rawValue
} label: {
Text(theme.displayNameKey)
.bitchatFont(size: 13, weight: selectedTheme == theme ? .semibold : .regular)
.foregroundColor(selectedTheme == theme ? palette.accent : secondaryTextColor)
.padding(.horizontal, 10)
.padding(.vertical, 6)
.background(
RoundedRectangle(cornerRadius: 8, style: .continuous)
.fill(selectedTheme == theme ? palette.accent.opacity(0.15) : Color.clear)
)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.accessibilityAddTraits(selectedTheme == theme ? .isSelected : [])
}
}
@ -573,6 +601,50 @@ struct AppInfoView: View {
.bitchatFont(size: 11)
.foregroundColor(secondaryTextColor)
.fixedSize(horizontal: false, vertical: true)
// The gesture is the accident-prone entry point, so its
// behavior is the user's call — three choices rather than
// a toggle, because "never wipe from the logo" and "ask me
// first" are different answers and both were asked for.
settingsCard {
VStack(alignment: .leading, spacing: 2) {
Text(verbatim: Strings.Settings.gestureTitle)
.bitchatFont(size: 12, weight: .semibold)
.foregroundColor(textColor)
Text(verbatim: Strings.Settings.gestureSubtitle)
.bitchatFont(size: 11)
.foregroundColor(secondaryTextColor)
.fixedSize(horizontal: false, vertical: true)
}
HStack(spacing: 8) {
ForEach(PanicGestureMode.allCases) { mode in
optionChip(
Text(verbatim: Strings.Settings.gestureMode(mode)),
isSelected: panicGestureMode == mode
) {
selectPanicGestureMode(mode)
}
}
}
Text(verbatim: Strings.Settings.gestureResetNote)
.bitchatFont(size: 11)
.foregroundColor(secondaryTextColor)
.fixedSize(horizontal: false, vertical: true)
}
.confirmationDialog(
Text(verbatim: Strings.Settings.gestureDisableTitle),
isPresented: $showDisableGestureConfirm,
titleVisibility: .visible
) {
Button(Strings.Settings.gestureDisableAction, role: .destructive) {
panicGestureRawValue = PanicGestureMode.off.rawValue
}
Button("common.cancel", role: .cancel) {}
} message: {
Text(verbatim: Strings.Settings.gestureDisableMessage)
}
}
}
}
@ -738,6 +810,35 @@ struct AppInfoView: View {
.toggleStyle(IRCToggleStyle(accent: palette.accent, onLabel: Strings.Settings.toggleOn, offLabel: Strings.Settings.toggleOff))
}
/// One option in a multi-choice row — the appearance picker's chip, shared
/// so a second such row is the same control rather than a lookalike.
private func optionChip(_ title: Text, isSelected: Bool, action: @escaping () -> Void) -> some View {
Button(action: action) {
title
.bitchatFont(size: 13, weight: isSelected ? .semibold : .regular)
.foregroundColor(isSelected ? palette.accent : secondaryTextColor)
.padding(.horizontal, 10)
.padding(.vertical, 6)
.background(
RoundedRectangle(cornerRadius: 8, style: .continuous)
.fill(isSelected ? palette.accent.opacity(0.15) : Color.clear)
)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.accessibilityAddTraits(isSelected ? .isSelected : [])
}
/// Privacy-pane panic row, rebuilt per mode so its one-liner cannot
/// promise a gesture the user has changed or switched off.
private var panicPrivacyRow: AppInfoFeatureInfo {
AppInfoFeatureInfo(
icon: "hand.raised.fill",
resolvedTitle: String(localized: "app_info.privacy.panic.title", comment: "Title of the privacy-pane row describing the panic wipe"),
resolvedDescription: Strings.Settings.privacyPanicDescription(panicGestureMode)
)
}
// MARK: - Info pane
@ViewBuilder
@ -814,7 +915,7 @@ struct AppInfoView: View {
FeatureRow(info: Strings.Privacy.ephemeral)
FeatureRow(info: Strings.Privacy.panic)
FeatureRow(info: panicPrivacyRow)
}
// Symbols legend

View File

@ -55,7 +55,9 @@ struct ContentHeaderView: View {
// App Info entry point and sits beside the nickname field, so
// a fumbled tap must never be able to wipe the device. The
// dialog matches the Settings-pane panic button; under duress
// it costs one extra tap.
// it costs one extra tap. Whether it confirms, wipes at once,
// or does nothing is a DANGER ZONE setting — decided inside
// requestPanicWipe(), never here.
appChromeModel.requestPanicWipe()
}
.onTapGesture(count: 1) {

View File

@ -25,6 +25,12 @@ struct ContentRootModalPresentationState {
var isVoiceAlertPresented = false
var isScreenshotPrivacyAlertPresented = false
var isMediaPickerPresented = false
/// The panic confirmation and the gesture-disabled notice are hosted on
/// ContentView, so they must count as presentations like every other
/// modal here — otherwise a Bluetooth alert can stack on top of a pending
/// "wipe all data?" dialog.
var isPanicConfirmationPresented = false
var isPanicGestureDisabledAlertPresented = false
var hasPresentation: Bool {
isPeopleSheetPresented
@ -37,6 +43,8 @@ struct ContentRootModalPresentationState {
|| isVoiceAlertPresented
|| isScreenshotPrivacyAlertPresented
|| isMediaPickerPresented
|| isPanicConfirmationPresented
|| isPanicGestureDisabledAlertPresented
}
}
@ -64,7 +72,11 @@ extension ContentRootModalPresentationState {
isVoiceAlertPresented: isVoiceAlertPresented,
isScreenshotPrivacyAlertPresented:
appChromeModel.showScreenshotPrivacyWarning,
isMediaPickerPresented: isMediaPickerPresented
isMediaPickerPresented: isMediaPickerPresented,
isPanicConfirmationPresented:
appChromeModel.showPanicConfirmation,
isPanicGestureDisabledAlertPresented:
appChromeModel.showPanicGestureDisabledAlert
)
}
}
@ -533,6 +545,21 @@ struct ContentView: View {
}
Button("common.cancel", role: .cancel) {}
}
// Switching the gesture off must not make it silently inert: someone
// triple-tapping in a hurry would otherwise walk away believing the
// device was wiped.
.alert(
Text(
String(localized: "content.alert.panic_gesture_off.title", defaultValue: "logo wipe is off", comment: "Title of the alert shown when the logo is triple-tapped while the panic gesture is disabled")
),
isPresented: $appChromeModel.showPanicGestureDisabledAlert
) {
Button("common.ok", role: .cancel) {}
} message: {
Text(
String(localized: "content.alert.panic_gesture_off.message", defaultValue: "nothing was wiped. turn the logo gesture back on in settings, or use the panic wipe button there.", comment: "Message of the alert shown when the logo is triple-tapped while the panic gesture is disabled")
)
}
}
private var publicMessageList: some View {

View File

@ -4,6 +4,13 @@ import Foundation
import Testing
@testable import bitchat
/// A throwaway suite for the panic-gesture preference, so the tests below
/// drive `requestPanicWipe()` through its real read path without ever
/// touching the shared defaults another suite may be using.
private func makeIsolatedPanicGestureDefaults() -> UserDefaults {
UserDefaults(suiteName: "bitchat.tests.architecture.panic.\(UUID().uuidString)")!
}
@MainActor
private func makeArchitectureViewModel(
locationManager: LocationChannelManager? = nil
@ -462,12 +469,19 @@ struct AppArchitectureTests {
#expect(chromeModel.showingFingerprintFor == nil)
}
@Test("Triple-tap panic entry point only raises the confirmation dialog")
@Test("The shipped default makes the triple-tap raise the confirmation dialog")
@MainActor
func requestPanicWipeAsksBeforeDestroying() {
let viewModel = makeArchitectureViewModel()
let privateInboxModel = PrivateInboxModel(conversations: ConversationStore())
let chromeModel = AppChromeModel(chatViewModel: viewModel, privateInboxModel: privateInboxModel)
// An empty store: this asserts what a fresh install does, through the
// real read path, without depending on whatever the shared defaults
// happen to hold on this machine.
let chromeModel = AppChromeModel(
chatViewModel: viewModel,
privateInboxModel: privateInboxModel,
panicGestureDefaults: makeIsolatedPanicGestureDefaults()
)
viewModel.seedPublicMessages([
BitchatMessage(
id: "keep-1",
@ -486,6 +500,71 @@ struct AppArchitectureTests {
#expect(viewModel.messages.map(\.id) == ["keep-1"])
}
@Test("A disabled logo gesture wipes nothing and says so")
@MainActor
func panicGestureOffReportsThatNothingHappened() {
let viewModel = makeArchitectureViewModel()
let defaults = makeIsolatedPanicGestureDefaults()
PanicGestureSettings.setMode(.off, in: defaults)
let chromeModel = AppChromeModel(
chatViewModel: viewModel,
privateInboxModel: PrivateInboxModel(conversations: ConversationStore()),
panicGestureDefaults: defaults
)
viewModel.seedPublicMessages([
BitchatMessage(id: "keep-1", sender: "Tester", content: "still here", timestamp: Date(), isRelay: false)
])
chromeModel.requestPanicWipe()
// Silence is the dangerous outcome here: someone who triple-tapped in
// a hurry would otherwise believe the device had been wiped.
#expect(chromeModel.showPanicGestureDisabledAlert)
#expect(!chromeModel.showPanicConfirmation)
#expect(viewModel.messages.map(\.id) == ["keep-1"])
}
@Test("Instant mode wipes without asking")
@MainActor
func panicGestureInstantWipesImmediately() {
let viewModel = makeArchitectureViewModel()
let defaults = makeIsolatedPanicGestureDefaults()
PanicGestureSettings.setMode(.instant, in: defaults)
var wipes = 0
let chromeModel = AppChromeModel(
chatViewModel: viewModel,
privateInboxModel: PrivateInboxModel(conversations: ConversationStore()),
onPanicWipe: { wipes += 1 },
panicGestureDefaults: defaults
)
chromeModel.requestPanicWipe()
#expect(wipes == 1)
#expect(!chromeModel.showPanicConfirmation)
#expect(!chromeModel.showPanicGestureDisabledAlert)
}
@Test("Confirm mode destroys nothing until the dialog is answered")
@MainActor
func panicGestureConfirmDestroysNothingUpFront() {
let viewModel = makeArchitectureViewModel()
let defaults = makeIsolatedPanicGestureDefaults()
PanicGestureSettings.setMode(.confirm, in: defaults)
var wipes = 0
let chromeModel = AppChromeModel(
chatViewModel: viewModel,
privateInboxModel: PrivateInboxModel(conversations: ConversationStore()),
onPanicWipe: { wipes += 1 },
panicGestureDefaults: defaults
)
chromeModel.requestPanicWipe()
#expect(chromeModel.showPanicConfirmation)
#expect(wipes == 0)
}
@Test("Panic wipe dismisses chrome sheets so its outcome is visible")
@MainActor
func panicWipeDismissesChromePresentation() {

View File

@ -2077,6 +2077,43 @@ struct ChatViewModelPrivateMediaDeletionTests {
struct ChatViewModelPanicTests {
@Test @MainActor
func panicClearAllData_armsTheLogoGestureForTheNextWipe() {
// ChatViewModel's store is hardcoded to .standard, so this test must
// write the shared preference — restore it, or it leaks into every
// later test (and into the developer's test host).
let previous = PanicGestureSettings.mode
defer { PanicGestureSettings.mode = previous }
PanicGestureSettings.mode = .off
let (viewModel, _) = makeTestableViewModel()
_ = viewModel.panicClearAllData(restartServices: false)
// Guards the wiring, not the setting: deleting the reset call from
// panicClearAllData must fail here, not pass quietly.
#expect(PanicGestureSettings.mode == .instant)
}
@Test @MainActor
func panicClearAllData_leavesTheGestureAloneWhenTheWipeDoesNotCommit() {
// Writes the shared preference (ChatViewModel's store is fixed), so
// restore it — otherwise it leaks into later tests and the test host.
let previous = PanicGestureSettings.mode
defer { PanicGestureSettings.mode = previous }
PanicGestureSettings.mode = .off
let keychain = MockKeychain()
keychain.simulatedDeleteAllResult = false
let (viewModel, _) = makeTestableViewModel(keychain: keychain)
let completed = viewModel.panicClearAllData(restartServices: false)
// Arming the instant gesture is the one reset that moves the device
// to a LESS safe state. With the data still on disk, a gesture the
// user deliberately switched off must stay off.
#expect(!completed)
#expect(PanicGestureSettings.mode == .off)
}
@Test @MainActor
func panicClearAllData_finishesMediaWipeBeforeReturning() {
var wipeFinished = false

View File

@ -0,0 +1,69 @@
import Foundation
import Testing
@testable import bitchat
/// The logo triple-tap is an emergency control with two opposite failure
/// modes: wiping when nobody meant to, and failing to wipe when someone did.
/// The preference has to land on the safe side of each — confirm-first for an
/// install nobody has configured, armed for a device that was just wiped.
struct PanicGestureSettingsTests {
private func makeDefaults() -> UserDefaults {
UserDefaults(suiteName: "bitchat.tests.panicgesture.\(UUID().uuidString)")!
}
@Test func freshInstallAsksBeforeWiping() {
// Preserves the behavior shipped in #1588: an unset preference must
// not silently re-arm an instant wipe on someone who never chose one.
#expect(PanicGestureSettings.mode(in: makeDefaults()) == .confirm)
#expect(PanicGestureSettings.installDefault == .confirm)
}
@Test func theSettingRoundTrips() {
let defaults = makeDefaults()
for mode in PanicGestureMode.allCases {
PanicGestureSettings.setMode(mode, in: defaults)
#expect(PanicGestureSettings.mode(in: defaults) == mode)
}
}
@Test func unrecognizedStoredValueAsksBeforeWiping() {
let defaults = makeDefaults()
defaults.set("disabled", forKey: PanicGestureSettings.storageKey)
#expect(PanicGestureSettings.mode(in: defaults) == .confirm)
defaults.set(7, forKey: PanicGestureSettings.storageKey)
#expect(PanicGestureSettings.mode(in: defaults) == .confirm)
}
@Test func panicWipeLeavesTheGestureArmed() {
let defaults = makeDefaults()
PanicGestureSettings.setMode(.off, in: defaults)
PanicGestureSettings.resetForPanicWipe(in: defaults)
// Not the install default: someone who just wiped under duress is on
// the seizure path, and the next wipe must not cost them a dialog.
#expect(PanicGestureSettings.mode(in: defaults) == .instant)
}
@Test func panicWipeArmsTheGestureFromEveryStartingMode() {
for mode in PanicGestureMode.allCases {
let defaults = makeDefaults()
PanicGestureSettings.setMode(mode, in: defaults)
PanicGestureSettings.resetForPanicWipe(in: defaults)
// The written value is a constant, so nothing about the pre-wipe
// choice can be read back off the device afterwards.
#expect(PanicGestureSettings.mode(in: defaults) == .instant)
}
}
@Test func rawValuesAreStable() {
// Stored preferences are matched by these strings; renaming a case
// would strand everyone who had chosen it.
#expect(PanicGestureMode.allCases.map(\.rawValue) == ["instant", "confirm", "off"])
}
}

View File

@ -503,6 +503,10 @@ struct ViewSmokeTests {
// AppInfoView's settings pane reads LocationChannelsModel from the
// environment, so it can only render mounted with one installed.
// The danger zone (panic button, gesture chips) is gated on a non-nil
// wipe hook, so a plain AppInfoView never evaluates that branch.
let appInfoWithDangerZone = AppInfoView(onPanicWipe: {})
.environmentObject(LocationChannelsModel(manager: makeSmokeLocationManager()))
let appInfo = AppInfoView()
.environmentObject(LocationChannelsModel(manager: makeSmokeLocationManager()))
let header = SectionHeader("app_info.features.title")
@ -521,6 +525,21 @@ struct ViewSmokeTests {
_ = DeliveryStatusView(status: .failed(reason: "offline")).body
_ = DeliveryStatusView(status: .partiallyDelivered(reached: 2, total: 3)).body
_ = mount(appInfo)
// The pane picker is @AppStorage-backed and defaults to Info, so a
// mount lands on the Info pane; the danger zone lives in Settings.
// Force that pane for the second mount so the zone actually renders.
let paneKey = "appInfo.selectedPane"
let previousPane = UserDefaults.standard.object(forKey: paneKey)
defer {
if let previousPane {
UserDefaults.standard.set(previousPane, forKey: paneKey)
} else {
UserDefaults.standard.removeObject(forKey: paneKey)
}
}
UserDefaults.standard.set("settings", forKey: paneKey)
_ = mount(appInfoWithDangerZone)
_ = mount(header)
_ = mount(featureRow)
_ = mount(paymentCashu)
@ -570,6 +589,18 @@ struct ViewSmokeTests {
isNoticesSheetPresented: true
).hasPresentation
)
// Both panic modals are hosted on ContentView; if hasPresentation
// ignored them a Bluetooth alert could stack on a pending wipe dialog.
#expect(
ContentRootModalPresentationState(
isPanicConfirmationPresented: true
).hasPresentation
)
#expect(
ContentRootModalPresentationState(
isPanicGestureDisabledAlertPresented: true
).hasPresentation
)
}
@Test("People-sheet Bluetooth alert waits for local verification sheet")

View File

@ -109,7 +109,7 @@ Not addressed, and deliberately out of scope here:
## Panic Wipe Coverage
The panic action clears identity/session state, preferences, location state, groups, prekeys, outbox mail, courier mail, bridge dedup state, gossip archive, board data, managed media, hand-added relays, and active subscriptions/transports. Managed media deletion completes synchronously, after active media work has been invalidated. Keychain secrets use device-only accessibility, and an install marker detects and clears app keys that survive uninstall before a later reinstall can use them. New persistent stores must add an explicit wipe hook and a regression test.
The panic action clears identity/session state, preferences, location state, groups, prekeys, outbox mail, courier mail, bridge dedup state, gossip archive, board data, managed media, hand-added relays, and active subscriptions/transports. It also rewrites the logo-gesture mode (`panic.gestureMode`) to `instant` — deliberately not the install default, so a device wiped under duress comes back armed and retains no trace of the previous setting. Managed media deletion completes synchronously, after active media work has been invalidated. Keychain secrets use device-only accessibility, and an install marker detects and clears app keys that survive uninstall before a later reinstall can use them. New persistent stores must add an explicit wipe hook and a regression test.
## Release Review Checklist