Skip to content

Fix and redesign delete-account flow - #6669

Merged
mdmohsin7 merged 10 commits into
mainfrom
fix/delete-account-flow-ux
Apr 15, 2026
Merged

mdmohsin7 merged 10 commits into
mainfrom
fix/delete-account-flow-ux

Conversation

@mdmohsin7

@mdmohsin7 mdmohsin7 commented Apr 15, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Fixes prod 500s on /v1/users/delete-account. Grafana showed 'CollectionReference' object has no attribute 'path' — the success-log inside the batch loop was crashing after data had been deleted, so retries then hit Firebase "user not found" and 500'd again.
  • Deletion is now comprehensive. Walks user_ref.collections() live instead of a hardcoded list of 6 — picks up the 11 subcollections that were leaking (folders, goals, integrations, task_integrations, fcm_tokens, fair_use_*, hourly_usage, meetings, action_items, screen_activity) and any future ones. Pinecone + GCS intentionally untouched pending their own cleanup pass.
  • Fast response, idempotent. Feedback written, Firebase auth revoked, then Firestore wipe runs on a daemon thread. Endpoint returns in ~100ms instead of blocking for minutes on heavy users. Tolerates missing Firebase user on retry.
  • App UX redesigned. New 3-step flow (reason → feedback → confirm) matching the subscription-cancel aesthetic. Step 3 requires typing DELETE, lists consequences, makes "Keep my account" the primary CTA. Proper loading state, error handling, SafeArea. signOut now runs last so auth listeners see clean local state.
  • Reasons captured via Mixpanel (Delete Account Reason Selected, Delete Account Feedback Submitted, plus abandon/kept funnel events) and persisted to Firestore account_deletions/{uid} for durable analytics.

Test plan

  • Trigger deletion on a test account with lots of data — request returns quickly, data wiped in background
  • Try signing in again with same Google/Apple account → creates fresh user with new UID
  • Verify Mixpanel receives Delete Account Reason Selected / Feedback Submitted events with reason payload
  • Verify Firestore account_deletions/{uid} doc created with reason + timestamp
  • Verify all 17 user subcollections removed post-deletion
  • Exercise abandon and "Keep my account" paths — correct Mixpanel events fire
  • Translate new l10n keys for 33 non-English locales (follow-up)

🤖 Generated with Claude Code

…ctions

Fixes the 500 ("CollectionReference has no attribute 'path'") that was
caught in prod logs. Also rewrites delete_user_data to enumerate
subcollections live via user_ref.collections() so we stop leaking data
from the 11 collections that weren't in the hardcoded list.

Adds set_user_deletion_feedback that writes to a top-level
account_deletions/{uid} doc so feedback survives the user wipe.
Endpoint now accepts {reason, reason_details}, stores feedback before
deleting, revokes Firebase auth immediately, and runs the Firestore
wipe on a daemon thread so the request returns in ~100ms instead of
timing out at the LB for heavy users.

Also sanitizes error detail (no raw exception body) and tolerates a
missing Firebase user so retries after a partial deletion succeed.
Tracks flow started, reason selected, feedback submitted, abandoned,
and kept-account — mirrors the subscription cancel funnel.
Replaces the old one-page checkbox+button screen with a flow that
mirrors the subscription cancel UX: reason → feedback → final confirm.
Step 3 shows consequences, requires the user to type DELETE, surfaces
"Keep my account" as the primary CTA, and de-emphasizes the destructive
action. Proper back-navigation, SafeArea, loading state, error snackbar,
and the auth signOut now runs last so listeners see clean local state.
@greptile-apps

greptile-apps Bot commented Apr 15, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes the production 500 error on /v1/users/delete-account (caused by a CollectionReference.path crash in the batch loop), expands Firestore deletion to walk all live subcollections instead of a hardcoded six, and replaces the old single-screen checkbox flow with a 3-step reason → feedback → confirm UX. The backend now returns in ~100ms by moving the Firestore wipe to a background thread, and Firebase auth is revoked before the wipe starts to prevent re-login during deletion.

Confidence Score: 5/5

Safe to merge — the production crash is fixed, the data wipe is comprehensive, and the new UX is well-structured.

All findings are P2 (style, monitoring, and analytics quality). No blocking correctness or security issues were found. The daemon-thread data-privacy concern is real but low-probability and the PR explicitly documents the tradeoff.

backend/routers/users.py — duplicate import, logger level, and the daemon-thread wipe reliability note.

Important Files Changed

