This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: tauri2-mobile-lifecycle-atomic-state-rehydration

Tauri 2.0 Mobile Lifecycle State Preservation & Cold-Start IPC Rehydration

Enforces atomic state synchronization between the webview runtime and native Rust backend during aggressive Android and iOS mobile process reclamation. Prevents volatile UI state loss by utilizing native pause/resume hooks, write-ahead persistent state staging in Rust, and mandatory IPC rehydration gating before webview rendering.

Prohibited Anti-Pattern: Relying on browser-level beforeunload or asynchronous local storage during native OS mobile memory reclamation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Tauri 2.0 Mobile Lifecycle State Preservation & Cold-Start IPC Rehydration - Enforces atomic state synchronization between the webview runtime and native Rust backend during aggressive Android and iOS mobile process reclamation. Prevents volatile UI state loss by utilizing native pause/resume hooks, write-ahead persistent state staging in Rust, and mandatory IPC rehydration gating before webview rendering.
globs: src/**/*.{ts,tsx}, src-tauri/src/**/*.{rs,toml}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/tauri2-mobile-lifecycle-atomic-state-rehydration"
---

# Tauri 2.0 Mobile Lifecycle State Preservation & Cold-Start IPC Rehydration

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Relying on browser-level beforeunload or asynchronous local storage during native OS mobile memory reclamation

## System Constraints
You are a Principal Mobile Systems Architect specializing in Tauri 2.0 mobile runtimes. You mandate absolute state durability across mobile OS lifecycle transitions (Android Activity recreation, low-memory SIGKILL, and iOS background freezes). Enforce atomic delta/snapshot persistence across the Rust-WebView bridge and block frontend render pipelines until native state rehydration resolves.

## Strict Guidelines
- Engineers MUST NEVER rely on DOM events like 'beforeunload', 'pagehide', or synchronous window.localStorage for critical state persistence on mobile devices.
- Engineers MUST bind frontend lifecycle handlers directly to Tauri's native lifecycle event stream ('tauri://pause', 'tauri://resume', or dedicated lifecycle plugins) to flush pending buffers immediately.
- Frontend bootstrapping MUST implement a strict blocking initialization gate: the root application tree MUST NOT mount until an explicit 'rehydrate_state' IPC invocation returns the last verified atomic state snapshot from Rust.
- The Rust backend MUST persist lifecycle state snapshots to native non-volatile storage (such as sled, SQLite, or atomic file swaps via tempfile) rather than retaining them solely in Tauri managed state (tauri::State) memory.
- State transmissions across the IPC bridge during pause events MUST be serialized into compact binary or pre-validated JSON schemas to minimize serialization latency before OS process termination.
- Components NEVER manage isolated persistence logic; all state persistence MUST funnel through a centralized, atomic persistence coordinator that debounces delta writes and immediately flushes on OS pause interrupts.

## Bad vs Good Implementations
### Tauri 2.0 Mobile Lifecycle Persistence & Cold-Start Rehydration Gate

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Mobile operating systems terminate webview processes abruptly under memory pressure without triggering standard browser unload events. Storing state in browser local storage or relying on 'beforeunload' yields corrupt, stale, or discarded state upon next cold start.
```typescript
// Anti-pattern: Relying on browser events and local storage without Rust coordination
import React, { useEffect, useState } from 'react';

export function BadApp() {
  const [userDraft, setUserDraft] = useState(() => {
    // Synchronous localStorage will corrupt or lose data if OS kills webview unannounced
    return localStorage.getItem('draft') || '';
  });

  useEffect(() => {
    const handleUnload = () => {
      // In mobile Safari / Android WebView, beforeunload rarely executes reliably on process kill
      localStorage.setItem('draft', userDraft);
    };
    window.addEventListener('beforeunload', handleUnload);
    return () => window.removeEventListener('beforeunload', handleUnload);
  }, [userDraft]);

  return <input value={userDraft} onChange={(e) => setUserDraft(e.target.value)} />;
}
```

