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

Capacitor 7 Main-Thread JNI Decoupling & Background Task Standard

Enforces non-blocking native bridge execution boundaries and managed OS background task lifecycles in Capacitor 7. Eliminates UI thread deadlocks, Android Application Not Responding (ANR) violations, and iOS Watchdog (0x8badf00d) terminations caused by synchronous JNI/bridge executions during heavy workloads and background transitions.

Prohibited Anti-Pattern: Executing heavy bridge operations synchronously on native UI threads without background task assertions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Main-Thread JNI Decoupling & Background Task Standard - Enforces non-blocking native bridge execution boundaries and managed OS background task lifecycles in Capacitor 7. Eliminates UI thread deadlocks, Android Application Not Responding (ANR) violations, and iOS Watchdog (0x8badf00d) terminations caused by synchronous JNI/bridge executions during heavy workloads and background transitions.
globs: src/**/*.{ts,tsx}, android/app/src/main/java/**/*.java, android/app/src/main/kotlin/**/*.kt, ios/App/App/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-jni-decoupling-background-task-standard"
---

# Capacitor 7 Main-Thread JNI Decoupling & Background Task Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Executing heavy bridge operations synchronously on native UI threads without background task assertions

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 native bridge invariants. Mandate strict UI thread decoupling across the Web-to-Native bridge: all custom native plugin methods executing I/O, heavy computation, or JNI operations must dispatch to background worker threads, and client-side bridge invocations occurring across lifecycle transitions must acquire explicit OS background execution leases with strict timeouts.

## Strict Guidelines
- Engineers MUST ALWAYS wrap native bridge invocations initiated during background transitions inside explicit background task assertions (e.g., native beginBackgroundTask or @capacitor/app background state handlers) with fail-safe timeouts.
- Engineers MUST NOT execute heavy native JNI bridge invocations or synchronous disk/network I/O on the native UI/Main thread (Android MainLooper / iOS MainQueue).
- Native plugin implementations MUST dispatch heavy work via `bridge.executeOnBackgroundThread` (Android) or `DispatchQueue.global()` (iOS) before posting results back to PluginCall.
- Frontend bridge consumers MUST implement deterministic timeout boundaries and AbortController signals for every long-running plugin call to prevent hanging promise chains in WebKit.
- Components NEVER trigger synchronous native bridge calls directly within React/Vue render cycles or high-frequency frame events (e.g., scroll, requestAnimationFrame).

## Bad vs Good Implementations
### Decoupled Background Bridge Synchronization with Fail-Safe Timeout

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Awaiting unmanaged, sequential bridge calls during app backgrounding blocks the native lifecycle delegate. iOS kills the app within seconds (Watchdog termination 0x8badf00d), and Android risks bridge disconnection and ANRs.
```typescript
import { App } from '@capacitor/app';
import { Filesystem } from '@capacitor/filesystem';
import { DataSyncPlugin } from './plugins/data-sync';

// ANTI-PATTERN: Direct heavy bridge execution on background transition without task lease or timeout
App.addListener('appStateChange', async ({ isActive }) => {
  if (!isActive) {
    // Synchronously invoking heavy bridge calls during backgrounding causes OS termination (0x8badf00d / ANR)
    const cache = await Filesystem.readFile({ path: 'pending_sync.json' });
    await DataSyncPlugin.uploadPendingRecords({ payload: cache.data });
  }
});
```

#### Production Standard (Correct)
> **Standard**: Acquires a native OS background lease, establishes a hard deadline via AbortController, and guarantees resource cleanup in the finally block before OS-enforced termination.
```typescript
import { App } from '@capacitor/app';
import { Filesystem } from '@capacitor/filesystem';
import { DataSyncPlugin } from './plugins/data-sync';

const BACKGROUND_SYNC_TIMEOUT_MS = 25000;

App.addListener('appStateChange', async ({ isActive }) => {
  if (isActive) return;

  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), BACKGROUND_SYNC_TIMEOUT_MS);

  let taskId: string | null = null;
  try {
    // Acquire OS background execution lease via Capacitor native bridge boundary
    const lease = await DataSyncPlugin.beginBackgroundLease();
    taskId = lease.taskId;

    const cache = await Filesystem.readFile({ path: 'pending_sync.json' });
    
    // Execute decoupled background sync with strict timeout enforcement
    await Promise.race([
      DataSyncPlugin.uploadPendingRecords({
        payload: cache.data,
        taskId: lease.taskId
      }),
      new Promise((_, reject) => {
        controller.signal.addEventListener('abort', () => {
          reject(new Error('Background execution lease exceeded timeout'));
        });
      })
    ]);
  } catch (error) {
    console.error('Safe background sync failure / deadline reached:', error);
  } finally {
    clearTimeout(timeoutId);
    if (taskId) {
      // Mandatory release of OS execution assertion to prevent watchdog slaughter
      await DataSyncPlugin.endBackgroundLease({ taskId });
    }
  }
});
```

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 Main-Thread JNI Decoupling & Background Task Standard

Capacitor 7 Main-Thread JNI Decoupling & Background Task Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces non-blocking native bridge execution boundaries and managed OS background task lifecycles in Capacitor 7. Eliminates UI thread deadlocks, Android Application Not Responding (ANR) violations, and iOS Watchdog (0x8badf00d) terminations caused by synchronous JNI/bridge executions during heavy workloads and background transitions. 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: Executing heavy bridge operations synchronously on native UI threads without background task assertions 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 DriftExecuting heavy bridge operations synchronously on native UI threads without background task assertionsCritical
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 wrap native bridge invocations initiated during background transitions inside explicit background task assertions (e.g., native beginBackgroundTask or @capacitor/app background state handlers) with fail-safe timeouts.

Engineers MUST ALWAYS wrap native bridge invocations initiated during background transitions inside explicit background task assertions (e.g., native beginBackgroundTask or @capacitor/app background state handlers) with fail-safe timeouts.

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 heavy native JNI bridge invocations or synchronous disk/network I/O on the native UI/Main thread (Android MainLooper / iOS MainQueue).

Engineers MUST NOT execute heavy native JNI bridge invocations or synchronous disk/network I/O on the native UI/Main thread (Android MainLooper / iOS MainQueue).

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

Native plugin implementations MUST dispatch heavy work via `bridge.executeOnBackgroundThread` (Android) or `DispatchQueue.global()` (iOS) before posting results back to PluginCall.

Native plugin implementations MUST dispatch heavy work via `bridge.executeOnBackgroundThread` (Android) or `DispatchQueue.global()` (iOS) before posting results back to PluginCall.

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

Frontend bridge consumers MUST implement deterministic timeout boundaries and AbortController signals for every long-running plugin call to prevent hanging promise chains in WebKit.

Frontend bridge consumers MUST implement deterministic timeout boundaries and AbortController signals for every long-running plugin call to prevent hanging promise chains in WebKit.

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 trigger synchronous native bridge calls directly within React/Vue render cycles or high-frequency frame events (e.g., scroll, requestAnimationFrame).

Components NEVER trigger synchronous native bridge calls directly within React/Vue render cycles or high-frequency frame events (e.g., scroll, requestAnimationFrame).

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 Main-Thread JNI Decoupling & Background Task Standard critical for AI coding assistants?

Enforces non-blocking native bridge execution boundaries and managed OS background task lifecycles in Capacitor 7. Eliminates UI thread deadlocks, Android Application Not Responding (ANR) violations, and iOS Watchdog (0x8badf00d) terminations caused by synchronous JNI/bridge executions during heavy workloads and background transitions. 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 (Executing heavy bridge operations synchronously on native UI threads without background task assertions) 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