Filename Overview
backend/routers/users.py Delete endpoint redesigned: stores feedback, revokes Firebase auth, then starts a daemon thread for Firestore wipe; has duplicate Optional import and uses logger.info for wipe errors instead of logger.error
backend/database/users.py Adds set_user_deletion_feedback and recursive _delete_collection_recursive helper; delete_user_data now walks live subcollections instead of a hardcoded list — clean improvement
app/lib/pages/settings/delete_account.dart Full rewrite from checkbox dialog to 3-step PageView flow; proper lifecycle management, SafeArea, and loading states; minor analytics tracking gap on hardware-back from page 0
app/lib/backend/http/api/users.dart deleteAccount gains optional reason/reasonDetails params; Content-Type set only when feedback is present — straightforward change
app/lib/utils/analytics/mixpanel.dart Adds five new delete-flow tracking methods; remaining diff is reformatting only
app/lib/l10n/app_en.arb Adds 18 new delete-flow l10n keys with descriptions; all 33 non-English locale files carry English fallback text (acknowledged as a follow-up in the PR)

Sequence Diagram

sequenceDiagram
    participant App
    participant Backend
    participant FirebaseAuth
    participant Firestore
    participant BgThread

    App->>Backend: DELETE /v1/users/delete-account
    Backend->>Firestore: write account_deletions collection
    Backend->>FirebaseAuth: revoke user token
    FirebaseAuth-->>Backend: ok
    Backend->>BgThread: spawn daemon thread
    Backend-->>App: 200 ok (~100ms)
    App->>App: clear local state and sign out

    BgThread->>Firestore: enumerate all subcollections
    loop each subcollection
        BgThread->>Firestore: delete documents recursively
    end
    BgThread->>Firestore: delete user document
Loading

Comments Outside Diff (1)

  1. backend/routers/users.py, line 46 (link)

    P2 Duplicate Optional import

    Optional is already imported on line 4 (from typing import List, Dict, Any, Union, Optional). This second import is redundant and should be removed.

Reviews (1): Last reviewed commit: "chore(l10n): regenerate localizations" | Re-trigger Greptile

Comment thread backend/routers/users.py Outdated
Comment on lines +114 to +115
except Exception as e:
logger.info(f'delete_account background wipe failed for {uid}: {sanitize(str(e))}')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Use logger.error for background wipe failures

logger.info for a wipe failure silences the alert in any log-level-based monitoring. If the daemon thread is killed mid-deletion (e.g., on a pod restart), this failure is only visible by grepping info logs.

Suggested change
except Exception as e:
logger.info(f'delete_account background wipe failed for {uid}: {sanitize(str(e))}')
logger.error(f'delete_account background wipe failed for {uid}: {sanitize(str(e))}')

Comment thread backend/routers/users.py
Comment on lines +118 to +122
@router.delete('/v1/users/delete-account', tags=['v1'])
def delete_account(
request: DeleteAccountRequest = DeleteAccountRequest(),
uid: str = Depends(auth.get_current_user_uid),
):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Daemon thread wipe can be silently dropped on pod termination

Firebase auth is revoked before the background thread starts. If the pod is killed (deployment, OOM, Cloud Run scale-in) while the thread is mid-wipe, the Firestore data is partially or fully left behind. Because the user's auth token is already invalidated, they cannot re-authenticate and retry the deletion — the orphaned data persists indefinitely.

For most users the wipe is fast, but heavy users with many subcollections are at risk. Consider writing a job document to a pending_deletions collection first and processing it from a durable queue or a Cloud Task, so a pod restart doesn't silently abandon the wipe.

Comment on lines +262 to +267
);
}

// ─── Step 2: Feedback ───

Widget _stepFeedback() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 deleteAccountAbandoned not fired on hardware/gesture back from page 0

When _page == 0, canPop is true, so the system handles the pop natively and onPopInvokedWithResult receives didPop = true — _back() is never called and the Mixpanel event doesn't fire. Only tapping the AppBar ← button triggers _back() on page 0 and records the abandon event.

To capture all exit paths, move the tracking into onPopInvokedWithResult:

onPopInvokedWithResult: (didPop, _) {
  if (didPop && _page == 0) {
    MixpanelManager().deleteAccountAbandoned(step: 1, reason: _selectedReason);
  }
  if (!didPop && !_isDeleting) _back();
},

Comment on lines +224 to +235

