This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: tauri-android-jni-directbytebuffer-zero-copy-standard

Tauri 2.0 Android JNI DirectByteBuffer Zero-Copy Streaming Standard

Enforces zero-copy binary streaming between the Tauri 2.0 Rust backend and the Android WebView layer using JNI DirectByteBuffer and native memory mapping. Eliminates Dalvik/ART garbage collection pauses and IPC serialization overhead when handling high-throughput encrypted blob payloads.

Prohibited Anti-Pattern: Base64-encoding byte payloads or allocating JVM jbyteArray buffers over Tauri IPC, causing fatal GC churn and OOM crashes.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Tauri 2.0 Android JNI DirectByteBuffer Zero-Copy Streaming Standard - Enforces zero-copy binary streaming between the Tauri 2.0 Rust backend and the Android WebView layer using JNI DirectByteBuffer and native memory mapping. Eliminates Dalvik/ART garbage collection pauses and IPC serialization overhead when handling high-throughput encrypted blob payloads.
globs: src-tauri/src/**/*.rs, src-tauri/gen/android/**/*.kt, src/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/tauri-android-jni-directbytebuffer-zero-copy-standard"
---

# Tauri 2.0 Android JNI DirectByteBuffer Zero-Copy Streaming Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Base64-encoding byte payloads or allocating JVM jbyteArray buffers over Tauri IPC, causing fatal GC churn and OOM crashes.

## System Constraints
You are a Principal Mobile Systems Architect enforcing Tauri 2.0 Android JNI DirectByteBuffer Zero-Copy Streaming standards. Mandate zero-copy binary IPC and stream pipelines between Rust and Android WebViews.

## Strict Guidelines
- Engineers MUST ALWAYS pipe large binary payloads (>64KB) using raw IPC responses (`tauri::ipc::Response`) or custom protocol streaming rather than Base64 strings or serde-serialized `Vec<u8>` arrays.
- Engineers MUST NOT construct JVM-managed `jbyteArray` via `env.byte_array_from_slice()` for high-throughput streaming, as this forces memory duplication across the JNI boundary.
- Code MUST wrap native pinned heap allocations using JNI Direct Byte Buffers (`env.new_direct_byte_buffer`) when exposing off-heap buffers directly to Android ART runtimes.
- Services MUST pin native buffers and register explicit drop/cleanup callbacks to guarantee that Rust-allocated memory is not deallocated while a DirectByteBuffer is still referenced by Android.
- Components NEVER parse binary stream responses via `JSON.parse` or text decoders in the frontend; they MUST consume the payload directly via `Response.body.getReader()` as `Uint8Array`.

## Bad vs Good Implementations
### Tauri 2.0 Binary Stream IPC (Rust Backend)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Returning raw `Vec<u8>` across standard Tauri commands serializes data into a JSON array of integers (`[255, 0, ...]`), multiplying memory footprint by 4-6x and invoking ART GC on mobile devices.
```rust
// ANTI-PATTERN: Serializing binary payload into JSON Vec<u8> or Base64 string.
// Causes massive allocations, 33% Base64 bloat, and JVM GC thrashing in Android WebView.
#[tauri::command]
pub async fn stream_encrypted_blob(blob_id: String) -> Result<Vec<u8>, String> {
    let payload: Vec<u8> = fetch_and_decrypt_blob(&blob_id).await
        .map_err(|e| e.to_string())?;
    // Returning Vec<u8> directly in a standard command serializes into a JSON array of numbers: [12, 244, ...]
    Ok(payload)
}
```

#### Production Standard (Correct)
> **Standard**: Returning `tauri::ipc::Response::new(payload)` enables raw binary transport without JSON serialization overhead, preserving memory bandwidth on mobile devices.
```rust
// PRODUCTION STANDARD: Stream binary payload zero-copy using Tauri 2.0 Response IPC
use tauri::ipc::Response;

#[tauri::command]
pub async fn stream_encrypted_blob(blob_id: String) -> Result<Response, String> {
    let payload: Vec<u8> = fetch_and_decrypt_blob(&blob_id).await
        .map_err(|e| e.to_string())?;
    
    // Tauri 2.0 Response with raw binary payload bypasses JSON serialization,
    // delivering bytes directly to the WebView interface.
    Ok(Response::new(payload))
}
```