#### Production Standard (Correct)
> **Standard**: Blocks rendering until cold-start state is securely retrieved from native Rust storage via IPC ('rehydrate_application_state'). Binds to native OS pause events ('tauri://pause') to guarantee an atomic snapshot flush before OS reclaim, avoiding data loss entirely.
```typescript
// Production Standard: Atomic IPC-backed snapshots and native lifecycle rehydration gating
import React, { createContext, useContext, useEffect, useState, ReactNode } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';

interface AppState {
  draft: string;
  lastSyncedSeq: number;
}

interface HydrationContextValue {
  state: AppState;
  updateDraft: (draft: string) => void;
}

const HydrationContext = createContext<HydrationContextValue | null>(null);

export function HydrationRoot({ children }: { children: ReactNode }) {
  const [hydratedState, setHydratedState] = useState<AppState | null>(null);
  const [isHydrating, setIsHydrating] = useState(true);

  useEffect(() => {
    let isMounted = true;

    async function bootstrap() {
      try {
        // Step 1: Enforce cold-start rehydration gate from native atomic storage
        const initialSnapshot = await invoke<AppState>('rehydrate_application_state');
        if (isMounted) {
          setHydratedState(initialSnapshot);
          setIsHydrating(false);
        }
      } catch (err) {
        console.error('Failed to rehydrate from native storage:', err);
        if (isMounted) {
          setHydratedState({ draft: '', lastSyncedSeq: 0 });
          setIsHydrating(false);
        }
      }
    }

    bootstrap();

    // Step 2: Listen for native OS pause notifications across the bridge
    const unlistenPromise = listen('tauri://pause', async () => {
      if (hydratedState) {
        await invoke('persist_atomic_state_snapshot', { state: hydratedState });
      }
    });

    return () => {
      isMounted = false;
      unlistenPromise.then((unlisten) => unlisten());
    };
  }, []);

  const updateDraft = (draft: string) => {
    setHydratedState((prev) => {
      if (!prev) return null;
      const next = { ...prev, draft, lastSyncedSeq: prev.lastSyncedSeq + 1 };
      // Asynchronously stage delta in Rust backend without waiting for native kill
      invoke('stage_state_delta', { delta: next }).catch(console.error);
      return next;
    });
  };

  if (isHydrating || !hydratedState) {
    return <div className="splash-screen">Rehydrating state securely...</div>;
  }

  return (
    <HydrationContext.Provider value={{ state: hydratedState, updateDraft }}>
      {children}
    </HydrationContext.Provider>
  );
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Tauri 2.0 Mobile Lifecycle State Preservation & Cold-Start IPC Rehydration

Tauri 2.0 Mobile Lifecycle State Preservation & Cold-Start IPC Rehydration defines an industrial-grade behavioral standard for mobile engineering. Enforces atomic state synchronization between the webview runtime and native Rust backend during aggressive Android and iOS mobile process reclamation. Prevents volatile UI state loss by utilizing native pause/resume hooks, write-ahead persistent state staging in Rust, and mandatory IPC rehydration gating before webview rendering. 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: Relying on browser-level beforeunload or asynchronous local storage during native OS mobile memory reclamation 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 DriftRelying on browser-level beforeunload or asynchronous local storage during native OS mobile memory reclamationCritical
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 NEVER rely on DOM events like 'beforeunload', 'pagehide', or synchronous window.localStorage for critical state persistence on mobile devices.

Engineers MUST NEVER rely on DOM events like 'beforeunload', 'pagehide', or synchronous window.localStorage for critical state persistence on mobile devices.

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 bind frontend lifecycle handlers directly to Tauri's native lifecycle event stream ('tauri

Engineers MUST bind frontend lifecycle handlers directly to Tauri's native lifecycle event stream ('tauri://pause', 'tauri://resume', or dedicated lifecycle plugins) to flush pending buffers immediately.

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

Frontend bootstrapping MUST implement a strict blocking initialization gate

Frontend bootstrapping MUST implement a strict blocking initialization gate: the root application tree MUST NOT mount until an explicit 'rehydrate_state' IPC invocation returns the last verified atomic state snapshot from Rust.

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

The Rust backend MUST persist lifecycle state snapshots to native non-volatile storage (such as sled, SQLite, or atomic file swaps via tempfile) rather than retaining them solely in Tauri managed state (tauri

The Rust backend MUST persist lifecycle state snapshots to native non-volatile storage (such as sled, SQLite, or atomic file swaps via tempfile) rather than retaining them solely in Tauri managed state (tauri::State) memory.

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

State transmissions across the IPC bridge during pause events MUST be serialized into compact binary or pre-validated JSON schemas to minimize serialization latency before OS process termination.

State transmissions across the IPC bridge during pause events MUST be serialized into compact binary or pre-validated JSON schemas to minimize serialization latency before OS process termination.

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 manage isolated persistence logic

Components NEVER manage isolated persistence logic; all state persistence MUST funnel through a centralized, atomic persistence coordinator that debounces delta writes and immediately flushes on OS pause interrupts.

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 Lifecycle State Preservation & Cold-Start IPC Rehydration critical for AI coding assistants?

Enforces atomic state synchronization between the webview runtime and native Rust backend during aggressive Android and iOS mobile process reclamation. Prevents volatile UI state loss by utilizing native pause/resume hooks, write-ahead persistent state staging in Rust, and mandatory IPC rehydration gating before webview rendering. 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 (Relying on browser-level beforeunload or asynchronous local storage during native OS mobile memory reclamation) 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