Skip to content

fix: close account deletion to re-login and Agent VM broken-state leaks - #11029

Merged
Git-on-my-level merged 22 commits into
mainfrom
agent/m1-studio-nik-codex-sol-high/33032294
Aug 4, 2026
Merged

Git-on-my-level merged 22 commits into
mainfrom
agent/m1-studio-nik-codex-sol-high/33032294

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Aug 2, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Make the durable account_deletions/{uid} marker a single fail-closed admission policy across Firebase, developer/MCP keys, OAuth issuance, HTTP/WebSocket entry points, Agent proxy sessions, and Agent VM provisioning. Completed and unknown markers remain fenced so an old token cannot revive a deleted UID.
  • Make deletion admission atomic at pending, revoke UID-bearing API/OAuth credentials, delete the account's GCE Agent VM before its Firestore pointer disappears, and transactionally fence late proxy/VM writes so in-flight work cannot recreate owner data.
  • Make accepted macOS cleanup durable across restart, drain owner-bound VM/sync work before deleting storage, remove the legacy anonymous fallback, upload a consistent SQLite snapshot with cancellable compression and bounded retries, and preserve typed startup errors in Flutter.

Repeated delete requests during pending/running intentionally receive typed 403 account_deletion_in_progress responses without marker rollback or requeue. The deletion fence is preserved.

Canonical project: BasedHardware Project #15

Sanitized incident evidence

  • A delete confirmation preceded a later same-provider sign-in/onboarding sequence by nine days.
  • The deleted UID's user document and GCE instance were gone, while its durable deletion marker completed after retried queue acceleration failures.
  • No verified event proves old server memory reads after deletion. This PR treats legacy local-database migration, still-valid old credentials, and late owner-scoped work as identity-isolation risks; typed readiness failures remain timeout-class evidence rather than proof of server data disclosure.

Related lineage: #10444, #7696, #9632, #10597, #9821, #6891, #6892, #10600, and #10694.

Failure class

Failure-Class: none

This is an audit-driven hardening sweep across durable deletion admission, credential revocation, local owner-data disposal, and Agent VM/proxy lifecycle safety. The reusable prevention surfaces are the shared fail-closed policy, transactional admission/CAS writers, the durable local cleanup journal, the effective-owner generation fence, and behavioral regression tests.

Product invariants affected

  • INV-AUTH-1 — preserves the exclusive effective-owner transition, clears accepted-deletion storage before credential/session publication, blocks every credential family after durable admission, and rejects late owner-bound Agent VM continuations.
  • INV-CHAT-1 — drains Agent VM/sync work at the existing owner transition, transactionally fences late proxy message/session writes, and preserves typed startup failures without changing canonical transcript ownership.

Changed paths

  • .github/scripts/product_file_line_count_ratchet_baseline/backend-database.json
  • .github/scripts/product_file_line_count_ratchet_baseline/backend-routers.json
  • .github/scripts/product_file_line_count_ratchet_baseline/desktop-swift-root.json
  • app/lib/services/agent_chat_service.dart
  • app/test/services/agent_chat_service_test.dart
  • backend/agent-proxy/Dockerfile
  • backend/agent-proxy/main.py
  • backend/database/account_deletion_projection_fence.py
  • backend/database/mcp_oauth.py
  • backend/database/users.py
  • backend/dependencies.py
  • backend/routers/apps.py
  • backend/routers/desktop_agent_vm.py
  • backend/routers/mcp_sse.py
  • backend/routers/oauth.py
  • backend/routers/transcribe.py
  • backend/services/users/account_deletion.py
  • backend/testing/e2e/test_account_deletion_cloud_tasks.py
  • backend/tests/services/users/test_account_deletion.py
  • backend/tests/unit/test_account_deletion_auth_fence.py
  • backend/tests/unit/test_agent_proxy_async_boundaries.py
  • backend/tests/unit/test_agent_proxy_startup_client_gone.py
  • backend/tests/unit/test_byok_security.py
  • backend/tests/unit/test_dependency_async_boundaries.py
  • backend/tests/unit/test_desktop_agent_vm.py
  • backend/tests/unit/test_mcp_api_key_auth_context.py
  • backend/tests/unit/test_mcp_oauth.py
  • backend/tests/unit/test_oauth_token_async_boundaries.py
  • backend/utils/account_deletion_access.py
  • backend/utils/other/endpoints.py
  • desktop/macos/Desktop/Sources/AgentSyncService.swift
  • desktop/macos/Desktop/Sources/AgentVMService.swift
  • desktop/macos/Desktop/Sources/AuthService.swift
  • desktop/macos/Desktop/Sources/Chat/RuntimeOwnerIdentity.swift
  • desktop/macos/Desktop/Sources/DefaultsKey.swift
  • desktop/macos/Desktop/Sources/DesktopAutomationBridge.swift
  • desktop/macos/Desktop/Sources/MainWindow/Pages/Settings/Components/SettingsContentView+SettingsUpdates.swift
  • desktop/macos/Desktop/Sources/Rewind/Core/RewindDatabase+AccountDeletion.swift
  • desktop/macos/Desktop/Tests/AgentSyncBatchQueryTests.swift
  • desktop/macos/Desktop/Tests/AgentVMLifecycleFenceTests.swift
  • desktop/macos/Desktop/Tests/AuthSessionCoordinatorTests.swift
  • desktop/macos/Desktop/Tests/OnboardingPersistenceClearingTests.swift
  • desktop/macos/Desktop/Tests/RewindDatabaseLifecycleTests.swift
  • desktop/macos/changelog/unreleased/20260802-account-deletion-local-data.json
  • desktop/macos/e2e/flows/logout.yaml

