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

Capacitor 7 Swift 6 Structured Concurrency Task Cancellation Invariant

Guarantees that native Swift structured asynchronous task hierarchies initiated across the Capacitor 7 JS-to-Native bridge are explicitly tracked and cancelled when the originating WebView context tears down, navigates, or dispatches an explicit cancellation call. Without structured task cancellation propagation, orphaned native tasks retain UI references and background workers, leading to thread pool starvation, Swift 6 concurrency actor isolation violations, and memory leaks.

Prohibited Anti-Pattern: Unmanaged Unstructured Tasks Leaking Across Bridge During WebView Navigation and Plugin Teardown

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Swift 6 Structured Concurrency Task Cancellation Invariant - Guarantees that native Swift structured asynchronous task hierarchies initiated across the Capacitor 7 JS-to-Native bridge are explicitly tracked and cancelled when the originating WebView context tears down, navigates, or dispatches an explicit cancellation call. Without structured task cancellation propagation, orphaned native tasks retain UI references and background workers, leading to thread pool starvation, Swift 6 concurrency actor isolation violations, and memory leaks.
globs: ios/App/App/**/*.swift, ios/App/Plugins/**/*.swift, src/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-swift-6-task-cancellation-invariant"
---

# Capacitor 7 Swift 6 Structured Concurrency Task Cancellation Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unmanaged Unstructured Tasks Leaking Across Bridge During WebView Navigation and Plugin Teardown

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 and Swift 6 concurrency standards. You must ensure that all asynchronous native operations invoked via Capacitor plugins participate in Swift Structured Concurrency with deterministic Task cancellation bindings. Native plugin methods MUST track active Task instances keyed by call ID or plugin lifecycle, handle Task.isCancelled cooperatively, ensure non-isolated bridge execution safely transitions to isolated actors, and teardown automatically when the Capacitor ViewController or Bridge terminates.

## Strict Guidelines
- Plugin implementations MUST maintain a thread-safe registry (such as an actor or synchronised map) of active structured Task<Void, Never> instances indexed by CAPPluginCall.callbackId.
- Engineers MUST NOT spawn detached or unmanaged async Tasks (Task.detached or Task { ... }) in Capacitor plugins without storing a handle for explicit lifecycle cancellation.
- Native methods MUST check Task.isCancelled before yielding results back to CAPPluginCall, resolving with a cancelled status or rejecting cleanly rather than accessing deallocated Bridge resources.
- Plugins MUST override plugin cleanup hooks (such as CAPPlugin.deinit or WebView dismissal observers) to iterate through the active task registry and trigger .cancel() on every running structured Task.
- TypeScript bridge consumers MUST invoke explicit plugin cancellation APIs via AbortController signals when components unmount to release native hardware locks, geolocation listeners, or network streams.

## Bad vs Good Implementations
### Native Plugin Structured Concurrency Task Registry and Cancellation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Spawns an unmanaged Task that retains the CAPPluginCall reference. If the user navigates away or the WebView is torn down, the background Task continues executing and attempts to post results back through a dead bridge, causing thread starvation and potential crash on Swift 6 strict concurrency checks.
```swift
import Capacitor

@objc(DataSyncPlugin)
public class DataSyncPlugin: CAPPlugin, CAPBridgedPlugin {
    public let identifier = "DataSyncPlugin"
    public let jsName = "DataSync"
    public let pluginMethods: [CAPPluginMethod] = [
        CAPPluginMethod(name: "syncLargePayload", returnType: CAPPluginReturnPromise)
    ]

    @objc func syncLargePayload(_ call: CAPPluginCall) {
        // ANTI-PATTERN: Fire-and-forget unstructured Task with no cancellation handle,
        // strongly capturing call, leading to memory leaks and zombie thread execution when WebView dismisses.
        Task {
            let result = await HeavyWorker.processData()
            call.resolve(["data": result])
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Encapsulates task references within a dedicated Swift actor, exposes an explicit cancellation bridge method, checks Task.isCancelled cooperatively, and registers a deinit cancellation sweep to guarantee structural cleanup on native teardown.
```swift
import Capacitor

@objc(DataSyncPlugin)
public final class DataSyncPlugin: CAPPlugin, CAPBridgedPlugin, @unchecked Sendable {
    public let identifier = "DataSyncPlugin"
    public let jsName = "DataSync"
    public let pluginMethods: [CAPPluginMethod] = [
        CAPPluginMethod(name: "syncLargePayload", returnType: CAPPluginReturnPromise),
        CAPPluginMethod(name: "cancelSync", returnType: CAPPluginReturnPromise)
    ]

    // Thread-safe actor to manage in-flight structured tasks
    private actor TaskRegistry {
        private var tasks: [String: Task<Void, Never>] = [:]

        func register(id: String, task: Task<Void, Never>) {
            tasks[id] = task
        }

        func cancel(id: String) {
            tasks[id]?.cancel()
            tasks.removeValue(forKey: id)
        }

        func cancelAll() {
            tasks.values.forEach { $0.cancel() }
            tasks.removeAll()
        }
    }

    private let registry = TaskRegistry()