### Consuming Zero-Copy Binary Payload (TypeScript Frontend)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using standard invoke for binary data triggers JSON parsing in the WebView JavaScript engine, copying array elements one by one and freezing the mobile UI thread.
```typescript
// ANTI-PATTERN: Invoking binary command expecting standard JSON-parsed array
import { invoke } from '@tauri-apps/api/core';

async function loadBlob(id: string): Promise<Uint8Array> {
  // Incurs heavy JSON parsing overhead and produces a plain JS Array instead of typed memory
  const rawNumbers = await invoke<number[]>('stream_encrypted_blob', { blobId: id });
  return new Uint8Array(rawNumbers);
}
```

#### Production Standard (Correct)
> **Standard**: Consuming the response as an `ArrayBuffer` directly leverages WebKit/Blink zero-copy typed arrays, eliminating GC pressure and UI thread stalls.
```typescript
// PRODUCTION STANDARD: Fetch raw ArrayBuffer directly via Tauri 2.0 binary IPC invoke
import { invoke } from '@tauri-apps/api/core';

async function loadBlob(id: string): Promise<Uint8Array> {
  // invoke with 'bytes' or direct Response decoding returns an ArrayBuffer
  const buffer = await invoke<ArrayBuffer>('stream_encrypted_blob', {
    blobId: id,
  }, {
    // Bypasses JSON deserializer for raw binary body
    headers: { 'Accept': 'application/octet-stream' }
  });
  return new Uint8Array(buffer);
}
```

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 Android JNI DirectByteBuffer Zero-Copy Streaming Standard

Tauri 2.0 Android JNI DirectByteBuffer Zero-Copy Streaming Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces zero-copy binary streaming between the Tauri 2.0 Rust backend and the Android WebView layer using JNI DirectByteBuffer and native memory mapping. Eliminates Dalvik/ART garbage collection pauses and IPC serialization overhead when handling high-throughput encrypted blob payloads. 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: Base64-encoding byte payloads or allocating JVM jbyteArray buffers over Tauri IPC, causing fatal GC churn and OOM crashes. 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 DriftBase64-encoding byte payloads or allocating JVM jbyteArray buffers over Tauri IPC, causing fatal GC churn and OOM crashes.Critical
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 pipe large binary payloads (>64KB) using raw IPC responses (`tauri

Engineers MUST ALWAYS pipe large binary payloads (>64KB) using raw IPC responses (`tauri::ipc::Response`) or custom protocol streaming rather than Base64 strings or serde-serialized `Vec<u8>` arrays.

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 construct JVM-managed `jbyteArray` via `env.byte_array_from_slice()` for high-throughput streaming, as this forces memory duplication across the JNI boundary.

Engineers MUST NOT construct JVM-managed `jbyteArray` via `env.byte_array_from_slice()` for high-throughput streaming, as this forces memory duplication across the JNI boundary.

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 wrap native pinned heap allocations using JNI Direct Byte Buffers (`env.new_direct_byte_buffer`) when exposing off-heap buffers directly to Android ART runtimes.

Code MUST wrap native pinned heap allocations using JNI Direct Byte Buffers (`env.new_direct_byte_buffer`) when exposing off-heap buffers directly to Android ART 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.
4

Services MUST pin native buffers and register explicit drop/cleanup callbacks to guarantee that Rust-allocated memory is not deallocated while a DirectByteBuffer is still referenced by Android.

Services MUST pin native buffers and register explicit drop/cleanup callbacks to guarantee that Rust-allocated memory is not deallocated while a DirectByteBuffer is still referenced by Android.

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 parse binary stream responses via `JSON.parse` or text decoders in the frontend

Components NEVER parse binary stream responses via `JSON.parse` or text decoders in the frontend; they MUST consume the payload directly via `Response.body.getReader()` as `Uint8Array`.

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 Android JNI DirectByteBuffer Zero-Copy Streaming Standard critical for AI coding assistants?

Enforces zero-copy binary streaming between the Tauri 2.0 Rust backend and the Android WebView layer using JNI DirectByteBuffer and native memory mapping. Eliminates Dalvik/ART garbage collection pauses and IPC serialization overhead when handling high-throughput encrypted blob payloads. 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 (Base64-encoding byte payloads or allocating JVM jbyteArray buffers over Tauri IPC, causing fatal GC churn and OOM crashes.) 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