This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-7-jsi-thread-safety-zero-copy-guardrail

Capacitor 7 JSI Synchronous Bridge Thread-Safety and Zero-Copy Buffer Isolation

Enforces strict thread-affinity boundaries and zero-copy binary buffer swapping across JavaScript and native execution threads in Capacitor 7 JSI plugins. Prevents main-thread UI hitching, memory trashing, and concurrent execution crashes during high-frequency native telemetry streaming by forbidding JSON serialization over the bridge and isolating JSI host function execution to the dedicated JS runtime thread.

Prohibited Anti-Pattern: Marshalling High-Frequency Hardware Telemetry via Serialized Bridge Objects on the Main Thread

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 JSI Synchronous Bridge Thread-Safety and Zero-Copy Buffer Isolation - Enforces strict thread-affinity boundaries and zero-copy binary buffer swapping across JavaScript and native execution threads in Capacitor 7 JSI plugins. Prevents main-thread UI hitching, memory trashing, and concurrent execution crashes during high-frequency native telemetry streaming by forbidding JSON serialization over the bridge and isolating JSI host function execution to the dedicated JS runtime thread.
globs: src/plugins/**/*.{ts,tsx}, ios/Plugin/**/*.{swift,m,mm,cpp}, android/src/main/**/*.{java,kt,cpp}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-jsi-thread-safety-zero-copy-guardrail"
---

# Capacitor 7 JSI Synchronous Bridge Thread-Safety and Zero-Copy Buffer Isolation

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Marshalling High-Frequency Hardware Telemetry via Serialized Bridge Objects on the Main Thread

## System Constraints
You are a Principal Software Architect enforcing Capacitor 7 JSI Synchronous Bridge Thread-Safety Invariants. You must eliminate all instances of serialized JSON object bridging for high-frequency hardware events (accelerometer, IMU, BLE, audio) and mandate thread-affinity enforcement with direct ArrayBuffer memory passing to maintain 60/120 FPS UI performance.

## Strict Guidelines
- Engineers MUST ALWAYS isolate JSI runtime interactions to the JavaScript execution thread; native worker threads MUST NEVER invoke JSI HostFunction instances directly.
- Engineers MUST use pre-allocated, zero-copy TypedArray/ArrayBuffer instances (or JSI ArrayBuffer references) for transferring rapid telemetry payloads across native and web boundaries.
- Engineers MUST NOT serialize streaming telemetry data into JSON strings, dictionaries, or bridge PluginCall objects at frequencies exceeding 30Hz.
- Native plugins MUST implement lock-free ring buffers or atomic double-buffering when staging incoming hardware sensor telemetry from high-frequency native threads before exposing it to the JSI bridge.
- Web clients MUST process high-rate telemetry buffers using Web Workers or requestAnimationFrame batching, never executing long synchronous data parsing loops inside the JSI callback on the UI thread.
- Plugins MUST explicitly validate buffer byte lengths and memory bounds before native memory access to prevent segmentation faults and buffer overflow vulnerabilities.

## Bad vs Good Implementations
### High-Frequency Telemetry Ingestion (Capacitor Bridge vs JSI Zero-Copy)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Emitting high-frequency (200Hz) events over the legacy Capacitor asynchronous bridge serializes each sensor tick into a JSON object via the UI main thread. This leads to thread contention, heavy Garbage Collection thrashing, frame drops, and severe UI hitching.
```typescript
import { registerPlugin } from '@capacitor/core';

interface SensorPlugin {
  // Anti-Pattern: Serializes rapid (100Hz+) telemetry as dynamic JSON objects
  // over the standard asynchronous bridge, flooding main thread dispatch queue
  startStreaming(options: { hz: number }): Promise<void>;
  addListener(eventName: 'telemetry', listenerFunc: (data: { x: number; y: number; z: number; timestamp: number }) => void): Promise<void>;
}

const Sensor = registerPlugin<SensorPlugin>('Sensor');

export function monitorSensor() {
  Sensor.addListener('telemetry', (data) => {
    // Serialized bridge payloads trigger heavy JSON parsing & GC pressure on UI thread
    renderTelemetry(data.x, data.y, data.z);
  });
  Sensor.startStreaming({ hz: 200 });
}

function renderTelemetry(x: number, y: number, z: number) {
  console.log(x, y, z);
}
```