Verification

  • Focused backend deletion/auth/proxy/VM suite: 194 passed.
  • Hermetic Cloud Tasks deletion suite: 5 passed; repeated pending/running requests are asserted as typed 403 without requeue.
  • Focused macOS deletion, owner-fence, snapshot, and sync suite: 32 tests, 0 failures.
  • Focused Flutter Agent Chat suite: 2 passed.
  • Follow-up MCP OAuth consent suite: 37 passed.
  • Follow-up macOS cleanup/bridge compile suite: 17 tests, 0 failures.
  • Python runtime sources compile cleanly; pinned Python/Dart/Swift formatters and git diff --check are clean.
  • Required CI-lane PR-body preflight: 34 checks passed in 108.01s.

Backend Hermetic Merge Gate: in scope because backend runtime and hermetic contract code changed.

Limitations

  • No production Firebase/Auth, Firestore, Cloud Tasks, GCE, deployment, release, or customer-data mutation was performed.
  • Same-provider recreation is covered hermetically at the UID/auth boundary; no live Google sign-in was attempted.
  • Agent readiness and teardown are covered through backend state-machine, proxy protocol, owner-generation, snapshot/upload, credential cleanup, and stale-pointer tests; no live GCE VM was provisioned.

Review in cubic

Git-on-my-level and others added 6 commits August 2, 2026 13:27
Failure-Class: none
Co-authored-by: multica-agent <[email protected]>
Failure-Class: none
Co-authored-by: multica-agent <[email protected]>
Failure-Class: none
Co-authored-by: multica-agent <[email protected]>
Failure-Class: none
Co-authored-by: multica-agent <[email protected]>
Failure-Class: none
Co-authored-by: multica-agent <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

2 issues found across 20 files

Confidence score: 3/5

  • In backend/utils/other/endpoints.py, /v4/web/listen currently maps deleted-account socket failures to generic auth error 1008, which can hide the deletion state from clients and trigger the wrong reconnect/session behavior—handle WebSocketException before the generic catch and close with its original code/reason (4005 for deletions).
  • In desktop/macos/Desktop/Sources/AgentVMService.swift, running Process.waitUntilExit() on the actor means cancelForOwnerTransition() cannot interrupt a long DB gzip, so owner transition, deletion, and sign-out cleanup can stay blocked longer than expected—move the wait off the actor or make process waiting cancellable so transition cancellation can complete promptly.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/utils/other/endpoints.py">

<violation number="1" location="backend/utils/other/endpoints.py:271">
P2: `/v4/web/listen` reports a deleted account as generic auth failure (1008), not the new 4005 deletion event. Catch `WebSocketException` before the generic handler there and close using its code and reason.</violation>
</file>

<file name="desktop/macos/Desktop/Sources/AgentVMService.swift">

