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

Capacitor 7 Swift 6 Actor-Isolated Plugin Boundary

Enforces complete Swift 6 actor-isolation and structured concurrency boundaries across all Capacitor 7 WKWebView IPC bridge calls. Eliminates MainActor thread starvation and data races by strictly partitioning synchronous bridge receipt from asynchronous actor execution, forbidding mutable CAPPluginCall reference escaping across isolation domains.

Prohibited Anti-Pattern: Executing Blocking I/O Directly on MainActor Bridge Threads and Escaping Unchecked Plugin Call State

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Swift 6 Actor-Isolated Plugin Boundary - Enforces complete Swift 6 actor-isolation and structured concurrency boundaries across all Capacitor 7 WKWebView IPC bridge calls. Eliminates MainActor thread starvation and data races by strictly partitioning synchronous bridge receipt from asynchronous actor execution, forbidding mutable CAPPluginCall reference escaping across isolation domains.
globs: ios/Plugin/**/*.{swift,h,m}, ios/App/**/*.{swift,h,m}, src/definitions.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-swift-concurrency-actor-isolation"
---

# Capacitor 7 Swift 6 Actor-Isolated Plugin Boundary

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Executing Blocking I/O Directly on MainActor Bridge Threads and Escaping Unchecked Plugin Call State

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 Swift Concurrency Plugin Isolation Boundaries. In Capacitor 7 on Swift 6, WKWebView IPC messages enter via @MainActor or designated bridge dispatch queues. You must mandate strict actor isolation: all CPU-bound, disk, or network operations must immediately jump off the main isolation boundary via dedicated worker actors or detached background tasks. CAPPluginCall instances must never be mutated across concurrency domains; extract immutable Sendable values immediately at the bridge boundary before dispatching work.

## Strict Guidelines
- Engineers MUST ALWAYS mark plugin classes with explicit actor boundaries (e.g., `@objc(MyPlugin) public class MyPlugin: CAPPlugin, @unchecked Sendable` or isolated worker actors) under Swift 6 complete concurrency checking.
- Engineers MUST extract and validate all call arguments into immutable, `Sendable` Swift structs before crossing actor isolation boundaries.
- Engineers MUST NOT execute synchronous file I/O, cryptographic operations, or network requests directly inside `@objc public func method(_ call: CAPPluginCall)` on `@MainActor`.
- Code MUST capture only isolated copies of primitive values or `Sendable` parameter records, never passing un-isolated reference-type objects or raw pointers across `Task` closures.
- Services MUST resolve bridge callbacks (`call.resolve()` or `call.reject()`) deterministically on the expected boundary without double-invoking or dropping calls on early error exits.
- Components NEVER hold non-weak references to `CAPPlugin` or `CAPBridgeViewController` inside detached background asynchronous streams.

## Bad vs Good Implementations
### Swift 6 Actor Isolation for Capacitor 7 Plugin Calls

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Blocks the native UI/IPC run loop by capturing mutable plugin call references across an un-isolated GCD queue, leading to data races under Swift 6 complete concurrency checking and potential MainActor hitching.
```swift
@objc(FileCryptoPlugin)
public class FileCryptoPlugin: CAPPlugin {
    // ANTI-PATTERN: Blocking MainActor during bridge call,
    // mutating CAPPluginCall across unconstrained global queue
    @objc func computeChecksum(_ call: CAPPluginCall) {
        guard let filePath = call.getString("path") else {
            call.reject("Path required")
            return
        }
        
        // Blocks the WKWebView render pipeline and MainActor thread
        DispatchQueue.global(qos: .userInitiated).async {
            let url = URL(fileURLWithPath: filePath)
            if let data = try? Data(contentsOf: url) {
                let hash = data.base64EncodedString() // Simulating heavy operation
                // Race condition: unsafely modifying CAPPluginCall across threads
                call.resolve(["checksum": hash])
            } else {
                call.reject("Failed to read file")
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Extracts immutable Sendable parameters immediately, dispatches heavy I/O to a dedicated Swift actor, and executes within a structured Task lifecycle without freezing the MainActor or violating Swift 6 concurrency rules.
```swift
@objc(FileCryptoPlugin)
public class FileCryptoPlugin: CAPPlugin {
    // Dedicated worker actor isolating heavy cryptographic computation
    private actor CryptoWorker {
        func computeHash(for path: String) throws -> String {
            let url = URL(fileURLWithPath: path)
            let data = try Data(contentsOf: url)
            return data.base64EncodedString()
        }
    }

