This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: tauri-2-mobile-core-thread-affinity-guardrail

Tauri 2.0 Mobile Cross-Runtime Thread Affinity & UI Loop Isolation

Enforces strict thread-affinity boundaries between native mobile UI threads (Android Main Looper / iOS Main RunLoop) and Tauri 2.0's Rust Tokio runtime. Prevents catastrophic frame hitches, Choreographer dropped frame warnings, and CADisplayLink pipeline stalls by mandating asynchronous bridge execution, non-blocking IPC batching, and off-main-thread FFI marshaling.

Prohibited Anti-Pattern: Executing synchronous Rust FFI operations or unbounded Tauri IPC calls directly within native UI gesture and render lifecycles.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Tauri 2.0 Mobile Cross-Runtime Thread Affinity & UI Loop Isolation - Enforces strict thread-affinity boundaries between native mobile UI threads (Android Main Looper / iOS Main RunLoop) and Tauri 2.0's Rust Tokio runtime. Prevents catastrophic frame hitches, Choreographer dropped frame warnings, and CADisplayLink pipeline stalls by mandating asynchronous bridge execution, non-blocking IPC batching, and off-main-thread FFI marshaling.
globs: src/**/*.{ts,tsx}, src-tauri/src/**/*.rs, src-tauri/gen/android/**/*.kt, src-tauri/gen/ios/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/tauri-2-mobile-core-thread-affinity-guardrail"
---

# Tauri 2.0 Mobile Cross-Runtime Thread Affinity & UI Loop Isolation

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Executing synchronous Rust FFI operations or unbounded Tauri IPC calls directly within native UI gesture and render lifecycles.

## System Constraints
You are a Principal Mobile Architect enforcing the Tauri 2.0 Mobile Core Plugin Thread-Affinity Guardrail. Mandate strict execution boundary separation between native mobile UI render loops (Android Choreographer, iOS CADisplayLink) and cross-runtime Rust FFI invocations to maintain an uninterrupted 60/120 FPS baseline.

## Strict Guidelines
- Engineers MUST ALWAYS define Tauri mobile commands as asynchronous (`async fn`) in Rust and offload blocking CPU/IO operations using `tauri::async_runtime::spawn_blocking` to protect the WebView IPC worker thread.
- Engineers MUST NOT invoke Tauri IPC (`invoke()`) directly inside continuous gesture listeners (`touchmove`, `pointermove`, `scroll`) without decoupled frame-coalescing or RAF-aligned batching.
- Code SHOULD marshal cross-runtime data using typed JSON strings or binary buffers (`tauri::ipc::Response`) without invoking synchronous Android JNI or Swift RunLoop operations on the main thread.
- Services MUST dispatch native mobile plugin logic to background queues (Kotlin `Dispatchers.IO` / Swift `DispatchQueue.global(qos: .userInitiated)`) before executing Rust FFI callbacks.
- Components NEVER await Tauri IPC round-trips synchronously within active gesture animations or interruptive UI interaction frames.

## Bad vs Good Implementations
### Decoupling High-Frequency Mobile Touch/Gesture IPC from Choreographer/CADisplayLink

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly firing asynchronous IPC calls on every touch event floods the native bridge with 120Hz micro-tasks, saturating the Android JNI or iOS WebKit script message handler and blocking native frame presentation deadlines.
```typescript
import { invoke } from '@tauri-apps/api/core';

// ANTI-PATTERN: Direct IPC invocation per touch event stalls CADisplayLink and Choreographer
export function attachGestureTracker(element: HTMLElement) {
  element.addEventListener('touchmove', async (event: TouchEvent) => {
    const touch = event.touches[0];
    if (!touch) return;

    // Synchronous dispatch floods Tauri's native message queue on every touch sample (~120Hz)
    // This forces Android Choreographer / iOS RunLoop to drop frames waiting on JNI/FFI bridging
    await invoke('plugin:gesture|process_coordinates', {
      x: touch.clientX,
      y: touch.clientY,
      timestamp: event.timeStamp,
    });
  }, { passive: true });
}
```

