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

Capacitor 7 Predictive Back Gesture Navigation Decoupling Invariant

Enforces strict transactional synchronization between native Android 15 OnBackInvokedCallback animations and the hybrid WebView routing state machine. Prevents deadlocked transitions, history desynchronization, and blank screen rendering caused by asynchronous bridge latency during predictive back gestures in Capacitor 7 applications.

Prohibited Anti-Pattern: Unsynchronized Async BackButton Bridge Handlers Causing Dropped Frames, Blank Views, or Routing Desynchronization During Native Predictive Back

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Predictive Back Gesture Navigation Decoupling Invariant - Enforces strict transactional synchronization between native Android 15 OnBackInvokedCallback animations and the hybrid WebView routing state machine. Prevents deadlocked transitions, history desynchronization, and blank screen rendering caused by asynchronous bridge latency during predictive back gestures in Capacitor 7 applications.
globs: src/**/*.{ts,tsx,js,jsx}, android/app/src/main/res/values/styles.xml, android/app/src/main/AndroidManifest.xml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-predictive-back-decoupling-invariant"
---

# Capacitor 7 Predictive Back Gesture Navigation Decoupling Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unsynchronized Async BackButton Bridge Handlers Causing Dropped Frames, Blank Views, or Routing Desynchronization During Native Predictive Back

## System Constraints
You are a Principal Mobile Architect enforcing the Capacitor 7 Predictive Back Gesture Navigation Decoupling Invariant. Android 15 enables predictive back animations system-wide by default, driving OnBackAnimationCallback frames at 120Hz. You must prevent asynchronous bridge callbacks from desynchronizing router state, causing blank screen flashes, or triggering simultaneous native finish and SPA route pops.

## Strict Guidelines
- Engineers MUST ALWAYS maintain an atomic, synchronous in-memory navigation stack state in the WebView to evaluate `canGoBack()` synchronously before native gesture commitment.
- Engineers MUST NOT execute raw asynchronous router navigations directly inside `App.addListener('backButton')` without acquiring a transactional navigation lock.
- Services MUST explicitly notify the native bridge via Capacitor plugins or custom bridge interfaces when the in-app history stack transitions between root and nested states.
- Components NEVER attach uncontrolled, non-cleanup listeners to `App.addListener('backButton')` at the screen level; back navigation dispatching MUST be centralized in a dedicated Navigation Coordinator.
- Code SHOULD gracefully degrade to native system activity popping when the atomic WebView navigation stack depth is zero or at root level.

## Bad vs Good Implementations
### Predictive Back Navigation Coordination

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly handling backButton asynchronously without coordinating with the native Android 15 predictive back dispatcher causes race conditions. The native OS completes the predictive dismiss gesture while the bridge is awaiting execution, corrupting the router state and leaving an empty/blank WebView.
```typescript
import { App } from '@capacitor/app';
import { createBrowserHistory } from 'history';

const history = createBrowserHistory();

// Anti-pattern: Asynchronous back listener without state sync or gesture locking.
// Android 15 predictive back will commit/cancel native animation before this bridge promise resolves,
// leading to a blank screen or dual-pop (SPA pops router AND Android closes activity).
App.addListener('backButton', async ({ canGoBack }) => {
  if (canGoBack) {
    await new Promise((resolve) => setTimeout(resolve, 50)); // Simulated async bridge latency
    history.back();
  } else {
    App.exitApp();
  }
});
```

