This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: tauri2-mobile-shm-ringbuffer-protocol

Tauri 2.0 Mobile Zero-Copy Binary Ring Buffer Protocol Invariant

Enforces zero-copy or direct binary channel streaming for high-frequency binary data between the Tauri 2.0 native Rust core and platform WebViews (iOS WKWebView / Android WebView). Prohibits JSON or Base64 serialization over the standard IPC bridge for binary streams to prevent mobile garbage collector thrashing, main thread stalls, and excessive battery consumption.

Prohibited Anti-Pattern: Serializing High-Frequency Binary Streaming Payloads via Standard JSON/Base64 invoke() IPC

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Tauri 2.0 Mobile Zero-Copy Binary Ring Buffer Protocol Invariant - Enforces zero-copy or direct binary channel streaming for high-frequency binary data between the Tauri 2.0 native Rust core and platform WebViews (iOS WKWebView / Android WebView). Prohibits JSON or Base64 serialization over the standard IPC bridge for binary streams to prevent mobile garbage collector thrashing, main thread stalls, and excessive battery consumption.
globs: src/**/*.{ts,tsx}, src-tauri/src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/tauri2-mobile-shm-ringbuffer-protocol"
---

# Tauri 2.0 Mobile Zero-Copy Binary Ring Buffer Protocol Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Serializing High-Frequency Binary Streaming Payloads via Standard JSON/Base64 invoke() IPC

## System Constraints
You are a Principal Systems and Mobile Architect enforcing strict IPC performance boundaries for Tauri 2.0 on Android and iOS. Standard IPC channels rely on WebKit/V8 messaging layers that serialize through JSON strings, causing severe thermal throttling, high GC pause intervals, and frame drops when processing high-frequency streams (such as PCM audio, real-time camera frames, sensor telemetry, and neural embeddings). You must strictly mandate binary streaming channels (Tauri 2.0 `Channel<Vec<u8>>`), memory-mapped ring buffers, or custom protocol streams, maintaining zero-copy semantics and pre-allocated buffer pools across the webview-native boundary.

## Strict Guidelines
- Engineers MUST ALWAYS transfer binary streams exceeding 10Hz or 1KB/frame via Tauri 2.0 `Channel<Vec<u8>>` or custom protocol streaming (`tauri://` / `http://tauri.localhost`).
- Engineers MUST NOT convert binary data (`ArrayBuffer`, `Uint8Array`, `Vec<u8>`) to Base64 strings, comma-separated numeric arrays, or JSON arrays over `invoke()` on mobile platforms.
- Code MUST employ pre-allocated, fixed-capacity ring buffer pools on the webview consumer to eliminate per-frame allocations and garbage collection cycles.
- Services MUST manage read/write offsets using atomic sequence counters or structured 16-byte fixed binary headers (magic, sequence_id, payload_length, timestamp) preceding frame payloads.
- Components NEVER bridge streaming sensor, audio, or video frame cycles through standard reactive UI state (e.g., React `useState` / Vue `ref`) directly from high-rate IPC subscribers.

## Bad vs Good Implementations
### Tauri 2.0 Webview Binary Ingestion: Serialization vs Binary Channel Ring Buffer

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Invoking `poll_audio_samples` over standard `invoke()` forces Rust to serialize floating-point numbers into a JSON array string. Parsing this JSON array inside mobile WebKit/V8 generates thousands of ephemeral heap objects every frame, triggering aggressive garbage collection pauses and exceeding the 16.6ms frame budget.
```typescript
import { invoke } from '@tauri-apps/api/core';

// ANTI-PATTERN: Serializes high-throughput raw audio/sensor buffers through JSON IPC
export async function startAudioStream(onSample: (data: Float32Array) => void) {
  const interval = setInterval(async () => {
    // Serializes a 2048-sample Float32Array into a JSON numeric array [0.012, 0.432, ...]
    // Causes massive string allocations and JSON parser thrashing in WebView JSC/V8
    const rawData = await invoke<number[]>('poll_audio_samples');
    const sampleBuffer = new Float32Array(rawData);
    onSample(sampleBuffer);
  }, 16);

  return () => clearInterval(interval);
}
```