#### Production Standard (Correct)
> **Standard**: Coalesces high-frequency touch updates into a single payload dispatched strictly within requestAnimationFrame cycles, preventing IPC bridge flooding and eliminating frame drops on mobile UI runtimes.
```typescript
import { invoke } from '@tauri-apps/api/core';

interface GesturePayload {
  x: number;
  y: number;
  timestamp: number;
}

// PRODUCTION INVARIANT: Frame-aligned coalescing decoupled from native render ticks
export function attachGestureTracker(element: HTMLElement): () => void {
  let pendingCoords: GesturePayload | null = null;
  let rafId: number | null = null;
  let isDispatching = false;

  const flushToNativeBridge = async () => {
    if (!pendingCoords || isDispatching) {
      rafId = null;
      return;
    }

    const payload = pendingCoords;
    pendingCoords = null;
    isDispatching = true;

    try {
      // Execute during frame budget window without stalling Choreographer/CADisplayLink
      await invoke('plugin:gesture|process_coordinates', { payload });
    } catch (err) {
      console.error('Failed to dispatch gesture coordinate batch', err);
    } finally {
      isDispatching = false;
      if (pendingCoords !== null) {
        rafId = requestAnimationFrame(flushToNativeBridge);
      } else {
        rafId = null;
      }
    }
  };

  const onTouchMove = (event: TouchEvent) => {
    const touch = event.touches[0];
    if (!touch) return;

    pendingCoords = {
      x: touch.clientX,
      y: touch.clientY,
      timestamp: event.timeStamp,
    };

    if (rafId === null) {
      rafId = requestAnimationFrame(flushToNativeBridge);
    }
  };

  element.addEventListener('touchmove', onTouchMove, { passive: true });

  return () => {
    element.removeEventListener('touchmove', onTouchMove);
    if (rafId !== null) {
      cancelAnimationFrame(rafId);
    }
  };
}
```

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 Cross-Runtime Thread Affinity & UI Loop Isolation

Tauri 2.0 Mobile Cross-Runtime Thread Affinity & UI Loop Isolation defines an industrial-grade behavioral standard for mobile engineering. Enforces strict thread-affinity boundaries between native mobile UI threads (Android Main Looper / iOS Main RunLoop) and Tauri 2.0's Rust Tokio runtime. Prevents catastrophic frame hitches, Choreographer dropped frame warnings, and CADisplayLink pipeline stalls by mandating asynchronous bridge execution, non-blocking IPC batching, and off-main-thread FFI marshaling. 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: Executing synchronous Rust FFI operations or unbounded Tauri IPC calls directly within native UI gesture and render lifecycles. 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 DriftExecuting synchronous Rust FFI operations or unbounded Tauri IPC calls directly within native UI gesture and render lifecycles.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 define Tauri mobile commands as asynchronous (`async fn`) in Rust and offload blocking CPU/IO operations using `tauri

Engineers MUST ALWAYS define Tauri mobile commands as asynchronous (`async fn`) in Rust and offload blocking CPU/IO operations using `tauri::async_runtime::spawn_blocking` to protect the WebView IPC worker 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.
2

Engineers MUST NOT invoke Tauri IPC (`invoke()`) directly inside continuous gesture listeners (`touchmove`, `pointermove`, `scroll`) without decoupled frame-coalescing or RAF-aligned batching.

Engineers MUST NOT invoke Tauri IPC (`invoke()`) directly inside continuous gesture listeners (`touchmove`, `pointermove`, `scroll`) without decoupled frame-coalescing or RAF-aligned batching.

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 SHOULD marshal cross-runtime data using typed JSON strings or binary buffers (`tauri

Code SHOULD marshal cross-runtime data using typed JSON strings or binary buffers (`tauri::ipc::Response`) without invoking synchronous Android JNI or Swift RunLoop operations on the main 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.
4

Services MUST dispatch native mobile plugin logic to background queues (Kotlin `Dispatchers.IO` / Swift `DispatchQueue.global(qos

Services MUST dispatch native mobile plugin logic to background queues (Kotlin `Dispatchers.IO` / Swift `DispatchQueue.global(qos: .userInitiated)`) before executing Rust FFI callbacks.

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 await Tauri IPC round-trips synchronously within active gesture animations or interruptive UI interaction frames.

Components NEVER await Tauri IPC round-trips synchronously within active gesture animations or interruptive UI interaction frames.

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 Cross-Runtime Thread Affinity & UI Loop Isolation critical for AI coding assistants?

Enforces strict thread-affinity boundaries between native mobile UI threads (Android Main Looper / iOS Main RunLoop) and Tauri 2.0's Rust Tokio runtime. Prevents catastrophic frame hitches, Choreographer dropped frame warnings, and CADisplayLink pipeline stalls by mandating asynchronous bridge execution, non-blocking IPC batching, and off-main-thread FFI marshaling. 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 (Executing synchronous Rust FFI operations or unbounded Tauri IPC calls directly within native UI gesture and render lifecycles.) 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