#### Production Standard (Correct)
> **Standard**: Implements an atomic lock (`isTransitioning`) and a synchronous representation of route depth to prevent re-entrant back gestures. Accurately coordinates route popping with the native finish lifecycle, eliminating race conditions during Android 15 predictive back animations.
```typescript
import { App, PluginListenerHandle } from '@capacitor/app';

interface NavigationCoordinatorState {
  depth: number;
  isTransitioning: boolean;
}

export class PredictiveBackCoordinator {
  private state: NavigationCoordinatorState = {
    depth: 0,
    isTransitioning: false,
  };
  private backHandler?: PluginListenerHandle;

  constructor(
    private readonly routerPop: () => Promise<boolean>,
    private readonly onExit: () => void
  ) {}

  public async initialize(): Promise<void> {
    this.backHandler = await App.addListener('backButton', () => {
      this.handleBackInvocation();
    });
  }

  public setDepth(depth: number): void {
    this.state.depth = Math.max(0, depth);
  }

  private handleBackInvocation(): void {
    // Reject re-entrant invocations during active transitions
    if (this.state.isTransitioning) {
      return;
    }

    if (this.state.depth <= 0) {
      this.onExit();
      return;
    }

    this.state.isTransitioning = true;

    // Execute pop transaction synchronously with state lock
    this.routerPop()
      .then((popped) => {
        if (popped) {
          this.state.depth = Math.max(0, this.state.depth - 1);
        } else {
          this.onExit();
        }
      })
      .catch(() => {
        this.onExit();
      })
      .finally(() => {
        this.state.isTransitioning = false;
      });
  }

  public async destroy(): Promise<void> {
    if (this.backHandler) {
      await this.backHandler.remove();
    }
  }
}
```

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 Gesture Navigation Decoupling Invariant

Capacitor 7 Predictive Back Gesture Navigation Decoupling Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces strict transactional synchronization between native Android 15 OnBackInvokedCallback animations and the hybrid WebView routing state machine. Prevents deadlocked transitions, history desynchronization, and blank screen rendering caused by asynchronous bridge latency during predictive back gestures in Capacitor 7 applications. 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: Unsynchronized Async BackButton Bridge Handlers Causing Dropped Frames, Blank Views, or Routing Desynchronization During Native Predictive Back 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 DriftUnsynchronized Async BackButton Bridge Handlers Causing Dropped Frames, Blank Views, or Routing Desynchronization During Native Predictive BackCritical
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 maintain an atomic, synchronous in-memory navigation stack state in the WebView to evaluate `canGoBack()` synchronously before native gesture commitment.

Engineers MUST ALWAYS maintain an atomic, synchronous in-memory navigation stack state in the WebView to evaluate `canGoBack()` synchronously before native 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.
2

Engineers MUST NOT execute raw asynchronous router navigations directly inside `App.addListener('backButton')` without acquiring a transactional navigation lock.

Engineers MUST NOT execute raw asynchronous router navigations directly inside `App.addListener('backButton')` without acquiring a transactional navigation lock.

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

Services MUST explicitly notify the native bridge via Capacitor plugins or custom bridge interfaces when the in-app history stack transitions between root and nested states.

Services MUST explicitly notify the native bridge via Capacitor plugins or custom bridge interfaces when the in-app history stack transitions between root and nested states.

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

Components NEVER attach uncontrolled, non-cleanup listeners to `App.addListener('backButton')` at the screen level

Components NEVER attach uncontrolled, non-cleanup listeners to `App.addListener('backButton')` at the screen level; back navigation dispatching MUST be centralized in a dedicated Navigation Coordinator.

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

Code SHOULD gracefully degrade to native system activity popping when the atomic WebView navigation stack depth is zero or at root level.

Code SHOULD gracefully degrade to native system activity popping when the atomic WebView navigation stack depth is zero or at root level.

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 Gesture Navigation Decoupling Invariant critical for AI coding assistants?

Enforces strict transactional synchronization between native Android 15 OnBackInvokedCallback animations and the hybrid WebView routing state machine. Prevents deadlocked transitions, history desynchronization, and blank screen rendering caused by asynchronous bridge latency during predictive back gestures in Capacitor 7 applications. 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 (Unsynchronized Async BackButton Bridge Handlers Causing Dropped Frames, Blank Views, or Routing Desynchronization During Native Predictive Back) 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