This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: tauri-v2-custom-protocol-streaming-range-invariant

Tauri 2.0 Webview Custom Protocol HTTP Range Chunking Invariant

Standardizes chunked HTTP Range-request streaming for local asset retrieval across Tauri 2.0 Android and iOS webviews. Bypasses IPC serialization bottlenecks and prevents catastrophic OOM memory spikes by serving native file data through asynchronous seek-and-slice operations instead of monolithic base64 or complete byte array payloads.

Prohibited Anti-Pattern: Buffering Entire Media Assets in Memory via Tauri IPC or Non-Ranged Custom Protocols

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Tauri 2.0 Webview Custom Protocol HTTP Range Chunking Invariant - Standardizes chunked HTTP Range-request streaming for local asset retrieval across Tauri 2.0 Android and iOS webviews. Bypasses IPC serialization bottlenecks and prevents catastrophic OOM memory spikes by serving native file data through asynchronous seek-and-slice operations instead of monolithic base64 or complete byte array payloads.
globs: src/**/*.{ts,tsx,js,jsx}, src-tauri/src/**/*.{rs}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/tauri-v2-custom-protocol-streaming-range-invariant"
---

# Tauri 2.0 Webview Custom Protocol HTTP Range Chunking Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Buffering Entire Media Assets in Memory via Tauri IPC or Non-Ranged Custom Protocols

## System Constraints
You are a Principal Engineer enforcing the Tauri 2.0 Webview Custom Protocol Streaming Range Invariant. Mandate that all large asset reads (video, audio, high-resolution blobs) across mobile webviews bypass IPC serialization, utilize Tauri's custom asset/stream protocol, and strictly respond with HTTP 206 Partial Content parsed via standard HTTP Range headers.

## Strict Guidelines
- Engineers MUST ALWAYS implement HTTP 206 Partial Content and process the `Range: bytes=start-end` header when serving binary assets via `tauri::ipc` or custom protocols.
- Engineers MUST NOT read entire files into memory using `std::fs::read` or transfer binary assets across the Tauri IPC bridge as base64-encoded strings or contiguous `Vec<u8>` arrays.
- Custom protocol handlers MUST cap the maximum chunk size (recommended: 1MB to 4MB) per slice to eliminate UI thread starvation in iOS WKWebView and Android WebView.
- Rust protocol handlers MUST implement `std::io::Seek` on file descriptors to directly pipe seeked byte chunks into the `tauri::http::Response` body without intermediate allocations.
- Webview clients MUST fetch large media assets using standard `<video>`, `<audio>`, or DOM `fetch` streaming patterns pointing to registered protocol URIs (e.g., `asset://` or `stream://`) rather than invoking `invoke('get_file_bytes')`.

## Bad vs Good Implementations
### Tauri 2.0 Native Protocol Handler with HTTP Range Support

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Reading the entire file into a Vec<u8> forces the OS to allocate the whole binary into process memory. On mobile devices, loading a 200MB video will instantly trigger OS-level termination (OOM killer) or freeze the webview main runloop.
```rust
use tauri::{AppHandle, Manager};
use tauri::http::{Response, ResponseBuilder};

// ANTI-PATTERN: Reads entire asset into RAM, crashes mobile webview on 4K/audio files
pub fn setup_broken_protocol(app: &mut tauri::App) {
    app.register_uri_scheme_protocol("stream", |_app, request| {
        let file_path = request.uri().path().trim_start_matches('/');
        let file_bytes = std::fs::read(file_path).map_err(|_| tauri::http::status::StatusCode::NOT_FOUND)?;
        
        ResponseBuilder::new()
            .header("Access-Control-Allow-Origin", "*")
            .body(file_bytes)
    });
}
```

#### Production Standard (Correct)
> **Standard**: The good implementation parses HTTP Range headers, seeks directly into the file handle, and reads only an bounded 1MB chunk into memory. It returns a valid HTTP 206 Partial Content header, enabling smooth seeking and constant bounded memory on mobile webviews.
```rust
use std::io::{Read, Seek, SeekFrom};
use std::fs::File;
use tauri::http::{header, status::StatusCode, Request, Response, ResponseBuilder};

const CHUNK_SIZE: u64 = 1024 * 1024; // 1 MB chunks

pub fn handle_stream_protocol(request: &Request<Vec<u8>>) -> Result<Response<Vec<u8>>, Box<dyn std::error::Error>> {
    let file_path = request.uri().path().trim_start_matches('/');
    let mut file = File::open(file_path)?;
    let total_len = file.metadata()?.len();

    if let Some(range_header) = request.headers().get(header::RANGE) {
        let range_str = range_header.to_str()?;
        let ranges = http_range_header::parse_range_header(range_str)?.validate(total_len)?;
        let range = ranges.first().ok_or("Invalid range")?;
        
        let start = *range.start();
        let end = (*range.end()).min(start + CHUNK_SIZE - 1);
        let chunk_len = (end - start + 1) as usize;

        file.seek(SeekFrom::Start(start))?;
        let mut buffer = vec![0u8; chunk_len];
        file.read_exact(&mut buffer)?;

        ResponseBuilder::new()
            .status(StatusCode::PARTIAL_CONTENT)
            .header(header::CONTENT_RANGE, format!("bytes {}-{}/{}", start, end, total_len))
            .header(header::CONTENT_LENGTH, chunk_len.to_string())
            .header(header::ACCEPT_RANGES, "bytes")
            .header(header::CONTENT_TYPE, "application/octet-stream")
            .body(buffer)
    } else {
        ResponseBuilder::new()
            .status(StatusCode::OK)
            .header(header::CONTENT_LENGTH, total_len.to_string())
            .header(header::ACCEPT_RANGES, "bytes")
            .body(Vec::new())
    }
}
```