    @objc func syncLargePayload(_ call: CAPPluginCall) {
        guard let callId = call.callbackId else {
            call.reject("Missing call identifier")
            return
        }

        let task = Task { [weak self, callId] in
            do {
                let result = try await HeavyWorker.processDataWithCancellationCheck()
                guard !Task.isCancelled else {
                    call.reject("Task was cancelled")
                    return
                }
                call.resolve(["data": result])
            } catch is CancellationError {
                call.reject("Operation aborted", "CANCELLED")
            } catch {
                call.reject(error.localizedDescription)
            }
            await self?.registry.cancel(id: callId)
        }

        Task { await registry.register(id: callId, task: task) }
    }

    @objc func cancelSync(_ call: CAPPluginCall) {
        guard let targetId = call.getString("callId") else {
            call.reject("callId is required")
            return
        }
        Task {
            await registry.cancel(id: targetId)
            call.resolve(["cancelled": true])
        }
    }

    deinit {
        let reg = registry
        Task { await reg.cancelAll() }
    }
}
```

### TypeScript Bridge AbortController Integration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Client triggers long-running native processing without propagating unmount lifecycle signals, keeping native CPU threads actively executing unneeded work in the background.
```typescript
import { registerPlugin } from '@capacitor/core';

const DataSync = registerPlugin<any>('DataSync');

export function useSyncData() {
  const triggerSync = async () => {
    // ANTI-PATTERN: Native promise ignored upon unmount; no mechanism to signal native task cancellation
    await DataSync.syncLargePayload();
  };
  return { triggerSync };
}
```

#### Production Standard (Correct)
> **Standard**: Uses standard AbortController combined with cleanup hooks to proactively send cancellation signals to the native Swift task registry when the UI unmounts.
```typescript
import { registerPlugin } from '@capacitor/core';
import { useEffect } from 'react';

interface DataSyncPlugin {
  syncLargePayload(): Promise<{ data: string }>;
  cancelSync(options: { callId: string }): Promise<{ cancelled: boolean }>;
}

const DataSync = registerPlugin<DataSyncPlugin>('DataSync');

export function useSyncData() {
  useEffect(() => {
    const controller = new AbortController();
    const callId = crypto.randomUUID();

    const run = async () => {
      try {
        await DataSync.syncLargePayload();
      } catch (err: unknown) {
        if (!controller.signal.aborted) {
          console.error('Sync failed:', err);
        }
      }
    };

    run();

    return () => {
      controller.abort();
      DataSync.cancelSync({ callId }).catch(() => {
        // Suppress teardown errors
      });
    };
  }, []);
}
```

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 Structured Concurrency Task Cancellation Invariant

Capacitor 7 Swift 6 Structured Concurrency Task Cancellation Invariant defines an industrial-grade behavioral standard for mobile engineering. Guarantees that native Swift structured asynchronous task hierarchies initiated across the Capacitor 7 JS-to-Native bridge are explicitly tracked and cancelled when the originating WebView context tears down, navigates, or dispatches an explicit cancellation call. Without structured task cancellation propagation, orphaned native tasks retain UI references and background workers, leading to thread pool starvation, Swift 6 concurrency actor isolation violations, and memory leaks. 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: Unmanaged Unstructured Tasks Leaking Across Bridge During WebView Navigation and Plugin Teardown 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 DriftUnmanaged Unstructured Tasks Leaking Across Bridge During WebView Navigation and Plugin TeardownCritical
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

Plugin implementations MUST maintain a thread-safe registry (such as an actor or synchronised map) of active structured Task<Void, Never> instances indexed by CAPPluginCall.callbackId.

Plugin implementations MUST maintain a thread-safe registry (such as an actor or synchronised map) of active structured Task<Void, Never> instances indexed by CAPPluginCall.callbackId.

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 spawn detached or unmanaged async Tasks (Task.detached or Task { ... }) in Capacitor plugins without storing a handle for explicit lifecycle cancellation.

Engineers MUST NOT spawn detached or unmanaged async Tasks (Task.detached or Task { ... }) in Capacitor plugins without storing a handle for explicit lifecycle cancellation.

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 methods MUST check Task.isCancelled before yielding results back to CAPPluginCall, resolving with a cancelled status or rejecting cleanly rather than accessing deallocated Bridge resources.

Native methods MUST check Task.isCancelled before yielding results back to CAPPluginCall, resolving with a cancelled status or rejecting cleanly rather than accessing deallocated Bridge resources.

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

Plugins MUST override plugin cleanup hooks (such as CAPPlugin.deinit or WebView dismissal observers) to iterate through the active task registry and trigger .cancel() on every running structured Task.

Plugins MUST override plugin cleanup hooks (such as CAPPlugin.deinit or WebView dismissal observers) to iterate through the active task registry and trigger .cancel() on every running structured Task.

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

TypeScript bridge consumers MUST invoke explicit plugin cancellation APIs via AbortController signals when components unmount to release native hardware locks, geolocation listeners, or network streams.

TypeScript bridge consumers MUST invoke explicit plugin cancellation APIs via AbortController signals when components unmount to release native hardware locks, geolocation listeners, or network 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 Structured Concurrency Task Cancellation Invariant critical for AI coding assistants?

Guarantees that native Swift structured asynchronous task hierarchies initiated across the Capacitor 7 JS-to-Native bridge are explicitly tracked and cancelled when the originating WebView context tears down, navigates, or dispatches an explicit cancellation call. Without structured task cancellation propagation, orphaned native tasks retain UI references and background workers, leading to thread pool starvation, Swift 6 concurrency actor isolation violations, and memory leaks. 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 (Unmanaged Unstructured Tasks Leaking Across Bridge During WebView Navigation and Plugin Teardown) 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