<violation number="1" location="desktop/macos/Desktop/Sources/AgentVMService.swift:18">
P2: Owner transitions can remain blocked for the full database gzip despite cancelling the pipeline, delaying deletion/sign-out cleanup. `Process.waitUntilExit()` runs on this actor, so `cancelForOwnerTransition()` cannot increment the generation or cancel this task until that synchronous work returns; run compression off the actor (and make the process cancellable) before relying on this fence.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread backend/agent-proxy/main.py Resolved
/// remain harmless because each continuation revalidates this generation.
func cancelForOwnerTransition() {
lifecycleGeneration &+= 1
pipelineTask?.cancel()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: Owner transitions can remain blocked for the full database gzip despite cancelling the pipeline, delaying deletion/sign-out cleanup. Process.waitUntilExit() runs on this actor, so cancelForOwnerTransition() cannot increment the generation or cancel this task until that synchronous work returns; run compression off the actor (and make the process cancellable) before relying on this fence.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/Desktop/Sources/AgentVMService.swift, line 18:

<comment>Owner transitions can remain blocked for the full database gzip despite cancelling the pipeline, delaying deletion/sign-out cleanup. `Process.waitUntilExit()` runs on this actor, so `cancelForOwnerTransition()` cannot increment the generation or cancel this task until that synchronous work returns; run compression off the actor (and make the process cancellable) before relying on this fence.</comment>

<file context>
@@ -7,78 +7,94 @@ actor AgentVMService {
+  /// remain harmless because each continuation revalidates this generation.
+  func cancelForOwnerTransition() {
+    lifecycleGeneration &+= 1
+    pipelineTask?.cancel()
+    pipelineTask = nil
+    isRunning = false
</file context>

Comment thread backend/utils/other/endpoints.py Resolved
Comment thread backend/utils/other/endpoints.py Outdated
token = authorization.split(' ')[1]
return verify_token(token)
uid = verify_token(token)
_enforce_account_deletion_ws_access(uid)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: /v4/web/listen reports a deleted account as generic auth failure (1008), not the new 4005 deletion event. Catch WebSocketException before the generic handler there and close using its code and reason.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/other/endpoints.py, line 271:

<comment>`/v4/web/listen` reports a deleted account as generic auth failure (1008), not the new 4005 deletion event. Catch `WebSocketException` before the generic handler there and close using its code and reason.</comment>

<file context>
@@ -208,11 +267,15 @@ def _verify_ws_auth(authorization: str) -> str:
         token = authorization.split(' ')[1]
-        return verify_token(token)
+        uid = verify_token(token)
+        _enforce_account_deletion_ws_access(uid)
+        return uid
     except (InvalidIdTokenError, CertificateFetchError) as e:
</file context>

Comment thread desktop/macos/e2e/flows/logout.yaml Resolved
Comment thread backend/database/users.py Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 93c421cc9d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread backend/utils/other/endpoints.py Outdated
WS_AUTH_CODE_TOKEN_REFRESH = 4001
WS_AUTH_CODE_RELOGIN_REQUIRED = 4004
WS_AUTH_CODE_ACCOUNT_DELETION = 4005
ACCOUNT_DELETION_ACCESS_BLOCKING_STATUSES = frozenset({'deleting_auth', 'pending', 'retrying', 'running', 'failed'})

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep completed deletions behind the authentication fence

When the wipe reaches completed, this allowlist stops blocking the deleted UID, but verify_token calls auth.verify_id_token(token) without revocation checking; an ID token minted before Firebase Auth deletion can therefore remain cryptographically valid until expiry. During that window the deleted client can authenticate again and read or recreate owner-scoped data after the wipe. The durable deletion marker should continue denying access for completed records as well, including at the duplicated Agent proxy boundary.

Useful? React with 👍 / 👎.

Comment thread backend/utils/other/endpoints.py Outdated
logger.error(e)
raise HTTPException(status_code=401, detail="Invalid authorization token")

_enforce_account_deletion_http_access(uid)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Apply the deletion fence to every user authentication path

This enforcement only covers callers of utils.other.endpoints.get_current_user_uid, while several authenticated HTTP surfaces resolve the same UID elsewhere and never consult the marker. For example, dependencies.get_current_user_id directly verifies Firebase tokens for /v1/api-keys/* and /v1/mcp/oauth-grants, and the developer/MCP API-key dependencies return their stored user_id without this check; consequently a client can create credentials or continue owner-scoped API access while its marker is pending, running, or failed. Route every UID-bearing authentication dependency through the same deletion authority rather than fencing only this shared dependency.

Useful? React with 👍 / 👎.

Comment thread backend/utils/other/endpoints.py Outdated

return verify_token(token)
uid = verify_token(token)
_enforce_account_deletion_ws_access(uid)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Offload the deletion lookup in first-message WebSocket auth

For /v4/web/listen, transcribe.web_listen_handler calls this synchronous helper directly from the async handler, and the newly added enforcement performs a synchronous Firestore .get(). A slow or unavailable Firestore request during any web-listen handshake therefore blocks the process event loop, freezing existing transcription connections and health checks; make this first-message authentication path async or invoke the blocking verification and deletion lookup through run_blocking.

AGENTS.md reference: backend/AGENTS.md:L276-L285

Useful? React with 👍 / 👎.

Comment on lines +55 to +58
for artifact in [
"omi.db", "omi.db-wal", "omi.db-shm", ".omi_running",
"Screenshots", "Videos", "backups",
] {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Delete the anonymous legacy migration source as well

On the non-isolated production profile, old Rewind content can live under Omi/users/anonymous when initialization runs before the authenticated owner is configured; migrateFromLegacyPathIfNeeded explicitly treats that directory as a fallback source for the next non-anonymous UID. This cleanup removes the accepted owner's directory and only top-level legacy artifacts, leaving users/anonymous intact, so a later fresh UID can still inherit the deleted account's database, screenshots, videos, or backups. Remove that anonymous migration source at the accepted-deletion boundary too.

Useful? React with 👍 / 👎.

Comment thread backend/agent-proxy/main.py Outdated
return

try:
deletion_status = await run_blocking(db_executor, _get_account_deletion_status, uid)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Revoke agent sockets when deletion becomes actionable

The proxy reads the deletion marker only once during the WebSocket handshake. If an agent socket is already connected when /v1/users/delete-account commits the marker, the existing phone_to_vm and vm_to_phone relay loops continue accepting queries and persisting messages without another fence check, allowing owner data to be read or recreated while the wipe is running. Active sessions need to be closed or revalidated when the marker changes, not just rejected on their next connection attempt.

Useful? React with 👍 / 👎.

Comment thread backend/utils/other/endpoints.py Outdated

def _enforce_account_deletion_http_access(uid: str) -> None:
status = _account_deletion_status(uid)
if status in ACCOUNT_DELETION_ACCESS_BLOCKING_STATUSES:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve a recovery path for deleting_auth markers

If the intent write succeeds but the transactional promotion to pending fails or the process crashes before it, the record remains deleting_auth while the Firebase user still exists. This fence then blocks the user's retry of the delete endpoint, while reconcile_pending_deletion_wipes deliberately skips deleting_auth records whose Auth user still exists, leaving the account permanently authenticated but unable to access the backend or finish deletion. Keep ordinary access blocked, but allow the idempotent deletion request to resume that marker or make reconciliation safely promote this pre-worker state.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 47d8929e27

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread backend/routers/desktop_agent_vm.py Outdated
try:
ip = await _create_vm(project, source_image, bucket, vm_name, auth_token)
await run_blocking(db_executor, _set_vm, uid, vm_name, "ready", auth_token, _now(), ip)
await run_blocking(db_executor, _set_vm_if_current, uid, vm_name, auth_token, "ready", ip)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Claim provisioning ownership before creating the VM

When two /v2/agent/provision requests for a fresh UID overlap, both can pass _get_vm and write different tokens for the same deterministic VM name. If the first GCE creation succeeds after the second request's Firestore write, this compare-and-set returns false; the second creation then receives a conflict and records error with its token. Recovery can subsequently mark that record ready, but the VM still expects the first token, so connections remain unauthorized indefinitely. Claim the provisioning identity transactionally before launching the background creation rather than only fencing its completion.

AGENTS.md reference: AGENTS.md:L41-L45

Useful? React with 👍 / 👎.

// These actors retain pools, directories, encoders, or owner-derived
// values. Purge them while the transition reservation is still held so
// automation swaps and every auth path share the same hard boundary.
await AgentVMService.shared.cancelForOwnerTransition()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Cancel VM uploads before the storage transition

If account deletion begins while uploadDatabase is suspended in its up-to-600-second URLSession upload, this cancellation is not invoked until retargetLocalStorage, after prepareLocalStorageTransition has removed the old owner's directory and the transition closure has cleared credentials. The upload can therefore finish copying the deleted account's complete database to the VM after deletion was accepted; the generation check after the request returns cannot undo that remote write. Cancel and drain the owner-bound pipeline during the pre-transition quiescence phase instead.

AGENTS.md reference: AGENTS.md:L41-L45

Useful? React with 👍 / 👎.

Comment on lines +681 to +685
"type": "error",
"code": "agent_vm_not_ready",
"state": "not_provisioned",
"retryable": True,
"message": "Your agent is still being prepared. Please try again shortly.",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Buffer startup errors until a query consumer exists

For the no-VM path, the proxy sends this error immediately after accepting the socket and then closes it, before the mobile caller can issue a query. app/lib/services/agent_chat_service.dart installs its socket listener during connect(), but line 114 discards every non-init event while _eventController is null; that controller is created only by sendQuery(). Consequently this new typed retryable error is always lost, and fresh users still receive a generic disconnect/reconnect failure rather than the actionable readiness message. Preserve startup errors until sendQuery() can consume them or change the handshake so the server emits them after a client request.

Useful? React with 👍 / 👎.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

@cursor review

@cursor

cursor Bot commented Aug 2, 2026

Copy link
Copy Markdown

Skipping Bugbot: Bugbot is disabled for this repository. Visit the Bugbot dashboard to update your settings.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f2fe4eabc4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread backend/utils/other/endpoints.py Outdated
token = authorization.split(' ')[1]
return verify_token(token)
uid = verify_token(token)
_enforce_account_deletion_ws_access(uid)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Move deletion lookups out of the critical auth pool

When Firestore is slow or unavailable during a /v4/listen or chat WebSocket handshake, this newly added uncached document read runs inside _verify_ws_auth, whose caller submits the whole function to the eight-worker critical_executor. Eight stalled deletion lookups can therefore exhaust the auth bulkhead and queue unrelated token checks; verify the token on the critical pool, then perform the deletion lookup on db_executor.

AGENTS.md reference: backend/AGENTS.md:L289-L292

Useful? React with 👍 / 👎.

Comment on lines +152 to +160
guard
await uploadDatabase(
vmIP: ip,
authToken: status.authToken,
ownerID: ownerID,
generation: generation)
else {
log("AgentVMService: VM database is not ready; incremental sync remains stopped")
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Retry transient initial database uploads

When the health check reports databaseReady: false—or transiently fails and is treated as needing an upload—and uploadDatabase then returns false because the VM or network is temporarily unavailable, this new early return prevents AgentSyncService.start from running. That sync loop contains the in-session missing-schema re-upload recovery, while normal startup schedules ensureProvisioned only once, so a single transient upload failure leaves synchronization and repair stopped until another launch or provisioning trigger; retain a bounded retry path instead of terminating the lifecycle here.

Useful? React with 👍 / 👎.

}
do {
try await AuthService.shared.signOut()
try await AuthService.shared.signOut(acceptedAccountDeletion: true)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Persist accepted cleanup across sign-out failures

When the backend has accepted deletion but local preparation fails—for example because removing an owner or legacy directory encounters a transient I/O or permission error—signOut aborts before clearing credentials, and this caller only displays a quit-and-reopen message. No accepted-deletion state is persisted locally, and this is the sole call that passes acceptedAccountDeletion: true; after restart or a button retry the server fence returns 403, while ordinary sign-out passes false and preserves any remaining artifacts, so the promised cleanup can never resume. Persist the accepted cleanup intent and retry it independently of repeating the authenticated delete request.

AGENTS.md reference: AGENTS.md:L43-L43

Useful? React with 👍 / 👎.

Comment thread backend/routers/desktop_agent_vm.py Outdated
Comment on lines +431 to +433
instance_ip = _ip(instance)
if instance_ip is None:
return _response(pending)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Resolve running VMs that still lack an address

When GCE reports RUNNING but the instance has no usable natIP—for example after address assignment was absent during provisioning or an access configuration was removed—this branch returns a synthetic provisioning response without persisting any state or scheduling recovery. The underlying agentVm record therefore remains unchanged, every subsequent status poll takes the same branch, and the desktop gives up after its 30 attempts, leaving the agent permanently unavailable; transition the record to an actionable error/recreate state or repair the missing address instead of only synthesizing pending.

AGENTS.md reference: AGENTS.md:L43-L43

Useful? React with 👍 / 👎.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

@codex review

@Git-on-my-level

Copy link
Copy Markdown
Member Author

@cursor address merge conflict

@cursor

cursor Bot commented Aug 3, 2026 •

Copy link
Copy Markdown

Merge conflict resolved and pushed.

What conflicted: Only .github/scripts/product_file_line_count_ratchet_baseline/backend-routers.json — a line-count ratchet baseline, not RewindDatabase+AccountDeletion.swift (that file was already clean on the branch).

Resolution:

  • backend/routers/mcp_sse.py: 1897 (from this branch — matches the merged file and reflects the account-deletion auth fencing added here)
  • backend/routers/sync.py: 2053 (from main — matches the current file; the branch’s stale 2058 was dropped)

Done:

  • Merged origin/main into agent/m1-studio-nik-codex-sol-high/33032294
  • Committed: fb9fc0758c — merge: resolve main into account-deletion hardening branch
  • Pushed to origin

The PR should now be mergeable with main. All other incoming changes from main (desktop notification previews, sync contract updates, CI tweaks, etc.) merged cleanly without further conflicts.

Open in Web Open in Cursor 

Resolve backend-routers.json ratchet baseline conflict by keeping the
branch mcp_sse.py cap (1897) and main sync.py cap (2053), matching the
merged file line counts.

Co-authored-by: David Zhang <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 00ba6b603c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread backend/agent-proxy/main.py Outdated
Comment on lines +1143 to +1144
await asyncio.sleep(1)
if not await session_access_allowed():

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Avoid polling Firestore once per socket per second

With many concurrent agent sockets, this loop performs one uncached Firestore read per connection every second—86,400 reads per day for each continuously connected client. Because every poll also occupies the shared 24-worker db_executor, a sufficiently large active population can continuously saturate that pool, delaying deletion detection and starving VM lookups and message persistence; use a shared notification/listener mechanism or a substantially bounded polling strategy instead.

AGENTS.md reference: backend/AGENTS.md:L291-L291

Useful? React with 👍 / 👎.

}

private static func createConsistentSnapshot(sourcePool: DatabasePool, destination: URL) async throws {
try await Task.detached(priority: .utility) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Propagate owner-transition cancellation into the snapshot task

When account deletion or an owner switch cancels the pipeline during a large SQLite backup, cancelling the parent does not cancel this unstructured Task.detached, so Task.checkCancellation() inside the backup never observes the transition. cancelForOwnerTransition() then waits for the entire backup before it can delete local data or clear credentials, potentially leaving an already accepted deletion stuck for the duration; retain and cancel the detached task explicitly or perform the backup in cancellation-linked structured work.

Useful? React with 👍 / 👎.

Comment thread backend/database/users.py Outdated
access barrier on the very next request, and a cached pre-delete miss would
reopen the exact half-deleted-account window this marker closes.
"""
snapshot = db.collection('account_deletions').document(uid).get()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Use the injectable Firestore client in the new fence

This new authoritative authentication fence accesses the legacy global db proxy directly, so tests cannot inject a strict Firestore client and every authentication boundary becomes coupled to mutable global database state. Use get_firestore_client() at call time and accept the component-required keyword-only client seam for this helper.

AGENTS.md reference: backend/AGENTS.md:L193-L193

Useful? React with 👍 / 👎.

Comment thread backend/routers/desktop_agent_vm.py Outdated
await run_blocking(db_executor, _set_vm, uid, vm_name, "ready", auth_token, _now(), ip)
if not await run_blocking(db_executor, _vm_lifecycle_allowed, uid, vm_name, auth_token):
logger.warning("Deleting late-created Agent VM after deletion/owner transition for uid=%s", uid)
await _delete_vm(project, vm_name, _ZONE)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Retry deletion of late-created VMs

When deletion is admitted after the pre-create lifecycle check, the account-deletion worker can observe the claimed pointer, issue its DELETE before the instance materializes, and accept a 404; this post-create call is then the only remaining cleanup. If that GCE deletion fails transiently, the outer handler only records an error when _vm_lifecycle_allowed is still true—which it is not after deletion—so no durable retry remains, while the reaper explicitly never removes RUNNING instances. The resulting orphan can run indefinitely with provider credentials and the deleted client's static VM token, so late-created cleanup must be durably retried independently of lifecycle admission.

Useful? React with 👍 / 👎.

for grant in grants:
grant_id = grant.id
revoke_grant(grant_id)
for collection_name in ("mcp_oauth_access_tokens", "mcp_oauth_refresh_tokens"):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Delete OAuth authorization codes during the account wipe

For users who have completed an MCP OAuth consent flow, this cleanup deletes access and refresh tokens for each grant but never deletes mcp_oauth_authorization_codes, whose documents also contain the deleted UID, grant, client, scopes, and redirect URI. Removing the grant makes those codes unusable, but there is no other janitor for this collection, so account deletion leaves UID-bearing OAuth records indefinitely; include authorization-code documents in the credential purge.

Useful? React with 👍 / 👎.

Comment on lines +262 to +264
if (_pendingStartupEvents.isNotEmpty) {
final pending = List<AgentChatEvent>.of(_pendingStartupEvents);
_pendingStartupEvents.clear();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Clear buffered startup errors when replacing the socket

The new startup-event buffer survives connect(), disconnect(), and reconnect(), and is cleared only when sendQuery() consumes it. If the app's startup connection receives agent_vm_not_ready, then the VM becomes ready before the user sends a prompt, _sendMessageViaAgent opens a new successful connection but sendQuery() drains the stale error, closes its stream, and never sends the prompt; because the new socket is connected, the provider's disconnected-only retry does not run. Clear or generation-tag buffered events whenever the underlying socket is replaced.

Useful? React with 👍 / 👎.

# VM is RUNNING but agent process is dead — hard reset
logger.info(f"[agent-proxy] VM {vm_name} is RUNNING but unhealthy, resetting...")
await run_blocking(db_executor, _update_firestore_vm, uid, None, "provisioning")
await run_blocking(db_executor, _update_firestore_vm, uid, vm_name, vm_auth_token, None, "provisioning")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Handle deletion admission during VM startup repair

If the deletion marker is committed after the handshake check but while an unhealthy or stopped VM is being repaired, the newly transactional _update_firestore_vm raises AccountDeletionAccessBlocked here before entering the surrounding reset try. The calls to _ensure_vm_running occur before the handler's VM-session exception block, so this exception escapes an already accepted WebSocket as an ASGI failure instead of sending the typed deletion event and close code; catch it at the startup boundary and route it through _admit_account_access_or_close.

AGENTS.md reference: backend/AGENTS.md:L201-L201

Useful? React with 👍 / 👎.

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Closes the account-deletion re-login and Agent VM broken-state leaks with targeted tests — approve; not merging (red CI + touches OAuth/token paths, which needs your eyes).

…-fixes

# Conflicts:
#	.github/scripts/product_file_line_count_ratchet_baseline/backend-routers.json
#	.github/scripts/product_file_line_count_ratchet_baseline/desktop-swift-root.json

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 30064ce363

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread backend/database/users.py Outdated
db.collection('account_deletions').document(uid).set(
{
'late_agent_vm_cleanup': {'vmName': vm_name, 'zone': zone},
'wipe_status': 'failed',

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Make late-VM failure win over wipe completion

When the active deletion worker observes a pre-create 404 and continues wiping, a provisioning task can subsequently create the VM, fail its late DELETE, and write this failed state while the original worker is still running. That worker then unconditionally writes completed, overwriting failed while leaving late_agent_vm_cleanup behind; completed records are not reconciled, so the VM can remain running indefinitely. Fresh evidence is that the new durable retry write is not transactionally coordinated with mark_user_deletion_wipe_completed; completion must refuse to commit while a late cleanup is pending.

AGENTS.md reference: AGENTS.md:L41-L44

Useful? React with 👍 / 👎.

from dataclasses import dataclass
from typing import Any, Dict, cast

from utils.account_deletion_access import ACCOUNT_DELETION_ACCESS_BLOCKING_STATUSES

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep the deletion policy below the database layer

This new import reverses the repository's strict database → utils → routers dependency direction, and database/users.py additionally imports the same utils module from inside a function. Because these database modules are shared across multiple runtime images, the dependency inversion makes them vulnerable to utils/database import cycles; move the pure policy to a lower-level database/config module and keep all imports at module scope.

AGENTS.md reference: backend/AGENTS.md:L179-L187

Useful? React with 👍 / 👎.

Comment on lines +323 to +324
guard controller.install(process) else { throw CancellationError() }
try process.run()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Close the cancellation gap before launching gzip

If owner-transition cancellation arrives after controller.install(process) but before process.run(), cancel() sees isRunning == false and does nothing, after which this line launches gzip anyway and waits for the entire compression. Fresh evidence is the replacement controller's install-to-run gap, which still makes cancelForOwnerTransition() block on a large snapshot despite cancelling the pipeline; recheck cancellation immediately after launch or make launch and cancellation atomic.

Useful? React with 👍 / 👎.

Firestore calls are offloaded via ``run_blocking``.
"""
uid = await run_blocking(critical_executor, _verify_ws_auth, authorization)
await run_blocking(db_executor, enforce_account_deletion_ws_access, uid)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Revalidate deletion during active listen sessions

For /v4/listen and /v4/web/listen, this check runs only during the handshake; a socket authenticated just before deletion admission remains active afterward. The inspected listen runtime continues creating conversations and persisting transcript segments through LiveConversationController and TranscriptProcessor, so it can write owner data after the wipe has already deleted the user's subcollections and recreate that data before the worker records completion. Add a supervised deletion watcher or revalidate before persisted listen work and close the session when the marker becomes blocking.

AGENTS.md reference: backend/AGENTS.md:L309-L316

Useful? React with 👍 / 👎.

vm = users_db.get_agent_vm(uid) or users_db.get_late_agent_vm_cleanup(uid)
if not isinstance(vm, dict) or not vm.get('vmName'):
return
project = os.getenv('GCE_PROJECT_ID') or os.getenv('FIREBASE_PROJECT_ID') or os.getenv('GCP_PROJECT_ID')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Read the project variable deployed with the wipe worker

For production account deletion on the main backend, backend/charts/backend-listen/prod_omi_backend_listen_values.yaml supplies the project as GOOGLE_CLOUD_PROJECT, but this new cleanup accepts only three different variable names. Any deleting user with an agentVm therefore reaches this line with no project, repeatedly fails the worker before credentials, Firebase Auth, or user data are removed, and remains permanently fenced in failed; include GOOGLE_CLOUD_PROJECT or align the runtime manifest with this new requirement.

AGENTS.md reference: backend/AGENTS.md:L173-L173

Useful? React with 👍 / 👎.

"completed",
}
)
ACCOUNT_DELETION_PROJECTION_FENCE_STATUSES = ACCOUNT_DELETION_ACCESS_BLOCKING_STATUSES

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Fail closed for malformed projection-fence states

The shared HTTP policy deliberately blocks every existing marker except cancelled and billing_failed, including malformed markers and unknown future states, but this imported enumeration contains only today's six named blocking states. read_account_deletion_projection_fence consequently treats a marker with a missing/blank status or a newly introduced status as blocks_projection_writes=False, allowing the memory outbox and compatibility projections to republish deleted-user data while ordinary account access is correctly fenced. Share the fail-closed predicate or derive projection admission from the allowed-state set rather than membership in this finite list.

AGENTS.md reference: AGENTS.md:L41-L44

Useful? React with 👍 / 👎.

Centralize fail-closed deletion policy and transactional state transitions, fence late VM publication and active listen sessions, and make gzip launch cancellation atomic. Repair isolated backend fixtures and cover the review regressions.

Verification: OMI_PR_BODY_FILE=/tmp/omi-pr-11029-body.md scripts/pre-push

Verification: xcrun swift test -c debug --package-path Desktop --filter AgentVMLifecycleFenceTests

Failure-Class: none

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1ff15af695

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines 377 to +380
except Exception as exc:
logger.error("Agent VM provisioning failed for uid=%s: %s", uid, exc)
await run_blocking(db_executor, _set_vm, uid, vm_name, "error", auth_token, _now())
if await run_blocking(db_executor, _vm_lifecycle_allowed, uid, vm_name, auth_token):
await run_blocking(db_executor, _set_vm_if_current, uid, vm_name, auth_token, "error")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Record late VMs when creation exits with an error

If GCE accepts the create request but _create_vm later raises while polling the operation or resolving its IP, and account deletion is admitted in the meantime, this exception path skips both _delete_late_vm_or_record and the Firestore error update because _vm_lifecycle_allowed is false. The deletion worker may already have accepted a pre-materialization 404, allowing the VM to appear afterward and run indefinitely without a durable cleanup record. Fresh evidence is that late cleanup now covers only successful _create_vm returns; persist or delete the possibly-created instance on this failure path too.

AGENTS.md reference: AGENTS.md:L43-L44

Useful? React with 👍 / 👎.

Comment on lines +64 to +67
done, pending = await asyncio.wait((session, deletion_watcher), return_when=asyncio.FIRST_COMPLETED)
for task in pending:
task.cancel()
await asyncio.gather(*pending, return_exceptions=True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Fence listen teardown writes after deletion cancellation

When this watcher detects deletion during an active conversation, cancelling the production run_listen_session executes ListenSessionRuntime._teardown() in its finally block; that teardown still flushes usage, speaker assignments, and calls process_conversation without rechecking the deletion marker. If finalization finishes after the wipe has removed Firestore data, it can recreate owner-scoped records after deletion completion. Fresh evidence is that the new regression test substitutes a trivial cancellation-only session and therefore does not exercise this production teardown path; route teardown persistence through the deletion authority or suppress it for this cancellation reason.

AGENTS.md reference: AGENTS.md:L43-L45

Useful? React with 👍 / 👎.

Comment thread backend/routers/mcp_sse.py Outdated
Comment on lines +1653 to +1658
await run_blocking(db_executor, enforce_account_deletion_http_access, uid)

grant = await run_blocking(db_executor, mcp_oauth_db.create_or_update_grant, uid, client_id, resource, scopes)
code = await run_blocking(
db_executor,
mcp_oauth_db.issue_authorization_code,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Make OAuth consent writes atomic with the deletion fence

If deletion is admitted after the standalone fence check—or after the grant is created but before the code is issued—the wipe can finish delete_user_oauth_credentials and then this request can create a new grant or UID-bearing authorization code. That record is outside users/{uid} and no later cleanup scans completed markers, so account deletion leaves OAuth data behind indefinitely. Fresh evidence is that the new credential purge and these two writes are not transactionally coordinated; check the marker in the same transaction that creates the grant and code.

AGENTS.md reference: AGENTS.md:L43-L44

Useful? React with 👍 / 👎.

Comment on lines +17 to +24
if isinstance(raw_status, str) and raw_status.strip():
return raw_status.strip()
return ACCOUNT_DELETION_INVALID_STATUS


def account_deletion_blocks_access(status: str | None) -> bool:
"""Deny every existing marker unless its state explicitly restores access."""
return status is not None and status not in ACCOUNT_DELETION_ACCESS_ALLOWED_STATUSES

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Avoid fencing feedback-only deletion records

When a deletion request includes feedback, set_user_deletion_feedback creates account_deletions/{uid} before the actionable intent transaction. If that subsequent transaction exhausts its retries, this policy converts the feedback-only document's missing wipe_status into a blocking state: every authenticated retry receives 403, while reconciliation only queries named lifecycle statuses and will never repair the document. The user is therefore permanently locked out even though deletion was never admitted; write feedback and intent atomically or distinguish non-authoritative feedback-only records.

AGENTS.md reference: AGENTS.md:L43-L44

Useful? React with 👍 / 👎.

Fence OAuth consent and listen teardown writes behind durable deletion authority, make Agent VM generations cleanup-safe, and persist deletion intent before feedback.

Tests: 54 focused backend tests; 38 account-deletion service tests; DesktopAutomationSecondaryActionTests/testSignOutRequiresLocalAuthProfile; make preflight; backend typecheck.

Failure-Class: none
@Git-on-my-level

Copy link
Copy Markdown
Member Author

@cursor address merge conflict

@cursor

cursor Bot commented Aug 4, 2026 •

Copy link
Copy Markdown

Merge conflicts are resolved and pushed. The branch is now up to date with main.

Conflicts resolved

  1. .github/scripts/product_file_line_count_ratchet_baseline/backend-routers.json

    • mcp_sse.py: 1903 (merged file count)
    • users.py: 2086 (from main, webhook repair)
  2. .github/scripts/product_file_line_count_ratchet_baseline/desktop-swift-root.json

    • DesktopAutomationBridge.swift: 4467 (merged file count)
    • Combined raise justifications from both branches (account-deletion cleanup + Gmail/Calendar probe coverage)

Commits pushed

  • f805b274ad — merge main ratchet baselines
  • bfdee95df4 — reconcile with remote branch updates

Status: git merge origin/main reports "Already up to date" — the PR should be mergeable with main now.

Open in Web Open in Cursor 

cursoragent and others added 2 commits August 4, 2026 17:18
Keep merged file line counts for backend-routers and desktop-swift-root
ratchet shards, and combine raise justifications from both branches.

Co-authored-by: David Zhang <[email protected]>
Keep DesktopAutomationBridge.swift at 4467 to match the merged file after
integrating upstream main and remote branch updates.

Co-authored-by: David Zhang <[email protected]>
@Git-on-my-level
Git-on-my-level merged commit 2670d65 into main Aug 4, 2026
39 checks passed
@Git-on-my-level
Git-on-my-level deleted the agent/m1-studio-nik-codex-sol-high/33032294 branch August 4, 2026 20:20
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.

3 participants