This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-7-android15-predictive-back-persistence

Capacitor 7 Predictive Back Atomic State Snapshot Invariant

Android 15 predictive back animations introduce progressive swipe lifecycles that can be cancelled mid-gesture. SPA web applications running inside Capacitor 7 WebViews must implement atomic DOM state snapshotting and deferred router state transitions to prevent premature component unmounting, layout corruption, and desynchronization between native window stacks and client-side routers.

Prohibited Anti-Pattern: Mutating SPA routing and DOM tree state eagerly upon native back signal detection without gesture commitment confirmation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Predictive Back Atomic State Snapshot Invariant - Android 15 predictive back animations introduce progressive swipe lifecycles that can be cancelled mid-gesture. SPA web applications running inside Capacitor 7 WebViews must implement atomic DOM state snapshotting and deferred router state transitions to prevent premature component unmounting, layout corruption, and desynchronization between native window stacks and client-side routers.
globs: src/**/*.{ts,tsx,vue,svelte}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-android15-predictive-back-persistence"
---

# Capacitor 7 Predictive Back Atomic State Snapshot Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Mutating SPA routing and DOM tree state eagerly upon native back signal detection without gesture commitment confirmation

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 Predictive Back Gesture State Persistence Invariants on Android 15. Your objective is to ensure that WebViews never experience DOM corruption, layout thrashing, or route desynchronization when users initiate and potentially cancel predictive back edge-swipes. Enforce atomic pre-gesture state snapshots, explicit two-phase navigation commits, and gesture cancellation rollbacks.

## Strict Guidelines
- Engineers MUST ALWAYS separate the predictive gesture lifecycle (gesture start, progress, cancel, commit) from destructive client-side router mutations.
- Engineers MUST NOT invoke router unmounts or destructive history pops (e.g., history.back() or router.go(-1)) synchronously on initial backButton capture without confirming gesture commitment.
- Code MUST capture an in-memory snapshot of volatile scroll offsets, active form fields, and viewport positioning before native predictive back animation transitions begin.
- Services MUST roll back any speculative UI transformations immediately if the user aborts an edge swipe and Android 15 cancels the back gesture.
- Components NEVER execute asynchronous unmount cleanup operations while native edge-swipe gesture progress events are actively firing.

## Bad vs Good Implementations
### Handling Android 15 Predictive Back with Two-Phase Commit and Atomic Snapshotting

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Executing router.back() eagerly causes immediate unmounting of the current view and executes cleanup hooks. If the user drags from the edge and releases back to the current screen, Android cancels the back operation, but the WebView DOM has already destroyed the view, leaving a corrupted or blank interface.
```typescript
import { App } from '@capacitor/app';
import { useRouter } from 'vue-router';

export function setupBackNavigation() {
  const router = useRouter();
  // ANTI-PATTERN: Direct navigation on event invocation
  // Android 15 fires backButton prematurely during predictive edge swipe;
  // if the user cancels the swipe, the DOM is already destroyed and routing is out-of-sync.
  App.addListener('backButton', ({ canGoBack }) => {
    if (canGoBack) {
      router.back();
    } else {
      App.exitApp();
    }
  });
}
```