#### Production Standard (Correct)
> **Standard**: Utilizes Tauri 2.0 `Channel<Uint8Array>` to transfer direct raw byte arrays bypassing JSON serialization. Incoming buffers are processed via a zero-allocation circular ring buffer with atomic pointer updates, eliminating mobile UI thread GC pressure and ensuring continuous 60/120 FPS performance.
```typescript
import { Channel, invoke } from '@tauri-apps/api/core';

const RING_BUFFER_SIZE = 16 * 1024 * 1024; // 16MB pre-allocated ring buffer
const ringBuffer = new SharedArrayBuffer(RING_BUFFER_SIZE);
const atomicHeader = new Int32Array(ringBuffer, 0, 4); // [0]=write_ptr, [1]=read_ptr
const ringData = new Uint8Array(ringBuffer, 16);

export async function startBinaryRingBufferConsumer(
  onFrame: (payload: Uint8Array) => void
): Promise<() => void> {
  // Invariant: Native stream writes raw Uint8Array frames directly over Tauri 2.0 Channel
  const channel = new Channel<Uint8Array>();
  
  channel.onmessage = (chunk: Uint8Array) => {
    const writePtr = Atomics.load(atomicHeader, 0);
    const chunkLen = chunk.byteLength;
    const capacity = ringData.byteLength;
    
    // Zero-alloc circular buffer copy
    if (writePtr + chunkLen <= capacity) {
      ringData.set(chunk, writePtr);
      Atomics.store(atomicHeader, 0, (writePtr + chunkLen) % capacity);
    } else {
      const firstPart = capacity - writePtr;
      ringData.set(chunk.subarray(0, firstPart), writePtr);
      ringData.set(chunk.subarray(firstPart), 0);
      Atomics.store(atomicHeader, 0, chunkLen - firstPart);
    }
    
    onFrame(chunk);
  };

  await invoke('start_native_binary_stream', { onEvent: channel });
  
  return () => {
    invoke('stop_native_binary_stream');
  };
}
```

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: Tauri 2.0 Mobile Zero-Copy Binary Ring Buffer Protocol Invariant

Tauri 2.0 Mobile Zero-Copy Binary Ring Buffer Protocol Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces zero-copy or direct binary channel streaming for high-frequency binary data between the Tauri 2.0 native Rust core and platform WebViews (iOS WKWebView / Android WebView). Prohibits JSON or Base64 serialization over the standard IPC bridge for binary streams to prevent mobile garbage collector thrashing, main thread stalls, and excessive battery consumption. 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: Serializing High-Frequency Binary Streaming Payloads via Standard JSON/Base64 invoke() IPC 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 DriftSerializing High-Frequency Binary Streaming Payloads via Standard JSON/Base64 invoke() IPCCritical
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 transfer binary streams exceeding 10Hz or 1KB/frame via Tauri 2.0 `Channel<Vec<u8>>` or custom protocol streaming (`tauri

Engineers MUST ALWAYS transfer binary streams exceeding 10Hz or 1KB/frame via Tauri 2.0 `Channel<Vec<u8>>` or custom protocol streaming (`tauri://` / `http://tauri.localhost`).

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 convert binary data (`ArrayBuffer`, `Uint8Array`, `Vec<u8>`) to Base64 strings, comma-separated numeric arrays, or JSON arrays over `invoke()` on mobile platforms.

Engineers MUST NOT convert binary data (`ArrayBuffer`, `Uint8Array`, `Vec<u8>`) to Base64 strings, comma-separated numeric arrays, or JSON arrays over `invoke()` on mobile platforms.

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 MUST employ pre-allocated, fixed-capacity ring buffer pools on the webview consumer to eliminate per-frame allocations and garbage collection cycles.

Code MUST employ pre-allocated, fixed-capacity ring buffer pools on the webview consumer to eliminate per-frame allocations and garbage collection cycles.

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 manage read/write offsets using atomic sequence counters or structured 16-byte fixed binary headers (magic, sequence_id, payload_length, timestamp) preceding frame payloads.

Services MUST manage read/write offsets using atomic sequence counters or structured 16-byte fixed binary headers (magic, sequence_id, payload_length, timestamp) preceding frame payloads.

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 bridge streaming sensor, audio, or video frame cycles through standard reactive UI state (e.g., React `useState` / Vue `ref`) directly from high-rate IPC subscribers.

Components NEVER bridge streaming sensor, audio, or video frame cycles through standard reactive UI state (e.g., React `useState` / Vue `ref`) directly from high-rate IPC subscribers.

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 Tauri 2.0 Mobile Zero-Copy Binary Ring Buffer Protocol Invariant critical for AI coding assistants?

Enforces zero-copy or direct binary channel streaming for high-frequency binary data between the Tauri 2.0 native Rust core and platform WebViews (iOS WKWebView / Android WebView). Prohibits JSON or Base64 serialization over the standard IPC bridge for binary streams to prevent mobile garbage collector thrashing, main thread stalls, and excessive battery consumption. 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 (Serializing High-Frequency Binary Streaming Payloads via Standard JSON/Base64 invoke() IPC) 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

Tauri