Widget _reasonTile(_Reason reason) {
final selected = _selectedReason == reason.key;
return GestureDetector(
onTap: () => setState(() => _selectedReason = reason.key),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 13),
decoration: BoxDecoration(
color: selected ? Colors.grey.shade900 : Colors.grey.shade900.withValues(alpha: 0.5),
borderRadius: BorderRadius.circular(14),
border: Border.all(color: selected ? Colors.grey.shade600 : Colors.grey.shade800),
),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Mixpanel funnel events fire before the API call succeeds

deleteAccountConfirmed and deleteAccountFeedbackSubmitted are tracked before deleteAccount() is awaited. If the request fails (network error, 5xx), both events are already emitted, inflating the confirmed-deletion funnel. Consider firing them only after ok == true.

Adds 21 new localized strings for the delete-account UX flow across
every non-English ARB file and regenerates the companion
app_localizations_*.dart files. The literal uppercase DELETE token is
preserved in every locale so the confirmation TextField continues to
match user input.
- Log background wipe failures at ERROR, not INFO, so monitoring picks
  them up instead of requiring a manual grep.
- Fire Mixpanel "Confirmed" / "Feedback Submitted" only after the API
  succeeds — failed requests no longer inflate the deletion funnel.
- Route system back/swipe on step 1 through onPopInvokedWithResult so
  the "Abandoned" event fires for every exit path, not just AppBar taps.
@mdmohsin7
mdmohsin7 merged commit e248382 into main Apr 15, 2026
2 checks passed
@mdmohsin7
mdmohsin7 deleted the fix/delete-account-flow-ux branch April 15, 2026 10:56
shaun0927 added a commit to shaun0927/omi that referenced this pull request Apr 17, 2026
…oc Thread

backend/CLAUDE.md and the root CLAUDE.md both say:

  never `Thread().start().join()` (use `critical_executor` /
  `storage_executor`)

The async-native refactor (PR BasedHardware#6377) removed the remaining ad-hoc
threads and added a lint script that catches this pattern in async
def. The delete-account wipe added in PR BasedHardware#6669 brought one back —
inside a sync def, so the lint at scripts/lint_async_blockers.py
doesn't see it (it only walks async functions and only matches
.join()).

Two follow-on problems with the daemon=True form:

  1. Cloud Run sends SIGTERM during scale-down or rolling deploys.
     Daemon threads are killed mid-wipe, leaving partial deletion
     and no retry — Firebase auth has already been revoked, so the
     user can no longer sign in to retry.
  2. The lint script will keep missing the pattern as long as the
     trigger lives in a sync endpoint.

Switching to critical_executor.submit(...) reuses the bounded shared
pool, runs as non-daemon (graceful shutdown blocks on the wipe), and
keeps the trigger fire-and-forget. Behavior is otherwise unchanged.

A separate issue (BasedHardware#6750) tracks the bigger move to Cloud Tasks /
Pub-Sub for proper retry + DLQ; this PR is the in-place fix that
gets us back inside the documented executor lane in the meantime.
shaun0927 added a commit to shaun0927/omi that referenced this pull request Apr 17, 2026
Today delete-account revokes Firebase auth and wipes Firestore but
leaves Stripe untouched, so a user who deletes their account keeps
being charged with no remaining identity to access invoices or
self-service the cancellation. PR BasedHardware#6669 explicitly noted Pinecone
and GCS as 'intentionally untouched pending their own pass'; Stripe
is not mentioned anywhere in that PR and looks like a real omission
rather than a deferred item.

Calls the new stripe_utils.cancel_all_active_subscriptions(customer)
between the Firebase auth revoke and the Firestore wipe trigger.
Period-end cancel matches the existing cancel_subscription helper
convention used elsewhere; flip to immediate cancel here if the
team's compliance position is no-grace-period.

Wrapped in try/except so a Stripe outage cannot block the account
deletion the user already requested — the error is logged with
sanitize() and reconciliation can happen via the existing webhook
path.

Tracking issue: BasedHardware#6750.
Glucksberg pushed a commit to Glucksberg/omi-local that referenced this pull request Apr 28, 2026
## Summary

- **Fixes prod 500s** on `/v1/users/delete-account`. Grafana showed
`'CollectionReference' object has no attribute 'path'` — the success-log
inside the batch loop was crashing *after* data had been deleted, so
retries then hit Firebase "user not found" and 500'd again.
- **Deletion is now comprehensive.** Walks `user_ref.collections()` live
instead of a hardcoded list of 6 — picks up the 11 subcollections that
were leaking (folders, goals, integrations, task_integrations,
fcm_tokens, fair_use_*, hourly_usage, meetings, action_items,
screen_activity) and any future ones. Pinecone + GCS intentionally
untouched pending their own cleanup pass.
- **Fast response, idempotent.** Feedback written, Firebase auth
revoked, then Firestore wipe runs on a daemon thread. Endpoint returns
in ~100ms instead of blocking for minutes on heavy users. Tolerates
missing Firebase user on retry.
- **App UX redesigned.** New 3-step flow (reason → feedback → confirm)
matching the subscription-cancel aesthetic. Step 3 requires typing
`DELETE`, lists consequences, makes "Keep my account" the primary CTA.
Proper loading state, error handling, SafeArea. `signOut` now runs last
so auth listeners see clean local state.
- **Reasons captured** via Mixpanel (`Delete Account Reason Selected`,
`Delete Account Feedback Submitted`, plus abandon/kept funnel events)
and persisted to Firestore `account_deletions/{uid}` for durable
analytics.

## Test plan
- [x] Trigger deletion on a test account with lots of data — request
returns quickly, data wiped in background
- [x] Try signing in again with same Google/Apple account → creates
fresh user with new UID
- [ ] Verify Mixpanel receives `Delete Account Reason Selected` /
`Feedback Submitted` events with reason payload
- [x] Verify Firestore `account_deletions/{uid}` doc created with reason
+ timestamp
- [x] Verify all 17 user subcollections removed post-deletion
- [ ] Exercise abandon and "Keep my account" paths — correct Mixpanel
events fire
- [x] Translate new l10n keys for 33 non-English locales (follow-up)

🤖 Generated with [Claude Code](https://claude.com/claude-code)
mdmohsin7 added a commit that referenced this pull request Jun 7, 2026
…7679)

Fixes #6750

## Summary

`DELETE /v1/users/delete-account` revokes Firebase auth and wipes
Firestore but never cancels the user's Stripe subscription. A paying
user who deletes their account keeps getting billed, and since their
auth and data are gone they can't log back in to self-serve the
cancellation. This cancels the active subscription (best-effort) before
the wipe.

## Root cause

`delete_account` (`backend/routers/users.py`) does: store feedback ->
`auth.delete_account(uid)` (Firebase revoke) -> background Firestore
wipe (`_background_wipe_user_data` -> `delete_user_data`). None of those
touch Stripe, so the subscription stays active. The delete-account
redesign (#6669) explicitly deferred Pinecone/GCS but didn't mention
Stripe, so this reads as an unintentional gap.

## Fix

Insert a best-effort cancel right after the feedback step and before the
Firebase revoke, so the user doc (and
`subscription.stripe_subscription_id`) is still readable:

```python
try:
    sub = users_db.get_user_subscription(uid)
    if sub and sub.stripe_subscription_id:
        canceled = stripe_utils.cancel_subscription(sub.stripe_subscription_id)
        if not canceled:
            logger.error(f'delete_account stripe cancel returned None for {uid}')
except Exception as e:
    logger.error(f'delete_account stripe cancel failed for {uid}: {sanitize(str(e))}')
```

It uses the existing `utils/stripe.py` `cancel_subscription` helper
(`cancel_at_period_end=True`), which is idempotent and already
error-tolerant. The try/except guarantees a Stripe outage can never
strand an account half-deleted; a `None` return or exception is logged
so support can clean up manually.

## Behavior change

- Paid user deletes account: subscription is now canceled (was:
continued billing).
- Free user: no Stripe call.
- Stripe error: logged, deletion proceeds exactly as before.

## Testing

New `backend/tests/unit/test_delete_account_stripe_cancel.py`
(registered in `backend/test.sh`):

- paid user -> `cancel_subscription` called with the subscription id,
deletion still proceeds
- free user (`stripe_subscription_id is None`) -> Stripe not called
- Stripe raises -> deletion still returns `{'status': 'ok'}`

Verified the paid-user test fails against current `main` (no cancel
happens) and passes with this change.

## Scope and possible follow-ups (kept out to keep this minimal)

- Timing: uses the existing `cancel_at_period_end=True` helper for
consistency. If the intent is "deleted account means no active paid
service," an immediate-cancel variant could be added.
- This cancels the user's own Omi subscription. Canceling
app-marketplace / Connect subscriptions tied to the Stripe customer
(discovered separately via the customer id) is a broader cleanup worth
its own pass.
- `get_user_subscription` writes a default subscription doc if none
exists. It's harmless here since the doc is wiped moments later, but a
non-mutating read would be slightly cleaner.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant