This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: tauri-v2-mobile-ipc-zerocopy-isolation

Tauri 2.0 Mobile IPC Zero-Copy ArrayBuffer Transfer & Memory Isolation Guardrail

Enforces strict transfer semantics, buffer detachment, and lifetime isolation when streaming high-bandwidth binary data across Tauri 2.0 IPC between Rust and mobile WebViews (WebKit/WKWebView and Android WebView). Prevents silent data corruption, use-after-free, and double-free conditions caused by concurrent mutations of shared memory buffers or improper JNI/WebKit FFI pointer lifecycle management.

Prohibited Anti-Pattern: Mutating Shared ArrayBuffer Instances Post-IPC Dispatch or Unsafely Aliasing Raw JNI/WebKit Byte Buffers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Tauri 2.0 Mobile IPC Zero-Copy ArrayBuffer Transfer & Memory Isolation Guardrail - Enforces strict transfer semantics, buffer detachment, and lifetime isolation when streaming high-bandwidth binary data across Tauri 2.0 IPC between Rust and mobile WebViews (WebKit/WKWebView and Android WebView). Prevents silent data corruption, use-after-free, and double-free conditions caused by concurrent mutations of shared memory buffers or improper JNI/WebKit FFI pointer lifecycle management.
globs: src/**/*.{ts,tsx}, src-tauri/src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/tauri-v2-mobile-ipc-zerocopy-isolation"
---

# Tauri 2.0 Mobile IPC Zero-Copy ArrayBuffer Transfer & Memory Isolation Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Mutating Shared ArrayBuffer Instances Post-IPC Dispatch or Unsafely Aliasing Raw JNI/WebKit Byte Buffers

## System Constraints
You are a Principal Mobile Systems Architect and Rust/WebAssembly Security Specialist. Enforce strict memory safety, ownership transfer, and buffer detachment protocols for Tauri 2.0 cross-runtime IPC. Prohibit mutable buffer aliasing across the V8/JavaScriptCore and Rust FFI boundary, mandate Tauri 2.0 Channel/Response transfer invariants, and guarantee zero-copy streaming safety without memory leaks or race conditions.

## Strict Guidelines
- Engineers MUST ALWAYS treat ArrayBuffers passed across the IPC boundary as single-ownership transferred resources, detaching or discarding the client reference immediately after dispatch.
- Engineers MUST NOT mutate a Uint8Array or ArrayBuffer after passing it to `invoke()` or an IPC `Channel`, as mobile WebViews (JNI DirectByteBuffer / WKScriptMessage) execute asynchronous buffer consumption.
- Rust handlers receiving high-throughput binary frames MUST consume buffers via `tauri::ipc::Request` binary payloads or `tauri::ipc::Channel<Vec<u8>>` and NEVER store raw heap pointers across async await boundaries without explicit pin and ownership guarantees.
- Code MUST verify `buffer.detached` prior to dispatch and utilize `ArrayBuffer.prototype.transfer()` (or sliced defensive allocation if transfer is unsupported) to guarantee thread isolation.
- Services streaming binary frames from Rust to mobile WebViews MUST use `tauri::ipc::Response::new(bytes)` or custom protocol asset streaming rather than base64 serialization, which causes critical GC pressure and memory spikes on mobile runtimes.
- Components NEVER perform concurrent writes to overlapping byte offsets in shared memory mapped regions without atomic synchronization primitives recognized by both Rust and the WebView JS engine.

## Bad vs Good Implementations
### TypeScript IPC Binary Payload Dispatch & Buffer Isolation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Reusing a single mutable TypedArray across calls to Tauri IPC causes concurrent reads and writes between the JS thread and the native mobile WebView IPC serialization thread. On Android/iOS, this causes torn reads, data corruption, or memory access violations.
```typescript
import { invoke } from '@tauri-apps/api/core';

// ANTI-PATTERN: Reusing and mutating a shared buffer across async IPC calls
const sharedFrameBuffer = new Uint8Array(1024 * 1024 * 4);

export async function pushCameraFrame(rawSensorData: ArrayBuffer): Promise<void> {
  // In-place copy to shared buffer
  sharedFrameBuffer.set(new Uint8Array(rawSensorData));
  
  // Mutating or writing to sharedFrameBuffer concurrently while Tauri mobile IPC
  // is reading it asynchronously via JNI or WKWebView creates a data race / corruption
  await invoke('process_frame', { frame: sharedFrameBuffer });
}
```

#### Production Standard (Correct)
> **Standard**: The good pattern enforces buffer transfer semantics via ArrayBuffer.prototype.transfer (or defensive zero-shared slicing), prevents post-call buffer reuse, and safely isolates the memory space before transferring the binary payload across the Tauri 2.0 native IPC boundary.
```typescript
import { invoke } from '@tauri-apps/api/core';

// PRODUCTION INVARIANT: Ownership transfer and explicit detachment
export async function pushCameraFrame(rawSensorData: ArrayBuffer): Promise<void> {
  if (rawSensorData.detached) {
    throw new Error('Transferable ArrayBuffer is already detached.');
  }

  // Transfer buffer ownership or take an isolated slice with strict ownership semantics
  const isolatedBuffer = 'transfer' in rawSensorData
    ? (rawSensorData as { transfer: () => ArrayBuffer }).transfer()
    : rawSensorData.slice(0);

  const payload = new Uint8Array(isolatedBuffer);

  try {
    // Native Tauri 2.0 IPC invocation with ownership isolation
    await invoke('process_frame', payload.buffer, {
      headers: { 'content-type': 'application/octet-stream' }
    });
  } finally {
    // Ensure references are dereferenced to assist mobile V8/JSC GC scavenging
    // and ensure no post-invocation mutations can occur.
  }
}
```