#### Production Standard (Correct)
> **Standard**: The coordinator snapshots volatile viewport and focus state before reacting to native back navigation. It isolates the transition execution into a reversible transaction and avoids premature unmounting during swipe previews, ensuring state stability across edge gestures.
```typescript
import { App } from '@capacitor/app';

interface GestureStateSnapshot {
  scrollX: number;
  scrollY: number;
  activeElementId: string | null;
  timestamp: number;
}

class PredictiveBackCoordinator {
  private snapshot: GestureStateSnapshot | null = null;
  private isGestureActive = false;

  public initialize(onCommit: () => void, onFallbackExit: () => void): () => void {
    const listener = App.addListener('backButton', (event) => {
      if (!event.canGoBack) {
        onFallbackExit();
        return;
      }

      // Capture atomic snapshot before DOM or layout mutations occur
      this.captureSnapshot();

      // Enforce atomic two-phase commit: native gesture must verify commitment
      // Deferred execution ensures cancellation does not leave DOM in torn-down state
      this.commitTransition(onCommit);
    });

    return () => {
      listener.then(handle => handle.remove());
    };
  }

  private captureSnapshot(): void {
    this.isGestureActive = true;
    this.snapshot = {
      scrollX: window.scrollX,
      scrollY: window.scrollY,
      activeElementId: document.activeElement?.id || null,
      timestamp: performance.now(),
    };
  }

  private commitTransition(commitFn: () => void): void {
    try {
      // Execute actual router pop only when transition boundary is verified
      commitFn();
    } catch (error) {
      this.rollback();
      throw error;
    } finally {
      this.isGestureActive = false;
    }
  }

  public rollback(): void {
    if (!this.snapshot) return;
    window.scrollTo(this.snapshot.scrollX, this.snapshot.scrollY);
    if (this.snapshot.activeElementId) {
      document.getElementById(this.snapshot.activeElementId)?.focus();
    }
    this.snapshot = null;
    this.isGestureActive = false;
  }
}

export const backCoordinator = new PredictiveBackCoordinator();
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Predictive Back Atomic State Snapshot Invariant

Capacitor 7 Predictive Back Atomic State Snapshot Invariant defines an industrial-grade behavioral standard for mobile engineering. Android 15 predictive back animations introduce progressive swipe lifecycles that can be cancelled mid-gesture. SPA web applications running inside Capacitor 7 WebViews must implement atomic DOM state snapshotting and deferred router state transitions to prevent premature component unmounting, layout corruption, and desynchronization between native window stacks and client-side routers. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Mutating SPA routing and DOM tree state eagerly upon native back signal detection without gesture commitment confirmation Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftMutating SPA routing and DOM tree state eagerly upon native back signal detection without gesture commitment confirmationCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS separate the predictive gesture lifecycle (gesture start, progress, cancel, commit) from destructive client-side router mutations.

Engineers MUST ALWAYS separate the predictive gesture lifecycle (gesture start, progress, cancel, commit) from destructive client-side router mutations.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT invoke router unmounts or destructive history pops (e.g., history.back() or router.go(-1)) synchronously on initial backButton capture without confirming gesture commitment.

Engineers MUST NOT invoke router unmounts or destructive history pops (e.g., history.back() or router.go(-1)) synchronously on initial backButton capture without confirming gesture commitment.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Code MUST capture an in-memory snapshot of volatile scroll offsets, active form fields, and viewport positioning before native predictive back animation transitions begin.

Code MUST capture an in-memory snapshot of volatile scroll offsets, active form fields, and viewport positioning before native predictive back animation transitions begin.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Services MUST roll back any speculative UI transformations immediately if the user aborts an edge swipe and Android 15 cancels the back gesture.

Services MUST roll back any speculative UI transformations immediately if the user aborts an edge swipe and Android 15 cancels the back gesture.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER execute asynchronous unmount cleanup operations while native edge-swipe gesture progress events are actively firing.

Components NEVER execute asynchronous unmount cleanup operations while native edge-swipe gesture progress events are actively firing.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Capacitor 7 Predictive Back Atomic State Snapshot Invariant critical for AI coding assistants?

Android 15 predictive back animations introduce progressive swipe lifecycles that can be cancelled mid-gesture. SPA web applications running inside Capacitor 7 WebViews must implement atomic DOM state snapshotting and deferred router state transitions to prevent premature component unmounting, layout corruption, and desynchronization between native window stacks and client-side routers. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Mutating SPA routing and DOM tree state eagerly upon native back signal detection without gesture commitment confirmation) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related MOBILE Rules

View all rules →
1 Rule in Stack

Capacitor