### Frontend Media Ingestion Invariant

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Invoking IPC to return complete byte arrays forces JSON serialization or heavy IPC buffer duplication across the native-webview boundary, causing frame drops and potential mobile browser sandbox crashes.
```typescript
import { invoke } from '@tauri-apps/api/core';

// ANTI-PATTERN: Serializing binary over IPC causes IPC queue stalls and GC pauses
export async function loadMediaToElement(filePath: string, videoEl: HTMLVideoElement) {
  const bytes: number[] = await invoke('load_media_bytes', { path: filePath });
  const blob = new Blob([new Uint8Array(bytes)], { type: 'video/mp4' });
  videoEl.src = URL.createObjectURL(blob);
}
```

#### Production Standard (Correct)
> **Standard**: Using convertFileSrc redirects media decoding to the mobile platform's native multimedia engine (AVFoundation on iOS, ExoPlayer/MediaCodec on Android) using streaming HTTP Range chunks via the registered native scheme.
```typescript
import { convertFileSrc } from '@tauri-apps/api/core';

// PRODUCTION FIX: Delegate streaming and range resolution to the custom protocol
export function attachStreamingMedia(filePath: string, videoEl: HTMLVideoElement): void {
  // convertFileSrc utilizes Tauri 2.0 asset protocol or custom stream protocol
  const streamUrl = convertFileSrc(filePath, 'stream');
  videoEl.preload = 'metadata';
  videoEl.src = streamUrl;
}
```

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 Webview Custom Protocol HTTP Range Chunking Invariant

Tauri 2.0 Webview Custom Protocol HTTP Range Chunking Invariant defines an industrial-grade behavioral standard for mobile engineering. Standardizes chunked HTTP Range-request streaming for local asset retrieval across Tauri 2.0 Android and iOS webviews. Bypasses IPC serialization bottlenecks and prevents catastrophic OOM memory spikes by serving native file data through asynchronous seek-and-slice operations instead of monolithic base64 or complete byte array 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: Buffering Entire Media Assets in Memory via Tauri IPC or Non-Ranged Custom Protocols 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 DriftBuffering Entire Media Assets in Memory via Tauri IPC or Non-Ranged Custom ProtocolsCritical
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 implement HTTP 206 Partial Content and process the `Range

Engineers MUST ALWAYS implement HTTP 206 Partial Content and process the `Range: bytes=start-end` header when serving binary assets via `tauri::ipc` or custom protocols.

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 read entire files into memory using `std

Engineers MUST NOT read entire files into memory using `std::fs::read` or transfer binary assets across the Tauri IPC bridge as base64-encoded strings or contiguous `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.
3

Custom protocol handlers MUST cap the maximum chunk size (recommended

Custom protocol handlers MUST cap the maximum chunk size (recommended: 1MB to 4MB) per slice to eliminate UI thread starvation in iOS WKWebView and Android WebView.

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

Rust protocol handlers MUST implement `std

Rust protocol handlers MUST implement `std::io::Seek` on file descriptors to directly pipe seeked byte chunks into the `tauri::http::Response` body without intermediate allocations.

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

Webview clients MUST fetch large media assets using standard `<video>`, `<audio>`, or DOM `fetch` streaming patterns pointing to registered protocol URIs (e.g., `asset

Webview clients MUST fetch large media assets using standard `<video>`, `<audio>`, or DOM `fetch` streaming patterns pointing to registered protocol URIs (e.g., `asset://` or `stream://`) rather than invoking `invoke('get_file_bytes')`.

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 Webview Custom Protocol HTTP Range Chunking Invariant critical for AI coding assistants?

Standardizes chunked HTTP Range-request streaming for local asset retrieval across Tauri 2.0 Android and iOS webviews. Bypasses IPC serialization bottlenecks and prevents catastrophic OOM memory spikes by serving native file data through asynchronous seek-and-slice operations instead of monolithic base64 or complete byte array 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 (Buffering Entire Media Assets in Memory via Tauri IPC or Non-Ranged Custom Protocols) 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