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

Capacitor 7 Native Bridge Thread Concurrency Invariant

Mandates asynchronous background worker offloading for all custom native Capacitor 7 plugin implementations to prevent native main UI thread starvation. Heavy file operations, cryptographic calculations, database transactions, and network I/O must execute on dedicated background queues or coroutine dispatchers before resolving back through the Capacitor bridge.

Prohibited Anti-Pattern: Executing Blocking I/O or Compute Directly on the Native UI/Main Dispatch Thread in Capacitor Plugins

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Native Bridge Thread Concurrency Invariant - Mandates asynchronous background worker offloading for all custom native Capacitor 7 plugin implementations to prevent native main UI thread starvation. Heavy file operations, cryptographic calculations, database transactions, and network I/O must execute on dedicated background queues or coroutine dispatchers before resolving back through the Capacitor bridge.
globs: ios/App/**/*.swift, android/app/**/*.kt, android/app/**/*.java, src/plugins/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-native-bridge-thread-concurrency-invariant"
---

# Capacitor 7 Native Bridge Thread Concurrency Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Executing Blocking I/O or Compute Directly on the Native UI/Main Dispatch Thread in Capacitor Plugins

## System Constraints
You are a Principal Mobile Architect enforcing the Capacitor 7 Native Bridge Thread Concurrency Invariant. Mandate that all custom native Capacitor 7 plugin methods execute non-trivial work off the main UI dispatch thread (Android UI Thread and iOS DispatchQueue.main). Require explicit background dispatching via Kotlin Coroutines (Dispatchers.IO) on Android and Grand Central Dispatch (DispatchQueue.global) or Swift Structured Concurrency (Task.detached) on iOS, returning bridge results asynchronously to maintain 60/120 FPS frame budgets and prevent ANRs.

## Strict Guidelines
- Engineers MUST ALWAYS offload disk I/O, SQLite operations, image processing, and network calls inside Capacitor native plugins to background execution contexts (DispatchQueue.global or Dispatchers.IO).
- Engineers MUST NOT invoke synchronous file read/write operations or long-running computations directly on the thread executing @PluginMethod / @objc plugin hooks.
- Code SHOULD leverage Swift structured concurrency (Task.detached(priority: .userInitiated)) or Kotlin Coroutines (CoroutineScope(Dispatchers.IO).launch) when implementing native plugin handlers.
- Services MUST ensure CAPPluginCall.resolve() or CAPPluginCall.reject() can be invoked thread-safely without re-dispatching back to the main UI thread unless manipulating native UI views directly.
- Components NEVER block the WebView JavaScript evaluation thread awaiting synchronous native bridge telemetry.

## Bad vs Good Implementations
### Swift (iOS) Capacitor 7 Plugin Thread Offloading

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Reading large files synchronously inside the plugin method blocks the calling dispatch queue, which in iOS Capacitor plugins can tie up the main UI thread, causing frame drops and unresponsive touch interactions.
```swift
import Foundation
import Capacitor

@objc(FileSystemPlugin)
public class FileSystemPlugin: CAPPlugin, CAPBridgedPlugin {
    public let identifier = "FileSystemPlugin"
    public let jsName = "FileSystem"
    public let pluginMethods: [CAPPluginMethod] = [
        CAPPluginMethod(name: "hashLargeFile", returnType: CAPPluginReturnPromise)
    ]

    @objc func hashLargeFile(_ call: CAPPluginCall) {
        guard let filePath = call.getString("path") else {
            call.reject("Path required")
            return
        }
        // VIOLATION: Executing synchronous, blocking I/O directly on the calling thread (often Main UI)
        let url = URL(fileURLWithPath: filePath)
        if let data = try? Data(contentsOf: url) {
            let hash = data.base64EncodedString() // Simulating heavy digest
            call.resolve(["hash": hash])
        } else {
            call.reject("File read failed")
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: The file read and hashing operation is explicitly dispatched to a background thread pool (DispatchQueue.global(qos: .userInitiated)), leaving the main thread unblocked. Capacitor thread-safely resolves the call from the background worker.
```swift
import Foundation
import Capacitor

@objc(FileSystemPlugin)
public class FileSystemPlugin: CAPPlugin, CAPBridgedPlugin {
    public let identifier = "FileSystemPlugin"
    public let jsName = "FileSystem"
    public let pluginMethods: [CAPPluginMethod] = [
        CAPPluginMethod(name: "hashLargeFile", returnType: CAPPluginReturnPromise)
    ]

    @objc func hashLargeFile(_ call: CAPPluginCall) {
        guard let filePath = call.getString("path") else {
            call.reject("Path required")
            return
        }
        // COMPLIANT: Offload blocking I/O to QoS background worker pool
        DispatchQueue.global(qos: .userInitiated).async {
            let url = URL(fileURLWithPath: filePath)
            do {
                let data = try Data(contentsOf: url, options: .mappedIfSafe)
                let hash = data.base64EncodedString()
                call.resolve(["hash": hash])
            } catch {
                call.reject("File read failed: \(error.localizedDescription)")
            }
        }
    }
}
```

### Kotlin (Android) Capacitor 7 Plugin Coroutine Dispatch

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Performing synchronous disk writes directly in the @PluginMethod body stalls the Android thread executing the plugin call, which can lead to Application Not Responding (ANR) events under load.
```kotlin
package com.example.plugins