### Rust Tauri 2.0 Command Binary Frame Ownership Isolation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Borrowing IPC request body bytes across Tokio async task boundaries risks use-after-free when the JNI DirectByteBuffer or WebKit IPC bridge frame completes and deallocates the underlying buffer.
```rust
// ANTI-PATTERN: Aliasing raw pointer from native mobile bridge without lifetime bounds
use tauri::ipc::Request;

#[tauri::command]
pub async fn process_frame(request: Request<'_>) -> Result<(), String> {
    let raw_bytes = request.body();
    
    // Spawning an un-owned background task referencing borrowed request slice
    // causes use-after-free when mobile IPC bridge tears down the frame.
    tokio::spawn(async move {
        // UNSAFE: Accessing body data after IPC request lifetime expires
        println!("Processing {} bytes", raw_bytes.len());
    });
    
    Ok(())
}
```

#### Production Standard (Correct)
> **Standard**: Accepting `Vec<u8>` directly takes full ownership of the transferred buffer from Tauri's IPC deserializer, safely detaching it from the mobile WebView runtime and allowing safe transfer across Rust threads without use-after-free or dangling references.
```rust
// PRODUCTION INVARIANT: Safe byte consumption with explicit owned transfer
use tauri::ipc::Response;

#[tauri::command]
pub async fn process_frame(body: Vec<u8>) -> Result<Response, String> {
    // Direct owned Vec<u8> transfer guaranteed by Tauri 2.0 IPC deserializer
    let frame_len = body.len();
    
    tokio::task::spawn_blocking(move || {
        // Safe owned execution: body is completely isolated from the mobile WebView runtime
        crate::processing::analyze_frame(body)
    })
    .await
    .map_err(|e| format!("Processing task failed: {e}"))?
    .map_err(|e| format!("Frame pipeline error: {e}"))?;

    // Return isolated binary response with zero base64 overhead
    Ok(Response::new(format!("{{\"status\":\"ok\",\"processed\":{frame_len}}}").into_bytes()))
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Tauri 2.0 Mobile IPC Zero-Copy ArrayBuffer Transfer & Memory Isolation Guardrail

Tauri 2.0 Mobile IPC Zero-Copy ArrayBuffer Transfer & Memory Isolation Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict transfer semantics, buffer detachment, and lifetime isolation when streaming high-bandwidth binary data across Tauri 2.0 IPC between Rust and mobile WebViews (WebKit/WKWebView and Android WebView). Prevents silent data corruption, use-after-free, and double-free conditions caused by concurrent mutations of shared memory buffers or improper JNI/WebKit FFI pointer lifecycle management. 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: Mutating Shared ArrayBuffer Instances Post-IPC Dispatch or Unsafely Aliasing Raw JNI/WebKit Byte Buffers 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 DriftMutating Shared ArrayBuffer Instances Post-IPC Dispatch or Unsafely Aliasing Raw JNI/WebKit Byte BuffersCritical
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 treat ArrayBuffers passed across the IPC boundary as single-ownership transferred resources, detaching or discarding the client reference immediately after dispatch.

Engineers MUST ALWAYS treat ArrayBuffers passed across the IPC boundary as single-ownership transferred resources, detaching or discarding the client reference immediately after dispatch.

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 mutate a Uint8Array or ArrayBuffer after passing it to `invoke()` or an IPC `Channel`, as mobile WebViews (JNI DirectByteBuffer / WKScriptMessage) execute asynchronous buffer consumption.

Engineers MUST NOT mutate a Uint8Array or ArrayBuffer after passing it to `invoke()` or an IPC `Channel`, as mobile WebViews (JNI DirectByteBuffer / WKScriptMessage) execute asynchronous buffer consumption.

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

Rust handlers receiving high-throughput binary frames MUST consume buffers via `tauri

Rust handlers receiving high-throughput binary frames MUST consume buffers via `tauri::ipc::Request` binary payloads or `tauri::ipc::Channel<Vec<u8>>` and NEVER store raw heap pointers across async await boundaries without explicit pin and ownership guarantees.

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 verify `buffer.detached` prior to dispatch and utilize `ArrayBuffer.prototype.transfer()` (or sliced defensive allocation if transfer is unsupported) to guarantee thread isolation.

Code MUST verify `buffer.detached` prior to dispatch and utilize `ArrayBuffer.prototype.transfer()` (or sliced defensive allocation if transfer is unsupported) to guarantee thread isolation.

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 streaming binary frames from Rust to mobile WebViews MUST use `tauri

Services streaming binary frames from Rust to mobile WebViews MUST use `tauri::ipc::Response::new(bytes)` or custom protocol asset streaming rather than base64 serialization, which causes critical GC pressure and memory spikes on mobile runtimes.

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 perform concurrent writes to overlapping byte offsets in shared memory mapped regions without atomic synchronization primitives recognized by both Rust and the WebView JS engine.

Components NEVER perform concurrent writes to overlapping byte offsets in shared memory mapped regions without atomic synchronization primitives recognized by both Rust and the WebView JS engine.

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 IPC Zero-Copy ArrayBuffer Transfer & Memory Isolation Guardrail critical for AI coding assistants?

Enforces strict transfer semantics, buffer detachment, and lifetime isolation when streaming high-bandwidth binary data across Tauri 2.0 IPC between Rust and mobile WebViews (WebKit/WKWebView and Android WebView). Prevents silent data corruption, use-after-free, and double-free conditions caused by concurrent mutations of shared memory buffers or improper JNI/WebKit FFI pointer lifecycle management. 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 (Mutating Shared ArrayBuffer Instances Post-IPC Dispatch or Unsafely Aliasing Raw JNI/WebKit Byte Buffers) 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