    private let worker = CryptoWorker()

    @objc func computeChecksum(_ call: CAPPluginCall) {
        guard let filePath = call.getString("path") else {
            call.reject("Path required")
            return
        }

        // Structured concurrency boundary with explicit Sendable capture
        Task { [worker] in
            do {
                let hash = try await worker.computeHash(for: filePath)
                // Safely resolve back to caller without leaking call across contexts
                call.resolve(["checksum": hash])
            } catch {
                call.reject("Failed to read file: \(error.localizedDescription)")
            }
        }
    }
}
```

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 Swift 6 Actor-Isolated Plugin Boundary

Capacitor 7 Swift 6 Actor-Isolated Plugin Boundary defines an industrial-grade behavioral standard for mobile engineering. Enforces complete Swift 6 actor-isolation and structured concurrency boundaries across all Capacitor 7 WKWebView IPC bridge calls. Eliminates MainActor thread starvation and data races by strictly partitioning synchronous bridge receipt from asynchronous actor execution, forbidding mutable CAPPluginCall reference escaping across isolation domains. 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 Directly on MainActor Bridge Threads and Escaping Unchecked Plugin Call State 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 Directly on MainActor Bridge Threads and Escaping Unchecked Plugin Call StateCritical
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 mark plugin classes with explicit actor boundaries (e.g., `@objc(MyPlugin) public class MyPlugin

Engineers MUST ALWAYS mark plugin classes with explicit actor boundaries (e.g., `@objc(MyPlugin) public class MyPlugin: CAPPlugin, @unchecked Sendable` or isolated worker actors) under Swift 6 complete concurrency checking.

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 extract and validate all call arguments into immutable, `Sendable` Swift structs before crossing actor isolation boundaries.

Engineers MUST extract and validate all call arguments into immutable, `Sendable` Swift structs before crossing actor isolation boundaries.

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

Engineers MUST NOT execute synchronous file I/O, cryptographic operations, or network requests directly inside `@objc public func method(_ call

Engineers MUST NOT execute synchronous file I/O, cryptographic operations, or network requests directly inside `@objc public func method(_ call: CAPPluginCall)` on `@MainActor`.

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

Code MUST capture only isolated copies of primitive values or `Sendable` parameter records, never passing un-isolated reference-type objects or raw pointers across `Task` closures.

Code MUST capture only isolated copies of primitive values or `Sendable` parameter records, never passing un-isolated reference-type objects or raw pointers across `Task` closures.

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

Services MUST resolve bridge callbacks (`call.resolve()` or `call.reject()`) deterministically on the expected boundary without double-invoking or dropping calls on early error exits.

Services MUST resolve bridge callbacks (`call.resolve()` or `call.reject()`) deterministically on the expected boundary without double-invoking or dropping calls on early error exits.

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.
6

Components NEVER hold non-weak references to `CAPPlugin` or `CAPBridgeViewController` inside detached background asynchronous streams.

Components NEVER hold non-weak references to `CAPPlugin` or `CAPBridgeViewController` inside detached background asynchronous streams.

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 Swift 6 Actor-Isolated Plugin Boundary critical for AI coding assistants?

Enforces complete Swift 6 actor-isolation and structured concurrency boundaries across all Capacitor 7 WKWebView IPC bridge calls. Eliminates MainActor thread starvation and data races by strictly partitioning synchronous bridge receipt from asynchronous actor execution, forbidding mutable CAPPluginCall reference escaping across isolation domains. 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 Directly on MainActor Bridge Threads and Escaping Unchecked Plugin Call State) 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