import com.getcapacitor.Plugin
import com.getcapacitor.PluginCall
import com.getcapacitor.PluginMethod
import com.getcapacitor.annotation.CapacitorPlugin
import java.io.File

@CapacitorPlugin(name = "DataStore")
class DataStorePlugin : Plugin() {
    @PluginMethod
    fun writeLargeBlob(call: PluginCall) {
        val content = call.getString("content") ?: return call.reject("Missing content")
        val fileName = call.getString("filename") ?: return call.reject("Missing filename")
        
        // VIOLATION: Directly writing to disk on native plugin thread, triggering Android ANR warnings
        val file = File(context.filesDir, fileName)
        file.writeText(content)
        call.resolve()
    }
}
```

#### Production Standard (Correct)
> **Standard**: Kotlin Coroutines with Dispatchers.IO shifts heavy disk I/O off the UI/calling thread. Results or exceptions are safely captured and returned via Capacitor's PluginCall.
```kotlin
package com.example.plugins

import com.getcapacitor.Plugin
import com.getcapacitor.PluginCall
import com.getcapacitor.PluginMethod
import com.getcapacitor.annotation.CapacitorPlugin
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File

@CapacitorPlugin(name = "DataStore")
class DataStorePlugin : Plugin() {
    private val pluginScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)

    @PluginMethod
    fun writeLargeBlob(call: PluginCall) {
        val content = call.getString("content") ?: return call.reject("Missing content")
        val fileName = call.getString("filename") ?: return call.reject("Missing filename")

        // COMPLIANT: Offload I/O to Dispatchers.IO coroutine context
        pluginScope.launch {
            try {
                withContext(Dispatchers.IO) {
                    val file = File(context.filesDir, fileName)
                    file.writeText(content)
                }
                call.resolve()
            } catch (e: Exception) {
                call.reject("Write failed: ${e.localizedMessage}", e)
            }
        }
    }
}
```

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 Native Bridge Thread Concurrency Invariant

Capacitor 7 Native Bridge Thread Concurrency Invariant defines an industrial-grade behavioral standard for mobile engineering. Mandates asynchronous background worker offloading for all custom native Capacitor 7 plugin implementations to prevent native main UI thread starvation. Heavy file operations, cryptographic calculations, database transactions, and network I/O must execute on dedicated background queues or coroutine dispatchers before resolving back through the Capacitor bridge. 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 Blocking I/O or Compute Directly on the Native UI/Main Dispatch Thread in Capacitor Plugins 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 Blocking I/O or Compute Directly on the Native UI/Main Dispatch Thread in Capacitor PluginsCritical
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 offload disk I/O, SQLite operations, image processing, and network calls inside Capacitor native plugins to background execution contexts (DispatchQueue.global or Dispatchers.IO).

Engineers MUST ALWAYS offload disk I/O, SQLite operations, image processing, and network calls inside Capacitor native plugins to background execution contexts (DispatchQueue.global or Dispatchers.IO).

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 synchronous file read/write operations or long-running computations directly on the thread executing @PluginMethod / @objc plugin hooks.

Engineers MUST NOT invoke synchronous file read/write operations or long-running computations directly on the thread executing @PluginMethod / @objc plugin hooks.

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 SHOULD leverage Swift structured concurrency (Task.detached(priority

Code SHOULD leverage Swift structured concurrency (Task.detached(priority: .userInitiated)) or Kotlin Coroutines (CoroutineScope(Dispatchers.IO).launch) when implementing native plugin handlers.

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 ensure CAPPluginCall.resolve() or CAPPluginCall.reject() can be invoked thread-safely without re-dispatching back to the main UI thread unless manipulating native UI views directly.

Services MUST ensure CAPPluginCall.resolve() or CAPPluginCall.reject() can be invoked thread-safely without re-dispatching back to the main UI thread unless manipulating native UI views directly.

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 block the WebView JavaScript evaluation thread awaiting synchronous native bridge telemetry.

Components NEVER block the WebView JavaScript evaluation thread awaiting synchronous native bridge telemetry.

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 Native Bridge Thread Concurrency Invariant critical for AI coding assistants?

Mandates asynchronous background worker offloading for all custom native Capacitor 7 plugin implementations to prevent native main UI thread starvation. Heavy file operations, cryptographic calculations, database transactions, and network I/O must execute on dedicated background queues or coroutine dispatchers before resolving back through the Capacitor bridge. 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 Blocking I/O or Compute Directly on the Native UI/Main Dispatch Thread in Capacitor Plugins) 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