#### Production Standard (Correct)
> **Standard**: Adheres to the Capacitor 7 JSI invariant by leveraging a pre-allocated Float32Array/ArrayBuffer. Telemetry is read synchronously via zero-copy native memory access synchronized with the display refresh cycle (requestAnimationFrame), eliminating object allocation and main-thread serialization bottlenecks.
```typescript
interface JSIBufferHandle {
  buffer: ArrayBuffer;
  byteOffset: number;
  length: number;
}

interface FastSensorNativeBridge {
  // Invariant: Direct synchronous access via JSI using pre-allocated zero-copy buffers
  syncReadLatestTelemetry(targetBuffer: ArrayBuffer): number;
}

declare const FastSensorJSI: FastSensorNativeBridge | undefined;

export class TelemetryConsumer {
  // Statically allocated 16-byte buffer: [float32 x, float32 y, float32 z, float32 timestamp]
  private sharedBuffer = new ArrayBuffer(16);
  private view = new Float32Array(this.sharedBuffer);
  private isRunning = false;

  public startPolling(): void {
    if (!FastSensorJSI) {
      throw new Error('JSI Synchronous Bridge unavailable');
    }
    this.isRunning = true;

    const poll = () => {
      if (!this.isRunning) return;
      // Zero-copy sync call: reads atomic snapshot directly into shared ArrayBuffer
      const bytesRead = FastSensorJSI.syncReadLatestTelemetry(this.sharedBuffer);
      if (bytesRead === 16) {
        const x = this.view[0];
        const y = this.view[1];
        const z = this.view[2];
        this.consumeTelemetry(x, y, z);
      }
      requestAnimationFrame(poll);
    };

    requestAnimationFrame(poll);
  }

  public stop(): void {
    this.isRunning = false;
  }

  private consumeTelemetry(x: number, y: number, z: number): void {
    // Telemetry consumed with 0 object allocations and 0 serialization overhead
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 JSI Synchronous Bridge Thread-Safety and Zero-Copy Buffer Isolation

Capacitor 7 JSI Synchronous Bridge Thread-Safety and Zero-Copy Buffer Isolation defines an industrial-grade behavioral standard for mobile engineering. Enforces strict thread-affinity boundaries and zero-copy binary buffer swapping across JavaScript and native execution threads in Capacitor 7 JSI plugins. Prevents main-thread UI hitching, memory trashing, and concurrent execution crashes during high-frequency native telemetry streaming by forbidding JSON serialization over the bridge and isolating JSI host function execution to the dedicated JS runtime thread. 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: Marshalling High-Frequency Hardware Telemetry via Serialized Bridge Objects on the Main Thread 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 DriftMarshalling High-Frequency Hardware Telemetry via Serialized Bridge Objects on the Main ThreadCritical
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 isolate JSI runtime interactions to the JavaScript execution thread

Engineers MUST ALWAYS isolate JSI runtime interactions to the JavaScript execution thread; native worker threads MUST NEVER invoke JSI HostFunction instances 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.
2

Engineers MUST use pre-allocated, zero-copy TypedArray/ArrayBuffer instances (or JSI ArrayBuffer references) for transferring rapid telemetry payloads across native and web boundaries.

Engineers MUST use pre-allocated, zero-copy TypedArray/ArrayBuffer instances (or JSI ArrayBuffer references) for transferring rapid telemetry payloads across native and web 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 serialize streaming telemetry data into JSON strings, dictionaries, or bridge PluginCall objects at frequencies exceeding 30Hz.

Engineers MUST NOT serialize streaming telemetry data into JSON strings, dictionaries, or bridge PluginCall objects at frequencies exceeding 30Hz.

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

Native plugins MUST implement lock-free ring buffers or atomic double-buffering when staging incoming hardware sensor telemetry from high-frequency native threads before exposing it to the JSI bridge.

Native plugins MUST implement lock-free ring buffers or atomic double-buffering when staging incoming hardware sensor telemetry from high-frequency native threads before exposing it to the JSI bridge.

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

Web clients MUST process high-rate telemetry buffers using Web Workers or requestAnimationFrame batching, never executing long synchronous data parsing loops inside the JSI callback on the UI thread.

Web clients MUST process high-rate telemetry buffers using Web Workers or requestAnimationFrame batching, never executing long synchronous data parsing loops inside the JSI callback on the UI thread.

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

Plugins MUST explicitly validate buffer byte lengths and memory bounds before native memory access to prevent segmentation faults and buffer overflow vulnerabilities.

Plugins MUST explicitly validate buffer byte lengths and memory bounds before native memory access to prevent segmentation faults and buffer overflow vulnerabilities.

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 JSI Synchronous Bridge Thread-Safety and Zero-Copy Buffer Isolation critical for AI coding assistants?

Enforces strict thread-affinity boundaries and zero-copy binary buffer swapping across JavaScript and native execution threads in Capacitor 7 JSI plugins. Prevents main-thread UI hitching, memory trashing, and concurrent execution crashes during high-frequency native telemetry streaming by forbidding JSON serialization over the bridge and isolating JSI host function execution to the dedicated JS runtime thread. 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 (Marshalling High-Frequency Hardware Telemetry via Serialized Bridge Objects on the Main Thread) 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